civetweb.c 555 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704
  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 0x0501
  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__)
  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 8096
  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. #else
  209. #define DEBUG_TRACE(fmt, ...) \
  210. do { \
  211. } while (0)
  212. #endif /* DEBUG */
  213. #endif /* DEBUG_TRACE */
  214. #if !defined(DEBUG_ASSERT)
  215. #if defined(DEBUG)
  216. #define DEBUG_ASSERT(cond) \
  217. do { \
  218. if (!(cond)) { \
  219. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  220. exit(2); /* Exit with error */ \
  221. } \
  222. } while (0)
  223. #else
  224. #define DEBUG_ASSERT(cond)
  225. #endif /* DEBUG */
  226. #endif
  227. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  228. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  229. __attribute__((no_instrument_function));
  230. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  231. __attribute__((no_instrument_function));
  232. void
  233. __cyg_profile_func_enter(void *this_fn, void *call_site)
  234. {
  235. if ((void *)this_fn != (void *)printf) {
  236. printf("E %p %p\n", this_fn, call_site);
  237. }
  238. }
  239. void
  240. __cyg_profile_func_exit(void *this_fn, void *call_site)
  241. {
  242. if ((void *)this_fn != (void *)printf) {
  243. printf("X %p %p\n", this_fn, call_site);
  244. }
  245. }
  246. #endif
  247. #if !defined(IGNORE_UNUSED_RESULT)
  248. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  249. #endif
  250. #if defined(__GNUC__) || defined(__MINGW32__)
  251. /* GCC unused function attribute seems fundamentally broken.
  252. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  253. * OR UNUSED" for individual functions failed.
  254. * Either the compiler creates an "unused-function" warning if a
  255. * function is not marked with __attribute__((unused)).
  256. * On the other hand, if the function is marked with this attribute,
  257. * but is used, the compiler raises a completely idiotic
  258. * "used-but-marked-unused" warning - and
  259. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  260. * raises error: unknown option after "#pragma GCC diagnostic".
  261. * Disable this warning completely, until the GCC guys sober up
  262. * again.
  263. */
  264. #pragma GCC diagnostic ignored "-Wunused-function"
  265. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  266. #else
  267. #define FUNCTION_MAY_BE_UNUSED
  268. #endif
  269. /* Some ANSI #includes are not available on Windows CE */
  270. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  271. #include <errno.h>
  272. #include <fcntl.h>
  273. #include <signal.h>
  274. #include <stdlib.h>
  275. #include <sys/stat.h>
  276. #include <sys/types.h>
  277. #endif /* !_WIN32_WCE */
  278. #if defined(__clang__)
  279. /* When using -Weverything, clang does not accept it's own headers
  280. * in a release build configuration. Disable what is too much in
  281. * -Weverything. */
  282. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  283. #endif
  284. #if defined(__GNUC__) || defined(__MINGW32__)
  285. /* Who on earth came to the conclusion, using __DATE__ should rise
  286. * an "expansion of date or time macro is not reproducible"
  287. * warning. That's exactly what was intended by using this macro.
  288. * Just disable this nonsense warning. */
  289. /* And disabling them does not work either:
  290. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  291. * #pragma clang diagnostic ignored "-Wdate-time"
  292. * So we just have to disable ALL warnings for some lines
  293. * of code.
  294. * This seems to be a known GCC bug, not resolved since 2012:
  295. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  296. */
  297. #endif
  298. #if defined(__MACH__) /* Apple OSX section */
  299. #if defined(__clang__)
  300. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  301. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  302. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  303. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  304. #endif
  305. #endif
  306. #define CLOCK_MONOTONIC (1)
  307. #define CLOCK_REALTIME (2)
  308. #include <mach/clock.h>
  309. #include <mach/mach.h>
  310. #include <mach/mach_time.h>
  311. #include <sys/errno.h>
  312. #include <sys/time.h>
  313. /* clock_gettime is not implemented on OSX prior to 10.12 */
  314. static int
  315. _civet_clock_gettime(int clk_id, struct timespec *t)
  316. {
  317. memset(t, 0, sizeof(*t));
  318. if (clk_id == CLOCK_REALTIME) {
  319. struct timeval now;
  320. int rv = gettimeofday(&now, NULL);
  321. if (rv) {
  322. return rv;
  323. }
  324. t->tv_sec = now.tv_sec;
  325. t->tv_nsec = now.tv_usec * 1000;
  326. return 0;
  327. } else if (clk_id == CLOCK_MONOTONIC) {
  328. static uint64_t clock_start_time = 0;
  329. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  330. uint64_t now = mach_absolute_time();
  331. if (clock_start_time == 0) {
  332. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  333. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  334. /* appease "unused variable" warning for release builds */
  335. (void)mach_status;
  336. clock_start_time = now;
  337. }
  338. now = (uint64_t)((double)(now - clock_start_time)
  339. * (double)timebase_ifo.numer
  340. / (double)timebase_ifo.denom);
  341. t->tv_sec = now / 1000000000;
  342. t->tv_nsec = now % 1000000000;
  343. return 0;
  344. }
  345. return -1; /* EINVAL - Clock ID is unknown */
  346. }
  347. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  348. #if defined(__CLOCK_AVAILABILITY)
  349. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  350. * declared but it may be NULL at runtime. So we need to check before using
  351. * it. */
  352. static int
  353. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  354. {
  355. if (clock_gettime) {
  356. return clock_gettime(clk_id, t);
  357. }
  358. return _civet_clock_gettime(clk_id, t);
  359. }
  360. #define clock_gettime _civet_safe_clock_gettime
  361. #else
  362. #define clock_gettime _civet_clock_gettime
  363. #endif
  364. #endif
  365. /********************************************************************/
  366. /* CivetWeb configuration defines */
  367. /********************************************************************/
  368. /* Maximum number of threads that can be configured.
  369. * The number of threads actually created depends on the "num_threads"
  370. * configuration parameter, but this is the upper limit. */
  371. #if !defined(MAX_WORKER_THREADS)
  372. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  373. #endif
  374. /* Timeout interval for select/poll calls.
  375. * The timeouts depend on "*_timeout_ms" configuration values, but long
  376. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  377. * This reduces the time required to stop the server. */
  378. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  379. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  380. #endif
  381. /* Do not try to compress files smaller than this limit. */
  382. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  383. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  384. #endif
  385. #if !defined(PASSWORDS_FILE_NAME)
  386. #define PASSWORDS_FILE_NAME ".htpasswd"
  387. #endif
  388. /* Initial buffer size for all CGI environment variables. In case there is
  389. * not enough space, another block is allocated. */
  390. #if !defined(CGI_ENVIRONMENT_SIZE)
  391. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  392. #endif
  393. /* Maximum number of environment variables. */
  394. #if !defined(MAX_CGI_ENVIR_VARS)
  395. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  396. #endif
  397. /* General purpose buffer size. */
  398. #if !defined(MG_BUF_LEN) /* in bytes */
  399. #define MG_BUF_LEN (1024 * 8)
  400. #endif
  401. /********************************************************************/
  402. /* Helper makros */
  403. #if !defined(ARRAY_SIZE)
  404. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  405. #endif
  406. #include <stdint.h>
  407. /* Standard defines */
  408. #if !defined(INT64_MAX)
  409. #define INT64_MAX (9223372036854775807)
  410. #endif
  411. #define SHUTDOWN_RD (0)
  412. #define SHUTDOWN_WR (1)
  413. #define SHUTDOWN_BOTH (2)
  414. mg_static_assert(MAX_WORKER_THREADS >= 1,
  415. "worker threads must be a positive number");
  416. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  417. "size_t data type size check");
  418. #if defined(_WIN32) /* WINDOWS include block */
  419. #include <malloc.h> /* *alloc( */
  420. #include <stdlib.h> /* *alloc( */
  421. #include <time.h> /* struct timespec */
  422. #include <windows.h>
  423. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  424. #include <ws2tcpip.h>
  425. typedef const char *SOCK_OPT_TYPE;
  426. #if !defined(PATH_MAX)
  427. #define W_PATH_MAX (MAX_PATH)
  428. /* at most three UTF-8 chars per wchar_t */
  429. #define PATH_MAX (W_PATH_MAX * 3)
  430. #else
  431. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  432. #endif
  433. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  434. #if !defined(_IN_PORT_T)
  435. #if !defined(in_port_t)
  436. #define in_port_t u_short
  437. #endif
  438. #endif
  439. #if !defined(_WIN32_WCE)
  440. #include <direct.h>
  441. #include <io.h>
  442. #include <process.h>
  443. #else /* _WIN32_WCE */
  444. #define NO_CGI /* WinCE has no pipes */
  445. #define NO_POPEN /* WinCE has no popen */
  446. typedef long off_t;
  447. #define errno ((int)(GetLastError()))
  448. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  449. #endif /* _WIN32_WCE */
  450. #define MAKEUQUAD(lo, hi) \
  451. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  452. #define RATE_DIFF (10000000) /* 100 nsecs */
  453. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  454. #define SYS2UNIX_TIME(lo, hi) \
  455. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  456. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  457. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  458. * Also use _strtoui64 on modern M$ compilers */
  459. #if defined(_MSC_VER)
  460. #if (_MSC_VER < 1300)
  461. #define STRX(x) #x
  462. #define STR(x) STRX(x)
  463. #define __func__ __FILE__ ":" STR(__LINE__)
  464. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  465. #define strtoll(x, y, z) (_atoi64(x))
  466. #else
  467. #define __func__ __FUNCTION__
  468. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  469. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  470. #endif
  471. #endif /* _MSC_VER */
  472. #define ERRNO ((int)(GetLastError()))
  473. #define NO_SOCKLEN_T
  474. #if defined(_WIN64) || defined(__MINGW64__)
  475. #if !defined(SSL_LIB)
  476. #if defined(OPENSSL_API_1_1)
  477. #define SSL_LIB "libssl-1_1-x64.dll"
  478. #else /* OPENSSL_API_1_1 */
  479. #define SSL_LIB "ssleay64.dll"
  480. #endif /* OPENSSL_API_1_1 */
  481. #endif /* SSL_LIB */
  482. #if !defined(CRYPTO_LIB)
  483. #if defined(OPENSSL_API_1_1)
  484. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  485. #else /* OPENSSL_API_1_1 */
  486. #define CRYPTO_LIB "libeay64.dll"
  487. #endif /* OPENSSL_API_1_1 */
  488. #endif /* CRYPTO_LIB */
  489. #else /* defined(_WIN64) || defined(__MINGW64__) */
  490. #if !defined(SSL_LIB)
  491. #define SSL_LIB "ssleay32.dll"
  492. #endif /* SSL_LIB */
  493. #if !defined(CRYPTO_LIB)
  494. #define CRYPTO_LIB "libeay32.dll"
  495. #endif /* CRYPTO_LIB */
  496. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  497. #define O_NONBLOCK (0)
  498. #if !defined(W_OK)
  499. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  500. #endif
  501. #define _POSIX_
  502. #define INT64_FMT "I64d"
  503. #define UINT64_FMT "I64u"
  504. #define WINCDECL __cdecl
  505. #define vsnprintf_impl _vsnprintf
  506. #define access _access
  507. #define mg_sleep(x) (Sleep(x))
  508. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  509. #if !defined(popen)
  510. #define popen(x, y) (_popen(x, y))
  511. #endif
  512. #if !defined(pclose)
  513. #define pclose(x) (_pclose(x))
  514. #endif
  515. #define close(x) (_close(x))
  516. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  517. #define RTLD_LAZY (0)
  518. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  519. #define fdopen(x, y) (_fdopen((x), (y)))
  520. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  521. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  522. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  523. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  524. #define sleep(x) (Sleep((x)*1000))
  525. #define rmdir(x) (_rmdir(x))
  526. #if defined(_WIN64) || !defined(__MINGW32__)
  527. /* Only MinGW 32 bit is missing this function */
  528. #define timegm(x) (_mkgmtime(x))
  529. #else
  530. time_t timegm(struct tm *tm);
  531. #define NEED_TIMEGM
  532. #endif
  533. #if !defined(fileno)
  534. #define fileno(x) (_fileno(x))
  535. #endif /* !fileno MINGW #defines fileno */
  536. typedef struct {
  537. CRITICAL_SECTION sec; /* Immovable */
  538. } pthread_mutex_t;
  539. typedef DWORD pthread_key_t;
  540. typedef HANDLE pthread_t;
  541. typedef struct {
  542. pthread_mutex_t threadIdSec;
  543. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  544. } pthread_cond_t;
  545. #if !defined(__clockid_t_defined)
  546. typedef DWORD clockid_t;
  547. #endif
  548. #if !defined(CLOCK_MONOTONIC)
  549. #define CLOCK_MONOTONIC (1)
  550. #endif
  551. #if !defined(CLOCK_REALTIME)
  552. #define CLOCK_REALTIME (2)
  553. #endif
  554. #if !defined(CLOCK_THREAD)
  555. #define CLOCK_THREAD (3)
  556. #endif
  557. #if !defined(CLOCK_PROCESS)
  558. #define CLOCK_PROCESS (4)
  559. #endif
  560. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  561. #define _TIMESPEC_DEFINED
  562. #endif
  563. #if !defined(_TIMESPEC_DEFINED)
  564. struct timespec {
  565. time_t tv_sec; /* seconds */
  566. long tv_nsec; /* nanoseconds */
  567. };
  568. #endif
  569. #if !defined(WIN_PTHREADS_TIME_H)
  570. #define MUST_IMPLEMENT_CLOCK_GETTIME
  571. #endif
  572. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  573. #define clock_gettime mg_clock_gettime
  574. static int
  575. clock_gettime(clockid_t clk_id, struct timespec *tp)
  576. {
  577. FILETIME ft;
  578. ULARGE_INTEGER li, li2;
  579. BOOL ok = FALSE;
  580. double d;
  581. static double perfcnt_per_sec = 0.0;
  582. static BOOL initialized = FALSE;
  583. if (!initialized) {
  584. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  585. perfcnt_per_sec = 1.0 / li.QuadPart;
  586. initialized = TRUE;
  587. }
  588. if (tp) {
  589. memset(tp, 0, sizeof(*tp));
  590. if (clk_id == CLOCK_REALTIME) {
  591. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  592. GetSystemTimeAsFileTime(&ft);
  593. li.LowPart = ft.dwLowDateTime;
  594. li.HighPart = ft.dwHighDateTime;
  595. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  596. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  597. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  598. ok = TRUE;
  599. /* END: CLOCK_REALTIME */
  600. } else if (clk_id == CLOCK_MONOTONIC) {
  601. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  602. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  603. d = li.QuadPart * perfcnt_per_sec;
  604. tp->tv_sec = (time_t)d;
  605. d -= (double)tp->tv_sec;
  606. tp->tv_nsec = (long)(d * 1.0E9);
  607. ok = TRUE;
  608. /* END: CLOCK_MONOTONIC */
  609. } else if (clk_id == CLOCK_THREAD) {
  610. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  611. FILETIME t_create, t_exit, t_kernel, t_user;
  612. if (GetThreadTimes(GetCurrentThread(),
  613. &t_create,
  614. &t_exit,
  615. &t_kernel,
  616. &t_user)) {
  617. li.LowPart = t_user.dwLowDateTime;
  618. li.HighPart = t_user.dwHighDateTime;
  619. li2.LowPart = t_kernel.dwLowDateTime;
  620. li2.HighPart = t_kernel.dwHighDateTime;
  621. li.QuadPart += li2.QuadPart;
  622. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  623. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  624. ok = TRUE;
  625. }
  626. /* END: CLOCK_THREAD */
  627. } else if (clk_id == CLOCK_PROCESS) {
  628. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  629. FILETIME t_create, t_exit, t_kernel, t_user;
  630. if (GetProcessTimes(GetCurrentProcess(),
  631. &t_create,
  632. &t_exit,
  633. &t_kernel,
  634. &t_user)) {
  635. li.LowPart = t_user.dwLowDateTime;
  636. li.HighPart = t_user.dwHighDateTime;
  637. li2.LowPart = t_kernel.dwLowDateTime;
  638. li2.HighPart = t_kernel.dwHighDateTime;
  639. li.QuadPart += li2.QuadPart;
  640. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  641. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  642. ok = TRUE;
  643. }
  644. /* END: CLOCK_PROCESS */
  645. } else {
  646. /* BEGIN: unknown clock */
  647. /* ok = FALSE; already set by init */
  648. /* END: unknown clock */
  649. }
  650. }
  651. return ok ? 0 : -1;
  652. }
  653. #endif
  654. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  655. static int pthread_mutex_lock(pthread_mutex_t *);
  656. static int pthread_mutex_unlock(pthread_mutex_t *);
  657. static void path_to_unicode(const struct mg_connection *conn,
  658. const char *path,
  659. wchar_t *wbuf,
  660. size_t wbuf_len);
  661. /* All file operations need to be rewritten to solve #246. */
  662. struct mg_file;
  663. static const char *
  664. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  665. /* POSIX dirent interface */
  666. struct dirent {
  667. char d_name[PATH_MAX];
  668. };
  669. typedef struct DIR {
  670. HANDLE handle;
  671. WIN32_FIND_DATAW info;
  672. struct dirent result;
  673. } DIR;
  674. #if defined(HAVE_POLL)
  675. #define mg_pollfd pollfd
  676. #else
  677. struct mg_pollfd {
  678. SOCKET fd;
  679. short events;
  680. short revents;
  681. };
  682. #endif
  683. /* Mark required libraries */
  684. #if defined(_MSC_VER)
  685. #pragma comment(lib, "Ws2_32.lib")
  686. #endif
  687. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  688. #include <inttypes.h>
  689. typedef const void *SOCK_OPT_TYPE;
  690. #if defined(ANDROID)
  691. typedef unsigned short int in_port_t;
  692. #endif
  693. #if !defined(__ZEPHYR__)
  694. #include <arpa/inet.h>
  695. #include <ctype.h>
  696. #include <dirent.h>
  697. #include <grp.h>
  698. #include <limits.h>
  699. #include <netdb.h>
  700. #include <netinet/in.h>
  701. #include <netinet/tcp.h>
  702. #include <pthread.h>
  703. #include <pwd.h>
  704. #include <stdarg.h>
  705. #include <stddef.h>
  706. #include <stdio.h>
  707. #include <stdlib.h>
  708. #include <string.h>
  709. #include <sys/poll.h>
  710. #include <sys/socket.h>
  711. #include <sys/time.h>
  712. #include <sys/utsname.h>
  713. #include <sys/wait.h>
  714. #include <time.h>
  715. #include <unistd.h>
  716. #endif
  717. #define vsnprintf_impl vsnprintf
  718. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  719. #include <dlfcn.h>
  720. #endif
  721. #if defined(__MACH__)
  722. #define SSL_LIB "libssl.dylib"
  723. #define CRYPTO_LIB "libcrypto.dylib"
  724. #else
  725. #if !defined(SSL_LIB)
  726. #define SSL_LIB "libssl.so"
  727. #endif
  728. #if !defined(CRYPTO_LIB)
  729. #define CRYPTO_LIB "libcrypto.so"
  730. #endif
  731. #endif
  732. #if !defined(O_BINARY)
  733. #define O_BINARY (0)
  734. #endif /* O_BINARY */
  735. #define closesocket(a) (close(a))
  736. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  737. #define mg_remove(conn, x) (remove(x))
  738. #define mg_sleep(x) (usleep((x)*1000))
  739. #define mg_opendir(conn, x) (opendir(x))
  740. #define mg_closedir(x) (closedir(x))
  741. #define mg_readdir(x) (readdir(x))
  742. #define ERRNO (errno)
  743. #define INVALID_SOCKET (-1)
  744. #define INT64_FMT PRId64
  745. #define UINT64_FMT PRIu64
  746. typedef int SOCKET;
  747. #define WINCDECL
  748. #if defined(__hpux)
  749. /* HPUX 11 does not have monotonic, fall back to realtime */
  750. #if !defined(CLOCK_MONOTONIC)
  751. #define CLOCK_MONOTONIC CLOCK_REALTIME
  752. #endif
  753. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  754. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  755. * the prototypes use int* rather than socklen_t* which matches the
  756. * actual library expectation. When called with the wrong size arg
  757. * accept() returns a zero client inet addr and check_acl() always
  758. * fails. Since socklen_t is widely used below, just force replace
  759. * their typedef with int. - DTL
  760. */
  761. #define socklen_t int
  762. #endif /* hpux */
  763. #define mg_pollfd pollfd
  764. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  765. /* In case our C library is missing "timegm", provide an implementation */
  766. #if defined(NEED_TIMEGM)
  767. static inline int
  768. is_leap(int y)
  769. {
  770. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  771. }
  772. static inline int
  773. count_leap(int y)
  774. {
  775. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  776. }
  777. time_t
  778. timegm(struct tm *tm)
  779. {
  780. static const unsigned short ydays[] = {
  781. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  782. int year = tm->tm_year + 1900;
  783. int mon = tm->tm_mon;
  784. int mday = tm->tm_mday - 1;
  785. int hour = tm->tm_hour;
  786. int min = tm->tm_min;
  787. int sec = tm->tm_sec;
  788. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  789. || (mday >= ydays[mon + 1] - ydays[mon]
  790. + (mon == 1 && is_leap(year) ? 1 : 0))
  791. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  792. return -1;
  793. time_t res = year - 1970;
  794. res *= 365;
  795. res += mday;
  796. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  797. res += count_leap(year);
  798. res *= 24;
  799. res += hour;
  800. res *= 60;
  801. res += min;
  802. res *= 60;
  803. res += sec;
  804. return res;
  805. }
  806. #endif /* NEED_TIMEGM */
  807. /* va_copy should always be a macro, C99 and C++11 - DTL */
  808. #if !defined(va_copy)
  809. #define va_copy(x, y) ((x) = (y))
  810. #endif
  811. #if defined(_WIN32)
  812. /* Create substitutes for POSIX functions in Win32. */
  813. #if defined(GCC_DIAGNOSTIC)
  814. /* Show no warning in case system functions are not used. */
  815. #pragma GCC diagnostic push
  816. #pragma GCC diagnostic ignored "-Wunused-function"
  817. #endif
  818. static pthread_mutex_t global_log_file_lock;
  819. FUNCTION_MAY_BE_UNUSED
  820. static DWORD
  821. pthread_self(void)
  822. {
  823. return GetCurrentThreadId();
  824. }
  825. FUNCTION_MAY_BE_UNUSED
  826. static int
  827. pthread_key_create(
  828. pthread_key_t *key,
  829. void (*_ignored)(void *) /* destructor not supported for Windows */
  830. )
  831. {
  832. (void)_ignored;
  833. if ((key != 0)) {
  834. *key = TlsAlloc();
  835. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  836. }
  837. return -2;
  838. }
  839. FUNCTION_MAY_BE_UNUSED
  840. static int
  841. pthread_key_delete(pthread_key_t key)
  842. {
  843. return TlsFree(key) ? 0 : 1;
  844. }
  845. FUNCTION_MAY_BE_UNUSED
  846. static int
  847. pthread_setspecific(pthread_key_t key, void *value)
  848. {
  849. return TlsSetValue(key, value) ? 0 : 1;
  850. }
  851. FUNCTION_MAY_BE_UNUSED
  852. static void *
  853. pthread_getspecific(pthread_key_t key)
  854. {
  855. return TlsGetValue(key);
  856. }
  857. #if defined(GCC_DIAGNOSTIC)
  858. /* Enable unused function warning again */
  859. #pragma GCC diagnostic pop
  860. #endif
  861. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  862. #else
  863. static pthread_mutexattr_t pthread_mutex_attr;
  864. #endif /* _WIN32 */
  865. #if defined(_WIN32_WCE)
  866. /* Create substitutes for POSIX functions in Win32. */
  867. #if defined(GCC_DIAGNOSTIC)
  868. /* Show no warning in case system functions are not used. */
  869. #pragma GCC diagnostic push
  870. #pragma GCC diagnostic ignored "-Wunused-function"
  871. #endif
  872. FUNCTION_MAY_BE_UNUSED
  873. static time_t
  874. time(time_t *ptime)
  875. {
  876. time_t t;
  877. SYSTEMTIME st;
  878. FILETIME ft;
  879. GetSystemTime(&st);
  880. SystemTimeToFileTime(&st, &ft);
  881. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  882. if (ptime != NULL) {
  883. *ptime = t;
  884. }
  885. return t;
  886. }
  887. FUNCTION_MAY_BE_UNUSED
  888. static struct tm *
  889. localtime_s(const time_t *ptime, struct tm *ptm)
  890. {
  891. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  892. FILETIME ft, lft;
  893. SYSTEMTIME st;
  894. TIME_ZONE_INFORMATION tzinfo;
  895. if (ptm == NULL) {
  896. return NULL;
  897. }
  898. *(int64_t *)&ft = t;
  899. FileTimeToLocalFileTime(&ft, &lft);
  900. FileTimeToSystemTime(&lft, &st);
  901. ptm->tm_year = st.wYear - 1900;
  902. ptm->tm_mon = st.wMonth - 1;
  903. ptm->tm_wday = st.wDayOfWeek;
  904. ptm->tm_mday = st.wDay;
  905. ptm->tm_hour = st.wHour;
  906. ptm->tm_min = st.wMinute;
  907. ptm->tm_sec = st.wSecond;
  908. ptm->tm_yday = 0; /* hope nobody uses this */
  909. ptm->tm_isdst =
  910. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  911. return ptm;
  912. }
  913. FUNCTION_MAY_BE_UNUSED
  914. static struct tm *
  915. gmtime_s(const time_t *ptime, struct tm *ptm)
  916. {
  917. /* FIXME(lsm): fix this. */
  918. return localtime_s(ptime, ptm);
  919. }
  920. static int mg_atomic_inc(volatile int *addr);
  921. static struct tm tm_array[MAX_WORKER_THREADS];
  922. static int tm_index = 0;
  923. FUNCTION_MAY_BE_UNUSED
  924. static struct tm *
  925. localtime(const time_t *ptime)
  926. {
  927. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  928. return localtime_s(ptime, tm_array + i);
  929. }
  930. FUNCTION_MAY_BE_UNUSED
  931. static struct tm *
  932. gmtime(const time_t *ptime)
  933. {
  934. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  935. return gmtime_s(ptime, tm_array + i);
  936. }
  937. FUNCTION_MAY_BE_UNUSED
  938. static size_t
  939. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  940. {
  941. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  942. * for WinCE"); */
  943. return 0;
  944. }
  945. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  946. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  947. #define remove(f) mg_remove(NULL, f)
  948. FUNCTION_MAY_BE_UNUSED
  949. static int
  950. rename(const char *a, const char *b)
  951. {
  952. wchar_t wa[W_PATH_MAX];
  953. wchar_t wb[W_PATH_MAX];
  954. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  955. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  956. return MoveFileW(wa, wb) ? 0 : -1;
  957. }
  958. struct stat {
  959. int64_t st_size;
  960. time_t st_mtime;
  961. };
  962. FUNCTION_MAY_BE_UNUSED
  963. static int
  964. stat(const char *name, struct stat *st)
  965. {
  966. wchar_t wbuf[W_PATH_MAX];
  967. WIN32_FILE_ATTRIBUTE_DATA attr;
  968. time_t creation_time, write_time;
  969. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  970. memset(&attr, 0, sizeof(attr));
  971. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  972. st->st_size =
  973. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  974. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  975. attr.ftLastWriteTime.dwHighDateTime);
  976. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  977. attr.ftCreationTime.dwHighDateTime);
  978. if (creation_time > write_time) {
  979. st->st_mtime = creation_time;
  980. } else {
  981. st->st_mtime = write_time;
  982. }
  983. return 0;
  984. }
  985. #define access(x, a) 1 /* not required anyway */
  986. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  987. /* Values from errno.h in Windows SDK (Visual Studio). */
  988. #define EEXIST 17
  989. #define EACCES 13
  990. #define ENOENT 2
  991. #if defined(GCC_DIAGNOSTIC)
  992. /* Enable unused function warning again */
  993. #pragma GCC diagnostic pop
  994. #endif
  995. #endif /* defined(_WIN32_WCE) */
  996. #if defined(GCC_DIAGNOSTIC)
  997. /* Show no warning in case system functions are not used. */
  998. #pragma GCC diagnostic push
  999. #pragma GCC diagnostic ignored "-Wunused-function"
  1000. #endif /* defined(GCC_DIAGNOSTIC) */
  1001. #if defined(__clang__)
  1002. /* Show no warning in case system functions are not used. */
  1003. #pragma clang diagnostic push
  1004. #pragma clang diagnostic ignored "-Wunused-function"
  1005. #endif
  1006. static pthread_mutex_t global_lock_mutex;
  1007. FUNCTION_MAY_BE_UNUSED
  1008. static void
  1009. mg_global_lock(void)
  1010. {
  1011. (void)pthread_mutex_lock(&global_lock_mutex);
  1012. }
  1013. FUNCTION_MAY_BE_UNUSED
  1014. static void
  1015. mg_global_unlock(void)
  1016. {
  1017. (void)pthread_mutex_unlock(&global_lock_mutex);
  1018. }
  1019. FUNCTION_MAY_BE_UNUSED
  1020. static int
  1021. mg_atomic_inc(volatile int *addr)
  1022. {
  1023. int ret;
  1024. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1025. /* Depending on the SDK, this function uses either
  1026. * (volatile unsigned int *) or (volatile LONG *),
  1027. * so whatever you use, the other SDK is likely to raise a warning. */
  1028. ret = InterlockedIncrement((volatile long *)addr);
  1029. #elif defined(__GNUC__) \
  1030. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1031. && !defined(NO_ATOMICS)
  1032. ret = __sync_add_and_fetch(addr, 1);
  1033. #else
  1034. mg_global_lock();
  1035. ret = (++(*addr));
  1036. mg_global_unlock();
  1037. #endif
  1038. return ret;
  1039. }
  1040. FUNCTION_MAY_BE_UNUSED
  1041. static int
  1042. mg_atomic_dec(volatile int *addr)
  1043. {
  1044. int ret;
  1045. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1046. /* Depending on the SDK, this function uses either
  1047. * (volatile unsigned int *) or (volatile LONG *),
  1048. * so whatever you use, the other SDK is likely to raise a warning. */
  1049. ret = InterlockedDecrement((volatile long *)addr);
  1050. #elif defined(__GNUC__) \
  1051. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1052. && !defined(NO_ATOMICS)
  1053. ret = __sync_sub_and_fetch(addr, 1);
  1054. #else
  1055. mg_global_lock();
  1056. ret = (--(*addr));
  1057. mg_global_unlock();
  1058. #endif
  1059. return ret;
  1060. }
  1061. #if defined(USE_SERVER_STATS)
  1062. static int64_t
  1063. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1064. {
  1065. int64_t ret;
  1066. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1067. ret = InterlockedAdd64(addr, value);
  1068. #elif defined(__GNUC__) \
  1069. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1070. && !defined(NO_ATOMICS)
  1071. ret = __sync_add_and_fetch(addr, value);
  1072. #else
  1073. mg_global_lock();
  1074. *addr += value;
  1075. ret = (*addr);
  1076. mg_global_unlock();
  1077. #endif
  1078. return ret;
  1079. }
  1080. #endif
  1081. #if defined(GCC_DIAGNOSTIC)
  1082. /* Show no warning in case system functions are not used. */
  1083. #pragma GCC diagnostic pop
  1084. #endif /* defined(GCC_DIAGNOSTIC) */
  1085. #if defined(__clang__)
  1086. /* Show no warning in case system functions are not used. */
  1087. #pragma clang diagnostic pop
  1088. #endif
  1089. #if defined(USE_SERVER_STATS)
  1090. struct mg_memory_stat {
  1091. volatile int64_t totalMemUsed;
  1092. volatile int64_t maxMemUsed;
  1093. volatile int blockCount;
  1094. };
  1095. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1096. static void *
  1097. mg_malloc_ex(size_t size,
  1098. struct mg_context *ctx,
  1099. const char *file,
  1100. unsigned line)
  1101. {
  1102. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1103. void *memory = 0;
  1104. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1105. #if defined(MEMORY_DEBUGGING)
  1106. char mallocStr[256];
  1107. #else
  1108. (void)file;
  1109. (void)line;
  1110. #endif
  1111. if (data) {
  1112. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1113. if (mmem > mstat->maxMemUsed) {
  1114. /* could use atomic compare exchange, but this
  1115. * seems overkill for statistics data */
  1116. mstat->maxMemUsed = mmem;
  1117. }
  1118. mg_atomic_inc(&mstat->blockCount);
  1119. ((uintptr_t *)data)[0] = size;
  1120. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1121. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1122. }
  1123. #if defined(MEMORY_DEBUGGING)
  1124. sprintf(mallocStr,
  1125. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1126. memory,
  1127. (unsigned long)size,
  1128. (unsigned long)mstat->totalMemUsed,
  1129. (unsigned long)mstat->blockCount,
  1130. file,
  1131. line);
  1132. #if defined(_WIN32)
  1133. OutputDebugStringA(mallocStr);
  1134. #else
  1135. DEBUG_TRACE("%s", mallocStr);
  1136. #endif
  1137. #endif
  1138. return memory;
  1139. }
  1140. static void *
  1141. mg_calloc_ex(size_t count,
  1142. size_t size,
  1143. struct mg_context *ctx,
  1144. const char *file,
  1145. unsigned line)
  1146. {
  1147. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1148. if (data) {
  1149. memset(data, 0, size * count);
  1150. }
  1151. return data;
  1152. }
  1153. static void
  1154. mg_free_ex(void *memory, const char *file, unsigned line)
  1155. {
  1156. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1157. #if defined(MEMORY_DEBUGGING)
  1158. char mallocStr[256];
  1159. #else
  1160. (void)file;
  1161. (void)line;
  1162. #endif
  1163. if (memory) {
  1164. uintptr_t size = ((uintptr_t *)data)[0];
  1165. struct mg_memory_stat *mstat =
  1166. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1167. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1168. mg_atomic_dec(&mstat->blockCount);
  1169. #if defined(MEMORY_DEBUGGING)
  1170. sprintf(mallocStr,
  1171. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1172. memory,
  1173. (unsigned long)size,
  1174. (unsigned long)mstat->totalMemUsed,
  1175. (unsigned long)mstat->blockCount,
  1176. file,
  1177. line);
  1178. #if defined(_WIN32)
  1179. OutputDebugStringA(mallocStr);
  1180. #else
  1181. DEBUG_TRACE("%s", mallocStr);
  1182. #endif
  1183. #endif
  1184. free(data);
  1185. }
  1186. }
  1187. static void *
  1188. mg_realloc_ex(void *memory,
  1189. size_t newsize,
  1190. struct mg_context *ctx,
  1191. const char *file,
  1192. unsigned line)
  1193. {
  1194. void *data;
  1195. void *_realloc;
  1196. uintptr_t oldsize;
  1197. #if defined(MEMORY_DEBUGGING)
  1198. char mallocStr[256];
  1199. #else
  1200. (void)file;
  1201. (void)line;
  1202. #endif
  1203. if (newsize) {
  1204. if (memory) {
  1205. /* Reallocate existing block */
  1206. struct mg_memory_stat *mstat;
  1207. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1208. oldsize = ((uintptr_t *)data)[0];
  1209. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1210. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1211. if (_realloc) {
  1212. data = _realloc;
  1213. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1214. #if defined(MEMORY_DEBUGGING)
  1215. sprintf(mallocStr,
  1216. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1217. memory,
  1218. (unsigned long)oldsize,
  1219. (unsigned long)mstat->totalMemUsed,
  1220. (unsigned long)mstat->blockCount,
  1221. file,
  1222. line);
  1223. #if defined(_WIN32)
  1224. OutputDebugStringA(mallocStr);
  1225. #else
  1226. DEBUG_TRACE("%s", mallocStr);
  1227. #endif
  1228. #endif
  1229. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1230. #if defined(MEMORY_DEBUGGING)
  1231. sprintf(mallocStr,
  1232. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1233. memory,
  1234. (unsigned long)newsize,
  1235. (unsigned long)mstat->totalMemUsed,
  1236. (unsigned long)mstat->blockCount,
  1237. file,
  1238. line);
  1239. #if defined(_WIN32)
  1240. OutputDebugStringA(mallocStr);
  1241. #else
  1242. DEBUG_TRACE("%s", mallocStr);
  1243. #endif
  1244. #endif
  1245. *(uintptr_t *)data = newsize;
  1246. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1247. } else {
  1248. #if defined(MEMORY_DEBUGGING)
  1249. #if defined(_WIN32)
  1250. OutputDebugStringA("MEM: realloc failed\n");
  1251. #else
  1252. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1253. #endif
  1254. #endif
  1255. return _realloc;
  1256. }
  1257. } else {
  1258. /* Allocate new block */
  1259. data = mg_malloc_ex(newsize, ctx, file, line);
  1260. }
  1261. } else {
  1262. /* Free existing block */
  1263. data = 0;
  1264. mg_free_ex(memory, file, line);
  1265. }
  1266. return data;
  1267. }
  1268. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1269. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1270. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1271. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1272. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1273. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1274. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1275. #else /* USE_SERVER_STATS */
  1276. static __inline void *
  1277. mg_malloc(size_t a)
  1278. {
  1279. return malloc(a);
  1280. }
  1281. static __inline void *
  1282. mg_calloc(size_t a, size_t b)
  1283. {
  1284. return calloc(a, b);
  1285. }
  1286. static __inline void *
  1287. mg_realloc(void *a, size_t b)
  1288. {
  1289. return realloc(a, b);
  1290. }
  1291. static __inline void
  1292. mg_free(void *a)
  1293. {
  1294. free(a);
  1295. }
  1296. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1297. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1298. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1299. #define mg_free_ctx(a, c) mg_free(a)
  1300. #endif /* USE_SERVER_STATS */
  1301. static void mg_vsnprintf(const struct mg_connection *conn,
  1302. int *truncated,
  1303. char *buf,
  1304. size_t buflen,
  1305. const char *fmt,
  1306. va_list ap);
  1307. static void mg_snprintf(const struct mg_connection *conn,
  1308. int *truncated,
  1309. char *buf,
  1310. size_t buflen,
  1311. PRINTF_FORMAT_STRING(const char *fmt),
  1312. ...) PRINTF_ARGS(5, 6);
  1313. /* This following lines are just meant as a reminder to use the mg-functions
  1314. * for memory management */
  1315. #if defined(malloc)
  1316. #undef malloc
  1317. #endif
  1318. #if defined(calloc)
  1319. #undef calloc
  1320. #endif
  1321. #if defined(realloc)
  1322. #undef realloc
  1323. #endif
  1324. #if defined(free)
  1325. #undef free
  1326. #endif
  1327. #if defined(snprintf)
  1328. #undef snprintf
  1329. #endif
  1330. #if defined(vsnprintf)
  1331. #undef vsnprintf
  1332. #endif
  1333. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1334. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1335. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1336. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1337. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1338. #if defined(_WIN32)
  1339. /* vsnprintf must not be used in any system,
  1340. * but this define only works well for Windows. */
  1341. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1342. #endif
  1343. /* mg_init_library counter */
  1344. static int mg_init_library_called = 0;
  1345. #if !defined(NO_SSL)
  1346. static int mg_ssl_initialized = 0;
  1347. #endif
  1348. static pthread_key_t sTlsKey; /* Thread local storage index */
  1349. static int thread_idx_max = 0;
  1350. #if defined(MG_LEGACY_INTERFACE)
  1351. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1352. #endif
  1353. struct mg_workerTLS {
  1354. int is_master;
  1355. unsigned long thread_idx;
  1356. void *user_ptr;
  1357. #if defined(_WIN32)
  1358. HANDLE pthread_cond_helper_mutex;
  1359. struct mg_workerTLS *next_waiting_thread;
  1360. #endif
  1361. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1362. char txtbuf[4];
  1363. #endif
  1364. };
  1365. #if defined(GCC_DIAGNOSTIC)
  1366. /* Show no warning in case system functions are not used. */
  1367. #pragma GCC diagnostic push
  1368. #pragma GCC diagnostic ignored "-Wunused-function"
  1369. #endif /* defined(GCC_DIAGNOSTIC) */
  1370. #if defined(__clang__)
  1371. /* Show no warning in case system functions are not used. */
  1372. #pragma clang diagnostic push
  1373. #pragma clang diagnostic ignored "-Wunused-function"
  1374. #endif
  1375. /* Get a unique thread ID as unsigned long, independent from the data type
  1376. * of thread IDs defined by the operating system API.
  1377. * If two calls to mg_current_thread_id return the same value, they calls
  1378. * are done from the same thread. If they return different values, they are
  1379. * done from different threads. (Provided this function is used in the same
  1380. * process context and threads are not repeatedly created and deleted, but
  1381. * CivetWeb does not do that).
  1382. * This function must match the signature required for SSL id callbacks:
  1383. * CRYPTO_set_id_callback
  1384. */
  1385. FUNCTION_MAY_BE_UNUSED
  1386. static unsigned long
  1387. mg_current_thread_id(void)
  1388. {
  1389. #if defined(_WIN32)
  1390. return GetCurrentThreadId();
  1391. #else
  1392. #if defined(__clang__)
  1393. #pragma clang diagnostic push
  1394. #pragma clang diagnostic ignored "-Wunreachable-code"
  1395. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1396. * or not, so one of the two conditions will be unreachable by construction.
  1397. * Unfortunately the C standard does not define a way to check this at
  1398. * compile time, since the #if preprocessor conditions can not use the sizeof
  1399. * operator as an argument. */
  1400. #endif
  1401. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1402. /* This is the problematic case for CRYPTO_set_id_callback:
  1403. * The OS pthread_t can not be cast to unsigned long. */
  1404. struct mg_workerTLS *tls =
  1405. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1406. if (tls == NULL) {
  1407. /* SSL called from an unknown thread: Create some thread index.
  1408. */
  1409. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1410. tls->is_master = -2; /* -2 means "3rd party thread" */
  1411. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1412. pthread_setspecific(sTlsKey, tls);
  1413. }
  1414. return tls->thread_idx;
  1415. } else {
  1416. /* pthread_t may be any data type, so a simple cast to unsigned long
  1417. * can rise a warning/error, depending on the platform.
  1418. * Here memcpy is used as an anything-to-anything cast. */
  1419. unsigned long ret = 0;
  1420. pthread_t t = pthread_self();
  1421. memcpy(&ret, &t, sizeof(pthread_t));
  1422. return ret;
  1423. }
  1424. #if defined(__clang__)
  1425. #pragma clang diagnostic pop
  1426. #endif
  1427. #endif
  1428. }
  1429. FUNCTION_MAY_BE_UNUSED
  1430. static uint64_t
  1431. mg_get_current_time_ns(void)
  1432. {
  1433. struct timespec tsnow;
  1434. clock_gettime(CLOCK_REALTIME, &tsnow);
  1435. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1436. }
  1437. #if defined(GCC_DIAGNOSTIC)
  1438. /* Show no warning in case system functions are not used. */
  1439. #pragma GCC diagnostic pop
  1440. #endif /* defined(GCC_DIAGNOSTIC) */
  1441. #if defined(__clang__)
  1442. /* Show no warning in case system functions are not used. */
  1443. #pragma clang diagnostic pop
  1444. #endif
  1445. #if defined(NEED_DEBUG_TRACE_FUNC)
  1446. static void
  1447. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1448. {
  1449. va_list args;
  1450. uint64_t nsnow;
  1451. static uint64_t nslast;
  1452. struct timespec tsnow;
  1453. /* Get some operating system independent thread id */
  1454. unsigned long thread_id = mg_current_thread_id();
  1455. clock_gettime(CLOCK_REALTIME, &tsnow);
  1456. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1457. + ((uint64_t)tsnow.tv_nsec);
  1458. if (!nslast) {
  1459. nslast = nsnow;
  1460. }
  1461. flockfile(stdout);
  1462. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1463. (unsigned long)tsnow.tv_sec,
  1464. (unsigned long)tsnow.tv_nsec,
  1465. nsnow - nslast,
  1466. thread_id,
  1467. func,
  1468. line);
  1469. va_start(args, fmt);
  1470. vprintf(fmt, args);
  1471. va_end(args);
  1472. putchar('\n');
  1473. fflush(stdout);
  1474. funlockfile(stdout);
  1475. nslast = nsnow;
  1476. }
  1477. #endif /* NEED_DEBUG_TRACE_FUNC */
  1478. #define MD5_STATIC static
  1479. #include "md5.inl"
  1480. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1481. #if defined(NO_SOCKLEN_T)
  1482. typedef int socklen_t;
  1483. #endif /* NO_SOCKLEN_T */
  1484. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1485. #if !defined(MSG_NOSIGNAL)
  1486. #define MSG_NOSIGNAL (0)
  1487. #endif
  1488. #if defined(NO_SSL)
  1489. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1490. typedef struct SSL_CTX SSL_CTX;
  1491. #else
  1492. #if defined(NO_SSL_DL)
  1493. #include <openssl/bn.h>
  1494. #include <openssl/conf.h>
  1495. #include <openssl/crypto.h>
  1496. #include <openssl/dh.h>
  1497. #include <openssl/engine.h>
  1498. #include <openssl/err.h>
  1499. #include <openssl/opensslv.h>
  1500. #include <openssl/pem.h>
  1501. #include <openssl/ssl.h>
  1502. #include <openssl/tls1.h>
  1503. #include <openssl/x509.h>
  1504. #if defined(WOLFSSL_VERSION)
  1505. /* Additional defines for WolfSSL, see
  1506. * https://github.com/civetweb/civetweb/issues/583 */
  1507. #include "wolfssl_extras.inl"
  1508. #endif
  1509. #if defined(OPENSSL_IS_BORINGSSL)
  1510. /* From boringssl/src/include/openssl/mem.h:
  1511. *
  1512. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1513. * However, that was written in a time before Valgrind and ASAN. Since we now
  1514. * have those tools, the OpenSSL allocation functions are simply macros around
  1515. * the standard memory functions.
  1516. *
  1517. * #define OPENSSL_free free */
  1518. #define free free
  1519. // disable for boringssl
  1520. #define CONF_modules_unload(a) ((void)0)
  1521. #define ENGINE_cleanup() ((void)0)
  1522. #endif
  1523. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1524. /* If OpenSSL headers are included, automatically select the API version */
  1525. #if !defined(OPENSSL_API_1_1)
  1526. #define OPENSSL_API_1_1
  1527. #endif
  1528. #define OPENSSL_REMOVE_THREAD_STATE()
  1529. #else
  1530. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1531. #endif
  1532. #else
  1533. /* SSL loaded dynamically from DLL.
  1534. * I put the prototypes here to be independent from OpenSSL source
  1535. * installation. */
  1536. typedef struct ssl_st SSL;
  1537. typedef struct ssl_method_st SSL_METHOD;
  1538. typedef struct ssl_ctx_st SSL_CTX;
  1539. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1540. typedef struct x509_name X509_NAME;
  1541. typedef struct asn1_integer ASN1_INTEGER;
  1542. typedef struct bignum BIGNUM;
  1543. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1544. typedef struct evp_md EVP_MD;
  1545. typedef struct x509 X509;
  1546. #define SSL_CTRL_OPTIONS (32)
  1547. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1548. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1549. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1550. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1551. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1552. #define SSL_VERIFY_NONE (0)
  1553. #define SSL_VERIFY_PEER (1)
  1554. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1555. #define SSL_VERIFY_CLIENT_ONCE (4)
  1556. #define SSL_OP_ALL (0x80000BFFul)
  1557. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1558. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1559. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1560. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1561. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1562. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1563. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1564. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1565. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1566. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1567. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1568. #define SSL_CB_HANDSHAKE_START (0x10)
  1569. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1570. #define SSL_ERROR_NONE (0)
  1571. #define SSL_ERROR_SSL (1)
  1572. #define SSL_ERROR_WANT_READ (2)
  1573. #define SSL_ERROR_WANT_WRITE (3)
  1574. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1575. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1576. #define SSL_ERROR_ZERO_RETURN (6)
  1577. #define SSL_ERROR_WANT_CONNECT (7)
  1578. #define SSL_ERROR_WANT_ACCEPT (8)
  1579. #define TLSEXT_TYPE_server_name (0)
  1580. #define TLSEXT_NAMETYPE_host_name (0)
  1581. #define SSL_TLSEXT_ERR_OK (0)
  1582. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1583. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1584. #define SSL_TLSEXT_ERR_NOACK (3)
  1585. struct ssl_func {
  1586. const char *name; /* SSL function name */
  1587. void (*ptr)(void); /* Function pointer */
  1588. };
  1589. #if defined(OPENSSL_API_1_1)
  1590. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1591. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1592. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1593. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1594. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1595. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1596. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1597. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1598. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1599. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1600. #define OPENSSL_init_ssl \
  1601. (*(int (*)(uint64_t opts, \
  1602. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1603. .ptr)
  1604. #define SSL_CTX_use_PrivateKey_file \
  1605. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1606. #define SSL_CTX_use_certificate_file \
  1607. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1608. #define SSL_CTX_set_default_passwd_cb \
  1609. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1610. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1611. #define SSL_CTX_use_certificate_chain_file \
  1612. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1613. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1614. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1615. #define SSL_CTX_set_verify \
  1616. (*(void (*)(SSL_CTX *, \
  1617. int, \
  1618. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1619. .ptr)
  1620. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1621. #define SSL_CTX_load_verify_locations \
  1622. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1623. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1624. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1625. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1626. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1627. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1628. #define SSL_CIPHER_get_name \
  1629. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1630. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1631. #define SSL_CTX_set_session_id_context \
  1632. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1633. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1634. #define SSL_CTX_set_cipher_list \
  1635. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1636. #define SSL_CTX_set_options \
  1637. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1638. #define SSL_CTX_set_info_callback \
  1639. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1640. ssl_sw[32] \
  1641. .ptr)
  1642. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1643. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1644. #define SSL_CTX_callback_ctrl \
  1645. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1646. #define SSL_get_servername \
  1647. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1648. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1649. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1650. #define SSL_CTX_clear_options(ctx, op) \
  1651. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1652. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1653. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1654. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1655. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1656. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1657. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1658. SSL_CTX_callback_ctrl(ctx, \
  1659. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1660. (void (*)(void))cb)
  1661. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1662. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1663. #define SSL_set_tlsext_host_name(ctx, arg) \
  1664. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1665. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1666. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1667. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1668. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1669. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1670. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1671. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1672. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1673. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1674. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1675. #define X509_NAME_oneline \
  1676. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1677. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1678. #define EVP_get_digestbyname \
  1679. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1680. #define EVP_Digest \
  1681. (*(int (*)( \
  1682. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1683. crypto_sw[9] \
  1684. .ptr)
  1685. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1686. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1687. #define ASN1_INTEGER_to_BN \
  1688. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1689. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1690. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1691. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1692. #define OPENSSL_free(a) CRYPTO_free(a)
  1693. #define OPENSSL_REMOVE_THREAD_STATE()
  1694. /* init_ssl_ctx() function updates this array.
  1695. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1696. * of respective functions. The macros above (like SSL_connect()) are really
  1697. * just calling these functions indirectly via the pointer. */
  1698. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1699. {"SSL_accept", NULL},
  1700. {"SSL_connect", NULL},
  1701. {"SSL_read", NULL},
  1702. {"SSL_write", NULL},
  1703. {"SSL_get_error", NULL},
  1704. {"SSL_set_fd", NULL},
  1705. {"SSL_new", NULL},
  1706. {"SSL_CTX_new", NULL},
  1707. {"TLS_server_method", NULL},
  1708. {"OPENSSL_init_ssl", NULL},
  1709. {"SSL_CTX_use_PrivateKey_file", NULL},
  1710. {"SSL_CTX_use_certificate_file", NULL},
  1711. {"SSL_CTX_set_default_passwd_cb", NULL},
  1712. {"SSL_CTX_free", NULL},
  1713. {"SSL_CTX_use_certificate_chain_file", NULL},
  1714. {"TLS_client_method", NULL},
  1715. {"SSL_pending", NULL},
  1716. {"SSL_CTX_set_verify", NULL},
  1717. {"SSL_shutdown", NULL},
  1718. {"SSL_CTX_load_verify_locations", NULL},
  1719. {"SSL_CTX_set_default_verify_paths", NULL},
  1720. {"SSL_CTX_set_verify_depth", NULL},
  1721. {"SSL_get_peer_certificate", NULL},
  1722. {"SSL_get_version", NULL},
  1723. {"SSL_get_current_cipher", NULL},
  1724. {"SSL_CIPHER_get_name", NULL},
  1725. {"SSL_CTX_check_private_key", NULL},
  1726. {"SSL_CTX_set_session_id_context", NULL},
  1727. {"SSL_CTX_ctrl", NULL},
  1728. {"SSL_CTX_set_cipher_list", NULL},
  1729. {"SSL_CTX_set_options", NULL},
  1730. {"SSL_CTX_set_info_callback", NULL},
  1731. {"SSL_get_ex_data", NULL},
  1732. {"SSL_set_ex_data", NULL},
  1733. {"SSL_CTX_callback_ctrl", NULL},
  1734. {"SSL_get_servername", NULL},
  1735. {"SSL_set_SSL_CTX", NULL},
  1736. {"SSL_ctrl", NULL},
  1737. {NULL, NULL}};
  1738. /* Similar array as ssl_sw. These functions could be located in different
  1739. * lib. */
  1740. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1741. {"ERR_error_string", NULL},
  1742. {"CONF_modules_unload", NULL},
  1743. {"X509_free", NULL},
  1744. {"X509_get_subject_name", NULL},
  1745. {"X509_get_issuer_name", NULL},
  1746. {"X509_NAME_oneline", NULL},
  1747. {"X509_get_serialNumber", NULL},
  1748. {"EVP_get_digestbyname", NULL},
  1749. {"EVP_Digest", NULL},
  1750. {"i2d_X509", NULL},
  1751. {"BN_bn2hex", NULL},
  1752. {"ASN1_INTEGER_to_BN", NULL},
  1753. {"BN_free", NULL},
  1754. {"CRYPTO_free", NULL},
  1755. {"ERR_clear_error", NULL},
  1756. {NULL, NULL}};
  1757. #else
  1758. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1759. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1760. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1761. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1762. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1763. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1764. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1765. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1766. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1767. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1768. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1769. #define SSL_CTX_use_PrivateKey_file \
  1770. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1771. #define SSL_CTX_use_certificate_file \
  1772. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1773. #define SSL_CTX_set_default_passwd_cb \
  1774. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1775. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1776. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1777. #define SSL_CTX_use_certificate_chain_file \
  1778. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1779. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1780. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1781. #define SSL_CTX_set_verify \
  1782. (*(void (*)(SSL_CTX *, \
  1783. int, \
  1784. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1785. .ptr)
  1786. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1787. #define SSL_CTX_load_verify_locations \
  1788. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1789. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1790. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1791. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1792. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1793. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1794. #define SSL_CIPHER_get_name \
  1795. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1796. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1797. #define SSL_CTX_set_session_id_context \
  1798. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1799. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1800. #define SSL_CTX_set_cipher_list \
  1801. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1802. #define SSL_CTX_set_info_callback \
  1803. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1804. .ptr)
  1805. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1806. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1807. #define SSL_CTX_callback_ctrl \
  1808. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1809. #define SSL_get_servername \
  1810. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1811. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1812. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1813. #define SSL_CTX_set_options(ctx, op) \
  1814. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1815. #define SSL_CTX_clear_options(ctx, op) \
  1816. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1817. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1818. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1819. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1820. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1821. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1822. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1823. SSL_CTX_callback_ctrl(ctx, \
  1824. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1825. (void (*)(void))cb)
  1826. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1827. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1828. #define SSL_set_tlsext_host_name(ctx, arg) \
  1829. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1830. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1831. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1832. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1833. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1834. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1835. #define CRYPTO_set_locking_callback \
  1836. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1837. #define CRYPTO_set_id_callback \
  1838. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1839. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1840. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1841. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1842. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1843. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1844. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1845. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1846. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1847. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1848. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1849. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1850. #define X509_NAME_oneline \
  1851. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1852. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1853. #define i2c_ASN1_INTEGER \
  1854. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1855. #define EVP_get_digestbyname \
  1856. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1857. #define EVP_Digest \
  1858. (*(int (*)( \
  1859. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1860. crypto_sw[18] \
  1861. .ptr)
  1862. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1863. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1864. #define ASN1_INTEGER_to_BN \
  1865. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1866. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1867. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1868. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1869. #define OPENSSL_free(a) CRYPTO_free(a)
  1870. /* use here ERR_remove_state,
  1871. * while on some platforms function is not included into library due to
  1872. * deprication */
  1873. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1874. /* init_ssl_ctx() function updates this array.
  1875. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1876. * of respective functions. The macros above (like SSL_connect()) are really
  1877. * just calling these functions indirectly via the pointer. */
  1878. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1879. {"SSL_accept", NULL},
  1880. {"SSL_connect", NULL},
  1881. {"SSL_read", NULL},
  1882. {"SSL_write", NULL},
  1883. {"SSL_get_error", NULL},
  1884. {"SSL_set_fd", NULL},
  1885. {"SSL_new", NULL},
  1886. {"SSL_CTX_new", NULL},
  1887. {"SSLv23_server_method", NULL},
  1888. {"SSL_library_init", NULL},
  1889. {"SSL_CTX_use_PrivateKey_file", NULL},
  1890. {"SSL_CTX_use_certificate_file", NULL},
  1891. {"SSL_CTX_set_default_passwd_cb", NULL},
  1892. {"SSL_CTX_free", NULL},
  1893. {"SSL_load_error_strings", NULL},
  1894. {"SSL_CTX_use_certificate_chain_file", NULL},
  1895. {"SSLv23_client_method", NULL},
  1896. {"SSL_pending", NULL},
  1897. {"SSL_CTX_set_verify", NULL},
  1898. {"SSL_shutdown", NULL},
  1899. {"SSL_CTX_load_verify_locations", NULL},
  1900. {"SSL_CTX_set_default_verify_paths", NULL},
  1901. {"SSL_CTX_set_verify_depth", NULL},
  1902. {"SSL_get_peer_certificate", NULL},
  1903. {"SSL_get_version", NULL},
  1904. {"SSL_get_current_cipher", NULL},
  1905. {"SSL_CIPHER_get_name", NULL},
  1906. {"SSL_CTX_check_private_key", NULL},
  1907. {"SSL_CTX_set_session_id_context", NULL},
  1908. {"SSL_CTX_ctrl", NULL},
  1909. {"SSL_CTX_set_cipher_list", NULL},
  1910. {"SSL_CTX_set_info_callback", NULL},
  1911. {"SSL_get_ex_data", NULL},
  1912. {"SSL_set_ex_data", NULL},
  1913. {"SSL_CTX_callback_ctrl", NULL},
  1914. {"SSL_get_servername", NULL},
  1915. {"SSL_set_SSL_CTX", NULL},
  1916. {"SSL_ctrl", NULL},
  1917. {NULL, NULL}};
  1918. /* Similar array as ssl_sw. These functions could be located in different
  1919. * lib. */
  1920. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1921. {"CRYPTO_set_locking_callback", NULL},
  1922. {"CRYPTO_set_id_callback", NULL},
  1923. {"ERR_get_error", NULL},
  1924. {"ERR_error_string", NULL},
  1925. {"ERR_remove_state", NULL},
  1926. {"ERR_free_strings", NULL},
  1927. {"ENGINE_cleanup", NULL},
  1928. {"CONF_modules_unload", NULL},
  1929. {"CRYPTO_cleanup_all_ex_data", NULL},
  1930. {"EVP_cleanup", NULL},
  1931. {"X509_free", NULL},
  1932. {"X509_get_subject_name", NULL},
  1933. {"X509_get_issuer_name", NULL},
  1934. {"X509_NAME_oneline", NULL},
  1935. {"X509_get_serialNumber", NULL},
  1936. {"i2c_ASN1_INTEGER", NULL},
  1937. {"EVP_get_digestbyname", NULL},
  1938. {"EVP_Digest", NULL},
  1939. {"i2d_X509", NULL},
  1940. {"BN_bn2hex", NULL},
  1941. {"ASN1_INTEGER_to_BN", NULL},
  1942. {"BN_free", NULL},
  1943. {"CRYPTO_free", NULL},
  1944. {"ERR_clear_error", NULL},
  1945. {NULL, NULL}};
  1946. #endif /* OPENSSL_API_1_1 */
  1947. #endif /* NO_SSL_DL */
  1948. #endif /* NO_SSL */
  1949. #if !defined(NO_CACHING)
  1950. static const char month_names[][4] = {"Jan",
  1951. "Feb",
  1952. "Mar",
  1953. "Apr",
  1954. "May",
  1955. "Jun",
  1956. "Jul",
  1957. "Aug",
  1958. "Sep",
  1959. "Oct",
  1960. "Nov",
  1961. "Dec"};
  1962. #endif /* !NO_CACHING */
  1963. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1964. * the
  1965. * union u. */
  1966. union usa {
  1967. struct sockaddr sa;
  1968. struct sockaddr_in sin;
  1969. #if defined(USE_IPV6)
  1970. struct sockaddr_in6 sin6;
  1971. #endif
  1972. };
  1973. /* Describes a string (chunk of memory). */
  1974. struct vec {
  1975. const char *ptr;
  1976. size_t len;
  1977. };
  1978. struct mg_file_stat {
  1979. /* File properties filled by mg_stat: */
  1980. uint64_t size;
  1981. time_t last_modified;
  1982. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1983. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1984. * case we need a "Content-Eencoding: gzip" header */
  1985. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1986. };
  1987. struct mg_file_in_memory {
  1988. char *p;
  1989. uint32_t pos;
  1990. char mode;
  1991. };
  1992. struct mg_file_access {
  1993. /* File properties filled by mg_fopen: */
  1994. FILE *fp;
  1995. #if defined(MG_USE_OPEN_FILE)
  1996. /* TODO (low): Remove obsolete "file in memory" implementation.
  1997. * In an "early 2017" discussion at Google groups
  1998. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1999. * we decided to get rid of this feature (after some fade-out
  2000. * phase). */
  2001. const char *membuf;
  2002. #endif
  2003. };
  2004. struct mg_file {
  2005. struct mg_file_stat stat;
  2006. struct mg_file_access access;
  2007. };
  2008. #if defined(MG_USE_OPEN_FILE)
  2009. #define STRUCT_FILE_INITIALIZER \
  2010. { \
  2011. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2012. { \
  2013. (FILE *)NULL, (const char *)NULL \
  2014. } \
  2015. }
  2016. #else
  2017. #define STRUCT_FILE_INITIALIZER \
  2018. { \
  2019. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2020. { \
  2021. (FILE *)NULL \
  2022. } \
  2023. }
  2024. #endif
  2025. /* Describes listening socket, or socket which was accept()-ed by the master
  2026. * thread and queued for future handling by the worker thread. */
  2027. struct socket {
  2028. SOCKET sock; /* Listening socket */
  2029. union usa lsa; /* Local socket address */
  2030. union usa rsa; /* Remote socket address */
  2031. unsigned char is_ssl; /* Is port SSL-ed */
  2032. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2033. * port */
  2034. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2035. };
  2036. /* Enum const for all options must be in sync with
  2037. * static struct mg_option config_options[]
  2038. * This is tested in the unit test (test/private.c)
  2039. * "Private Config Options"
  2040. */
  2041. enum {
  2042. /* Once for each server */
  2043. LISTENING_PORTS,
  2044. NUM_THREADS,
  2045. RUN_AS_USER,
  2046. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2047. * socket option typedef TCP_NODELAY. */
  2048. MAX_REQUEST_SIZE,
  2049. LINGER_TIMEOUT,
  2050. CONNECTION_QUEUE_SIZE,
  2051. LISTEN_BACKLOG_SIZE,
  2052. #if defined(__linux__)
  2053. ALLOW_SENDFILE_CALL,
  2054. #endif
  2055. #if defined(_WIN32)
  2056. CASE_SENSITIVE_FILES,
  2057. #endif
  2058. THROTTLE,
  2059. ACCESS_LOG_FILE,
  2060. ERROR_LOG_FILE,
  2061. ENABLE_KEEP_ALIVE,
  2062. REQUEST_TIMEOUT,
  2063. KEEP_ALIVE_TIMEOUT,
  2064. #if defined(USE_WEBSOCKET)
  2065. WEBSOCKET_TIMEOUT,
  2066. ENABLE_WEBSOCKET_PING_PONG,
  2067. #endif
  2068. DECODE_URL,
  2069. #if defined(USE_LUA)
  2070. LUA_BACKGROUND_SCRIPT,
  2071. LUA_BACKGROUND_SCRIPT_PARAMS,
  2072. #endif
  2073. #if defined(USE_TIMERS)
  2074. CGI_TIMEOUT,
  2075. #endif
  2076. /* Once for each domain */
  2077. DOCUMENT_ROOT,
  2078. CGI_EXTENSIONS,
  2079. CGI_ENVIRONMENT,
  2080. PUT_DELETE_PASSWORDS_FILE,
  2081. CGI_INTERPRETER,
  2082. PROTECT_URI,
  2083. AUTHENTICATION_DOMAIN,
  2084. ENABLE_AUTH_DOMAIN_CHECK,
  2085. SSI_EXTENSIONS,
  2086. ENABLE_DIRECTORY_LISTING,
  2087. GLOBAL_PASSWORDS_FILE,
  2088. INDEX_FILES,
  2089. ACCESS_CONTROL_LIST,
  2090. EXTRA_MIME_TYPES,
  2091. SSL_CERTIFICATE,
  2092. SSL_CERTIFICATE_CHAIN,
  2093. URL_REWRITE_PATTERN,
  2094. HIDE_FILES,
  2095. SSL_DO_VERIFY_PEER,
  2096. SSL_CA_PATH,
  2097. SSL_CA_FILE,
  2098. SSL_VERIFY_DEPTH,
  2099. SSL_DEFAULT_VERIFY_PATHS,
  2100. SSL_CIPHER_LIST,
  2101. SSL_PROTOCOL_VERSION,
  2102. SSL_SHORT_TRUST,
  2103. #if defined(USE_LUA)
  2104. LUA_PRELOAD_FILE,
  2105. LUA_SCRIPT_EXTENSIONS,
  2106. LUA_SERVER_PAGE_EXTENSIONS,
  2107. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2108. LUA_DEBUG_PARAMS,
  2109. #endif
  2110. #endif
  2111. #if defined(USE_DUKTAPE)
  2112. DUKTAPE_SCRIPT_EXTENSIONS,
  2113. #endif
  2114. #if defined(USE_WEBSOCKET)
  2115. WEBSOCKET_ROOT,
  2116. #endif
  2117. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2118. LUA_WEBSOCKET_EXTENSIONS,
  2119. #endif
  2120. ACCESS_CONTROL_ALLOW_ORIGIN,
  2121. ACCESS_CONTROL_ALLOW_METHODS,
  2122. ACCESS_CONTROL_ALLOW_HEADERS,
  2123. ERROR_PAGES,
  2124. #if !defined(NO_CACHING)
  2125. STATIC_FILE_MAX_AGE,
  2126. STATIC_FILE_CACHE_CONTROL,
  2127. #endif
  2128. #if !defined(NO_SSL)
  2129. STRICT_HTTPS_MAX_AGE,
  2130. #endif
  2131. ADDITIONAL_HEADER,
  2132. ALLOW_INDEX_SCRIPT_SUB_RES,
  2133. #if defined(DAEMONIZE)
  2134. ENABLE_DAEMONIZE,
  2135. #endif
  2136. NUM_OPTIONS
  2137. };
  2138. /* Config option name, config types, default value.
  2139. * Must be in the same order as the enum const above.
  2140. */
  2141. static const struct mg_option config_options[] = {
  2142. /* Once for each server */
  2143. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2144. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2145. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2146. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2147. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2148. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2149. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2150. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2151. #if defined(__linux__)
  2152. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2153. #endif
  2154. #if defined(_WIN32)
  2155. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2156. #endif
  2157. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2158. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2159. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2160. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2161. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2162. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2163. #if defined(USE_WEBSOCKET)
  2164. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2165. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2166. #endif
  2167. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2168. #if defined(USE_LUA)
  2169. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2170. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2171. #endif
  2172. #if defined(USE_TIMERS)
  2173. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2174. #endif
  2175. /* Once for each domain */
  2176. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2177. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2178. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2179. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2180. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2181. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2182. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2183. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2184. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2185. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2186. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2187. {"index_files",
  2188. MG_CONFIG_TYPE_STRING_LIST,
  2189. #if defined(USE_LUA)
  2190. "index.xhtml,index.html,index.htm,"
  2191. "index.lp,index.lsp,index.lua,index.cgi,"
  2192. "index.shtml,index.php"},
  2193. #else
  2194. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2195. #endif
  2196. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2197. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2198. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2199. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2200. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2201. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2202. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2203. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2204. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2205. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2206. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2207. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2208. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2209. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2210. #if defined(USE_LUA)
  2211. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2212. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2213. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2214. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2215. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2216. #endif
  2217. #endif
  2218. #if defined(USE_DUKTAPE)
  2219. /* The support for duktape is still in alpha version state.
  2220. * The name of this config option might change. */
  2221. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2222. #endif
  2223. #if defined(USE_WEBSOCKET)
  2224. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2225. #endif
  2226. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2227. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2228. #endif
  2229. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2230. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2231. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2232. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2233. #if !defined(NO_CACHING)
  2234. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2235. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2236. #endif
  2237. #if !defined(NO_SSL)
  2238. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2239. #endif
  2240. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2241. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2242. #if defined(DAEMONIZE)
  2243. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2244. #endif
  2245. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2246. /* Check if the config_options and the corresponding enum have compatible
  2247. * sizes. */
  2248. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2249. == (NUM_OPTIONS + 1),
  2250. "config_options and enum not sync");
  2251. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2252. struct mg_handler_info {
  2253. /* Name/Pattern of the URI. */
  2254. char *uri;
  2255. size_t uri_len;
  2256. /* handler type */
  2257. int handler_type;
  2258. /* Handler for http/https or authorization requests. */
  2259. mg_request_handler handler;
  2260. unsigned int refcount;
  2261. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2262. pthread_cond_t
  2263. refcount_cond; /* Signaled when handler refcount is decremented */
  2264. /* Handler for ws/wss (websocket) requests. */
  2265. mg_websocket_connect_handler connect_handler;
  2266. mg_websocket_ready_handler ready_handler;
  2267. mg_websocket_data_handler data_handler;
  2268. mg_websocket_close_handler close_handler;
  2269. /* accepted subprotocols for ws/wss requests. */
  2270. struct mg_websocket_subprotocols *subprotocols;
  2271. /* Handler for authorization requests */
  2272. mg_authorization_handler auth_handler;
  2273. /* User supplied argument for the handler function. */
  2274. void *cbdata;
  2275. /* next handler in a linked list */
  2276. struct mg_handler_info *next;
  2277. };
  2278. enum {
  2279. CONTEXT_INVALID,
  2280. CONTEXT_SERVER,
  2281. CONTEXT_HTTP_CLIENT,
  2282. CONTEXT_WS_CLIENT
  2283. };
  2284. struct mg_domain_context {
  2285. SSL_CTX *ssl_ctx; /* SSL context */
  2286. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2287. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2288. /* Server nonce */
  2289. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2290. unsigned long nonce_count; /* Used nonces, used for authentication */
  2291. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2292. /* linked list of shared lua websockets */
  2293. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2294. #endif
  2295. /* Linked list of domains */
  2296. struct mg_domain_context *next;
  2297. };
  2298. struct mg_context {
  2299. /* Part 1 - Physical context:
  2300. * This holds threads, ports, timeouts, ...
  2301. * set for the entire server, independent from the
  2302. * addressed hostname.
  2303. */
  2304. /* Connection related */
  2305. int context_type; /* See CONTEXT_* above */
  2306. struct socket *listening_sockets;
  2307. struct mg_pollfd *listening_socket_fds;
  2308. unsigned int num_listening_sockets;
  2309. struct mg_connection *worker_connections; /* The connection struct, pre-
  2310. * allocated for each worker */
  2311. #if defined(USE_SERVER_STATS)
  2312. int active_connections;
  2313. int max_active_connections;
  2314. int64_t total_connections;
  2315. int64_t total_requests;
  2316. int64_t total_data_read;
  2317. int64_t total_data_written;
  2318. #endif
  2319. /* Thread related */
  2320. volatile int stop_flag; /* Should we stop event loop */
  2321. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2322. pthread_t masterthreadid; /* The master thread ID */
  2323. unsigned int
  2324. cfg_worker_threads; /* The number of configured worker threads. */
  2325. pthread_t *worker_threadids; /* The worker thread IDs */
  2326. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2327. /* Connection to thread dispatching */
  2328. #if defined(ALTERNATIVE_QUEUE)
  2329. struct socket *client_socks;
  2330. void **client_wait_events;
  2331. #else
  2332. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2333. worker thread */
  2334. volatile int sq_head; /* Head of the socket queue */
  2335. volatile int sq_tail; /* Tail of the socket queue */
  2336. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2337. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2338. volatile int sq_blocked; /* Status information: sq is full */
  2339. int sq_size; /* No of elements in socket queue */
  2340. #if defined(USE_SERVER_STATS)
  2341. int sq_max_fill;
  2342. #endif /* USE_SERVER_STATS */
  2343. #endif /* ALTERNATIVE_QUEUE */
  2344. /* Memory related */
  2345. unsigned int max_request_size; /* The max request size */
  2346. #if defined(USE_SERVER_STATS)
  2347. struct mg_memory_stat ctx_memory;
  2348. #endif
  2349. /* Operating system related */
  2350. char *systemName; /* What operating system is running */
  2351. time_t start_time; /* Server start time, used for authentication
  2352. * and for diagnstics. */
  2353. #if defined(USE_TIMERS)
  2354. struct ttimers *timers;
  2355. #endif
  2356. /* Lua specific: Background operations and shared websockets */
  2357. #if defined(USE_LUA)
  2358. void *lua_background_state;
  2359. #endif
  2360. /* Server nonce */
  2361. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2362. /* Server callbacks */
  2363. struct mg_callbacks callbacks; /* User-defined callback function */
  2364. void *user_data; /* User-defined data */
  2365. /* Part 2 - Logical domain:
  2366. * This holds hostname, TLS certificate, document root, ...
  2367. * set for a domain hosted at the server.
  2368. * There may be multiple domains hosted at one physical server.
  2369. * The default domain "dd" is the first element of a list of
  2370. * domains.
  2371. */
  2372. struct mg_domain_context dd; /* default domain */
  2373. };
  2374. #if defined(USE_SERVER_STATS)
  2375. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2376. static struct mg_memory_stat *
  2377. get_memory_stat(struct mg_context *ctx)
  2378. {
  2379. if (ctx) {
  2380. return &(ctx->ctx_memory);
  2381. }
  2382. return &mg_common_memory;
  2383. }
  2384. #endif
  2385. enum {
  2386. CONNECTION_TYPE_INVALID,
  2387. CONNECTION_TYPE_REQUEST,
  2388. CONNECTION_TYPE_RESPONSE
  2389. };
  2390. struct mg_connection {
  2391. int connection_type; /* see CONNECTION_TYPE_* above */
  2392. struct mg_request_info request_info;
  2393. struct mg_response_info response_info;
  2394. struct mg_context *phys_ctx;
  2395. struct mg_domain_context *dom_ctx;
  2396. #if defined(USE_SERVER_STATS)
  2397. int conn_state; /* 0 = undef, numerical value may change in different
  2398. * versions. For the current definition, see
  2399. * mg_get_connection_info_impl */
  2400. #endif
  2401. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2402. SSL *ssl; /* SSL descriptor */
  2403. struct socket client; /* Connected client */
  2404. time_t conn_birth_time; /* Time (wall clock) when connection was
  2405. * established */
  2406. #if defined(USE_SERVER_STATS)
  2407. time_t conn_close_time; /* Time (wall clock) when connection was
  2408. * closed (or 0 if still open) */
  2409. #endif
  2410. struct timespec req_time; /* Time (since system start) when the request
  2411. * was received */
  2412. int64_t num_bytes_sent; /* Total bytes sent to client */
  2413. int64_t content_len; /* How many bytes of content can be read
  2414. * !is_chunked: Content-Length header value
  2415. * or -1 (until connection closed,
  2416. * not allowed for a request)
  2417. * is_chunked: >= 0, appended gradually
  2418. */
  2419. int64_t consumed_content; /* How many bytes of content have been read */
  2420. int is_chunked; /* Transfer-Encoding is chunked:
  2421. * 0 = not chunked,
  2422. * 1 = chunked, not yet, or some data read,
  2423. * 2 = chunked, has error,
  2424. * 3 = chunked, all data read except trailer,
  2425. * 4 = chunked, all data read
  2426. */
  2427. char *buf; /* Buffer for received data */
  2428. char *path_info; /* PATH_INFO part of the URL */
  2429. int must_close; /* 1 if connection must be closed */
  2430. int accept_gzip; /* 1 if gzip encoding is accepted */
  2431. int in_error_handler; /* 1 if in handler for user defined error
  2432. * pages */
  2433. #if defined(USE_WEBSOCKET)
  2434. int in_websocket_handling; /* 1 if in read_websocket */
  2435. #endif
  2436. int handled_requests; /* Number of requests handled by this connection
  2437. */
  2438. int buf_size; /* Buffer size */
  2439. int request_len; /* Size of the request + headers in a buffer */
  2440. int data_len; /* Total size of data in a buffer */
  2441. int status_code; /* HTTP reply status code, e.g. 200 */
  2442. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2443. * throttle */
  2444. time_t last_throttle_time; /* Last time throttled data was sent */
  2445. int last_throttle_bytes; /* Bytes sent this second */
  2446. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2447. * atomic transmissions for websockets */
  2448. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2449. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2450. #endif
  2451. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2452. * for quick access */
  2453. };
  2454. /* Directory entry */
  2455. struct de {
  2456. struct mg_connection *conn;
  2457. char *file_name;
  2458. struct mg_file_stat file;
  2459. };
  2460. #if defined(USE_WEBSOCKET)
  2461. static int is_websocket_protocol(const struct mg_connection *conn);
  2462. #else
  2463. #define is_websocket_protocol(conn) (0)
  2464. #endif
  2465. #define mg_cry_internal(conn, fmt, ...) \
  2466. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2467. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2468. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2469. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2470. struct mg_context *ctx,
  2471. const char *func,
  2472. unsigned line,
  2473. const char *fmt,
  2474. ...) PRINTF_ARGS(5, 6);
  2475. #if !defined(NO_THREAD_NAME)
  2476. #if defined(_WIN32) && defined(_MSC_VER)
  2477. /* Set the thread name for debugging purposes in Visual Studio
  2478. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2479. */
  2480. #pragma pack(push, 8)
  2481. typedef struct tagTHREADNAME_INFO {
  2482. DWORD dwType; /* Must be 0x1000. */
  2483. LPCSTR szName; /* Pointer to name (in user addr space). */
  2484. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2485. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2486. } THREADNAME_INFO;
  2487. #pragma pack(pop)
  2488. #elif defined(__linux__)
  2489. #include <sys/prctl.h>
  2490. #include <sys/sendfile.h>
  2491. #if defined(ALTERNATIVE_QUEUE)
  2492. #include <sys/eventfd.h>
  2493. #endif /* ALTERNATIVE_QUEUE */
  2494. #if defined(ALTERNATIVE_QUEUE)
  2495. static void *
  2496. event_create(void)
  2497. {
  2498. int evhdl = eventfd(0, EFD_CLOEXEC);
  2499. int *ret;
  2500. if (evhdl == -1) {
  2501. /* Linux uses -1 on error, Windows NULL. */
  2502. /* However, Linux does not return 0 on success either. */
  2503. return 0;
  2504. }
  2505. ret = (int *)mg_malloc(sizeof(int));
  2506. if (ret) {
  2507. *ret = evhdl;
  2508. } else {
  2509. (void)close(evhdl);
  2510. }
  2511. return (void *)ret;
  2512. }
  2513. static int
  2514. event_wait(void *eventhdl)
  2515. {
  2516. uint64_t u;
  2517. int evhdl, s;
  2518. if (!eventhdl) {
  2519. /* error */
  2520. return 0;
  2521. }
  2522. evhdl = *(int *)eventhdl;
  2523. s = (int)read(evhdl, &u, sizeof(u));
  2524. if (s != sizeof(u)) {
  2525. /* error */
  2526. return 0;
  2527. }
  2528. (void)u; /* the value is not required */
  2529. return 1;
  2530. }
  2531. static int
  2532. event_signal(void *eventhdl)
  2533. {
  2534. uint64_t u = 1;
  2535. int evhdl, s;
  2536. if (!eventhdl) {
  2537. /* error */
  2538. return 0;
  2539. }
  2540. evhdl = *(int *)eventhdl;
  2541. s = (int)write(evhdl, &u, sizeof(u));
  2542. if (s != sizeof(u)) {
  2543. /* error */
  2544. return 0;
  2545. }
  2546. return 1;
  2547. }
  2548. static void
  2549. event_destroy(void *eventhdl)
  2550. {
  2551. int evhdl;
  2552. if (!eventhdl) {
  2553. /* error */
  2554. return;
  2555. }
  2556. evhdl = *(int *)eventhdl;
  2557. close(evhdl);
  2558. mg_free(eventhdl);
  2559. }
  2560. #endif
  2561. #endif
  2562. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2563. struct posix_event {
  2564. pthread_mutex_t mutex;
  2565. pthread_cond_t cond;
  2566. int signaled;
  2567. };
  2568. static void *
  2569. event_create(void)
  2570. {
  2571. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2572. if (ret == 0) {
  2573. /* out of memory */
  2574. return 0;
  2575. }
  2576. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2577. /* pthread mutex not available */
  2578. mg_free(ret);
  2579. return 0;
  2580. }
  2581. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2582. /* pthread cond not available */
  2583. pthread_mutex_destroy(&(ret->mutex));
  2584. mg_free(ret);
  2585. return 0;
  2586. }
  2587. ret->signaled = 0;
  2588. return (void *)ret;
  2589. }
  2590. static int
  2591. event_wait(void *eventhdl)
  2592. {
  2593. struct posix_event *ev = (struct posix_event *)eventhdl;
  2594. pthread_mutex_lock(&(ev->mutex));
  2595. while (!ev->signaled) {
  2596. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2597. }
  2598. ev->signaled = 0;
  2599. pthread_mutex_unlock(&(ev->mutex));
  2600. return 1;
  2601. }
  2602. static int
  2603. event_signal(void *eventhdl)
  2604. {
  2605. struct posix_event *ev = (struct posix_event *)eventhdl;
  2606. pthread_mutex_lock(&(ev->mutex));
  2607. pthread_cond_signal(&(ev->cond));
  2608. ev->signaled = 1;
  2609. pthread_mutex_unlock(&(ev->mutex));
  2610. return 1;
  2611. }
  2612. static void
  2613. event_destroy(void *eventhdl)
  2614. {
  2615. struct posix_event *ev = (struct posix_event *)eventhdl;
  2616. pthread_cond_destroy(&(ev->cond));
  2617. pthread_mutex_destroy(&(ev->mutex));
  2618. mg_free(ev);
  2619. }
  2620. #endif
  2621. static void
  2622. mg_set_thread_name(const char *name)
  2623. {
  2624. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2625. mg_snprintf(
  2626. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2627. #if defined(_WIN32)
  2628. #if defined(_MSC_VER)
  2629. /* Windows and Visual Studio Compiler */
  2630. __try {
  2631. THREADNAME_INFO info;
  2632. info.dwType = 0x1000;
  2633. info.szName = threadName;
  2634. info.dwThreadID = ~0U;
  2635. info.dwFlags = 0;
  2636. RaiseException(0x406D1388,
  2637. 0,
  2638. sizeof(info) / sizeof(ULONG_PTR),
  2639. (ULONG_PTR *)&info);
  2640. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2641. }
  2642. #elif defined(__MINGW32__)
  2643. /* No option known to set thread name for MinGW known */
  2644. #endif
  2645. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2646. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2647. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2648. #if defined(__MACH__)
  2649. /* OS X only current thread name can be changed */
  2650. (void)pthread_setname_np(threadName);
  2651. #else
  2652. (void)pthread_setname_np(pthread_self(), threadName);
  2653. #endif
  2654. #elif defined(__linux__)
  2655. /* On Linux we can use the prctl function.
  2656. * When building for Linux Standard Base (LSB) use
  2657. * NO_THREAD_NAME. However, thread names are a big
  2658. * help for debugging, so the stadard is to set them.
  2659. */
  2660. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2661. #endif
  2662. }
  2663. #else /* !defined(NO_THREAD_NAME) */
  2664. void
  2665. mg_set_thread_name(const char *threadName)
  2666. {
  2667. }
  2668. #endif
  2669. #if defined(MG_LEGACY_INTERFACE)
  2670. const char **
  2671. mg_get_valid_option_names(void)
  2672. {
  2673. /* This function is deprecated. Use mg_get_valid_options instead. */
  2674. static const char
  2675. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2676. int i;
  2677. for (i = 0; config_options[i].name != NULL; i++) {
  2678. data[i * 2] = config_options[i].name;
  2679. data[i * 2 + 1] = config_options[i].default_value;
  2680. }
  2681. return data;
  2682. }
  2683. #endif
  2684. const struct mg_option *
  2685. mg_get_valid_options(void)
  2686. {
  2687. return config_options;
  2688. }
  2689. /* Do not open file (used in is_file_in_memory) */
  2690. #define MG_FOPEN_MODE_NONE (0)
  2691. /* Open file for read only access */
  2692. #define MG_FOPEN_MODE_READ (1)
  2693. /* Open file for writing, create and overwrite */
  2694. #define MG_FOPEN_MODE_WRITE (2)
  2695. /* Open file for writing, create and append */
  2696. #define MG_FOPEN_MODE_APPEND (4)
  2697. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2698. * output filep and return 1, otherwise return 0 and don't modify anything.
  2699. */
  2700. static int
  2701. open_file_in_memory(const struct mg_connection *conn,
  2702. const char *path,
  2703. struct mg_file *filep,
  2704. int mode)
  2705. {
  2706. #if defined(MG_USE_OPEN_FILE)
  2707. size_t size = 0;
  2708. const char *buf = NULL;
  2709. if (!conn) {
  2710. return 0;
  2711. }
  2712. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2713. return 0;
  2714. }
  2715. if (conn->phys_ctx->callbacks.open_file) {
  2716. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2717. if (buf != NULL) {
  2718. if (filep == NULL) {
  2719. /* This is a file in memory, but we cannot store the
  2720. * properties
  2721. * now.
  2722. * Called from "is_file_in_memory" function. */
  2723. return 1;
  2724. }
  2725. /* NOTE: override filep->size only on success. Otherwise, it
  2726. * might
  2727. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2728. filep->access.membuf = buf;
  2729. filep->access.fp = NULL;
  2730. /* Size was set by the callback */
  2731. filep->stat.size = size;
  2732. /* Assume the data may change during runtime by setting
  2733. * last_modified = now */
  2734. filep->stat.last_modified = time(NULL);
  2735. filep->stat.is_directory = 0;
  2736. filep->stat.is_gzipped = 0;
  2737. }
  2738. }
  2739. return (buf != NULL);
  2740. #else
  2741. (void)conn;
  2742. (void)path;
  2743. (void)filep;
  2744. (void)mode;
  2745. return 0;
  2746. #endif
  2747. }
  2748. static int
  2749. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2750. {
  2751. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2752. }
  2753. static int
  2754. is_file_opened(const struct mg_file_access *fileacc)
  2755. {
  2756. if (!fileacc) {
  2757. return 0;
  2758. }
  2759. #if defined(MG_USE_OPEN_FILE)
  2760. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2761. #else
  2762. return (fileacc->fp != NULL);
  2763. #endif
  2764. }
  2765. #if !defined(NO_FILESYSTEMS)
  2766. static int mg_stat(const struct mg_connection *conn,
  2767. const char *path,
  2768. struct mg_file_stat *filep);
  2769. /* mg_fopen will open a file either in memory or on the disk.
  2770. * The input parameter path is a string in UTF-8 encoding.
  2771. * The input parameter mode is MG_FOPEN_MODE_*
  2772. * On success, either fp or membuf will be set in the output
  2773. * struct file. All status members will also be set.
  2774. * The function returns 1 on success, 0 on error. */
  2775. static int
  2776. mg_fopen(const struct mg_connection *conn,
  2777. const char *path,
  2778. int mode,
  2779. struct mg_file *filep)
  2780. {
  2781. int found;
  2782. if (!filep) {
  2783. return 0;
  2784. }
  2785. filep->access.fp = NULL;
  2786. #if defined(MG_USE_OPEN_FILE)
  2787. filep->access.membuf = NULL;
  2788. #endif
  2789. if (!is_file_in_memory(conn, path)) {
  2790. /* filep is initialized in mg_stat: all fields with memset to,
  2791. * some fields like size and modification date with values */
  2792. found = mg_stat(conn, path, &(filep->stat));
  2793. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2794. /* file does not exist and will not be created */
  2795. return 0;
  2796. }
  2797. #if defined(_WIN32)
  2798. {
  2799. wchar_t wbuf[W_PATH_MAX];
  2800. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2801. switch (mode) {
  2802. case MG_FOPEN_MODE_READ:
  2803. filep->access.fp = _wfopen(wbuf, L"rb");
  2804. break;
  2805. case MG_FOPEN_MODE_WRITE:
  2806. filep->access.fp = _wfopen(wbuf, L"wb");
  2807. break;
  2808. case MG_FOPEN_MODE_APPEND:
  2809. filep->access.fp = _wfopen(wbuf, L"ab");
  2810. break;
  2811. }
  2812. }
  2813. #else
  2814. /* Linux et al already use unicode. No need to convert. */
  2815. switch (mode) {
  2816. case MG_FOPEN_MODE_READ:
  2817. filep->access.fp = fopen(path, "r");
  2818. break;
  2819. case MG_FOPEN_MODE_WRITE:
  2820. filep->access.fp = fopen(path, "w");
  2821. break;
  2822. case MG_FOPEN_MODE_APPEND:
  2823. filep->access.fp = fopen(path, "a");
  2824. break;
  2825. }
  2826. #endif
  2827. if (!found) {
  2828. /* File did not exist before fopen was called.
  2829. * Maybe it has been created now. Get stat info
  2830. * like creation time now. */
  2831. found = mg_stat(conn, path, &(filep->stat));
  2832. (void)found;
  2833. }
  2834. /* file is on disk */
  2835. return (filep->access.fp != NULL);
  2836. } else {
  2837. #if defined(MG_USE_OPEN_FILE)
  2838. /* is_file_in_memory returned true */
  2839. if (open_file_in_memory(conn, path, filep, mode)) {
  2840. /* file is in memory */
  2841. return (filep->access.membuf != NULL);
  2842. }
  2843. #endif
  2844. }
  2845. /* Open failed */
  2846. return 0;
  2847. }
  2848. /* return 0 on success, just like fclose */
  2849. static int
  2850. mg_fclose(struct mg_file_access *fileacc)
  2851. {
  2852. int ret = -1;
  2853. if (fileacc != NULL) {
  2854. if (fileacc->fp != NULL) {
  2855. ret = fclose(fileacc->fp);
  2856. #if defined(MG_USE_OPEN_FILE)
  2857. } else if (fileacc->membuf != NULL) {
  2858. ret = 0;
  2859. #endif
  2860. }
  2861. /* reset all members of fileacc */
  2862. memset(fileacc, 0, sizeof(*fileacc));
  2863. }
  2864. return ret;
  2865. }
  2866. #endif /* NO_FILESYSTEMS */
  2867. static void
  2868. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2869. {
  2870. for (; *src != '\0' && n > 1; n--) {
  2871. *dst++ = *src++;
  2872. }
  2873. *dst = '\0';
  2874. }
  2875. static int
  2876. lowercase(const char *s)
  2877. {
  2878. return tolower((unsigned char)*s);
  2879. }
  2880. int
  2881. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2882. {
  2883. int diff = 0;
  2884. if (len > 0) {
  2885. do {
  2886. diff = lowercase(s1++) - lowercase(s2++);
  2887. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2888. }
  2889. return diff;
  2890. }
  2891. int
  2892. mg_strcasecmp(const char *s1, const char *s2)
  2893. {
  2894. int diff;
  2895. do {
  2896. diff = lowercase(s1++) - lowercase(s2++);
  2897. } while (diff == 0 && s1[-1] != '\0');
  2898. return diff;
  2899. }
  2900. static char *
  2901. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2902. {
  2903. char *p;
  2904. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2905. * defined */
  2906. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2907. mg_strlcpy(p, ptr, len + 1);
  2908. }
  2909. return p;
  2910. }
  2911. static char *
  2912. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2913. {
  2914. return mg_strndup_ctx(str, strlen(str), ctx);
  2915. }
  2916. static char *
  2917. mg_strdup(const char *str)
  2918. {
  2919. return mg_strndup_ctx(str, strlen(str), NULL);
  2920. }
  2921. static const char *
  2922. mg_strcasestr(const char *big_str, const char *small_str)
  2923. {
  2924. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2925. if (big_len >= small_len) {
  2926. for (i = 0; i <= (big_len - small_len); i++) {
  2927. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2928. return big_str + i;
  2929. }
  2930. }
  2931. }
  2932. return NULL;
  2933. }
  2934. /* Return null terminated string of given maximum length.
  2935. * Report errors if length is exceeded. */
  2936. static void
  2937. mg_vsnprintf(const struct mg_connection *conn,
  2938. int *truncated,
  2939. char *buf,
  2940. size_t buflen,
  2941. const char *fmt,
  2942. va_list ap)
  2943. {
  2944. int n, ok;
  2945. if (buflen == 0) {
  2946. if (truncated) {
  2947. *truncated = 1;
  2948. }
  2949. return;
  2950. }
  2951. #if defined(__clang__)
  2952. #pragma clang diagnostic push
  2953. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2954. /* Using fmt as a non-literal is intended here, since it is mostly called
  2955. * indirectly by mg_snprintf */
  2956. #endif
  2957. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2958. ok = (n >= 0) && ((size_t)n < buflen);
  2959. #if defined(__clang__)
  2960. #pragma clang diagnostic pop
  2961. #endif
  2962. if (ok) {
  2963. if (truncated) {
  2964. *truncated = 0;
  2965. }
  2966. } else {
  2967. if (truncated) {
  2968. *truncated = 1;
  2969. }
  2970. mg_cry_internal(conn,
  2971. "truncating vsnprintf buffer: [%.*s]",
  2972. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2973. buf);
  2974. n = (int)buflen - 1;
  2975. }
  2976. buf[n] = '\0';
  2977. }
  2978. static void
  2979. mg_snprintf(const struct mg_connection *conn,
  2980. int *truncated,
  2981. char *buf,
  2982. size_t buflen,
  2983. const char *fmt,
  2984. ...)
  2985. {
  2986. va_list ap;
  2987. va_start(ap, fmt);
  2988. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2989. va_end(ap);
  2990. }
  2991. static int
  2992. get_option_index(const char *name)
  2993. {
  2994. int i;
  2995. for (i = 0; config_options[i].name != NULL; i++) {
  2996. if (strcmp(config_options[i].name, name) == 0) {
  2997. return i;
  2998. }
  2999. }
  3000. return -1;
  3001. }
  3002. const char *
  3003. mg_get_option(const struct mg_context *ctx, const char *name)
  3004. {
  3005. int i;
  3006. if ((i = get_option_index(name)) == -1) {
  3007. return NULL;
  3008. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3009. return "";
  3010. } else {
  3011. return ctx->dd.config[i];
  3012. }
  3013. }
  3014. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3015. struct mg_context *
  3016. mg_get_context(const struct mg_connection *conn)
  3017. {
  3018. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3019. }
  3020. void *
  3021. mg_get_user_data(const struct mg_context *ctx)
  3022. {
  3023. return (ctx == NULL) ? NULL : ctx->user_data;
  3024. }
  3025. void *
  3026. mg_get_user_context_data(const struct mg_connection *conn)
  3027. {
  3028. return mg_get_user_data(mg_get_context(conn));
  3029. }
  3030. void *
  3031. mg_get_thread_pointer(const struct mg_connection *conn)
  3032. {
  3033. /* both methods should return the same pointer */
  3034. if (conn) {
  3035. /* quick access, in case conn is known */
  3036. return conn->tls_user_ptr;
  3037. } else {
  3038. /* otherwise get pointer from thread local storage (TLS) */
  3039. struct mg_workerTLS *tls =
  3040. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3041. return tls->user_ptr;
  3042. }
  3043. }
  3044. void
  3045. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3046. {
  3047. if (conn != NULL) {
  3048. conn->request_info.conn_data = data;
  3049. }
  3050. }
  3051. void *
  3052. mg_get_user_connection_data(const struct mg_connection *conn)
  3053. {
  3054. if (conn != NULL) {
  3055. return conn->request_info.conn_data;
  3056. }
  3057. return NULL;
  3058. }
  3059. #if defined(MG_LEGACY_INTERFACE)
  3060. /* Deprecated: Use mg_get_server_ports instead. */
  3061. size_t
  3062. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3063. {
  3064. size_t i;
  3065. if (!ctx) {
  3066. return 0;
  3067. }
  3068. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3069. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3070. ports[i] =
  3071. #if defined(USE_IPV6)
  3072. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3073. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3074. :
  3075. #endif
  3076. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3077. }
  3078. return i;
  3079. }
  3080. #endif
  3081. int
  3082. mg_get_server_ports(const struct mg_context *ctx,
  3083. int size,
  3084. struct mg_server_port *ports)
  3085. {
  3086. int i, cnt = 0;
  3087. if (size <= 0) {
  3088. return -1;
  3089. }
  3090. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3091. if (!ctx) {
  3092. return -1;
  3093. }
  3094. if (!ctx->listening_sockets) {
  3095. return -1;
  3096. }
  3097. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3098. ports[cnt].port =
  3099. #if defined(USE_IPV6)
  3100. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3101. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3102. :
  3103. #endif
  3104. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3105. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3106. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3107. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3108. /* IPv4 */
  3109. ports[cnt].protocol = 1;
  3110. cnt++;
  3111. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3112. /* IPv6 */
  3113. ports[cnt].protocol = 3;
  3114. cnt++;
  3115. }
  3116. }
  3117. return cnt;
  3118. }
  3119. static void
  3120. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3121. {
  3122. buf[0] = '\0';
  3123. if (!usa) {
  3124. return;
  3125. }
  3126. if (usa->sa.sa_family == AF_INET) {
  3127. getnameinfo(&usa->sa,
  3128. sizeof(usa->sin),
  3129. buf,
  3130. (unsigned)len,
  3131. NULL,
  3132. 0,
  3133. NI_NUMERICHOST);
  3134. }
  3135. #if defined(USE_IPV6)
  3136. else if (usa->sa.sa_family == AF_INET6) {
  3137. getnameinfo(&usa->sa,
  3138. sizeof(usa->sin6),
  3139. buf,
  3140. (unsigned)len,
  3141. NULL,
  3142. 0,
  3143. NI_NUMERICHOST);
  3144. }
  3145. #endif
  3146. }
  3147. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3148. * included in all responses other than 100, 101, 5xx. */
  3149. static void
  3150. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3151. {
  3152. #if !defined(REENTRANT_TIME)
  3153. struct tm *tm;
  3154. tm = ((t != NULL) ? gmtime(t) : NULL);
  3155. if (tm != NULL) {
  3156. #else
  3157. struct tm _tm;
  3158. struct tm *tm = &_tm;
  3159. if (t != NULL) {
  3160. gmtime_r(t, tm);
  3161. #endif
  3162. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3163. } else {
  3164. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3165. buf[buf_len - 1] = '\0';
  3166. }
  3167. }
  3168. /* difftime for struct timespec. Return value is in seconds. */
  3169. static double
  3170. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3171. {
  3172. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3173. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3174. }
  3175. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3176. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3177. const char *func,
  3178. unsigned line,
  3179. const char *fmt,
  3180. va_list ap);
  3181. #include "external_mg_cry_internal_impl.inl"
  3182. #elif !defined(NO_FILESYSTEMS)
  3183. /* Print error message to the opened error log stream. */
  3184. static void
  3185. mg_cry_internal_impl(const struct mg_connection *conn,
  3186. const char *func,
  3187. unsigned line,
  3188. const char *fmt,
  3189. va_list ap)
  3190. {
  3191. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3192. struct mg_file fi;
  3193. time_t timestamp;
  3194. /* Unused, in the RELEASE build */
  3195. (void)func;
  3196. (void)line;
  3197. #if defined(GCC_DIAGNOSTIC)
  3198. #pragma GCC diagnostic push
  3199. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3200. #endif
  3201. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3202. #if defined(GCC_DIAGNOSTIC)
  3203. #pragma GCC diagnostic pop
  3204. #endif
  3205. buf[sizeof(buf) - 1] = 0;
  3206. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3207. if (!conn) {
  3208. puts(buf);
  3209. return;
  3210. }
  3211. /* Do not lock when getting the callback value, here and below.
  3212. * I suppose this is fine, since function cannot disappear in the
  3213. * same way string option can. */
  3214. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3215. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3216. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3217. if (mg_fopen(conn,
  3218. conn->dom_ctx->config[ERROR_LOG_FILE],
  3219. MG_FOPEN_MODE_APPEND,
  3220. &fi)
  3221. == 0) {
  3222. fi.access.fp = NULL;
  3223. }
  3224. } else {
  3225. fi.access.fp = NULL;
  3226. }
  3227. if (fi.access.fp != NULL) {
  3228. flockfile(fi.access.fp);
  3229. timestamp = time(NULL);
  3230. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3231. fprintf(fi.access.fp,
  3232. "[%010lu] [error] [client %s] ",
  3233. (unsigned long)timestamp,
  3234. src_addr);
  3235. if (conn->request_info.request_method != NULL) {
  3236. fprintf(fi.access.fp,
  3237. "%s %s: ",
  3238. conn->request_info.request_method,
  3239. conn->request_info.request_uri
  3240. ? conn->request_info.request_uri
  3241. : "");
  3242. }
  3243. fprintf(fi.access.fp, "%s", buf);
  3244. fputc('\n', fi.access.fp);
  3245. fflush(fi.access.fp);
  3246. funlockfile(fi.access.fp);
  3247. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3248. * mg_cry here anyway ;-) */
  3249. }
  3250. }
  3251. }
  3252. #else
  3253. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3254. #endif /* Externally provided function */
  3255. /* Construct fake connection structure. Used for logging, if connection
  3256. * is not applicable at the moment of logging. */
  3257. static struct mg_connection *
  3258. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3259. {
  3260. static const struct mg_connection conn_zero = {0};
  3261. *fc = conn_zero;
  3262. fc->phys_ctx = ctx;
  3263. fc->dom_ctx = &(ctx->dd);
  3264. return fc;
  3265. }
  3266. static void
  3267. mg_cry_internal_wrap(const struct mg_connection *conn,
  3268. struct mg_context *ctx,
  3269. const char *func,
  3270. unsigned line,
  3271. const char *fmt,
  3272. ...)
  3273. {
  3274. va_list ap;
  3275. va_start(ap, fmt);
  3276. if (!conn && ctx) {
  3277. struct mg_connection fc;
  3278. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3279. } else {
  3280. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3281. }
  3282. va_end(ap);
  3283. }
  3284. void
  3285. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3286. {
  3287. va_list ap;
  3288. va_start(ap, fmt);
  3289. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3290. va_end(ap);
  3291. }
  3292. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3293. const char *
  3294. mg_version(void)
  3295. {
  3296. return CIVETWEB_VERSION;
  3297. }
  3298. const struct mg_request_info *
  3299. mg_get_request_info(const struct mg_connection *conn)
  3300. {
  3301. if (!conn) {
  3302. return NULL;
  3303. }
  3304. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3305. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3306. char txt[16];
  3307. struct mg_workerTLS *tls =
  3308. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3309. sprintf(txt, "%03i", conn->response_info.status_code);
  3310. if (strlen(txt) == 3) {
  3311. memcpy(tls->txtbuf, txt, 4);
  3312. } else {
  3313. strcpy(tls->txtbuf, "ERR");
  3314. }
  3315. ((struct mg_connection *)conn)->request_info.local_uri =
  3316. ((struct mg_connection *)conn)->request_info.request_uri =
  3317. tls->txtbuf; /* use thread safe buffer */
  3318. ((struct mg_connection *)conn)->request_info.num_headers =
  3319. conn->response_info.num_headers;
  3320. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3321. conn->response_info.http_headers,
  3322. sizeof(conn->response_info.http_headers));
  3323. } else
  3324. #endif
  3325. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3326. return NULL;
  3327. }
  3328. return &conn->request_info;
  3329. }
  3330. const struct mg_response_info *
  3331. mg_get_response_info(const struct mg_connection *conn)
  3332. {
  3333. if (!conn) {
  3334. return NULL;
  3335. }
  3336. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3337. return NULL;
  3338. }
  3339. return &conn->response_info;
  3340. }
  3341. static const char *
  3342. get_proto_name(const struct mg_connection *conn)
  3343. {
  3344. #if defined(__clang__)
  3345. #pragma clang diagnostic push
  3346. #pragma clang diagnostic ignored "-Wunreachable-code"
  3347. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3348. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3349. * unreachable, but splitting into four different #ifdef clauses here is more
  3350. * complicated.
  3351. */
  3352. #endif
  3353. const struct mg_request_info *ri = &conn->request_info;
  3354. const char *proto =
  3355. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3356. : (ri->is_ssl ? "https" : "http"));
  3357. return proto;
  3358. #if defined(__clang__)
  3359. #pragma clang diagnostic pop
  3360. #endif
  3361. }
  3362. int
  3363. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3364. {
  3365. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3366. return -1;
  3367. } else {
  3368. int truncated = 0;
  3369. const struct mg_request_info *ri = &conn->request_info;
  3370. const char *proto = get_proto_name(conn);
  3371. if (ri->local_uri == NULL) {
  3372. return -1;
  3373. }
  3374. if ((ri->request_uri != NULL)
  3375. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3376. /* The request uri is different from the local uri.
  3377. * This is usually if an absolute URI, including server
  3378. * name has been provided. */
  3379. mg_snprintf(conn,
  3380. &truncated,
  3381. buf,
  3382. buflen,
  3383. "%s://%s",
  3384. proto,
  3385. ri->request_uri);
  3386. if (truncated) {
  3387. return -1;
  3388. }
  3389. return 0;
  3390. } else {
  3391. /* The common case is a relative URI, so we have to
  3392. * construct an absolute URI from server name and port */
  3393. #if defined(USE_IPV6)
  3394. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3395. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3396. : htons(conn->client.lsa.sin.sin_port);
  3397. #else
  3398. int port = htons(conn->client.lsa.sin.sin_port);
  3399. #endif
  3400. int def_port = ri->is_ssl ? 443 : 80;
  3401. int auth_domain_check_enabled =
  3402. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3403. && (!mg_strcasecmp(
  3404. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3405. const char *server_domain =
  3406. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3407. char portstr[16];
  3408. char server_ip[48];
  3409. if (port != def_port) {
  3410. sprintf(portstr, ":%u", (unsigned)port);
  3411. } else {
  3412. portstr[0] = 0;
  3413. }
  3414. if (!auth_domain_check_enabled || !server_domain) {
  3415. sockaddr_to_string(server_ip,
  3416. sizeof(server_ip),
  3417. &conn->client.lsa);
  3418. server_domain = server_ip;
  3419. }
  3420. mg_snprintf(conn,
  3421. &truncated,
  3422. buf,
  3423. buflen,
  3424. "%s://%s%s%s",
  3425. proto,
  3426. server_domain,
  3427. portstr,
  3428. ri->local_uri);
  3429. if (truncated) {
  3430. return -1;
  3431. }
  3432. return 0;
  3433. }
  3434. }
  3435. }
  3436. /* Skip the characters until one of the delimiters characters found.
  3437. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3438. * Advance pointer to buffer to the next word. Return found 0-terminated
  3439. * word.
  3440. * Delimiters can be quoted with quotechar. */
  3441. static char *
  3442. skip_quoted(char **buf,
  3443. const char *delimiters,
  3444. const char *whitespace,
  3445. char quotechar)
  3446. {
  3447. char *p, *begin_word, *end_word, *end_whitespace;
  3448. begin_word = *buf;
  3449. end_word = begin_word + strcspn(begin_word, delimiters);
  3450. /* Check for quotechar */
  3451. if (end_word > begin_word) {
  3452. p = end_word - 1;
  3453. while (*p == quotechar) {
  3454. /* While the delimiter is quoted, look for the next delimiter.
  3455. */
  3456. /* This happens, e.g., in calls from parse_auth_header,
  3457. * if the user name contains a " character. */
  3458. /* If there is anything beyond end_word, copy it. */
  3459. if (*end_word != '\0') {
  3460. size_t end_off = strcspn(end_word + 1, delimiters);
  3461. memmove(p, end_word, end_off + 1);
  3462. p += end_off; /* p must correspond to end_word - 1 */
  3463. end_word += end_off + 1;
  3464. } else {
  3465. *p = '\0';
  3466. break;
  3467. }
  3468. }
  3469. for (p++; p < end_word; p++) {
  3470. *p = '\0';
  3471. }
  3472. }
  3473. if (*end_word == '\0') {
  3474. *buf = end_word;
  3475. } else {
  3476. #if defined(GCC_DIAGNOSTIC)
  3477. /* Disable spurious conversion warning for GCC */
  3478. #pragma GCC diagnostic push
  3479. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3480. #endif /* defined(GCC_DIAGNOSTIC) */
  3481. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3482. #if defined(GCC_DIAGNOSTIC)
  3483. #pragma GCC diagnostic pop
  3484. #endif /* defined(GCC_DIAGNOSTIC) */
  3485. for (p = end_word; p < end_whitespace; p++) {
  3486. *p = '\0';
  3487. }
  3488. *buf = end_whitespace;
  3489. }
  3490. return begin_word;
  3491. }
  3492. /* Return HTTP header value, or NULL if not found. */
  3493. static const char *
  3494. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3495. {
  3496. int i;
  3497. for (i = 0; i < num_hdr; i++) {
  3498. if (!mg_strcasecmp(name, hdr[i].name)) {
  3499. return hdr[i].value;
  3500. }
  3501. }
  3502. return NULL;
  3503. }
  3504. #if defined(USE_WEBSOCKET)
  3505. /* Retrieve requested HTTP header multiple values, and return the number of
  3506. * found occurrences */
  3507. static int
  3508. get_req_headers(const struct mg_request_info *ri,
  3509. const char *name,
  3510. const char **output,
  3511. int output_max_size)
  3512. {
  3513. int i;
  3514. int cnt = 0;
  3515. if (ri) {
  3516. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3517. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3518. output[cnt++] = ri->http_headers[i].value;
  3519. }
  3520. }
  3521. }
  3522. return cnt;
  3523. }
  3524. #endif
  3525. const char *
  3526. mg_get_header(const struct mg_connection *conn, const char *name)
  3527. {
  3528. if (!conn) {
  3529. return NULL;
  3530. }
  3531. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3532. return get_header(conn->request_info.http_headers,
  3533. conn->request_info.num_headers,
  3534. name);
  3535. }
  3536. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3537. return get_header(conn->response_info.http_headers,
  3538. conn->response_info.num_headers,
  3539. name);
  3540. }
  3541. return NULL;
  3542. }
  3543. static const char *
  3544. get_http_version(const struct mg_connection *conn)
  3545. {
  3546. if (!conn) {
  3547. return NULL;
  3548. }
  3549. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3550. return conn->request_info.http_version;
  3551. }
  3552. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3553. return conn->response_info.http_version;
  3554. }
  3555. return NULL;
  3556. }
  3557. /* A helper function for traversing a comma separated list of values.
  3558. * It returns a list pointer shifted to the next value, or NULL if the end
  3559. * of the list found.
  3560. * Value is stored in val vector. If value has form "x=y", then eq_val
  3561. * vector is initialized to point to the "y" part, and val vector length
  3562. * is adjusted to point only to "x". */
  3563. static const char *
  3564. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3565. {
  3566. int end;
  3567. reparse:
  3568. if (val == NULL || list == NULL || *list == '\0') {
  3569. /* End of the list */
  3570. return NULL;
  3571. }
  3572. /* Skip over leading LWS */
  3573. while (*list == ' ' || *list == '\t')
  3574. list++;
  3575. val->ptr = list;
  3576. if ((list = strchr(val->ptr, ',')) != NULL) {
  3577. /* Comma found. Store length and shift the list ptr */
  3578. val->len = ((size_t)(list - val->ptr));
  3579. list++;
  3580. } else {
  3581. /* This value is the last one */
  3582. list = val->ptr + strlen(val->ptr);
  3583. val->len = ((size_t)(list - val->ptr));
  3584. }
  3585. /* Adjust length for trailing LWS */
  3586. end = (int)val->len - 1;
  3587. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3588. end--;
  3589. val->len = (size_t)(end) + (size_t)(1);
  3590. if (val->len == 0) {
  3591. /* Ignore any empty entries. */
  3592. goto reparse;
  3593. }
  3594. if (eq_val != NULL) {
  3595. /* Value has form "x=y", adjust pointers and lengths
  3596. * so that val points to "x", and eq_val points to "y". */
  3597. eq_val->len = 0;
  3598. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3599. if (eq_val->ptr != NULL) {
  3600. eq_val->ptr++; /* Skip over '=' character */
  3601. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3602. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3603. }
  3604. }
  3605. return list;
  3606. }
  3607. /* A helper function for checking if a comma separated list of values
  3608. * contains
  3609. * the given option (case insensitvely).
  3610. * 'header' can be NULL, in which case false is returned. */
  3611. static int
  3612. header_has_option(const char *header, const char *option)
  3613. {
  3614. struct vec opt_vec;
  3615. struct vec eq_vec;
  3616. DEBUG_ASSERT(option != NULL);
  3617. DEBUG_ASSERT(option[0] != '\0');
  3618. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3619. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3620. return 1;
  3621. }
  3622. return 0;
  3623. }
  3624. /* Perform case-insensitive match of string against pattern */
  3625. static ptrdiff_t
  3626. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3627. {
  3628. const char *or_str;
  3629. ptrdiff_t i, j, len, res;
  3630. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3631. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3632. return (res > 0) ? res
  3633. : match_prefix(or_str + 1,
  3634. (size_t)((pattern + pattern_len)
  3635. - (or_str + 1)),
  3636. str);
  3637. }
  3638. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3639. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3640. continue;
  3641. } else if (pattern[i] == '$') {
  3642. return (str[j] == '\0') ? j : -1;
  3643. } else if (pattern[i] == '*') {
  3644. i++;
  3645. if (pattern[i] == '*') {
  3646. i++;
  3647. len = strlen(str + j);
  3648. } else {
  3649. len = strcspn(str + j, "/");
  3650. }
  3651. if (i == (ptrdiff_t)pattern_len) {
  3652. return j + len;
  3653. }
  3654. do {
  3655. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3656. } while (res == -1 && len-- > 0);
  3657. return (res == -1) ? -1 : j + res + len;
  3658. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3659. return -1;
  3660. }
  3661. }
  3662. return (ptrdiff_t)j;
  3663. }
  3664. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3665. * This function must tolerate situations when connection info is not
  3666. * set up, for example if request parsing failed. */
  3667. static int
  3668. should_keep_alive(const struct mg_connection *conn)
  3669. {
  3670. const char *http_version;
  3671. const char *header;
  3672. /* First satisfy needs of the server */
  3673. if ((conn == NULL) || conn->must_close) {
  3674. /* Close, if civetweb framework needs to close */
  3675. return 0;
  3676. }
  3677. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3678. /* Close, if keep alive is not enabled */
  3679. return 0;
  3680. }
  3681. /* Check explicit wish of the client */
  3682. header = mg_get_header(conn, "Connection");
  3683. if (header) {
  3684. /* If there is a connection header from the client, obey */
  3685. if (header_has_option(header, "keep-alive")) {
  3686. return 1;
  3687. }
  3688. return 0;
  3689. }
  3690. /* Use default of the standard */
  3691. http_version = get_http_version(conn);
  3692. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3693. /* HTTP 1.1 default is keep alive */
  3694. return 1;
  3695. }
  3696. /* HTTP 1.0 (and earlier) default is to close the connection */
  3697. return 0;
  3698. }
  3699. static int
  3700. should_decode_url(const struct mg_connection *conn)
  3701. {
  3702. if (!conn || !conn->dom_ctx) {
  3703. return 0;
  3704. }
  3705. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3706. }
  3707. static const char *
  3708. suggest_connection_header(const struct mg_connection *conn)
  3709. {
  3710. return should_keep_alive(conn) ? "keep-alive" : "close";
  3711. }
  3712. static int
  3713. send_no_cache_header(struct mg_connection *conn)
  3714. {
  3715. /* Send all current and obsolete cache opt-out directives. */
  3716. return mg_printf(conn,
  3717. "Cache-Control: no-cache, no-store, "
  3718. "must-revalidate, private, max-age=0\r\n"
  3719. "Pragma: no-cache\r\n"
  3720. "Expires: 0\r\n");
  3721. }
  3722. static int
  3723. send_static_cache_header(struct mg_connection *conn)
  3724. {
  3725. #if !defined(NO_CACHING)
  3726. int max_age;
  3727. const char *cache_control =
  3728. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3729. if (cache_control != NULL) {
  3730. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3731. }
  3732. /* Read the server config to check how long a file may be cached.
  3733. * The configuration is in seconds. */
  3734. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3735. if (max_age <= 0) {
  3736. /* 0 means "do not cache". All values <0 are reserved
  3737. * and may be used differently in the future. */
  3738. /* If a file should not be cached, do not only send
  3739. * max-age=0, but also pragmas and Expires headers. */
  3740. return send_no_cache_header(conn);
  3741. }
  3742. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3743. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3744. /* See also https://www.mnot.net/cache_docs/ */
  3745. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3746. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3747. * leap
  3748. * year to 31622400 seconds. For the moment, we just send whatever has
  3749. * been configured, still the behavior for >1 year should be considered
  3750. * as undefined. */
  3751. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3752. #else /* NO_CACHING */
  3753. return send_no_cache_header(conn);
  3754. #endif /* !NO_CACHING */
  3755. }
  3756. static int
  3757. send_additional_header(struct mg_connection *conn)
  3758. {
  3759. int i = 0;
  3760. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3761. #if !defined(NO_SSL)
  3762. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3763. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3764. if (max_age >= 0) {
  3765. i += mg_printf(conn,
  3766. "Strict-Transport-Security: max-age=%u\r\n",
  3767. (unsigned)max_age);
  3768. }
  3769. }
  3770. #endif
  3771. if (header && header[0]) {
  3772. i += mg_printf(conn, "%s\r\n", header);
  3773. }
  3774. return i;
  3775. }
  3776. #if !defined(NO_FILESYSTEMS)
  3777. static void handle_file_based_request(struct mg_connection *conn,
  3778. const char *path,
  3779. struct mg_file *filep);
  3780. #endif /* NO_FILESYSTEMS */
  3781. const char *
  3782. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3783. {
  3784. /* See IANA HTTP status code assignment:
  3785. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3786. */
  3787. switch (response_code) {
  3788. /* RFC2616 Section 10.1 - Informational 1xx */
  3789. case 100:
  3790. return "Continue"; /* RFC2616 Section 10.1.1 */
  3791. case 101:
  3792. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3793. case 102:
  3794. return "Processing"; /* RFC2518 Section 10.1 */
  3795. /* RFC2616 Section 10.2 - Successful 2xx */
  3796. case 200:
  3797. return "OK"; /* RFC2616 Section 10.2.1 */
  3798. case 201:
  3799. return "Created"; /* RFC2616 Section 10.2.2 */
  3800. case 202:
  3801. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3802. case 203:
  3803. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3804. case 204:
  3805. return "No Content"; /* RFC2616 Section 10.2.5 */
  3806. case 205:
  3807. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3808. case 206:
  3809. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3810. case 207:
  3811. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3812. */
  3813. case 208:
  3814. return "Already Reported"; /* RFC5842 Section 7.1 */
  3815. case 226:
  3816. return "IM used"; /* RFC3229 Section 10.4.1 */
  3817. /* RFC2616 Section 10.3 - Redirection 3xx */
  3818. case 300:
  3819. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3820. case 301:
  3821. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3822. case 302:
  3823. return "Found"; /* RFC2616 Section 10.3.3 */
  3824. case 303:
  3825. return "See Other"; /* RFC2616 Section 10.3.4 */
  3826. case 304:
  3827. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3828. case 305:
  3829. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3830. case 307:
  3831. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3832. case 308:
  3833. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3834. /* RFC2616 Section 10.4 - Client Error 4xx */
  3835. case 400:
  3836. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3837. case 401:
  3838. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3839. case 402:
  3840. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3841. case 403:
  3842. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3843. case 404:
  3844. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3845. case 405:
  3846. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3847. case 406:
  3848. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3849. case 407:
  3850. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3851. case 408:
  3852. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3853. case 409:
  3854. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3855. case 410:
  3856. return "Gone"; /* RFC2616 Section 10.4.11 */
  3857. case 411:
  3858. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3859. case 412:
  3860. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3861. case 413:
  3862. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3863. case 414:
  3864. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3865. case 415:
  3866. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3867. case 416:
  3868. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3869. */
  3870. case 417:
  3871. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3872. case 421:
  3873. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3874. case 422:
  3875. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3876. * Section 11.2 */
  3877. case 423:
  3878. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3879. case 424:
  3880. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3881. * Section 11.4 */
  3882. case 426:
  3883. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3884. case 428:
  3885. return "Precondition Required"; /* RFC 6585, Section 3 */
  3886. case 429:
  3887. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3888. case 431:
  3889. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3890. case 451:
  3891. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3892. * Section 3 */
  3893. /* RFC2616 Section 10.5 - Server Error 5xx */
  3894. case 500:
  3895. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3896. case 501:
  3897. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3898. case 502:
  3899. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3900. case 503:
  3901. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3902. case 504:
  3903. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3904. case 505:
  3905. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3906. case 506:
  3907. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3908. case 507:
  3909. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3910. * Section 11.5 */
  3911. case 508:
  3912. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3913. case 510:
  3914. return "Not Extended"; /* RFC 2774, Section 7 */
  3915. case 511:
  3916. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3917. /* Other status codes, not shown in the IANA HTTP status code
  3918. * assignment.
  3919. * E.g., "de facto" standards due to common use, ... */
  3920. case 418:
  3921. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3922. case 419:
  3923. return "Authentication Timeout"; /* common use */
  3924. case 420:
  3925. return "Enhance Your Calm"; /* common use */
  3926. case 440:
  3927. return "Login Timeout"; /* common use */
  3928. case 509:
  3929. return "Bandwidth Limit Exceeded"; /* common use */
  3930. default:
  3931. /* This error code is unknown. This should not happen. */
  3932. if (conn) {
  3933. mg_cry_internal(conn,
  3934. "Unknown HTTP response code: %u",
  3935. response_code);
  3936. }
  3937. /* Return at least a category according to RFC 2616 Section 10. */
  3938. if (response_code >= 100 && response_code < 200) {
  3939. /* Unknown informational status code */
  3940. return "Information";
  3941. }
  3942. if (response_code >= 200 && response_code < 300) {
  3943. /* Unknown success code */
  3944. return "Success";
  3945. }
  3946. if (response_code >= 300 && response_code < 400) {
  3947. /* Unknown redirection code */
  3948. return "Redirection";
  3949. }
  3950. if (response_code >= 400 && response_code < 500) {
  3951. /* Unknown request error code */
  3952. return "Client Error";
  3953. }
  3954. if (response_code >= 500 && response_code < 600) {
  3955. /* Unknown server error code */
  3956. return "Server Error";
  3957. }
  3958. /* Response code not even within reasonable range */
  3959. return "";
  3960. }
  3961. }
  3962. static int
  3963. mg_send_http_error_impl(struct mg_connection *conn,
  3964. int status,
  3965. const char *fmt,
  3966. va_list args)
  3967. {
  3968. char errmsg_buf[MG_BUF_LEN];
  3969. va_list ap;
  3970. int has_body;
  3971. char date[64];
  3972. time_t curtime = time(NULL);
  3973. #if !defined(NO_FILESYSTEMS)
  3974. char path_buf[PATH_MAX];
  3975. int len, i, page_handler_found, scope, truncated;
  3976. const char *error_handler = NULL;
  3977. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3978. const char *error_page_file_ext, *tstr;
  3979. #endif /* NO_FILESYSTEMS */
  3980. int handled_by_callback = 0;
  3981. const char *status_text = mg_get_response_code_text(conn, status);
  3982. if ((conn == NULL) || (fmt == NULL)) {
  3983. return -2;
  3984. }
  3985. /* Set status (for log) */
  3986. conn->status_code = status;
  3987. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3988. has_body = ((status > 199) && (status != 204) && (status != 304));
  3989. /* Prepare message in buf, if required */
  3990. if (has_body
  3991. || (!conn->in_error_handler
  3992. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3993. /* Store error message in errmsg_buf */
  3994. va_copy(ap, args);
  3995. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3996. va_end(ap);
  3997. /* In a debug build, print all html errors */
  3998. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3999. }
  4000. /* If there is a http_error callback, call it.
  4001. * But don't do it recursively, if callback calls mg_send_http_error again.
  4002. */
  4003. if (!conn->in_error_handler
  4004. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4005. /* Mark in_error_handler to avoid recursion and call user callback. */
  4006. conn->in_error_handler = 1;
  4007. handled_by_callback =
  4008. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4009. == 0);
  4010. conn->in_error_handler = 0;
  4011. }
  4012. if (!handled_by_callback) {
  4013. /* Check for recursion */
  4014. if (conn->in_error_handler) {
  4015. DEBUG_TRACE(
  4016. "Recursion when handling error %u - fall back to default",
  4017. status);
  4018. #if !defined(NO_FILESYSTEMS)
  4019. } else {
  4020. /* Send user defined error pages, if defined */
  4021. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4022. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4023. page_handler_found = 0;
  4024. if (error_handler != NULL) {
  4025. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4026. switch (scope) {
  4027. case 1: /* Handler for specific error, e.g. 404 error */
  4028. mg_snprintf(conn,
  4029. &truncated,
  4030. path_buf,
  4031. sizeof(path_buf) - 32,
  4032. "%serror%03u.",
  4033. error_handler,
  4034. status);
  4035. break;
  4036. case 2: /* Handler for error group, e.g., 5xx error
  4037. * handler
  4038. * for all server errors (500-599) */
  4039. mg_snprintf(conn,
  4040. &truncated,
  4041. path_buf,
  4042. sizeof(path_buf) - 32,
  4043. "%serror%01uxx.",
  4044. error_handler,
  4045. status / 100);
  4046. break;
  4047. default: /* Handler for all errors */
  4048. mg_snprintf(conn,
  4049. &truncated,
  4050. path_buf,
  4051. sizeof(path_buf) - 32,
  4052. "%serror.",
  4053. error_handler);
  4054. break;
  4055. }
  4056. /* String truncation in buf may only occur if
  4057. * error_handler is too long. This string is
  4058. * from the config, not from a client. */
  4059. (void)truncated;
  4060. len = (int)strlen(path_buf);
  4061. tstr = strchr(error_page_file_ext, '.');
  4062. while (tstr) {
  4063. for (i = 1;
  4064. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4065. i++) {
  4066. /* buffer overrun is not possible here, since
  4067. * (i < 32) && (len < sizeof(path_buf) - 32)
  4068. * ==> (i + len) < sizeof(path_buf) */
  4069. path_buf[len + i - 1] = tstr[i];
  4070. }
  4071. /* buffer overrun is not possible here, since
  4072. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4073. * ==> (i + len) <= sizeof(path_buf) */
  4074. path_buf[len + i - 1] = 0;
  4075. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4076. DEBUG_TRACE("Check error page %s - found",
  4077. path_buf);
  4078. page_handler_found = 1;
  4079. break;
  4080. }
  4081. DEBUG_TRACE("Check error page %s - not found",
  4082. path_buf);
  4083. tstr = strchr(tstr + i, '.');
  4084. }
  4085. }
  4086. }
  4087. if (page_handler_found) {
  4088. conn->in_error_handler = 1;
  4089. handle_file_based_request(conn, path_buf, &error_page_file);
  4090. conn->in_error_handler = 0;
  4091. return 0;
  4092. }
  4093. #endif /* NO_FILESYSTEMS */
  4094. }
  4095. /* No custom error page. Send default error page. */
  4096. gmt_time_string(date, sizeof(date), &curtime);
  4097. conn->must_close = 1;
  4098. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4099. send_no_cache_header(conn);
  4100. send_additional_header(conn);
  4101. if (has_body) {
  4102. mg_printf(conn,
  4103. "%s",
  4104. "Content-Type: text/plain; charset=utf-8\r\n");
  4105. }
  4106. mg_printf(conn,
  4107. "Date: %s\r\n"
  4108. "Connection: close\r\n\r\n",
  4109. date);
  4110. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4111. if (has_body) {
  4112. /* For other errors, send a generic error message. */
  4113. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4114. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4115. } else {
  4116. /* No body allowed. Close the connection. */
  4117. DEBUG_TRACE("Error %i", status);
  4118. }
  4119. }
  4120. return 0;
  4121. }
  4122. int
  4123. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4124. {
  4125. va_list ap;
  4126. int ret;
  4127. va_start(ap, fmt);
  4128. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4129. va_end(ap);
  4130. return ret;
  4131. }
  4132. int
  4133. mg_send_http_ok(struct mg_connection *conn,
  4134. const char *mime_type,
  4135. long long content_length)
  4136. {
  4137. char date[64];
  4138. time_t curtime = time(NULL);
  4139. if ((mime_type == NULL) || (*mime_type == 0)) {
  4140. /* No content type defined: default to text/html */
  4141. mime_type = "text/html";
  4142. }
  4143. gmt_time_string(date, sizeof(date), &curtime);
  4144. mg_printf(conn,
  4145. "HTTP/1.1 200 OK\r\n"
  4146. "Content-Type: %s\r\n"
  4147. "Date: %s\r\n"
  4148. "Connection: %s\r\n",
  4149. mime_type,
  4150. date,
  4151. suggest_connection_header(conn));
  4152. send_no_cache_header(conn);
  4153. send_additional_header(conn);
  4154. if (content_length < 0) {
  4155. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4156. } else {
  4157. mg_printf(conn,
  4158. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4159. (uint64_t)content_length);
  4160. }
  4161. return 0;
  4162. }
  4163. int
  4164. mg_send_http_redirect(struct mg_connection *conn,
  4165. const char *target_url,
  4166. int redirect_code)
  4167. {
  4168. /* Send a 30x redirect response.
  4169. *
  4170. * Redirect types (status codes):
  4171. *
  4172. * Status | Perm/Temp | Method | Version
  4173. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4174. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4175. * 303 | temporary | always use GET | HTTP/1.1
  4176. * 307 | temporary | always keep method | HTTP/1.1
  4177. * 308 | permanent | always keep method | HTTP/1.1
  4178. */
  4179. const char *redirect_text;
  4180. int ret;
  4181. size_t content_len = 0;
  4182. char reply[MG_BUF_LEN];
  4183. /* In case redirect_code=0, use 307. */
  4184. if (redirect_code == 0) {
  4185. redirect_code = 307;
  4186. }
  4187. /* In case redirect_code is none of the above, return error. */
  4188. if ((redirect_code != 301) && (redirect_code != 302)
  4189. && (redirect_code != 303) && (redirect_code != 307)
  4190. && (redirect_code != 308)) {
  4191. /* Parameter error */
  4192. return -2;
  4193. }
  4194. /* Get proper text for response code */
  4195. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4196. /* If target_url is not defined, redirect to "/". */
  4197. if ((target_url == NULL) || (*target_url == 0)) {
  4198. target_url = "/";
  4199. }
  4200. #if defined(MG_SEND_REDIRECT_BODY)
  4201. /* TODO: condition name? */
  4202. /* Prepare a response body with a hyperlink.
  4203. *
  4204. * According to RFC2616 (and RFC1945 before):
  4205. * Unless the request method was HEAD, the entity of the
  4206. * response SHOULD contain a short hypertext note with a hyperlink to
  4207. * the new URI(s).
  4208. *
  4209. * However, this response body is not useful in M2M communication.
  4210. * Probably the original reason in the RFC was, clients not supporting
  4211. * a 30x HTTP redirect could still show the HTML page and let the user
  4212. * press the link. Since current browsers support 30x HTTP, the additional
  4213. * HTML body does not seem to make sense anymore.
  4214. *
  4215. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4216. * but it only notes:
  4217. * The server's response payload usually contains a short
  4218. * hypertext note with a hyperlink to the new URI(s).
  4219. *
  4220. * Deactivated by default. If you need the 30x body, set the define.
  4221. */
  4222. mg_snprintf(
  4223. conn,
  4224. NULL /* ignore truncation */,
  4225. reply,
  4226. sizeof(reply),
  4227. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4228. redirect_text,
  4229. target_url,
  4230. target_url);
  4231. content_len = strlen(reply);
  4232. #else
  4233. reply[0] = 0;
  4234. #endif
  4235. /* Do not send any additional header. For all other options,
  4236. * including caching, there are suitable defaults. */
  4237. ret = mg_printf(conn,
  4238. "HTTP/1.1 %i %s\r\n"
  4239. "Location: %s\r\n"
  4240. "Content-Length: %u\r\n"
  4241. "Connection: %s\r\n\r\n",
  4242. redirect_code,
  4243. redirect_text,
  4244. target_url,
  4245. (unsigned int)content_len,
  4246. suggest_connection_header(conn));
  4247. /* Send response body */
  4248. if (ret > 0) {
  4249. /* ... unless it is a HEAD request */
  4250. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4251. ret = mg_write(conn, reply, content_len);
  4252. }
  4253. }
  4254. return (ret > 0) ? ret : -1;
  4255. }
  4256. #if defined(_WIN32)
  4257. /* Create substitutes for POSIX functions in Win32. */
  4258. #if defined(GCC_DIAGNOSTIC)
  4259. /* Show no warning in case system functions are not used. */
  4260. #pragma GCC diagnostic push
  4261. #pragma GCC diagnostic ignored "-Wunused-function"
  4262. #endif
  4263. static int
  4264. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4265. {
  4266. (void)unused;
  4267. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4268. InitializeCriticalSection(&mutex->sec);
  4269. return 0;
  4270. }
  4271. static int
  4272. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4273. {
  4274. DeleteCriticalSection(&mutex->sec);
  4275. return 0;
  4276. }
  4277. static int
  4278. pthread_mutex_lock(pthread_mutex_t *mutex)
  4279. {
  4280. EnterCriticalSection(&mutex->sec);
  4281. return 0;
  4282. }
  4283. static int
  4284. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4285. {
  4286. LeaveCriticalSection(&mutex->sec);
  4287. return 0;
  4288. }
  4289. FUNCTION_MAY_BE_UNUSED
  4290. static int
  4291. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4292. {
  4293. (void)unused;
  4294. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4295. cv->waiting_thread = NULL;
  4296. return 0;
  4297. }
  4298. FUNCTION_MAY_BE_UNUSED
  4299. static int
  4300. pthread_cond_timedwait(pthread_cond_t *cv,
  4301. pthread_mutex_t *mutex,
  4302. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4303. {
  4304. struct mg_workerTLS **ptls,
  4305. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4306. int ok;
  4307. int64_t nsnow, nswaitabs, nswaitrel;
  4308. DWORD mswaitrel;
  4309. pthread_mutex_lock(&cv->threadIdSec);
  4310. /* Add this thread to cv's waiting list */
  4311. ptls = &cv->waiting_thread;
  4312. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4313. ;
  4314. tls->next_waiting_thread = NULL;
  4315. *ptls = tls;
  4316. pthread_mutex_unlock(&cv->threadIdSec);
  4317. if (abstime) {
  4318. nsnow = mg_get_current_time_ns();
  4319. nswaitabs =
  4320. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4321. nswaitrel = nswaitabs - nsnow;
  4322. if (nswaitrel < 0) {
  4323. nswaitrel = 0;
  4324. }
  4325. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4326. } else {
  4327. mswaitrel = (DWORD)INFINITE;
  4328. }
  4329. pthread_mutex_unlock(mutex);
  4330. ok = (WAIT_OBJECT_0
  4331. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4332. if (!ok) {
  4333. ok = 1;
  4334. pthread_mutex_lock(&cv->threadIdSec);
  4335. ptls = &cv->waiting_thread;
  4336. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4337. if (*ptls == tls) {
  4338. *ptls = tls->next_waiting_thread;
  4339. ok = 0;
  4340. break;
  4341. }
  4342. }
  4343. pthread_mutex_unlock(&cv->threadIdSec);
  4344. if (ok) {
  4345. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4346. (DWORD)INFINITE);
  4347. }
  4348. }
  4349. /* This thread has been removed from cv's waiting list */
  4350. pthread_mutex_lock(mutex);
  4351. return ok ? 0 : -1;
  4352. }
  4353. FUNCTION_MAY_BE_UNUSED
  4354. static int
  4355. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4356. {
  4357. return pthread_cond_timedwait(cv, mutex, NULL);
  4358. }
  4359. FUNCTION_MAY_BE_UNUSED
  4360. static int
  4361. pthread_cond_signal(pthread_cond_t *cv)
  4362. {
  4363. HANDLE wkup = NULL;
  4364. BOOL ok = FALSE;
  4365. pthread_mutex_lock(&cv->threadIdSec);
  4366. if (cv->waiting_thread) {
  4367. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4368. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4369. ok = SetEvent(wkup);
  4370. DEBUG_ASSERT(ok);
  4371. }
  4372. pthread_mutex_unlock(&cv->threadIdSec);
  4373. return ok ? 0 : 1;
  4374. }
  4375. FUNCTION_MAY_BE_UNUSED
  4376. static int
  4377. pthread_cond_broadcast(pthread_cond_t *cv)
  4378. {
  4379. pthread_mutex_lock(&cv->threadIdSec);
  4380. while (cv->waiting_thread) {
  4381. pthread_cond_signal(cv);
  4382. }
  4383. pthread_mutex_unlock(&cv->threadIdSec);
  4384. return 0;
  4385. }
  4386. FUNCTION_MAY_BE_UNUSED
  4387. static int
  4388. pthread_cond_destroy(pthread_cond_t *cv)
  4389. {
  4390. pthread_mutex_lock(&cv->threadIdSec);
  4391. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4392. pthread_mutex_unlock(&cv->threadIdSec);
  4393. pthread_mutex_destroy(&cv->threadIdSec);
  4394. return 0;
  4395. }
  4396. #if defined(ALTERNATIVE_QUEUE)
  4397. FUNCTION_MAY_BE_UNUSED
  4398. static void *
  4399. event_create(void)
  4400. {
  4401. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4402. }
  4403. FUNCTION_MAY_BE_UNUSED
  4404. static int
  4405. event_wait(void *eventhdl)
  4406. {
  4407. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4408. return (res == WAIT_OBJECT_0);
  4409. }
  4410. FUNCTION_MAY_BE_UNUSED
  4411. static int
  4412. event_signal(void *eventhdl)
  4413. {
  4414. return (int)SetEvent((HANDLE)eventhdl);
  4415. }
  4416. FUNCTION_MAY_BE_UNUSED
  4417. static void
  4418. event_destroy(void *eventhdl)
  4419. {
  4420. CloseHandle((HANDLE)eventhdl);
  4421. }
  4422. #endif
  4423. #if defined(GCC_DIAGNOSTIC)
  4424. /* Enable unused function warning again */
  4425. #pragma GCC diagnostic pop
  4426. #endif
  4427. /* For Windows, change all slashes to backslashes in path names. */
  4428. static void
  4429. change_slashes_to_backslashes(char *path)
  4430. {
  4431. int i;
  4432. for (i = 0; path[i] != '\0'; i++) {
  4433. if (path[i] == '/') {
  4434. path[i] = '\\';
  4435. }
  4436. /* remove double backslash (check i > 0 to preserve UNC paths,
  4437. * like \\server\file.txt) */
  4438. if ((path[i] == '\\') && (i > 0)) {
  4439. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4440. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4441. }
  4442. }
  4443. }
  4444. }
  4445. static int
  4446. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4447. {
  4448. int diff;
  4449. do {
  4450. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4451. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4452. s1++;
  4453. s2++;
  4454. } while ((diff == 0) && (s1[-1] != L'\0'));
  4455. return diff;
  4456. }
  4457. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4458. * wbuf and wbuf_len is a target buffer and its length. */
  4459. static void
  4460. path_to_unicode(const struct mg_connection *conn,
  4461. const char *path,
  4462. wchar_t *wbuf,
  4463. size_t wbuf_len)
  4464. {
  4465. char buf[PATH_MAX], buf2[PATH_MAX];
  4466. wchar_t wbuf2[W_PATH_MAX + 1];
  4467. DWORD long_len, err;
  4468. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4469. mg_strlcpy(buf, path, sizeof(buf));
  4470. change_slashes_to_backslashes(buf);
  4471. /* Convert to Unicode and back. If doubly-converted string does not
  4472. * match the original, something is fishy, reject. */
  4473. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4474. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4475. WideCharToMultiByte(
  4476. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4477. if (strcmp(buf, buf2) != 0) {
  4478. wbuf[0] = L'\0';
  4479. }
  4480. /* Windows file systems are not case sensitive, but you can still use
  4481. * uppercase and lowercase letters (on all modern file systems).
  4482. * The server can check if the URI uses the same upper/lowercase
  4483. * letters an the file system, effectively making Windows servers
  4484. * case sensitive (like Linux servers are). It is still not possible
  4485. * to use two files with the same name in different cases on Windows
  4486. * (like /a and /A) - this would be possible in Linux.
  4487. * As a default, Windows is not case sensitive, but the case sensitive
  4488. * file name check can be activated by an additional configuration. */
  4489. if (conn) {
  4490. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4491. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4492. "yes")) {
  4493. /* Use case sensitive compare function */
  4494. fcompare = wcscmp;
  4495. }
  4496. }
  4497. (void)conn; /* conn is currently unused */
  4498. #if !defined(_WIN32_WCE)
  4499. /* Only accept a full file path, not a Windows short (8.3) path. */
  4500. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4501. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4502. if (long_len == 0) {
  4503. err = GetLastError();
  4504. if (err == ERROR_FILE_NOT_FOUND) {
  4505. /* File does not exist. This is not always a problem here. */
  4506. return;
  4507. }
  4508. }
  4509. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4510. /* Short name is used. */
  4511. wbuf[0] = L'\0';
  4512. }
  4513. #else
  4514. (void)long_len;
  4515. (void)wbuf2;
  4516. (void)err;
  4517. if (strchr(path, '~')) {
  4518. wbuf[0] = L'\0';
  4519. }
  4520. #endif
  4521. }
  4522. #if !defined(NO_FILESYSTEMS)
  4523. static int
  4524. mg_stat(const struct mg_connection *conn,
  4525. const char *path,
  4526. struct mg_file_stat *filep)
  4527. {
  4528. wchar_t wbuf[W_PATH_MAX];
  4529. WIN32_FILE_ATTRIBUTE_DATA info;
  4530. time_t creation_time;
  4531. size_t len;
  4532. if (!filep) {
  4533. return 0;
  4534. }
  4535. memset(filep, 0, sizeof(*filep));
  4536. if (conn && is_file_in_memory(conn, path)) {
  4537. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4538. * memset */
  4539. /* Quick fix (for 1.9.x): */
  4540. /* mg_stat must fill all fields, also for files in memory */
  4541. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4542. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4543. filep->size = tmp_file.stat.size;
  4544. filep->location = 2;
  4545. /* TODO: for 1.10: restructure how files in memory are handled */
  4546. /* The "file in memory" feature is a candidate for deletion.
  4547. * Please join the discussion at
  4548. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4549. */
  4550. filep->last_modified = time(NULL); /* TODO */
  4551. /* last_modified = now ... assumes the file may change during
  4552. * runtime,
  4553. * so every mg_fopen call may return different data */
  4554. /* last_modified = conn->phys_ctx.start_time;
  4555. * May be used it the data does not change during runtime. This
  4556. * allows
  4557. * browser caching. Since we do not know, we have to assume the file
  4558. * in memory may change. */
  4559. return 1;
  4560. }
  4561. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4562. /* Windows happily opens files with some garbage at the end of file name.
  4563. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4564. * "a.cgi", despite one would expect an error back. */
  4565. len = strlen(path);
  4566. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4567. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4568. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4569. filep->last_modified =
  4570. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4571. info.ftLastWriteTime.dwHighDateTime);
  4572. /* On Windows, the file creation time can be higher than the
  4573. * modification time, e.g. when a file is copied.
  4574. * Since the Last-Modified timestamp is used for caching
  4575. * it should be based on the most recent timestamp. */
  4576. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4577. info.ftCreationTime.dwHighDateTime);
  4578. if (creation_time > filep->last_modified) {
  4579. filep->last_modified = creation_time;
  4580. }
  4581. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4582. return 1;
  4583. }
  4584. return 0;
  4585. }
  4586. #endif
  4587. static int
  4588. mg_remove(const struct mg_connection *conn, const char *path)
  4589. {
  4590. wchar_t wbuf[W_PATH_MAX];
  4591. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4592. return DeleteFileW(wbuf) ? 0 : -1;
  4593. }
  4594. static int
  4595. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4596. {
  4597. wchar_t wbuf[W_PATH_MAX];
  4598. (void)mode;
  4599. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4600. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4601. }
  4602. /* Create substitutes for POSIX functions in Win32. */
  4603. #if defined(GCC_DIAGNOSTIC)
  4604. /* Show no warning in case system functions are not used. */
  4605. #pragma GCC diagnostic push
  4606. #pragma GCC diagnostic ignored "-Wunused-function"
  4607. #endif
  4608. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4609. FUNCTION_MAY_BE_UNUSED
  4610. static DIR *
  4611. mg_opendir(const struct mg_connection *conn, const char *name)
  4612. {
  4613. DIR *dir = NULL;
  4614. wchar_t wpath[W_PATH_MAX];
  4615. DWORD attrs;
  4616. if (name == NULL) {
  4617. SetLastError(ERROR_BAD_ARGUMENTS);
  4618. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4619. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4620. } else {
  4621. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4622. attrs = GetFileAttributesW(wpath);
  4623. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4624. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4625. (void)wcscat(wpath, L"\\*");
  4626. dir->handle = FindFirstFileW(wpath, &dir->info);
  4627. dir->result.d_name[0] = '\0';
  4628. } else {
  4629. mg_free(dir);
  4630. dir = NULL;
  4631. }
  4632. }
  4633. return dir;
  4634. }
  4635. FUNCTION_MAY_BE_UNUSED
  4636. static int
  4637. mg_closedir(DIR *dir)
  4638. {
  4639. int result = 0;
  4640. if (dir != NULL) {
  4641. if (dir->handle != INVALID_HANDLE_VALUE)
  4642. result = FindClose(dir->handle) ? 0 : -1;
  4643. mg_free(dir);
  4644. } else {
  4645. result = -1;
  4646. SetLastError(ERROR_BAD_ARGUMENTS);
  4647. }
  4648. return result;
  4649. }
  4650. FUNCTION_MAY_BE_UNUSED
  4651. static struct dirent *
  4652. mg_readdir(DIR *dir)
  4653. {
  4654. struct dirent *result = 0;
  4655. if (dir) {
  4656. if (dir->handle != INVALID_HANDLE_VALUE) {
  4657. result = &dir->result;
  4658. (void)WideCharToMultiByte(CP_UTF8,
  4659. 0,
  4660. dir->info.cFileName,
  4661. -1,
  4662. result->d_name,
  4663. sizeof(result->d_name),
  4664. NULL,
  4665. NULL);
  4666. if (!FindNextFileW(dir->handle, &dir->info)) {
  4667. (void)FindClose(dir->handle);
  4668. dir->handle = INVALID_HANDLE_VALUE;
  4669. }
  4670. } else {
  4671. SetLastError(ERROR_FILE_NOT_FOUND);
  4672. }
  4673. } else {
  4674. SetLastError(ERROR_BAD_ARGUMENTS);
  4675. }
  4676. return result;
  4677. }
  4678. #if !defined(HAVE_POLL)
  4679. #undef POLLIN
  4680. #undef POLLPRI
  4681. #undef POLLOUT
  4682. #define POLLIN (1) /* Data ready - read will not block. */
  4683. #define POLLPRI (2) /* Priority data ready. */
  4684. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4685. FUNCTION_MAY_BE_UNUSED
  4686. static int
  4687. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4688. {
  4689. struct timeval tv;
  4690. fd_set rset;
  4691. fd_set wset;
  4692. unsigned int i;
  4693. int result;
  4694. SOCKET maxfd = 0;
  4695. memset(&tv, 0, sizeof(tv));
  4696. tv.tv_sec = milliseconds / 1000;
  4697. tv.tv_usec = (milliseconds % 1000) * 1000;
  4698. FD_ZERO(&rset);
  4699. FD_ZERO(&wset);
  4700. for (i = 0; i < n; i++) {
  4701. if (pfd[i].events & POLLIN) {
  4702. FD_SET(pfd[i].fd, &rset);
  4703. }
  4704. if (pfd[i].events & POLLOUT) {
  4705. FD_SET(pfd[i].fd, &wset);
  4706. }
  4707. pfd[i].revents = 0;
  4708. if (pfd[i].fd > maxfd) {
  4709. maxfd = pfd[i].fd;
  4710. }
  4711. }
  4712. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4713. for (i = 0; i < n; i++) {
  4714. if (FD_ISSET(pfd[i].fd, &rset)) {
  4715. pfd[i].revents |= POLLIN;
  4716. }
  4717. if (FD_ISSET(pfd[i].fd, &wset)) {
  4718. pfd[i].revents |= POLLOUT;
  4719. }
  4720. }
  4721. }
  4722. /* We should subtract the time used in select from remaining
  4723. * "milliseconds", in particular if called from mg_poll with a
  4724. * timeout quantum.
  4725. * Unfortunately, the remaining time is not stored in "tv" in all
  4726. * implementations, so the result in "tv" must be considered undefined.
  4727. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4728. return result;
  4729. }
  4730. #endif /* HAVE_POLL */
  4731. #if defined(GCC_DIAGNOSTIC)
  4732. /* Enable unused function warning again */
  4733. #pragma GCC diagnostic pop
  4734. #endif
  4735. static void
  4736. set_close_on_exec(SOCKET sock,
  4737. const struct mg_connection *conn /* may be null */,
  4738. struct mg_context *ctx /* may be null */)
  4739. {
  4740. (void)conn; /* Unused. */
  4741. (void)ctx;
  4742. #if defined(_WIN32_WCE)
  4743. (void)sock;
  4744. #else
  4745. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4746. #endif
  4747. }
  4748. int
  4749. mg_start_thread(mg_thread_func_t f, void *p)
  4750. {
  4751. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4752. /* Compile-time option to control stack size, e.g.
  4753. * -DUSE_STACK_SIZE=16384
  4754. */
  4755. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4756. == ((uintptr_t)(-1L)))
  4757. ? -1
  4758. : 0);
  4759. #else
  4760. return (
  4761. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4762. ? -1
  4763. : 0);
  4764. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4765. }
  4766. /* Start a thread storing the thread context. */
  4767. static int
  4768. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4769. void *p,
  4770. pthread_t *threadidptr)
  4771. {
  4772. uintptr_t uip;
  4773. HANDLE threadhandle;
  4774. int result = -1;
  4775. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4776. threadhandle = (HANDLE)uip;
  4777. if ((uip != 0) && (threadidptr != NULL)) {
  4778. *threadidptr = threadhandle;
  4779. result = 0;
  4780. }
  4781. return result;
  4782. }
  4783. /* Wait for a thread to finish. */
  4784. static int
  4785. mg_join_thread(pthread_t threadid)
  4786. {
  4787. int result;
  4788. DWORD dwevent;
  4789. result = -1;
  4790. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4791. if (dwevent == WAIT_FAILED) {
  4792. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4793. } else {
  4794. if (dwevent == WAIT_OBJECT_0) {
  4795. CloseHandle(threadid);
  4796. result = 0;
  4797. }
  4798. }
  4799. return result;
  4800. }
  4801. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4802. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4803. /* Create substitutes for POSIX functions in Win32. */
  4804. #if defined(GCC_DIAGNOSTIC)
  4805. /* Show no warning in case system functions are not used. */
  4806. #pragma GCC diagnostic push
  4807. #pragma GCC diagnostic ignored "-Wunused-function"
  4808. #endif
  4809. FUNCTION_MAY_BE_UNUSED
  4810. static HANDLE
  4811. dlopen(const char *dll_name, int flags)
  4812. {
  4813. wchar_t wbuf[W_PATH_MAX];
  4814. (void)flags;
  4815. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4816. return LoadLibraryW(wbuf);
  4817. }
  4818. FUNCTION_MAY_BE_UNUSED
  4819. static int
  4820. dlclose(void *handle)
  4821. {
  4822. int result;
  4823. if (FreeLibrary((HMODULE)handle) != 0) {
  4824. result = 0;
  4825. } else {
  4826. result = -1;
  4827. }
  4828. return result;
  4829. }
  4830. #if defined(GCC_DIAGNOSTIC)
  4831. /* Enable unused function warning again */
  4832. #pragma GCC diagnostic pop
  4833. #endif
  4834. #endif
  4835. #if !defined(NO_CGI)
  4836. #define SIGKILL (0)
  4837. static int
  4838. kill(pid_t pid, int sig_num)
  4839. {
  4840. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4841. (void)CloseHandle((HANDLE)pid);
  4842. return 0;
  4843. }
  4844. #if !defined(WNOHANG)
  4845. #define WNOHANG (1)
  4846. #endif
  4847. static pid_t
  4848. waitpid(pid_t pid, int *status, int flags)
  4849. {
  4850. DWORD timeout = INFINITE;
  4851. DWORD waitres;
  4852. (void)status; /* Currently not used by any client here */
  4853. if ((flags | WNOHANG) == WNOHANG) {
  4854. timeout = 0;
  4855. }
  4856. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4857. if (waitres == WAIT_OBJECT_0) {
  4858. return pid;
  4859. }
  4860. if (waitres == WAIT_TIMEOUT) {
  4861. return 0;
  4862. }
  4863. return (pid_t)-1;
  4864. }
  4865. static void
  4866. trim_trailing_whitespaces(char *s)
  4867. {
  4868. char *e = s + strlen(s);
  4869. while ((e > s) && isspace((unsigned char)e[-1])) {
  4870. *(--e) = '\0';
  4871. }
  4872. }
  4873. static pid_t
  4874. spawn_process(struct mg_connection *conn,
  4875. const char *prog,
  4876. char *envblk,
  4877. char *envp[],
  4878. int fdin[2],
  4879. int fdout[2],
  4880. int fderr[2],
  4881. const char *dir)
  4882. {
  4883. HANDLE me;
  4884. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4885. cmdline[PATH_MAX], buf[PATH_MAX];
  4886. int truncated;
  4887. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4888. STARTUPINFOA si;
  4889. PROCESS_INFORMATION pi = {0};
  4890. (void)envp;
  4891. memset(&si, 0, sizeof(si));
  4892. si.cb = sizeof(si);
  4893. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4894. si.wShowWindow = SW_HIDE;
  4895. me = GetCurrentProcess();
  4896. DuplicateHandle(me,
  4897. (HANDLE)_get_osfhandle(fdin[0]),
  4898. me,
  4899. &si.hStdInput,
  4900. 0,
  4901. TRUE,
  4902. DUPLICATE_SAME_ACCESS);
  4903. DuplicateHandle(me,
  4904. (HANDLE)_get_osfhandle(fdout[1]),
  4905. me,
  4906. &si.hStdOutput,
  4907. 0,
  4908. TRUE,
  4909. DUPLICATE_SAME_ACCESS);
  4910. DuplicateHandle(me,
  4911. (HANDLE)_get_osfhandle(fderr[1]),
  4912. me,
  4913. &si.hStdError,
  4914. 0,
  4915. TRUE,
  4916. DUPLICATE_SAME_ACCESS);
  4917. /* Mark handles that should not be inherited. See
  4918. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4919. */
  4920. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4921. HANDLE_FLAG_INHERIT,
  4922. 0);
  4923. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4924. HANDLE_FLAG_INHERIT,
  4925. 0);
  4926. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4927. HANDLE_FLAG_INHERIT,
  4928. 0);
  4929. /* If CGI file is a script, try to read the interpreter line */
  4930. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4931. if (interp == NULL) {
  4932. buf[0] = buf[1] = '\0';
  4933. /* Read the first line of the script into the buffer */
  4934. mg_snprintf(
  4935. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4936. if (truncated) {
  4937. pi.hProcess = (pid_t)-1;
  4938. goto spawn_cleanup;
  4939. }
  4940. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4941. #if defined(MG_USE_OPEN_FILE)
  4942. p = (char *)file.access.membuf;
  4943. #else
  4944. p = (char *)NULL;
  4945. #endif
  4946. mg_fgets(buf, sizeof(buf), &file, &p);
  4947. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4948. buf[sizeof(buf) - 1] = '\0';
  4949. }
  4950. if ((buf[0] == '#') && (buf[1] == '!')) {
  4951. trim_trailing_whitespaces(buf + 2);
  4952. } else {
  4953. buf[2] = '\0';
  4954. }
  4955. interp = buf + 2;
  4956. }
  4957. if (interp[0] != '\0') {
  4958. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4959. interp = full_interp;
  4960. }
  4961. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4962. if (interp[0] != '\0') {
  4963. mg_snprintf(conn,
  4964. &truncated,
  4965. cmdline,
  4966. sizeof(cmdline),
  4967. "\"%s\" \"%s\\%s\"",
  4968. interp,
  4969. full_dir,
  4970. prog);
  4971. } else {
  4972. mg_snprintf(conn,
  4973. &truncated,
  4974. cmdline,
  4975. sizeof(cmdline),
  4976. "\"%s\\%s\"",
  4977. full_dir,
  4978. prog);
  4979. }
  4980. if (truncated) {
  4981. pi.hProcess = (pid_t)-1;
  4982. goto spawn_cleanup;
  4983. }
  4984. DEBUG_TRACE("Running [%s]", cmdline);
  4985. if (CreateProcessA(NULL,
  4986. cmdline,
  4987. NULL,
  4988. NULL,
  4989. TRUE,
  4990. CREATE_NEW_PROCESS_GROUP,
  4991. envblk,
  4992. NULL,
  4993. &si,
  4994. &pi)
  4995. == 0) {
  4996. mg_cry_internal(
  4997. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4998. pi.hProcess = (pid_t)-1;
  4999. /* goto spawn_cleanup; */
  5000. }
  5001. spawn_cleanup:
  5002. (void)CloseHandle(si.hStdOutput);
  5003. (void)CloseHandle(si.hStdError);
  5004. (void)CloseHandle(si.hStdInput);
  5005. if (pi.hThread != NULL) {
  5006. (void)CloseHandle(pi.hThread);
  5007. }
  5008. return (pid_t)pi.hProcess;
  5009. }
  5010. #endif /* !NO_CGI */
  5011. static int
  5012. set_blocking_mode(SOCKET sock)
  5013. {
  5014. unsigned long non_blocking = 0;
  5015. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5016. }
  5017. static int
  5018. set_non_blocking_mode(SOCKET sock)
  5019. {
  5020. unsigned long non_blocking = 1;
  5021. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5022. }
  5023. #else
  5024. #if !defined(NO_FILESYSTEMS)
  5025. static int
  5026. mg_stat(const struct mg_connection *conn,
  5027. const char *path,
  5028. struct mg_file_stat *filep)
  5029. {
  5030. struct stat st;
  5031. if (!filep) {
  5032. return 0;
  5033. }
  5034. memset(filep, 0, sizeof(*filep));
  5035. if (conn && is_file_in_memory(conn, path)) {
  5036. /* Quick fix (for 1.9.x): */
  5037. /* mg_stat must fill all fields, also for files in memory */
  5038. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5039. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5040. filep->size = tmp_file.stat.size;
  5041. filep->last_modified = time(NULL);
  5042. filep->location = 2;
  5043. /* TODO: remove legacy "files in memory" feature */
  5044. return 1;
  5045. }
  5046. if (0 == stat(path, &st)) {
  5047. filep->size = (uint64_t)(st.st_size);
  5048. filep->last_modified = st.st_mtime;
  5049. filep->is_directory = S_ISDIR(st.st_mode);
  5050. return 1;
  5051. }
  5052. return 0;
  5053. }
  5054. #endif /* NO_FILESYSTEMS */
  5055. static void
  5056. set_close_on_exec(int fd,
  5057. const struct mg_connection *conn /* may be null */,
  5058. struct mg_context *ctx /* may be null */)
  5059. {
  5060. #if defined(__ZEPHYR__)
  5061. (void)fd;
  5062. (void)conn;
  5063. (void)ctx;
  5064. #else
  5065. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5066. if (conn || ctx) {
  5067. struct mg_connection fc;
  5068. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5069. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5070. __func__,
  5071. strerror(ERRNO));
  5072. }
  5073. }
  5074. #endif
  5075. }
  5076. int
  5077. mg_start_thread(mg_thread_func_t func, void *param)
  5078. {
  5079. pthread_t thread_id;
  5080. pthread_attr_t attr;
  5081. int result;
  5082. (void)pthread_attr_init(&attr);
  5083. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5084. #if defined(__ZEPHYR__)
  5085. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5086. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5087. /* Compile-time option to control stack size,
  5088. * e.g. -DUSE_STACK_SIZE=16384 */
  5089. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5090. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5091. result = pthread_create(&thread_id, &attr, func, param);
  5092. pthread_attr_destroy(&attr);
  5093. return result;
  5094. }
  5095. /* Start a thread storing the thread context. */
  5096. static int
  5097. mg_start_thread_with_id(mg_thread_func_t func,
  5098. void *param,
  5099. pthread_t *threadidptr)
  5100. {
  5101. pthread_t thread_id;
  5102. pthread_attr_t attr;
  5103. int result;
  5104. (void)pthread_attr_init(&attr);
  5105. #if defined(__ZEPHYR__)
  5106. pthread_attr_setstack(&attr,
  5107. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5108. ZEPHYR_STACK_SIZE);
  5109. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5110. /* Compile-time option to control stack size,
  5111. * e.g. -DUSE_STACK_SIZE=16384 */
  5112. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5113. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5114. result = pthread_create(&thread_id, &attr, func, param);
  5115. pthread_attr_destroy(&attr);
  5116. if ((result == 0) && (threadidptr != NULL)) {
  5117. *threadidptr = thread_id;
  5118. }
  5119. return result;
  5120. }
  5121. /* Wait for a thread to finish. */
  5122. static int
  5123. mg_join_thread(pthread_t threadid)
  5124. {
  5125. int result;
  5126. result = pthread_join(threadid, NULL);
  5127. return result;
  5128. }
  5129. #if !defined(NO_CGI)
  5130. static pid_t
  5131. spawn_process(struct mg_connection *conn,
  5132. const char *prog,
  5133. char *envblk,
  5134. char *envp[],
  5135. int fdin[2],
  5136. int fdout[2],
  5137. int fderr[2],
  5138. const char *dir)
  5139. {
  5140. pid_t pid;
  5141. const char *interp;
  5142. (void)envblk;
  5143. if ((pid = fork()) == -1) {
  5144. /* Parent */
  5145. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5146. } else if (pid != 0) {
  5147. /* Make sure children close parent-side descriptors.
  5148. * The caller will close the child-side immediately. */
  5149. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5150. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5151. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5152. } else {
  5153. /* Child */
  5154. if (chdir(dir) != 0) {
  5155. mg_cry_internal(
  5156. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5157. } else if (dup2(fdin[0], 0) == -1) {
  5158. mg_cry_internal(conn,
  5159. "%s: dup2(%d, 0): %s",
  5160. __func__,
  5161. fdin[0],
  5162. strerror(ERRNO));
  5163. } else if (dup2(fdout[1], 1) == -1) {
  5164. mg_cry_internal(conn,
  5165. "%s: dup2(%d, 1): %s",
  5166. __func__,
  5167. fdout[1],
  5168. strerror(ERRNO));
  5169. } else if (dup2(fderr[1], 2) == -1) {
  5170. mg_cry_internal(conn,
  5171. "%s: dup2(%d, 2): %s",
  5172. __func__,
  5173. fderr[1],
  5174. strerror(ERRNO));
  5175. } else {
  5176. struct sigaction sa;
  5177. /* Keep stderr and stdout in two different pipes.
  5178. * Stdout will be sent back to the client,
  5179. * stderr should go into a server error log. */
  5180. (void)close(fdin[0]);
  5181. (void)close(fdout[1]);
  5182. (void)close(fderr[1]);
  5183. /* Close write end fdin and read end fdout and fderr */
  5184. (void)close(fdin[1]);
  5185. (void)close(fdout[0]);
  5186. (void)close(fderr[0]);
  5187. /* After exec, all signal handlers are restored to their default
  5188. * values, with one exception of SIGCHLD. According to
  5189. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5190. * will leave unchanged after exec if it was set to be ignored.
  5191. * Restore it to default action. */
  5192. memset(&sa, 0, sizeof(sa));
  5193. sa.sa_handler = SIG_DFL;
  5194. sigaction(SIGCHLD, &sa, NULL);
  5195. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5196. if (interp == NULL) {
  5197. (void)execle(prog, prog, NULL, envp);
  5198. mg_cry_internal(conn,
  5199. "%s: execle(%s): %s",
  5200. __func__,
  5201. prog,
  5202. strerror(ERRNO));
  5203. } else {
  5204. (void)execle(interp, interp, prog, NULL, envp);
  5205. mg_cry_internal(conn,
  5206. "%s: execle(%s %s): %s",
  5207. __func__,
  5208. interp,
  5209. prog,
  5210. strerror(ERRNO));
  5211. }
  5212. }
  5213. exit(EXIT_FAILURE);
  5214. }
  5215. return pid;
  5216. }
  5217. #endif /* !NO_CGI */
  5218. static int
  5219. set_non_blocking_mode(SOCKET sock)
  5220. {
  5221. int flags = fcntl(sock, F_GETFL, 0);
  5222. if (flags < 0) {
  5223. return -1;
  5224. }
  5225. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5226. return -1;
  5227. }
  5228. return 0;
  5229. }
  5230. static int
  5231. set_blocking_mode(SOCKET sock)
  5232. {
  5233. int flags = fcntl(sock, F_GETFL, 0);
  5234. if (flags < 0) {
  5235. return -1;
  5236. }
  5237. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5238. return -1;
  5239. }
  5240. return 0;
  5241. }
  5242. #endif /* _WIN32 / else */
  5243. /* End of initial operating system specific define block. */
  5244. /* Get a random number (independent of C rand function) */
  5245. static uint64_t
  5246. get_random(void)
  5247. {
  5248. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5249. static uint64_t lcg = 0; /* Linear congruential generator */
  5250. uint64_t now = mg_get_current_time_ns();
  5251. if (lfsr == 0) {
  5252. /* lfsr will be only 0 if has not been initialized,
  5253. * so this code is called only once. */
  5254. lfsr = mg_get_current_time_ns();
  5255. lcg = mg_get_current_time_ns();
  5256. } else {
  5257. /* Get the next step of both random number generators. */
  5258. lfsr = (lfsr >> 1)
  5259. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5260. << 63);
  5261. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5262. }
  5263. /* Combining two pseudo-random number generators and a high resolution
  5264. * part
  5265. * of the current server time will make it hard (impossible?) to guess
  5266. * the
  5267. * next number. */
  5268. return (lfsr ^ lcg ^ now);
  5269. }
  5270. static int
  5271. mg_poll(struct mg_pollfd *pfd,
  5272. unsigned int n,
  5273. int milliseconds,
  5274. volatile int *stop_server)
  5275. {
  5276. /* Call poll, but only for a maximum time of a few seconds.
  5277. * This will allow to stop the server after some seconds, instead
  5278. * of having to wait for a long socket timeout. */
  5279. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5280. do {
  5281. int result;
  5282. if (*stop_server) {
  5283. /* Shut down signal */
  5284. return -2;
  5285. }
  5286. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5287. ms_now = milliseconds;
  5288. }
  5289. result = poll(pfd, n, ms_now);
  5290. if (result != 0) {
  5291. /* Poll returned either success (1) or error (-1).
  5292. * Forward both to the caller. */
  5293. return result;
  5294. }
  5295. /* Poll returned timeout (0). */
  5296. if (milliseconds > 0) {
  5297. milliseconds -= ms_now;
  5298. }
  5299. } while (milliseconds != 0);
  5300. /* timeout: return 0 */
  5301. return 0;
  5302. }
  5303. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5304. * descriptor.
  5305. * Return value:
  5306. * >=0 .. number of bytes successfully written
  5307. * -1 .. timeout
  5308. * -2 .. error
  5309. */
  5310. static int
  5311. push_inner(struct mg_context *ctx,
  5312. FILE *fp,
  5313. SOCKET sock,
  5314. SSL *ssl,
  5315. const char *buf,
  5316. int len,
  5317. double timeout)
  5318. {
  5319. uint64_t start = 0, now = 0, timeout_ns = 0;
  5320. int n, err;
  5321. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5322. #if defined(_WIN32)
  5323. typedef int len_t;
  5324. #else
  5325. typedef size_t len_t;
  5326. #endif
  5327. if (timeout > 0) {
  5328. now = mg_get_current_time_ns();
  5329. start = now;
  5330. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5331. }
  5332. if (ctx == NULL) {
  5333. return -2;
  5334. }
  5335. #if defined(NO_SSL)
  5336. if (ssl) {
  5337. return -2;
  5338. }
  5339. #endif
  5340. /* Try to read until it succeeds, fails, times out, or the server
  5341. * shuts down. */
  5342. for (;;) {
  5343. #if !defined(NO_SSL)
  5344. if (ssl != NULL) {
  5345. n = SSL_write(ssl, buf, len);
  5346. if (n <= 0) {
  5347. err = SSL_get_error(ssl, n);
  5348. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5349. err = ERRNO;
  5350. } else if ((err == SSL_ERROR_WANT_READ)
  5351. || (err == SSL_ERROR_WANT_WRITE)) {
  5352. n = 0;
  5353. } else {
  5354. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5355. return -2;
  5356. }
  5357. } else {
  5358. err = 0;
  5359. }
  5360. } else
  5361. #endif
  5362. if (fp != NULL) {
  5363. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5364. if (ferror(fp)) {
  5365. n = -1;
  5366. err = ERRNO;
  5367. } else {
  5368. err = 0;
  5369. }
  5370. } else {
  5371. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5372. err = (n < 0) ? ERRNO : 0;
  5373. #if defined(_WIN32)
  5374. if (err == WSAEWOULDBLOCK) {
  5375. err = 0;
  5376. n = 0;
  5377. }
  5378. #else
  5379. if (err == EWOULDBLOCK) {
  5380. err = 0;
  5381. n = 0;
  5382. }
  5383. #endif
  5384. if (n < 0) {
  5385. /* shutdown of the socket at client side */
  5386. return -2;
  5387. }
  5388. }
  5389. if (ctx->stop_flag) {
  5390. return -2;
  5391. }
  5392. if ((n > 0) || ((n == 0) && (len == 0))) {
  5393. /* some data has been read, or no data was requested */
  5394. return n;
  5395. }
  5396. if (n < 0) {
  5397. /* socket error - check errno */
  5398. DEBUG_TRACE("send() failed, error %d", err);
  5399. /* TODO (mid): error handling depending on the error code.
  5400. * These codes are different between Windows and Linux.
  5401. * Currently there is no problem with failing send calls,
  5402. * if there is a reproducible situation, it should be
  5403. * investigated in detail.
  5404. */
  5405. return -2;
  5406. }
  5407. /* Only in case n=0 (timeout), repeat calling the write function */
  5408. /* If send failed, wait before retry */
  5409. if (fp != NULL) {
  5410. /* For files, just wait a fixed time.
  5411. * Maybe it helps, maybe not. */
  5412. mg_sleep(5);
  5413. } else {
  5414. /* For sockets, wait for the socket using poll */
  5415. struct mg_pollfd pfd[1];
  5416. int pollres;
  5417. pfd[0].fd = sock;
  5418. pfd[0].events = POLLOUT;
  5419. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5420. if (ctx->stop_flag) {
  5421. return -2;
  5422. }
  5423. if (pollres > 0) {
  5424. continue;
  5425. }
  5426. }
  5427. if (timeout > 0) {
  5428. now = mg_get_current_time_ns();
  5429. if ((now - start) > timeout_ns) {
  5430. /* Timeout */
  5431. break;
  5432. }
  5433. }
  5434. }
  5435. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5436. used */
  5437. return -1;
  5438. }
  5439. static int
  5440. push_all(struct mg_context *ctx,
  5441. FILE *fp,
  5442. SOCKET sock,
  5443. SSL *ssl,
  5444. const char *buf,
  5445. int len)
  5446. {
  5447. double timeout = -1.0;
  5448. int n, nwritten = 0;
  5449. if (ctx == NULL) {
  5450. return -1;
  5451. }
  5452. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5453. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5454. }
  5455. while ((len > 0) && (ctx->stop_flag == 0)) {
  5456. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5457. if (n < 0) {
  5458. if (nwritten == 0) {
  5459. nwritten = -1; /* Propagate the error */
  5460. }
  5461. break;
  5462. } else if (n == 0) {
  5463. break; /* No more data to write */
  5464. } else {
  5465. nwritten += n;
  5466. len -= n;
  5467. }
  5468. }
  5469. return nwritten;
  5470. }
  5471. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5472. * Return value:
  5473. * >=0 .. number of bytes successfully read
  5474. * -1 .. timeout
  5475. * -2 .. error
  5476. */
  5477. static int
  5478. pull_inner(FILE *fp,
  5479. struct mg_connection *conn,
  5480. char *buf,
  5481. int len,
  5482. double timeout)
  5483. {
  5484. int nread, err = 0;
  5485. #if defined(_WIN32)
  5486. typedef int len_t;
  5487. #else
  5488. typedef size_t len_t;
  5489. #endif
  5490. #if !defined(NO_SSL)
  5491. int ssl_pending;
  5492. #endif
  5493. /* We need an additional wait loop around this, because in some cases
  5494. * with TLSwe may get data from the socket but not from SSL_read.
  5495. * In this case we need to repeat at least once.
  5496. */
  5497. if (fp != NULL) {
  5498. #if !defined(_WIN32_WCE)
  5499. /* Use read() instead of fread(), because if we're reading from the
  5500. * CGI pipe, fread() may block until IO buffer is filled up. We
  5501. * cannot afford to block and must pass all read bytes immediately
  5502. * to the client. */
  5503. nread = (int)read(fileno(fp), buf, (size_t)len);
  5504. #else
  5505. /* WinCE does not support CGI pipes */
  5506. nread = (int)fread(buf, 1, (size_t)len, fp);
  5507. #endif
  5508. err = (nread < 0) ? ERRNO : 0;
  5509. if ((nread == 0) && (len > 0)) {
  5510. /* Should get data, but got EOL */
  5511. return -2;
  5512. }
  5513. #if !defined(NO_SSL)
  5514. } else if ((conn->ssl != NULL)
  5515. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5516. /* We already know there is no more data buffered in conn->buf
  5517. * but there is more available in the SSL layer. So don't poll
  5518. * conn->client.sock yet. */
  5519. if (ssl_pending > len) {
  5520. ssl_pending = len;
  5521. }
  5522. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5523. if (nread <= 0) {
  5524. err = SSL_get_error(conn->ssl, nread);
  5525. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5526. err = ERRNO;
  5527. } else if ((err == SSL_ERROR_WANT_READ)
  5528. || (err == SSL_ERROR_WANT_WRITE)) {
  5529. nread = 0;
  5530. } else {
  5531. /* All errors should return -2 */
  5532. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5533. return -2;
  5534. }
  5535. ERR_clear_error();
  5536. } else {
  5537. err = 0;
  5538. }
  5539. } else if (conn->ssl != NULL) {
  5540. struct mg_pollfd pfd[1];
  5541. int pollres;
  5542. pfd[0].fd = conn->client.sock;
  5543. pfd[0].events = POLLIN;
  5544. pollres = mg_poll(pfd,
  5545. 1,
  5546. (int)(timeout * 1000.0),
  5547. &(conn->phys_ctx->stop_flag));
  5548. if (conn->phys_ctx->stop_flag) {
  5549. return -2;
  5550. }
  5551. if (pollres > 0) {
  5552. nread = SSL_read(conn->ssl, buf, len);
  5553. if (nread <= 0) {
  5554. err = SSL_get_error(conn->ssl, nread);
  5555. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5556. err = ERRNO;
  5557. } else if ((err == SSL_ERROR_WANT_READ)
  5558. || (err == SSL_ERROR_WANT_WRITE)) {
  5559. nread = 0;
  5560. } else {
  5561. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5562. return -2;
  5563. }
  5564. } else {
  5565. err = 0;
  5566. }
  5567. ERR_clear_error();
  5568. } else if (pollres < 0) {
  5569. /* Error */
  5570. return -2;
  5571. } else {
  5572. /* pollres = 0 means timeout */
  5573. nread = 0;
  5574. }
  5575. #endif
  5576. } else {
  5577. struct mg_pollfd pfd[1];
  5578. int pollres;
  5579. pfd[0].fd = conn->client.sock;
  5580. pfd[0].events = POLLIN;
  5581. pollres = mg_poll(pfd,
  5582. 1,
  5583. (int)(timeout * 1000.0),
  5584. &(conn->phys_ctx->stop_flag));
  5585. if (conn->phys_ctx->stop_flag) {
  5586. return -2;
  5587. }
  5588. if (pollres > 0) {
  5589. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5590. err = (nread < 0) ? ERRNO : 0;
  5591. if (nread <= 0) {
  5592. /* shutdown of the socket at client side */
  5593. return -2;
  5594. }
  5595. } else if (pollres < 0) {
  5596. /* error callint poll */
  5597. return -2;
  5598. } else {
  5599. /* pollres = 0 means timeout */
  5600. nread = 0;
  5601. }
  5602. }
  5603. if (conn->phys_ctx->stop_flag) {
  5604. return -2;
  5605. }
  5606. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5607. /* some data has been read, or no data was requested */
  5608. return nread;
  5609. }
  5610. if (nread < 0) {
  5611. /* socket error - check errno */
  5612. #if defined(_WIN32)
  5613. if (err == WSAEWOULDBLOCK) {
  5614. /* TODO (low): check if this is still required */
  5615. /* standard case if called from close_socket_gracefully */
  5616. return -2;
  5617. } else if (err == WSAETIMEDOUT) {
  5618. /* TODO (low): check if this is still required */
  5619. /* timeout is handled by the while loop */
  5620. return 0;
  5621. } else if (err == WSAECONNABORTED) {
  5622. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5623. return -2;
  5624. } else {
  5625. DEBUG_TRACE("recv() failed, error %d", err);
  5626. return -2;
  5627. }
  5628. #else
  5629. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5630. * if the timeout is reached and if the socket was set to non-
  5631. * blocking in close_socket_gracefully, so we can not distinguish
  5632. * here. We have to wait for the timeout in both cases for now.
  5633. */
  5634. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5635. /* TODO (low): check if this is still required */
  5636. /* EAGAIN/EWOULDBLOCK:
  5637. * standard case if called from close_socket_gracefully
  5638. * => should return -1 */
  5639. /* or timeout occurred
  5640. * => the code must stay in the while loop */
  5641. /* EINTR can be generated on a socket with a timeout set even
  5642. * when SA_RESTART is effective for all relevant signals
  5643. * (see signal(7)).
  5644. * => stay in the while loop */
  5645. } else {
  5646. DEBUG_TRACE("recv() failed, error %d", err);
  5647. return -2;
  5648. }
  5649. #endif
  5650. }
  5651. /* Timeout occurred, but no data available. */
  5652. return -1;
  5653. }
  5654. static int
  5655. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5656. {
  5657. int n, nread = 0;
  5658. double timeout = -1.0;
  5659. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5660. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5661. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5662. }
  5663. if (timeout >= 0.0) {
  5664. start_time = mg_get_current_time_ns();
  5665. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5666. }
  5667. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5668. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5669. if (n == -2) {
  5670. if (nread == 0) {
  5671. nread = -1; /* Propagate the error */
  5672. }
  5673. break;
  5674. } else if (n == -1) {
  5675. /* timeout */
  5676. if (timeout >= 0.0) {
  5677. now = mg_get_current_time_ns();
  5678. if ((now - start_time) <= timeout_ns) {
  5679. continue;
  5680. }
  5681. }
  5682. break;
  5683. } else if (n == 0) {
  5684. break; /* No more data to read */
  5685. } else {
  5686. nread += n;
  5687. len -= n;
  5688. }
  5689. }
  5690. return nread;
  5691. }
  5692. static void
  5693. discard_unread_request_data(struct mg_connection *conn)
  5694. {
  5695. char buf[MG_BUF_LEN];
  5696. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5697. ;
  5698. }
  5699. static int
  5700. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5701. {
  5702. int64_t content_len, n, buffered_len, nread;
  5703. int64_t len64 =
  5704. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5705. * int, we may not read more
  5706. * bytes */
  5707. const char *body;
  5708. if (conn == NULL) {
  5709. return 0;
  5710. }
  5711. /* If Content-Length is not set for a response with body data,
  5712. * we do not know in advance how much data should be read. */
  5713. content_len = conn->content_len;
  5714. if (content_len < 0) {
  5715. /* The body data is completed when the connection is closed. */
  5716. content_len = INT64_MAX;
  5717. }
  5718. nread = 0;
  5719. if (conn->consumed_content < content_len) {
  5720. /* Adjust number of bytes to read. */
  5721. int64_t left_to_read = content_len - conn->consumed_content;
  5722. if (left_to_read < len64) {
  5723. /* Do not read more than the total content length of the
  5724. * request.
  5725. */
  5726. len64 = left_to_read;
  5727. }
  5728. /* Return buffered data */
  5729. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5730. - conn->consumed_content;
  5731. if (buffered_len > 0) {
  5732. if (len64 < buffered_len) {
  5733. buffered_len = len64;
  5734. }
  5735. body = conn->buf + conn->request_len + conn->consumed_content;
  5736. memcpy(buf, body, (size_t)buffered_len);
  5737. len64 -= buffered_len;
  5738. conn->consumed_content += buffered_len;
  5739. nread += buffered_len;
  5740. buf = (char *)buf + buffered_len;
  5741. }
  5742. /* We have returned all buffered data. Read new data from the remote
  5743. * socket.
  5744. */
  5745. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5746. conn->consumed_content += n;
  5747. nread += n;
  5748. } else {
  5749. nread = ((nread > 0) ? nread : n);
  5750. }
  5751. }
  5752. return (int)nread;
  5753. }
  5754. int
  5755. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5756. {
  5757. if (len > INT_MAX) {
  5758. len = INT_MAX;
  5759. }
  5760. if (conn == NULL) {
  5761. return 0;
  5762. }
  5763. if (conn->is_chunked) {
  5764. size_t all_read = 0;
  5765. while (len > 0) {
  5766. if (conn->is_chunked >= 3) {
  5767. /* No more data left to read */
  5768. return 0;
  5769. }
  5770. if (conn->is_chunked != 1) {
  5771. /* Has error */
  5772. return -1;
  5773. }
  5774. if (conn->consumed_content != conn->content_len) {
  5775. /* copy from the current chunk */
  5776. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5777. if (read_ret < 1) {
  5778. /* read error */
  5779. conn->is_chunked = 2;
  5780. return -1;
  5781. }
  5782. all_read += (size_t)read_ret;
  5783. len -= (size_t)read_ret;
  5784. if (conn->consumed_content == conn->content_len) {
  5785. /* Add data bytes in the current chunk have been read,
  5786. * so we are expecting \r\n now. */
  5787. char x[2];
  5788. conn->content_len += 2;
  5789. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5790. || (x[1] != '\n')) {
  5791. /* Protocol violation */
  5792. conn->is_chunked = 2;
  5793. return -1;
  5794. }
  5795. }
  5796. } else {
  5797. /* fetch a new chunk */
  5798. size_t i;
  5799. char lenbuf[64];
  5800. char *end = NULL;
  5801. unsigned long chunkSize = 0;
  5802. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5803. conn->content_len++;
  5804. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5805. lenbuf[i] = 0;
  5806. }
  5807. if ((i > 0) && (lenbuf[i] == '\r')
  5808. && (lenbuf[i - 1] != '\r')) {
  5809. continue;
  5810. }
  5811. if ((i > 1) && (lenbuf[i] == '\n')
  5812. && (lenbuf[i - 1] == '\r')) {
  5813. lenbuf[i + 1] = 0;
  5814. chunkSize = strtoul(lenbuf, &end, 16);
  5815. if (chunkSize == 0) {
  5816. /* regular end of content */
  5817. conn->is_chunked = 3;
  5818. }
  5819. break;
  5820. }
  5821. if (!isxdigit((unsigned char)lenbuf[i])) {
  5822. /* illegal character for chunk length */
  5823. conn->is_chunked = 2;
  5824. return -1;
  5825. }
  5826. }
  5827. if ((end == NULL) || (*end != '\r')) {
  5828. /* chunksize not set correctly */
  5829. conn->is_chunked = 2;
  5830. return -1;
  5831. }
  5832. if (chunkSize == 0) {
  5833. /* try discarding trailer for keep-alive */
  5834. conn->content_len += 2;
  5835. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5836. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5837. conn->is_chunked = 4;
  5838. }
  5839. break;
  5840. }
  5841. /* append a new chunk */
  5842. conn->content_len += chunkSize;
  5843. }
  5844. }
  5845. return (int)all_read;
  5846. }
  5847. return mg_read_inner(conn, buf, len);
  5848. }
  5849. int
  5850. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5851. {
  5852. time_t now;
  5853. int n, total, allowed;
  5854. if (conn == NULL) {
  5855. return 0;
  5856. }
  5857. if (len > INT_MAX) {
  5858. return -1;
  5859. }
  5860. if (conn->throttle > 0) {
  5861. if ((now = time(NULL)) != conn->last_throttle_time) {
  5862. conn->last_throttle_time = now;
  5863. conn->last_throttle_bytes = 0;
  5864. }
  5865. allowed = conn->throttle - conn->last_throttle_bytes;
  5866. if (allowed > (int)len) {
  5867. allowed = (int)len;
  5868. }
  5869. if ((total = push_all(conn->phys_ctx,
  5870. NULL,
  5871. conn->client.sock,
  5872. conn->ssl,
  5873. (const char *)buf,
  5874. allowed))
  5875. == allowed) {
  5876. buf = (const char *)buf + total;
  5877. conn->last_throttle_bytes += total;
  5878. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5879. allowed = (conn->throttle > ((int)len - total))
  5880. ? (int)len - total
  5881. : conn->throttle;
  5882. if ((n = push_all(conn->phys_ctx,
  5883. NULL,
  5884. conn->client.sock,
  5885. conn->ssl,
  5886. (const char *)buf,
  5887. allowed))
  5888. != allowed) {
  5889. break;
  5890. }
  5891. sleep(1);
  5892. conn->last_throttle_bytes = allowed;
  5893. conn->last_throttle_time = time(NULL);
  5894. buf = (const char *)buf + n;
  5895. total += n;
  5896. }
  5897. }
  5898. } else {
  5899. total = push_all(conn->phys_ctx,
  5900. NULL,
  5901. conn->client.sock,
  5902. conn->ssl,
  5903. (const char *)buf,
  5904. (int)len);
  5905. }
  5906. if (total > 0) {
  5907. conn->num_bytes_sent += total;
  5908. }
  5909. return total;
  5910. }
  5911. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5912. int
  5913. mg_send_chunk(struct mg_connection *conn,
  5914. const char *chunk,
  5915. unsigned int chunk_len)
  5916. {
  5917. char lenbuf[16];
  5918. size_t lenbuf_len;
  5919. int ret;
  5920. int t;
  5921. /* First store the length information in a text buffer. */
  5922. sprintf(lenbuf, "%x\r\n", chunk_len);
  5923. lenbuf_len = strlen(lenbuf);
  5924. /* Then send length information, chunk and terminating \r\n. */
  5925. ret = mg_write(conn, lenbuf, lenbuf_len);
  5926. if (ret != (int)lenbuf_len) {
  5927. return -1;
  5928. }
  5929. t = ret;
  5930. ret = mg_write(conn, chunk, chunk_len);
  5931. if (ret != (int)chunk_len) {
  5932. return -1;
  5933. }
  5934. t += ret;
  5935. ret = mg_write(conn, "\r\n", 2);
  5936. if (ret != 2) {
  5937. return -1;
  5938. }
  5939. t += ret;
  5940. return t;
  5941. }
  5942. #if defined(GCC_DIAGNOSTIC)
  5943. /* This block forwards format strings to printf implementations,
  5944. * so we need to disable the format-nonliteral warning. */
  5945. #pragma GCC diagnostic push
  5946. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5947. #endif
  5948. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5949. static int
  5950. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5951. {
  5952. va_list ap_copy;
  5953. size_t size = MG_BUF_LEN / 4;
  5954. int len = -1;
  5955. *buf = NULL;
  5956. while (len < 0) {
  5957. if (*buf) {
  5958. mg_free(*buf);
  5959. }
  5960. size *= 4;
  5961. *buf = (char *)mg_malloc(size);
  5962. if (!*buf) {
  5963. break;
  5964. }
  5965. va_copy(ap_copy, ap);
  5966. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5967. va_end(ap_copy);
  5968. (*buf)[size - 1] = 0;
  5969. }
  5970. return len;
  5971. }
  5972. /* Print message to buffer. If buffer is large enough to hold the message,
  5973. * return buffer. If buffer is to small, allocate large enough buffer on
  5974. * heap,
  5975. * and return allocated buffer. */
  5976. static int
  5977. alloc_vprintf(char **out_buf,
  5978. char *prealloc_buf,
  5979. size_t prealloc_size,
  5980. const char *fmt,
  5981. va_list ap)
  5982. {
  5983. va_list ap_copy;
  5984. int len;
  5985. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5986. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5987. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5988. * Therefore, we make two passes: on first pass, get required message
  5989. * length.
  5990. * On second pass, actually print the message. */
  5991. va_copy(ap_copy, ap);
  5992. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5993. va_end(ap_copy);
  5994. if (len < 0) {
  5995. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5996. * Switch to alternative code path that uses incremental
  5997. * allocations.
  5998. */
  5999. va_copy(ap_copy, ap);
  6000. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6001. va_end(ap_copy);
  6002. } else if ((size_t)(len) >= prealloc_size) {
  6003. /* The pre-allocated buffer not large enough. */
  6004. /* Allocate a new buffer. */
  6005. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6006. if (!*out_buf) {
  6007. /* Allocation failed. Return -1 as "out of memory" error. */
  6008. return -1;
  6009. }
  6010. /* Buffer allocation successful. Store the string there. */
  6011. va_copy(ap_copy, ap);
  6012. IGNORE_UNUSED_RESULT(
  6013. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6014. va_end(ap_copy);
  6015. } else {
  6016. /* The pre-allocated buffer is large enough.
  6017. * Use it to store the string and return the address. */
  6018. va_copy(ap_copy, ap);
  6019. IGNORE_UNUSED_RESULT(
  6020. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6021. va_end(ap_copy);
  6022. *out_buf = prealloc_buf;
  6023. }
  6024. return len;
  6025. }
  6026. #if defined(GCC_DIAGNOSTIC)
  6027. /* Enable format-nonliteral warning again. */
  6028. #pragma GCC diagnostic pop
  6029. #endif
  6030. static int
  6031. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6032. {
  6033. char mem[MG_BUF_LEN];
  6034. char *buf = NULL;
  6035. int len;
  6036. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6037. len = mg_write(conn, buf, (size_t)len);
  6038. }
  6039. if (buf != mem) {
  6040. mg_free(buf);
  6041. }
  6042. return len;
  6043. }
  6044. int
  6045. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6046. {
  6047. va_list ap;
  6048. int result;
  6049. va_start(ap, fmt);
  6050. result = mg_vprintf(conn, fmt, ap);
  6051. va_end(ap);
  6052. return result;
  6053. }
  6054. int
  6055. mg_url_decode(const char *src,
  6056. int src_len,
  6057. char *dst,
  6058. int dst_len,
  6059. int is_form_url_encoded)
  6060. {
  6061. int i, j, a, b;
  6062. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6063. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6064. if ((i < src_len - 2) && (src[i] == '%')
  6065. && isxdigit((unsigned char)src[i + 1])
  6066. && isxdigit((unsigned char)src[i + 2])) {
  6067. a = tolower((unsigned char)src[i + 1]);
  6068. b = tolower((unsigned char)src[i + 2]);
  6069. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6070. i += 2;
  6071. } else if (is_form_url_encoded && (src[i] == '+')) {
  6072. dst[j] = ' ';
  6073. } else {
  6074. dst[j] = src[i];
  6075. }
  6076. }
  6077. dst[j] = '\0'; /* Null-terminate the destination */
  6078. return (i >= src_len) ? j : -1;
  6079. }
  6080. int
  6081. mg_get_var(const char *data,
  6082. size_t data_len,
  6083. const char *name,
  6084. char *dst,
  6085. size_t dst_len)
  6086. {
  6087. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6088. }
  6089. int
  6090. mg_get_var2(const char *data,
  6091. size_t data_len,
  6092. const char *name,
  6093. char *dst,
  6094. size_t dst_len,
  6095. size_t occurrence)
  6096. {
  6097. const char *p, *e, *s;
  6098. size_t name_len;
  6099. int len;
  6100. if ((dst == NULL) || (dst_len == 0)) {
  6101. len = -2;
  6102. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6103. len = -1;
  6104. dst[0] = '\0';
  6105. } else {
  6106. name_len = strlen(name);
  6107. e = data + data_len;
  6108. len = -1;
  6109. dst[0] = '\0';
  6110. /* data is "var1=val1&var2=val2...". Find variable first */
  6111. for (p = data; p + name_len < e; p++) {
  6112. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6113. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6114. /* Point p to variable value */
  6115. p += name_len + 1;
  6116. /* Point s to the end of the value */
  6117. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6118. if (s == NULL) {
  6119. s = e;
  6120. }
  6121. DEBUG_ASSERT(s >= p);
  6122. if (s < p) {
  6123. return -3;
  6124. }
  6125. /* Decode variable into destination buffer */
  6126. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6127. /* Redirect error code from -1 to -2 (destination buffer too
  6128. * small). */
  6129. if (len == -1) {
  6130. len = -2;
  6131. }
  6132. break;
  6133. }
  6134. }
  6135. }
  6136. return len;
  6137. }
  6138. /* HCP24: some changes to compare hole var_name */
  6139. int
  6140. mg_get_cookie(const char *cookie_header,
  6141. const char *var_name,
  6142. char *dst,
  6143. size_t dst_size)
  6144. {
  6145. const char *s, *p, *end;
  6146. int name_len, len = -1;
  6147. if ((dst == NULL) || (dst_size == 0)) {
  6148. return -2;
  6149. }
  6150. dst[0] = '\0';
  6151. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6152. return -1;
  6153. }
  6154. name_len = (int)strlen(var_name);
  6155. end = s + strlen(s);
  6156. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6157. if (s[name_len] == '=') {
  6158. /* HCP24: now check is it a substring or a full cookie name */
  6159. if ((s == cookie_header) || (s[-1] == ' ')) {
  6160. s += name_len + 1;
  6161. if ((p = strchr(s, ' ')) == NULL) {
  6162. p = end;
  6163. }
  6164. if (p[-1] == ';') {
  6165. p--;
  6166. }
  6167. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6168. s++;
  6169. p--;
  6170. }
  6171. if ((size_t)(p - s) < dst_size) {
  6172. len = (int)(p - s);
  6173. mg_strlcpy(dst, s, (size_t)len + 1);
  6174. } else {
  6175. len = -3;
  6176. }
  6177. break;
  6178. }
  6179. }
  6180. }
  6181. return len;
  6182. }
  6183. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6184. static void
  6185. base64_encode(const unsigned char *src, int src_len, char *dst)
  6186. {
  6187. static const char *b64 =
  6188. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6189. int i, j, a, b, c;
  6190. for (i = j = 0; i < src_len; i += 3) {
  6191. a = src[i];
  6192. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6193. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6194. dst[j++] = b64[a >> 2];
  6195. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6196. if (i + 1 < src_len) {
  6197. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6198. }
  6199. if (i + 2 < src_len) {
  6200. dst[j++] = b64[c & 63];
  6201. }
  6202. }
  6203. while (j % 4 != 0) {
  6204. dst[j++] = '=';
  6205. }
  6206. dst[j++] = '\0';
  6207. }
  6208. #endif
  6209. #if defined(USE_LUA)
  6210. static unsigned char
  6211. b64reverse(char letter)
  6212. {
  6213. if ((letter >= 'A') && (letter <= 'Z')) {
  6214. return letter - 'A';
  6215. }
  6216. if ((letter >= 'a') && (letter <= 'z')) {
  6217. return letter - 'a' + 26;
  6218. }
  6219. if ((letter >= '0') && (letter <= '9')) {
  6220. return letter - '0' + 52;
  6221. }
  6222. if (letter == '+') {
  6223. return 62;
  6224. }
  6225. if (letter == '/') {
  6226. return 63;
  6227. }
  6228. if (letter == '=') {
  6229. return 255; /* normal end */
  6230. }
  6231. return 254; /* error */
  6232. }
  6233. static int
  6234. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6235. {
  6236. int i;
  6237. unsigned char a, b, c, d;
  6238. *dst_len = 0;
  6239. for (i = 0; i < src_len; i += 4) {
  6240. a = b64reverse(src[i]);
  6241. if (a >= 254) {
  6242. return i;
  6243. }
  6244. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6245. if (b >= 254) {
  6246. return i + 1;
  6247. }
  6248. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6249. if (c == 254) {
  6250. return i + 2;
  6251. }
  6252. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6253. if (d == 254) {
  6254. return i + 3;
  6255. }
  6256. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6257. if (c != 255) {
  6258. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6259. if (d != 255) {
  6260. dst[(*dst_len)++] = (c << 6) + d;
  6261. }
  6262. }
  6263. }
  6264. return -1;
  6265. }
  6266. #endif
  6267. static int
  6268. is_put_or_delete_method(const struct mg_connection *conn)
  6269. {
  6270. if (conn) {
  6271. const char *s = conn->request_info.request_method;
  6272. return (s != NULL)
  6273. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6274. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6275. }
  6276. return 0;
  6277. }
  6278. #if !defined(NO_FILES)
  6279. static int
  6280. extention_matches_script(
  6281. struct mg_connection *conn, /* in: request (must be valid) */
  6282. const char *filename /* in: filename (must be valid) */
  6283. )
  6284. {
  6285. #if !defined(NO_CGI)
  6286. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6287. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6288. filename)
  6289. > 0) {
  6290. return 1;
  6291. }
  6292. #endif
  6293. #if defined(USE_LUA)
  6294. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6295. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6296. filename)
  6297. > 0) {
  6298. return 1;
  6299. }
  6300. #endif
  6301. #if defined(USE_DUKTAPE)
  6302. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6303. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6304. filename)
  6305. > 0) {
  6306. return 1;
  6307. }
  6308. #endif
  6309. /* filename and conn could be unused, if all preocessor conditions
  6310. * are false (no script language supported). */
  6311. (void)filename;
  6312. (void)conn;
  6313. return 0;
  6314. }
  6315. /* For given directory path, substitute it to valid index file.
  6316. * Return 1 if index file has been found, 0 if not found.
  6317. * If the file is found, it's stats is returned in stp. */
  6318. static int
  6319. substitute_index_file(struct mg_connection *conn,
  6320. char *path,
  6321. size_t path_len,
  6322. struct mg_file_stat *filestat)
  6323. {
  6324. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6325. struct vec filename_vec;
  6326. size_t n = strlen(path);
  6327. int found = 0;
  6328. /* The 'path' given to us points to the directory. Remove all trailing
  6329. * directory separator characters from the end of the path, and
  6330. * then append single directory separator character. */
  6331. while ((n > 0) && (path[n - 1] == '/')) {
  6332. n--;
  6333. }
  6334. path[n] = '/';
  6335. /* Traverse index files list. For each entry, append it to the given
  6336. * path and see if the file exists. If it exists, break the loop */
  6337. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6338. /* Ignore too long entries that may overflow path buffer */
  6339. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6340. continue;
  6341. }
  6342. /* Prepare full path to the index file */
  6343. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6344. /* Does it exist? */
  6345. if (mg_stat(conn, path, filestat)) {
  6346. /* Yes it does, break the loop */
  6347. found = 1;
  6348. break;
  6349. }
  6350. }
  6351. /* If no index file exists, restore directory path */
  6352. if (!found) {
  6353. path[n] = '\0';
  6354. }
  6355. return found;
  6356. }
  6357. #endif
  6358. static void
  6359. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6360. char *filename, /* out: filename */
  6361. size_t filename_buf_len, /* in: size of filename buffer */
  6362. struct mg_file_stat *filestat, /* out: file status structure */
  6363. int *is_found, /* out: file found (directly) */
  6364. int *is_script_resource, /* out: handled by a script? */
  6365. int *is_websocket_request, /* out: websocket connetion? */
  6366. int *is_put_or_delete_request /* out: put/delete a file? */
  6367. )
  6368. {
  6369. char const *accept_encoding;
  6370. #if !defined(NO_FILES)
  6371. const char *uri = conn->request_info.local_uri;
  6372. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6373. const char *rewrite;
  6374. struct vec a, b;
  6375. ptrdiff_t match_len;
  6376. char gz_path[PATH_MAX];
  6377. int truncated;
  6378. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6379. char *tmp_str;
  6380. size_t tmp_str_len, sep_pos;
  6381. int allow_substitute_script_subresources;
  6382. #endif
  6383. #else
  6384. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6385. #endif
  6386. /* Step 1: Set all initially unknown outputs to zero */
  6387. memset(filestat, 0, sizeof(*filestat));
  6388. *filename = 0;
  6389. *is_found = 0;
  6390. *is_script_resource = 0;
  6391. /* Step 2: Check if the request attempts to modify the file system */
  6392. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6393. /* Step 3: Check if it is a websocket request, and modify the document
  6394. * root if required */
  6395. #if defined(USE_WEBSOCKET)
  6396. *is_websocket_request = is_websocket_protocol(conn);
  6397. #if !defined(NO_FILES)
  6398. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6399. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6400. }
  6401. #endif /* !NO_FILES */
  6402. #else /* USE_WEBSOCKET */
  6403. *is_websocket_request = 0;
  6404. #endif /* USE_WEBSOCKET */
  6405. /* Step 4: Check if gzip encoded response is allowed */
  6406. conn->accept_gzip = 0;
  6407. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6408. if (strstr(accept_encoding, "gzip") != NULL) {
  6409. conn->accept_gzip = 1;
  6410. }
  6411. }
  6412. #if !defined(NO_FILES)
  6413. /* Step 5: If there is no root directory, don't look for files. */
  6414. /* Note that root == NULL is a regular use case here. This occurs,
  6415. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6416. * config is not required. */
  6417. if (root == NULL) {
  6418. /* all file related outputs have already been set to 0, just return
  6419. */
  6420. return;
  6421. }
  6422. /* Step 6: Determine the local file path from the root path and the
  6423. * request uri. */
  6424. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6425. * part of the path one byte on the right. */
  6426. mg_snprintf(
  6427. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6428. if (truncated) {
  6429. goto interpret_cleanup;
  6430. }
  6431. /* Step 7: URI rewriting */
  6432. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6433. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6434. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6435. mg_snprintf(conn,
  6436. &truncated,
  6437. filename,
  6438. filename_buf_len - 1,
  6439. "%.*s%s",
  6440. (int)b.len,
  6441. b.ptr,
  6442. uri + match_len);
  6443. break;
  6444. }
  6445. }
  6446. if (truncated) {
  6447. goto interpret_cleanup;
  6448. }
  6449. /* Step 8: Check if the file exists at the server */
  6450. /* Local file path and name, corresponding to requested URI
  6451. * is now stored in "filename" variable. */
  6452. if (mg_stat(conn, filename, filestat)) {
  6453. int uri_len = (int)strlen(uri);
  6454. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6455. /* 8.1: File exists. */
  6456. *is_found = 1;
  6457. /* 8.2: Check if it is a script type. */
  6458. if (extention_matches_script(conn, filename)) {
  6459. /* The request addresses a CGI resource, Lua script or
  6460. * server-side javascript.
  6461. * The URI corresponds to the script itself (like
  6462. * /path/script.cgi), and there is no additional resource
  6463. * path (like /path/script.cgi/something).
  6464. * Requests that modify (replace or delete) a resource, like
  6465. * PUT and DELETE requests, should replace/delete the script
  6466. * file.
  6467. * Requests that read or write from/to a resource, like GET and
  6468. * POST requests, should call the script and return the
  6469. * generated response. */
  6470. *is_script_resource = (!*is_put_or_delete_request);
  6471. }
  6472. /* 8.3: If the request target is a directory, there could be
  6473. * a substitute file (index.html, index.cgi, ...). */
  6474. if (filestat->is_directory && is_uri_end_slash) {
  6475. /* Use a local copy here, since substitute_index_file will
  6476. * change the content of the file status */
  6477. struct mg_file_stat tmp_filestat;
  6478. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6479. if (substitute_index_file(
  6480. conn, filename, filename_buf_len, &tmp_filestat)) {
  6481. /* Substitute file found. Copy stat to the output, then
  6482. * check if the file is a script file */
  6483. *filestat = tmp_filestat;
  6484. if (extention_matches_script(conn, filename)) {
  6485. /* Substitute file is a script file */
  6486. *is_script_resource = 1;
  6487. } else {
  6488. /* Substitute file is a regular file */
  6489. *is_script_resource = 0;
  6490. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6491. }
  6492. }
  6493. /* If there is no substitute file, the server could return
  6494. * a directory listing in a later step */
  6495. }
  6496. return;
  6497. }
  6498. /* Step 9: Check for zipped files: */
  6499. /* If we can't find the actual file, look for the file
  6500. * with the same name but a .gz extension. If we find it,
  6501. * use that and set the gzipped flag in the file struct
  6502. * to indicate that the response need to have the content-
  6503. * encoding: gzip header.
  6504. * We can only do this if the browser declares support. */
  6505. if (conn->accept_gzip) {
  6506. mg_snprintf(
  6507. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6508. if (truncated) {
  6509. goto interpret_cleanup;
  6510. }
  6511. if (mg_stat(conn, gz_path, filestat)) {
  6512. if (filestat) {
  6513. filestat->is_gzipped = 1;
  6514. *is_found = 1;
  6515. }
  6516. /* Currently gz files can not be scripts. */
  6517. return;
  6518. }
  6519. }
  6520. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6521. /* Step 10: Script resources may handle sub-resources */
  6522. /* Support PATH_INFO for CGI scripts. */
  6523. tmp_str_len = strlen(filename);
  6524. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6525. if (!tmp_str) {
  6526. /* Out of memory */
  6527. goto interpret_cleanup;
  6528. }
  6529. memcpy(tmp_str, filename, tmp_str_len + 1);
  6530. /* Check config, if index scripts may have sub-resources */
  6531. allow_substitute_script_subresources =
  6532. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6533. "yes");
  6534. sep_pos = tmp_str_len;
  6535. while (sep_pos > 0) {
  6536. sep_pos--;
  6537. if (tmp_str[sep_pos] == '/') {
  6538. int is_script = 0, does_exist = 0;
  6539. tmp_str[sep_pos] = 0;
  6540. if (tmp_str[0]) {
  6541. is_script = extention_matches_script(conn, tmp_str);
  6542. does_exist = mg_stat(conn, tmp_str, filestat);
  6543. }
  6544. if (does_exist && is_script) {
  6545. filename[sep_pos] = 0;
  6546. memmove(filename + sep_pos + 2,
  6547. filename + sep_pos + 1,
  6548. strlen(filename + sep_pos + 1) + 1);
  6549. conn->path_info = filename + sep_pos + 1;
  6550. filename[sep_pos + 1] = '/';
  6551. *is_script_resource = 1;
  6552. *is_found = 1;
  6553. break;
  6554. }
  6555. if (allow_substitute_script_subresources) {
  6556. if (substitute_index_file(
  6557. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6558. /* some intermediate directory has an index file */
  6559. if (extention_matches_script(conn, tmp_str)) {
  6560. char *tmp_str2;
  6561. DEBUG_TRACE("Substitute script %s serving path %s",
  6562. tmp_str,
  6563. filename);
  6564. /* this index file is a script */
  6565. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6566. conn->phys_ctx);
  6567. mg_snprintf(conn,
  6568. &truncated,
  6569. filename,
  6570. filename_buf_len,
  6571. "%s//%s",
  6572. tmp_str,
  6573. tmp_str2);
  6574. mg_free(tmp_str2);
  6575. if (truncated) {
  6576. mg_free(tmp_str);
  6577. goto interpret_cleanup;
  6578. }
  6579. sep_pos = strlen(tmp_str);
  6580. filename[sep_pos] = 0;
  6581. conn->path_info = filename + sep_pos + 1;
  6582. *is_script_resource = 1;
  6583. *is_found = 1;
  6584. break;
  6585. } else {
  6586. DEBUG_TRACE("Substitute file %s serving path %s",
  6587. tmp_str,
  6588. filename);
  6589. /* non-script files will not have sub-resources */
  6590. filename[sep_pos] = 0;
  6591. conn->path_info = 0;
  6592. *is_script_resource = 0;
  6593. *is_found = 0;
  6594. break;
  6595. }
  6596. }
  6597. }
  6598. tmp_str[sep_pos] = '/';
  6599. }
  6600. }
  6601. mg_free(tmp_str);
  6602. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6603. #endif /* !defined(NO_FILES) */
  6604. return;
  6605. #if !defined(NO_FILES)
  6606. /* Reset all outputs */
  6607. interpret_cleanup:
  6608. memset(filestat, 0, sizeof(*filestat));
  6609. *filename = 0;
  6610. *is_found = 0;
  6611. *is_script_resource = 0;
  6612. *is_websocket_request = 0;
  6613. *is_put_or_delete_request = 0;
  6614. #endif /* !defined(NO_FILES) */
  6615. }
  6616. /* Check whether full request is buffered. Return:
  6617. * -1 if request or response is malformed
  6618. * 0 if request or response is not yet fully buffered
  6619. * >0 actual request length, including last \r\n\r\n */
  6620. static int
  6621. get_http_header_len(const char *buf, int buflen)
  6622. {
  6623. int i;
  6624. for (i = 0; i < buflen; i++) {
  6625. /* Do an unsigned comparison in some conditions below */
  6626. const unsigned char c = (unsigned char)buf[i];
  6627. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6628. && !isprint(c)) {
  6629. /* abort scan as soon as one malformed character is found */
  6630. return -1;
  6631. }
  6632. if (i < buflen - 1) {
  6633. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6634. /* Two newline, no carriage return - not standard compliant,
  6635. * but
  6636. * it
  6637. * should be accepted */
  6638. return i + 2;
  6639. }
  6640. }
  6641. if (i < buflen - 3) {
  6642. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6643. && (buf[i + 3] == '\n')) {
  6644. /* Two \r\n - standard compliant */
  6645. return i + 4;
  6646. }
  6647. }
  6648. }
  6649. return 0;
  6650. }
  6651. #if !defined(NO_CACHING)
  6652. /* Convert month to the month number. Return -1 on error, or month number */
  6653. static int
  6654. get_month_index(const char *s)
  6655. {
  6656. size_t i;
  6657. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6658. if (!strcmp(s, month_names[i])) {
  6659. return (int)i;
  6660. }
  6661. }
  6662. return -1;
  6663. }
  6664. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6665. static time_t
  6666. parse_date_string(const char *datetime)
  6667. {
  6668. char month_str[32] = {0};
  6669. int second, minute, hour, day, month, year;
  6670. time_t result = (time_t)0;
  6671. struct tm tm;
  6672. if ((sscanf(datetime,
  6673. "%d/%3s/%d %d:%d:%d",
  6674. &day,
  6675. month_str,
  6676. &year,
  6677. &hour,
  6678. &minute,
  6679. &second)
  6680. == 6)
  6681. || (sscanf(datetime,
  6682. "%d %3s %d %d:%d:%d",
  6683. &day,
  6684. month_str,
  6685. &year,
  6686. &hour,
  6687. &minute,
  6688. &second)
  6689. == 6)
  6690. || (sscanf(datetime,
  6691. "%*3s, %d %3s %d %d:%d:%d",
  6692. &day,
  6693. month_str,
  6694. &year,
  6695. &hour,
  6696. &minute,
  6697. &second)
  6698. == 6)
  6699. || (sscanf(datetime,
  6700. "%d-%3s-%d %d:%d:%d",
  6701. &day,
  6702. month_str,
  6703. &year,
  6704. &hour,
  6705. &minute,
  6706. &second)
  6707. == 6)) {
  6708. month = get_month_index(month_str);
  6709. if ((month >= 0) && (year >= 1970)) {
  6710. memset(&tm, 0, sizeof(tm));
  6711. tm.tm_year = year - 1900;
  6712. tm.tm_mon = month;
  6713. tm.tm_mday = day;
  6714. tm.tm_hour = hour;
  6715. tm.tm_min = minute;
  6716. tm.tm_sec = second;
  6717. result = timegm(&tm);
  6718. }
  6719. }
  6720. return result;
  6721. }
  6722. #endif /* !NO_CACHING */
  6723. /* Pre-process URIs according to RFC + protect against directory disclosure
  6724. * attacks by removing '..', excessive '/' and '\' characters */
  6725. static void
  6726. remove_dot_segments(char *inout)
  6727. {
  6728. /* Windows backend protection
  6729. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash in
  6730. * URI by slash */
  6731. char *in_copy = mg_strdup(inout);
  6732. char *out_begin = inout;
  6733. char *out_end = inout;
  6734. char *in = in_copy;
  6735. int replaced;
  6736. while (*in) {
  6737. if (*in == '\\') {
  6738. *in = '/';
  6739. }
  6740. in++;
  6741. }
  6742. /* Algorithm "remove_dot_segments" from
  6743. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6744. /* Step 1:
  6745. * The input buffer is initialized.
  6746. * The output buffer is initialized to the empty string.
  6747. */
  6748. in = in_copy;
  6749. /* Step 2:
  6750. * While the input buffer is not empty, loop as follows:
  6751. */
  6752. while (*in) {
  6753. /* Step 2a:
  6754. * If the input buffer begins with a prefix of "../" or "./",
  6755. * then remove that prefix from the input buffer;
  6756. */
  6757. if (!strncmp(in, "../", 3)) {
  6758. in += 3;
  6759. } else if (!strncmp(in, "./", 2)) {
  6760. in += 2;
  6761. }
  6762. /* otherwise */
  6763. /* Step 2b:
  6764. * if the input buffer begins with a prefix of "/./" or "/.",
  6765. * where "." is a complete path segment, then replace that
  6766. * prefix with "/" in the input buffer;
  6767. */
  6768. else if (!strncmp(in, "/./", 3)) {
  6769. in += 2;
  6770. } else if (!strcmp(in, "/.")) {
  6771. in[1] = 0;
  6772. }
  6773. /* otherwise */
  6774. /* Step 2c:
  6775. * if the input buffer begins with a prefix of "/../" or "/..",
  6776. * where ".." is a complete path segment, then replace that
  6777. * prefix with "/" in the input buffer and remove the last
  6778. * segment and its preceding "/" (if any) from the output
  6779. * buffer;
  6780. */
  6781. else if (!strncmp(in, "/../", 4)) {
  6782. in += 3;
  6783. if (out_begin != out_end) {
  6784. /* remove last segment */
  6785. do {
  6786. out_end--;
  6787. *out_end = 0;
  6788. } while ((out_begin != out_end) && (*out_end != '/'));
  6789. }
  6790. } else if (!strcmp(in, "/..")) {
  6791. in[1] = 0;
  6792. if (out_begin != out_end) {
  6793. /* remove last segment */
  6794. do {
  6795. out_end--;
  6796. *out_end = 0;
  6797. } while ((out_begin != out_end) && (*out_end != '/'));
  6798. }
  6799. }
  6800. /* otherwise */
  6801. /* Step 2d:
  6802. * if the input buffer consists only of "." or "..", then remove
  6803. * that from the input buffer;
  6804. */
  6805. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6806. *in = 0;
  6807. }
  6808. /* otherwise */
  6809. /* Step 2e:
  6810. * move the first path segment in the input buffer to the end of
  6811. * the output buffer, including the initial "/" character (if
  6812. * any) and any subsequent characters up to, but not including,
  6813. * the next "/" character or the end of the input buffer.
  6814. */
  6815. else {
  6816. do {
  6817. *out_end = *in;
  6818. out_end++;
  6819. in++;
  6820. } while ((*in != 0) && (*in != '/'));
  6821. }
  6822. }
  6823. /* Step 3:
  6824. * Finally, the output buffer is returned as the result of
  6825. * remove_dot_segments.
  6826. */
  6827. /* Terminate output */
  6828. *out_end = 0;
  6829. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6830. * extension) are identical. Replace all "./" by "/" and remove a "." at the
  6831. * end.
  6832. * Also replace all "//" by "/".
  6833. * Repeat until there is no "./" or "//" anymore.
  6834. */
  6835. do {
  6836. replaced = 0;
  6837. /* replace ./ by / */
  6838. out_end = out_begin;
  6839. while (*out_end) {
  6840. if ((*out_end == '.')
  6841. && ((out_end[1] == '/') || (out_end[1] == 0))) {
  6842. char *r = out_end;
  6843. do {
  6844. r[0] = r[1];
  6845. r++;
  6846. replaced = 1;
  6847. } while (r[0] != 0);
  6848. }
  6849. out_end++;
  6850. }
  6851. /* replace ./ by / */
  6852. out_end = out_begin;
  6853. while (*out_end) {
  6854. if ((out_end[0] == '/') && (out_end[1] == '/')) {
  6855. char *c = out_end;
  6856. while (*c) {
  6857. c[0] = c[1];
  6858. c++;
  6859. }
  6860. replaced = 1;
  6861. }
  6862. out_end++;
  6863. }
  6864. } while (replaced);
  6865. /* Free temporary copies */
  6866. mg_free(in_copy);
  6867. }
  6868. static const struct {
  6869. const char *extension;
  6870. size_t ext_len;
  6871. const char *mime_type;
  6872. } builtin_mime_types[] = {
  6873. /* IANA registered MIME types
  6874. * (http://www.iana.org/assignments/media-types)
  6875. * application types */
  6876. {".doc", 4, "application/msword"},
  6877. {".eps", 4, "application/postscript"},
  6878. {".exe", 4, "application/octet-stream"},
  6879. {".js", 3, "application/javascript"},
  6880. {".json", 5, "application/json"},
  6881. {".pdf", 4, "application/pdf"},
  6882. {".ps", 3, "application/postscript"},
  6883. {".rtf", 4, "application/rtf"},
  6884. {".xhtml", 6, "application/xhtml+xml"},
  6885. {".xsl", 4, "application/xml"},
  6886. {".xslt", 5, "application/xml"},
  6887. /* fonts */
  6888. {".ttf", 4, "application/font-sfnt"},
  6889. {".cff", 4, "application/font-sfnt"},
  6890. {".otf", 4, "application/font-sfnt"},
  6891. {".aat", 4, "application/font-sfnt"},
  6892. {".sil", 4, "application/font-sfnt"},
  6893. {".pfr", 4, "application/font-tdpfr"},
  6894. {".woff", 5, "application/font-woff"},
  6895. /* audio */
  6896. {".mp3", 4, "audio/mpeg"},
  6897. {".oga", 4, "audio/ogg"},
  6898. {".ogg", 4, "audio/ogg"},
  6899. /* image */
  6900. {".gif", 4, "image/gif"},
  6901. {".ief", 4, "image/ief"},
  6902. {".jpeg", 5, "image/jpeg"},
  6903. {".jpg", 4, "image/jpeg"},
  6904. {".jpm", 4, "image/jpm"},
  6905. {".jpx", 4, "image/jpx"},
  6906. {".png", 4, "image/png"},
  6907. {".svg", 4, "image/svg+xml"},
  6908. {".tif", 4, "image/tiff"},
  6909. {".tiff", 5, "image/tiff"},
  6910. /* model */
  6911. {".wrl", 4, "model/vrml"},
  6912. /* text */
  6913. {".css", 4, "text/css"},
  6914. {".csv", 4, "text/csv"},
  6915. {".htm", 4, "text/html"},
  6916. {".html", 5, "text/html"},
  6917. {".sgm", 4, "text/sgml"},
  6918. {".shtm", 5, "text/html"},
  6919. {".shtml", 6, "text/html"},
  6920. {".txt", 4, "text/plain"},
  6921. {".xml", 4, "text/xml"},
  6922. /* video */
  6923. {".mov", 4, "video/quicktime"},
  6924. {".mp4", 4, "video/mp4"},
  6925. {".mpeg", 5, "video/mpeg"},
  6926. {".mpg", 4, "video/mpeg"},
  6927. {".ogv", 4, "video/ogg"},
  6928. {".qt", 3, "video/quicktime"},
  6929. /* not registered types
  6930. * (http://reference.sitepoint.com/html/mime-types-full,
  6931. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6932. {".arj", 4, "application/x-arj-compressed"},
  6933. {".gz", 3, "application/x-gunzip"},
  6934. {".rar", 4, "application/x-arj-compressed"},
  6935. {".swf", 4, "application/x-shockwave-flash"},
  6936. {".tar", 4, "application/x-tar"},
  6937. {".tgz", 4, "application/x-tar-gz"},
  6938. {".torrent", 8, "application/x-bittorrent"},
  6939. {".ppt", 4, "application/x-mspowerpoint"},
  6940. {".xls", 4, "application/x-msexcel"},
  6941. {".zip", 4, "application/x-zip-compressed"},
  6942. {".aac",
  6943. 4,
  6944. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6945. {".aif", 4, "audio/x-aif"},
  6946. {".m3u", 4, "audio/x-mpegurl"},
  6947. {".mid", 4, "audio/x-midi"},
  6948. {".ra", 3, "audio/x-pn-realaudio"},
  6949. {".ram", 4, "audio/x-pn-realaudio"},
  6950. {".wav", 4, "audio/x-wav"},
  6951. {".bmp", 4, "image/bmp"},
  6952. {".ico", 4, "image/x-icon"},
  6953. {".pct", 4, "image/x-pct"},
  6954. {".pict", 5, "image/pict"},
  6955. {".rgb", 4, "image/x-rgb"},
  6956. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6957. {".asf", 4, "video/x-ms-asf"},
  6958. {".avi", 4, "video/x-msvideo"},
  6959. {".m4v", 4, "video/x-m4v"},
  6960. {NULL, 0, NULL}};
  6961. const char *
  6962. mg_get_builtin_mime_type(const char *path)
  6963. {
  6964. const char *ext;
  6965. size_t i, path_len;
  6966. path_len = strlen(path);
  6967. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6968. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6969. if ((path_len > builtin_mime_types[i].ext_len)
  6970. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6971. return builtin_mime_types[i].mime_type;
  6972. }
  6973. }
  6974. return "text/plain";
  6975. }
  6976. /* Look at the "path" extension and figure what mime type it has.
  6977. * Store mime type in the vector. */
  6978. static void
  6979. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6980. {
  6981. struct vec ext_vec, mime_vec;
  6982. const char *list, *ext;
  6983. size_t path_len;
  6984. path_len = strlen(path);
  6985. if ((conn == NULL) || (vec == NULL)) {
  6986. if (vec != NULL) {
  6987. memset(vec, '\0', sizeof(struct vec));
  6988. }
  6989. return;
  6990. }
  6991. /* Scan user-defined mime types first, in case user wants to
  6992. * override default mime types. */
  6993. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6994. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6995. /* ext now points to the path suffix */
  6996. ext = path + path_len - ext_vec.len;
  6997. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6998. *vec = mime_vec;
  6999. return;
  7000. }
  7001. }
  7002. vec->ptr = mg_get_builtin_mime_type(path);
  7003. vec->len = strlen(vec->ptr);
  7004. }
  7005. /* Stringify binary data. Output buffer must be twice as big as input,
  7006. * because each byte takes 2 bytes in string representation */
  7007. static void
  7008. bin2str(char *to, const unsigned char *p, size_t len)
  7009. {
  7010. static const char *hex = "0123456789abcdef";
  7011. for (; len--; p++) {
  7012. *to++ = hex[p[0] >> 4];
  7013. *to++ = hex[p[0] & 0x0f];
  7014. }
  7015. *to = '\0';
  7016. }
  7017. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7018. */
  7019. char *
  7020. mg_md5(char buf[33], ...)
  7021. {
  7022. md5_byte_t hash[16];
  7023. const char *p;
  7024. va_list ap;
  7025. md5_state_t ctx;
  7026. md5_init(&ctx);
  7027. va_start(ap, buf);
  7028. while ((p = va_arg(ap, const char *)) != NULL) {
  7029. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7030. }
  7031. va_end(ap);
  7032. md5_finish(&ctx, hash);
  7033. bin2str(buf, hash, sizeof(hash));
  7034. return buf;
  7035. }
  7036. /* Check the user's password, return 1 if OK */
  7037. static int
  7038. check_password(const char *method,
  7039. const char *ha1,
  7040. const char *uri,
  7041. const char *nonce,
  7042. const char *nc,
  7043. const char *cnonce,
  7044. const char *qop,
  7045. const char *response)
  7046. {
  7047. char ha2[32 + 1], expected_response[32 + 1];
  7048. /* Some of the parameters may be NULL */
  7049. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7050. || (qop == NULL) || (response == NULL)) {
  7051. return 0;
  7052. }
  7053. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7054. if (strlen(response) != 32) {
  7055. return 0;
  7056. }
  7057. mg_md5(ha2, method, ":", uri, NULL);
  7058. mg_md5(expected_response,
  7059. ha1,
  7060. ":",
  7061. nonce,
  7062. ":",
  7063. nc,
  7064. ":",
  7065. cnonce,
  7066. ":",
  7067. qop,
  7068. ":",
  7069. ha2,
  7070. NULL);
  7071. return mg_strcasecmp(response, expected_response) == 0;
  7072. }
  7073. #if !defined(NO_FILESYSTEMS)
  7074. /* Use the global passwords file, if specified by auth_gpass option,
  7075. * or search for .htpasswd in the requested directory. */
  7076. static void
  7077. open_auth_file(struct mg_connection *conn,
  7078. const char *path,
  7079. struct mg_file *filep)
  7080. {
  7081. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7082. char name[PATH_MAX];
  7083. const char *p, *e,
  7084. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7085. int truncated;
  7086. if (gpass != NULL) {
  7087. /* Use global passwords file */
  7088. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7089. #if defined(DEBUG)
  7090. /* Use mg_cry_internal here, since gpass has been configured. */
  7091. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7092. #endif
  7093. }
  7094. /* Important: using local struct mg_file to test path for
  7095. * is_directory flag. If filep is used, mg_stat() makes it
  7096. * appear as if auth file was opened.
  7097. * TODO(mid): Check if this is still required after rewriting
  7098. * mg_stat */
  7099. } else if (mg_stat(conn, path, &filep->stat)
  7100. && filep->stat.is_directory) {
  7101. mg_snprintf(conn,
  7102. &truncated,
  7103. name,
  7104. sizeof(name),
  7105. "%s/%s",
  7106. path,
  7107. PASSWORDS_FILE_NAME);
  7108. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7109. #if defined(DEBUG)
  7110. /* Don't use mg_cry_internal here, but only a trace, since this
  7111. * is
  7112. * a typical case. It will occur for every directory
  7113. * without a password file. */
  7114. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7115. #endif
  7116. }
  7117. } else {
  7118. /* Try to find .htpasswd in requested directory. */
  7119. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7120. if (e[0] == '/') {
  7121. break;
  7122. }
  7123. }
  7124. mg_snprintf(conn,
  7125. &truncated,
  7126. name,
  7127. sizeof(name),
  7128. "%.*s/%s",
  7129. (int)(e - p),
  7130. p,
  7131. PASSWORDS_FILE_NAME);
  7132. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7133. #if defined(DEBUG)
  7134. /* Don't use mg_cry_internal here, but only a trace, since this
  7135. * is
  7136. * a typical case. It will occur for every directory
  7137. * without a password file. */
  7138. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7139. #endif
  7140. }
  7141. }
  7142. }
  7143. }
  7144. #endif /* NO_FILESYSTEMS */
  7145. /* Parsed Authorization header */
  7146. struct ah {
  7147. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7148. };
  7149. /* Return 1 on success. Always initializes the ah structure. */
  7150. static int
  7151. parse_auth_header(struct mg_connection *conn,
  7152. char *buf,
  7153. size_t buf_size,
  7154. struct ah *ah)
  7155. {
  7156. char *name, *value, *s;
  7157. const char *auth_header;
  7158. uint64_t nonce;
  7159. if (!ah || !conn) {
  7160. return 0;
  7161. }
  7162. (void)memset(ah, 0, sizeof(*ah));
  7163. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7164. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7165. return 0;
  7166. }
  7167. /* Make modifiable copy of the auth header */
  7168. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7169. s = buf;
  7170. /* Parse authorization header */
  7171. for (;;) {
  7172. /* Gobble initial spaces */
  7173. while (isspace((unsigned char)*s)) {
  7174. s++;
  7175. }
  7176. name = skip_quoted(&s, "=", " ", 0);
  7177. /* Value is either quote-delimited, or ends at first comma or space.
  7178. */
  7179. if (s[0] == '\"') {
  7180. s++;
  7181. value = skip_quoted(&s, "\"", " ", '\\');
  7182. if (s[0] == ',') {
  7183. s++;
  7184. }
  7185. } else {
  7186. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  7187. * spaces */
  7188. }
  7189. if (*name == '\0') {
  7190. break;
  7191. }
  7192. if (!strcmp(name, "username")) {
  7193. ah->user = value;
  7194. } else if (!strcmp(name, "cnonce")) {
  7195. ah->cnonce = value;
  7196. } else if (!strcmp(name, "response")) {
  7197. ah->response = value;
  7198. } else if (!strcmp(name, "uri")) {
  7199. ah->uri = value;
  7200. } else if (!strcmp(name, "qop")) {
  7201. ah->qop = value;
  7202. } else if (!strcmp(name, "nc")) {
  7203. ah->nc = value;
  7204. } else if (!strcmp(name, "nonce")) {
  7205. ah->nonce = value;
  7206. }
  7207. }
  7208. #if !defined(NO_NONCE_CHECK)
  7209. /* Read the nonce from the response. */
  7210. if (ah->nonce == NULL) {
  7211. return 0;
  7212. }
  7213. s = NULL;
  7214. nonce = strtoull(ah->nonce, &s, 10);
  7215. if ((s == NULL) || (*s != 0)) {
  7216. return 0;
  7217. }
  7218. /* Convert the nonce from the client to a number. */
  7219. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7220. /* The converted number corresponds to the time the nounce has been
  7221. * created. This should not be earlier than the server start. */
  7222. /* Server side nonce check is valuable in all situations but one:
  7223. * if the server restarts frequently, but the client should not see
  7224. * that, so the server should accept nonces from previous starts. */
  7225. /* However, the reasonable default is to not accept a nonce from a
  7226. * previous start, so if anyone changed the access rights between
  7227. * two restarts, a new login is required. */
  7228. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7229. /* nonce is from a previous start of the server and no longer valid
  7230. * (replay attack?) */
  7231. return 0;
  7232. }
  7233. /* Check if the nonce is too high, so it has not (yet) been used by the
  7234. * server. */
  7235. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7236. + conn->dom_ctx->nonce_count)) {
  7237. return 0;
  7238. }
  7239. #else
  7240. (void)nonce;
  7241. #endif
  7242. /* CGI needs it as REMOTE_USER */
  7243. if (ah->user != NULL) {
  7244. conn->request_info.remote_user =
  7245. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7246. } else {
  7247. return 0;
  7248. }
  7249. return 1;
  7250. }
  7251. static const char *
  7252. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7253. {
  7254. #if defined(MG_USE_OPEN_FILE)
  7255. const char *eof;
  7256. size_t len;
  7257. const char *memend;
  7258. #else
  7259. (void)p; /* parameter is unused */
  7260. #endif
  7261. if (!filep) {
  7262. return NULL;
  7263. }
  7264. #if defined(MG_USE_OPEN_FILE)
  7265. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7266. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7267. /* Search for \n from p till the end of stream */
  7268. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7269. if (eof != NULL) {
  7270. eof += 1; /* Include \n */
  7271. } else {
  7272. eof = memend; /* Copy remaining data */
  7273. }
  7274. len =
  7275. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7276. memcpy(buf, *p, len);
  7277. buf[len] = '\0';
  7278. *p += len;
  7279. return len ? eof : NULL;
  7280. } else /* filep->access.fp block below */
  7281. #endif
  7282. if (filep->access.fp != NULL) {
  7283. return fgets(buf, (int)size, filep->access.fp);
  7284. } else {
  7285. return NULL;
  7286. }
  7287. }
  7288. /* Define the initial recursion depth for procesesing htpasswd files that
  7289. * include other htpasswd
  7290. * (or even the same) files. It is not difficult to provide a file or files
  7291. * s.t. they force civetweb
  7292. * to infinitely recurse and then crash.
  7293. */
  7294. #define INITIAL_DEPTH 9
  7295. #if INITIAL_DEPTH <= 0
  7296. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7297. #endif
  7298. #if !defined(NO_FILESYSTEMS)
  7299. struct read_auth_file_struct {
  7300. struct mg_connection *conn;
  7301. struct ah ah;
  7302. const char *domain;
  7303. char buf[256 + 256 + 40];
  7304. const char *f_user;
  7305. const char *f_domain;
  7306. const char *f_ha1;
  7307. };
  7308. static int
  7309. read_auth_file(struct mg_file *filep,
  7310. struct read_auth_file_struct *workdata,
  7311. int depth)
  7312. {
  7313. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7314. int is_authorized = 0;
  7315. struct mg_file fp;
  7316. size_t l;
  7317. if (!filep || !workdata || (0 == depth)) {
  7318. return 0;
  7319. }
  7320. /* Loop over passwords file */
  7321. #if defined(MG_USE_OPEN_FILE)
  7322. p = (char *)filep->access.membuf;
  7323. #endif
  7324. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7325. l = strlen(workdata->buf);
  7326. while (l > 0) {
  7327. if (isspace((unsigned char)workdata->buf[l - 1])
  7328. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7329. l--;
  7330. workdata->buf[l] = 0;
  7331. } else
  7332. break;
  7333. }
  7334. if (l < 1) {
  7335. continue;
  7336. }
  7337. workdata->f_user = workdata->buf;
  7338. if (workdata->f_user[0] == ':') {
  7339. /* user names may not contain a ':' and may not be empty,
  7340. * so lines starting with ':' may be used for a special purpose
  7341. */
  7342. if (workdata->f_user[1] == '#') {
  7343. /* :# is a comment */
  7344. continue;
  7345. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7346. if (mg_fopen(workdata->conn,
  7347. workdata->f_user + 9,
  7348. MG_FOPEN_MODE_READ,
  7349. &fp)) {
  7350. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7351. (void)mg_fclose(
  7352. &fp.access); /* ignore error on read only file */
  7353. /* No need to continue processing files once we have a
  7354. * match, since nothing will reset it back
  7355. * to 0.
  7356. */
  7357. if (is_authorized) {
  7358. return is_authorized;
  7359. }
  7360. } else {
  7361. mg_cry_internal(workdata->conn,
  7362. "%s: cannot open authorization file: %s",
  7363. __func__,
  7364. workdata->buf);
  7365. }
  7366. continue;
  7367. }
  7368. /* everything is invalid for the moment (might change in the
  7369. * future) */
  7370. mg_cry_internal(workdata->conn,
  7371. "%s: syntax error in authorization file: %s",
  7372. __func__,
  7373. workdata->buf);
  7374. continue;
  7375. }
  7376. workdata->f_domain = strchr(workdata->f_user, ':');
  7377. if (workdata->f_domain == NULL) {
  7378. mg_cry_internal(workdata->conn,
  7379. "%s: syntax error in authorization file: %s",
  7380. __func__,
  7381. workdata->buf);
  7382. continue;
  7383. }
  7384. *(char *)(workdata->f_domain) = 0;
  7385. (workdata->f_domain)++;
  7386. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7387. if (workdata->f_ha1 == NULL) {
  7388. mg_cry_internal(workdata->conn,
  7389. "%s: syntax error in authorization file: %s",
  7390. __func__,
  7391. workdata->buf);
  7392. continue;
  7393. }
  7394. *(char *)(workdata->f_ha1) = 0;
  7395. (workdata->f_ha1)++;
  7396. if (!strcmp(workdata->ah.user, workdata->f_user)
  7397. && !strcmp(workdata->domain, workdata->f_domain)) {
  7398. return check_password(workdata->conn->request_info.request_method,
  7399. workdata->f_ha1,
  7400. workdata->ah.uri,
  7401. workdata->ah.nonce,
  7402. workdata->ah.nc,
  7403. workdata->ah.cnonce,
  7404. workdata->ah.qop,
  7405. workdata->ah.response);
  7406. }
  7407. }
  7408. return is_authorized;
  7409. }
  7410. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7411. static int
  7412. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7413. {
  7414. struct read_auth_file_struct workdata;
  7415. char buf[MG_BUF_LEN];
  7416. if (!conn || !conn->dom_ctx) {
  7417. return 0;
  7418. }
  7419. memset(&workdata, 0, sizeof(workdata));
  7420. workdata.conn = conn;
  7421. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7422. return 0;
  7423. }
  7424. if (realm) {
  7425. workdata.domain = realm;
  7426. } else {
  7427. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7428. }
  7429. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7430. }
  7431. /* Public function to check http digest authentication header */
  7432. int
  7433. mg_check_digest_access_authentication(struct mg_connection *conn,
  7434. const char *realm,
  7435. const char *filename)
  7436. {
  7437. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7438. int auth;
  7439. if (!conn || !filename) {
  7440. return -1;
  7441. }
  7442. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7443. return -2;
  7444. }
  7445. auth = authorize(conn, &file, realm);
  7446. mg_fclose(&file.access);
  7447. return auth;
  7448. }
  7449. #endif /* NO_FILESYSTEMS */
  7450. /* Return 1 if request is authorised, 0 otherwise. */
  7451. static int
  7452. check_authorization(struct mg_connection *conn, const char *path)
  7453. {
  7454. #if !defined(NO_FILESYSTEMS)
  7455. char fname[PATH_MAX];
  7456. struct vec uri_vec, filename_vec;
  7457. const char *list;
  7458. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7459. int authorized = 1, truncated;
  7460. if (!conn || !conn->dom_ctx) {
  7461. return 0;
  7462. }
  7463. list = conn->dom_ctx->config[PROTECT_URI];
  7464. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7465. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7466. mg_snprintf(conn,
  7467. &truncated,
  7468. fname,
  7469. sizeof(fname),
  7470. "%.*s",
  7471. (int)filename_vec.len,
  7472. filename_vec.ptr);
  7473. if (truncated
  7474. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7475. mg_cry_internal(conn,
  7476. "%s: cannot open %s: %s",
  7477. __func__,
  7478. fname,
  7479. strerror(errno));
  7480. }
  7481. break;
  7482. }
  7483. }
  7484. if (!is_file_opened(&file.access)) {
  7485. open_auth_file(conn, path, &file);
  7486. }
  7487. if (is_file_opened(&file.access)) {
  7488. authorized = authorize(conn, &file, NULL);
  7489. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7490. }
  7491. return authorized;
  7492. #else
  7493. (void)conn;
  7494. (void)path;
  7495. return 1;
  7496. #endif /* NO_FILESYSTEMS */
  7497. }
  7498. /* Internal function. Assumes conn is valid */
  7499. static void
  7500. send_authorization_request(struct mg_connection *conn, const char *realm)
  7501. {
  7502. char date[64];
  7503. time_t curtime = time(NULL);
  7504. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7505. if (!realm) {
  7506. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7507. }
  7508. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7509. nonce += conn->dom_ctx->nonce_count;
  7510. ++conn->dom_ctx->nonce_count;
  7511. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7512. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7513. conn->status_code = 401;
  7514. conn->must_close = 1;
  7515. gmt_time_string(date, sizeof(date), &curtime);
  7516. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7517. send_no_cache_header(conn);
  7518. send_additional_header(conn);
  7519. mg_printf(conn,
  7520. "Date: %s\r\n"
  7521. "Connection: %s\r\n"
  7522. "Content-Length: 0\r\n"
  7523. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7524. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7525. date,
  7526. suggest_connection_header(conn),
  7527. realm,
  7528. nonce);
  7529. }
  7530. /* Interface function. Parameters are provided by the user, so do
  7531. * at least some basic checks.
  7532. */
  7533. int
  7534. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7535. const char *realm)
  7536. {
  7537. if (conn && conn->dom_ctx) {
  7538. send_authorization_request(conn, realm);
  7539. return 0;
  7540. }
  7541. return -1;
  7542. }
  7543. #if !defined(NO_FILES)
  7544. static int
  7545. is_authorized_for_put(struct mg_connection *conn)
  7546. {
  7547. if (conn) {
  7548. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7549. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7550. int ret = 0;
  7551. if (passfile != NULL
  7552. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7553. ret = authorize(conn, &file, NULL);
  7554. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7555. }
  7556. return ret;
  7557. }
  7558. return 0;
  7559. }
  7560. #endif
  7561. int
  7562. mg_modify_passwords_file(const char *fname,
  7563. const char *domain,
  7564. const char *user,
  7565. const char *pass)
  7566. {
  7567. int found, i;
  7568. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7569. FILE *fp, *fp2;
  7570. found = 0;
  7571. fp = fp2 = NULL;
  7572. /* Regard empty password as no password - remove user record. */
  7573. if ((pass != NULL) && (pass[0] == '\0')) {
  7574. pass = NULL;
  7575. }
  7576. /* Other arguments must not be empty */
  7577. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7578. return 0;
  7579. }
  7580. /* Using the given file format, user name and domain must not contain
  7581. * ':'
  7582. */
  7583. if (strchr(user, ':') != NULL) {
  7584. return 0;
  7585. }
  7586. if (strchr(domain, ':') != NULL) {
  7587. return 0;
  7588. }
  7589. /* Do not allow control characters like newline in user name and domain.
  7590. * Do not allow excessively long names either. */
  7591. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7592. if (iscntrl((unsigned char)user[i])) {
  7593. return 0;
  7594. }
  7595. }
  7596. if (user[i]) {
  7597. return 0;
  7598. }
  7599. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7600. if (iscntrl((unsigned char)domain[i])) {
  7601. return 0;
  7602. }
  7603. }
  7604. if (domain[i]) {
  7605. return 0;
  7606. }
  7607. /* The maximum length of the path to the password file is limited */
  7608. if ((strlen(fname) + 4) >= PATH_MAX) {
  7609. return 0;
  7610. }
  7611. /* Create a temporary file name. Length has been checked before. */
  7612. strcpy(tmp, fname);
  7613. strcat(tmp, ".tmp");
  7614. /* Create the file if does not exist */
  7615. /* Use of fopen here is OK, since fname is only ASCII */
  7616. if ((fp = fopen(fname, "a+")) != NULL) {
  7617. (void)fclose(fp);
  7618. }
  7619. /* Open the given file and temporary file */
  7620. if ((fp = fopen(fname, "r")) == NULL) {
  7621. return 0;
  7622. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7623. fclose(fp);
  7624. return 0;
  7625. }
  7626. /* Copy the stuff to temporary file */
  7627. while (fgets(line, sizeof(line), fp) != NULL) {
  7628. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7629. continue;
  7630. }
  7631. u[255] = 0;
  7632. d[255] = 0;
  7633. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7634. found++;
  7635. if (pass != NULL) {
  7636. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7637. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7638. }
  7639. } else {
  7640. fprintf(fp2, "%s", line);
  7641. }
  7642. }
  7643. /* If new user, just add it */
  7644. if (!found && (pass != NULL)) {
  7645. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7646. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7647. }
  7648. /* Close files */
  7649. fclose(fp);
  7650. fclose(fp2);
  7651. /* Put the temp file in place of real file */
  7652. IGNORE_UNUSED_RESULT(remove(fname));
  7653. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7654. return 1;
  7655. }
  7656. static int
  7657. is_valid_port(unsigned long port)
  7658. {
  7659. return (port <= 0xffff);
  7660. }
  7661. static int
  7662. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7663. {
  7664. struct addrinfo hints, *res, *ressave;
  7665. int func_ret = 0;
  7666. int gai_ret;
  7667. memset(&hints, 0, sizeof(struct addrinfo));
  7668. hints.ai_family = af;
  7669. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7670. if (gai_ret != 0) {
  7671. /* gai_strerror could be used to convert gai_ret to a string */
  7672. /* POSIX return values: see
  7673. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7674. */
  7675. /* Windows return values: see
  7676. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7677. */
  7678. return 0;
  7679. }
  7680. ressave = res;
  7681. while (res) {
  7682. if (dstlen >= (size_t)res->ai_addrlen) {
  7683. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7684. func_ret = 1;
  7685. }
  7686. res = res->ai_next;
  7687. }
  7688. freeaddrinfo(ressave);
  7689. return func_ret;
  7690. }
  7691. static int
  7692. connect_socket(struct mg_context *ctx /* may be NULL */,
  7693. const char *host,
  7694. int port,
  7695. int use_ssl,
  7696. char *ebuf,
  7697. size_t ebuf_len,
  7698. SOCKET *sock /* output: socket, must not be NULL */,
  7699. union usa *sa /* output: socket address, must not be NULL */
  7700. )
  7701. {
  7702. int ip_ver = 0;
  7703. int conn_ret = -1;
  7704. int sockerr = 0;
  7705. *sock = INVALID_SOCKET;
  7706. memset(sa, 0, sizeof(*sa));
  7707. if (ebuf_len > 0) {
  7708. *ebuf = 0;
  7709. }
  7710. if (host == NULL) {
  7711. mg_snprintf(NULL,
  7712. NULL, /* No truncation check for ebuf */
  7713. ebuf,
  7714. ebuf_len,
  7715. "%s",
  7716. "NULL host");
  7717. return 0;
  7718. }
  7719. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7720. mg_snprintf(NULL,
  7721. NULL, /* No truncation check for ebuf */
  7722. ebuf,
  7723. ebuf_len,
  7724. "%s",
  7725. "invalid port");
  7726. return 0;
  7727. }
  7728. #if !defined(NO_SSL)
  7729. #if !defined(NO_SSL_DL)
  7730. #if defined(OPENSSL_API_1_1)
  7731. if (use_ssl && (TLS_client_method == NULL)) {
  7732. mg_snprintf(NULL,
  7733. NULL, /* No truncation check for ebuf */
  7734. ebuf,
  7735. ebuf_len,
  7736. "%s",
  7737. "SSL is not initialized");
  7738. return 0;
  7739. }
  7740. #else
  7741. if (use_ssl && (SSLv23_client_method == NULL)) {
  7742. mg_snprintf(NULL,
  7743. NULL, /* No truncation check for ebuf */
  7744. ebuf,
  7745. ebuf_len,
  7746. "%s",
  7747. "SSL is not initialized");
  7748. return 0;
  7749. }
  7750. #endif /* OPENSSL_API_1_1 */
  7751. #else
  7752. (void)use_ssl;
  7753. #endif /* NO_SSL_DL */
  7754. #else
  7755. (void)use_ssl;
  7756. #endif /* !defined(NO_SSL) */
  7757. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7758. sa->sin.sin_family = AF_INET;
  7759. sa->sin.sin_port = htons((uint16_t)port);
  7760. ip_ver = 4;
  7761. #if defined(USE_IPV6)
  7762. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7763. sa->sin6.sin6_family = AF_INET6;
  7764. sa->sin6.sin6_port = htons((uint16_t)port);
  7765. ip_ver = 6;
  7766. } else if (host[0] == '[') {
  7767. /* While getaddrinfo on Windows will work with [::1],
  7768. * getaddrinfo on Linux only works with ::1 (without []). */
  7769. size_t l = strlen(host + 1);
  7770. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7771. if (h) {
  7772. h[l - 1] = 0;
  7773. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7774. sa->sin6.sin6_family = AF_INET6;
  7775. sa->sin6.sin6_port = htons((uint16_t)port);
  7776. ip_ver = 6;
  7777. }
  7778. mg_free(h);
  7779. }
  7780. #endif
  7781. }
  7782. if (ip_ver == 0) {
  7783. mg_snprintf(NULL,
  7784. NULL, /* No truncation check for ebuf */
  7785. ebuf,
  7786. ebuf_len,
  7787. "%s",
  7788. "host not found");
  7789. return 0;
  7790. }
  7791. if (ip_ver == 4) {
  7792. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7793. }
  7794. #if defined(USE_IPV6)
  7795. else if (ip_ver == 6) {
  7796. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7797. }
  7798. #endif
  7799. if (*sock == INVALID_SOCKET) {
  7800. mg_snprintf(NULL,
  7801. NULL, /* No truncation check for ebuf */
  7802. ebuf,
  7803. ebuf_len,
  7804. "socket(): %s",
  7805. strerror(ERRNO));
  7806. return 0;
  7807. }
  7808. if (0 != set_non_blocking_mode(*sock)) {
  7809. mg_snprintf(NULL,
  7810. NULL, /* No truncation check for ebuf */
  7811. ebuf,
  7812. ebuf_len,
  7813. "Cannot set socket to non-blocking: %s",
  7814. strerror(ERRNO));
  7815. closesocket(*sock);
  7816. *sock = INVALID_SOCKET;
  7817. return 0;
  7818. }
  7819. set_close_on_exec(*sock, NULL, ctx);
  7820. if (ip_ver == 4) {
  7821. /* connected with IPv4 */
  7822. conn_ret = connect(*sock,
  7823. (struct sockaddr *)((void *)&sa->sin),
  7824. sizeof(sa->sin));
  7825. }
  7826. #if defined(USE_IPV6)
  7827. else if (ip_ver == 6) {
  7828. /* connected with IPv6 */
  7829. conn_ret = connect(*sock,
  7830. (struct sockaddr *)((void *)&sa->sin6),
  7831. sizeof(sa->sin6));
  7832. }
  7833. #endif
  7834. if (conn_ret != 0) {
  7835. sockerr = ERRNO;
  7836. }
  7837. #if defined(_WIN32)
  7838. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7839. #else
  7840. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7841. #endif
  7842. /* Data for getsockopt */
  7843. void *psockerr = &sockerr;
  7844. int ret;
  7845. #if defined(_WIN32)
  7846. int len = (int)sizeof(sockerr);
  7847. #else
  7848. socklen_t len = (socklen_t)sizeof(sockerr);
  7849. #endif
  7850. /* Data for poll */
  7851. struct mg_pollfd pfd[1];
  7852. int pollres;
  7853. int ms_wait = 10000; /* 10 second timeout */
  7854. int nonstop = 0;
  7855. /* For a non-blocking socket, the connect sequence is:
  7856. * 1) call connect (will not block)
  7857. * 2) wait until the socket is ready for writing (select or poll)
  7858. * 3) check connection state with getsockopt
  7859. */
  7860. pfd[0].fd = *sock;
  7861. pfd[0].events = POLLOUT;
  7862. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7863. if (pollres != 1) {
  7864. /* Not connected */
  7865. mg_snprintf(NULL,
  7866. NULL, /* No truncation check for ebuf */
  7867. ebuf,
  7868. ebuf_len,
  7869. "connect(%s:%d): timeout",
  7870. host,
  7871. port);
  7872. closesocket(*sock);
  7873. *sock = INVALID_SOCKET;
  7874. return 0;
  7875. }
  7876. #if defined(_WIN32)
  7877. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7878. #else
  7879. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7880. #endif
  7881. if ((ret == 0) && (sockerr == 0)) {
  7882. conn_ret = 0;
  7883. }
  7884. }
  7885. if (conn_ret != 0) {
  7886. /* Not connected */
  7887. mg_snprintf(NULL,
  7888. NULL, /* No truncation check for ebuf */
  7889. ebuf,
  7890. ebuf_len,
  7891. "connect(%s:%d): error %s",
  7892. host,
  7893. port,
  7894. strerror(sockerr));
  7895. closesocket(*sock);
  7896. *sock = INVALID_SOCKET;
  7897. return 0;
  7898. }
  7899. return 1;
  7900. }
  7901. int
  7902. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7903. {
  7904. static const char *dont_escape = "._-$,;~()";
  7905. static const char *hex = "0123456789abcdef";
  7906. char *pos = dst;
  7907. const char *end = dst + dst_len - 1;
  7908. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7909. if (isalnum((unsigned char)*src)
  7910. || (strchr(dont_escape, *src) != NULL)) {
  7911. *pos = *src;
  7912. } else if (pos + 2 < end) {
  7913. pos[0] = '%';
  7914. pos[1] = hex[(unsigned char)*src >> 4];
  7915. pos[2] = hex[(unsigned char)*src & 0xf];
  7916. pos += 2;
  7917. } else {
  7918. break;
  7919. }
  7920. }
  7921. *pos = '\0';
  7922. return (*src == '\0') ? (int)(pos - dst) : -1;
  7923. }
  7924. /* Return 0 on success, non-zero if an error occurs. */
  7925. static int
  7926. print_dir_entry(struct de *de)
  7927. {
  7928. size_t namesize, escsize, i;
  7929. char *href, *esc, *p;
  7930. char size[64], mod[64];
  7931. #if defined(REENTRANT_TIME)
  7932. struct tm _tm;
  7933. struct tm *tm = &_tm;
  7934. #else
  7935. struct tm *tm;
  7936. #endif
  7937. /* Estimate worst case size for encoding and escaping */
  7938. namesize = strlen(de->file_name) + 1;
  7939. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7940. href = (char *)mg_malloc(namesize * 3 + escsize);
  7941. if (href == NULL) {
  7942. return -1;
  7943. }
  7944. mg_url_encode(de->file_name, href, namesize * 3);
  7945. esc = NULL;
  7946. if (escsize > 0) {
  7947. /* HTML escaping needed */
  7948. esc = href + namesize * 3;
  7949. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7950. mg_strlcpy(p, de->file_name + i, 2);
  7951. if (*p == '&') {
  7952. strcpy(p, "&amp;");
  7953. } else if (*p == '<') {
  7954. strcpy(p, "&lt;");
  7955. } else if (*p == '>') {
  7956. strcpy(p, "&gt;");
  7957. }
  7958. }
  7959. }
  7960. if (de->file.is_directory) {
  7961. mg_snprintf(de->conn,
  7962. NULL, /* Buffer is big enough */
  7963. size,
  7964. sizeof(size),
  7965. "%s",
  7966. "[DIRECTORY]");
  7967. } else {
  7968. /* We use (signed) cast below because MSVC 6 compiler cannot
  7969. * convert unsigned __int64 to double. Sigh. */
  7970. if (de->file.size < 1024) {
  7971. mg_snprintf(de->conn,
  7972. NULL, /* Buffer is big enough */
  7973. size,
  7974. sizeof(size),
  7975. "%d",
  7976. (int)de->file.size);
  7977. } else if (de->file.size < 0x100000) {
  7978. mg_snprintf(de->conn,
  7979. NULL, /* Buffer is big enough */
  7980. size,
  7981. sizeof(size),
  7982. "%.1fk",
  7983. (double)de->file.size / 1024.0);
  7984. } else if (de->file.size < 0x40000000) {
  7985. mg_snprintf(de->conn,
  7986. NULL, /* Buffer is big enough */
  7987. size,
  7988. sizeof(size),
  7989. "%.1fM",
  7990. (double)de->file.size / 1048576);
  7991. } else {
  7992. mg_snprintf(de->conn,
  7993. NULL, /* Buffer is big enough */
  7994. size,
  7995. sizeof(size),
  7996. "%.1fG",
  7997. (double)de->file.size / 1073741824);
  7998. }
  7999. }
  8000. /* Note: mg_snprintf will not cause a buffer overflow above.
  8001. * So, string truncation checks are not required here. */
  8002. #if defined(REENTRANT_TIME)
  8003. localtime_r(&de->file.last_modified, tm);
  8004. #else
  8005. tm = localtime(&de->file.last_modified);
  8006. #endif
  8007. if (tm != NULL) {
  8008. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8009. } else {
  8010. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8011. mod[sizeof(mod) - 1] = '\0';
  8012. }
  8013. mg_printf(de->conn,
  8014. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8015. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8016. href,
  8017. de->file.is_directory ? "/" : "",
  8018. esc ? esc : de->file_name,
  8019. de->file.is_directory ? "/" : "",
  8020. mod,
  8021. size);
  8022. mg_free(href);
  8023. return 0;
  8024. }
  8025. /* This function is called from send_directory() and used for
  8026. * sorting directory entries by size, or name, or modification time.
  8027. * On windows, __cdecl specification is needed in case if project is built
  8028. * with __stdcall convention. qsort always requires __cdels callback. */
  8029. static int WINCDECL
  8030. compare_dir_entries(const void *p1, const void *p2)
  8031. {
  8032. if (p1 && p2) {
  8033. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8034. const char *query_string = a->conn->request_info.query_string;
  8035. int cmp_result = 0;
  8036. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8037. query_string = "n";
  8038. }
  8039. if (a->file.is_directory && !b->file.is_directory) {
  8040. return -1; /* Always put directories on top */
  8041. } else if (!a->file.is_directory && b->file.is_directory) {
  8042. return 1; /* Always put directories on top */
  8043. } else if (*query_string == 'n') {
  8044. cmp_result = strcmp(a->file_name, b->file_name);
  8045. } else if (*query_string == 's') {
  8046. cmp_result = (a->file.size == b->file.size)
  8047. ? 0
  8048. : ((a->file.size > b->file.size) ? 1 : -1);
  8049. } else if (*query_string == 'd') {
  8050. cmp_result =
  8051. (a->file.last_modified == b->file.last_modified)
  8052. ? 0
  8053. : ((a->file.last_modified > b->file.last_modified) ? 1
  8054. : -1);
  8055. }
  8056. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8057. }
  8058. return 0;
  8059. }
  8060. static int
  8061. must_hide_file(struct mg_connection *conn, const char *path)
  8062. {
  8063. if (conn && conn->dom_ctx) {
  8064. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8065. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8066. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8067. || ((pattern != NULL)
  8068. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8069. }
  8070. return 0;
  8071. }
  8072. #if !defined(NO_FILESYSTEMS)
  8073. static int
  8074. scan_directory(struct mg_connection *conn,
  8075. const char *dir,
  8076. void *data,
  8077. int (*cb)(struct de *, void *))
  8078. {
  8079. char path[PATH_MAX];
  8080. struct dirent *dp;
  8081. DIR *dirp;
  8082. struct de de;
  8083. int truncated;
  8084. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8085. return 0;
  8086. } else {
  8087. de.conn = conn;
  8088. while ((dp = mg_readdir(dirp)) != NULL) {
  8089. /* Do not show current dir and hidden files */
  8090. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8091. || must_hide_file(conn, dp->d_name)) {
  8092. continue;
  8093. }
  8094. mg_snprintf(
  8095. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8096. /* If we don't memset stat structure to zero, mtime will have
  8097. * garbage and strftime() will segfault later on in
  8098. * print_dir_entry(). memset is required only if mg_stat()
  8099. * fails. For more details, see
  8100. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8101. memset(&de.file, 0, sizeof(de.file));
  8102. if (truncated) {
  8103. /* If the path is not complete, skip processing. */
  8104. continue;
  8105. }
  8106. if (!mg_stat(conn, path, &de.file)) {
  8107. mg_cry_internal(conn,
  8108. "%s: mg_stat(%s) failed: %s",
  8109. __func__,
  8110. path,
  8111. strerror(ERRNO));
  8112. }
  8113. de.file_name = dp->d_name;
  8114. cb(&de, data);
  8115. }
  8116. (void)mg_closedir(dirp);
  8117. }
  8118. return 1;
  8119. }
  8120. #endif /* NO_FILESYSTEMS */
  8121. #if !defined(NO_FILES)
  8122. static int
  8123. remove_directory(struct mg_connection *conn, const char *dir)
  8124. {
  8125. char path[PATH_MAX];
  8126. struct dirent *dp;
  8127. DIR *dirp;
  8128. struct de de;
  8129. int truncated;
  8130. int ok = 1;
  8131. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8132. return 0;
  8133. } else {
  8134. de.conn = conn;
  8135. while ((dp = mg_readdir(dirp)) != NULL) {
  8136. /* Do not show current dir (but show hidden files as they will
  8137. * also be removed) */
  8138. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8139. continue;
  8140. }
  8141. mg_snprintf(
  8142. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8143. /* If we don't memset stat structure to zero, mtime will have
  8144. * garbage and strftime() will segfault later on in
  8145. * print_dir_entry(). memset is required only if mg_stat()
  8146. * fails. For more details, see
  8147. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8148. memset(&de.file, 0, sizeof(de.file));
  8149. if (truncated) {
  8150. /* Do not delete anything shorter */
  8151. ok = 0;
  8152. continue;
  8153. }
  8154. if (!mg_stat(conn, path, &de.file)) {
  8155. mg_cry_internal(conn,
  8156. "%s: mg_stat(%s) failed: %s",
  8157. __func__,
  8158. path,
  8159. strerror(ERRNO));
  8160. ok = 0;
  8161. }
  8162. if (de.file.is_directory) {
  8163. if (remove_directory(conn, path) == 0) {
  8164. ok = 0;
  8165. }
  8166. } else {
  8167. /* This will fail file is the file is in memory */
  8168. if (mg_remove(conn, path) == 0) {
  8169. ok = 0;
  8170. }
  8171. }
  8172. }
  8173. (void)mg_closedir(dirp);
  8174. IGNORE_UNUSED_RESULT(rmdir(dir));
  8175. }
  8176. return ok;
  8177. }
  8178. #endif
  8179. struct dir_scan_data {
  8180. struct de *entries;
  8181. unsigned int num_entries;
  8182. unsigned int arr_size;
  8183. };
  8184. /* Behaves like realloc(), but frees original pointer on failure */
  8185. static void *
  8186. realloc2(void *ptr, size_t size)
  8187. {
  8188. void *new_ptr = mg_realloc(ptr, size);
  8189. if (new_ptr == NULL) {
  8190. mg_free(ptr);
  8191. }
  8192. return new_ptr;
  8193. }
  8194. #if !defined(NO_FILESYSTEMS)
  8195. static int
  8196. dir_scan_callback(struct de *de, void *data)
  8197. {
  8198. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8199. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8200. dsd->arr_size *= 2;
  8201. dsd->entries =
  8202. (struct de *)realloc2(dsd->entries,
  8203. dsd->arr_size * sizeof(dsd->entries[0]));
  8204. }
  8205. if (dsd->entries == NULL) {
  8206. /* TODO(lsm, low): propagate an error to the caller */
  8207. dsd->num_entries = 0;
  8208. } else {
  8209. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8210. dsd->entries[dsd->num_entries].file = de->file;
  8211. dsd->entries[dsd->num_entries].conn = de->conn;
  8212. dsd->num_entries++;
  8213. }
  8214. return 0;
  8215. }
  8216. static void
  8217. handle_directory_request(struct mg_connection *conn, const char *dir)
  8218. {
  8219. unsigned int i;
  8220. int sort_direction;
  8221. struct dir_scan_data data = {NULL, 0, 128};
  8222. char date[64], *esc, *p;
  8223. const char *title;
  8224. time_t curtime = time(NULL);
  8225. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8226. mg_send_http_error(conn,
  8227. 500,
  8228. "Error: Cannot open directory\nopendir(%s): %s",
  8229. dir,
  8230. strerror(ERRNO));
  8231. return;
  8232. }
  8233. gmt_time_string(date, sizeof(date), &curtime);
  8234. if (!conn) {
  8235. return;
  8236. }
  8237. esc = NULL;
  8238. title = conn->request_info.local_uri;
  8239. if (title[strcspn(title, "&<>")]) {
  8240. /* HTML escaping needed */
  8241. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8242. if (esc) {
  8243. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8244. mg_strlcpy(p, title + i, 2);
  8245. if (*p == '&') {
  8246. strcpy(p, "&amp;");
  8247. } else if (*p == '<') {
  8248. strcpy(p, "&lt;");
  8249. } else if (*p == '>') {
  8250. strcpy(p, "&gt;");
  8251. }
  8252. }
  8253. } else {
  8254. title = "";
  8255. }
  8256. }
  8257. sort_direction = ((conn->request_info.query_string != NULL)
  8258. && (conn->request_info.query_string[0] != '\0')
  8259. && (conn->request_info.query_string[1] == 'd'))
  8260. ? 'a'
  8261. : 'd';
  8262. conn->must_close = 1;
  8263. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8264. send_static_cache_header(conn);
  8265. send_additional_header(conn);
  8266. mg_printf(conn,
  8267. "Date: %s\r\n"
  8268. "Connection: close\r\n"
  8269. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8270. date);
  8271. mg_printf(conn,
  8272. "<html><head><title>Index of %s</title>"
  8273. "<style>th {text-align: left;}</style></head>"
  8274. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8275. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8276. "<th><a href=\"?d%c\">Modified</a></th>"
  8277. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8278. "<tr><td colspan=\"3\"><hr></td></tr>",
  8279. esc ? esc : title,
  8280. esc ? esc : title,
  8281. sort_direction,
  8282. sort_direction,
  8283. sort_direction);
  8284. mg_free(esc);
  8285. /* Print first entry - link to a parent directory */
  8286. mg_printf(conn,
  8287. "<tr><td><a href=\"%s\">%s</a></td>"
  8288. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8289. "..",
  8290. "Parent directory",
  8291. "-",
  8292. "-");
  8293. /* Sort and print directory entries */
  8294. if (data.entries != NULL) {
  8295. qsort(data.entries,
  8296. (size_t)data.num_entries,
  8297. sizeof(data.entries[0]),
  8298. compare_dir_entries);
  8299. for (i = 0; i < data.num_entries; i++) {
  8300. print_dir_entry(&data.entries[i]);
  8301. mg_free(data.entries[i].file_name);
  8302. }
  8303. mg_free(data.entries);
  8304. }
  8305. mg_printf(conn, "%s", "</table></pre></body></html>");
  8306. conn->status_code = 200;
  8307. }
  8308. #endif /* NO_FILESYSTEMS */
  8309. /* Send len bytes from the opened file to the client. */
  8310. static void
  8311. send_file_data(struct mg_connection *conn,
  8312. struct mg_file *filep,
  8313. int64_t offset,
  8314. int64_t len)
  8315. {
  8316. char buf[MG_BUF_LEN];
  8317. int to_read, num_read, num_written;
  8318. int64_t size;
  8319. if (!filep || !conn) {
  8320. return;
  8321. }
  8322. /* Sanity check the offset */
  8323. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8324. : (int64_t)(filep->stat.size);
  8325. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8326. #if defined(MG_USE_OPEN_FILE)
  8327. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8328. /* file stored in memory */
  8329. if (len > size - offset) {
  8330. len = size - offset;
  8331. }
  8332. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8333. } else /* else block below */
  8334. #endif
  8335. if (len > 0 && filep->access.fp != NULL) {
  8336. /* file stored on disk */
  8337. #if defined(__linux__)
  8338. /* sendfile is only available for Linux */
  8339. if ((conn->ssl == 0) && (conn->throttle == 0)
  8340. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8341. "yes"))) {
  8342. off_t sf_offs = (off_t)offset;
  8343. ssize_t sf_sent;
  8344. int sf_file = fileno(filep->access.fp);
  8345. int loop_cnt = 0;
  8346. do {
  8347. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8348. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8349. size_t sf_tosend =
  8350. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8351. sf_sent =
  8352. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8353. if (sf_sent > 0) {
  8354. len -= sf_sent;
  8355. offset += sf_sent;
  8356. } else if (loop_cnt == 0) {
  8357. /* This file can not be sent using sendfile.
  8358. * This might be the case for pseudo-files in the
  8359. * /sys/ and /proc/ file system.
  8360. * Use the regular user mode copy code instead. */
  8361. break;
  8362. } else if (sf_sent == 0) {
  8363. /* No error, but 0 bytes sent. May be EOF? */
  8364. return;
  8365. }
  8366. loop_cnt++;
  8367. } while ((len > 0) && (sf_sent >= 0));
  8368. if (sf_sent > 0) {
  8369. return; /* OK */
  8370. }
  8371. /* sf_sent<0 means error, thus fall back to the classic way */
  8372. /* This is always the case, if sf_file is not a "normal" file,
  8373. * e.g., for sending data from the output of a CGI process. */
  8374. offset = (int64_t)sf_offs;
  8375. }
  8376. #endif
  8377. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8378. mg_cry_internal(conn,
  8379. "%s: fseeko() failed: %s",
  8380. __func__,
  8381. strerror(ERRNO));
  8382. mg_send_http_error(
  8383. conn,
  8384. 500,
  8385. "%s",
  8386. "Error: Unable to access file at requested position.");
  8387. } else {
  8388. while (len > 0) {
  8389. /* Calculate how much to read from the file in the buffer */
  8390. to_read = sizeof(buf);
  8391. if ((int64_t)to_read > len) {
  8392. to_read = (int)len;
  8393. }
  8394. /* Read from file, exit the loop on error */
  8395. if ((num_read =
  8396. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8397. <= 0) {
  8398. break;
  8399. }
  8400. /* Send read bytes to the client, exit the loop on error */
  8401. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8402. != num_read) {
  8403. break;
  8404. }
  8405. /* Both read and were successful, adjust counters */
  8406. len -= num_written;
  8407. }
  8408. }
  8409. }
  8410. }
  8411. static int
  8412. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8413. {
  8414. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8415. }
  8416. static void
  8417. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8418. {
  8419. if ((filestat != NULL) && (buf != NULL)) {
  8420. mg_snprintf(NULL,
  8421. NULL, /* All calls to construct_etag use 64 byte buffer */
  8422. buf,
  8423. buf_len,
  8424. "\"%lx.%" INT64_FMT "\"",
  8425. (unsigned long)filestat->last_modified,
  8426. filestat->size);
  8427. }
  8428. }
  8429. static void
  8430. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8431. {
  8432. if (filep != NULL && filep->fp != NULL) {
  8433. #if defined(_WIN32)
  8434. (void)conn; /* Unused. */
  8435. #else
  8436. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8437. mg_cry_internal(conn,
  8438. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8439. __func__,
  8440. strerror(ERRNO));
  8441. }
  8442. #endif
  8443. }
  8444. }
  8445. #if defined(USE_ZLIB)
  8446. #include "mod_zlib.inl"
  8447. #endif
  8448. #if !defined(NO_FILESYSTEMS)
  8449. static void
  8450. handle_static_file_request(struct mg_connection *conn,
  8451. const char *path,
  8452. struct mg_file *filep,
  8453. const char *mime_type,
  8454. const char *additional_headers)
  8455. {
  8456. char date[64], lm[64], etag[64];
  8457. char range[128]; /* large enough, so there will be no overflow */
  8458. const char *msg = "OK";
  8459. const char *range_hdr;
  8460. time_t curtime = time(NULL);
  8461. int64_t cl, r1, r2;
  8462. struct vec mime_vec;
  8463. int n, truncated;
  8464. char gz_path[PATH_MAX];
  8465. const char *encoding = "";
  8466. const char *origin_hdr;
  8467. const char *cors_orig_cfg;
  8468. const char *cors1, *cors2, *cors3;
  8469. int is_head_request;
  8470. #if defined(USE_ZLIB)
  8471. /* Compression is allowed, unless there is a reason not to use compression.
  8472. * If the file is already compressed, too small or a "range" request was
  8473. * made, on the fly compression is not possible. */
  8474. int allow_on_the_fly_compression = 1;
  8475. #endif
  8476. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8477. return;
  8478. }
  8479. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8480. if (mime_type == NULL) {
  8481. get_mime_type(conn, path, &mime_vec);
  8482. } else {
  8483. mime_vec.ptr = mime_type;
  8484. mime_vec.len = strlen(mime_type);
  8485. }
  8486. if (filep->stat.size > INT64_MAX) {
  8487. mg_send_http_error(conn,
  8488. 500,
  8489. "Error: File size is too large to send\n%" INT64_FMT,
  8490. filep->stat.size);
  8491. return;
  8492. }
  8493. cl = (int64_t)filep->stat.size;
  8494. conn->status_code = 200;
  8495. range[0] = '\0';
  8496. #if defined(USE_ZLIB)
  8497. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8498. * it's important to rewrite the filename after resolving
  8499. * the mime type from it, to preserve the actual file's type */
  8500. if (!conn->accept_gzip) {
  8501. allow_on_the_fly_compression = 0;
  8502. }
  8503. #endif
  8504. /* Check if there is a range header */
  8505. range_hdr = mg_get_header(conn, "Range");
  8506. /* For gzipped files, add *.gz */
  8507. if (filep->stat.is_gzipped) {
  8508. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8509. if (truncated) {
  8510. mg_send_http_error(conn,
  8511. 500,
  8512. "Error: Path of zipped file too long (%s)",
  8513. path);
  8514. return;
  8515. }
  8516. path = gz_path;
  8517. encoding = "Content-Encoding: gzip\r\n";
  8518. #if defined(USE_ZLIB)
  8519. /* File is already compressed. No "on the fly" compression. */
  8520. allow_on_the_fly_compression = 0;
  8521. #endif
  8522. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8523. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8524. struct mg_file_stat file_stat;
  8525. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8526. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8527. && !file_stat.is_directory) {
  8528. file_stat.is_gzipped = 1;
  8529. filep->stat = file_stat;
  8530. cl = (int64_t)filep->stat.size;
  8531. path = gz_path;
  8532. encoding = "Content-Encoding: gzip\r\n";
  8533. #if defined(USE_ZLIB)
  8534. /* File is already compressed. No "on the fly" compression. */
  8535. allow_on_the_fly_compression = 0;
  8536. #endif
  8537. }
  8538. }
  8539. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8540. mg_send_http_error(conn,
  8541. 500,
  8542. "Error: Cannot open file\nfopen(%s): %s",
  8543. path,
  8544. strerror(ERRNO));
  8545. return;
  8546. }
  8547. fclose_on_exec(&filep->access, conn);
  8548. /* If "Range" request was made: parse header, send only selected part
  8549. * of the file. */
  8550. r1 = r2 = 0;
  8551. if ((range_hdr != NULL)
  8552. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8553. && (r2 >= 0)) {
  8554. /* actually, range requests don't play well with a pre-gzipped
  8555. * file (since the range is specified in the uncompressed space) */
  8556. if (filep->stat.is_gzipped) {
  8557. mg_send_http_error(
  8558. conn,
  8559. 416, /* 416 = Range Not Satisfiable */
  8560. "%s",
  8561. "Error: Range requests in gzipped files are not supported");
  8562. (void)mg_fclose(
  8563. &filep->access); /* ignore error on read only file */
  8564. return;
  8565. }
  8566. conn->status_code = 206;
  8567. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8568. mg_snprintf(conn,
  8569. NULL, /* range buffer is big enough */
  8570. range,
  8571. sizeof(range),
  8572. "Content-Range: bytes "
  8573. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8574. r1,
  8575. r1 + cl - 1,
  8576. filep->stat.size);
  8577. msg = "Partial Content";
  8578. #if defined(USE_ZLIB)
  8579. /* Do not compress ranges. */
  8580. allow_on_the_fly_compression = 0;
  8581. #endif
  8582. }
  8583. /* Do not compress small files. Small files do not benefit from file
  8584. * compression, but there is still some overhead. */
  8585. #if defined(USE_ZLIB)
  8586. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8587. /* File is below the size limit. */
  8588. allow_on_the_fly_compression = 0;
  8589. }
  8590. #endif
  8591. /* Standard CORS header */
  8592. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8593. origin_hdr = mg_get_header(conn, "Origin");
  8594. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8595. /* Cross-origin resource sharing (CORS), see
  8596. * http://www.html5rocks.com/en/tutorials/cors/,
  8597. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8598. * -
  8599. * preflight is not supported for files. */
  8600. cors1 = "Access-Control-Allow-Origin: ";
  8601. cors2 = cors_orig_cfg;
  8602. cors3 = "\r\n";
  8603. } else {
  8604. cors1 = cors2 = cors3 = "";
  8605. }
  8606. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8607. * according to
  8608. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8609. gmt_time_string(date, sizeof(date), &curtime);
  8610. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8611. construct_etag(etag, sizeof(etag), &filep->stat);
  8612. /* Send header */
  8613. (void)mg_printf(conn,
  8614. "HTTP/1.1 %d %s\r\n"
  8615. "%s%s%s" /* CORS */
  8616. "Date: %s\r\n"
  8617. "Last-Modified: %s\r\n"
  8618. "Etag: %s\r\n"
  8619. "Content-Type: %.*s\r\n"
  8620. "Connection: %s\r\n",
  8621. conn->status_code,
  8622. msg,
  8623. cors1,
  8624. cors2,
  8625. cors3,
  8626. date,
  8627. lm,
  8628. etag,
  8629. (int)mime_vec.len,
  8630. mime_vec.ptr,
  8631. suggest_connection_header(conn));
  8632. send_static_cache_header(conn);
  8633. send_additional_header(conn);
  8634. #if defined(USE_ZLIB)
  8635. /* On the fly compression allowed */
  8636. if (allow_on_the_fly_compression) {
  8637. /* For on the fly compression, we don't know the content size in
  8638. * advance, so we have to use chunked encoding */
  8639. (void)mg_printf(conn,
  8640. "Content-Encoding: gzip\r\n"
  8641. "Transfer-Encoding: chunked\r\n");
  8642. } else
  8643. #endif
  8644. {
  8645. /* Without on-the-fly compression, we know the content-length
  8646. * and we can use ranges (with on-the-fly compression we cannot).
  8647. * So we send these response headers only in this case. */
  8648. (void)mg_printf(conn,
  8649. "Content-Length: %" INT64_FMT "\r\n"
  8650. "Accept-Ranges: bytes\r\n"
  8651. "%s" /* range */
  8652. "%s" /* encoding */,
  8653. cl,
  8654. range,
  8655. encoding);
  8656. }
  8657. /* The previous code must not add any header starting with X- to make
  8658. * sure no one of the additional_headers is included twice */
  8659. if (additional_headers != NULL) {
  8660. (void)mg_printf(conn,
  8661. "%.*s\r\n\r\n",
  8662. (int)strlen(additional_headers),
  8663. additional_headers);
  8664. } else {
  8665. (void)mg_printf(conn, "\r\n");
  8666. }
  8667. if (!is_head_request) {
  8668. #if defined(USE_ZLIB)
  8669. if (allow_on_the_fly_compression) {
  8670. /* Compress and send */
  8671. send_compressed_data(conn, filep);
  8672. } else
  8673. #endif
  8674. {
  8675. /* Send file directly */
  8676. send_file_data(conn, filep, r1, cl);
  8677. }
  8678. }
  8679. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8680. }
  8681. int
  8682. mg_send_file_body(struct mg_connection *conn, const char *path)
  8683. {
  8684. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8685. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8686. return -1;
  8687. }
  8688. fclose_on_exec(&file.access, conn);
  8689. send_file_data(conn, &file, 0, INT64_MAX);
  8690. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8691. return 0; /* >= 0 for OK */
  8692. }
  8693. #endif /* NO_FILESYSTEMS */
  8694. #if !defined(NO_CACHING)
  8695. /* Return True if we should reply 304 Not Modified. */
  8696. static int
  8697. is_not_modified(const struct mg_connection *conn,
  8698. const struct mg_file_stat *filestat)
  8699. {
  8700. char etag[64];
  8701. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8702. const char *inm = mg_get_header(conn, "If-None-Match");
  8703. construct_etag(etag, sizeof(etag), filestat);
  8704. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8705. || ((ims != NULL)
  8706. && (filestat->last_modified <= parse_date_string(ims)));
  8707. }
  8708. static void
  8709. handle_not_modified_static_file_request(struct mg_connection *conn,
  8710. struct mg_file *filep)
  8711. {
  8712. char date[64], lm[64], etag[64];
  8713. time_t curtime = time(NULL);
  8714. if ((conn == NULL) || (filep == NULL)) {
  8715. return;
  8716. }
  8717. conn->status_code = 304;
  8718. gmt_time_string(date, sizeof(date), &curtime);
  8719. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8720. construct_etag(etag, sizeof(etag), &filep->stat);
  8721. (void)mg_printf(conn,
  8722. "HTTP/1.1 %d %s\r\n"
  8723. "Date: %s\r\n",
  8724. conn->status_code,
  8725. mg_get_response_code_text(conn, conn->status_code),
  8726. date);
  8727. send_static_cache_header(conn);
  8728. send_additional_header(conn);
  8729. (void)mg_printf(conn,
  8730. "Last-Modified: %s\r\n"
  8731. "Etag: %s\r\n"
  8732. "Connection: %s\r\n"
  8733. "\r\n",
  8734. lm,
  8735. etag,
  8736. suggest_connection_header(conn));
  8737. }
  8738. #endif
  8739. #if !defined(NO_FILESYSTEMS)
  8740. void
  8741. mg_send_file(struct mg_connection *conn, const char *path)
  8742. {
  8743. mg_send_mime_file2(conn, path, NULL, NULL);
  8744. }
  8745. void
  8746. mg_send_mime_file(struct mg_connection *conn,
  8747. const char *path,
  8748. const char *mime_type)
  8749. {
  8750. mg_send_mime_file2(conn, path, mime_type, NULL);
  8751. }
  8752. void
  8753. mg_send_mime_file2(struct mg_connection *conn,
  8754. const char *path,
  8755. const char *mime_type,
  8756. const char *additional_headers)
  8757. {
  8758. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8759. if (!conn) {
  8760. /* No conn */
  8761. return;
  8762. }
  8763. if (mg_stat(conn, path, &file.stat)) {
  8764. #if !defined(NO_CACHING)
  8765. if (is_not_modified(conn, &file.stat)) {
  8766. /* Send 304 "Not Modified" - this must not send any body data */
  8767. handle_not_modified_static_file_request(conn, &file);
  8768. } else
  8769. #endif /* NO_CACHING */
  8770. if (file.stat.is_directory) {
  8771. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8772. "yes")) {
  8773. handle_directory_request(conn, path);
  8774. } else {
  8775. mg_send_http_error(conn,
  8776. 403,
  8777. "%s",
  8778. "Error: Directory listing denied");
  8779. }
  8780. } else {
  8781. handle_static_file_request(
  8782. conn, path, &file, mime_type, additional_headers);
  8783. }
  8784. } else {
  8785. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8786. }
  8787. }
  8788. /* For a given PUT path, create all intermediate subdirectories.
  8789. * Return 0 if the path itself is a directory.
  8790. * Return 1 if the path leads to a file.
  8791. * Return -1 for if the path is too long.
  8792. * Return -2 if path can not be created.
  8793. */
  8794. static int
  8795. put_dir(struct mg_connection *conn, const char *path)
  8796. {
  8797. char buf[PATH_MAX];
  8798. const char *s, *p;
  8799. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8800. size_t len;
  8801. int res = 1;
  8802. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8803. len = (size_t)(p - path);
  8804. if (len >= sizeof(buf)) {
  8805. /* path too long */
  8806. res = -1;
  8807. break;
  8808. }
  8809. memcpy(buf, path, len);
  8810. buf[len] = '\0';
  8811. /* Try to create intermediate directory */
  8812. DEBUG_TRACE("mkdir(%s)", buf);
  8813. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8814. /* path does not exixt and can not be created */
  8815. res = -2;
  8816. break;
  8817. }
  8818. /* Is path itself a directory? */
  8819. if (p[1] == '\0') {
  8820. res = 0;
  8821. }
  8822. }
  8823. return res;
  8824. }
  8825. static void
  8826. remove_bad_file(const struct mg_connection *conn, const char *path)
  8827. {
  8828. int r = mg_remove(conn, path);
  8829. if (r != 0) {
  8830. mg_cry_internal(conn,
  8831. "%s: Cannot remove invalid file %s",
  8832. __func__,
  8833. path);
  8834. }
  8835. }
  8836. long long
  8837. mg_store_body(struct mg_connection *conn, const char *path)
  8838. {
  8839. char buf[MG_BUF_LEN];
  8840. long long len = 0;
  8841. int ret, n;
  8842. struct mg_file fi;
  8843. if (conn->consumed_content != 0) {
  8844. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8845. return -11;
  8846. }
  8847. ret = put_dir(conn, path);
  8848. if (ret < 0) {
  8849. /* -1 for path too long,
  8850. * -2 for path can not be created. */
  8851. return ret;
  8852. }
  8853. if (ret != 1) {
  8854. /* Return 0 means, path itself is a directory. */
  8855. return 0;
  8856. }
  8857. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8858. return -12;
  8859. }
  8860. ret = mg_read(conn, buf, sizeof(buf));
  8861. while (ret > 0) {
  8862. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8863. if (n != ret) {
  8864. (void)mg_fclose(
  8865. &fi.access); /* File is bad and will be removed anyway. */
  8866. remove_bad_file(conn, path);
  8867. return -13;
  8868. }
  8869. len += ret;
  8870. ret = mg_read(conn, buf, sizeof(buf));
  8871. }
  8872. /* File is open for writing. If fclose fails, there was probably an
  8873. * error flushing the buffer to disk, so the file on disk might be
  8874. * broken. Delete it and return an error to the caller. */
  8875. if (mg_fclose(&fi.access) != 0) {
  8876. remove_bad_file(conn, path);
  8877. return -14;
  8878. }
  8879. return len;
  8880. }
  8881. #endif /* NO_FILESYSTEMS */
  8882. /* Parse a buffer:
  8883. * Forward the string pointer till the end of a word, then
  8884. * terminate it and forward till the begin of the next word.
  8885. */
  8886. static int
  8887. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8888. {
  8889. /* Forward until a space is found - use isgraph here */
  8890. /* See http://www.cplusplus.com/reference/cctype/ */
  8891. while (isgraph((unsigned char)**ppw)) {
  8892. (*ppw)++;
  8893. }
  8894. /* Check end of word */
  8895. if (eol) {
  8896. /* must be a end of line */
  8897. if ((**ppw != '\r') && (**ppw != '\n')) {
  8898. return -1;
  8899. }
  8900. } else {
  8901. /* must be a end of a word, but not a line */
  8902. if (**ppw != ' ') {
  8903. return -1;
  8904. }
  8905. }
  8906. /* Terminate and forward to the next word */
  8907. do {
  8908. **ppw = 0;
  8909. (*ppw)++;
  8910. } while (isspace((unsigned char)**ppw));
  8911. /* Check after term */
  8912. if (!eol) {
  8913. /* if it's not the end of line, there must be a next word */
  8914. if (!isgraph((unsigned char)**ppw)) {
  8915. return -1;
  8916. }
  8917. }
  8918. /* ok */
  8919. return 1;
  8920. }
  8921. /* Parse HTTP headers from the given buffer, advance buf pointer
  8922. * to the point where parsing stopped.
  8923. * All parameters must be valid pointers (not NULL).
  8924. * Return <0 on error. */
  8925. static int
  8926. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8927. {
  8928. int i;
  8929. int num_headers = 0;
  8930. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8931. char *dp = *buf;
  8932. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8933. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8934. dp++;
  8935. }
  8936. if (dp == *buf) {
  8937. /* End of headers reached. */
  8938. break;
  8939. }
  8940. if (*dp != ':') {
  8941. /* This is not a valid field. */
  8942. return -1;
  8943. }
  8944. /* End of header key (*dp == ':') */
  8945. /* Truncate here and set the key name */
  8946. *dp = 0;
  8947. hdr[i].name = *buf;
  8948. /* Skip all spaces */
  8949. do {
  8950. dp++;
  8951. } while ((*dp == ' ') || (*dp == '\t'));
  8952. /* The rest of the line is the value */
  8953. hdr[i].value = dp;
  8954. /* Find end of line */
  8955. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8956. dp++;
  8957. };
  8958. /* eliminate \r */
  8959. if (*dp == '\r') {
  8960. *dp = 0;
  8961. dp++;
  8962. if (*dp != '\n') {
  8963. /* This is not a valid line. */
  8964. return -1;
  8965. }
  8966. }
  8967. /* here *dp is either 0 or '\n' */
  8968. /* in any case, we have a new header */
  8969. num_headers = i + 1;
  8970. if (*dp) {
  8971. *dp = 0;
  8972. dp++;
  8973. *buf = dp;
  8974. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8975. /* This is the end of the header */
  8976. break;
  8977. }
  8978. } else {
  8979. *buf = dp;
  8980. break;
  8981. }
  8982. }
  8983. return num_headers;
  8984. }
  8985. struct mg_http_method_info {
  8986. const char *name;
  8987. int request_has_body;
  8988. int response_has_body;
  8989. int is_safe;
  8990. int is_idempotent;
  8991. int is_cacheable;
  8992. };
  8993. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8994. static struct mg_http_method_info http_methods[] = {
  8995. /* HTTP (RFC 2616) */
  8996. {"GET", 0, 1, 1, 1, 1},
  8997. {"POST", 1, 1, 0, 0, 0},
  8998. {"PUT", 1, 0, 0, 1, 0},
  8999. {"DELETE", 0, 0, 0, 1, 0},
  9000. {"HEAD", 0, 0, 1, 1, 1},
  9001. {"OPTIONS", 0, 0, 1, 1, 0},
  9002. {"CONNECT", 1, 1, 0, 0, 0},
  9003. /* TRACE method (RFC 2616) is not supported for security reasons */
  9004. /* PATCH method (RFC 5789) */
  9005. {"PATCH", 1, 0, 0, 0, 0},
  9006. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9007. /* WEBDAV (RFC 2518) */
  9008. {"PROPFIND", 0, 1, 1, 1, 0},
  9009. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9010. * Some PROPFIND results MAY be cached, with care,
  9011. * as there is no cache validation mechanism for
  9012. * most properties. This method is both safe and
  9013. * idempotent (see Section 9.1 of [RFC2616]). */
  9014. {"MKCOL", 0, 0, 0, 1, 0},
  9015. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9016. * When MKCOL is invoked without a request body,
  9017. * the newly created collection SHOULD have no
  9018. * members. A MKCOL request message may contain
  9019. * a message body. The precise behavior of a MKCOL
  9020. * request when the body is present is undefined,
  9021. * ... ==> We do not support MKCOL with body data.
  9022. * This method is idempotent, but not safe (see
  9023. * Section 9.1 of [RFC2616]). Responses to this
  9024. * method MUST NOT be cached. */
  9025. /* Unsupported WEBDAV Methods: */
  9026. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9027. /* + 11 methods from RFC 3253 */
  9028. /* ORDERPATCH (RFC 3648) */
  9029. /* ACL (RFC 3744) */
  9030. /* SEARCH (RFC 5323) */
  9031. /* + MicroSoft extensions
  9032. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9033. /* REPORT method (RFC 3253) */
  9034. {"REPORT", 1, 1, 1, 1, 1},
  9035. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9036. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9037. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9038. * to be useful for REST in case a "GET request with body" is
  9039. * required. */
  9040. {NULL, 0, 0, 0, 0, 0}
  9041. /* end of list */
  9042. };
  9043. static const struct mg_http_method_info *
  9044. get_http_method_info(const char *method)
  9045. {
  9046. /* Check if the method is known to the server. The list of all known
  9047. * HTTP methods can be found here at
  9048. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9049. */
  9050. const struct mg_http_method_info *m = http_methods;
  9051. while (m->name) {
  9052. if (!strcmp(m->name, method)) {
  9053. return m;
  9054. }
  9055. m++;
  9056. }
  9057. return NULL;
  9058. }
  9059. static int
  9060. is_valid_http_method(const char *method)
  9061. {
  9062. return (get_http_method_info(method) != NULL);
  9063. }
  9064. /* Parse HTTP request, fill in mg_request_info structure.
  9065. * This function modifies the buffer by NUL-terminating
  9066. * HTTP request components, header names and header values.
  9067. * Parameters:
  9068. * buf (in/out): pointer to the HTTP header to parse and split
  9069. * len (in): length of HTTP header buffer
  9070. * re (out): parsed header as mg_request_info
  9071. * buf and ri must be valid pointers (not NULL), len>0.
  9072. * Returns <0 on error. */
  9073. static int
  9074. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9075. {
  9076. int request_length;
  9077. int init_skip = 0;
  9078. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9079. * remote_port */
  9080. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9081. NULL;
  9082. ri->num_headers = 0;
  9083. /* RFC says that all initial whitespaces should be ingored */
  9084. /* This included all leading \r and \n (isspace) */
  9085. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9086. while ((len > 0) && isspace((unsigned char)*buf)) {
  9087. buf++;
  9088. len--;
  9089. init_skip++;
  9090. }
  9091. if (len == 0) {
  9092. /* Incomplete request */
  9093. return 0;
  9094. }
  9095. /* Control characters are not allowed, including zero */
  9096. if (iscntrl((unsigned char)*buf)) {
  9097. return -1;
  9098. }
  9099. /* Find end of HTTP header */
  9100. request_length = get_http_header_len(buf, len);
  9101. if (request_length <= 0) {
  9102. return request_length;
  9103. }
  9104. buf[request_length - 1] = '\0';
  9105. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9106. return -1;
  9107. }
  9108. /* The first word has to be the HTTP method */
  9109. ri->request_method = buf;
  9110. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9111. return -1;
  9112. }
  9113. /* Check for a valid http method */
  9114. if (!is_valid_http_method(ri->request_method)) {
  9115. return -1;
  9116. }
  9117. /* The second word is the URI */
  9118. ri->request_uri = buf;
  9119. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9120. return -1;
  9121. }
  9122. /* Next would be the HTTP version */
  9123. ri->http_version = buf;
  9124. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9125. return -1;
  9126. }
  9127. /* Check for a valid HTTP version key */
  9128. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9129. /* Invalid request */
  9130. return -1;
  9131. }
  9132. ri->http_version += 5;
  9133. /* Parse all HTTP headers */
  9134. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9135. if (ri->num_headers < 0) {
  9136. /* Error while parsing headers */
  9137. return -1;
  9138. }
  9139. return request_length + init_skip;
  9140. }
  9141. static int
  9142. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9143. {
  9144. int response_length;
  9145. int init_skip = 0;
  9146. char *tmp, *tmp2;
  9147. long l;
  9148. /* Initialize elements. */
  9149. ri->http_version = ri->status_text = NULL;
  9150. ri->num_headers = ri->status_code = 0;
  9151. /* RFC says that all initial whitespaces should be ingored */
  9152. /* This included all leading \r and \n (isspace) */
  9153. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9154. while ((len > 0) && isspace((unsigned char)*buf)) {
  9155. buf++;
  9156. len--;
  9157. init_skip++;
  9158. }
  9159. if (len == 0) {
  9160. /* Incomplete request */
  9161. return 0;
  9162. }
  9163. /* Control characters are not allowed, including zero */
  9164. if (iscntrl((unsigned char)*buf)) {
  9165. return -1;
  9166. }
  9167. /* Find end of HTTP header */
  9168. response_length = get_http_header_len(buf, len);
  9169. if (response_length <= 0) {
  9170. return response_length;
  9171. }
  9172. buf[response_length - 1] = '\0';
  9173. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9174. return -1;
  9175. }
  9176. /* The first word is the HTTP version */
  9177. /* Check for a valid HTTP version key */
  9178. if (strncmp(buf, "HTTP/", 5) != 0) {
  9179. /* Invalid request */
  9180. return -1;
  9181. }
  9182. buf += 5;
  9183. if (!isgraph((unsigned char)buf[0])) {
  9184. /* Invalid request */
  9185. return -1;
  9186. }
  9187. ri->http_version = buf;
  9188. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9189. return -1;
  9190. }
  9191. /* The second word is the status as a number */
  9192. tmp = buf;
  9193. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9194. return -1;
  9195. }
  9196. l = strtol(tmp, &tmp2, 10);
  9197. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9198. /* Everything else but a 3 digit code is invalid */
  9199. return -1;
  9200. }
  9201. ri->status_code = (int)l;
  9202. /* The rest of the line is the status text */
  9203. ri->status_text = buf;
  9204. /* Find end of status text */
  9205. /* isgraph or isspace = isprint */
  9206. while (isprint((unsigned char)*buf)) {
  9207. buf++;
  9208. }
  9209. if ((*buf != '\r') && (*buf != '\n')) {
  9210. return -1;
  9211. }
  9212. /* Terminate string and forward buf to next line */
  9213. do {
  9214. *buf = 0;
  9215. buf++;
  9216. } while (isspace((unsigned char)*buf));
  9217. /* Parse all HTTP headers */
  9218. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9219. if (ri->num_headers < 0) {
  9220. /* Error while parsing headers */
  9221. return -1;
  9222. }
  9223. return response_length + init_skip;
  9224. }
  9225. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9226. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9227. * buffer (which marks the end of HTTP request). Buffer buf may already
  9228. * have some data. The length of the data is stored in nread.
  9229. * Upon every read operation, increase nread by the number of bytes read. */
  9230. static int
  9231. read_message(FILE *fp,
  9232. struct mg_connection *conn,
  9233. char *buf,
  9234. int bufsiz,
  9235. int *nread)
  9236. {
  9237. int request_len, n = 0;
  9238. struct timespec last_action_time;
  9239. double request_timeout;
  9240. if (!conn) {
  9241. return 0;
  9242. }
  9243. memset(&last_action_time, 0, sizeof(last_action_time));
  9244. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9245. /* value of request_timeout is in seconds, config in milliseconds */
  9246. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9247. } else {
  9248. request_timeout = -1.0;
  9249. }
  9250. if (conn->handled_requests > 0) {
  9251. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9252. request_timeout =
  9253. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9254. }
  9255. }
  9256. request_len = get_http_header_len(buf, *nread);
  9257. while (request_len == 0) {
  9258. /* Full request not yet received */
  9259. if (conn->phys_ctx->stop_flag != 0) {
  9260. /* Server is to be stopped. */
  9261. return -1;
  9262. }
  9263. if (*nread >= bufsiz) {
  9264. /* Request too long */
  9265. return -2;
  9266. }
  9267. n = pull_inner(
  9268. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9269. if (n == -2) {
  9270. /* Receive error */
  9271. return -1;
  9272. }
  9273. /* update clock after every read request */
  9274. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9275. if (n > 0) {
  9276. *nread += n;
  9277. request_len = get_http_header_len(buf, *nread);
  9278. } else {
  9279. request_len = 0;
  9280. }
  9281. if ((request_len == 0) && (request_timeout >= 0)) {
  9282. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9283. > request_timeout) {
  9284. /* Timeout */
  9285. return -1;
  9286. }
  9287. }
  9288. }
  9289. return request_len;
  9290. }
  9291. #if !defined(NO_CGI) || !defined(NO_FILES)
  9292. static int
  9293. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9294. {
  9295. const char *expect;
  9296. char buf[MG_BUF_LEN];
  9297. int success = 0;
  9298. if (!conn) {
  9299. return 0;
  9300. }
  9301. expect = mg_get_header(conn, "Expect");
  9302. DEBUG_ASSERT(fp != NULL);
  9303. if (!fp) {
  9304. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9305. return 0;
  9306. }
  9307. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9308. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9309. */
  9310. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9311. } else {
  9312. if (expect != NULL) {
  9313. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9314. conn->status_code = 100;
  9315. } else {
  9316. conn->status_code = 200;
  9317. }
  9318. DEBUG_ASSERT(conn->consumed_content == 0);
  9319. if (conn->consumed_content != 0) {
  9320. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9321. return 0;
  9322. }
  9323. for (;;) {
  9324. int nread = mg_read(conn, buf, sizeof(buf));
  9325. if (nread <= 0) {
  9326. success = (nread == 0);
  9327. break;
  9328. }
  9329. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9330. break;
  9331. }
  9332. }
  9333. /* Each error code path in this function must send an error */
  9334. if (!success) {
  9335. /* NOTE: Maybe some data has already been sent. */
  9336. /* TODO (low): If some data has been sent, a correct error
  9337. * reply can no longer be sent, so just close the connection */
  9338. mg_send_http_error(conn, 500, "%s", "");
  9339. }
  9340. }
  9341. return success;
  9342. }
  9343. #endif
  9344. #if defined(USE_TIMERS)
  9345. #define TIMER_API static
  9346. #include "timer.inl"
  9347. #endif /* USE_TIMERS */
  9348. #if !defined(NO_CGI)
  9349. /* This structure helps to create an environment for the spawned CGI
  9350. * program.
  9351. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9352. * last element must be NULL.
  9353. * However, on Windows there is a requirement that all these
  9354. * VARIABLE=VALUE\0
  9355. * strings must reside in a contiguous buffer. The end of the buffer is
  9356. * marked by two '\0' characters.
  9357. * We satisfy both worlds: we create an envp array (which is vars), all
  9358. * entries are actually pointers inside buf. */
  9359. struct cgi_environment {
  9360. struct mg_connection *conn;
  9361. /* Data block */
  9362. char *buf; /* Environment buffer */
  9363. size_t buflen; /* Space available in buf */
  9364. size_t bufused; /* Space taken in buf */
  9365. /* Index block */
  9366. char **var; /* char **envp */
  9367. size_t varlen; /* Number of variables available in var */
  9368. size_t varused; /* Number of variables stored in var */
  9369. };
  9370. static void addenv(struct cgi_environment *env,
  9371. PRINTF_FORMAT_STRING(const char *fmt),
  9372. ...) PRINTF_ARGS(2, 3);
  9373. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9374. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9375. static void
  9376. addenv(struct cgi_environment *env, const char *fmt, ...)
  9377. {
  9378. size_t i, n, space;
  9379. int truncated = 0;
  9380. char *added;
  9381. va_list ap;
  9382. if ((env->varlen - env->varused) < 2) {
  9383. mg_cry_internal(env->conn,
  9384. "%s: Cannot register CGI variable [%s]",
  9385. __func__,
  9386. fmt);
  9387. return;
  9388. }
  9389. /* Calculate how much space is left in the buffer */
  9390. space = (env->buflen - env->bufused);
  9391. do {
  9392. /* Space for "\0\0" is always needed. */
  9393. if (space <= 2) {
  9394. /* Allocate new buffer */
  9395. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9396. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9397. if (!added) {
  9398. /* Out of memory */
  9399. mg_cry_internal(
  9400. env->conn,
  9401. "%s: Cannot allocate memory for CGI variable [%s]",
  9402. __func__,
  9403. fmt);
  9404. return;
  9405. }
  9406. /* Retarget pointers */
  9407. env->buf = added;
  9408. env->buflen = n;
  9409. for (i = 0, n = 0; i < env->varused; i++) {
  9410. env->var[i] = added + n;
  9411. n += strlen(added + n) + 1;
  9412. }
  9413. space = (env->buflen - env->bufused);
  9414. }
  9415. /* Make a pointer to the free space int the buffer */
  9416. added = env->buf + env->bufused;
  9417. /* Copy VARIABLE=VALUE\0 string into the free space */
  9418. va_start(ap, fmt);
  9419. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9420. va_end(ap);
  9421. /* Do not add truncated strings to the environment */
  9422. if (truncated) {
  9423. /* Reallocate the buffer */
  9424. space = 0;
  9425. }
  9426. } while (truncated);
  9427. /* Calculate number of bytes added to the environment */
  9428. n = strlen(added) + 1;
  9429. env->bufused += n;
  9430. /* Append a pointer to the added string into the envp array */
  9431. env->var[env->varused] = added;
  9432. env->varused++;
  9433. }
  9434. /* Return 0 on success, non-zero if an error occurs. */
  9435. static int
  9436. prepare_cgi_environment(struct mg_connection *conn,
  9437. const char *prog,
  9438. struct cgi_environment *env)
  9439. {
  9440. const char *s;
  9441. struct vec var_vec;
  9442. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9443. int i, truncated, uri_len;
  9444. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9445. return -1;
  9446. }
  9447. env->conn = conn;
  9448. env->buflen = CGI_ENVIRONMENT_SIZE;
  9449. env->bufused = 0;
  9450. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9451. if (env->buf == NULL) {
  9452. mg_cry_internal(conn,
  9453. "%s: Not enough memory for environmental buffer",
  9454. __func__);
  9455. return -1;
  9456. }
  9457. env->varlen = MAX_CGI_ENVIR_VARS;
  9458. env->varused = 0;
  9459. env->var =
  9460. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9461. if (env->var == NULL) {
  9462. mg_cry_internal(conn,
  9463. "%s: Not enough memory for environmental variables",
  9464. __func__);
  9465. mg_free(env->buf);
  9466. return -1;
  9467. }
  9468. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9469. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9470. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9471. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9472. /* Prepare the environment block */
  9473. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9474. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9475. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9476. #if defined(USE_IPV6)
  9477. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9478. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9479. } else
  9480. #endif
  9481. {
  9482. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9483. }
  9484. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9485. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9486. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9487. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9488. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9489. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9490. /* SCRIPT_NAME */
  9491. uri_len = (int)strlen(conn->request_info.local_uri);
  9492. if (conn->path_info == NULL) {
  9493. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9494. /* URI: /path_to_script/script.cgi */
  9495. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9496. } else {
  9497. /* URI: /path_to_script/ ... using index.cgi */
  9498. const char *index_file = strrchr(prog, '/');
  9499. if (index_file) {
  9500. addenv(env,
  9501. "SCRIPT_NAME=%s%s",
  9502. conn->request_info.local_uri,
  9503. index_file + 1);
  9504. }
  9505. }
  9506. } else {
  9507. /* URI: /path_to_script/script.cgi/path_info */
  9508. addenv(env,
  9509. "SCRIPT_NAME=%.*s",
  9510. uri_len - (int)strlen(conn->path_info),
  9511. conn->request_info.local_uri);
  9512. }
  9513. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9514. if (conn->path_info == NULL) {
  9515. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9516. } else {
  9517. addenv(env,
  9518. "PATH_TRANSLATED=%s%s",
  9519. conn->dom_ctx->config[DOCUMENT_ROOT],
  9520. conn->path_info);
  9521. }
  9522. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9523. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9524. addenv(env, "CONTENT_TYPE=%s", s);
  9525. }
  9526. if (conn->request_info.query_string != NULL) {
  9527. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9528. }
  9529. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9530. addenv(env, "CONTENT_LENGTH=%s", s);
  9531. }
  9532. if ((s = getenv("PATH")) != NULL) {
  9533. addenv(env, "PATH=%s", s);
  9534. }
  9535. if (conn->path_info != NULL) {
  9536. addenv(env, "PATH_INFO=%s", conn->path_info);
  9537. }
  9538. if (conn->status_code > 0) {
  9539. /* CGI error handler should show the status code */
  9540. addenv(env, "STATUS=%d", conn->status_code);
  9541. }
  9542. #if defined(_WIN32)
  9543. if ((s = getenv("COMSPEC")) != NULL) {
  9544. addenv(env, "COMSPEC=%s", s);
  9545. }
  9546. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9547. addenv(env, "SYSTEMROOT=%s", s);
  9548. }
  9549. if ((s = getenv("SystemDrive")) != NULL) {
  9550. addenv(env, "SystemDrive=%s", s);
  9551. }
  9552. if ((s = getenv("ProgramFiles")) != NULL) {
  9553. addenv(env, "ProgramFiles=%s", s);
  9554. }
  9555. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9556. addenv(env, "ProgramFiles(x86)=%s", s);
  9557. }
  9558. #else
  9559. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9560. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9561. }
  9562. #endif /* _WIN32 */
  9563. if ((s = getenv("PERLLIB")) != NULL) {
  9564. addenv(env, "PERLLIB=%s", s);
  9565. }
  9566. if (conn->request_info.remote_user != NULL) {
  9567. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9568. addenv(env, "%s", "AUTH_TYPE=Digest");
  9569. }
  9570. /* Add all headers as HTTP_* variables */
  9571. for (i = 0; i < conn->request_info.num_headers; i++) {
  9572. (void)mg_snprintf(conn,
  9573. &truncated,
  9574. http_var_name,
  9575. sizeof(http_var_name),
  9576. "HTTP_%s",
  9577. conn->request_info.http_headers[i].name);
  9578. if (truncated) {
  9579. mg_cry_internal(conn,
  9580. "%s: HTTP header variable too long [%s]",
  9581. __func__,
  9582. conn->request_info.http_headers[i].name);
  9583. continue;
  9584. }
  9585. /* Convert variable name into uppercase, and change - to _ */
  9586. for (p = http_var_name; *p != '\0'; p++) {
  9587. if (*p == '-') {
  9588. *p = '_';
  9589. }
  9590. *p = (char)toupper((unsigned char)*p);
  9591. }
  9592. addenv(env,
  9593. "%s=%s",
  9594. http_var_name,
  9595. conn->request_info.http_headers[i].value);
  9596. }
  9597. /* Add user-specified variables */
  9598. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9599. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9600. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9601. }
  9602. env->var[env->varused] = NULL;
  9603. env->buf[env->bufused] = '\0';
  9604. return 0;
  9605. }
  9606. /* Data for CGI process control: PID and number of references */
  9607. struct process_control_data {
  9608. pid_t pid;
  9609. int references;
  9610. };
  9611. static int
  9612. abort_process(void *data)
  9613. {
  9614. /* Waitpid checks for child status and won't work for a pid that does not
  9615. * identify a child of the current process. Thus, if the pid is reused,
  9616. * we will not affect a different process. */
  9617. struct process_control_data *proc = (struct process_control_data *)data;
  9618. int status = 0;
  9619. int refs;
  9620. pid_t ret_pid;
  9621. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9622. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9623. /* Stop child process */
  9624. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9625. kill(proc->pid, SIGABRT);
  9626. /* Wait until process is terminated (don't leave zombies) */
  9627. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9628. ;
  9629. } else {
  9630. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9631. }
  9632. /* Dec reference counter */
  9633. refs = mg_atomic_dec(&proc->references);
  9634. if (refs == 0) {
  9635. /* no more references - free data */
  9636. mg_free(data);
  9637. }
  9638. return 0;
  9639. }
  9640. /* Local (static) function assumes all arguments are valid. */
  9641. static void
  9642. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9643. {
  9644. char *buf;
  9645. size_t buflen;
  9646. int headers_len, data_len, i, truncated;
  9647. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9648. const char *status, *status_text, *connection_state;
  9649. char *pbuf, dir[PATH_MAX], *p;
  9650. struct mg_request_info ri;
  9651. struct cgi_environment blk;
  9652. FILE *in = NULL, *out = NULL, *err = NULL;
  9653. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9654. pid_t pid = (pid_t)-1;
  9655. struct process_control_data *proc = NULL;
  9656. #if defined(USE_TIMERS)
  9657. double cgi_timeout = -1.0;
  9658. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9659. /* Get timeout in seconds */
  9660. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9661. }
  9662. #endif
  9663. buf = NULL;
  9664. buflen = conn->phys_ctx->max_request_size;
  9665. i = prepare_cgi_environment(conn, prog, &blk);
  9666. if (i != 0) {
  9667. blk.buf = NULL;
  9668. blk.var = NULL;
  9669. goto done;
  9670. }
  9671. /* CGI must be executed in its own directory. 'dir' must point to the
  9672. * directory containing executable program, 'p' must point to the
  9673. * executable program name relative to 'dir'. */
  9674. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9675. if (truncated) {
  9676. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9677. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9678. goto done;
  9679. }
  9680. if ((p = strrchr(dir, '/')) != NULL) {
  9681. *p++ = '\0';
  9682. } else {
  9683. dir[0] = '.';
  9684. dir[1] = '\0';
  9685. p = (char *)prog;
  9686. }
  9687. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9688. status = strerror(ERRNO);
  9689. mg_cry_internal(
  9690. conn,
  9691. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9692. prog,
  9693. status);
  9694. mg_send_http_error(conn,
  9695. 500,
  9696. "Error: Cannot create CGI pipe: %s",
  9697. status);
  9698. goto done;
  9699. }
  9700. proc = (struct process_control_data *)
  9701. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9702. if (proc == NULL) {
  9703. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9704. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9705. goto done;
  9706. }
  9707. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9708. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9709. if (pid == (pid_t)-1) {
  9710. status = strerror(ERRNO);
  9711. mg_cry_internal(
  9712. conn,
  9713. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9714. prog,
  9715. status);
  9716. mg_send_http_error(conn,
  9717. 500,
  9718. "Error: Cannot spawn CGI process [%s]: %s",
  9719. prog,
  9720. status);
  9721. mg_free(proc);
  9722. proc = NULL;
  9723. goto done;
  9724. }
  9725. /* Store data in shared process_control_data */
  9726. proc->pid = pid;
  9727. proc->references = 1;
  9728. #if defined(USE_TIMERS)
  9729. if (cgi_timeout > 0.0) {
  9730. proc->references = 2;
  9731. // Start a timer for CGI
  9732. timer_add(conn->phys_ctx,
  9733. cgi_timeout /* in seconds */,
  9734. 0.0,
  9735. 1,
  9736. abort_process,
  9737. (void *)proc);
  9738. }
  9739. #endif
  9740. /* Parent closes only one side of the pipes.
  9741. * If we don't mark them as closed, close() attempt before
  9742. * return from this function throws an exception on Windows.
  9743. * Windows does not like when closed descriptor is closed again. */
  9744. (void)close(fdin[0]);
  9745. (void)close(fdout[1]);
  9746. (void)close(fderr[1]);
  9747. fdin[0] = fdout[1] = fderr[1] = -1;
  9748. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9749. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9750. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9751. status = strerror(ERRNO);
  9752. mg_cry_internal(conn,
  9753. "Error: CGI program \"%s\": Can not open fd: %s",
  9754. prog,
  9755. status);
  9756. mg_send_http_error(conn,
  9757. 500,
  9758. "Error: CGI can not open fd\nfdopen: %s",
  9759. status);
  9760. goto done;
  9761. }
  9762. setbuf(in, NULL);
  9763. setbuf(out, NULL);
  9764. setbuf(err, NULL);
  9765. fout.access.fp = out;
  9766. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9767. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9768. conn->content_len);
  9769. /* This is a POST/PUT request, or another request with body data. */
  9770. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9771. /* Error sending the body data */
  9772. mg_cry_internal(
  9773. conn,
  9774. "Error: CGI program \"%s\": Forward body data failed",
  9775. prog);
  9776. goto done;
  9777. }
  9778. }
  9779. /* Close so child gets an EOF. */
  9780. fclose(in);
  9781. in = NULL;
  9782. fdin[1] = -1;
  9783. /* Now read CGI reply into a buffer. We need to set correct
  9784. * status code, thus we need to see all HTTP headers first.
  9785. * Do not send anything back to client, until we buffer in all
  9786. * HTTP headers. */
  9787. data_len = 0;
  9788. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9789. if (buf == NULL) {
  9790. mg_send_http_error(conn,
  9791. 500,
  9792. "Error: Not enough memory for CGI buffer (%u bytes)",
  9793. (unsigned int)buflen);
  9794. mg_cry_internal(
  9795. conn,
  9796. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9797. "bytes)",
  9798. prog,
  9799. (unsigned int)buflen);
  9800. goto done;
  9801. }
  9802. DEBUG_TRACE("CGI: %s", "wait for response");
  9803. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9804. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9805. if (headers_len <= 0) {
  9806. /* Could not parse the CGI response. Check if some error message on
  9807. * stderr. */
  9808. i = pull_all(err, conn, buf, (int)buflen);
  9809. if (i > 0) {
  9810. /* CGI program explicitly sent an error */
  9811. /* Write the error message to the internal log */
  9812. mg_cry_internal(conn,
  9813. "Error: CGI program \"%s\" sent error "
  9814. "message: [%.*s]",
  9815. prog,
  9816. i,
  9817. buf);
  9818. /* Don't send the error message back to the client */
  9819. mg_send_http_error(conn,
  9820. 500,
  9821. "Error: CGI program \"%s\" failed.",
  9822. prog);
  9823. } else {
  9824. /* CGI program did not explicitly send an error, but a broken
  9825. * respon header */
  9826. mg_cry_internal(conn,
  9827. "Error: CGI program sent malformed or too big "
  9828. "(>%u bytes) HTTP headers: [%.*s]",
  9829. (unsigned)buflen,
  9830. data_len,
  9831. buf);
  9832. mg_send_http_error(conn,
  9833. 500,
  9834. "Error: CGI program sent malformed or too big "
  9835. "(>%u bytes) HTTP headers: [%.*s]",
  9836. (unsigned)buflen,
  9837. data_len,
  9838. buf);
  9839. }
  9840. /* in both cases, abort processing CGI */
  9841. goto done;
  9842. }
  9843. pbuf = buf;
  9844. buf[headers_len - 1] = '\0';
  9845. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9846. /* Make up and send the status line */
  9847. status_text = "OK";
  9848. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9849. != NULL) {
  9850. conn->status_code = atoi(status);
  9851. status_text = status;
  9852. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9853. status_text++;
  9854. }
  9855. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9856. != NULL) {
  9857. conn->status_code = 307;
  9858. } else {
  9859. conn->status_code = 200;
  9860. }
  9861. connection_state =
  9862. get_header(ri.http_headers, ri.num_headers, "Connection");
  9863. if (!header_has_option(connection_state, "keep-alive")) {
  9864. conn->must_close = 1;
  9865. }
  9866. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9867. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9868. /* Send headers */
  9869. for (i = 0; i < ri.num_headers; i++) {
  9870. DEBUG_TRACE("CGI header: %s: %s",
  9871. ri.http_headers[i].name,
  9872. ri.http_headers[i].value);
  9873. mg_printf(conn,
  9874. "%s: %s\r\n",
  9875. ri.http_headers[i].name,
  9876. ri.http_headers[i].value);
  9877. }
  9878. mg_write(conn, "\r\n", 2);
  9879. /* Send chunk of data that may have been read after the headers */
  9880. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9881. /* Read the rest of CGI output and send to the client */
  9882. DEBUG_TRACE("CGI: %s", "forward all data");
  9883. send_file_data(conn, &fout, 0, INT64_MAX);
  9884. DEBUG_TRACE("CGI: %s", "all data sent");
  9885. done:
  9886. mg_free(blk.var);
  9887. mg_free(blk.buf);
  9888. if (pid != (pid_t)-1) {
  9889. abort_process((void *)proc);
  9890. }
  9891. if (fdin[0] != -1) {
  9892. close(fdin[0]);
  9893. }
  9894. if (fdout[1] != -1) {
  9895. close(fdout[1]);
  9896. }
  9897. if (fderr[1] != -1) {
  9898. close(fderr[1]);
  9899. }
  9900. if (in != NULL) {
  9901. fclose(in);
  9902. } else if (fdin[1] != -1) {
  9903. close(fdin[1]);
  9904. }
  9905. if (out != NULL) {
  9906. fclose(out);
  9907. } else if (fdout[0] != -1) {
  9908. close(fdout[0]);
  9909. }
  9910. if (err != NULL) {
  9911. fclose(err);
  9912. } else if (fderr[0] != -1) {
  9913. close(fderr[0]);
  9914. }
  9915. mg_free(buf);
  9916. }
  9917. #endif /* !NO_CGI */
  9918. #if !defined(NO_FILES)
  9919. static void
  9920. mkcol(struct mg_connection *conn, const char *path)
  9921. {
  9922. int rc, body_len;
  9923. struct de de;
  9924. char date[64];
  9925. time_t curtime = time(NULL);
  9926. if (conn == NULL) {
  9927. return;
  9928. }
  9929. /* TODO (mid): Check the mg_send_http_error situations in this function
  9930. */
  9931. memset(&de.file, 0, sizeof(de.file));
  9932. if (!mg_stat(conn, path, &de.file)) {
  9933. mg_cry_internal(conn,
  9934. "%s: mg_stat(%s) failed: %s",
  9935. __func__,
  9936. path,
  9937. strerror(ERRNO));
  9938. }
  9939. if (de.file.last_modified) {
  9940. /* TODO (mid): This check does not seem to make any sense ! */
  9941. /* TODO (mid): Add a webdav unit test first, before changing
  9942. * anything here. */
  9943. mg_send_http_error(
  9944. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9945. return;
  9946. }
  9947. body_len = conn->data_len - conn->request_len;
  9948. if (body_len > 0) {
  9949. mg_send_http_error(
  9950. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9951. return;
  9952. }
  9953. rc = mg_mkdir(conn, path, 0755);
  9954. if (rc == 0) {
  9955. conn->status_code = 201;
  9956. gmt_time_string(date, sizeof(date), &curtime);
  9957. mg_printf(conn,
  9958. "HTTP/1.1 %d Created\r\n"
  9959. "Date: %s\r\n",
  9960. conn->status_code,
  9961. date);
  9962. send_static_cache_header(conn);
  9963. send_additional_header(conn);
  9964. mg_printf(conn,
  9965. "Content-Length: 0\r\n"
  9966. "Connection: %s\r\n\r\n",
  9967. suggest_connection_header(conn));
  9968. } else {
  9969. if (errno == EEXIST) {
  9970. mg_send_http_error(
  9971. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9972. } else if (errno == EACCES) {
  9973. mg_send_http_error(
  9974. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9975. } else if (errno == ENOENT) {
  9976. mg_send_http_error(
  9977. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9978. } else {
  9979. mg_send_http_error(
  9980. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9981. }
  9982. }
  9983. }
  9984. static void
  9985. put_file(struct mg_connection *conn, const char *path)
  9986. {
  9987. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9988. const char *range;
  9989. int64_t r1, r2;
  9990. int rc;
  9991. char date[64];
  9992. time_t curtime = time(NULL);
  9993. if (conn == NULL) {
  9994. return;
  9995. }
  9996. if (mg_stat(conn, path, &file.stat)) {
  9997. /* File already exists */
  9998. conn->status_code = 200;
  9999. if (file.stat.is_directory) {
  10000. /* This is an already existing directory,
  10001. * so there is nothing to do for the server. */
  10002. rc = 0;
  10003. } else {
  10004. /* File exists and is not a directory. */
  10005. /* Can it be replaced? */
  10006. #if defined(MG_USE_OPEN_FILE)
  10007. if (file.access.membuf != NULL) {
  10008. /* This is an "in-memory" file, that can not be replaced */
  10009. mg_send_http_error(conn,
  10010. 405,
  10011. "Error: Put not possible\nReplacing %s "
  10012. "is not supported",
  10013. path);
  10014. return;
  10015. }
  10016. #endif
  10017. /* Check if the server may write this file */
  10018. if (access(path, W_OK) == 0) {
  10019. /* Access granted */
  10020. conn->status_code = 200;
  10021. rc = 1;
  10022. } else {
  10023. mg_send_http_error(
  10024. conn,
  10025. 403,
  10026. "Error: Put not possible\nReplacing %s is not allowed",
  10027. path);
  10028. return;
  10029. }
  10030. }
  10031. } else {
  10032. /* File should be created */
  10033. conn->status_code = 201;
  10034. rc = put_dir(conn, path);
  10035. }
  10036. if (rc == 0) {
  10037. /* put_dir returns 0 if path is a directory */
  10038. gmt_time_string(date, sizeof(date), &curtime);
  10039. mg_printf(conn,
  10040. "HTTP/1.1 %d %s\r\n",
  10041. conn->status_code,
  10042. mg_get_response_code_text(NULL, conn->status_code));
  10043. send_no_cache_header(conn);
  10044. send_additional_header(conn);
  10045. mg_printf(conn,
  10046. "Date: %s\r\n"
  10047. "Content-Length: 0\r\n"
  10048. "Connection: %s\r\n\r\n",
  10049. date,
  10050. suggest_connection_header(conn));
  10051. /* Request to create a directory has been fulfilled successfully.
  10052. * No need to put a file. */
  10053. return;
  10054. }
  10055. if (rc == -1) {
  10056. /* put_dir returns -1 if the path is too long */
  10057. mg_send_http_error(conn,
  10058. 414,
  10059. "Error: Path too long\nput_dir(%s): %s",
  10060. path,
  10061. strerror(ERRNO));
  10062. return;
  10063. }
  10064. if (rc == -2) {
  10065. /* put_dir returns -2 if the directory can not be created */
  10066. mg_send_http_error(conn,
  10067. 500,
  10068. "Error: Can not create directory\nput_dir(%s): %s",
  10069. path,
  10070. strerror(ERRNO));
  10071. return;
  10072. }
  10073. /* A file should be created or overwritten. */
  10074. /* Currently CivetWeb does not nead read+write access. */
  10075. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10076. || file.access.fp == NULL) {
  10077. (void)mg_fclose(&file.access);
  10078. mg_send_http_error(conn,
  10079. 500,
  10080. "Error: Can not create file\nfopen(%s): %s",
  10081. path,
  10082. strerror(ERRNO));
  10083. return;
  10084. }
  10085. fclose_on_exec(&file.access, conn);
  10086. range = mg_get_header(conn, "Content-Range");
  10087. r1 = r2 = 0;
  10088. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10089. conn->status_code = 206; /* Partial content */
  10090. fseeko(file.access.fp, r1, SEEK_SET);
  10091. }
  10092. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10093. /* forward_body_data failed.
  10094. * The error code has already been sent to the client,
  10095. * and conn->status_code is already set. */
  10096. (void)mg_fclose(&file.access);
  10097. return;
  10098. }
  10099. if (mg_fclose(&file.access) != 0) {
  10100. /* fclose failed. This might have different reasons, but a likely
  10101. * one is "no space on disk", http 507. */
  10102. conn->status_code = 507;
  10103. }
  10104. gmt_time_string(date, sizeof(date), &curtime);
  10105. mg_printf(conn,
  10106. "HTTP/1.1 %d %s\r\n",
  10107. conn->status_code,
  10108. mg_get_response_code_text(NULL, conn->status_code));
  10109. send_no_cache_header(conn);
  10110. send_additional_header(conn);
  10111. mg_printf(conn,
  10112. "Date: %s\r\n"
  10113. "Content-Length: 0\r\n"
  10114. "Connection: %s\r\n\r\n",
  10115. date,
  10116. suggest_connection_header(conn));
  10117. }
  10118. static void
  10119. delete_file(struct mg_connection *conn, const char *path)
  10120. {
  10121. struct de de;
  10122. memset(&de.file, 0, sizeof(de.file));
  10123. if (!mg_stat(conn, path, &de.file)) {
  10124. /* mg_stat returns 0 if the file does not exist */
  10125. mg_send_http_error(conn,
  10126. 404,
  10127. "Error: Cannot delete file\nFile %s not found",
  10128. path);
  10129. return;
  10130. }
  10131. #if 0 /* Ignore if a file in memory is inside a folder */
  10132. if (de.access.membuf != NULL) {
  10133. /* the file is cached in memory */
  10134. mg_send_http_error(
  10135. conn,
  10136. 405,
  10137. "Error: Delete not possible\nDeleting %s is not supported",
  10138. path);
  10139. return;
  10140. }
  10141. #endif
  10142. if (de.file.is_directory) {
  10143. if (remove_directory(conn, path)) {
  10144. /* Delete is successful: Return 204 without content. */
  10145. mg_send_http_error(conn, 204, "%s", "");
  10146. } else {
  10147. /* Delete is not successful: Return 500 (Server error). */
  10148. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10149. }
  10150. return;
  10151. }
  10152. /* This is an existing file (not a directory).
  10153. * Check if write permission is granted. */
  10154. if (access(path, W_OK) != 0) {
  10155. /* File is read only */
  10156. mg_send_http_error(
  10157. conn,
  10158. 403,
  10159. "Error: Delete not possible\nDeleting %s is not allowed",
  10160. path);
  10161. return;
  10162. }
  10163. /* Try to delete it. */
  10164. if (mg_remove(conn, path) == 0) {
  10165. /* Delete was successful: Return 204 without content. */
  10166. mg_send_http_error(conn, 204, "%s", "");
  10167. } else {
  10168. /* Delete not successful (file locked). */
  10169. mg_send_http_error(conn,
  10170. 423,
  10171. "Error: Cannot delete file\nremove(%s): %s",
  10172. path,
  10173. strerror(ERRNO));
  10174. }
  10175. }
  10176. #endif /* !NO_FILES */
  10177. #if !defined(NO_FILESYSTEMS)
  10178. static void
  10179. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10180. static void
  10181. do_ssi_include(struct mg_connection *conn,
  10182. const char *ssi,
  10183. char *tag,
  10184. int include_level)
  10185. {
  10186. char file_name[MG_BUF_LEN], path[512], *p;
  10187. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10188. size_t len;
  10189. int truncated = 0;
  10190. if (conn == NULL) {
  10191. return;
  10192. }
  10193. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10194. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10195. * always < MG_BUF_LEN. */
  10196. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10197. /* File name is relative to the webserver root */
  10198. file_name[511] = 0;
  10199. (void)mg_snprintf(conn,
  10200. &truncated,
  10201. path,
  10202. sizeof(path),
  10203. "%s/%s",
  10204. conn->dom_ctx->config[DOCUMENT_ROOT],
  10205. file_name);
  10206. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10207. /* File name is relative to the webserver working directory
  10208. * or it is absolute system path */
  10209. file_name[511] = 0;
  10210. (void)
  10211. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10212. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10213. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10214. /* File name is relative to the currect document */
  10215. file_name[511] = 0;
  10216. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10217. if (!truncated) {
  10218. if ((p = strrchr(path, '/')) != NULL) {
  10219. p[1] = '\0';
  10220. }
  10221. len = strlen(path);
  10222. (void)mg_snprintf(conn,
  10223. &truncated,
  10224. path + len,
  10225. sizeof(path) - len,
  10226. "%s",
  10227. file_name);
  10228. }
  10229. } else {
  10230. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10231. return;
  10232. }
  10233. if (truncated) {
  10234. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10235. return;
  10236. }
  10237. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10238. mg_cry_internal(conn,
  10239. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10240. tag,
  10241. path,
  10242. strerror(ERRNO));
  10243. } else {
  10244. fclose_on_exec(&file.access, conn);
  10245. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10246. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10247. path)
  10248. > 0) {
  10249. send_ssi_file(conn, path, &file, include_level + 1);
  10250. } else {
  10251. send_file_data(conn, &file, 0, INT64_MAX);
  10252. }
  10253. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10254. }
  10255. }
  10256. #if !defined(NO_POPEN)
  10257. static void
  10258. do_ssi_exec(struct mg_connection *conn, char *tag)
  10259. {
  10260. char cmd[1024] = "";
  10261. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10262. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10263. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10264. } else {
  10265. cmd[1023] = 0;
  10266. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10267. mg_cry_internal(conn,
  10268. "Cannot SSI #exec: [%s]: %s",
  10269. cmd,
  10270. strerror(ERRNO));
  10271. } else {
  10272. send_file_data(conn, &file, 0, INT64_MAX);
  10273. pclose(file.access.fp);
  10274. }
  10275. }
  10276. }
  10277. #endif /* !NO_POPEN */
  10278. static int
  10279. mg_fgetc(struct mg_file *filep, int offset)
  10280. {
  10281. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10282. if (filep == NULL) {
  10283. return EOF;
  10284. }
  10285. #if defined(MG_USE_OPEN_FILE)
  10286. if ((filep->access.membuf != NULL) && (offset >= 0)
  10287. && (((unsigned int)(offset)) < filep->stat.size)) {
  10288. return ((const unsigned char *)filep->access.membuf)[offset];
  10289. } else /* else block below */
  10290. #endif
  10291. if (filep->access.fp != NULL) {
  10292. return fgetc(filep->access.fp);
  10293. } else {
  10294. return EOF;
  10295. }
  10296. }
  10297. static void
  10298. send_ssi_file(struct mg_connection *conn,
  10299. const char *path,
  10300. struct mg_file *filep,
  10301. int include_level)
  10302. {
  10303. char buf[MG_BUF_LEN];
  10304. int ch, offset, len, in_tag, in_ssi_tag;
  10305. if (include_level > 10) {
  10306. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10307. return;
  10308. }
  10309. in_tag = in_ssi_tag = len = offset = 0;
  10310. /* Read file, byte by byte, and look for SSI include tags */
  10311. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10312. if (in_tag) {
  10313. /* We are in a tag, either SSI tag or html tag */
  10314. if (ch == '>') {
  10315. /* Tag is closing */
  10316. buf[len++] = '>';
  10317. if (in_ssi_tag) {
  10318. /* Handle SSI tag */
  10319. buf[len] = 0;
  10320. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10321. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10322. #if !defined(NO_POPEN)
  10323. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10324. do_ssi_exec(conn, buf + 9);
  10325. #endif /* !NO_POPEN */
  10326. } else {
  10327. mg_cry_internal(conn,
  10328. "%s: unknown SSI "
  10329. "command: \"%s\"",
  10330. path,
  10331. buf);
  10332. }
  10333. len = 0;
  10334. in_ssi_tag = in_tag = 0;
  10335. } else {
  10336. /* Not an SSI tag */
  10337. /* Flush buffer */
  10338. (void)mg_write(conn, buf, (size_t)len);
  10339. len = 0;
  10340. in_tag = 0;
  10341. }
  10342. } else {
  10343. /* Tag is still open */
  10344. buf[len++] = (char)(ch & 0xff);
  10345. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10346. /* All SSI tags start with <!--# */
  10347. in_ssi_tag = 1;
  10348. }
  10349. if ((len + 2) > (int)sizeof(buf)) {
  10350. /* Tag to long for buffer */
  10351. mg_cry_internal(conn, "%s: tag is too large", path);
  10352. return;
  10353. }
  10354. }
  10355. } else {
  10356. /* We are not in a tag yet. */
  10357. if (ch == '<') {
  10358. /* Tag is opening */
  10359. in_tag = 1;
  10360. if (len > 0) {
  10361. /* Flush current buffer.
  10362. * Buffer is filled with "len" bytes. */
  10363. (void)mg_write(conn, buf, (size_t)len);
  10364. }
  10365. /* Store the < */
  10366. len = 1;
  10367. buf[0] = '<';
  10368. } else {
  10369. /* No Tag */
  10370. /* Add data to buffer */
  10371. buf[len++] = (char)(ch & 0xff);
  10372. /* Flush if buffer is full */
  10373. if (len == (int)sizeof(buf)) {
  10374. mg_write(conn, buf, (size_t)len);
  10375. len = 0;
  10376. }
  10377. }
  10378. }
  10379. }
  10380. /* Send the rest of buffered data */
  10381. if (len > 0) {
  10382. mg_write(conn, buf, (size_t)len);
  10383. }
  10384. }
  10385. static void
  10386. handle_ssi_file_request(struct mg_connection *conn,
  10387. const char *path,
  10388. struct mg_file *filep)
  10389. {
  10390. char date[64];
  10391. time_t curtime = time(NULL);
  10392. const char *cors_orig_cfg;
  10393. const char *cors1, *cors2, *cors3;
  10394. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10395. return;
  10396. }
  10397. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10398. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10399. /* Cross-origin resource sharing (CORS). */
  10400. cors1 = "Access-Control-Allow-Origin: ";
  10401. cors2 = cors_orig_cfg;
  10402. cors3 = "\r\n";
  10403. } else {
  10404. cors1 = cors2 = cors3 = "";
  10405. }
  10406. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10407. /* File exists (precondition for calling this function),
  10408. * but can not be opened by the server. */
  10409. mg_send_http_error(conn,
  10410. 500,
  10411. "Error: Cannot read file\nfopen(%s): %s",
  10412. path,
  10413. strerror(ERRNO));
  10414. } else {
  10415. conn->must_close = 1;
  10416. gmt_time_string(date, sizeof(date), &curtime);
  10417. fclose_on_exec(&filep->access, conn);
  10418. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10419. send_no_cache_header(conn);
  10420. send_additional_header(conn);
  10421. mg_printf(conn,
  10422. "%s%s%s"
  10423. "Date: %s\r\n"
  10424. "Content-Type: text/html\r\n"
  10425. "Connection: %s\r\n\r\n",
  10426. cors1,
  10427. cors2,
  10428. cors3,
  10429. date,
  10430. suggest_connection_header(conn));
  10431. send_ssi_file(conn, path, filep, 0);
  10432. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10433. }
  10434. }
  10435. #endif /* NO_FILESYSTEMS */
  10436. #if !defined(NO_FILES)
  10437. static void
  10438. send_options(struct mg_connection *conn)
  10439. {
  10440. char date[64];
  10441. time_t curtime = time(NULL);
  10442. if (!conn) {
  10443. return;
  10444. }
  10445. conn->status_code = 200;
  10446. conn->must_close = 1;
  10447. gmt_time_string(date, sizeof(date), &curtime);
  10448. /* We do not set a "Cache-Control" header here, but leave the default.
  10449. * Since browsers do not send an OPTIONS request, we can not test the
  10450. * effect anyway. */
  10451. mg_printf(conn,
  10452. "HTTP/1.1 200 OK\r\n"
  10453. "Date: %s\r\n"
  10454. "Connection: %s\r\n"
  10455. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10456. "PROPFIND, MKCOL\r\n"
  10457. "DAV: 1\r\n",
  10458. date,
  10459. suggest_connection_header(conn));
  10460. send_additional_header(conn);
  10461. mg_printf(conn, "\r\n");
  10462. }
  10463. /* Writes PROPFIND properties for a collection element */
  10464. static int
  10465. print_props(struct mg_connection *conn,
  10466. const char *uri,
  10467. const char *name,
  10468. struct mg_file_stat *filep)
  10469. {
  10470. size_t href_size, i, j;
  10471. int len;
  10472. char *href, mtime[64];
  10473. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10474. return 0;
  10475. }
  10476. /* Estimate worst case size for encoding */
  10477. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10478. href = (char *)mg_malloc(href_size);
  10479. if (href == NULL) {
  10480. return 0;
  10481. }
  10482. len = mg_url_encode(uri, href, href_size);
  10483. if (len >= 0) {
  10484. /* Append an extra string */
  10485. mg_url_encode(name, href + len, href_size - (size_t)len);
  10486. }
  10487. /* Directory separator should be preserved. */
  10488. for (i = j = 0; href[i]; j++) {
  10489. if (!strncmp(href + i, "%2f", 3)) {
  10490. href[j] = '/';
  10491. i += 3;
  10492. } else {
  10493. href[j] = href[i++];
  10494. }
  10495. }
  10496. href[j] = '\0';
  10497. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10498. mg_printf(conn,
  10499. "<d:response>"
  10500. "<d:href>%s</d:href>"
  10501. "<d:propstat>"
  10502. "<d:prop>"
  10503. "<d:resourcetype>%s</d:resourcetype>"
  10504. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10505. "<d:getlastmodified>%s</d:getlastmodified>"
  10506. "</d:prop>"
  10507. "<d:status>HTTP/1.1 200 OK</d:status>"
  10508. "</d:propstat>"
  10509. "</d:response>\n",
  10510. href,
  10511. filep->is_directory ? "<d:collection/>" : "",
  10512. filep->size,
  10513. mtime);
  10514. mg_free(href);
  10515. return 1;
  10516. }
  10517. static int
  10518. print_dav_dir_entry(struct de *de, void *data)
  10519. {
  10520. struct mg_connection *conn = (struct mg_connection *)data;
  10521. if (!de || !conn
  10522. || !print_props(
  10523. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10524. return -1;
  10525. }
  10526. return 0;
  10527. }
  10528. static void
  10529. handle_propfind(struct mg_connection *conn,
  10530. const char *path,
  10531. struct mg_file_stat *filep)
  10532. {
  10533. const char *depth = mg_get_header(conn, "Depth");
  10534. char date[64];
  10535. time_t curtime = time(NULL);
  10536. gmt_time_string(date, sizeof(date), &curtime);
  10537. if (!conn || !path || !filep || !conn->dom_ctx) {
  10538. return;
  10539. }
  10540. conn->must_close = 1;
  10541. conn->status_code = 207;
  10542. mg_printf(conn,
  10543. "HTTP/1.1 207 Multi-Status\r\n"
  10544. "Date: %s\r\n",
  10545. date);
  10546. send_static_cache_header(conn);
  10547. send_additional_header(conn);
  10548. mg_printf(conn,
  10549. "Connection: %s\r\n"
  10550. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10551. suggest_connection_header(conn));
  10552. mg_printf(conn,
  10553. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10554. "<d:multistatus xmlns:d='DAV:'>\n");
  10555. /* Print properties for the requested resource itself */
  10556. print_props(conn, conn->request_info.local_uri, "", filep);
  10557. /* If it is a directory, print directory entries too if Depth is not 0
  10558. */
  10559. if (filep->is_directory
  10560. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10561. "yes")
  10562. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10563. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10564. }
  10565. mg_printf(conn, "%s\n", "</d:multistatus>");
  10566. }
  10567. #endif
  10568. void
  10569. mg_lock_connection(struct mg_connection *conn)
  10570. {
  10571. if (conn) {
  10572. (void)pthread_mutex_lock(&conn->mutex);
  10573. }
  10574. }
  10575. void
  10576. mg_unlock_connection(struct mg_connection *conn)
  10577. {
  10578. if (conn) {
  10579. (void)pthread_mutex_unlock(&conn->mutex);
  10580. }
  10581. }
  10582. void
  10583. mg_lock_context(struct mg_context *ctx)
  10584. {
  10585. if (ctx) {
  10586. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10587. }
  10588. }
  10589. void
  10590. mg_unlock_context(struct mg_context *ctx)
  10591. {
  10592. if (ctx) {
  10593. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10594. }
  10595. }
  10596. #if defined(USE_LUA)
  10597. #include "mod_lua.inl"
  10598. #endif /* USE_LUA */
  10599. #if defined(USE_DUKTAPE)
  10600. #include "mod_duktape.inl"
  10601. #endif /* USE_DUKTAPE */
  10602. #if defined(USE_WEBSOCKET)
  10603. #if !defined(NO_SSL_DL)
  10604. #define SHA_API static
  10605. #include "sha1.inl"
  10606. #endif
  10607. static int
  10608. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10609. {
  10610. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10611. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10612. SHA_CTX sha_ctx;
  10613. int truncated;
  10614. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10615. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10616. if (truncated) {
  10617. conn->must_close = 1;
  10618. return 0;
  10619. }
  10620. DEBUG_TRACE("%s", "Send websocket handshake");
  10621. SHA1_Init(&sha_ctx);
  10622. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10623. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10624. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10625. mg_printf(conn,
  10626. "HTTP/1.1 101 Switching Protocols\r\n"
  10627. "Upgrade: websocket\r\n"
  10628. "Connection: Upgrade\r\n"
  10629. "Sec-WebSocket-Accept: %s\r\n",
  10630. b64_sha);
  10631. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10632. mg_printf(conn,
  10633. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10634. conn->request_info.acceptedWebSocketSubprotocol);
  10635. } else {
  10636. mg_printf(conn, "%s", "\r\n");
  10637. }
  10638. return 1;
  10639. }
  10640. #if !defined(MG_MAX_UNANSWERED_PING)
  10641. /* Configuration of the maximum number of websocket PINGs that might
  10642. * stay unanswered before the connection is considered broken.
  10643. * Note: The name of this define may still change (until it is
  10644. * defined as a compile parameter in a documentation).
  10645. */
  10646. #define MG_MAX_UNANSWERED_PING (5)
  10647. #endif
  10648. static void
  10649. read_websocket(struct mg_connection *conn,
  10650. mg_websocket_data_handler ws_data_handler,
  10651. void *callback_data)
  10652. {
  10653. /* Pointer to the beginning of the portion of the incoming websocket
  10654. * message queue.
  10655. * The original websocket upgrade request is never removed, so the queue
  10656. * begins after it. */
  10657. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10658. int n, error, exit_by_callback;
  10659. int ret;
  10660. /* body_len is the length of the entire queue in bytes
  10661. * len is the length of the current message
  10662. * data_len is the length of the current message's data payload
  10663. * header_len is the length of the current message's header */
  10664. size_t i, len, mask_len = 0, header_len, body_len;
  10665. uint64_t data_len = 0;
  10666. /* "The masking key is a 32-bit value chosen at random by the client."
  10667. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10668. */
  10669. unsigned char mask[4];
  10670. /* data points to the place where the message is stored when passed to
  10671. * the websocket_data callback. This is either mem on the stack, or a
  10672. * dynamically allocated buffer if it is too large. */
  10673. unsigned char mem[4096];
  10674. unsigned char mop; /* mask flag and opcode */
  10675. /* Variables used for connection monitoring */
  10676. double timeout = -1.0;
  10677. int enable_ping_pong = 0;
  10678. int ping_count = 0;
  10679. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10680. enable_ping_pong =
  10681. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10682. "yes");
  10683. }
  10684. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10685. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10686. }
  10687. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10688. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10689. }
  10690. /* Enter data processing loop */
  10691. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10692. conn->request_info.remote_addr,
  10693. conn->request_info.remote_port);
  10694. conn->in_websocket_handling = 1;
  10695. mg_set_thread_name("wsock");
  10696. /* Loop continuously, reading messages from the socket, invoking the
  10697. * callback, and waiting repeatedly until an error occurs. */
  10698. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10699. header_len = 0;
  10700. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10701. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10702. len = buf[1] & 127;
  10703. mask_len = (buf[1] & 128) ? 4 : 0;
  10704. if ((len < 126) && (body_len >= mask_len)) {
  10705. /* inline 7-bit length field */
  10706. data_len = len;
  10707. header_len = 2 + mask_len;
  10708. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10709. /* 16-bit length field */
  10710. header_len = 4 + mask_len;
  10711. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10712. } else if (body_len >= (10 + mask_len)) {
  10713. /* 64-bit length field */
  10714. uint32_t l1, l2;
  10715. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10716. memcpy(&l2, &buf[6], 4);
  10717. header_len = 10 + mask_len;
  10718. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10719. if (data_len > (uint64_t)0x7FFF0000ul) {
  10720. /* no can do */
  10721. mg_cry_internal(
  10722. conn,
  10723. "%s",
  10724. "websocket out of memory; closing connection");
  10725. break;
  10726. }
  10727. }
  10728. }
  10729. if ((header_len > 0) && (body_len >= header_len)) {
  10730. /* Allocate space to hold websocket payload */
  10731. unsigned char *data = mem;
  10732. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10733. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10734. conn->phys_ctx);
  10735. if (data == NULL) {
  10736. /* Allocation failed, exit the loop and then close the
  10737. * connection */
  10738. mg_cry_internal(
  10739. conn,
  10740. "%s",
  10741. "websocket out of memory; closing connection");
  10742. break;
  10743. }
  10744. }
  10745. /* Copy the mask before we shift the queue and destroy it */
  10746. if (mask_len > 0) {
  10747. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10748. } else {
  10749. memset(mask, 0, sizeof(mask));
  10750. }
  10751. /* Read frame payload from the first message in the queue into
  10752. * data and advance the queue by moving the memory in place. */
  10753. DEBUG_ASSERT(body_len >= header_len);
  10754. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10755. mop = buf[0]; /* current mask and opcode */
  10756. /* Overflow case */
  10757. len = body_len - header_len;
  10758. memcpy(data, buf + header_len, len);
  10759. error = 0;
  10760. while ((uint64_t)len < data_len) {
  10761. n = pull_inner(NULL,
  10762. conn,
  10763. (char *)(data + len),
  10764. (int)(data_len - len),
  10765. timeout);
  10766. if (n <= -2) {
  10767. error = 1;
  10768. break;
  10769. } else if (n > 0) {
  10770. len += (size_t)n;
  10771. } else {
  10772. /* Timeout: should retry */
  10773. /* TODO: retry condition */
  10774. }
  10775. }
  10776. if (error) {
  10777. mg_cry_internal(
  10778. conn,
  10779. "%s",
  10780. "Websocket pull failed; closing connection");
  10781. if (data != mem) {
  10782. mg_free(data);
  10783. }
  10784. break;
  10785. }
  10786. conn->data_len = conn->request_len;
  10787. } else {
  10788. mop = buf[0]; /* current mask and opcode, overwritten by
  10789. * memmove() */
  10790. /* Length of the message being read at the front of the
  10791. * queue. Cast to 31 bit is OK, since we limited
  10792. * data_len before. */
  10793. len = (size_t)data_len + header_len;
  10794. /* Copy the data payload into the data pointer for the
  10795. * callback. Cast to 31 bit is OK, since we
  10796. * limited data_len */
  10797. memcpy(data, buf + header_len, (size_t)data_len);
  10798. /* Move the queue forward len bytes */
  10799. memmove(buf, buf + len, body_len - len);
  10800. /* Mark the queue as advanced */
  10801. conn->data_len -= (int)len;
  10802. }
  10803. /* Apply mask if necessary */
  10804. if (mask_len > 0) {
  10805. for (i = 0; i < (size_t)data_len; i++) {
  10806. data[i] ^= mask[i & 3];
  10807. }
  10808. }
  10809. exit_by_callback = 0;
  10810. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10811. /* filter PONG messages */
  10812. DEBUG_TRACE("PONG from %s:%u",
  10813. conn->request_info.remote_addr,
  10814. conn->request_info.remote_port);
  10815. /* No unanwered PINGs left */
  10816. ping_count = 0;
  10817. } else if (enable_ping_pong
  10818. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10819. /* reply PING messages */
  10820. DEBUG_TRACE("Reply PING from %s:%u",
  10821. conn->request_info.remote_addr,
  10822. conn->request_info.remote_port);
  10823. ret = mg_websocket_write(conn,
  10824. MG_WEBSOCKET_OPCODE_PONG,
  10825. (char *)data,
  10826. (size_t)data_len);
  10827. if (ret <= 0) {
  10828. /* Error: send failed */
  10829. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10830. break;
  10831. }
  10832. } else {
  10833. /* Exit the loop if callback signals to exit (server side),
  10834. * or "connection close" opcode received (client side). */
  10835. if ((ws_data_handler != NULL)
  10836. && !ws_data_handler(conn,
  10837. mop,
  10838. (char *)data,
  10839. (size_t)data_len,
  10840. callback_data)) {
  10841. exit_by_callback = 1;
  10842. }
  10843. }
  10844. /* It a buffer has been allocated, free it again */
  10845. if (data != mem) {
  10846. mg_free(data);
  10847. }
  10848. if (exit_by_callback) {
  10849. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10850. conn->request_info.remote_addr,
  10851. conn->request_info.remote_port);
  10852. break;
  10853. }
  10854. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10855. /* Opcode == 8, connection close */
  10856. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10857. conn->request_info.remote_addr,
  10858. conn->request_info.remote_port);
  10859. break;
  10860. }
  10861. /* Not breaking the loop, process next websocket frame. */
  10862. } else {
  10863. /* Read from the socket into the next available location in the
  10864. * message queue. */
  10865. n = pull_inner(NULL,
  10866. conn,
  10867. conn->buf + conn->data_len,
  10868. conn->buf_size - conn->data_len,
  10869. timeout);
  10870. if (n <= -2) {
  10871. /* Error, no bytes read */
  10872. DEBUG_TRACE("PULL from %s:%u failed",
  10873. conn->request_info.remote_addr,
  10874. conn->request_info.remote_port);
  10875. break;
  10876. }
  10877. if (n > 0) {
  10878. conn->data_len += n;
  10879. /* Reset open PING count */
  10880. ping_count = 0;
  10881. } else {
  10882. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10883. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10884. /* Stop sending PING */
  10885. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10886. "- closing connection",
  10887. ping_count,
  10888. conn->request_info.remote_addr,
  10889. conn->request_info.remote_port);
  10890. break;
  10891. }
  10892. if (enable_ping_pong) {
  10893. /* Send Websocket PING message */
  10894. DEBUG_TRACE("PING to %s:%u",
  10895. conn->request_info.remote_addr,
  10896. conn->request_info.remote_port);
  10897. ret = mg_websocket_write(conn,
  10898. MG_WEBSOCKET_OPCODE_PING,
  10899. NULL,
  10900. 0);
  10901. if (ret <= 0) {
  10902. /* Error: send failed */
  10903. DEBUG_TRACE("Send PING failed (%i)", ret);
  10904. break;
  10905. }
  10906. ping_count++;
  10907. }
  10908. }
  10909. /* Timeout: should retry */
  10910. /* TODO: get timeout def */
  10911. }
  10912. }
  10913. }
  10914. /* Leave data processing loop */
  10915. mg_set_thread_name("worker");
  10916. conn->in_websocket_handling = 0;
  10917. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10918. conn->request_info.remote_addr,
  10919. conn->request_info.remote_port);
  10920. }
  10921. static int
  10922. mg_websocket_write_exec(struct mg_connection *conn,
  10923. int opcode,
  10924. const char *data,
  10925. size_t dataLen,
  10926. uint32_t masking_key)
  10927. {
  10928. unsigned char header[14];
  10929. size_t headerLen;
  10930. int retval;
  10931. #if defined(GCC_DIAGNOSTIC)
  10932. /* Disable spurious conversion warning for GCC */
  10933. #pragma GCC diagnostic push
  10934. #pragma GCC diagnostic ignored "-Wconversion"
  10935. #endif
  10936. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10937. #if defined(GCC_DIAGNOSTIC)
  10938. #pragma GCC diagnostic pop
  10939. #endif
  10940. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10941. if (dataLen < 126) {
  10942. /* inline 7-bit length field */
  10943. header[1] = (unsigned char)dataLen;
  10944. headerLen = 2;
  10945. } else if (dataLen <= 0xFFFF) {
  10946. /* 16-bit length field */
  10947. uint16_t len = htons((uint16_t)dataLen);
  10948. header[1] = 126;
  10949. memcpy(header + 2, &len, 2);
  10950. headerLen = 4;
  10951. } else {
  10952. /* 64-bit length field */
  10953. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10954. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10955. header[1] = 127;
  10956. memcpy(header + 2, &len1, 4);
  10957. memcpy(header + 6, &len2, 4);
  10958. headerLen = 10;
  10959. }
  10960. if (masking_key) {
  10961. /* add mask */
  10962. header[1] |= 0x80;
  10963. memcpy(header + headerLen, &masking_key, 4);
  10964. headerLen += 4;
  10965. }
  10966. /* Note that POSIX/Winsock's send() is threadsafe
  10967. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10968. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10969. * push(), although that is only a problem if the packet is large or
  10970. * outgoing buffer is full). */
  10971. /* TODO: Check if this lock should be moved to user land.
  10972. * Currently the server sets this lock for websockets, but
  10973. * not for any other connection. It must be set for every
  10974. * conn read/written by more than one thread, no matter if
  10975. * it is a websocket or regular connection. */
  10976. (void)mg_lock_connection(conn);
  10977. retval = mg_write(conn, header, headerLen);
  10978. if (retval != (int)headerLen) {
  10979. /* Did not send complete header */
  10980. retval = -1;
  10981. } else {
  10982. if (dataLen > 0) {
  10983. retval = mg_write(conn, data, dataLen);
  10984. }
  10985. /* if dataLen == 0, the header length (2) is returned */
  10986. }
  10987. /* TODO: Remove this unlock as well, when lock is removed. */
  10988. mg_unlock_connection(conn);
  10989. return retval;
  10990. }
  10991. int
  10992. mg_websocket_write(struct mg_connection *conn,
  10993. int opcode,
  10994. const char *data,
  10995. size_t dataLen)
  10996. {
  10997. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10998. }
  10999. static void
  11000. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11001. {
  11002. size_t i = 0;
  11003. i = 0;
  11004. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11005. /* Convert in 32 bit words, if data is 4 byte aligned */
  11006. while (i < (in_len - 3)) {
  11007. *(uint32_t *)(void *)(out + i) =
  11008. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11009. i += 4;
  11010. }
  11011. }
  11012. if (i != in_len) {
  11013. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11014. while (i < in_len) {
  11015. *(uint8_t *)(void *)(out + i) =
  11016. *(uint8_t *)(void *)(in + i)
  11017. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11018. i++;
  11019. }
  11020. }
  11021. }
  11022. int
  11023. mg_websocket_client_write(struct mg_connection *conn,
  11024. int opcode,
  11025. const char *data,
  11026. size_t dataLen)
  11027. {
  11028. int retval = -1;
  11029. char *masked_data =
  11030. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11031. uint32_t masking_key = 0;
  11032. if (masked_data == NULL) {
  11033. /* Return -1 in an error case */
  11034. mg_cry_internal(conn,
  11035. "%s",
  11036. "Cannot allocate buffer for masked websocket response: "
  11037. "Out of memory");
  11038. return -1;
  11039. }
  11040. do {
  11041. /* Get a masking key - but not 0 */
  11042. masking_key = (uint32_t)get_random();
  11043. } while (masking_key == 0);
  11044. mask_data(data, dataLen, masking_key, masked_data);
  11045. retval = mg_websocket_write_exec(
  11046. conn, opcode, masked_data, dataLen, masking_key);
  11047. mg_free(masked_data);
  11048. return retval;
  11049. }
  11050. static void
  11051. handle_websocket_request(struct mg_connection *conn,
  11052. const char *path,
  11053. int is_callback_resource,
  11054. struct mg_websocket_subprotocols *subprotocols,
  11055. mg_websocket_connect_handler ws_connect_handler,
  11056. mg_websocket_ready_handler ws_ready_handler,
  11057. mg_websocket_data_handler ws_data_handler,
  11058. mg_websocket_close_handler ws_close_handler,
  11059. void *cbData)
  11060. {
  11061. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11062. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11063. ptrdiff_t lua_websock = 0;
  11064. #if !defined(USE_LUA)
  11065. (void)path;
  11066. #endif
  11067. /* Step 1: Check websocket protocol version. */
  11068. /* Step 1.1: Check Sec-WebSocket-Key. */
  11069. if (!websock_key) {
  11070. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11071. * requires a Sec-WebSocket-Key header.
  11072. */
  11073. /* It could be the hixie draft version
  11074. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11075. */
  11076. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11077. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11078. char key3[8];
  11079. if ((key1 != NULL) && (key2 != NULL)) {
  11080. /* This version uses 8 byte body data in a GET request */
  11081. conn->content_len = 8;
  11082. if (8 == mg_read(conn, key3, 8)) {
  11083. /* This is the hixie version */
  11084. mg_send_http_error(conn,
  11085. 426,
  11086. "%s",
  11087. "Protocol upgrade to RFC 6455 required");
  11088. return;
  11089. }
  11090. }
  11091. /* This is an unknown version */
  11092. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11093. return;
  11094. }
  11095. /* Step 1.2: Check websocket protocol version. */
  11096. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11097. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11098. /* Reject wrong versions */
  11099. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11100. return;
  11101. }
  11102. /* Step 1.3: Could check for "Host", but we do not really nead this
  11103. * value for anything, so just ignore it. */
  11104. /* Step 2: If a callback is responsible, call it. */
  11105. if (is_callback_resource) {
  11106. /* Step 2.1 check and select subprotocol */
  11107. const char *protocols[64]; // max 64 headers
  11108. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11109. "Sec-WebSocket-Protocol",
  11110. protocols,
  11111. 64);
  11112. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11113. int cnt = 0;
  11114. int idx;
  11115. unsigned long len;
  11116. const char *sep, *curSubProtocol,
  11117. *acceptedWebSocketSubprotocol = NULL;
  11118. /* look for matching subprotocol */
  11119. do {
  11120. const char *protocol = protocols[cnt];
  11121. do {
  11122. sep = strchr(protocol, ',');
  11123. curSubProtocol = protocol;
  11124. len = sep ? (unsigned long)(sep - protocol)
  11125. : (unsigned long)strlen(protocol);
  11126. while (sep && isspace((unsigned char)*++sep))
  11127. ; // ignore leading whitespaces
  11128. protocol = sep;
  11129. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11130. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11131. && (strncmp(curSubProtocol,
  11132. subprotocols->subprotocols[idx],
  11133. len)
  11134. == 0)) {
  11135. acceptedWebSocketSubprotocol =
  11136. subprotocols->subprotocols[idx];
  11137. break;
  11138. }
  11139. }
  11140. } while (sep && !acceptedWebSocketSubprotocol);
  11141. } while (++cnt < nbSubprotocolHeader
  11142. && !acceptedWebSocketSubprotocol);
  11143. conn->request_info.acceptedWebSocketSubprotocol =
  11144. acceptedWebSocketSubprotocol;
  11145. } else if (nbSubprotocolHeader > 0) {
  11146. /* keep legacy behavior */
  11147. const char *protocol = protocols[0];
  11148. /* The protocol is a comma separated list of names. */
  11149. /* The server must only return one value from this list. */
  11150. /* First check if it is a list or just a single value. */
  11151. const char *sep = strrchr(protocol, ',');
  11152. if (sep == NULL) {
  11153. /* Just a single protocol -> accept it. */
  11154. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11155. } else {
  11156. /* Multiple protocols -> accept the last one. */
  11157. /* This is just a quick fix if the client offers multiple
  11158. * protocols. The handler should have a list of accepted
  11159. * protocols on his own
  11160. * and use it to select one protocol among those the client
  11161. * has
  11162. * offered.
  11163. */
  11164. while (isspace((unsigned char)*++sep)) {
  11165. ; /* ignore leading whitespaces */
  11166. }
  11167. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11168. }
  11169. }
  11170. if ((ws_connect_handler != NULL)
  11171. && (ws_connect_handler(conn, cbData) != 0)) {
  11172. /* C callback has returned non-zero, do not proceed with
  11173. * handshake.
  11174. */
  11175. /* Note that C callbacks are no longer called when Lua is
  11176. * responsible, so C can no longer filter callbacks for Lua. */
  11177. return;
  11178. }
  11179. }
  11180. #if defined(USE_LUA)
  11181. /* Step 3: No callback. Check if Lua is responsible. */
  11182. else {
  11183. /* Step 3.1: Check if Lua is responsible. */
  11184. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11185. lua_websock = match_prefix(
  11186. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11187. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11188. path);
  11189. }
  11190. if (lua_websock) {
  11191. /* Step 3.2: Lua is responsible: call it. */
  11192. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11193. if (!conn->lua_websocket_state) {
  11194. /* Lua rejected the new client */
  11195. return;
  11196. }
  11197. }
  11198. }
  11199. #endif
  11200. /* Step 4: Check if there is a responsible websocket handler. */
  11201. if (!is_callback_resource && !lua_websock) {
  11202. /* There is no callback, and Lua is not responsible either. */
  11203. /* Reply with a 404 Not Found. We are still at a standard
  11204. * HTTP request here, before the websocket handshake, so
  11205. * we can still send standard HTTP error replies. */
  11206. mg_send_http_error(conn, 404, "%s", "Not found");
  11207. return;
  11208. }
  11209. /* Step 5: The websocket connection has been accepted */
  11210. if (!send_websocket_handshake(conn, websock_key)) {
  11211. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11212. return;
  11213. }
  11214. /* Step 6: Call the ready handler */
  11215. if (is_callback_resource) {
  11216. if (ws_ready_handler != NULL) {
  11217. ws_ready_handler(conn, cbData);
  11218. }
  11219. #if defined(USE_LUA)
  11220. } else if (lua_websock) {
  11221. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11222. /* the ready handler returned false */
  11223. return;
  11224. }
  11225. #endif
  11226. }
  11227. /* Step 7: Enter the read loop */
  11228. if (is_callback_resource) {
  11229. read_websocket(conn, ws_data_handler, cbData);
  11230. #if defined(USE_LUA)
  11231. } else if (lua_websock) {
  11232. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11233. #endif
  11234. }
  11235. /* Step 8: Call the close handler */
  11236. if (ws_close_handler) {
  11237. ws_close_handler(conn, cbData);
  11238. }
  11239. }
  11240. static int
  11241. is_websocket_protocol(const struct mg_connection *conn)
  11242. {
  11243. const char *upgrade, *connection;
  11244. /* A websocket protocoll has the following HTTP headers:
  11245. *
  11246. * Connection: Upgrade
  11247. * Upgrade: Websocket
  11248. */
  11249. upgrade = mg_get_header(conn, "Upgrade");
  11250. if (upgrade == NULL) {
  11251. return 0; /* fail early, don't waste time checking other header
  11252. * fields
  11253. */
  11254. }
  11255. DEBUG_TRACE("Upgrade: %s", upgrade);
  11256. if (!mg_strcasestr(upgrade, "websocket")) {
  11257. return 0;
  11258. }
  11259. connection = mg_get_header(conn, "Connection");
  11260. if (connection == NULL) {
  11261. return 0;
  11262. }
  11263. if (!mg_strcasestr(connection, "upgrade")) {
  11264. return 0;
  11265. }
  11266. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11267. * "Sec-WebSocket-Version" are also required.
  11268. * Don't check them here, since even an unsupported websocket protocol
  11269. * request still IS a websocket request (in contrast to a standard HTTP
  11270. * request). It will fail later in handle_websocket_request.
  11271. */
  11272. return 1;
  11273. }
  11274. #endif /* !USE_WEBSOCKET */
  11275. static int
  11276. isbyte(int n)
  11277. {
  11278. return (n >= 0) && (n <= 255);
  11279. }
  11280. static int
  11281. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11282. {
  11283. int n, a, b, c, d, slash = 32, len = 0;
  11284. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11285. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11286. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11287. && (slash < 33)) {
  11288. len = n;
  11289. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11290. | (uint32_t)d;
  11291. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11292. }
  11293. return len;
  11294. }
  11295. static int
  11296. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11297. {
  11298. int throttle = 0;
  11299. struct vec vec, val;
  11300. uint32_t net, mask;
  11301. char mult;
  11302. double v;
  11303. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11304. mult = ',';
  11305. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11306. || (v < 0)
  11307. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11308. && (mult != ','))) {
  11309. continue;
  11310. }
  11311. v *= (lowercase(&mult) == 'k')
  11312. ? 1024
  11313. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11314. if (vec.len == 1 && vec.ptr[0] == '*') {
  11315. throttle = (int)v;
  11316. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11317. if ((remote_ip & mask) == net) {
  11318. throttle = (int)v;
  11319. }
  11320. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11321. throttle = (int)v;
  11322. }
  11323. }
  11324. return throttle;
  11325. }
  11326. static uint32_t
  11327. get_remote_ip(const struct mg_connection *conn)
  11328. {
  11329. if (!conn) {
  11330. return 0;
  11331. }
  11332. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11333. }
  11334. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11335. #include "handle_form.inl"
  11336. #if defined(MG_LEGACY_INTERFACE)
  11337. /* Implement the deprecated mg_upload function by calling the new
  11338. * mg_handle_form_request function. While mg_upload could only handle
  11339. * HTML forms sent as POST request in multipart/form-data format
  11340. * containing only file input elements, mg_handle_form_request can
  11341. * handle all form input elements and all standard request methods. */
  11342. struct mg_upload_user_data {
  11343. struct mg_connection *conn;
  11344. const char *destination_dir;
  11345. int num_uploaded_files;
  11346. };
  11347. /* Helper function for deprecated mg_upload. */
  11348. static int
  11349. mg_upload_field_found(const char *key,
  11350. const char *filename,
  11351. char *path,
  11352. size_t pathlen,
  11353. void *user_data)
  11354. {
  11355. int truncated = 0;
  11356. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11357. (void)key;
  11358. if (!filename) {
  11359. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11360. return FORM_FIELD_STORAGE_ABORT;
  11361. }
  11362. mg_snprintf(fud->conn,
  11363. &truncated,
  11364. path,
  11365. pathlen - 1,
  11366. "%s/%s",
  11367. fud->destination_dir,
  11368. filename);
  11369. if (truncated) {
  11370. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11371. return FORM_FIELD_STORAGE_ABORT;
  11372. }
  11373. return FORM_FIELD_STORAGE_STORE;
  11374. }
  11375. /* Helper function for deprecated mg_upload. */
  11376. static int
  11377. mg_upload_field_get(const char *key,
  11378. const char *value,
  11379. size_t value_size,
  11380. void *user_data)
  11381. {
  11382. /* Function should never be called */
  11383. (void)key;
  11384. (void)value;
  11385. (void)value_size;
  11386. (void)user_data;
  11387. return 0;
  11388. }
  11389. /* Helper function for deprecated mg_upload. */
  11390. static int
  11391. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11392. {
  11393. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11394. (void)file_size;
  11395. fud->num_uploaded_files++;
  11396. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11397. return 0;
  11398. }
  11399. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11400. int
  11401. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11402. {
  11403. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11404. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11405. mg_upload_field_get,
  11406. mg_upload_field_stored,
  11407. 0};
  11408. int ret;
  11409. fdh.user_data = (void *)&fud;
  11410. ret = mg_handle_form_request(conn, &fdh);
  11411. if (ret < 0) {
  11412. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11413. }
  11414. return fud.num_uploaded_files;
  11415. }
  11416. #endif
  11417. static int
  11418. get_first_ssl_listener_index(const struct mg_context *ctx)
  11419. {
  11420. unsigned int i;
  11421. int idx = -1;
  11422. if (ctx) {
  11423. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11424. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11425. }
  11426. }
  11427. return idx;
  11428. }
  11429. /* Return host (without port) */
  11430. /* Use mg_free to free the result */
  11431. static const char *
  11432. alloc_get_host(struct mg_connection *conn)
  11433. {
  11434. char buf[1025];
  11435. size_t buflen = sizeof(buf);
  11436. const char *host_header = get_header(conn->request_info.http_headers,
  11437. conn->request_info.num_headers,
  11438. "Host");
  11439. char *host;
  11440. if (host_header != NULL) {
  11441. char *pos;
  11442. /* Create a local copy of the "Host" header, since it might be
  11443. * modified here. */
  11444. mg_strlcpy(buf, host_header, buflen);
  11445. buf[buflen - 1] = '\0';
  11446. host = buf;
  11447. while (isspace((unsigned char)*host)) {
  11448. host++;
  11449. }
  11450. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11451. * is found. */
  11452. if (*host == '[') {
  11453. pos = strchr(host, ']');
  11454. if (!pos) {
  11455. /* Malformed hostname starts with '[', but no ']' found */
  11456. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11457. return NULL;
  11458. }
  11459. /* terminate after ']' */
  11460. pos[1] = 0;
  11461. } else {
  11462. /* Otherwise, a ':' separates hostname and port number */
  11463. pos = strchr(host, ':');
  11464. if (pos != NULL) {
  11465. *pos = '\0';
  11466. }
  11467. }
  11468. if (conn->ssl) {
  11469. /* This is a HTTPS connection, maybe we have a hostname
  11470. * from SNI (set in ssl_servername_callback). */
  11471. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11472. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11473. /* We are not using the default domain */
  11474. if (mg_strcasecmp(host, sslhost)) {
  11475. /* Mismatch between SNI domain and HTTP domain */
  11476. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11477. sslhost,
  11478. host);
  11479. return NULL;
  11480. }
  11481. }
  11482. DEBUG_TRACE("HTTPS Host: %s", host);
  11483. } else {
  11484. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11485. while (dom) {
  11486. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11487. /* Found matching domain */
  11488. DEBUG_TRACE("HTTP domain %s found",
  11489. dom->config[AUTHENTICATION_DOMAIN]);
  11490. /* TODO: Check if this is a HTTP or HTTPS domain */
  11491. conn->dom_ctx = dom;
  11492. break;
  11493. }
  11494. dom = dom->next;
  11495. }
  11496. DEBUG_TRACE("HTTP Host: %s", host);
  11497. }
  11498. } else {
  11499. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11500. host = buf;
  11501. DEBUG_TRACE("IP: %s", host);
  11502. }
  11503. return mg_strdup_ctx(host, conn->phys_ctx);
  11504. }
  11505. static void
  11506. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11507. {
  11508. char target_url[MG_BUF_LEN];
  11509. int truncated = 0;
  11510. conn->must_close = 1;
  11511. /* Send host, port, uri and (if it exists) ?query_string */
  11512. if (conn->host) {
  11513. /* Use "308 Permanent Redirect" */
  11514. int redirect_code = 308;
  11515. /* Create target URL */
  11516. mg_snprintf(
  11517. conn,
  11518. &truncated,
  11519. target_url,
  11520. sizeof(target_url),
  11521. "https://%s:%d%s%s%s",
  11522. conn->host,
  11523. #if defined(USE_IPV6)
  11524. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11525. == AF_INET6)
  11526. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11527. .lsa.sin6.sin6_port)
  11528. :
  11529. #endif
  11530. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11531. .lsa.sin.sin_port),
  11532. conn->request_info.local_uri,
  11533. (conn->request_info.query_string == NULL) ? "" : "?",
  11534. (conn->request_info.query_string == NULL)
  11535. ? ""
  11536. : conn->request_info.query_string);
  11537. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11538. * is used as buffer size) */
  11539. if (truncated) {
  11540. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11541. return;
  11542. }
  11543. /* Use redirect helper function */
  11544. mg_send_http_redirect(conn, target_url, redirect_code);
  11545. }
  11546. }
  11547. static void
  11548. handler_info_acquire(struct mg_handler_info *handler_info)
  11549. {
  11550. pthread_mutex_lock(&handler_info->refcount_mutex);
  11551. handler_info->refcount++;
  11552. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11553. }
  11554. static void
  11555. handler_info_release(struct mg_handler_info *handler_info)
  11556. {
  11557. pthread_mutex_lock(&handler_info->refcount_mutex);
  11558. handler_info->refcount--;
  11559. pthread_cond_signal(&handler_info->refcount_cond);
  11560. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11561. }
  11562. static void
  11563. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11564. {
  11565. pthread_mutex_lock(&handler_info->refcount_mutex);
  11566. while (handler_info->refcount) {
  11567. pthread_cond_wait(&handler_info->refcount_cond,
  11568. &handler_info->refcount_mutex);
  11569. }
  11570. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11571. }
  11572. static void
  11573. mg_set_handler_type(struct mg_context *phys_ctx,
  11574. struct mg_domain_context *dom_ctx,
  11575. const char *uri,
  11576. int handler_type,
  11577. int is_delete_request,
  11578. mg_request_handler handler,
  11579. struct mg_websocket_subprotocols *subprotocols,
  11580. mg_websocket_connect_handler connect_handler,
  11581. mg_websocket_ready_handler ready_handler,
  11582. mg_websocket_data_handler data_handler,
  11583. mg_websocket_close_handler close_handler,
  11584. mg_authorization_handler auth_handler,
  11585. void *cbdata)
  11586. {
  11587. struct mg_handler_info *tmp_rh, **lastref;
  11588. size_t urilen = strlen(uri);
  11589. struct mg_workerTLS tls;
  11590. int is_tls_set = 0;
  11591. if (handler_type == WEBSOCKET_HANDLER) {
  11592. DEBUG_ASSERT(handler == NULL);
  11593. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11594. || ready_handler != NULL || data_handler != NULL
  11595. || close_handler != NULL);
  11596. DEBUG_ASSERT(auth_handler == NULL);
  11597. if (handler != NULL) {
  11598. return;
  11599. }
  11600. if (!is_delete_request && (connect_handler == NULL)
  11601. && (ready_handler == NULL) && (data_handler == NULL)
  11602. && (close_handler == NULL)) {
  11603. return;
  11604. }
  11605. if (auth_handler != NULL) {
  11606. return;
  11607. }
  11608. } else if (handler_type == REQUEST_HANDLER) {
  11609. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11610. && data_handler == NULL && close_handler == NULL);
  11611. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11612. DEBUG_ASSERT(auth_handler == NULL);
  11613. if ((connect_handler != NULL) || (ready_handler != NULL)
  11614. || (data_handler != NULL) || (close_handler != NULL)) {
  11615. return;
  11616. }
  11617. if (!is_delete_request && (handler == NULL)) {
  11618. return;
  11619. }
  11620. if (auth_handler != NULL) {
  11621. return;
  11622. }
  11623. } else { /* AUTH_HANDLER */
  11624. DEBUG_ASSERT(handler == NULL);
  11625. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11626. && data_handler == NULL && close_handler == NULL);
  11627. DEBUG_ASSERT(auth_handler != NULL);
  11628. if (handler != NULL) {
  11629. return;
  11630. }
  11631. if ((connect_handler != NULL) || (ready_handler != NULL)
  11632. || (data_handler != NULL) || (close_handler != NULL)) {
  11633. return;
  11634. }
  11635. if (!is_delete_request && (auth_handler == NULL)) {
  11636. return;
  11637. }
  11638. }
  11639. if (!phys_ctx || !dom_ctx) {
  11640. return;
  11641. }
  11642. /* Internal callbacks have their contexts set
  11643. * if called from non-related thread, context must be set
  11644. * since internal function assumes it exists.
  11645. * For an example see how handler_info_wait_unused()
  11646. * waits for reference to become zero
  11647. */
  11648. if (NULL == pthread_getspecific(sTlsKey)) {
  11649. is_tls_set = 1;
  11650. tls.is_master = -1;
  11651. tls.thread_idx = phys_ctx->starter_thread_idx;
  11652. #if defined(_WIN32)
  11653. tls.pthread_cond_helper_mutex = NULL;
  11654. #endif
  11655. pthread_setspecific(sTlsKey, &tls);
  11656. }
  11657. mg_lock_context(phys_ctx);
  11658. /* first try to find an existing handler */
  11659. lastref = &(dom_ctx->handlers);
  11660. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11661. if (tmp_rh->handler_type == handler_type) {
  11662. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11663. if (!is_delete_request) {
  11664. /* update existing handler */
  11665. if (handler_type == REQUEST_HANDLER) {
  11666. /* Wait for end of use before updating */
  11667. handler_info_wait_unused(tmp_rh);
  11668. /* Ok, the handler is no more use -> Update it */
  11669. tmp_rh->handler = handler;
  11670. } else if (handler_type == WEBSOCKET_HANDLER) {
  11671. tmp_rh->subprotocols = subprotocols;
  11672. tmp_rh->connect_handler = connect_handler;
  11673. tmp_rh->ready_handler = ready_handler;
  11674. tmp_rh->data_handler = data_handler;
  11675. tmp_rh->close_handler = close_handler;
  11676. } else { /* AUTH_HANDLER */
  11677. tmp_rh->auth_handler = auth_handler;
  11678. }
  11679. tmp_rh->cbdata = cbdata;
  11680. } else {
  11681. /* remove existing handler */
  11682. if (handler_type == REQUEST_HANDLER) {
  11683. /* Wait for end of use before removing */
  11684. handler_info_wait_unused(tmp_rh);
  11685. /* Ok, the handler is no more used -> Destroy resources
  11686. */
  11687. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11688. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11689. }
  11690. *lastref = tmp_rh->next;
  11691. mg_free(tmp_rh->uri);
  11692. mg_free(tmp_rh);
  11693. }
  11694. mg_unlock_context(phys_ctx);
  11695. if (is_tls_set) {
  11696. pthread_setspecific(sTlsKey, NULL);
  11697. }
  11698. return;
  11699. }
  11700. }
  11701. lastref = &(tmp_rh->next);
  11702. }
  11703. if (is_delete_request) {
  11704. /* no handler to set, this was a remove request to a non-existing
  11705. * handler */
  11706. mg_unlock_context(phys_ctx);
  11707. if (is_tls_set) {
  11708. pthread_setspecific(sTlsKey, NULL);
  11709. }
  11710. return;
  11711. }
  11712. tmp_rh =
  11713. (struct mg_handler_info *)mg_calloc_ctx(1,
  11714. sizeof(struct mg_handler_info),
  11715. phys_ctx);
  11716. if (tmp_rh == NULL) {
  11717. mg_unlock_context(phys_ctx);
  11718. mg_cry_ctx_internal(phys_ctx,
  11719. "%s",
  11720. "Cannot create new request handler struct, OOM");
  11721. if (is_tls_set) {
  11722. pthread_setspecific(sTlsKey, NULL);
  11723. }
  11724. return;
  11725. }
  11726. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11727. if (!tmp_rh->uri) {
  11728. mg_unlock_context(phys_ctx);
  11729. mg_free(tmp_rh);
  11730. mg_cry_ctx_internal(phys_ctx,
  11731. "%s",
  11732. "Cannot create new request handler struct, OOM");
  11733. if (is_tls_set) {
  11734. pthread_setspecific(sTlsKey, NULL);
  11735. }
  11736. return;
  11737. }
  11738. tmp_rh->uri_len = urilen;
  11739. if (handler_type == REQUEST_HANDLER) {
  11740. /* Init refcount mutex and condition */
  11741. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11742. mg_unlock_context(phys_ctx);
  11743. mg_free(tmp_rh);
  11744. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11745. if (is_tls_set) {
  11746. pthread_setspecific(sTlsKey, NULL);
  11747. }
  11748. return;
  11749. }
  11750. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11751. mg_unlock_context(phys_ctx);
  11752. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11753. mg_free(tmp_rh);
  11754. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11755. if (is_tls_set) {
  11756. pthread_setspecific(sTlsKey, NULL);
  11757. }
  11758. return;
  11759. }
  11760. tmp_rh->refcount = 0;
  11761. tmp_rh->handler = handler;
  11762. } else if (handler_type == WEBSOCKET_HANDLER) {
  11763. tmp_rh->subprotocols = subprotocols;
  11764. tmp_rh->connect_handler = connect_handler;
  11765. tmp_rh->ready_handler = ready_handler;
  11766. tmp_rh->data_handler = data_handler;
  11767. tmp_rh->close_handler = close_handler;
  11768. } else { /* AUTH_HANDLER */
  11769. tmp_rh->auth_handler = auth_handler;
  11770. }
  11771. tmp_rh->cbdata = cbdata;
  11772. tmp_rh->handler_type = handler_type;
  11773. tmp_rh->next = NULL;
  11774. *lastref = tmp_rh;
  11775. mg_unlock_context(phys_ctx);
  11776. if (is_tls_set) {
  11777. pthread_setspecific(sTlsKey, NULL);
  11778. }
  11779. }
  11780. void
  11781. mg_set_request_handler(struct mg_context *ctx,
  11782. const char *uri,
  11783. mg_request_handler handler,
  11784. void *cbdata)
  11785. {
  11786. mg_set_handler_type(ctx,
  11787. &(ctx->dd),
  11788. uri,
  11789. REQUEST_HANDLER,
  11790. handler == NULL,
  11791. handler,
  11792. NULL,
  11793. NULL,
  11794. NULL,
  11795. NULL,
  11796. NULL,
  11797. NULL,
  11798. cbdata);
  11799. }
  11800. void
  11801. mg_set_websocket_handler(struct mg_context *ctx,
  11802. const char *uri,
  11803. mg_websocket_connect_handler connect_handler,
  11804. mg_websocket_ready_handler ready_handler,
  11805. mg_websocket_data_handler data_handler,
  11806. mg_websocket_close_handler close_handler,
  11807. void *cbdata)
  11808. {
  11809. mg_set_websocket_handler_with_subprotocols(ctx,
  11810. uri,
  11811. NULL,
  11812. connect_handler,
  11813. ready_handler,
  11814. data_handler,
  11815. close_handler,
  11816. cbdata);
  11817. }
  11818. void
  11819. mg_set_websocket_handler_with_subprotocols(
  11820. struct mg_context *ctx,
  11821. const char *uri,
  11822. struct mg_websocket_subprotocols *subprotocols,
  11823. mg_websocket_connect_handler connect_handler,
  11824. mg_websocket_ready_handler ready_handler,
  11825. mg_websocket_data_handler data_handler,
  11826. mg_websocket_close_handler close_handler,
  11827. void *cbdata)
  11828. {
  11829. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11830. && (data_handler == NULL)
  11831. && (close_handler == NULL);
  11832. mg_set_handler_type(ctx,
  11833. &(ctx->dd),
  11834. uri,
  11835. WEBSOCKET_HANDLER,
  11836. is_delete_request,
  11837. NULL,
  11838. subprotocols,
  11839. connect_handler,
  11840. ready_handler,
  11841. data_handler,
  11842. close_handler,
  11843. NULL,
  11844. cbdata);
  11845. }
  11846. void
  11847. mg_set_auth_handler(struct mg_context *ctx,
  11848. const char *uri,
  11849. mg_authorization_handler handler,
  11850. void *cbdata)
  11851. {
  11852. mg_set_handler_type(ctx,
  11853. &(ctx->dd),
  11854. uri,
  11855. AUTH_HANDLER,
  11856. handler == NULL,
  11857. NULL,
  11858. NULL,
  11859. NULL,
  11860. NULL,
  11861. NULL,
  11862. NULL,
  11863. handler,
  11864. cbdata);
  11865. }
  11866. static int
  11867. get_request_handler(struct mg_connection *conn,
  11868. int handler_type,
  11869. mg_request_handler *handler,
  11870. struct mg_websocket_subprotocols **subprotocols,
  11871. mg_websocket_connect_handler *connect_handler,
  11872. mg_websocket_ready_handler *ready_handler,
  11873. mg_websocket_data_handler *data_handler,
  11874. mg_websocket_close_handler *close_handler,
  11875. mg_authorization_handler *auth_handler,
  11876. void **cbdata,
  11877. struct mg_handler_info **handler_info)
  11878. {
  11879. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11880. if (request_info) {
  11881. const char *uri = request_info->local_uri;
  11882. size_t urilen = strlen(uri);
  11883. struct mg_handler_info *tmp_rh;
  11884. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11885. return 0;
  11886. }
  11887. mg_lock_context(conn->phys_ctx);
  11888. /* first try for an exact match */
  11889. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11890. tmp_rh = tmp_rh->next) {
  11891. if (tmp_rh->handler_type == handler_type) {
  11892. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11893. if (handler_type == WEBSOCKET_HANDLER) {
  11894. *subprotocols = tmp_rh->subprotocols;
  11895. *connect_handler = tmp_rh->connect_handler;
  11896. *ready_handler = tmp_rh->ready_handler;
  11897. *data_handler = tmp_rh->data_handler;
  11898. *close_handler = tmp_rh->close_handler;
  11899. } else if (handler_type == REQUEST_HANDLER) {
  11900. *handler = tmp_rh->handler;
  11901. /* Acquire handler and give it back */
  11902. handler_info_acquire(tmp_rh);
  11903. *handler_info = tmp_rh;
  11904. } else { /* AUTH_HANDLER */
  11905. *auth_handler = tmp_rh->auth_handler;
  11906. }
  11907. *cbdata = tmp_rh->cbdata;
  11908. mg_unlock_context(conn->phys_ctx);
  11909. return 1;
  11910. }
  11911. }
  11912. }
  11913. /* next try for a partial match, we will accept uri/something */
  11914. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11915. tmp_rh = tmp_rh->next) {
  11916. if (tmp_rh->handler_type == handler_type) {
  11917. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11918. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11919. if (handler_type == WEBSOCKET_HANDLER) {
  11920. *subprotocols = tmp_rh->subprotocols;
  11921. *connect_handler = tmp_rh->connect_handler;
  11922. *ready_handler = tmp_rh->ready_handler;
  11923. *data_handler = tmp_rh->data_handler;
  11924. *close_handler = tmp_rh->close_handler;
  11925. } else if (handler_type == REQUEST_HANDLER) {
  11926. *handler = tmp_rh->handler;
  11927. /* Acquire handler and give it back */
  11928. handler_info_acquire(tmp_rh);
  11929. *handler_info = tmp_rh;
  11930. } else { /* AUTH_HANDLER */
  11931. *auth_handler = tmp_rh->auth_handler;
  11932. }
  11933. *cbdata = tmp_rh->cbdata;
  11934. mg_unlock_context(conn->phys_ctx);
  11935. return 1;
  11936. }
  11937. }
  11938. }
  11939. /* finally try for pattern match */
  11940. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11941. tmp_rh = tmp_rh->next) {
  11942. if (tmp_rh->handler_type == handler_type) {
  11943. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11944. if (handler_type == WEBSOCKET_HANDLER) {
  11945. *subprotocols = tmp_rh->subprotocols;
  11946. *connect_handler = tmp_rh->connect_handler;
  11947. *ready_handler = tmp_rh->ready_handler;
  11948. *data_handler = tmp_rh->data_handler;
  11949. *close_handler = tmp_rh->close_handler;
  11950. } else if (handler_type == REQUEST_HANDLER) {
  11951. *handler = tmp_rh->handler;
  11952. /* Acquire handler and give it back */
  11953. handler_info_acquire(tmp_rh);
  11954. *handler_info = tmp_rh;
  11955. } else { /* AUTH_HANDLER */
  11956. *auth_handler = tmp_rh->auth_handler;
  11957. }
  11958. *cbdata = tmp_rh->cbdata;
  11959. mg_unlock_context(conn->phys_ctx);
  11960. return 1;
  11961. }
  11962. }
  11963. }
  11964. mg_unlock_context(conn->phys_ctx);
  11965. }
  11966. return 0; /* none found */
  11967. }
  11968. /* Check if the script file is in a path, allowed for script files.
  11969. * This can be used if uploading files is possible not only for the server
  11970. * admin, and the upload mechanism does not check the file extension.
  11971. */
  11972. static int
  11973. is_in_script_path(const struct mg_connection *conn, const char *path)
  11974. {
  11975. /* TODO (Feature): Add config value for allowed script path.
  11976. * Default: All allowed. */
  11977. (void)conn;
  11978. (void)path;
  11979. return 1;
  11980. }
  11981. #if defined(USE_WEBSOCKET) \
  11982. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  11983. static int
  11984. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11985. void *cbdata)
  11986. {
  11987. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11988. if (pcallbacks->websocket_connect) {
  11989. return pcallbacks->websocket_connect(conn);
  11990. }
  11991. /* No handler set - assume "OK" */
  11992. return 0;
  11993. }
  11994. static void
  11995. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11996. {
  11997. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11998. if (pcallbacks->websocket_ready) {
  11999. pcallbacks->websocket_ready(conn);
  12000. }
  12001. }
  12002. static int
  12003. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12004. int bits,
  12005. char *data,
  12006. size_t len,
  12007. void *cbdata)
  12008. {
  12009. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12010. if (pcallbacks->websocket_data) {
  12011. return pcallbacks->websocket_data(conn, bits, data, len);
  12012. }
  12013. /* No handler set - assume "OK" */
  12014. return 1;
  12015. }
  12016. static void
  12017. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12018. void *cbdata)
  12019. {
  12020. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12021. if (pcallbacks->connection_close) {
  12022. pcallbacks->connection_close(conn);
  12023. }
  12024. }
  12025. #endif
  12026. /* This is the heart of the Civetweb's logic.
  12027. * This function is called when the request is read, parsed and validated,
  12028. * and Civetweb must decide what action to take: serve a file, or
  12029. * a directory, or call embedded function, etcetera. */
  12030. static void
  12031. handle_request(struct mg_connection *conn)
  12032. {
  12033. struct mg_request_info *ri = &conn->request_info;
  12034. char path[PATH_MAX];
  12035. int uri_len, ssl_index;
  12036. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12037. is_put_or_delete_request = 0, is_callback_resource = 0;
  12038. int i;
  12039. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12040. mg_request_handler callback_handler = NULL;
  12041. struct mg_handler_info *handler_info = NULL;
  12042. struct mg_websocket_subprotocols *subprotocols;
  12043. mg_websocket_connect_handler ws_connect_handler = NULL;
  12044. mg_websocket_ready_handler ws_ready_handler = NULL;
  12045. mg_websocket_data_handler ws_data_handler = NULL;
  12046. mg_websocket_close_handler ws_close_handler = NULL;
  12047. void *callback_data = NULL;
  12048. mg_authorization_handler auth_handler = NULL;
  12049. void *auth_callback_data = NULL;
  12050. int handler_type;
  12051. time_t curtime = time(NULL);
  12052. char date[64];
  12053. path[0] = 0;
  12054. /* 1. get the request url */
  12055. /* 1.1. split into url and query string */
  12056. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12057. != NULL) {
  12058. *((char *)conn->request_info.query_string++) = '\0';
  12059. }
  12060. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12061. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12062. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12063. if (ssl_index >= 0) {
  12064. redirect_to_https_port(conn, ssl_index);
  12065. } else {
  12066. /* A http to https forward port has been specified,
  12067. * but no https port to forward to. */
  12068. mg_send_http_error(conn,
  12069. 503,
  12070. "%s",
  12071. "Error: SSL forward not configured properly");
  12072. mg_cry_internal(conn,
  12073. "%s",
  12074. "Can not redirect to SSL, no SSL port available");
  12075. }
  12076. return;
  12077. }
  12078. uri_len = (int)strlen(ri->local_uri);
  12079. /* 1.3. decode url (if config says so) */
  12080. if (should_decode_url(conn)) {
  12081. mg_url_decode(
  12082. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12083. }
  12084. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12085. * not possible */
  12086. remove_dot_segments((char *)ri->local_uri);
  12087. /* step 1. completed, the url is known now */
  12088. uri_len = (int)strlen(ri->local_uri);
  12089. DEBUG_TRACE("URL: %s", ri->local_uri);
  12090. /* 2. if this ip has limited speed, set it for this connection */
  12091. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12092. get_remote_ip(conn),
  12093. ri->local_uri);
  12094. /* 3. call a "handle everything" callback, if registered */
  12095. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12096. /* Note that since V1.7 the "begin_request" function is called
  12097. * before an authorization check. If an authorization check is
  12098. * required, use a request_handler instead. */
  12099. i = conn->phys_ctx->callbacks.begin_request(conn);
  12100. if (i > 0) {
  12101. /* callback already processed the request. Store the
  12102. return value as a status code for the access log. */
  12103. conn->status_code = i;
  12104. if (!conn->must_close) {
  12105. discard_unread_request_data(conn);
  12106. }
  12107. return;
  12108. } else if (i == 0) {
  12109. /* civetweb should process the request */
  12110. } else {
  12111. /* unspecified - may change with the next version */
  12112. return;
  12113. }
  12114. }
  12115. /* request not yet handled by a handler or redirect, so the request
  12116. * is processed here */
  12117. /* 4. Check for CORS preflight requests and handle them (if configured).
  12118. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12119. */
  12120. if (!strcmp(ri->request_method, "OPTIONS")) {
  12121. /* Send a response to CORS preflights only if
  12122. * access_control_allow_methods is not NULL and not an empty string.
  12123. * In this case, scripts can still handle CORS. */
  12124. const char *cors_meth_cfg =
  12125. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12126. const char *cors_orig_cfg =
  12127. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12128. const char *cors_origin =
  12129. get_header(ri->http_headers, ri->num_headers, "Origin");
  12130. const char *cors_acrm = get_header(ri->http_headers,
  12131. ri->num_headers,
  12132. "Access-Control-Request-Method");
  12133. /* Todo: check if cors_origin is in cors_orig_cfg.
  12134. * Or, let the client check this. */
  12135. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12136. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12137. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12138. /* This is a valid CORS preflight, and the server is configured
  12139. * to
  12140. * handle it automatically. */
  12141. const char *cors_acrh =
  12142. get_header(ri->http_headers,
  12143. ri->num_headers,
  12144. "Access-Control-Request-Headers");
  12145. gmt_time_string(date, sizeof(date), &curtime);
  12146. mg_printf(conn,
  12147. "HTTP/1.1 200 OK\r\n"
  12148. "Date: %s\r\n"
  12149. "Access-Control-Allow-Origin: %s\r\n"
  12150. "Access-Control-Allow-Methods: %s\r\n"
  12151. "Content-Length: 0\r\n"
  12152. "Connection: %s\r\n",
  12153. date,
  12154. cors_orig_cfg,
  12155. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12156. suggest_connection_header(conn));
  12157. if (cors_acrh != NULL) {
  12158. /* CORS request is asking for additional headers */
  12159. const char *cors_hdr_cfg =
  12160. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12161. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12162. /* Allow only if access_control_allow_headers is
  12163. * not NULL and not an empty string. If this
  12164. * configuration is set to *, allow everything.
  12165. * Otherwise this configuration must be a list
  12166. * of allowed HTTP header names. */
  12167. mg_printf(conn,
  12168. "Access-Control-Allow-Headers: %s\r\n",
  12169. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12170. : cors_hdr_cfg));
  12171. }
  12172. }
  12173. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12174. mg_printf(conn, "\r\n");
  12175. return;
  12176. }
  12177. }
  12178. /* 5. interpret the url to find out how the request must be handled
  12179. */
  12180. /* 5.1. first test, if the request targets the regular http(s)://
  12181. * protocol namespace or the websocket ws(s):// protocol namespace.
  12182. */
  12183. is_websocket_request = is_websocket_protocol(conn);
  12184. #if defined(USE_WEBSOCKET)
  12185. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12186. #else
  12187. handler_type = REQUEST_HANDLER;
  12188. #endif /* defined(USE_WEBSOCKET) */
  12189. /* 5.2. check if the request will be handled by a callback */
  12190. if (get_request_handler(conn,
  12191. handler_type,
  12192. &callback_handler,
  12193. &subprotocols,
  12194. &ws_connect_handler,
  12195. &ws_ready_handler,
  12196. &ws_data_handler,
  12197. &ws_close_handler,
  12198. NULL,
  12199. &callback_data,
  12200. &handler_info)) {
  12201. /* 5.2.1. A callback will handle this request. All requests
  12202. * handled
  12203. * by a callback have to be considered as requests to a script
  12204. * resource. */
  12205. is_callback_resource = 1;
  12206. is_script_resource = 1;
  12207. is_put_or_delete_request = is_put_or_delete_method(conn);
  12208. } else {
  12209. no_callback_resource:
  12210. /* 5.2.2. No callback is responsible for this request. The URI
  12211. * addresses a file based resource (static content or Lua/cgi
  12212. * scripts in the file system). */
  12213. is_callback_resource = 0;
  12214. interpret_uri(conn,
  12215. path,
  12216. sizeof(path),
  12217. &file.stat,
  12218. &is_found,
  12219. &is_script_resource,
  12220. &is_websocket_request,
  12221. &is_put_or_delete_request);
  12222. }
  12223. /* 6. authorization check */
  12224. /* 6.1. a custom authorization handler is installed */
  12225. if (get_request_handler(conn,
  12226. AUTH_HANDLER,
  12227. NULL,
  12228. NULL,
  12229. NULL,
  12230. NULL,
  12231. NULL,
  12232. NULL,
  12233. &auth_handler,
  12234. &auth_callback_data,
  12235. NULL)) {
  12236. if (!auth_handler(conn, auth_callback_data)) {
  12237. return;
  12238. }
  12239. } else if (is_put_or_delete_request && !is_script_resource
  12240. && !is_callback_resource) {
  12241. /* 6.2. this request is a PUT/DELETE to a real file */
  12242. /* 6.2.1. thus, the server must have real files */
  12243. #if defined(NO_FILES)
  12244. if (1) {
  12245. #else
  12246. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12247. #endif
  12248. /* This server does not have any real files, thus the
  12249. * PUT/DELETE methods are not valid. */
  12250. mg_send_http_error(conn,
  12251. 405,
  12252. "%s method not allowed",
  12253. conn->request_info.request_method);
  12254. return;
  12255. }
  12256. #if !defined(NO_FILES)
  12257. /* 6.2.2. Check if put authorization for static files is
  12258. * available.
  12259. */
  12260. if (!is_authorized_for_put(conn)) {
  12261. send_authorization_request(conn, NULL);
  12262. return;
  12263. }
  12264. #endif
  12265. } else {
  12266. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12267. * or it is a PUT or DELETE request to a resource that does not
  12268. * correspond to a file. Check authorization. */
  12269. if (!check_authorization(conn, path)) {
  12270. send_authorization_request(conn, NULL);
  12271. return;
  12272. }
  12273. }
  12274. /* request is authorized or does not need authorization */
  12275. /* 7. check if there are request handlers for this uri */
  12276. if (is_callback_resource) {
  12277. if (!is_websocket_request) {
  12278. i = callback_handler(conn, callback_data);
  12279. /* Callback handler will not be used anymore. Release it */
  12280. handler_info_release(handler_info);
  12281. if (i > 0) {
  12282. /* Do nothing, callback has served the request. Store
  12283. * then return value as status code for the log and discard
  12284. * all data from the client not used by the callback. */
  12285. conn->status_code = i;
  12286. if (!conn->must_close) {
  12287. discard_unread_request_data(conn);
  12288. }
  12289. } else {
  12290. /* The handler did NOT handle the request. */
  12291. /* Some proper reactions would be:
  12292. * a) close the connections without sending anything
  12293. * b) send a 404 not found
  12294. * c) try if there is a file matching the URI
  12295. * It would be possible to do a, b or c in the callback
  12296. * implementation, and return 1 - we cannot do anything
  12297. * here, that is not possible in the callback.
  12298. *
  12299. * TODO: What would be the best reaction here?
  12300. * (Note: The reaction may change, if there is a better
  12301. *idea.)
  12302. */
  12303. /* For the moment, use option c: We look for a proper file,
  12304. * but since a file request is not always a script resource,
  12305. * the authorization check might be different. */
  12306. interpret_uri(conn,
  12307. path,
  12308. sizeof(path),
  12309. &file.stat,
  12310. &is_found,
  12311. &is_script_resource,
  12312. &is_websocket_request,
  12313. &is_put_or_delete_request);
  12314. callback_handler = NULL;
  12315. /* Here we are at a dead end:
  12316. * According to URI matching, a callback should be
  12317. * responsible for handling the request,
  12318. * we called it, but the callback declared itself
  12319. * not responsible.
  12320. * We use a goto here, to get out of this dead end,
  12321. * and continue with the default handling.
  12322. * A goto here is simpler and better to understand
  12323. * than some curious loop. */
  12324. goto no_callback_resource;
  12325. }
  12326. } else {
  12327. #if defined(USE_WEBSOCKET)
  12328. handle_websocket_request(conn,
  12329. path,
  12330. is_callback_resource,
  12331. subprotocols,
  12332. ws_connect_handler,
  12333. ws_ready_handler,
  12334. ws_data_handler,
  12335. ws_close_handler,
  12336. callback_data);
  12337. #endif
  12338. }
  12339. return;
  12340. }
  12341. /* 8. handle websocket requests */
  12342. #if defined(USE_WEBSOCKET)
  12343. if (is_websocket_request) {
  12344. if (is_script_resource) {
  12345. if (is_in_script_path(conn, path)) {
  12346. /* Websocket Lua script */
  12347. handle_websocket_request(conn,
  12348. path,
  12349. 0 /* Lua Script */,
  12350. NULL,
  12351. NULL,
  12352. NULL,
  12353. NULL,
  12354. NULL,
  12355. conn->phys_ctx->user_data);
  12356. } else {
  12357. /* Script was in an illegal path */
  12358. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12359. }
  12360. } else {
  12361. #if defined(MG_LEGACY_INTERFACE)
  12362. handle_websocket_request(
  12363. conn,
  12364. path,
  12365. !is_script_resource /* could be deprecated global callback */,
  12366. NULL,
  12367. deprecated_websocket_connect_wrapper,
  12368. deprecated_websocket_ready_wrapper,
  12369. deprecated_websocket_data_wrapper,
  12370. NULL,
  12371. conn->phys_ctx->callbacks);
  12372. #else
  12373. mg_send_http_error(conn, 404, "%s", "Not found");
  12374. #endif
  12375. }
  12376. return;
  12377. } else
  12378. #endif
  12379. #if defined(NO_FILES)
  12380. /* 9a. In case the server uses only callbacks, this uri is
  12381. * unknown.
  12382. * Then, all request handling ends here. */
  12383. mg_send_http_error(conn, 404, "%s", "Not Found");
  12384. #else
  12385. /* 9b. This request is either for a static file or resource handled
  12386. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12387. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12388. mg_send_http_error(conn, 404, "%s", "Not Found");
  12389. return;
  12390. }
  12391. /* 10. Request is handled by a script */
  12392. if (is_script_resource) {
  12393. handle_file_based_request(conn, path, &file);
  12394. return;
  12395. }
  12396. /* 11. Handle put/delete/mkcol requests */
  12397. if (is_put_or_delete_request) {
  12398. /* 11.1. PUT method */
  12399. if (!strcmp(ri->request_method, "PUT")) {
  12400. put_file(conn, path);
  12401. return;
  12402. }
  12403. /* 11.2. DELETE method */
  12404. if (!strcmp(ri->request_method, "DELETE")) {
  12405. delete_file(conn, path);
  12406. return;
  12407. }
  12408. /* 11.3. MKCOL method */
  12409. if (!strcmp(ri->request_method, "MKCOL")) {
  12410. mkcol(conn, path);
  12411. return;
  12412. }
  12413. /* 11.4. PATCH method
  12414. * This method is not supported for static resources,
  12415. * only for scripts (Lua, CGI) and callbacks. */
  12416. mg_send_http_error(conn,
  12417. 405,
  12418. "%s method not allowed",
  12419. conn->request_info.request_method);
  12420. return;
  12421. }
  12422. /* 11. File does not exist, or it was configured that it should be
  12423. * hidden */
  12424. if (!is_found || (must_hide_file(conn, path))) {
  12425. mg_send_http_error(conn, 404, "%s", "Not found");
  12426. return;
  12427. }
  12428. /* 12. Directory uris should end with a slash */
  12429. if (file.stat.is_directory && (uri_len > 0)
  12430. && (ri->local_uri[uri_len - 1] != '/')) {
  12431. gmt_time_string(date, sizeof(date), &curtime);
  12432. mg_printf(conn,
  12433. "HTTP/1.1 301 Moved Permanently\r\n"
  12434. "Location: %s/\r\n"
  12435. "Date: %s\r\n"
  12436. /* "Cache-Control: private\r\n" (= default) */
  12437. "Content-Length: 0\r\n"
  12438. "Connection: %s\r\n",
  12439. ri->request_uri,
  12440. date,
  12441. suggest_connection_header(conn));
  12442. send_additional_header(conn);
  12443. mg_printf(conn, "\r\n");
  12444. return;
  12445. }
  12446. /* 13. Handle other methods than GET/HEAD */
  12447. /* 13.1. Handle PROPFIND */
  12448. if (!strcmp(ri->request_method, "PROPFIND")) {
  12449. handle_propfind(conn, path, &file.stat);
  12450. return;
  12451. }
  12452. /* 13.2. Handle OPTIONS for files */
  12453. if (!strcmp(ri->request_method, "OPTIONS")) {
  12454. /* This standard handler is only used for real files.
  12455. * Scripts should support the OPTIONS method themselves, to allow a
  12456. * maximum flexibility.
  12457. * Lua and CGI scripts may fully support CORS this way (including
  12458. * preflights). */
  12459. send_options(conn);
  12460. return;
  12461. }
  12462. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12463. if ((0 != strcmp(ri->request_method, "GET"))
  12464. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12465. mg_send_http_error(conn,
  12466. 405,
  12467. "%s method not allowed",
  12468. conn->request_info.request_method);
  12469. return;
  12470. }
  12471. /* 14. directories */
  12472. if (file.stat.is_directory) {
  12473. /* Substitute files have already been handled above. */
  12474. /* Here we can either generate and send a directory listing,
  12475. * or send an "access denied" error. */
  12476. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12477. "yes")) {
  12478. handle_directory_request(conn, path);
  12479. } else {
  12480. mg_send_http_error(conn,
  12481. 403,
  12482. "%s",
  12483. "Error: Directory listing denied");
  12484. }
  12485. return;
  12486. }
  12487. /* 15. read a normal file with GET or HEAD */
  12488. handle_file_based_request(conn, path, &file);
  12489. #endif /* !defined(NO_FILES) */
  12490. }
  12491. #if !defined(NO_FILESYSTEMS)
  12492. static void
  12493. handle_file_based_request(struct mg_connection *conn,
  12494. const char *path,
  12495. struct mg_file *file)
  12496. {
  12497. if (!conn || !conn->dom_ctx) {
  12498. return;
  12499. }
  12500. if (0) {
  12501. #if defined(USE_LUA)
  12502. } else if (match_prefix(
  12503. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12504. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12505. path)
  12506. > 0) {
  12507. if (is_in_script_path(conn, path)) {
  12508. /* Lua server page: an SSI like page containing mostly plain
  12509. * html
  12510. * code
  12511. * plus some tags with server generated contents. */
  12512. handle_lsp_request(conn, path, file, NULL);
  12513. } else {
  12514. /* Script was in an illegal path */
  12515. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12516. }
  12517. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12518. strlen(
  12519. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12520. path)
  12521. > 0) {
  12522. if (is_in_script_path(conn, path)) {
  12523. /* Lua in-server module script: a CGI like script used to
  12524. * generate
  12525. * the
  12526. * entire reply. */
  12527. mg_exec_lua_script(conn, path, NULL);
  12528. } else {
  12529. /* Script was in an illegal path */
  12530. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12531. }
  12532. #endif
  12533. #if defined(USE_DUKTAPE)
  12534. } else if (match_prefix(
  12535. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12536. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12537. path)
  12538. > 0) {
  12539. if (is_in_script_path(conn, path)) {
  12540. /* Call duktape to generate the page */
  12541. mg_exec_duktape_script(conn, path);
  12542. } else {
  12543. /* Script was in an illegal path */
  12544. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12545. }
  12546. #endif
  12547. #if !defined(NO_CGI)
  12548. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12549. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12550. path)
  12551. > 0) {
  12552. if (is_in_script_path(conn, path)) {
  12553. /* CGI scripts may support all HTTP methods */
  12554. handle_cgi_request(conn, path);
  12555. } else {
  12556. /* Script was in an illegal path */
  12557. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12558. }
  12559. #endif /* !NO_CGI */
  12560. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12561. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12562. path)
  12563. > 0) {
  12564. if (is_in_script_path(conn, path)) {
  12565. handle_ssi_file_request(conn, path, file);
  12566. } else {
  12567. /* Script was in an illegal path */
  12568. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12569. }
  12570. #if !defined(NO_CACHING)
  12571. } else if ((!conn->in_error_handler)
  12572. && is_not_modified(conn, &file->stat)) {
  12573. /* Send 304 "Not Modified" - this must not send any body data */
  12574. handle_not_modified_static_file_request(conn, file);
  12575. #endif /* !NO_CACHING */
  12576. } else {
  12577. handle_static_file_request(conn, path, file, NULL, NULL);
  12578. }
  12579. }
  12580. #endif /* NO_FILESYSTEMS */
  12581. static void
  12582. close_all_listening_sockets(struct mg_context *ctx)
  12583. {
  12584. unsigned int i;
  12585. if (!ctx) {
  12586. return;
  12587. }
  12588. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12589. closesocket(ctx->listening_sockets[i].sock);
  12590. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12591. }
  12592. mg_free(ctx->listening_sockets);
  12593. ctx->listening_sockets = NULL;
  12594. mg_free(ctx->listening_socket_fds);
  12595. ctx->listening_socket_fds = NULL;
  12596. }
  12597. /* Valid listening port specification is: [ip_address:]port[s]
  12598. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12599. * Examples for IPv6: [::]:80, [::1]:80,
  12600. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12601. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12602. * In order to bind to both, IPv4 and IPv6, you can either add
  12603. * both ports using 8080,[::]:8080, or the short form +8080.
  12604. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12605. * one only accepting IPv4 the other only IPv6. +8080 creates
  12606. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12607. * environment, they might work differently, or might not work
  12608. * at all - it must be tested what options work best in the
  12609. * relevant network environment.
  12610. */
  12611. static int
  12612. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12613. {
  12614. unsigned int a, b, c, d, port;
  12615. int ch, len;
  12616. const char *cb;
  12617. char *endptr;
  12618. #if defined(USE_IPV6)
  12619. char buf[100] = {0};
  12620. #endif
  12621. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12622. * Also, all-zeroes in the socket address means binding to all addresses
  12623. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12624. memset(so, 0, sizeof(*so));
  12625. so->lsa.sin.sin_family = AF_INET;
  12626. *ip_version = 0;
  12627. /* Initialize port and len as invalid. */
  12628. port = 0;
  12629. len = 0;
  12630. /* Test for different ways to format this string */
  12631. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12632. == 5) {
  12633. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12634. so->lsa.sin.sin_addr.s_addr =
  12635. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12636. so->lsa.sin.sin_port = htons((uint16_t)port);
  12637. *ip_version = 4;
  12638. #if defined(USE_IPV6)
  12639. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12640. && mg_inet_pton(
  12641. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12642. /* IPv6 address, examples: see above */
  12643. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12644. */
  12645. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12646. *ip_version = 6;
  12647. #endif
  12648. } else if ((vec->ptr[0] == '+')
  12649. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12650. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12651. /* Add 1 to len for the + character we skipped before */
  12652. len++;
  12653. #if defined(USE_IPV6)
  12654. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12655. so->lsa.sin6.sin6_family = AF_INET6;
  12656. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12657. *ip_version = 4 + 6;
  12658. #else
  12659. /* Bind to IPv4 only, since IPv6 is not built in. */
  12660. so->lsa.sin.sin_port = htons((uint16_t)port);
  12661. *ip_version = 4;
  12662. #endif
  12663. } else if (is_valid_port(port = strtoul(vec->ptr, &endptr, 0))
  12664. && vec->ptr != endptr) {
  12665. len = endptr - vec->ptr;
  12666. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12667. so->lsa.sin.sin_port = htons((uint16_t)port);
  12668. *ip_version = 4;
  12669. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12670. /* String could be a hostname. This check algotithm
  12671. * will only work for RFC 952 compliant hostnames,
  12672. * starting with a letter, containing only letters,
  12673. * digits and hyphen ('-'). Newer specs may allow
  12674. * more, but this is not guaranteed here, since it
  12675. * may interfere with rules for port option lists. */
  12676. /* According to RFC 1035, hostnames are restricted to 255 characters
  12677. * in total (63 between two dots). */
  12678. char hostname[256];
  12679. size_t hostnlen = (size_t)(cb - vec->ptr);
  12680. if (hostnlen >= sizeof(hostname)) {
  12681. /* This would be invalid in any case */
  12682. *ip_version = 0;
  12683. return 0;
  12684. }
  12685. memcpy(hostname, vec->ptr, hostnlen);
  12686. hostname[hostnlen] = 0;
  12687. if (mg_inet_pton(
  12688. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12689. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12690. *ip_version = 4;
  12691. so->lsa.sin.sin_family = AF_INET;
  12692. so->lsa.sin.sin_port = htons((uint16_t)port);
  12693. len += (int)(hostnlen + 1);
  12694. } else {
  12695. port = 0;
  12696. len = 0;
  12697. }
  12698. #if defined(USE_IPV6)
  12699. } else if (mg_inet_pton(AF_INET6,
  12700. hostname,
  12701. &so->lsa.sin6,
  12702. sizeof(so->lsa.sin6))) {
  12703. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12704. *ip_version = 6;
  12705. so->lsa.sin6.sin6_family = AF_INET6;
  12706. so->lsa.sin.sin_port = htons((uint16_t)port);
  12707. len += (int)(hostnlen + 1);
  12708. } else {
  12709. port = 0;
  12710. len = 0;
  12711. }
  12712. #endif
  12713. }
  12714. } else {
  12715. /* Parsing failure. */
  12716. }
  12717. /* sscanf and the option splitting code ensure the following condition
  12718. */
  12719. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12720. *ip_version = 0;
  12721. return 0;
  12722. }
  12723. ch = vec->ptr[len]; /* Next character after the port number */
  12724. so->is_ssl = (ch == 's');
  12725. so->ssl_redir = (ch == 'r');
  12726. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12727. if (is_valid_port(port)
  12728. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12729. return 1;
  12730. }
  12731. /* Reset ip_version to 0 if there is an error */
  12732. *ip_version = 0;
  12733. return 0;
  12734. }
  12735. /* Is there any SSL port in use? */
  12736. static int
  12737. is_ssl_port_used(const char *ports)
  12738. {
  12739. if (ports) {
  12740. /* There are several different allowed syntax variants:
  12741. * - "80" for a single port using every network interface
  12742. * - "localhost:80" for a single port using only localhost
  12743. * - "80,localhost:8080" for two ports, one bound to localhost
  12744. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12745. * to IPv4 localhost, one to IPv6 localhost
  12746. * - "+80" use port 80 for IPv4 and IPv6
  12747. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12748. * for both: IPv4 and IPv4
  12749. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12750. * additionally port 8080 bound to localhost connections
  12751. *
  12752. * If we just look for 's' anywhere in the string, "localhost:80"
  12753. * will be detected as SSL (false positive).
  12754. * Looking for 's' after a digit may cause false positives in
  12755. * "my24service:8080".
  12756. * Looking from 's' backward if there are only ':' and numbers
  12757. * before will not work for "24service:8080" (non SSL, port 8080)
  12758. * or "24s" (SSL, port 24).
  12759. *
  12760. * Remark: Initially hostnames were not allowed to start with a
  12761. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12762. * Section 2.1).
  12763. *
  12764. * To get this correct, the entire string must be parsed as a whole,
  12765. * reading it as a list element for element and parsing with an
  12766. * algorithm equivalent to parse_port_string.
  12767. *
  12768. * In fact, we use local interface names here, not arbitrary hostnames,
  12769. * so in most cases the only name will be "localhost".
  12770. *
  12771. * So, for now, we use this simple algorithm, that may still return
  12772. * a false positive in bizarre cases.
  12773. */
  12774. int i;
  12775. int portslen = (int)strlen(ports);
  12776. char prevIsNumber = 0;
  12777. for (i = 0; i < portslen; i++) {
  12778. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12779. return 1;
  12780. }
  12781. if (ports[i] >= '0' && ports[i] <= '9') {
  12782. prevIsNumber = 1;
  12783. } else {
  12784. prevIsNumber = 0;
  12785. }
  12786. }
  12787. }
  12788. return 0;
  12789. }
  12790. static int
  12791. set_ports_option(struct mg_context *phys_ctx)
  12792. {
  12793. const char *list;
  12794. int on = 1;
  12795. #if defined(USE_IPV6)
  12796. int off = 0;
  12797. #endif
  12798. struct vec vec;
  12799. struct socket so, *ptr;
  12800. struct mg_pollfd *pfd;
  12801. union usa usa;
  12802. socklen_t len;
  12803. int ip_version;
  12804. int portsTotal = 0;
  12805. int portsOk = 0;
  12806. const char *opt_txt;
  12807. long opt_listen_backlog;
  12808. if (!phys_ctx) {
  12809. return 0;
  12810. }
  12811. memset(&so, 0, sizeof(so));
  12812. memset(&usa, 0, sizeof(usa));
  12813. len = sizeof(usa);
  12814. list = phys_ctx->dd.config[LISTENING_PORTS];
  12815. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12816. portsTotal++;
  12817. if (!parse_port_string(&vec, &so, &ip_version)) {
  12818. mg_cry_ctx_internal(
  12819. phys_ctx,
  12820. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12821. (int)vec.len,
  12822. vec.ptr,
  12823. portsTotal,
  12824. "[IP_ADDRESS:]PORT[s|r]");
  12825. continue;
  12826. }
  12827. #if !defined(NO_SSL)
  12828. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12829. mg_cry_ctx_internal(phys_ctx,
  12830. "Cannot add SSL socket (entry %i)",
  12831. portsTotal);
  12832. continue;
  12833. }
  12834. #endif
  12835. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12836. == INVALID_SOCKET) {
  12837. mg_cry_ctx_internal(phys_ctx,
  12838. "cannot create socket (entry %i)",
  12839. portsTotal);
  12840. continue;
  12841. }
  12842. #if defined(_WIN32)
  12843. /* Windows SO_REUSEADDR lets many procs binds to a
  12844. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12845. * if someone already has the socket -- DTL */
  12846. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12847. * Windows might need a few seconds before
  12848. * the same port can be used again in the
  12849. * same process, so a short Sleep may be
  12850. * required between mg_stop and mg_start.
  12851. */
  12852. if (setsockopt(so.sock,
  12853. SOL_SOCKET,
  12854. SO_EXCLUSIVEADDRUSE,
  12855. (SOCK_OPT_TYPE)&on,
  12856. sizeof(on))
  12857. != 0) {
  12858. /* Set reuse option, but don't abort on errors. */
  12859. mg_cry_ctx_internal(
  12860. phys_ctx,
  12861. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12862. portsTotal);
  12863. }
  12864. #else
  12865. if (setsockopt(so.sock,
  12866. SOL_SOCKET,
  12867. SO_REUSEADDR,
  12868. (SOCK_OPT_TYPE)&on,
  12869. sizeof(on))
  12870. != 0) {
  12871. /* Set reuse option, but don't abort on errors. */
  12872. mg_cry_ctx_internal(
  12873. phys_ctx,
  12874. "cannot set socket option SO_REUSEADDR (entry %i)",
  12875. portsTotal);
  12876. }
  12877. #endif
  12878. if (ip_version > 4) {
  12879. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12880. #if defined(USE_IPV6)
  12881. if (ip_version > 6) {
  12882. if (so.lsa.sa.sa_family == AF_INET6
  12883. && setsockopt(so.sock,
  12884. IPPROTO_IPV6,
  12885. IPV6_V6ONLY,
  12886. (void *)&off,
  12887. sizeof(off))
  12888. != 0) {
  12889. /* Set IPv6 only option, but don't abort on errors. */
  12890. mg_cry_ctx_internal(
  12891. phys_ctx,
  12892. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12893. portsTotal);
  12894. }
  12895. } else {
  12896. if (so.lsa.sa.sa_family == AF_INET6
  12897. && setsockopt(so.sock,
  12898. IPPROTO_IPV6,
  12899. IPV6_V6ONLY,
  12900. (void *)&on,
  12901. sizeof(on))
  12902. != 0) {
  12903. /* Set IPv6 only option, but don't abort on errors. */
  12904. mg_cry_ctx_internal(
  12905. phys_ctx,
  12906. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12907. portsTotal);
  12908. }
  12909. }
  12910. #else
  12911. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12912. closesocket(so.sock);
  12913. so.sock = INVALID_SOCKET;
  12914. continue;
  12915. #endif
  12916. }
  12917. if (so.lsa.sa.sa_family == AF_INET) {
  12918. len = sizeof(so.lsa.sin);
  12919. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12920. mg_cry_ctx_internal(phys_ctx,
  12921. "cannot bind to %.*s: %d (%s)",
  12922. (int)vec.len,
  12923. vec.ptr,
  12924. (int)ERRNO,
  12925. strerror(errno));
  12926. closesocket(so.sock);
  12927. so.sock = INVALID_SOCKET;
  12928. continue;
  12929. }
  12930. }
  12931. #if defined(USE_IPV6)
  12932. else if (so.lsa.sa.sa_family == AF_INET6) {
  12933. len = sizeof(so.lsa.sin6);
  12934. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12935. mg_cry_ctx_internal(phys_ctx,
  12936. "cannot bind to IPv6 %.*s: %d (%s)",
  12937. (int)vec.len,
  12938. vec.ptr,
  12939. (int)ERRNO,
  12940. strerror(errno));
  12941. closesocket(so.sock);
  12942. so.sock = INVALID_SOCKET;
  12943. continue;
  12944. }
  12945. }
  12946. #endif
  12947. else {
  12948. mg_cry_ctx_internal(
  12949. phys_ctx,
  12950. "cannot bind: address family not supported (entry %i)",
  12951. portsTotal);
  12952. closesocket(so.sock);
  12953. so.sock = INVALID_SOCKET;
  12954. continue;
  12955. }
  12956. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  12957. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  12958. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  12959. mg_cry_ctx_internal(phys_ctx,
  12960. "%s value \"%s\" is invalid",
  12961. config_options[LISTEN_BACKLOG_SIZE].name,
  12962. opt_txt);
  12963. continue;
  12964. }
  12965. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  12966. mg_cry_ctx_internal(phys_ctx,
  12967. "cannot listen to %.*s: %d (%s)",
  12968. (int)vec.len,
  12969. vec.ptr,
  12970. (int)ERRNO,
  12971. strerror(errno));
  12972. closesocket(so.sock);
  12973. so.sock = INVALID_SOCKET;
  12974. continue;
  12975. }
  12976. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12977. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12978. int err = (int)ERRNO;
  12979. mg_cry_ctx_internal(phys_ctx,
  12980. "call to getsockname failed %.*s: %d (%s)",
  12981. (int)vec.len,
  12982. vec.ptr,
  12983. err,
  12984. strerror(errno));
  12985. closesocket(so.sock);
  12986. so.sock = INVALID_SOCKET;
  12987. continue;
  12988. }
  12989. /* Update lsa port in case of random free ports */
  12990. #if defined(USE_IPV6)
  12991. if (so.lsa.sa.sa_family == AF_INET6) {
  12992. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12993. } else
  12994. #endif
  12995. {
  12996. so.lsa.sin.sin_port = usa.sin.sin_port;
  12997. }
  12998. if ((ptr = (struct socket *)
  12999. mg_realloc_ctx(phys_ctx->listening_sockets,
  13000. (phys_ctx->num_listening_sockets + 1)
  13001. * sizeof(phys_ctx->listening_sockets[0]),
  13002. phys_ctx))
  13003. == NULL) {
  13004. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13005. closesocket(so.sock);
  13006. so.sock = INVALID_SOCKET;
  13007. continue;
  13008. }
  13009. if ((pfd = (struct mg_pollfd *)
  13010. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13011. (phys_ctx->num_listening_sockets + 1)
  13012. * sizeof(phys_ctx->listening_socket_fds[0]),
  13013. phys_ctx))
  13014. == NULL) {
  13015. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13016. closesocket(so.sock);
  13017. so.sock = INVALID_SOCKET;
  13018. mg_free(ptr);
  13019. continue;
  13020. }
  13021. set_close_on_exec(so.sock, NULL, phys_ctx);
  13022. phys_ctx->listening_sockets = ptr;
  13023. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13024. phys_ctx->listening_socket_fds = pfd;
  13025. phys_ctx->num_listening_sockets++;
  13026. portsOk++;
  13027. }
  13028. if (portsOk != portsTotal) {
  13029. close_all_listening_sockets(phys_ctx);
  13030. portsOk = 0;
  13031. }
  13032. return portsOk;
  13033. }
  13034. static const char *
  13035. header_val(const struct mg_connection *conn, const char *header)
  13036. {
  13037. const char *header_value;
  13038. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13039. return "-";
  13040. } else {
  13041. return header_value;
  13042. }
  13043. }
  13044. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13045. static void log_access(const struct mg_connection *conn);
  13046. #include "external_log_access.inl"
  13047. #elif !defined(NO_FILESYSTEMS)
  13048. static void
  13049. log_access(const struct mg_connection *conn)
  13050. {
  13051. const struct mg_request_info *ri;
  13052. struct mg_file fi;
  13053. char date[64], src_addr[IP_ADDR_STR_LEN];
  13054. struct tm *tm;
  13055. const char *referer;
  13056. const char *user_agent;
  13057. char buf[4096];
  13058. if (!conn || !conn->dom_ctx) {
  13059. return;
  13060. }
  13061. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13062. if (mg_fopen(conn,
  13063. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13064. MG_FOPEN_MODE_APPEND,
  13065. &fi)
  13066. == 0) {
  13067. fi.access.fp = NULL;
  13068. }
  13069. } else {
  13070. fi.access.fp = NULL;
  13071. }
  13072. /* Log is written to a file and/or a callback. If both are not set,
  13073. * executing the rest of the function is pointless. */
  13074. if ((fi.access.fp == NULL)
  13075. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13076. return;
  13077. }
  13078. tm = localtime(&conn->conn_birth_time);
  13079. if (tm != NULL) {
  13080. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13081. } else {
  13082. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13083. date[sizeof(date) - 1] = '\0';
  13084. }
  13085. ri = &conn->request_info;
  13086. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13087. referer = header_val(conn, "Referer");
  13088. user_agent = header_val(conn, "User-Agent");
  13089. mg_snprintf(conn,
  13090. NULL, /* Ignore truncation in access log */
  13091. buf,
  13092. sizeof(buf),
  13093. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13094. src_addr,
  13095. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13096. date,
  13097. ri->request_method ? ri->request_method : "-",
  13098. ri->request_uri ? ri->request_uri : "-",
  13099. ri->query_string ? "?" : "",
  13100. ri->query_string ? ri->query_string : "",
  13101. ri->http_version,
  13102. conn->status_code,
  13103. conn->num_bytes_sent,
  13104. referer,
  13105. user_agent);
  13106. if (conn->phys_ctx->callbacks.log_access) {
  13107. conn->phys_ctx->callbacks.log_access(conn, buf);
  13108. }
  13109. if (fi.access.fp) {
  13110. int ok = 1;
  13111. flockfile(fi.access.fp);
  13112. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13113. ok = 0;
  13114. }
  13115. if (fflush(fi.access.fp) != 0) {
  13116. ok = 0;
  13117. }
  13118. funlockfile(fi.access.fp);
  13119. if (mg_fclose(&fi.access) != 0) {
  13120. ok = 0;
  13121. }
  13122. if (!ok) {
  13123. mg_cry_internal(conn,
  13124. "Error writing log file %s",
  13125. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13126. }
  13127. }
  13128. }
  13129. #else
  13130. #error Must either enable filesystems or provide a custom log_access implementation
  13131. #endif /* Externally provided function */
  13132. /* Verify given socket address against the ACL.
  13133. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13134. */
  13135. static int
  13136. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13137. {
  13138. int allowed, flag;
  13139. uint32_t net, mask;
  13140. struct vec vec;
  13141. if (phys_ctx) {
  13142. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13143. /* If any ACL is set, deny by default */
  13144. allowed = (list == NULL) ? '+' : '-';
  13145. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13146. flag = vec.ptr[0];
  13147. if ((flag != '+' && flag != '-')
  13148. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13149. mg_cry_ctx_internal(phys_ctx,
  13150. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13151. __func__);
  13152. return -1;
  13153. }
  13154. if (net == (remote_ip & mask)) {
  13155. allowed = flag;
  13156. }
  13157. }
  13158. return allowed == '+';
  13159. }
  13160. return -1;
  13161. }
  13162. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13163. static int
  13164. set_uid_option(struct mg_context *phys_ctx)
  13165. {
  13166. int success = 0;
  13167. if (phys_ctx) {
  13168. /* We are currently running as curr_uid. */
  13169. const uid_t curr_uid = getuid();
  13170. /* If set, we want to run as run_as_user. */
  13171. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13172. const struct passwd *to_pw = NULL;
  13173. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13174. /* run_as_user does not exist on the system. We can't proceed
  13175. * further. */
  13176. mg_cry_ctx_internal(phys_ctx,
  13177. "%s: unknown user [%s]",
  13178. __func__,
  13179. run_as_user);
  13180. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13181. /* There was either no request to change user, or we're already
  13182. * running as run_as_user. Nothing else to do.
  13183. */
  13184. success = 1;
  13185. } else {
  13186. /* Valid change request. */
  13187. if (setgid(to_pw->pw_gid) == -1) {
  13188. mg_cry_ctx_internal(phys_ctx,
  13189. "%s: setgid(%s): %s",
  13190. __func__,
  13191. run_as_user,
  13192. strerror(errno));
  13193. } else if (setgroups(0, NULL) == -1) {
  13194. mg_cry_ctx_internal(phys_ctx,
  13195. "%s: setgroups(): %s",
  13196. __func__,
  13197. strerror(errno));
  13198. } else if (setuid(to_pw->pw_uid) == -1) {
  13199. mg_cry_ctx_internal(phys_ctx,
  13200. "%s: setuid(%s): %s",
  13201. __func__,
  13202. run_as_user,
  13203. strerror(errno));
  13204. } else {
  13205. success = 1;
  13206. }
  13207. }
  13208. }
  13209. return success;
  13210. }
  13211. #endif /* !_WIN32 */
  13212. static void
  13213. tls_dtor(void *key)
  13214. {
  13215. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13216. /* key == pthread_getspecific(sTlsKey); */
  13217. if (tls) {
  13218. if (tls->is_master == 2) {
  13219. tls->is_master = -3; /* Mark memory as dead */
  13220. mg_free(tls);
  13221. }
  13222. }
  13223. pthread_setspecific(sTlsKey, NULL);
  13224. }
  13225. #if !defined(NO_SSL)
  13226. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13227. struct mg_domain_context *dom_ctx,
  13228. const char *pem,
  13229. const char *chain);
  13230. static const char *ssl_error(void);
  13231. static int
  13232. refresh_trust(struct mg_connection *conn)
  13233. {
  13234. static int reload_lock = 0;
  13235. static long int data_check = 0;
  13236. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  13237. struct stat cert_buf;
  13238. long int t;
  13239. const char *pem;
  13240. const char *chain;
  13241. int should_verify_peer;
  13242. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13243. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13244. * refresh_trust still can not work. */
  13245. return 0;
  13246. }
  13247. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13248. if (chain == NULL) {
  13249. /* pem is not NULL here */
  13250. chain = pem;
  13251. }
  13252. if (*chain == 0) {
  13253. chain = NULL;
  13254. }
  13255. t = data_check;
  13256. if (stat(pem, &cert_buf) != -1) {
  13257. t = (long int)cert_buf.st_mtime;
  13258. }
  13259. if (data_check != t) {
  13260. data_check = t;
  13261. should_verify_peer = 0;
  13262. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13263. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13264. == 0) {
  13265. should_verify_peer = 1;
  13266. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13267. "optional")
  13268. == 0) {
  13269. should_verify_peer = 1;
  13270. }
  13271. }
  13272. if (should_verify_peer) {
  13273. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13274. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13275. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13276. ca_file,
  13277. ca_path)
  13278. != 1) {
  13279. mg_cry_ctx_internal(
  13280. conn->phys_ctx,
  13281. "SSL_CTX_load_verify_locations error: %s "
  13282. "ssl_verify_peer requires setting "
  13283. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13284. "present in "
  13285. "the .conf file?",
  13286. ssl_error());
  13287. return 0;
  13288. }
  13289. }
  13290. if (1 == mg_atomic_inc(p_reload_lock)) {
  13291. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13292. == 0) {
  13293. return 0;
  13294. }
  13295. *p_reload_lock = 0;
  13296. }
  13297. }
  13298. /* lock while cert is reloading */
  13299. while (*p_reload_lock) {
  13300. sleep(1);
  13301. }
  13302. return 1;
  13303. }
  13304. #if defined(OPENSSL_API_1_1)
  13305. #else
  13306. static pthread_mutex_t *ssl_mutexes;
  13307. #endif /* OPENSSL_API_1_1 */
  13308. static int
  13309. sslize(struct mg_connection *conn,
  13310. SSL_CTX *s,
  13311. int (*func)(SSL *),
  13312. volatile int *stop_server,
  13313. const struct mg_client_options *client_options)
  13314. {
  13315. int ret, err;
  13316. int short_trust;
  13317. unsigned timeout = 1024;
  13318. unsigned i;
  13319. if (!conn) {
  13320. return 0;
  13321. }
  13322. short_trust =
  13323. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13324. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13325. if (short_trust) {
  13326. int trust_ret = refresh_trust(conn);
  13327. if (!trust_ret) {
  13328. return trust_ret;
  13329. }
  13330. }
  13331. conn->ssl = SSL_new(s);
  13332. if (conn->ssl == NULL) {
  13333. return 0;
  13334. }
  13335. SSL_set_app_data(conn->ssl, (char *)conn);
  13336. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13337. if (ret != 1) {
  13338. err = SSL_get_error(conn->ssl, ret);
  13339. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13340. SSL_free(conn->ssl);
  13341. conn->ssl = NULL;
  13342. OPENSSL_REMOVE_THREAD_STATE();
  13343. return 0;
  13344. }
  13345. if (client_options) {
  13346. if (client_options->host_name) {
  13347. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13348. }
  13349. }
  13350. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13351. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13352. /* NOTE: The loop below acts as a back-off, so we can end
  13353. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13354. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13355. }
  13356. /* SSL functions may fail and require to be called again:
  13357. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13358. * Here "func" could be SSL_connect or SSL_accept. */
  13359. for (i = 0; i <= timeout; i += 50) {
  13360. ret = func(conn->ssl);
  13361. if (ret != 1) {
  13362. err = SSL_get_error(conn->ssl, ret);
  13363. if ((err == SSL_ERROR_WANT_CONNECT)
  13364. || (err == SSL_ERROR_WANT_ACCEPT)
  13365. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13366. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13367. if (*stop_server) {
  13368. /* Don't wait if the server is going to be stopped. */
  13369. break;
  13370. }
  13371. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13372. /* Simply retry the function call. */
  13373. mg_sleep(50);
  13374. } else {
  13375. /* Need to retry the function call "later".
  13376. * See https://linux.die.net/man/3/ssl_get_error
  13377. * This is typical for non-blocking sockets. */
  13378. struct mg_pollfd pfd;
  13379. int pollres;
  13380. pfd.fd = conn->client.sock;
  13381. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13382. || (err == SSL_ERROR_WANT_WRITE))
  13383. ? POLLOUT
  13384. : POLLIN;
  13385. pollres = mg_poll(&pfd, 1, 50, stop_server);
  13386. if (pollres < 0) {
  13387. /* Break if error occured (-1)
  13388. * or server shutdown (-2) */
  13389. break;
  13390. }
  13391. }
  13392. } else if (err == SSL_ERROR_SYSCALL) {
  13393. /* This is an IO error. Look at errno. */
  13394. err = errno;
  13395. mg_cry_internal(conn, "SSL syscall error %i", err);
  13396. break;
  13397. } else {
  13398. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13399. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13400. break;
  13401. }
  13402. ERR_clear_error();
  13403. } else {
  13404. /* success */
  13405. break;
  13406. }
  13407. }
  13408. if (ret != 1) {
  13409. SSL_free(conn->ssl);
  13410. conn->ssl = NULL;
  13411. OPENSSL_REMOVE_THREAD_STATE();
  13412. return 0;
  13413. }
  13414. return 1;
  13415. }
  13416. /* Return OpenSSL error message (from CRYPTO lib) */
  13417. static const char *
  13418. ssl_error(void)
  13419. {
  13420. unsigned long err;
  13421. err = ERR_get_error();
  13422. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13423. }
  13424. static int
  13425. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13426. {
  13427. int i;
  13428. const char hexdigit[] = "0123456789abcdef";
  13429. if ((memlen <= 0) || (buflen <= 0)) {
  13430. return 0;
  13431. }
  13432. if (buflen < (3 * memlen)) {
  13433. return 0;
  13434. }
  13435. for (i = 0; i < memlen; i++) {
  13436. if (i > 0) {
  13437. buf[3 * i - 1] = ' ';
  13438. }
  13439. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13440. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13441. }
  13442. buf[3 * memlen - 1] = 0;
  13443. return 1;
  13444. }
  13445. static void
  13446. ssl_get_client_cert_info(struct mg_connection *conn)
  13447. {
  13448. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13449. if (cert) {
  13450. char str_subject[1024];
  13451. char str_issuer[1024];
  13452. char str_finger[1024];
  13453. unsigned char buf[256];
  13454. char *str_serial = NULL;
  13455. unsigned int ulen;
  13456. int ilen;
  13457. unsigned char *tmp_buf;
  13458. unsigned char *tmp_p;
  13459. /* Handle to algorithm used for fingerprint */
  13460. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13461. /* Get Subject and issuer */
  13462. X509_NAME *subj = X509_get_subject_name(cert);
  13463. X509_NAME *iss = X509_get_issuer_name(cert);
  13464. /* Get serial number */
  13465. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13466. /* Translate serial number to a hex string */
  13467. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13468. str_serial = BN_bn2hex(serial_bn);
  13469. BN_free(serial_bn);
  13470. /* Translate subject and issuer to a string */
  13471. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13472. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13473. /* Calculate SHA1 fingerprint and store as a hex string */
  13474. ulen = 0;
  13475. /* ASN1_digest is deprecated. Do the calculation manually,
  13476. * using EVP_Digest. */
  13477. ilen = i2d_X509(cert, NULL);
  13478. tmp_buf = (ilen > 0)
  13479. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13480. conn->phys_ctx)
  13481. : NULL;
  13482. if (tmp_buf) {
  13483. tmp_p = tmp_buf;
  13484. (void)i2d_X509(cert, &tmp_p);
  13485. if (!EVP_Digest(
  13486. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13487. ulen = 0;
  13488. }
  13489. mg_free(tmp_buf);
  13490. }
  13491. if (!hexdump2string(
  13492. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13493. *str_finger = 0;
  13494. }
  13495. conn->request_info.client_cert = (struct mg_client_cert *)
  13496. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13497. if (conn->request_info.client_cert) {
  13498. conn->request_info.client_cert->peer_cert = (void *)cert;
  13499. conn->request_info.client_cert->subject =
  13500. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13501. conn->request_info.client_cert->issuer =
  13502. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13503. conn->request_info.client_cert->serial =
  13504. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13505. conn->request_info.client_cert->finger =
  13506. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13507. } else {
  13508. mg_cry_internal(conn,
  13509. "%s",
  13510. "Out of memory: Cannot allocate memory for client "
  13511. "certificate");
  13512. }
  13513. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13514. * see https://linux.die.net/man/3/bn_bn2hex */
  13515. OPENSSL_free(str_serial);
  13516. }
  13517. }
  13518. #if defined(OPENSSL_API_1_1)
  13519. #else
  13520. static void
  13521. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13522. {
  13523. (void)line;
  13524. (void)file;
  13525. if (mode & 1) {
  13526. /* 1 is CRYPTO_LOCK */
  13527. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13528. } else {
  13529. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13530. }
  13531. }
  13532. #endif /* OPENSSL_API_1_1 */
  13533. #if !defined(NO_SSL_DL)
  13534. static void *
  13535. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13536. {
  13537. union {
  13538. void *p;
  13539. void (*fp)(void);
  13540. } u;
  13541. void *dll_handle;
  13542. struct ssl_func *fp;
  13543. int ok;
  13544. int truncated = 0;
  13545. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13546. mg_snprintf(NULL,
  13547. NULL, /* No truncation check for ebuf */
  13548. ebuf,
  13549. ebuf_len,
  13550. "%s: cannot load %s",
  13551. __func__,
  13552. dll_name);
  13553. return NULL;
  13554. }
  13555. ok = 1;
  13556. for (fp = sw; fp->name != NULL; fp++) {
  13557. #if defined(_WIN32)
  13558. /* GetProcAddress() returns pointer to function */
  13559. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13560. #else
  13561. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13562. * pointers to function pointers. We need to use a union to make a
  13563. * cast. */
  13564. u.p = dlsym(dll_handle, fp->name);
  13565. #endif /* _WIN32 */
  13566. if (u.fp == NULL) {
  13567. if (ok) {
  13568. mg_snprintf(NULL,
  13569. &truncated,
  13570. ebuf,
  13571. ebuf_len,
  13572. "%s: %s: cannot find %s",
  13573. __func__,
  13574. dll_name,
  13575. fp->name);
  13576. ok = 0;
  13577. } else {
  13578. size_t cur_len = strlen(ebuf);
  13579. if (!truncated) {
  13580. mg_snprintf(NULL,
  13581. &truncated,
  13582. ebuf + cur_len,
  13583. ebuf_len - cur_len - 3,
  13584. ", %s",
  13585. fp->name);
  13586. if (truncated) {
  13587. /* If truncated, add "..." */
  13588. strcat(ebuf, "...");
  13589. }
  13590. }
  13591. }
  13592. /* Debug:
  13593. * printf("Missing function: %s\n", fp->name); */
  13594. } else {
  13595. fp->ptr = u.fp;
  13596. }
  13597. }
  13598. if (!ok) {
  13599. (void)dlclose(dll_handle);
  13600. return NULL;
  13601. }
  13602. return dll_handle;
  13603. }
  13604. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13605. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13606. #endif /* NO_SSL_DL */
  13607. #if defined(SSL_ALREADY_INITIALIZED)
  13608. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13609. #else
  13610. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13611. #endif
  13612. static int
  13613. initialize_ssl(char *ebuf, size_t ebuf_len)
  13614. {
  13615. #if defined(OPENSSL_API_1_1)
  13616. if (ebuf_len > 0) {
  13617. ebuf[0] = 0;
  13618. }
  13619. #if !defined(NO_SSL_DL)
  13620. if (!cryptolib_dll_handle) {
  13621. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13622. if (!cryptolib_dll_handle) {
  13623. mg_snprintf(NULL,
  13624. NULL, /* No truncation check for ebuf */
  13625. ebuf,
  13626. ebuf_len,
  13627. "%s: error loading library %s",
  13628. __func__,
  13629. CRYPTO_LIB);
  13630. DEBUG_TRACE("%s", ebuf);
  13631. return 0;
  13632. }
  13633. }
  13634. #endif /* NO_SSL_DL */
  13635. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13636. return 1;
  13637. }
  13638. #else /* not OPENSSL_API_1_1 */
  13639. int i, num_locks;
  13640. size_t size;
  13641. if (ebuf_len > 0) {
  13642. ebuf[0] = 0;
  13643. }
  13644. #if !defined(NO_SSL_DL)
  13645. if (!cryptolib_dll_handle) {
  13646. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13647. if (!cryptolib_dll_handle) {
  13648. mg_snprintf(NULL,
  13649. NULL, /* No truncation check for ebuf */
  13650. ebuf,
  13651. ebuf_len,
  13652. "%s: error loading library %s",
  13653. __func__,
  13654. CRYPTO_LIB);
  13655. DEBUG_TRACE("%s", ebuf);
  13656. return 0;
  13657. }
  13658. }
  13659. #endif /* NO_SSL_DL */
  13660. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13661. return 1;
  13662. }
  13663. /* Initialize locking callbacks, needed for thread safety.
  13664. * http://www.openssl.org/support/faq.html#PROG1
  13665. */
  13666. num_locks = CRYPTO_num_locks();
  13667. if (num_locks < 0) {
  13668. num_locks = 0;
  13669. }
  13670. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13671. /* allocate mutex array, if required */
  13672. if (num_locks == 0) {
  13673. /* No mutex array required */
  13674. ssl_mutexes = NULL;
  13675. } else {
  13676. /* Mutex array required - allocate it */
  13677. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13678. /* Check OOM */
  13679. if (ssl_mutexes == NULL) {
  13680. mg_snprintf(NULL,
  13681. NULL, /* No truncation check for ebuf */
  13682. ebuf,
  13683. ebuf_len,
  13684. "%s: cannot allocate mutexes: %s",
  13685. __func__,
  13686. ssl_error());
  13687. DEBUG_TRACE("%s", ebuf);
  13688. return 0;
  13689. }
  13690. /* initialize mutex array */
  13691. for (i = 0; i < num_locks; i++) {
  13692. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13693. mg_snprintf(NULL,
  13694. NULL, /* No truncation check for ebuf */
  13695. ebuf,
  13696. ebuf_len,
  13697. "%s: error initializing mutex %i of %i",
  13698. __func__,
  13699. i,
  13700. num_locks);
  13701. DEBUG_TRACE("%s", ebuf);
  13702. mg_free(ssl_mutexes);
  13703. return 0;
  13704. }
  13705. }
  13706. }
  13707. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13708. CRYPTO_set_id_callback(&mg_current_thread_id);
  13709. #endif /* OPENSSL_API_1_1 */
  13710. #if !defined(NO_SSL_DL)
  13711. if (!ssllib_dll_handle) {
  13712. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13713. if (!ssllib_dll_handle) {
  13714. #if !defined(OPENSSL_API_1_1)
  13715. mg_free(ssl_mutexes);
  13716. #endif
  13717. DEBUG_TRACE("%s", ebuf);
  13718. return 0;
  13719. }
  13720. }
  13721. #endif /* NO_SSL_DL */
  13722. #if defined(OPENSSL_API_1_1)
  13723. /* Initialize SSL library */
  13724. OPENSSL_init_ssl(0, NULL);
  13725. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13726. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13727. NULL);
  13728. #else
  13729. /* Initialize SSL library */
  13730. SSL_library_init();
  13731. SSL_load_error_strings();
  13732. #endif
  13733. return 1;
  13734. }
  13735. static int
  13736. ssl_use_pem_file(struct mg_context *phys_ctx,
  13737. struct mg_domain_context *dom_ctx,
  13738. const char *pem,
  13739. const char *chain)
  13740. {
  13741. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13742. mg_cry_ctx_internal(phys_ctx,
  13743. "%s: cannot open certificate file %s: %s",
  13744. __func__,
  13745. pem,
  13746. ssl_error());
  13747. return 0;
  13748. }
  13749. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13750. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13751. mg_cry_ctx_internal(phys_ctx,
  13752. "%s: cannot open private key file %s: %s",
  13753. __func__,
  13754. pem,
  13755. ssl_error());
  13756. return 0;
  13757. }
  13758. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13759. mg_cry_ctx_internal(phys_ctx,
  13760. "%s: certificate and private key do not match: %s",
  13761. __func__,
  13762. pem);
  13763. return 0;
  13764. }
  13765. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13766. * chain files that contain private keys and certificates in
  13767. * SSL_CTX_use_certificate_chain_file.
  13768. * The CivetWeb-Server used pem-Files that contained both information.
  13769. * In order to make wolfSSL work, it is split in two files.
  13770. * One file that contains key and certificate used by the server and
  13771. * an optional chain file for the ssl stack.
  13772. */
  13773. if (chain) {
  13774. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13775. mg_cry_ctx_internal(phys_ctx,
  13776. "%s: cannot use certificate chain file %s: %s",
  13777. __func__,
  13778. chain,
  13779. ssl_error());
  13780. return 0;
  13781. }
  13782. }
  13783. return 1;
  13784. }
  13785. #if defined(OPENSSL_API_1_1)
  13786. static unsigned long
  13787. ssl_get_protocol(int version_id)
  13788. {
  13789. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13790. if (version_id > 0)
  13791. ret |= SSL_OP_NO_SSLv2;
  13792. if (version_id > 1)
  13793. ret |= SSL_OP_NO_SSLv3;
  13794. if (version_id > 2)
  13795. ret |= SSL_OP_NO_TLSv1;
  13796. if (version_id > 3)
  13797. ret |= SSL_OP_NO_TLSv1_1;
  13798. if (version_id > 4)
  13799. ret |= SSL_OP_NO_TLSv1_2;
  13800. #if defined(SSL_OP_NO_TLSv1_3)
  13801. if (version_id > 5)
  13802. ret |= SSL_OP_NO_TLSv1_3;
  13803. #endif
  13804. return ret;
  13805. }
  13806. #else
  13807. static long
  13808. ssl_get_protocol(int version_id)
  13809. {
  13810. long ret = (long)SSL_OP_ALL;
  13811. if (version_id > 0)
  13812. ret |= SSL_OP_NO_SSLv2;
  13813. if (version_id > 1)
  13814. ret |= SSL_OP_NO_SSLv3;
  13815. if (version_id > 2)
  13816. ret |= SSL_OP_NO_TLSv1;
  13817. if (version_id > 3)
  13818. ret |= SSL_OP_NO_TLSv1_1;
  13819. if (version_id > 4)
  13820. ret |= SSL_OP_NO_TLSv1_2;
  13821. #if defined(SSL_OP_NO_TLSv1_3)
  13822. if (version_id > 5)
  13823. ret |= SSL_OP_NO_TLSv1_3;
  13824. #endif
  13825. return ret;
  13826. }
  13827. #endif /* OPENSSL_API_1_1 */
  13828. /* SSL callback documentation:
  13829. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13830. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13831. * https://linux.die.net/man/3/ssl_set_info_callback */
  13832. /* Note: There is no "const" for the first argument in the documentation
  13833. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13834. * / OpenSSL compatibility layers have it. Having a different definition will
  13835. * cause a warning in C and an error in C++. Use "const SSL *", while
  13836. * automatical conversion from "SSL *" works for all compilers, but not other
  13837. * way around */
  13838. static void
  13839. ssl_info_callback(const SSL *ssl, int what, int ret)
  13840. {
  13841. (void)ret;
  13842. if (what & SSL_CB_HANDSHAKE_START) {
  13843. SSL_get_app_data(ssl);
  13844. }
  13845. if (what & SSL_CB_HANDSHAKE_DONE) {
  13846. /* TODO: check for openSSL 1.1 */
  13847. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13848. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13849. }
  13850. }
  13851. static int
  13852. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13853. {
  13854. struct mg_context *ctx = (struct mg_context *)arg;
  13855. struct mg_domain_context *dom =
  13856. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13857. #if defined(GCC_DIAGNOSTIC)
  13858. #pragma GCC diagnostic push
  13859. #pragma GCC diagnostic ignored "-Wcast-align"
  13860. #endif /* defined(GCC_DIAGNOSTIC) */
  13861. /* We used an aligned pointer in SSL_set_app_data */
  13862. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13863. #if defined(GCC_DIAGNOSTIC)
  13864. #pragma GCC diagnostic pop
  13865. #endif /* defined(GCC_DIAGNOSTIC) */
  13866. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13867. (void)ad;
  13868. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13869. DEBUG_TRACE("%s", "internal error - assertion failed");
  13870. return SSL_TLSEXT_ERR_NOACK;
  13871. }
  13872. /* Old clients (Win XP) will not support SNI. Then, there
  13873. * is no server name available in the request - we can
  13874. * only work with the default certificate.
  13875. * Multiple HTTPS hosts on one IP+port are only possible
  13876. * with a certificate containing all alternative names.
  13877. */
  13878. if ((servername == NULL) || (*servername == 0)) {
  13879. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13880. conn->dom_ctx = &(ctx->dd);
  13881. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13882. return SSL_TLSEXT_ERR_NOACK;
  13883. }
  13884. DEBUG_TRACE("TLS connection to host %s", servername);
  13885. while (dom) {
  13886. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13887. /* Found matching domain */
  13888. DEBUG_TRACE("TLS domain %s found",
  13889. dom->config[AUTHENTICATION_DOMAIN]);
  13890. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13891. conn->dom_ctx = dom;
  13892. return SSL_TLSEXT_ERR_OK;
  13893. }
  13894. dom = dom->next;
  13895. }
  13896. /* Default domain */
  13897. DEBUG_TRACE("TLS default domain %s used",
  13898. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13899. conn->dom_ctx = &(ctx->dd);
  13900. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13901. return SSL_TLSEXT_ERR_OK;
  13902. }
  13903. /* Setup SSL CTX as required by CivetWeb */
  13904. static int
  13905. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13906. struct mg_domain_context *dom_ctx,
  13907. const char *pem,
  13908. const char *chain)
  13909. {
  13910. int callback_ret;
  13911. int should_verify_peer;
  13912. int peer_certificate_optional;
  13913. const char *ca_path;
  13914. const char *ca_file;
  13915. int use_default_verify_paths;
  13916. int verify_depth;
  13917. struct timespec now_mt;
  13918. md5_byte_t ssl_context_id[16];
  13919. md5_state_t md5state;
  13920. int protocol_ver;
  13921. #if defined(OPENSSL_API_1_1)
  13922. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13923. mg_cry_ctx_internal(phys_ctx,
  13924. "SSL_CTX_new (server) error: %s",
  13925. ssl_error());
  13926. return 0;
  13927. }
  13928. #else
  13929. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13930. mg_cry_ctx_internal(phys_ctx,
  13931. "SSL_CTX_new (server) error: %s",
  13932. ssl_error());
  13933. return 0;
  13934. }
  13935. #endif /* OPENSSL_API_1_1 */
  13936. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13937. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13938. | SSL_OP_NO_TLSv1_1);
  13939. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13940. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13941. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13942. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13943. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13944. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13945. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13946. #if defined(SSL_OP_NO_RENEGOTIATION)
  13947. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13948. #endif
  13949. #if !defined(NO_SSL_DL)
  13950. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13951. #endif /* NO_SSL_DL */
  13952. /* In SSL documentation examples callback defined without const specifier
  13953. * 'void (*)(SSL *, int, int)' See:
  13954. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13955. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13956. * But in the source code const SSL is used:
  13957. * 'void (*)(const SSL *, int, int)' See:
  13958. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13959. * Problem about wrong documentation described, but not resolved:
  13960. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13961. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13962. * But when compiled with modern C++ compiler, correct const should be
  13963. * provided
  13964. */
  13965. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13966. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13967. ssl_servername_callback);
  13968. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13969. /* If a callback has been specified, call it. */
  13970. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13971. ? 0
  13972. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13973. phys_ctx->user_data));
  13974. /* If callback returns 0, civetweb sets up the SSL certificate.
  13975. * If it returns 1, civetweb assumes the calback already did this.
  13976. * If it returns -1, initializing ssl fails. */
  13977. if (callback_ret < 0) {
  13978. mg_cry_ctx_internal(phys_ctx,
  13979. "SSL callback returned error: %i",
  13980. callback_ret);
  13981. return 0;
  13982. }
  13983. if (callback_ret > 0) {
  13984. /* Callback did everything. */
  13985. return 1;
  13986. }
  13987. /* If a domain callback has been specified, call it. */
  13988. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  13989. ? 0
  13990. : (phys_ctx->callbacks.init_ssl_domain(
  13991. dom_ctx->config[AUTHENTICATION_DOMAIN],
  13992. dom_ctx->ssl_ctx,
  13993. phys_ctx->user_data));
  13994. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  13995. * If it returns 1, civetweb assumes the calback already did this.
  13996. * If it returns -1, initializing ssl fails. */
  13997. if (callback_ret < 0) {
  13998. mg_cry_ctx_internal(phys_ctx,
  13999. "Domain SSL callback returned error: %i",
  14000. callback_ret);
  14001. return 0;
  14002. }
  14003. if (callback_ret > 0) {
  14004. /* Domain callback did everything. */
  14005. return 1;
  14006. }
  14007. /* Use some combination of start time, domain and port as a SSL
  14008. * context ID. This should be unique on the current machine. */
  14009. md5_init(&md5state);
  14010. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14011. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14012. md5_append(&md5state,
  14013. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14014. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14015. md5_append(&md5state,
  14016. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14017. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14018. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14019. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14020. md5_finish(&md5state, ssl_context_id);
  14021. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14022. (unsigned char *)ssl_context_id,
  14023. sizeof(ssl_context_id));
  14024. if (pem != NULL) {
  14025. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14026. return 0;
  14027. }
  14028. }
  14029. /* Should we support client certificates? */
  14030. /* Default is "no". */
  14031. should_verify_peer = 0;
  14032. peer_certificate_optional = 0;
  14033. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14034. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14035. /* Yes, they are mandatory */
  14036. should_verify_peer = 1;
  14037. peer_certificate_optional = 0;
  14038. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14039. "optional")
  14040. == 0) {
  14041. /* Yes, they are optional */
  14042. should_verify_peer = 1;
  14043. peer_certificate_optional = 1;
  14044. }
  14045. }
  14046. use_default_verify_paths =
  14047. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14048. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14049. == 0);
  14050. if (should_verify_peer) {
  14051. ca_path = dom_ctx->config[SSL_CA_PATH];
  14052. ca_file = dom_ctx->config[SSL_CA_FILE];
  14053. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14054. != 1) {
  14055. mg_cry_ctx_internal(phys_ctx,
  14056. "SSL_CTX_load_verify_locations error: %s "
  14057. "ssl_verify_peer requires setting "
  14058. "either ssl_ca_path or ssl_ca_file. "
  14059. "Is any of them present in the "
  14060. ".conf file?",
  14061. ssl_error());
  14062. return 0;
  14063. }
  14064. if (peer_certificate_optional) {
  14065. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14066. } else {
  14067. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14068. SSL_VERIFY_PEER
  14069. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14070. NULL);
  14071. }
  14072. if (use_default_verify_paths
  14073. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14074. mg_cry_ctx_internal(phys_ctx,
  14075. "SSL_CTX_set_default_verify_paths error: %s",
  14076. ssl_error());
  14077. return 0;
  14078. }
  14079. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14080. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14081. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14082. }
  14083. }
  14084. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14085. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14086. dom_ctx->config[SSL_CIPHER_LIST])
  14087. != 1) {
  14088. mg_cry_ctx_internal(phys_ctx,
  14089. "SSL_CTX_set_cipher_list error: %s",
  14090. ssl_error());
  14091. }
  14092. }
  14093. return 1;
  14094. }
  14095. /* Check if SSL is required.
  14096. * If so, dynamically load SSL library
  14097. * and set up ctx->ssl_ctx pointer. */
  14098. static int
  14099. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14100. {
  14101. void *ssl_ctx = 0;
  14102. int callback_ret;
  14103. const char *pem;
  14104. const char *chain;
  14105. char ebuf[128];
  14106. if (!phys_ctx) {
  14107. return 0;
  14108. }
  14109. if (!dom_ctx) {
  14110. dom_ctx = &(phys_ctx->dd);
  14111. }
  14112. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14113. /* No SSL port is set. No need to setup SSL. */
  14114. return 1;
  14115. }
  14116. /* Check for external SSL_CTX */
  14117. callback_ret =
  14118. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14119. ? 0
  14120. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14121. phys_ctx->user_data));
  14122. if (callback_ret < 0) {
  14123. mg_cry_ctx_internal(phys_ctx,
  14124. "external_ssl_ctx callback returned error: %i",
  14125. callback_ret);
  14126. return 0;
  14127. } else if (callback_ret > 0) {
  14128. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14129. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14130. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14131. return 0;
  14132. }
  14133. return 1;
  14134. }
  14135. /* Check for external domain SSL_CTX */
  14136. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14137. ? 0
  14138. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14139. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14140. &ssl_ctx,
  14141. phys_ctx->user_data));
  14142. if (callback_ret < 0) {
  14143. mg_cry_ctx_internal(
  14144. phys_ctx,
  14145. "external_ssl_ctx_domain callback returned error: %i",
  14146. callback_ret);
  14147. return 0;
  14148. } else if (callback_ret > 0) {
  14149. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14150. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14151. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14152. return 0;
  14153. }
  14154. return 1;
  14155. }
  14156. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return 0,
  14157. * CivetWeb should continue initializing SSL */
  14158. /* If PEM file is not specified and the init_ssl callbacks
  14159. * are not specified, setup will fail. */
  14160. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14161. && (phys_ctx->callbacks.init_ssl == NULL)
  14162. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14163. /* No certificate and no init_ssl callbacks:
  14164. * Essential data to set up TLS is missing.
  14165. */
  14166. mg_cry_ctx_internal(phys_ctx,
  14167. "Initializing SSL failed: -%s is not set",
  14168. config_options[SSL_CERTIFICATE].name);
  14169. return 0;
  14170. }
  14171. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14172. if (chain == NULL) {
  14173. chain = pem;
  14174. }
  14175. if ((chain != NULL) && (*chain == 0)) {
  14176. chain = NULL;
  14177. }
  14178. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14179. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14180. return 0;
  14181. }
  14182. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14183. }
  14184. static void
  14185. uninitialize_ssl(void)
  14186. {
  14187. #if defined(OPENSSL_API_1_1)
  14188. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14189. /* Shutdown according to
  14190. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14191. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14192. */
  14193. CONF_modules_unload(1);
  14194. #else
  14195. int i;
  14196. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14197. /* Shutdown according to
  14198. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14199. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14200. */
  14201. CRYPTO_set_locking_callback(NULL);
  14202. CRYPTO_set_id_callback(NULL);
  14203. ENGINE_cleanup();
  14204. CONF_modules_unload(1);
  14205. ERR_free_strings();
  14206. EVP_cleanup();
  14207. CRYPTO_cleanup_all_ex_data();
  14208. OPENSSL_REMOVE_THREAD_STATE();
  14209. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14210. pthread_mutex_destroy(&ssl_mutexes[i]);
  14211. }
  14212. mg_free(ssl_mutexes);
  14213. ssl_mutexes = NULL;
  14214. #endif /* OPENSSL_API_1_1 */
  14215. }
  14216. }
  14217. #endif /* !NO_SSL */
  14218. #if !defined(NO_FILESYSTEMS)
  14219. static int
  14220. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14221. {
  14222. if (phys_ctx) {
  14223. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14224. const char *path;
  14225. struct mg_connection fc;
  14226. if (!dom_ctx) {
  14227. dom_ctx = &(phys_ctx->dd);
  14228. }
  14229. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14230. if ((path != NULL)
  14231. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14232. mg_cry_ctx_internal(phys_ctx,
  14233. "Cannot open %s: %s",
  14234. path,
  14235. strerror(ERRNO));
  14236. return 0;
  14237. }
  14238. return 1;
  14239. }
  14240. return 0;
  14241. }
  14242. #endif /* NO_FILESYSTEMS */
  14243. static int
  14244. set_acl_option(struct mg_context *phys_ctx)
  14245. {
  14246. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14247. }
  14248. static void
  14249. reset_per_request_attributes(struct mg_connection *conn)
  14250. {
  14251. if (!conn) {
  14252. return;
  14253. }
  14254. conn->connection_type =
  14255. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14256. conn->num_bytes_sent = conn->consumed_content = 0;
  14257. conn->path_info = NULL;
  14258. conn->status_code = -1;
  14259. conn->content_len = -1;
  14260. conn->is_chunked = 0;
  14261. conn->must_close = 0;
  14262. conn->request_len = 0;
  14263. conn->throttle = 0;
  14264. conn->accept_gzip = 0;
  14265. conn->response_info.content_length = conn->request_info.content_length = -1;
  14266. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14267. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14268. conn->response_info.status_text = NULL;
  14269. conn->response_info.status_code = 0;
  14270. conn->request_info.remote_user = NULL;
  14271. conn->request_info.request_method = NULL;
  14272. conn->request_info.request_uri = NULL;
  14273. conn->request_info.local_uri = NULL;
  14274. #if defined(MG_LEGACY_INTERFACE)
  14275. /* Legacy before split into local_uri and request_uri */
  14276. conn->request_info.uri = NULL;
  14277. #endif
  14278. }
  14279. static int
  14280. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14281. {
  14282. if (setsockopt(sock,
  14283. IPPROTO_TCP,
  14284. TCP_NODELAY,
  14285. (SOCK_OPT_TYPE)&nodelay_on,
  14286. sizeof(nodelay_on))
  14287. != 0) {
  14288. /* Error */
  14289. return 1;
  14290. }
  14291. /* OK */
  14292. return 0;
  14293. }
  14294. #if !defined(__ZEPHYR__)
  14295. static void
  14296. close_socket_gracefully(struct mg_connection *conn)
  14297. {
  14298. #if defined(_WIN32)
  14299. char buf[MG_BUF_LEN];
  14300. int n;
  14301. #endif
  14302. struct linger linger;
  14303. int error_code = 0;
  14304. int linger_timeout = -2;
  14305. socklen_t opt_len = sizeof(error_code);
  14306. if (!conn) {
  14307. return;
  14308. }
  14309. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14310. * "Note that enabling a nonzero timeout on a nonblocking socket
  14311. * is not recommended.", so set it to blocking now */
  14312. set_blocking_mode(conn->client.sock);
  14313. /* Send FIN to the client */
  14314. shutdown(conn->client.sock, SHUTDOWN_WR);
  14315. #if defined(_WIN32)
  14316. /* Read and discard pending incoming data. If we do not do that and
  14317. * close
  14318. * the socket, the data in the send buffer may be discarded. This
  14319. * behaviour is seen on Windows, when client keeps sending data
  14320. * when server decides to close the connection; then when client
  14321. * does recv() it gets no data back. */
  14322. do {
  14323. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14324. } while (n > 0);
  14325. #endif
  14326. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14327. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14328. }
  14329. /* Set linger option according to configuration */
  14330. if (linger_timeout >= 0) {
  14331. /* Set linger option to avoid socket hanging out after close. This
  14332. * prevent ephemeral port exhaust problem under high QPS. */
  14333. linger.l_onoff = 1;
  14334. #if defined(_MSC_VER)
  14335. #pragma warning(push)
  14336. #pragma warning(disable : 4244)
  14337. #endif
  14338. #if defined(GCC_DIAGNOSTIC)
  14339. #pragma GCC diagnostic push
  14340. #pragma GCC diagnostic ignored "-Wconversion"
  14341. #endif
  14342. /* Data type of linger structure elements may differ,
  14343. * so we don't know what cast we need here.
  14344. * Disable type conversion warnings. */
  14345. linger.l_linger = (linger_timeout + 999) / 1000;
  14346. #if defined(GCC_DIAGNOSTIC)
  14347. #pragma GCC diagnostic pop
  14348. #endif
  14349. #if defined(_MSC_VER)
  14350. #pragma warning(pop)
  14351. #endif
  14352. } else {
  14353. linger.l_onoff = 0;
  14354. linger.l_linger = 0;
  14355. }
  14356. if (linger_timeout < -1) {
  14357. /* Default: don't configure any linger */
  14358. } else if (getsockopt(conn->client.sock,
  14359. SOL_SOCKET,
  14360. SO_ERROR,
  14361. #if defined(_WIN32) /* WinSock uses different data type here */
  14362. (char *)&error_code,
  14363. #else
  14364. &error_code,
  14365. #endif
  14366. &opt_len)
  14367. != 0) {
  14368. /* Cannot determine if socket is already closed. This should
  14369. * not occur and never did in a test. Log an error message
  14370. * and continue. */
  14371. mg_cry_internal(conn,
  14372. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14373. __func__,
  14374. strerror(ERRNO));
  14375. #if defined(_WIN32)
  14376. } else if (error_code == WSAECONNRESET) {
  14377. #else
  14378. } else if (error_code == ECONNRESET) {
  14379. #endif
  14380. /* Socket already closed by client/peer, close socket without linger
  14381. */
  14382. } else {
  14383. /* Set linger timeout */
  14384. if (setsockopt(conn->client.sock,
  14385. SOL_SOCKET,
  14386. SO_LINGER,
  14387. (char *)&linger,
  14388. sizeof(linger))
  14389. != 0) {
  14390. mg_cry_internal(
  14391. conn,
  14392. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14393. __func__,
  14394. linger.l_onoff,
  14395. linger.l_linger,
  14396. strerror(ERRNO));
  14397. }
  14398. }
  14399. /* Now we know that our FIN is ACK-ed, safe to close */
  14400. closesocket(conn->client.sock);
  14401. conn->client.sock = INVALID_SOCKET;
  14402. }
  14403. #endif
  14404. static void
  14405. close_connection(struct mg_connection *conn)
  14406. {
  14407. #if defined(USE_SERVER_STATS)
  14408. conn->conn_state = 6; /* to close */
  14409. #endif
  14410. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14411. if (conn->lua_websocket_state) {
  14412. lua_websocket_close(conn, conn->lua_websocket_state);
  14413. conn->lua_websocket_state = NULL;
  14414. }
  14415. #endif
  14416. mg_lock_connection(conn);
  14417. /* Set close flag, so keep-alive loops will stop */
  14418. conn->must_close = 1;
  14419. /* call the connection_close callback if assigned */
  14420. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14421. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14422. conn->phys_ctx->callbacks.connection_close(conn);
  14423. }
  14424. }
  14425. /* Reset user data, after close callback is called.
  14426. * Do not reuse it. If the user needs a destructor,
  14427. * it must be done in the connection_close callback. */
  14428. mg_set_user_connection_data(conn, NULL);
  14429. #if defined(USE_SERVER_STATS)
  14430. conn->conn_state = 7; /* closing */
  14431. #endif
  14432. #if !defined(NO_SSL)
  14433. if (conn->ssl != NULL) {
  14434. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14435. */
  14436. SSL_shutdown(conn->ssl);
  14437. SSL_free(conn->ssl);
  14438. OPENSSL_REMOVE_THREAD_STATE();
  14439. conn->ssl = NULL;
  14440. }
  14441. #endif
  14442. if (conn->client.sock != INVALID_SOCKET) {
  14443. #if defined(__ZEPHYR__)
  14444. closesocket(conn->client.sock);
  14445. #else
  14446. close_socket_gracefully(conn);
  14447. #endif
  14448. conn->client.sock = INVALID_SOCKET;
  14449. }
  14450. if (conn->host) {
  14451. mg_free((void *)conn->host);
  14452. conn->host = NULL;
  14453. }
  14454. mg_unlock_connection(conn);
  14455. #if defined(USE_SERVER_STATS)
  14456. conn->conn_state = 8; /* closed */
  14457. #endif
  14458. }
  14459. void
  14460. mg_close_connection(struct mg_connection *conn)
  14461. {
  14462. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14463. return;
  14464. }
  14465. #if defined(USE_WEBSOCKET)
  14466. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14467. if (conn->in_websocket_handling) {
  14468. /* Set close flag, so the server thread can exit. */
  14469. conn->must_close = 1;
  14470. return;
  14471. }
  14472. }
  14473. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14474. unsigned int i;
  14475. /* client context: loops must end */
  14476. conn->phys_ctx->stop_flag = 1;
  14477. conn->must_close = 1;
  14478. /* We need to get the client thread out of the select/recv call
  14479. * here. */
  14480. /* Since we use a sleep quantum of some seconds to check for recv
  14481. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14482. /* join worker thread */
  14483. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14484. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14485. }
  14486. }
  14487. #endif /* defined(USE_WEBSOCKET) */
  14488. close_connection(conn);
  14489. #if !defined(NO_SSL)
  14490. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14491. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14492. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14493. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14494. }
  14495. #endif
  14496. #if defined(USE_WEBSOCKET)
  14497. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14498. mg_free(conn->phys_ctx->worker_threadids);
  14499. (void)pthread_mutex_destroy(&conn->mutex);
  14500. mg_free(conn);
  14501. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14502. mg_free(conn);
  14503. }
  14504. #else
  14505. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14506. mg_free(conn);
  14507. }
  14508. #endif /* defined(USE_WEBSOCKET) */
  14509. }
  14510. static struct mg_connection *
  14511. mg_connect_client_impl(const struct mg_client_options *client_options,
  14512. int use_ssl,
  14513. char *ebuf,
  14514. size_t ebuf_len)
  14515. {
  14516. struct mg_connection *conn = NULL;
  14517. SOCKET sock;
  14518. union usa sa;
  14519. struct sockaddr *psa;
  14520. socklen_t len;
  14521. unsigned max_req_size =
  14522. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14523. /* Size of structures, aligned to 8 bytes */
  14524. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14525. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14526. conn =
  14527. (struct mg_connection *)mg_calloc(1,
  14528. conn_size + ctx_size + max_req_size);
  14529. if (conn == NULL) {
  14530. mg_snprintf(NULL,
  14531. NULL, /* No truncation check for ebuf */
  14532. ebuf,
  14533. ebuf_len,
  14534. "calloc(): %s",
  14535. strerror(ERRNO));
  14536. return NULL;
  14537. }
  14538. #if defined(GCC_DIAGNOSTIC)
  14539. #pragma GCC diagnostic push
  14540. #pragma GCC diagnostic ignored "-Wcast-align"
  14541. #endif /* defined(GCC_DIAGNOSTIC) */
  14542. /* conn_size is aligned to 8 bytes */
  14543. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14544. #if defined(GCC_DIAGNOSTIC)
  14545. #pragma GCC diagnostic pop
  14546. #endif /* defined(GCC_DIAGNOSTIC) */
  14547. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14548. conn->buf_size = (int)max_req_size;
  14549. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14550. conn->dom_ctx = &(conn->phys_ctx->dd);
  14551. if (!connect_socket(conn->phys_ctx,
  14552. client_options->host,
  14553. client_options->port,
  14554. use_ssl,
  14555. ebuf,
  14556. ebuf_len,
  14557. &sock,
  14558. &sa)) {
  14559. /* ebuf is set by connect_socket,
  14560. * free all memory and return NULL; */
  14561. mg_free(conn);
  14562. return NULL;
  14563. }
  14564. #if !defined(NO_SSL)
  14565. #if defined(OPENSSL_API_1_1)
  14566. if (use_ssl
  14567. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14568. == NULL) {
  14569. mg_snprintf(NULL,
  14570. NULL, /* No truncation check for ebuf */
  14571. ebuf,
  14572. ebuf_len,
  14573. "SSL_CTX_new error: %s",
  14574. ssl_error());
  14575. closesocket(sock);
  14576. mg_free(conn);
  14577. return NULL;
  14578. }
  14579. #else
  14580. if (use_ssl
  14581. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14582. == NULL) {
  14583. mg_snprintf(NULL,
  14584. NULL, /* No truncation check for ebuf */
  14585. ebuf,
  14586. ebuf_len,
  14587. "SSL_CTX_new error: %s",
  14588. ssl_error());
  14589. closesocket(sock);
  14590. mg_free(conn);
  14591. return NULL;
  14592. }
  14593. #endif /* OPENSSL_API_1_1 */
  14594. #endif /* NO_SSL */
  14595. #if defined(USE_IPV6)
  14596. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14597. : sizeof(conn->client.rsa.sin6);
  14598. psa = (sa.sa.sa_family == AF_INET)
  14599. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14600. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14601. #else
  14602. len = sizeof(conn->client.rsa.sin);
  14603. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14604. #endif
  14605. conn->client.sock = sock;
  14606. conn->client.lsa = sa;
  14607. if (getsockname(sock, psa, &len) != 0) {
  14608. mg_cry_internal(conn,
  14609. "%s: getsockname() failed: %s",
  14610. __func__,
  14611. strerror(ERRNO));
  14612. }
  14613. conn->client.is_ssl = use_ssl ? 1 : 0;
  14614. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14615. mg_snprintf(NULL,
  14616. NULL, /* No truncation check for ebuf */
  14617. ebuf,
  14618. ebuf_len,
  14619. "Can not create mutex");
  14620. #if !defined(NO_SSL)
  14621. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14622. #endif
  14623. closesocket(sock);
  14624. mg_free(conn);
  14625. return NULL;
  14626. }
  14627. #if !defined(NO_SSL)
  14628. if (use_ssl) {
  14629. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14630. * SSL_CTX_set_verify call is needed to switch off server
  14631. * certificate checking, which is off by default in OpenSSL and
  14632. * on in yaSSL. */
  14633. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14634. * SSL_VERIFY_PEER, verify_ssl_server); */
  14635. if (client_options->client_cert) {
  14636. if (!ssl_use_pem_file(conn->phys_ctx,
  14637. conn->dom_ctx,
  14638. client_options->client_cert,
  14639. NULL)) {
  14640. mg_snprintf(NULL,
  14641. NULL, /* No truncation check for ebuf */
  14642. ebuf,
  14643. ebuf_len,
  14644. "Can not use SSL client certificate");
  14645. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14646. closesocket(sock);
  14647. mg_free(conn);
  14648. return NULL;
  14649. }
  14650. }
  14651. if (client_options->server_cert) {
  14652. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14653. client_options->server_cert,
  14654. NULL)
  14655. != 1) {
  14656. mg_cry_internal(conn,
  14657. "SSL_CTX_load_verify_locations error: %s ",
  14658. ssl_error());
  14659. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14660. closesocket(sock);
  14661. mg_free(conn);
  14662. return NULL;
  14663. }
  14664. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14665. } else {
  14666. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14667. }
  14668. if (!sslize(conn,
  14669. conn->dom_ctx->ssl_ctx,
  14670. SSL_connect,
  14671. &(conn->phys_ctx->stop_flag),
  14672. client_options)) {
  14673. mg_snprintf(NULL,
  14674. NULL, /* No truncation check for ebuf */
  14675. ebuf,
  14676. ebuf_len,
  14677. "SSL connection error");
  14678. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14679. closesocket(sock);
  14680. mg_free(conn);
  14681. return NULL;
  14682. }
  14683. }
  14684. #endif
  14685. return conn;
  14686. }
  14687. CIVETWEB_API struct mg_connection *
  14688. mg_connect_client_secure(const struct mg_client_options *client_options,
  14689. char *error_buffer,
  14690. size_t error_buffer_size)
  14691. {
  14692. return mg_connect_client_impl(client_options,
  14693. 1,
  14694. error_buffer,
  14695. error_buffer_size);
  14696. }
  14697. struct mg_connection *
  14698. mg_connect_client(const char *host,
  14699. int port,
  14700. int use_ssl,
  14701. char *error_buffer,
  14702. size_t error_buffer_size)
  14703. {
  14704. struct mg_client_options opts;
  14705. memset(&opts, 0, sizeof(opts));
  14706. opts.host = host;
  14707. opts.port = port;
  14708. return mg_connect_client_impl(&opts,
  14709. use_ssl,
  14710. error_buffer,
  14711. error_buffer_size);
  14712. }
  14713. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14714. struct mg_connection *
  14715. mg_connect_client2(const char *host,
  14716. const char *protocol,
  14717. int port,
  14718. const char *path,
  14719. struct mg_init_data *init,
  14720. struct mg_error_data *error)
  14721. {
  14722. int is_ssl, is_ws;
  14723. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14724. if (error != NULL) {
  14725. error->code = 0;
  14726. if (error->text_buffer_size > 0) {
  14727. *error->text = 0;
  14728. }
  14729. }
  14730. if ((host == NULL) || (protocol == NULL)) {
  14731. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14732. mg_snprintf(NULL,
  14733. NULL, /* No truncation check for error buffers */
  14734. error->text,
  14735. error->text_buffer_size,
  14736. "%s",
  14737. "Invalid parameters");
  14738. }
  14739. return NULL;
  14740. }
  14741. /* check all known protocolls */
  14742. if (!mg_strcasecmp(protocol, "http")) {
  14743. is_ssl = 0;
  14744. is_ws = 0;
  14745. } else if (!mg_strcasecmp(protocol, "https")) {
  14746. is_ssl = 1;
  14747. is_ws = 0;
  14748. #if defined(USE_WEBSOCKET)
  14749. } else if (!mg_strcasecmp(protocol, "ws")) {
  14750. is_ssl = 0;
  14751. is_ws = 1;
  14752. } else if (!mg_strcasecmp(protocol, "wss")) {
  14753. is_ssl = 1;
  14754. is_ws = 1;
  14755. #endif
  14756. } else {
  14757. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14758. mg_snprintf(NULL,
  14759. NULL, /* No truncation check for error buffers */
  14760. error->text,
  14761. error->text_buffer_size,
  14762. "Protocol %s not supported",
  14763. protocol);
  14764. }
  14765. return NULL;
  14766. }
  14767. /* TODO: The current implementation here just calls the old implementations,
  14768. * without using any new options. This is just a first step to test the new
  14769. * interfaces. */
  14770. #if defined(USE_WEBSOCKET)
  14771. if (is_ws) {
  14772. /* TODO: implement all options */
  14773. return mg_connect_websocket_client(host,
  14774. port,
  14775. is_ssl,
  14776. error->text,
  14777. error->text_buffer_size,
  14778. (path ? path : ""),
  14779. NULL /* TODO: origin */,
  14780. deprecated_websocket_data_wrapper,
  14781. deprecated_websocket_close_wrapper,
  14782. (void *)init->callbacks);
  14783. }
  14784. #endif
  14785. /* TODO: all additional options */
  14786. struct mg_client_options opts;
  14787. memset(&opts, 0, sizeof(opts));
  14788. opts.host = host;
  14789. opts.port = port;
  14790. return mg_connect_client_impl(&opts,
  14791. is_ssl,
  14792. error->text,
  14793. error->text_buffer_size);
  14794. }
  14795. #endif
  14796. static const struct {
  14797. const char *proto;
  14798. size_t proto_len;
  14799. unsigned default_port;
  14800. } abs_uri_protocols[] = {{"http://", 7, 80},
  14801. {"https://", 8, 443},
  14802. {"ws://", 5, 80},
  14803. {"wss://", 6, 443},
  14804. {NULL, 0, 0}};
  14805. /* Check if the uri is valid.
  14806. * return 0 for invalid uri,
  14807. * return 1 for *,
  14808. * return 2 for relative uri,
  14809. * return 3 for absolute uri without port,
  14810. * return 4 for absolute uri with port */
  14811. static int
  14812. get_uri_type(const char *uri)
  14813. {
  14814. int i;
  14815. const char *hostend, *portbegin;
  14816. char *portend;
  14817. unsigned long port;
  14818. /* According to the HTTP standard
  14819. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14820. * URI can be an asterisk (*) or should start with slash (relative uri),
  14821. * or it should start with the protocol (absolute uri). */
  14822. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14823. /* asterisk */
  14824. return 1;
  14825. }
  14826. /* Valid URIs according to RFC 3986
  14827. * (https://www.ietf.org/rfc/rfc3986.txt)
  14828. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14829. * and unreserved characters A-Z a-z 0-9 and -._~
  14830. * and % encoded symbols.
  14831. */
  14832. for (i = 0; uri[i] != 0; i++) {
  14833. if (uri[i] < 33) {
  14834. /* control characters and spaces are invalid */
  14835. return 0;
  14836. }
  14837. if (uri[i] > 126) {
  14838. /* non-ascii characters must be % encoded */
  14839. return 0;
  14840. } else {
  14841. switch (uri[i]) {
  14842. case '"': /* 34 */
  14843. case '<': /* 60 */
  14844. case '>': /* 62 */
  14845. case '\\': /* 92 */
  14846. case '^': /* 94 */
  14847. case '`': /* 96 */
  14848. case '{': /* 123 */
  14849. case '|': /* 124 */
  14850. case '}': /* 125 */
  14851. return 0;
  14852. default:
  14853. /* character is ok */
  14854. break;
  14855. }
  14856. }
  14857. }
  14858. /* A relative uri starts with a / character */
  14859. if (uri[0] == '/') {
  14860. /* relative uri */
  14861. return 2;
  14862. }
  14863. /* It could be an absolute uri: */
  14864. /* This function only checks if the uri is valid, not if it is
  14865. * addressing the current server. So civetweb can also be used
  14866. * as a proxy server. */
  14867. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14868. if (mg_strncasecmp(uri,
  14869. abs_uri_protocols[i].proto,
  14870. abs_uri_protocols[i].proto_len)
  14871. == 0) {
  14872. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14873. if (!hostend) {
  14874. return 0;
  14875. }
  14876. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14877. if (!portbegin) {
  14878. return 3;
  14879. }
  14880. port = strtoul(portbegin + 1, &portend, 10);
  14881. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14882. return 0;
  14883. }
  14884. return 4;
  14885. }
  14886. }
  14887. return 0;
  14888. }
  14889. /* Return NULL or the relative uri at the current server */
  14890. static const char *
  14891. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14892. {
  14893. const char *server_domain;
  14894. size_t server_domain_len;
  14895. size_t request_domain_len = 0;
  14896. unsigned long port = 0;
  14897. int i, auth_domain_check_enabled;
  14898. const char *hostbegin = NULL;
  14899. const char *hostend = NULL;
  14900. const char *portbegin;
  14901. char *portend;
  14902. auth_domain_check_enabled =
  14903. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14904. /* DNS is case insensitive, so use case insensitive string compare here
  14905. */
  14906. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14907. if (mg_strncasecmp(uri,
  14908. abs_uri_protocols[i].proto,
  14909. abs_uri_protocols[i].proto_len)
  14910. == 0) {
  14911. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14912. hostend = strchr(hostbegin, '/');
  14913. if (!hostend) {
  14914. return 0;
  14915. }
  14916. portbegin = strchr(hostbegin, ':');
  14917. if ((!portbegin) || (portbegin > hostend)) {
  14918. port = abs_uri_protocols[i].default_port;
  14919. request_domain_len = (size_t)(hostend - hostbegin);
  14920. } else {
  14921. port = strtoul(portbegin + 1, &portend, 10);
  14922. if ((portend != hostend) || (port <= 0)
  14923. || !is_valid_port(port)) {
  14924. return 0;
  14925. }
  14926. request_domain_len = (size_t)(portbegin - hostbegin);
  14927. }
  14928. /* protocol found, port set */
  14929. break;
  14930. }
  14931. }
  14932. if (!port) {
  14933. /* port remains 0 if the protocol is not found */
  14934. return 0;
  14935. }
  14936. /* Check if the request is directed to a different server. */
  14937. /* First check if the port is the same (IPv4 and IPv6). */
  14938. #if defined(USE_IPV6)
  14939. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14940. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14941. /* Request is directed to a different port */
  14942. return 0;
  14943. }
  14944. } else
  14945. #endif
  14946. {
  14947. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14948. /* Request is directed to a different port */
  14949. return 0;
  14950. }
  14951. }
  14952. /* Finally check if the server corresponds to the authentication
  14953. * domain of the server (the server domain).
  14954. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14955. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14956. * but do not allow substrings (like
  14957. * http://notmydomain.com/path/file.ext
  14958. * or http://mydomain.com.fake/path/file.ext).
  14959. */
  14960. if (auth_domain_check_enabled) {
  14961. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14962. server_domain_len = strlen(server_domain);
  14963. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14964. return 0;
  14965. }
  14966. if ((request_domain_len == server_domain_len)
  14967. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14968. /* Request is directed to this server - full name match. */
  14969. } else {
  14970. if (request_domain_len < (server_domain_len + 2)) {
  14971. /* Request is directed to another server: The server name
  14972. * is longer than the request name.
  14973. * Drop this case here to avoid overflows in the
  14974. * following checks. */
  14975. return 0;
  14976. }
  14977. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14978. /* Request is directed to another server: It could be a
  14979. * substring
  14980. * like notmyserver.com */
  14981. return 0;
  14982. }
  14983. if (0
  14984. != memcmp(server_domain,
  14985. hostbegin + request_domain_len - server_domain_len,
  14986. server_domain_len)) {
  14987. /* Request is directed to another server:
  14988. * The server name is different. */
  14989. return 0;
  14990. }
  14991. }
  14992. }
  14993. return hostend;
  14994. }
  14995. static int
  14996. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14997. {
  14998. if (ebuf_len > 0) {
  14999. ebuf[0] = '\0';
  15000. }
  15001. *err = 0;
  15002. reset_per_request_attributes(conn);
  15003. if (!conn) {
  15004. mg_snprintf(conn,
  15005. NULL, /* No truncation check for ebuf */
  15006. ebuf,
  15007. ebuf_len,
  15008. "%s",
  15009. "Internal error");
  15010. *err = 500;
  15011. return 0;
  15012. }
  15013. /* Set the time the request was received. This value should be used for
  15014. * timeouts. */
  15015. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15016. conn->request_len =
  15017. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15018. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15019. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15020. mg_snprintf(conn,
  15021. NULL, /* No truncation check for ebuf */
  15022. ebuf,
  15023. ebuf_len,
  15024. "%s",
  15025. "Invalid message size");
  15026. *err = 500;
  15027. return 0;
  15028. }
  15029. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15030. mg_snprintf(conn,
  15031. NULL, /* No truncation check for ebuf */
  15032. ebuf,
  15033. ebuf_len,
  15034. "%s",
  15035. "Message too large");
  15036. *err = 413;
  15037. return 0;
  15038. }
  15039. if (conn->request_len <= 0) {
  15040. if (conn->data_len > 0) {
  15041. mg_snprintf(conn,
  15042. NULL, /* No truncation check for ebuf */
  15043. ebuf,
  15044. ebuf_len,
  15045. "%s",
  15046. "Malformed message");
  15047. *err = 400;
  15048. } else {
  15049. /* Server did not recv anything -> just close the connection */
  15050. conn->must_close = 1;
  15051. mg_snprintf(conn,
  15052. NULL, /* No truncation check for ebuf */
  15053. ebuf,
  15054. ebuf_len,
  15055. "%s",
  15056. "No data received");
  15057. *err = 0;
  15058. }
  15059. return 0;
  15060. }
  15061. return 1;
  15062. }
  15063. static int
  15064. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15065. {
  15066. const char *cl;
  15067. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15068. return 0;
  15069. }
  15070. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15071. <= 0) {
  15072. mg_snprintf(conn,
  15073. NULL, /* No truncation check for ebuf */
  15074. ebuf,
  15075. ebuf_len,
  15076. "%s",
  15077. "Bad request");
  15078. *err = 400;
  15079. return 0;
  15080. }
  15081. /* Message is a valid request */
  15082. /* Is there a "host" ? */
  15083. if (conn->host != NULL) {
  15084. mg_free((void *)conn->host);
  15085. }
  15086. conn->host = alloc_get_host(conn);
  15087. if (!conn->host) {
  15088. mg_snprintf(conn,
  15089. NULL, /* No truncation check for ebuf */
  15090. ebuf,
  15091. ebuf_len,
  15092. "%s",
  15093. "Bad request: Host mismatch");
  15094. *err = 400;
  15095. return 0;
  15096. }
  15097. if (((cl = get_header(conn->request_info.http_headers,
  15098. conn->request_info.num_headers,
  15099. "Transfer-Encoding"))
  15100. != NULL)
  15101. && mg_strcasecmp(cl, "identity")) {
  15102. if (mg_strcasecmp(cl, "chunked")) {
  15103. mg_snprintf(conn,
  15104. NULL, /* No truncation check for ebuf */
  15105. ebuf,
  15106. ebuf_len,
  15107. "%s",
  15108. "Bad request");
  15109. *err = 400;
  15110. return 0;
  15111. }
  15112. conn->is_chunked = 1;
  15113. conn->content_len = 0; /* not yet read */
  15114. } else if ((cl = get_header(conn->request_info.http_headers,
  15115. conn->request_info.num_headers,
  15116. "Content-Length"))
  15117. != NULL) {
  15118. /* Request has content length set */
  15119. char *endptr = NULL;
  15120. conn->content_len = strtoll(cl, &endptr, 10);
  15121. if ((endptr == cl) || (conn->content_len < 0)) {
  15122. mg_snprintf(conn,
  15123. NULL, /* No truncation check for ebuf */
  15124. ebuf,
  15125. ebuf_len,
  15126. "%s",
  15127. "Bad request");
  15128. *err = 411;
  15129. return 0;
  15130. }
  15131. /* Publish the content length back to the request info. */
  15132. conn->request_info.content_length = conn->content_len;
  15133. } else {
  15134. /* There is no exception, see RFC7230. */
  15135. conn->content_len = 0;
  15136. }
  15137. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15138. return 1;
  15139. }
  15140. /* conn is assumed to be valid in this internal function */
  15141. static int
  15142. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15143. {
  15144. const char *cl;
  15145. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15146. return 0;
  15147. }
  15148. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15149. <= 0) {
  15150. mg_snprintf(conn,
  15151. NULL, /* No truncation check for ebuf */
  15152. ebuf,
  15153. ebuf_len,
  15154. "%s",
  15155. "Bad response");
  15156. *err = 400;
  15157. return 0;
  15158. }
  15159. /* Message is a valid response */
  15160. if (((cl = get_header(conn->response_info.http_headers,
  15161. conn->response_info.num_headers,
  15162. "Transfer-Encoding"))
  15163. != NULL)
  15164. && mg_strcasecmp(cl, "identity")) {
  15165. if (mg_strcasecmp(cl, "chunked")) {
  15166. mg_snprintf(conn,
  15167. NULL, /* No truncation check for ebuf */
  15168. ebuf,
  15169. ebuf_len,
  15170. "%s",
  15171. "Bad request");
  15172. *err = 400;
  15173. return 0;
  15174. }
  15175. conn->is_chunked = 1;
  15176. conn->content_len = 0; /* not yet read */
  15177. } else if ((cl = get_header(conn->response_info.http_headers,
  15178. conn->response_info.num_headers,
  15179. "Content-Length"))
  15180. != NULL) {
  15181. char *endptr = NULL;
  15182. conn->content_len = strtoll(cl, &endptr, 10);
  15183. if ((endptr == cl) || (conn->content_len < 0)) {
  15184. mg_snprintf(conn,
  15185. NULL, /* No truncation check for ebuf */
  15186. ebuf,
  15187. ebuf_len,
  15188. "%s",
  15189. "Bad request");
  15190. *err = 411;
  15191. return 0;
  15192. }
  15193. /* Publish the content length back to the response info. */
  15194. conn->response_info.content_length = conn->content_len;
  15195. /* TODO: check if it is still used in response_info */
  15196. conn->request_info.content_length = conn->content_len;
  15197. /* TODO: we should also consider HEAD method */
  15198. if (conn->response_info.status_code == 304) {
  15199. conn->content_len = 0;
  15200. }
  15201. } else {
  15202. /* TODO: we should also consider HEAD method */
  15203. if (((conn->response_info.status_code >= 100)
  15204. && (conn->response_info.status_code <= 199))
  15205. || (conn->response_info.status_code == 204)
  15206. || (conn->response_info.status_code == 304)) {
  15207. conn->content_len = 0;
  15208. } else {
  15209. conn->content_len = -1; /* unknown content length */
  15210. }
  15211. }
  15212. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15213. return 1;
  15214. }
  15215. int
  15216. mg_get_response(struct mg_connection *conn,
  15217. char *ebuf,
  15218. size_t ebuf_len,
  15219. int timeout)
  15220. {
  15221. int err, ret;
  15222. char txt[32]; /* will not overflow */
  15223. char *save_timeout;
  15224. char *new_timeout;
  15225. if (ebuf_len > 0) {
  15226. ebuf[0] = '\0';
  15227. }
  15228. if (!conn) {
  15229. mg_snprintf(conn,
  15230. NULL, /* No truncation check for ebuf */
  15231. ebuf,
  15232. ebuf_len,
  15233. "%s",
  15234. "Parameter error");
  15235. return -1;
  15236. }
  15237. /* Reset the previous responses */
  15238. conn->data_len = 0;
  15239. /* Implementation of API function for HTTP clients */
  15240. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15241. if (timeout >= 0) {
  15242. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15243. new_timeout = txt;
  15244. } else {
  15245. new_timeout = NULL;
  15246. }
  15247. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15248. ret = get_response(conn, ebuf, ebuf_len, &err);
  15249. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15250. #if defined(MG_LEGACY_INTERFACE)
  15251. /* TODO: 1) uri is deprecated;
  15252. * 2) here, ri.uri is the http response code */
  15253. conn->request_info.uri = conn->request_info.request_uri;
  15254. #endif
  15255. conn->request_info.local_uri = conn->request_info.request_uri;
  15256. /* TODO (mid): Define proper return values - maybe return length?
  15257. * For the first test use <0 for error and >0 for OK */
  15258. return (ret == 0) ? -1 : +1;
  15259. }
  15260. struct mg_connection *
  15261. mg_download(const char *host,
  15262. int port,
  15263. int use_ssl,
  15264. char *ebuf,
  15265. size_t ebuf_len,
  15266. const char *fmt,
  15267. ...)
  15268. {
  15269. struct mg_connection *conn;
  15270. va_list ap;
  15271. int i;
  15272. int reqerr;
  15273. if (ebuf_len > 0) {
  15274. ebuf[0] = '\0';
  15275. }
  15276. va_start(ap, fmt);
  15277. /* open a connection */
  15278. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15279. if (conn != NULL) {
  15280. i = mg_vprintf(conn, fmt, ap);
  15281. if (i <= 0) {
  15282. mg_snprintf(conn,
  15283. NULL, /* No truncation check for ebuf */
  15284. ebuf,
  15285. ebuf_len,
  15286. "%s",
  15287. "Error sending request");
  15288. } else {
  15289. /* make sure the buffer is clear */
  15290. conn->data_len = 0;
  15291. get_response(conn, ebuf, ebuf_len, &reqerr);
  15292. #if defined(MG_LEGACY_INTERFACE)
  15293. /* TODO: 1) uri is deprecated;
  15294. * 2) here, ri.uri is the http response code */
  15295. conn->request_info.uri = conn->request_info.request_uri;
  15296. #endif
  15297. conn->request_info.local_uri = conn->request_info.request_uri;
  15298. }
  15299. }
  15300. /* if an error occurred, close the connection */
  15301. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15302. mg_close_connection(conn);
  15303. conn = NULL;
  15304. }
  15305. va_end(ap);
  15306. return conn;
  15307. }
  15308. struct websocket_client_thread_data {
  15309. struct mg_connection *conn;
  15310. mg_websocket_data_handler data_handler;
  15311. mg_websocket_close_handler close_handler;
  15312. void *callback_data;
  15313. };
  15314. #if defined(USE_WEBSOCKET)
  15315. #if defined(_WIN32)
  15316. static unsigned __stdcall websocket_client_thread(void *data)
  15317. #else
  15318. static void *
  15319. websocket_client_thread(void *data)
  15320. #endif
  15321. {
  15322. struct websocket_client_thread_data *cdata =
  15323. (struct websocket_client_thread_data *)data;
  15324. void *user_thread_ptr = NULL;
  15325. #if !defined(_WIN32)
  15326. struct sigaction sa;
  15327. /* Ignore SIGPIPE */
  15328. memset(&sa, 0, sizeof(sa));
  15329. sa.sa_handler = SIG_IGN;
  15330. sigaction(SIGPIPE, &sa, NULL);
  15331. #endif
  15332. mg_set_thread_name("ws-clnt");
  15333. if (cdata->conn->phys_ctx) {
  15334. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15335. /* 3 indicates a websocket client thread */
  15336. /* TODO: check if conn->phys_ctx can be set */
  15337. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15338. cdata->conn->phys_ctx, 3);
  15339. }
  15340. }
  15341. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15342. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15343. if (cdata->close_handler != NULL) {
  15344. cdata->close_handler(cdata->conn, cdata->callback_data);
  15345. }
  15346. /* The websocket_client context has only this thread. If it runs out,
  15347. set the stop_flag to 2 (= "stopped"). */
  15348. cdata->conn->phys_ctx->stop_flag = 2;
  15349. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15350. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15351. 3,
  15352. user_thread_ptr);
  15353. }
  15354. mg_free((void *)cdata);
  15355. #if defined(_WIN32)
  15356. return 0;
  15357. #else
  15358. return NULL;
  15359. #endif
  15360. }
  15361. #endif
  15362. struct mg_connection *
  15363. mg_connect_websocket_client(const char *host,
  15364. int port,
  15365. int use_ssl,
  15366. char *error_buffer,
  15367. size_t error_buffer_size,
  15368. const char *path,
  15369. const char *origin,
  15370. mg_websocket_data_handler data_func,
  15371. mg_websocket_close_handler close_func,
  15372. void *user_data)
  15373. {
  15374. struct mg_connection *conn = NULL;
  15375. #if defined(USE_WEBSOCKET)
  15376. struct websocket_client_thread_data *thread_data;
  15377. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15378. static const char *handshake_req;
  15379. if (origin != NULL) {
  15380. handshake_req = "GET %s HTTP/1.1\r\n"
  15381. "Host: %s\r\n"
  15382. "Upgrade: websocket\r\n"
  15383. "Connection: Upgrade\r\n"
  15384. "Sec-WebSocket-Key: %s\r\n"
  15385. "Sec-WebSocket-Version: 13\r\n"
  15386. "Origin: %s\r\n"
  15387. "\r\n";
  15388. } else {
  15389. handshake_req = "GET %s HTTP/1.1\r\n"
  15390. "Host: %s\r\n"
  15391. "Upgrade: websocket\r\n"
  15392. "Connection: Upgrade\r\n"
  15393. "Sec-WebSocket-Key: %s\r\n"
  15394. "Sec-WebSocket-Version: 13\r\n"
  15395. "\r\n";
  15396. }
  15397. #if defined(__clang__)
  15398. #pragma clang diagnostic push
  15399. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15400. #endif
  15401. /* Establish the client connection and request upgrade */
  15402. conn = mg_download(host,
  15403. port,
  15404. use_ssl,
  15405. error_buffer,
  15406. error_buffer_size,
  15407. handshake_req,
  15408. path,
  15409. host,
  15410. magic,
  15411. origin);
  15412. #if defined(__clang__)
  15413. #pragma clang diagnostic pop
  15414. #endif
  15415. /* Connection object will be null if something goes wrong */
  15416. if (conn == NULL) {
  15417. if (!*error_buffer) {
  15418. /* There should be already an error message */
  15419. mg_snprintf(conn,
  15420. NULL, /* No truncation check for ebuf */
  15421. error_buffer,
  15422. error_buffer_size,
  15423. "Unexpected error");
  15424. }
  15425. return NULL;
  15426. }
  15427. if (conn->response_info.status_code != 101) {
  15428. /* We sent an "upgrade" request. For a correct websocket
  15429. * protocol handshake, we expect a "101 Continue" response.
  15430. * Otherwise it is a protocol violation. Maybe the HTTP
  15431. * Server does not know websockets. */
  15432. if (!*error_buffer) {
  15433. /* set an error, if not yet set */
  15434. mg_snprintf(conn,
  15435. NULL, /* No truncation check for ebuf */
  15436. error_buffer,
  15437. error_buffer_size,
  15438. "Unexpected server reply");
  15439. }
  15440. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15441. mg_close_connection(conn);
  15442. return NULL;
  15443. }
  15444. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15445. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15446. if (!thread_data) {
  15447. DEBUG_TRACE("%s\r\n", "Out of memory");
  15448. mg_close_connection(conn);
  15449. return NULL;
  15450. }
  15451. thread_data->conn = conn;
  15452. thread_data->data_handler = data_func;
  15453. thread_data->close_handler = close_func;
  15454. thread_data->callback_data = user_data;
  15455. conn->phys_ctx->worker_threadids =
  15456. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15457. if (!conn->phys_ctx->worker_threadids) {
  15458. DEBUG_TRACE("%s\r\n", "Out of memory");
  15459. mg_free(thread_data);
  15460. mg_close_connection(conn);
  15461. return NULL;
  15462. }
  15463. /* Now upgrade to ws/wss client context */
  15464. conn->phys_ctx->user_data = user_data;
  15465. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15466. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15467. /* Start a thread to read the websocket client connection
  15468. * This thread will automatically stop when mg_disconnect is
  15469. * called on the client connection */
  15470. if (mg_start_thread_with_id(websocket_client_thread,
  15471. thread_data,
  15472. conn->phys_ctx->worker_threadids)
  15473. != 0) {
  15474. conn->phys_ctx->cfg_worker_threads = 0;
  15475. mg_free(thread_data);
  15476. mg_close_connection(conn);
  15477. conn = NULL;
  15478. DEBUG_TRACE("%s",
  15479. "Websocket client connect thread could not be started\r\n");
  15480. }
  15481. #else
  15482. /* Appease "unused parameter" warnings */
  15483. (void)host;
  15484. (void)port;
  15485. (void)use_ssl;
  15486. (void)error_buffer;
  15487. (void)error_buffer_size;
  15488. (void)path;
  15489. (void)origin;
  15490. (void)user_data;
  15491. (void)data_func;
  15492. (void)close_func;
  15493. #endif
  15494. return conn;
  15495. }
  15496. /* Prepare connection data structure */
  15497. static void
  15498. init_connection(struct mg_connection *conn)
  15499. {
  15500. /* Is keep alive allowed by the server */
  15501. int keep_alive_enabled =
  15502. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15503. if (!keep_alive_enabled) {
  15504. conn->must_close = 1;
  15505. }
  15506. /* Important: on new connection, reset the receiving buffer. Credit
  15507. * goes to crule42. */
  15508. conn->data_len = 0;
  15509. conn->handled_requests = 0;
  15510. mg_set_user_connection_data(conn, NULL);
  15511. #if defined(USE_SERVER_STATS)
  15512. conn->conn_state = 2; /* init */
  15513. #endif
  15514. /* call the init_connection callback if assigned */
  15515. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15516. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15517. void *conn_data = NULL;
  15518. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15519. mg_set_user_connection_data(conn, conn_data);
  15520. }
  15521. }
  15522. }
  15523. /* Process a connection - may handle multiple requests
  15524. * using the same connection.
  15525. * Must be called with a valid connection (conn and
  15526. * conn->phys_ctx must be valid).
  15527. */
  15528. static void
  15529. process_new_connection(struct mg_connection *conn)
  15530. {
  15531. struct mg_request_info *ri = &conn->request_info;
  15532. int keep_alive, discard_len;
  15533. char ebuf[100];
  15534. const char *hostend;
  15535. int reqerr, uri_type;
  15536. #if defined(USE_SERVER_STATS)
  15537. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15538. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15539. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15540. /* could use atomic compare exchange, but this
  15541. * seems overkill for statistics data */
  15542. conn->phys_ctx->max_active_connections = mcon;
  15543. }
  15544. #endif
  15545. init_connection(conn);
  15546. DEBUG_TRACE("Start processing connection from %s",
  15547. conn->request_info.remote_addr);
  15548. /* Loop over multiple requests sent using the same connection
  15549. * (while "keep alive"). */
  15550. do {
  15551. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15552. conn->handled_requests + 1);
  15553. #if defined(USE_SERVER_STATS)
  15554. conn->conn_state = 3; /* ready */
  15555. #endif
  15556. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15557. /* The request sent by the client could not be understood by
  15558. * the server, or it was incomplete or a timeout. Send an
  15559. * error message and close the connection. */
  15560. if (reqerr > 0) {
  15561. DEBUG_ASSERT(ebuf[0] != '\0');
  15562. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15563. }
  15564. } else if (strcmp(ri->http_version, "1.0")
  15565. && strcmp(ri->http_version, "1.1")) {
  15566. mg_snprintf(conn,
  15567. NULL, /* No truncation check for ebuf */
  15568. ebuf,
  15569. sizeof(ebuf),
  15570. "Bad HTTP version: [%s]",
  15571. ri->http_version);
  15572. mg_send_http_error(conn, 505, "%s", ebuf);
  15573. }
  15574. if (ebuf[0] == '\0') {
  15575. uri_type = get_uri_type(conn->request_info.request_uri);
  15576. switch (uri_type) {
  15577. case 1:
  15578. /* Asterisk */
  15579. conn->request_info.local_uri = NULL;
  15580. break;
  15581. case 2:
  15582. /* relative uri */
  15583. conn->request_info.local_uri = conn->request_info.request_uri;
  15584. break;
  15585. case 3:
  15586. case 4:
  15587. /* absolute uri (with/without port) */
  15588. hostend = get_rel_url_at_current_server(
  15589. conn->request_info.request_uri, conn);
  15590. if (hostend) {
  15591. conn->request_info.local_uri = hostend;
  15592. } else {
  15593. conn->request_info.local_uri = NULL;
  15594. }
  15595. break;
  15596. default:
  15597. mg_snprintf(conn,
  15598. NULL, /* No truncation check for ebuf */
  15599. ebuf,
  15600. sizeof(ebuf),
  15601. "Invalid URI");
  15602. mg_send_http_error(conn, 400, "%s", ebuf);
  15603. conn->request_info.local_uri = NULL;
  15604. break;
  15605. }
  15606. #if defined(MG_LEGACY_INTERFACE)
  15607. /* Legacy before split into local_uri and request_uri */
  15608. conn->request_info.uri = conn->request_info.local_uri;
  15609. #endif
  15610. }
  15611. DEBUG_TRACE("http: %s, error: %s",
  15612. (ri->http_version ? ri->http_version : "none"),
  15613. (ebuf[0] ? ebuf : "none"));
  15614. if (ebuf[0] == '\0') {
  15615. if (conn->request_info.local_uri) {
  15616. /* handle request to local server */
  15617. #if defined(USE_SERVER_STATS)
  15618. conn->conn_state = 4; /* processing */
  15619. #endif
  15620. handle_request(conn);
  15621. #if defined(USE_SERVER_STATS)
  15622. conn->conn_state = 5; /* processed */
  15623. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15624. conn->consumed_content);
  15625. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15626. conn->num_bytes_sent);
  15627. #endif
  15628. DEBUG_TRACE("%s", "handle_request done");
  15629. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15630. conn->phys_ctx->callbacks.end_request(conn,
  15631. conn->status_code);
  15632. DEBUG_TRACE("%s", "end_request callback done");
  15633. }
  15634. log_access(conn);
  15635. } else {
  15636. /* TODO: handle non-local request (PROXY) */
  15637. conn->must_close = 1;
  15638. }
  15639. } else {
  15640. conn->must_close = 1;
  15641. }
  15642. if (ri->remote_user != NULL) {
  15643. mg_free((void *)ri->remote_user);
  15644. /* Important! When having connections with and without auth
  15645. * would cause double free and then crash */
  15646. ri->remote_user = NULL;
  15647. }
  15648. /* NOTE(lsm): order is important here. should_keep_alive() call
  15649. * is using parsed request, which will be invalid after
  15650. * memmove's below.
  15651. * Therefore, memorize should_keep_alive() result now for later
  15652. * use in loop exit condition. */
  15653. /* Enable it only if this request is completely discardable. */
  15654. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15655. && (conn->content_len >= 0) && (conn->request_len > 0)
  15656. && ((conn->is_chunked == 4)
  15657. || (!conn->is_chunked
  15658. && ((conn->consumed_content == conn->content_len)
  15659. || ((conn->request_len + conn->content_len)
  15660. <= conn->data_len))));
  15661. if (keep_alive) {
  15662. /* Discard all buffered data for this request */
  15663. discard_len =
  15664. ((conn->request_len + conn->content_len) < conn->data_len)
  15665. ? (int)(conn->request_len + conn->content_len)
  15666. : conn->data_len;
  15667. conn->data_len -= discard_len;
  15668. if (conn->data_len > 0) {
  15669. DEBUG_TRACE("discard_len = %d", discard_len);
  15670. memmove(conn->buf,
  15671. conn->buf + discard_len,
  15672. (size_t)conn->data_len);
  15673. }
  15674. }
  15675. DEBUG_ASSERT(conn->data_len >= 0);
  15676. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15677. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15678. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15679. (long int)conn->data_len,
  15680. (long int)conn->buf_size);
  15681. break;
  15682. }
  15683. conn->handled_requests++;
  15684. } while (keep_alive);
  15685. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15686. conn->request_info.remote_addr,
  15687. difftime(time(NULL), conn->conn_birth_time));
  15688. close_connection(conn);
  15689. #if defined(USE_SERVER_STATS)
  15690. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15691. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15692. #endif
  15693. }
  15694. #if defined(ALTERNATIVE_QUEUE)
  15695. static void
  15696. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15697. {
  15698. unsigned int i;
  15699. while (!ctx->stop_flag) {
  15700. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15701. /* find a free worker slot and signal it */
  15702. if (ctx->client_socks[i].in_use == 2) {
  15703. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15704. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15705. ctx->client_socks[i] = *sp;
  15706. ctx->client_socks[i].in_use = 1;
  15707. /* socket has been moved to the consumer */
  15708. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15709. (void)event_signal(ctx->client_wait_events[i]);
  15710. return;
  15711. }
  15712. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15713. }
  15714. }
  15715. /* queue is full */
  15716. mg_sleep(1);
  15717. }
  15718. /* must consume */
  15719. set_blocking_mode(sp->sock);
  15720. closesocket(sp->sock);
  15721. }
  15722. static int
  15723. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15724. {
  15725. DEBUG_TRACE("%s", "going idle");
  15726. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15727. ctx->client_socks[thread_index].in_use = 2;
  15728. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15729. event_wait(ctx->client_wait_events[thread_index]);
  15730. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15731. *sp = ctx->client_socks[thread_index];
  15732. if (ctx->stop_flag) {
  15733. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15734. if (sp->in_use == 1) {
  15735. /* must consume */
  15736. set_blocking_mode(sp->sock);
  15737. closesocket(sp->sock);
  15738. }
  15739. return 0;
  15740. }
  15741. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15742. if (sp->in_use == 1) {
  15743. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15744. return 1;
  15745. }
  15746. /* must not reach here */
  15747. DEBUG_ASSERT(0);
  15748. return 0;
  15749. }
  15750. #else /* ALTERNATIVE_QUEUE */
  15751. /* Worker threads take accepted socket from the queue */
  15752. static int
  15753. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15754. {
  15755. (void)thread_index;
  15756. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15757. DEBUG_TRACE("%s", "going idle");
  15758. /* If the queue is empty, wait. We're idle at this point. */
  15759. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15760. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15761. }
  15762. /* If we're stopping, sq_head may be equal to sq_tail. */
  15763. if (ctx->sq_head > ctx->sq_tail) {
  15764. /* Copy socket from the queue and increment tail */
  15765. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  15766. ctx->sq_tail++;
  15767. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15768. /* Wrap pointers if needed */
  15769. while (ctx->sq_tail > ctx->sq_size) {
  15770. ctx->sq_tail -= ctx->sq_size;
  15771. ctx->sq_head -= ctx->sq_size;
  15772. }
  15773. }
  15774. (void)pthread_cond_signal(&ctx->sq_empty);
  15775. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15776. return !ctx->stop_flag;
  15777. }
  15778. /* Master thread adds accepted socket to a queue */
  15779. static void
  15780. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15781. {
  15782. int queue_filled;
  15783. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15784. queue_filled = ctx->sq_head - ctx->sq_tail;
  15785. /* If the queue is full, wait */
  15786. while ((ctx->stop_flag == 0) && (queue_filled >= ctx->sq_size)) {
  15787. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  15788. #if defined(USE_SERVER_STATS)
  15789. if (queue_filled > ctx->sq_max_fill) {
  15790. ctx->sq_max_fill = queue_filled;
  15791. }
  15792. #endif
  15793. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15794. ctx->sq_blocked = 0; /* Not blocked now */
  15795. queue_filled = ctx->sq_head - ctx->sq_tail;
  15796. }
  15797. if (queue_filled < ctx->sq_size) {
  15798. /* Copy socket to the queue and increment head */
  15799. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  15800. ctx->sq_head++;
  15801. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15802. }
  15803. queue_filled = ctx->sq_head - ctx->sq_tail;
  15804. #if defined(USE_SERVER_STATS)
  15805. if (queue_filled > ctx->sq_max_fill) {
  15806. ctx->sq_max_fill = queue_filled;
  15807. }
  15808. #endif
  15809. (void)pthread_cond_signal(&ctx->sq_full);
  15810. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15811. }
  15812. #endif /* ALTERNATIVE_QUEUE */
  15813. static void
  15814. worker_thread_run(struct mg_connection *conn)
  15815. {
  15816. struct mg_context *ctx = conn->phys_ctx;
  15817. int thread_index;
  15818. struct mg_workerTLS tls;
  15819. #if defined(MG_LEGACY_INTERFACE)
  15820. uint32_t addr;
  15821. #endif
  15822. mg_set_thread_name("worker");
  15823. tls.is_master = 0;
  15824. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15825. #if defined(_WIN32)
  15826. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15827. #endif
  15828. /* Initialize thread local storage before calling any callback */
  15829. pthread_setspecific(sTlsKey, &tls);
  15830. /* Check if there is a user callback */
  15831. if (ctx->callbacks.init_thread) {
  15832. /* call init_thread for a worker thread (type 1), and store the return
  15833. * value */
  15834. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15835. } else {
  15836. /* No callback: set user pointer to NULL */
  15837. tls.user_ptr = NULL;
  15838. }
  15839. /* Connection structure has been pre-allocated */
  15840. thread_index = (int)(conn - ctx->worker_connections);
  15841. if ((thread_index < 0)
  15842. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15843. mg_cry_ctx_internal(ctx,
  15844. "Internal error: Invalid worker index %i",
  15845. thread_index);
  15846. return;
  15847. }
  15848. /* Request buffers are not pre-allocated. They are private to the
  15849. * request and do not contain any state information that might be
  15850. * of interest to anyone observing a server status. */
  15851. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15852. if (conn->buf == NULL) {
  15853. mg_cry_ctx_internal(
  15854. ctx,
  15855. "Out of memory: Cannot allocate buffer for worker %i",
  15856. thread_index);
  15857. return;
  15858. }
  15859. conn->buf_size = (int)ctx->max_request_size;
  15860. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15861. conn->host = NULL; /* until we have more information. */
  15862. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15863. conn->request_info.user_data = ctx->user_data;
  15864. /* Allocate a mutex for this connection to allow communication both
  15865. * within the request handler and from elsewhere in the application
  15866. */
  15867. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15868. mg_free(conn->buf);
  15869. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15870. return;
  15871. }
  15872. #if defined(USE_SERVER_STATS)
  15873. conn->conn_state = 1; /* not consumed */
  15874. #endif
  15875. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15876. * signal sq_empty condvar to wake up the master waiting in
  15877. * produce_socket() */
  15878. while (consume_socket(ctx, &conn->client, thread_index)) {
  15879. #if defined(USE_SERVER_STATS)
  15880. conn->conn_close_time = 0;
  15881. #endif
  15882. conn->conn_birth_time = time(NULL);
  15883. /* Fill in IP, port info early so even if SSL setup below fails,
  15884. * error handler would have the corresponding info.
  15885. * Thanks to Johannes Winkelmann for the patch.
  15886. */
  15887. #if defined(USE_IPV6)
  15888. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15889. conn->request_info.remote_port =
  15890. ntohs(conn->client.rsa.sin6.sin6_port);
  15891. } else
  15892. #endif
  15893. {
  15894. conn->request_info.remote_port =
  15895. ntohs(conn->client.rsa.sin.sin_port);
  15896. }
  15897. sockaddr_to_string(conn->request_info.remote_addr,
  15898. sizeof(conn->request_info.remote_addr),
  15899. &conn->client.rsa);
  15900. DEBUG_TRACE("Start processing connection from %s",
  15901. conn->request_info.remote_addr);
  15902. conn->request_info.is_ssl = conn->client.is_ssl;
  15903. if (conn->client.is_ssl) {
  15904. #if !defined(NO_SSL)
  15905. /* HTTPS connection */
  15906. if (sslize(conn,
  15907. conn->dom_ctx->ssl_ctx,
  15908. SSL_accept,
  15909. &(conn->phys_ctx->stop_flag),
  15910. NULL)) {
  15911. /* conn->dom_ctx is set in get_request */
  15912. /* Get SSL client certificate information (if set) */
  15913. ssl_get_client_cert_info(conn);
  15914. /* process HTTPS connection */
  15915. process_new_connection(conn);
  15916. /* Free client certificate info */
  15917. if (conn->request_info.client_cert) {
  15918. mg_free((void *)(conn->request_info.client_cert->subject));
  15919. mg_free((void *)(conn->request_info.client_cert->issuer));
  15920. mg_free((void *)(conn->request_info.client_cert->serial));
  15921. mg_free((void *)(conn->request_info.client_cert->finger));
  15922. /* Free certificate memory */
  15923. X509_free(
  15924. (X509 *)conn->request_info.client_cert->peer_cert);
  15925. conn->request_info.client_cert->peer_cert = 0;
  15926. conn->request_info.client_cert->subject = 0;
  15927. conn->request_info.client_cert->issuer = 0;
  15928. conn->request_info.client_cert->serial = 0;
  15929. conn->request_info.client_cert->finger = 0;
  15930. mg_free(conn->request_info.client_cert);
  15931. conn->request_info.client_cert = 0;
  15932. }
  15933. } else {
  15934. /* make sure the connection is cleaned up on SSL failure */
  15935. close_connection(conn);
  15936. }
  15937. #endif
  15938. } else {
  15939. /* process HTTP connection */
  15940. process_new_connection(conn);
  15941. }
  15942. DEBUG_TRACE("%s", "Connection closed");
  15943. #if defined(USE_SERVER_STATS)
  15944. conn->conn_close_time = time(NULL);
  15945. #endif
  15946. }
  15947. /* Call exit thread user callback */
  15948. if (ctx->callbacks.exit_thread) {
  15949. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15950. }
  15951. /* delete thread local storage objects */
  15952. pthread_setspecific(sTlsKey, NULL);
  15953. #if defined(_WIN32)
  15954. CloseHandle(tls.pthread_cond_helper_mutex);
  15955. #endif
  15956. pthread_mutex_destroy(&conn->mutex);
  15957. /* Free the request buffer. */
  15958. conn->buf_size = 0;
  15959. mg_free(conn->buf);
  15960. conn->buf = NULL;
  15961. #if defined(USE_SERVER_STATS)
  15962. conn->conn_state = 9; /* done */
  15963. #endif
  15964. DEBUG_TRACE("%s", "exiting");
  15965. }
  15966. /* Threads have different return types on Windows and Unix. */
  15967. #if defined(_WIN32)
  15968. static unsigned __stdcall worker_thread(void *thread_func_param)
  15969. {
  15970. worker_thread_run((struct mg_connection *)thread_func_param);
  15971. return 0;
  15972. }
  15973. #else
  15974. static void *
  15975. worker_thread(void *thread_func_param)
  15976. {
  15977. #if !defined(__ZEPHYR__)
  15978. struct sigaction sa;
  15979. /* Ignore SIGPIPE */
  15980. memset(&sa, 0, sizeof(sa));
  15981. sa.sa_handler = SIG_IGN;
  15982. sigaction(SIGPIPE, &sa, NULL);
  15983. #endif
  15984. worker_thread_run((struct mg_connection *)thread_func_param);
  15985. return NULL;
  15986. }
  15987. #endif /* _WIN32 */
  15988. /* This is an internal function, thus all arguments are expected to be
  15989. * valid - a NULL check is not required. */
  15990. static void
  15991. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15992. {
  15993. struct socket so;
  15994. char src_addr[IP_ADDR_STR_LEN];
  15995. socklen_t len = sizeof(so.rsa);
  15996. #if !defined(__ZEPHYR__)
  15997. int on = 1;
  15998. #endif
  15999. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16000. == INVALID_SOCKET) {
  16001. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16002. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16003. mg_cry_ctx_internal(ctx,
  16004. "%s: %s is not allowed to connect",
  16005. __func__,
  16006. src_addr);
  16007. closesocket(so.sock);
  16008. } else {
  16009. /* Put so socket structure into the queue */
  16010. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16011. set_close_on_exec(so.sock, NULL, ctx);
  16012. so.is_ssl = listener->is_ssl;
  16013. so.ssl_redir = listener->ssl_redir;
  16014. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16015. mg_cry_ctx_internal(ctx,
  16016. "%s: getsockname() failed: %s",
  16017. __func__,
  16018. strerror(ERRNO));
  16019. }
  16020. #if !defined(__ZEPHYR__)
  16021. /* Set TCP keep-alive. This is needed because if HTTP-level
  16022. * keep-alive
  16023. * is enabled, and client resets the connection, server won't get
  16024. * TCP FIN or RST and will keep the connection open forever. With
  16025. * TCP keep-alive, next keep-alive handshake will figure out that
  16026. * the client is down and will close the server end.
  16027. * Thanks to Igor Klopov who suggested the patch. */
  16028. if (setsockopt(so.sock,
  16029. SOL_SOCKET,
  16030. SO_KEEPALIVE,
  16031. (SOCK_OPT_TYPE)&on,
  16032. sizeof(on))
  16033. != 0) {
  16034. mg_cry_ctx_internal(
  16035. ctx,
  16036. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16037. __func__,
  16038. strerror(ERRNO));
  16039. }
  16040. #endif
  16041. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16042. * to effectively fill up the underlying IP packet payload and
  16043. * reduce the overhead of sending lots of small buffers. However
  16044. * this hurts the server's throughput (ie. operations per second)
  16045. * when HTTP 1.1 persistent connections are used and the responses
  16046. * are relatively small (eg. less than 1400 bytes).
  16047. */
  16048. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16049. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16050. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16051. mg_cry_ctx_internal(
  16052. ctx,
  16053. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16054. __func__,
  16055. strerror(ERRNO));
  16056. }
  16057. }
  16058. /* The "non blocking" property should already be
  16059. * inherited from the parent socket. Set it for
  16060. * non-compliant socket implementations. */
  16061. set_non_blocking_mode(so.sock);
  16062. so.in_use = 0;
  16063. produce_socket(ctx, &so);
  16064. }
  16065. }
  16066. static void
  16067. master_thread_run(struct mg_context *ctx)
  16068. {
  16069. struct mg_workerTLS tls;
  16070. struct mg_pollfd *pfd;
  16071. unsigned int i;
  16072. unsigned int workerthreadcount;
  16073. if (!ctx) {
  16074. return;
  16075. }
  16076. mg_set_thread_name("master");
  16077. /* Increase priority of the master thread */
  16078. #if defined(_WIN32)
  16079. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16080. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16081. int min_prio = sched_get_priority_min(SCHED_RR);
  16082. int max_prio = sched_get_priority_max(SCHED_RR);
  16083. if ((min_prio >= 0) && (max_prio >= 0)
  16084. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16085. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16086. struct sched_param sched_param = {0};
  16087. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16088. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16089. }
  16090. #endif
  16091. /* Initialize thread local storage */
  16092. #if defined(_WIN32)
  16093. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16094. #endif
  16095. tls.is_master = 1;
  16096. pthread_setspecific(sTlsKey, &tls);
  16097. if (ctx->callbacks.init_thread) {
  16098. /* Callback for the master thread (type 0) */
  16099. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16100. } else {
  16101. tls.user_ptr = NULL;
  16102. }
  16103. /* Server starts *now* */
  16104. ctx->start_time = time(NULL);
  16105. /* Start the server */
  16106. pfd = ctx->listening_socket_fds;
  16107. while (ctx->stop_flag == 0) {
  16108. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16109. pfd[i].fd = ctx->listening_sockets[i].sock;
  16110. pfd[i].events = POLLIN;
  16111. }
  16112. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16113. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16114. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16115. * successful poll, and POLLIN is defined as
  16116. * (POLLRDNORM | POLLRDBAND)
  16117. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16118. * pfd[i].revents == POLLIN. */
  16119. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  16120. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16121. }
  16122. }
  16123. }
  16124. }
  16125. /* Here stop_flag is 1 - Initiate shutdown. */
  16126. DEBUG_TRACE("%s", "stopping workers");
  16127. /* Stop signal received: somebody called mg_stop. Quit. */
  16128. close_all_listening_sockets(ctx);
  16129. /* Wakeup workers that are waiting for connections to handle. */
  16130. #if defined(ALTERNATIVE_QUEUE)
  16131. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16132. event_signal(ctx->client_wait_events[i]);
  16133. }
  16134. #else
  16135. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16136. pthread_cond_broadcast(&ctx->sq_full);
  16137. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16138. #endif
  16139. /* Join all worker threads to avoid leaking threads. */
  16140. workerthreadcount = ctx->cfg_worker_threads;
  16141. for (i = 0; i < workerthreadcount; i++) {
  16142. if (ctx->worker_threadids[i] != 0) {
  16143. mg_join_thread(ctx->worker_threadids[i]);
  16144. }
  16145. }
  16146. #if defined(USE_LUA)
  16147. /* Free Lua state of lua background task */
  16148. if (ctx->lua_background_state) {
  16149. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16150. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16151. if (lua_istable(lstate, -1)) {
  16152. reg_boolean(lstate, "shutdown", 1);
  16153. lua_pop(lstate, 1);
  16154. mg_sleep(2);
  16155. }
  16156. lua_close(lstate);
  16157. ctx->lua_background_state = 0;
  16158. }
  16159. #endif
  16160. DEBUG_TRACE("%s", "exiting");
  16161. /* call exit thread callback */
  16162. if (ctx->callbacks.exit_thread) {
  16163. /* Callback for the master thread (type 0) */
  16164. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16165. }
  16166. #if defined(_WIN32)
  16167. CloseHandle(tls.pthread_cond_helper_mutex);
  16168. #endif
  16169. pthread_setspecific(sTlsKey, NULL);
  16170. /* Signal mg_stop() that we're done.
  16171. * WARNING: This must be the very last thing this
  16172. * thread does, as ctx becomes invalid after this line. */
  16173. ctx->stop_flag = 2;
  16174. }
  16175. /* Threads have different return types on Windows and Unix. */
  16176. #if defined(_WIN32)
  16177. static unsigned __stdcall master_thread(void *thread_func_param)
  16178. {
  16179. master_thread_run((struct mg_context *)thread_func_param);
  16180. return 0;
  16181. }
  16182. #else
  16183. static void *
  16184. master_thread(void *thread_func_param)
  16185. {
  16186. #if !defined(__ZEPHYR__)
  16187. struct sigaction sa;
  16188. /* Ignore SIGPIPE */
  16189. memset(&sa, 0, sizeof(sa));
  16190. sa.sa_handler = SIG_IGN;
  16191. sigaction(SIGPIPE, &sa, NULL);
  16192. #endif
  16193. master_thread_run((struct mg_context *)thread_func_param);
  16194. return NULL;
  16195. }
  16196. #endif /* _WIN32 */
  16197. static void
  16198. free_context(struct mg_context *ctx)
  16199. {
  16200. int i;
  16201. struct mg_handler_info *tmp_rh;
  16202. if (ctx == NULL) {
  16203. return;
  16204. }
  16205. if (ctx->callbacks.exit_context) {
  16206. ctx->callbacks.exit_context(ctx);
  16207. }
  16208. /* All threads exited, no sync is needed. Destroy thread mutex and
  16209. * condvars
  16210. */
  16211. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16212. #if defined(ALTERNATIVE_QUEUE)
  16213. mg_free(ctx->client_socks);
  16214. if (ctx->client_wait_events != NULL) {
  16215. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16216. event_destroy(ctx->client_wait_events[i]);
  16217. }
  16218. mg_free(ctx->client_wait_events);
  16219. }
  16220. #else
  16221. (void)pthread_cond_destroy(&ctx->sq_empty);
  16222. (void)pthread_cond_destroy(&ctx->sq_full);
  16223. mg_free(ctx->squeue);
  16224. #endif
  16225. /* Destroy other context global data structures mutex */
  16226. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16227. #if defined(USE_TIMERS)
  16228. timers_exit(ctx);
  16229. #endif
  16230. /* Deallocate config parameters */
  16231. for (i = 0; i < NUM_OPTIONS; i++) {
  16232. if (ctx->dd.config[i] != NULL) {
  16233. #if defined(_MSC_VER)
  16234. #pragma warning(suppress : 6001)
  16235. #endif
  16236. mg_free(ctx->dd.config[i]);
  16237. }
  16238. }
  16239. /* Deallocate request handlers */
  16240. while (ctx->dd.handlers) {
  16241. tmp_rh = ctx->dd.handlers;
  16242. ctx->dd.handlers = tmp_rh->next;
  16243. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  16244. pthread_cond_destroy(&tmp_rh->refcount_cond);
  16245. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  16246. }
  16247. mg_free(tmp_rh->uri);
  16248. mg_free(tmp_rh);
  16249. }
  16250. #if !defined(NO_SSL)
  16251. /* Deallocate SSL context */
  16252. if (ctx->dd.ssl_ctx != NULL) {
  16253. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16254. int callback_ret =
  16255. (ctx->callbacks.external_ssl_ctx == NULL)
  16256. ? 0
  16257. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16258. if (callback_ret == 0) {
  16259. SSL_CTX_free(ctx->dd.ssl_ctx);
  16260. }
  16261. /* else: ignore error and ommit SSL_CTX_free in case
  16262. * callback_ret is 1 */
  16263. }
  16264. #endif /* !NO_SSL */
  16265. /* Deallocate worker thread ID array */
  16266. mg_free(ctx->worker_threadids);
  16267. /* Deallocate worker thread ID array */
  16268. mg_free(ctx->worker_connections);
  16269. /* deallocate system name string */
  16270. mg_free(ctx->systemName);
  16271. /* Deallocate context itself */
  16272. mg_free(ctx);
  16273. }
  16274. void
  16275. mg_stop(struct mg_context *ctx)
  16276. {
  16277. pthread_t mt;
  16278. if (!ctx) {
  16279. return;
  16280. }
  16281. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16282. * two threads is not allowed. */
  16283. mt = ctx->masterthreadid;
  16284. if (mt == 0) {
  16285. return;
  16286. }
  16287. ctx->masterthreadid = 0;
  16288. /* Set stop flag, so all threads know they have to exit. */
  16289. ctx->stop_flag = 1;
  16290. /* Wait until everything has stopped. */
  16291. while (ctx->stop_flag != 2) {
  16292. (void)mg_sleep(10);
  16293. }
  16294. mg_join_thread(mt);
  16295. free_context(ctx);
  16296. #if defined(_WIN32)
  16297. (void)WSACleanup();
  16298. #endif /* _WIN32 */
  16299. }
  16300. static void
  16301. get_system_name(char **sysName)
  16302. {
  16303. #if defined(_WIN32)
  16304. #if defined(_WIN32_WCE)
  16305. *sysName = mg_strdup("WinCE");
  16306. #else
  16307. char name[128];
  16308. DWORD dwVersion = 0;
  16309. DWORD dwMajorVersion = 0;
  16310. DWORD dwMinorVersion = 0;
  16311. DWORD dwBuild = 0;
  16312. BOOL wowRet, isWoW = FALSE;
  16313. #if defined(_MSC_VER)
  16314. #pragma warning(push)
  16315. /* GetVersion was declared deprecated */
  16316. #pragma warning(disable : 4996)
  16317. #endif
  16318. dwVersion = GetVersion();
  16319. #if defined(_MSC_VER)
  16320. #pragma warning(pop)
  16321. #endif
  16322. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16323. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16324. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16325. (void)dwBuild;
  16326. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16327. sprintf(name,
  16328. "Windows %u.%u%s",
  16329. (unsigned)dwMajorVersion,
  16330. (unsigned)dwMinorVersion,
  16331. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16332. *sysName = mg_strdup(name);
  16333. #endif
  16334. #elif defined(__ZEPHYR__)
  16335. *sysName = mg_strdup("Zephyr OS");
  16336. #else
  16337. struct utsname name;
  16338. memset(&name, 0, sizeof(name));
  16339. uname(&name);
  16340. *sysName = mg_strdup(name.sysname);
  16341. #endif
  16342. }
  16343. static void
  16344. legacy_init(const char **options)
  16345. {
  16346. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16347. if (options) {
  16348. const char **run_options = options;
  16349. const char *optname = config_options[LISTENING_PORTS].name;
  16350. /* Try to find the "listening_ports" option */
  16351. while (*run_options) {
  16352. if (!strcmp(*run_options, optname)) {
  16353. ports_option = run_options[1];
  16354. }
  16355. run_options += 2;
  16356. }
  16357. }
  16358. if (is_ssl_port_used(ports_option)) {
  16359. /* Initialize with SSL support */
  16360. mg_init_library(MG_FEATURES_TLS);
  16361. } else {
  16362. /* Initialize without SSL support */
  16363. mg_init_library(MG_FEATURES_DEFAULT);
  16364. }
  16365. }
  16366. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16367. static
  16368. #endif
  16369. struct mg_context *
  16370. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16371. {
  16372. struct mg_context *ctx;
  16373. const char *name, *value, *default_value;
  16374. int idx, ok, workerthreadcount;
  16375. unsigned int i;
  16376. int itmp;
  16377. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16378. const char **options =
  16379. ((init != NULL) ? (init->configuration_options) : (NULL));
  16380. struct mg_workerTLS tls;
  16381. #if defined(_WIN32)
  16382. WSADATA data;
  16383. WSAStartup(MAKEWORD(2, 2), &data);
  16384. #endif /* _WIN32 */
  16385. if (error != NULL) {
  16386. error->code = 0;
  16387. if (error->text_buffer_size > 0) {
  16388. *error->text = 0;
  16389. }
  16390. }
  16391. if (mg_init_library_called == 0) {
  16392. /* Legacy INIT, if mg_start is called without mg_init_library.
  16393. * Note: This will cause a memory leak when unloading the library. */
  16394. legacy_init(options);
  16395. }
  16396. /* Allocate context and initialize reasonable general case defaults. */
  16397. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16398. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16399. mg_snprintf(NULL,
  16400. NULL, /* No truncation check for error buffers */
  16401. error->text,
  16402. error->text_buffer_size,
  16403. "%s",
  16404. "Out of memory");
  16405. }
  16406. return NULL;
  16407. }
  16408. /* Random number generator will initialize at the first call */
  16409. ctx->dd.auth_nonce_mask =
  16410. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16411. /* Save started thread index to reuse in other external API calls
  16412. * For the sake of thread synchronization all non-civetweb threads
  16413. * can be considered as single external thread */
  16414. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16415. tls.is_master = -1; /* Thread calling mg_start */
  16416. tls.thread_idx = ctx->starter_thread_idx;
  16417. #if defined(_WIN32)
  16418. tls.pthread_cond_helper_mutex = NULL;
  16419. #endif
  16420. pthread_setspecific(sTlsKey, &tls);
  16421. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16422. #if !defined(ALTERNATIVE_QUEUE)
  16423. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16424. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16425. ctx->sq_blocked = 0;
  16426. #endif
  16427. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16428. if (!ok) {
  16429. const char *err_msg =
  16430. "Cannot initialize thread synchronization objects";
  16431. /* Fatal error - abort start. However, this situation should never
  16432. * occur in practice. */
  16433. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16434. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16435. mg_snprintf(NULL,
  16436. NULL, /* No truncation check for error buffers */
  16437. error->text,
  16438. error->text_buffer_size,
  16439. "%s",
  16440. err_msg);
  16441. }
  16442. mg_free(ctx);
  16443. pthread_setspecific(sTlsKey, NULL);
  16444. return NULL;
  16445. }
  16446. if ((init != NULL) && (init->callbacks != NULL)) {
  16447. /* Set all callbacks except exit_context. */
  16448. ctx->callbacks = *init->callbacks;
  16449. exit_callback = init->callbacks->exit_context;
  16450. /* The exit callback is activated once the context is successfully
  16451. * created. It should not be called, if an incomplete context object is
  16452. * deleted during a failed initialization. */
  16453. ctx->callbacks.exit_context = 0;
  16454. }
  16455. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16456. ctx->dd.handlers = NULL;
  16457. ctx->dd.next = NULL;
  16458. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16459. ctx->dd.shared_lua_websockets = NULL;
  16460. #endif
  16461. /* Store options */
  16462. while (options && (name = *options++) != NULL) {
  16463. if ((idx = get_option_index(name)) == -1) {
  16464. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16465. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16466. mg_snprintf(NULL,
  16467. NULL, /* No truncation check for error buffers */
  16468. error->text,
  16469. error->text_buffer_size,
  16470. "Invalid configuration option: %s",
  16471. name);
  16472. }
  16473. free_context(ctx);
  16474. pthread_setspecific(sTlsKey, NULL);
  16475. return NULL;
  16476. } else if ((value = *options++) == NULL) {
  16477. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16478. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16479. mg_snprintf(NULL,
  16480. NULL, /* No truncation check for error buffers */
  16481. error->text,
  16482. error->text_buffer_size,
  16483. "Invalid configuration option value: %s",
  16484. name);
  16485. }
  16486. free_context(ctx);
  16487. pthread_setspecific(sTlsKey, NULL);
  16488. return NULL;
  16489. }
  16490. if (ctx->dd.config[idx] != NULL) {
  16491. /* A duplicate configuration option is not an error - the last
  16492. * option value will be used. */
  16493. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16494. mg_free(ctx->dd.config[idx]);
  16495. }
  16496. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16497. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16498. }
  16499. /* Set default value if needed */
  16500. for (i = 0; config_options[i].name != NULL; i++) {
  16501. default_value = config_options[i].default_value;
  16502. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16503. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16504. }
  16505. }
  16506. /* Request size option */
  16507. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16508. if (itmp < 1024) {
  16509. mg_cry_ctx_internal(ctx,
  16510. "%s too small",
  16511. config_options[MAX_REQUEST_SIZE].name);
  16512. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16513. mg_snprintf(NULL,
  16514. NULL, /* No truncation check for error buffers */
  16515. error->text,
  16516. error->text_buffer_size,
  16517. "Invalid configuration option value: %s",
  16518. config_options[MAX_REQUEST_SIZE].name);
  16519. }
  16520. free_context(ctx);
  16521. pthread_setspecific(sTlsKey, NULL);
  16522. return NULL;
  16523. }
  16524. ctx->max_request_size = (unsigned)itmp;
  16525. /* Queue length */
  16526. #if !defined(ALTERNATIVE_QUEUE)
  16527. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16528. if (itmp < 1) {
  16529. mg_cry_ctx_internal(ctx,
  16530. "%s too small",
  16531. config_options[CONNECTION_QUEUE_SIZE].name);
  16532. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16533. mg_snprintf(NULL,
  16534. NULL, /* No truncation check for error buffers */
  16535. error->text,
  16536. error->text_buffer_size,
  16537. "Invalid configuration option value: %s",
  16538. config_options[CONNECTION_QUEUE_SIZE].name);
  16539. }
  16540. free_context(ctx);
  16541. pthread_setspecific(sTlsKey, NULL);
  16542. return NULL;
  16543. }
  16544. ctx->squeue = (struct socket *)mg_calloc(itmp, sizeof(struct socket));
  16545. if (ctx->squeue == NULL) {
  16546. mg_cry_ctx_internal(ctx,
  16547. "Out of memory: Cannot allocate %s",
  16548. config_options[CONNECTION_QUEUE_SIZE].name);
  16549. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16550. mg_snprintf(NULL,
  16551. NULL, /* No truncation check for error buffers */
  16552. error->text,
  16553. error->text_buffer_size,
  16554. "Out of memory: Cannot allocate %s",
  16555. config_options[CONNECTION_QUEUE_SIZE].name);
  16556. }
  16557. free_context(ctx);
  16558. pthread_setspecific(sTlsKey, NULL);
  16559. return NULL;
  16560. }
  16561. ctx->sq_size = itmp;
  16562. #endif
  16563. /* Worker thread count option */
  16564. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16565. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16566. if (workerthreadcount <= 0) {
  16567. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16568. } else {
  16569. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16570. }
  16571. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16572. mg_snprintf(NULL,
  16573. NULL, /* No truncation check for error buffers */
  16574. error->text,
  16575. error->text_buffer_size,
  16576. "Invalid configuration option value: %s",
  16577. config_options[NUM_THREADS].name);
  16578. }
  16579. free_context(ctx);
  16580. pthread_setspecific(sTlsKey, NULL);
  16581. return NULL;
  16582. }
  16583. /* Document root */
  16584. #if defined(NO_FILES)
  16585. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16586. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16587. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16588. mg_snprintf(NULL,
  16589. NULL, /* No truncation check for error buffers */
  16590. error->text,
  16591. error->text_buffer_size,
  16592. "Invalid configuration option value: %s",
  16593. config_options[DOCUMENT_ROOT].name);
  16594. }
  16595. free_context(ctx);
  16596. pthread_setspecific(sTlsKey, NULL);
  16597. return NULL;
  16598. }
  16599. #endif
  16600. get_system_name(&ctx->systemName);
  16601. #if defined(USE_LUA)
  16602. /* If a Lua background script has been configured, start it. */
  16603. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16604. char ebuf[256];
  16605. struct vec opt_vec;
  16606. struct vec eq_vec;
  16607. const char *sparams;
  16608. lua_State *state = mg_prepare_lua_context_script(
  16609. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16610. if (!state) {
  16611. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16612. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16613. mg_snprintf(NULL,
  16614. NULL, /* No truncation check for error buffers */
  16615. error->text,
  16616. error->text_buffer_size,
  16617. "Error in script %s: %s",
  16618. config_options[DOCUMENT_ROOT].name,
  16619. ebuf);
  16620. }
  16621. free_context(ctx);
  16622. pthread_setspecific(sTlsKey, NULL);
  16623. return NULL;
  16624. }
  16625. ctx->lua_background_state = (void *)state;
  16626. lua_newtable(state);
  16627. reg_boolean(state, "shutdown", 0);
  16628. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16629. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16630. reg_llstring(
  16631. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16632. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16633. break;
  16634. }
  16635. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16636. } else {
  16637. ctx->lua_background_state = 0;
  16638. }
  16639. #endif
  16640. /* Step by step initialization of ctx - depending on build options */
  16641. #if !defined(NO_FILESYSTEMS)
  16642. if (!set_gpass_option(ctx, NULL)) {
  16643. const char *err_msg = "Invalid global password file";
  16644. /* Fatal error - abort start. */
  16645. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16646. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16647. mg_snprintf(NULL,
  16648. NULL, /* No truncation check for error buffers */
  16649. error->text,
  16650. error->text_buffer_size,
  16651. "%s",
  16652. err_msg);
  16653. }
  16654. free_context(ctx);
  16655. pthread_setspecific(sTlsKey, NULL);
  16656. return NULL;
  16657. }
  16658. #endif
  16659. #if !defined(NO_SSL)
  16660. if (!init_ssl_ctx(ctx, NULL)) {
  16661. const char *err_msg = "Error initializing SSL context";
  16662. /* Fatal error - abort start. */
  16663. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16664. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16665. mg_snprintf(NULL,
  16666. NULL, /* No truncation check for error buffers */
  16667. error->text,
  16668. error->text_buffer_size,
  16669. "%s",
  16670. err_msg);
  16671. }
  16672. free_context(ctx);
  16673. pthread_setspecific(sTlsKey, NULL);
  16674. return NULL;
  16675. }
  16676. #endif
  16677. if (!set_ports_option(ctx)) {
  16678. const char *err_msg = "Failed to setup server ports";
  16679. /* Fatal error - abort start. */
  16680. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16681. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16682. mg_snprintf(NULL,
  16683. NULL, /* No truncation check for error buffers */
  16684. error->text,
  16685. error->text_buffer_size,
  16686. "%s",
  16687. err_msg);
  16688. }
  16689. free_context(ctx);
  16690. pthread_setspecific(sTlsKey, NULL);
  16691. return NULL;
  16692. }
  16693. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16694. if (!set_uid_option(ctx)) {
  16695. const char *err_msg = "Failed to run as configured user";
  16696. /* Fatal error - abort start. */
  16697. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16698. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16699. mg_snprintf(NULL,
  16700. NULL, /* No truncation check for error buffers */
  16701. error->text,
  16702. error->text_buffer_size,
  16703. "%s",
  16704. err_msg);
  16705. }
  16706. free_context(ctx);
  16707. pthread_setspecific(sTlsKey, NULL);
  16708. return NULL;
  16709. }
  16710. #endif
  16711. if (!set_acl_option(ctx)) {
  16712. const char *err_msg = "Failed to setup access control list";
  16713. /* Fatal error - abort start. */
  16714. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16715. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16716. mg_snprintf(NULL,
  16717. NULL, /* No truncation check for error buffers */
  16718. error->text,
  16719. error->text_buffer_size,
  16720. "%s",
  16721. err_msg);
  16722. }
  16723. free_context(ctx);
  16724. pthread_setspecific(sTlsKey, NULL);
  16725. return NULL;
  16726. }
  16727. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16728. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16729. sizeof(pthread_t),
  16730. ctx);
  16731. if (ctx->worker_threadids == NULL) {
  16732. const char *err_msg = "Not enough memory for worker thread ID array";
  16733. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16734. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16735. mg_snprintf(NULL,
  16736. NULL, /* No truncation check for error buffers */
  16737. error->text,
  16738. error->text_buffer_size,
  16739. "%s",
  16740. err_msg);
  16741. }
  16742. free_context(ctx);
  16743. pthread_setspecific(sTlsKey, NULL);
  16744. return NULL;
  16745. }
  16746. ctx->worker_connections =
  16747. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16748. sizeof(struct mg_connection),
  16749. ctx);
  16750. if (ctx->worker_connections == NULL) {
  16751. const char *err_msg =
  16752. "Not enough memory for worker thread connection array";
  16753. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16754. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16755. mg_snprintf(NULL,
  16756. NULL, /* No truncation check for error buffers */
  16757. error->text,
  16758. error->text_buffer_size,
  16759. "%s",
  16760. err_msg);
  16761. }
  16762. free_context(ctx);
  16763. pthread_setspecific(sTlsKey, NULL);
  16764. return NULL;
  16765. }
  16766. #if defined(ALTERNATIVE_QUEUE)
  16767. ctx->client_wait_events =
  16768. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  16769. sizeof(ctx->client_wait_events[0]),
  16770. ctx);
  16771. if (ctx->client_wait_events == NULL) {
  16772. const char *err_msg = "Not enough memory for worker event array";
  16773. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16774. mg_free(ctx->worker_threadids);
  16775. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16776. mg_snprintf(NULL,
  16777. NULL, /* No truncation check for error buffers */
  16778. error->text,
  16779. error->text_buffer_size,
  16780. "%s",
  16781. err_msg);
  16782. }
  16783. free_context(ctx);
  16784. pthread_setspecific(sTlsKey, NULL);
  16785. return NULL;
  16786. }
  16787. ctx->client_socks =
  16788. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16789. sizeof(ctx->client_socks[0]),
  16790. ctx);
  16791. if (ctx->client_socks == NULL) {
  16792. const char *err_msg = "Not enough memory for worker socket array";
  16793. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16794. mg_free(ctx->client_wait_events);
  16795. mg_free(ctx->worker_threadids);
  16796. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16797. mg_snprintf(NULL,
  16798. NULL, /* No truncation check for error buffers */
  16799. error->text,
  16800. error->text_buffer_size,
  16801. "%s",
  16802. err_msg);
  16803. }
  16804. free_context(ctx);
  16805. pthread_setspecific(sTlsKey, NULL);
  16806. return NULL;
  16807. }
  16808. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16809. ctx->client_wait_events[i] = event_create();
  16810. if (ctx->client_wait_events[i] == 0) {
  16811. const char *err_msg = "Error creating worker event %i";
  16812. mg_cry_ctx_internal(ctx, err_msg, i);
  16813. while (i > 0) {
  16814. i--;
  16815. event_destroy(ctx->client_wait_events[i]);
  16816. }
  16817. mg_free(ctx->client_socks);
  16818. mg_free(ctx->client_wait_events);
  16819. mg_free(ctx->worker_threadids);
  16820. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16821. mg_snprintf(NULL,
  16822. NULL, /* No truncation check for error buffers */
  16823. error->text,
  16824. error->text_buffer_size,
  16825. err_msg,
  16826. i);
  16827. }
  16828. free_context(ctx);
  16829. pthread_setspecific(sTlsKey, NULL);
  16830. return NULL;
  16831. }
  16832. }
  16833. #endif
  16834. #if defined(USE_TIMERS)
  16835. if (timers_init(ctx) != 0) {
  16836. const char *err_msg = "Error creating timers";
  16837. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16838. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16839. mg_snprintf(NULL,
  16840. NULL, /* No truncation check for error buffers */
  16841. error->text,
  16842. error->text_buffer_size,
  16843. "%s",
  16844. err_msg);
  16845. }
  16846. free_context(ctx);
  16847. pthread_setspecific(sTlsKey, NULL);
  16848. return NULL;
  16849. }
  16850. #endif
  16851. /* Context has been created - init user libraries */
  16852. if (ctx->callbacks.init_context) {
  16853. ctx->callbacks.init_context(ctx);
  16854. }
  16855. /* From now, the context is successfully created.
  16856. * When it is destroyed, the exit callback should be called. */
  16857. ctx->callbacks.exit_context = exit_callback;
  16858. ctx->context_type = CONTEXT_SERVER; /* server context */
  16859. /* Start master (listening) thread */
  16860. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16861. /* Start worker threads */
  16862. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16863. /* worker_thread sets up the other fields */
  16864. ctx->worker_connections[i].phys_ctx = ctx;
  16865. if (mg_start_thread_with_id(worker_thread,
  16866. &ctx->worker_connections[i],
  16867. &ctx->worker_threadids[i])
  16868. != 0) {
  16869. long error_no = (long)ERRNO;
  16870. /* thread was not created */
  16871. if (i > 0) {
  16872. /* If the second, third, ... thread cannot be created, set a
  16873. * warning, but keep running. */
  16874. mg_cry_ctx_internal(ctx,
  16875. "Cannot start worker thread %i: error %ld",
  16876. i + 1,
  16877. error_no);
  16878. /* If the server initialization should stop here, all threads
  16879. * that have already been created must be stopped first, before
  16880. * any free_context(ctx) call.
  16881. */
  16882. } else {
  16883. /* If the first worker thread cannot be created, stop
  16884. * initialization and free the entire server context. */
  16885. mg_cry_ctx_internal(ctx,
  16886. "Cannot create threads: error %ld",
  16887. error_no);
  16888. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16889. mg_snprintf(
  16890. NULL,
  16891. NULL, /* No truncation check for error buffers */
  16892. error->text,
  16893. error->text_buffer_size,
  16894. "Cannot create first worker thread: error %ld",
  16895. error_no);
  16896. }
  16897. free_context(ctx);
  16898. pthread_setspecific(sTlsKey, NULL);
  16899. return NULL;
  16900. }
  16901. break;
  16902. }
  16903. }
  16904. pthread_setspecific(sTlsKey, NULL);
  16905. return ctx;
  16906. }
  16907. struct mg_context *
  16908. mg_start(const struct mg_callbacks *callbacks,
  16909. void *user_data,
  16910. const char **options)
  16911. {
  16912. struct mg_init_data init = {0};
  16913. init.callbacks = callbacks;
  16914. init.user_data = user_data;
  16915. init.configuration_options = options;
  16916. return mg_start2(&init, NULL);
  16917. }
  16918. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16919. /* Add an additional domain to an already running web server. */
  16920. int
  16921. mg_start_domain2(struct mg_context *ctx,
  16922. const char **options,
  16923. struct mg_error_data *error)
  16924. {
  16925. const char *name;
  16926. const char *value;
  16927. const char *default_value;
  16928. struct mg_domain_context *new_dom;
  16929. struct mg_domain_context *dom;
  16930. int idx, i;
  16931. if (error != NULL) {
  16932. error->code = 0;
  16933. if (error->text_buffer_size > 0) {
  16934. *error->text = 0;
  16935. }
  16936. }
  16937. if ((ctx == NULL) || (options == NULL)) {
  16938. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16939. mg_snprintf(NULL,
  16940. NULL, /* No truncation check for error buffers */
  16941. error->text,
  16942. error->text_buffer_size,
  16943. "%s",
  16944. "Invalid parameters");
  16945. }
  16946. return -1;
  16947. }
  16948. if (ctx->stop_flag != 0) {
  16949. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16950. mg_snprintf(NULL,
  16951. NULL, /* No truncation check for error buffers */
  16952. error->text,
  16953. error->text_buffer_size,
  16954. "%s",
  16955. "Server already stopped");
  16956. }
  16957. return -1;
  16958. }
  16959. new_dom = (struct mg_domain_context *)
  16960. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16961. if (!new_dom) {
  16962. /* Out of memory */
  16963. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16964. mg_snprintf(NULL,
  16965. NULL, /* No truncation check for error buffers */
  16966. error->text,
  16967. error->text_buffer_size,
  16968. "%s",
  16969. "Out or memory");
  16970. }
  16971. return -6;
  16972. }
  16973. /* Store options - TODO: unite duplicate code */
  16974. while (options && (name = *options++) != NULL) {
  16975. if ((idx = get_option_index(name)) == -1) {
  16976. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16977. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16978. mg_snprintf(NULL,
  16979. NULL, /* No truncation check for error buffers */
  16980. error->text,
  16981. error->text_buffer_size,
  16982. "Invalid option: %s",
  16983. name);
  16984. }
  16985. mg_free(new_dom);
  16986. return -2;
  16987. } else if ((value = *options++) == NULL) {
  16988. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16989. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16990. mg_snprintf(NULL,
  16991. NULL, /* No truncation check for error buffers */
  16992. error->text,
  16993. error->text_buffer_size,
  16994. "Invalid option value: %s",
  16995. name);
  16996. }
  16997. mg_free(new_dom);
  16998. return -2;
  16999. }
  17000. if (new_dom->config[idx] != NULL) {
  17001. /* Duplicate option: Later values overwrite earlier ones. */
  17002. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17003. mg_free(new_dom->config[idx]);
  17004. }
  17005. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17006. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17007. }
  17008. /* Authentication domain is mandatory */
  17009. /* TODO: Maybe use a new option hostname? */
  17010. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17011. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17012. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17013. mg_snprintf(NULL,
  17014. NULL, /* No truncation check for error buffers */
  17015. error->text,
  17016. error->text_buffer_size,
  17017. "Mandatory option %s missing",
  17018. config_options[AUTHENTICATION_DOMAIN].name);
  17019. }
  17020. mg_free(new_dom);
  17021. return -4;
  17022. }
  17023. /* Set default value if needed. Take the config value from
  17024. * ctx as a default value. */
  17025. for (i = 0; config_options[i].name != NULL; i++) {
  17026. default_value = ctx->dd.config[i];
  17027. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17028. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17029. }
  17030. }
  17031. new_dom->handlers = NULL;
  17032. new_dom->next = NULL;
  17033. new_dom->nonce_count = 0;
  17034. new_dom->auth_nonce_mask =
  17035. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17036. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17037. new_dom->shared_lua_websockets = NULL;
  17038. #endif
  17039. if (!init_ssl_ctx(ctx, new_dom)) {
  17040. /* Init SSL failed */
  17041. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17042. mg_snprintf(NULL,
  17043. NULL, /* No truncation check for error buffers */
  17044. error->text,
  17045. error->text_buffer_size,
  17046. "%s",
  17047. "Initializing SSL context failed");
  17048. }
  17049. mg_free(new_dom);
  17050. return -3;
  17051. }
  17052. /* Add element to linked list. */
  17053. mg_lock_context(ctx);
  17054. idx = 0;
  17055. dom = &(ctx->dd);
  17056. for (;;) {
  17057. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17058. dom->config[AUTHENTICATION_DOMAIN])) {
  17059. /* Domain collision */
  17060. mg_cry_ctx_internal(ctx,
  17061. "domain %s already in use",
  17062. new_dom->config[AUTHENTICATION_DOMAIN]);
  17063. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17064. mg_snprintf(NULL,
  17065. NULL, /* No truncation check for error buffers */
  17066. error->text,
  17067. error->text_buffer_size,
  17068. "Domain %s specified by %s is already in use",
  17069. new_dom->config[AUTHENTICATION_DOMAIN],
  17070. config_options[AUTHENTICATION_DOMAIN].name);
  17071. }
  17072. mg_free(new_dom);
  17073. return -5;
  17074. }
  17075. /* Count number of domains */
  17076. idx++;
  17077. if (dom->next == NULL) {
  17078. dom->next = new_dom;
  17079. break;
  17080. }
  17081. dom = dom->next;
  17082. }
  17083. mg_unlock_context(ctx);
  17084. /* Return domain number */
  17085. return idx;
  17086. }
  17087. int
  17088. mg_start_domain(struct mg_context *ctx, const char **options)
  17089. {
  17090. return mg_start_domain2(ctx, options, NULL);
  17091. }
  17092. #endif
  17093. /* Feature check API function */
  17094. unsigned
  17095. mg_check_feature(unsigned feature)
  17096. {
  17097. static const unsigned feature_set = 0
  17098. /* Set bits for available features according to API documentation.
  17099. * This bit mask is created at compile time, according to the active
  17100. * preprocessor defines. It is a single const value at runtime. */
  17101. #if !defined(NO_FILES)
  17102. | MG_FEATURES_FILES
  17103. #endif
  17104. #if !defined(NO_SSL)
  17105. | MG_FEATURES_SSL
  17106. #endif
  17107. #if !defined(NO_CGI)
  17108. | MG_FEATURES_CGI
  17109. #endif
  17110. #if defined(USE_IPV6)
  17111. | MG_FEATURES_IPV6
  17112. #endif
  17113. #if defined(USE_WEBSOCKET)
  17114. | MG_FEATURES_WEBSOCKET
  17115. #endif
  17116. #if defined(USE_LUA)
  17117. | MG_FEATURES_LUA
  17118. #endif
  17119. #if defined(USE_DUKTAPE)
  17120. | MG_FEATURES_SSJS
  17121. #endif
  17122. #if !defined(NO_CACHING)
  17123. | MG_FEATURES_CACHE
  17124. #endif
  17125. #if defined(USE_SERVER_STATS)
  17126. | MG_FEATURES_STATS
  17127. #endif
  17128. #if defined(USE_ZLIB)
  17129. | MG_FEATURES_COMPRESSION
  17130. #endif
  17131. /* Set some extra bits not defined in the API documentation.
  17132. * These bits may change without further notice. */
  17133. #if defined(MG_LEGACY_INTERFACE)
  17134. | 0x00008000u
  17135. #endif
  17136. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17137. | 0x00004000u
  17138. #endif
  17139. #if defined(MEMORY_DEBUGGING)
  17140. | 0x00001000u
  17141. #endif
  17142. #if defined(USE_TIMERS)
  17143. | 0x00020000u
  17144. #endif
  17145. #if !defined(NO_NONCE_CHECK)
  17146. | 0x00040000u
  17147. #endif
  17148. #if !defined(NO_POPEN)
  17149. | 0x00080000u
  17150. #endif
  17151. ;
  17152. return (feature & feature_set);
  17153. }
  17154. static size_t
  17155. mg_str_append(char **dst, char *end, const char *src)
  17156. {
  17157. size_t len = strlen(src);
  17158. if (*dst != end) {
  17159. /* Append src if enough space, or close dst. */
  17160. if ((size_t)(end - *dst) > len) {
  17161. strcpy(*dst, src);
  17162. *dst += len;
  17163. } else {
  17164. *dst = end;
  17165. }
  17166. }
  17167. return len;
  17168. }
  17169. /* Get system information. It can be printed or stored by the caller.
  17170. * Return the size of available information. */
  17171. int
  17172. mg_get_system_info(char *buffer, int buflen)
  17173. {
  17174. char *end, *append_eoobj = NULL, block[256];
  17175. size_t system_info_length = 0;
  17176. #if defined(_WIN32)
  17177. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17178. #else
  17179. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17180. #endif
  17181. if ((buffer == NULL) || (buflen < 1)) {
  17182. buflen = 0;
  17183. end = buffer;
  17184. } else {
  17185. *buffer = 0;
  17186. end = buffer + buflen;
  17187. }
  17188. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17189. /* has enough space to append eoobj */
  17190. append_eoobj = buffer;
  17191. end -= sizeof(eoobj) - 1;
  17192. }
  17193. system_info_length += mg_str_append(&buffer, end, "{");
  17194. /* Server version */
  17195. {
  17196. const char *version = mg_version();
  17197. mg_snprintf(NULL,
  17198. NULL,
  17199. block,
  17200. sizeof(block),
  17201. "%s\"version\" : \"%s\"",
  17202. eol,
  17203. version);
  17204. system_info_length += mg_str_append(&buffer, end, block);
  17205. }
  17206. /* System info */
  17207. {
  17208. #if defined(_WIN32)
  17209. DWORD dwVersion = 0;
  17210. DWORD dwMajorVersion = 0;
  17211. DWORD dwMinorVersion = 0;
  17212. SYSTEM_INFO si;
  17213. GetSystemInfo(&si);
  17214. #if defined(_MSC_VER)
  17215. #pragma warning(push)
  17216. /* GetVersion was declared deprecated */
  17217. #pragma warning(disable : 4996)
  17218. #endif
  17219. dwVersion = GetVersion();
  17220. #if defined(_MSC_VER)
  17221. #pragma warning(pop)
  17222. #endif
  17223. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17224. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17225. mg_snprintf(NULL,
  17226. NULL,
  17227. block,
  17228. sizeof(block),
  17229. ",%s\"os\" : \"Windows %u.%u\"",
  17230. eol,
  17231. (unsigned)dwMajorVersion,
  17232. (unsigned)dwMinorVersion);
  17233. system_info_length += mg_str_append(&buffer, end, block);
  17234. mg_snprintf(NULL,
  17235. NULL,
  17236. block,
  17237. sizeof(block),
  17238. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17239. eol,
  17240. (unsigned)si.wProcessorArchitecture,
  17241. (unsigned)si.dwNumberOfProcessors,
  17242. (unsigned)si.dwActiveProcessorMask);
  17243. system_info_length += mg_str_append(&buffer, end, block);
  17244. #elif defined(__ZEPHYR__)
  17245. mg_snprintf(NULL,
  17246. NULL,
  17247. block,
  17248. sizeof(block),
  17249. ",%s\"os\" : \"%s %s\"",
  17250. eol,
  17251. "Zephyr OS",
  17252. ZEPHYR_VERSION);
  17253. system_info_length += mg_str_append(&buffer, end, block);
  17254. #else
  17255. struct utsname name;
  17256. memset(&name, 0, sizeof(name));
  17257. uname(&name);
  17258. mg_snprintf(NULL,
  17259. NULL,
  17260. block,
  17261. sizeof(block),
  17262. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17263. eol,
  17264. name.sysname,
  17265. name.version,
  17266. name.release,
  17267. name.machine);
  17268. system_info_length += mg_str_append(&buffer, end, block);
  17269. #endif
  17270. }
  17271. /* Features */
  17272. {
  17273. mg_snprintf(NULL,
  17274. NULL,
  17275. block,
  17276. sizeof(block),
  17277. ",%s\"features\" : %lu"
  17278. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17279. eol,
  17280. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17281. eol,
  17282. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17283. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17284. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17285. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17286. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17287. : "",
  17288. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17289. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17290. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17291. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17292. system_info_length += mg_str_append(&buffer, end, block);
  17293. #if defined(USE_LUA)
  17294. mg_snprintf(NULL,
  17295. NULL,
  17296. block,
  17297. sizeof(block),
  17298. ",%s\"lua_version\" : \"%u (%s)\"",
  17299. eol,
  17300. (unsigned)LUA_VERSION_NUM,
  17301. LUA_RELEASE);
  17302. system_info_length += mg_str_append(&buffer, end, block);
  17303. #endif
  17304. #if defined(USE_DUKTAPE)
  17305. mg_snprintf(NULL,
  17306. NULL,
  17307. block,
  17308. sizeof(block),
  17309. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17310. eol,
  17311. (unsigned)DUK_VERSION / 10000,
  17312. ((unsigned)DUK_VERSION / 100) % 100,
  17313. (unsigned)DUK_VERSION % 100);
  17314. system_info_length += mg_str_append(&buffer, end, block);
  17315. #endif
  17316. }
  17317. /* Build date */
  17318. {
  17319. #if defined(GCC_DIAGNOSTIC)
  17320. #if GCC_VERSION >= 40900
  17321. #pragma GCC diagnostic push
  17322. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17323. #pragma GCC diagnostic ignored "-Wdate-time"
  17324. #endif
  17325. #endif
  17326. mg_snprintf(NULL,
  17327. NULL,
  17328. block,
  17329. sizeof(block),
  17330. ",%s\"build\" : \"%s\"",
  17331. eol,
  17332. __DATE__);
  17333. #if defined(GCC_DIAGNOSTIC)
  17334. #if GCC_VERSION >= 40900
  17335. #pragma GCC diagnostic pop
  17336. #endif
  17337. #endif
  17338. system_info_length += mg_str_append(&buffer, end, block);
  17339. }
  17340. /* Compiler information */
  17341. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17342. {
  17343. #if defined(_MSC_VER)
  17344. mg_snprintf(NULL,
  17345. NULL,
  17346. block,
  17347. sizeof(block),
  17348. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17349. eol,
  17350. (unsigned)_MSC_VER,
  17351. (unsigned)_MSC_FULL_VER);
  17352. system_info_length += mg_str_append(&buffer, end, block);
  17353. #elif defined(__MINGW64__)
  17354. mg_snprintf(NULL,
  17355. NULL,
  17356. block,
  17357. sizeof(block),
  17358. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17359. eol,
  17360. (unsigned)__MINGW64_VERSION_MAJOR,
  17361. (unsigned)__MINGW64_VERSION_MINOR);
  17362. system_info_length += mg_str_append(&buffer, end, block);
  17363. mg_snprintf(NULL,
  17364. NULL,
  17365. block,
  17366. sizeof(block),
  17367. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17368. eol,
  17369. (unsigned)__MINGW32_MAJOR_VERSION,
  17370. (unsigned)__MINGW32_MINOR_VERSION);
  17371. system_info_length += mg_str_append(&buffer, end, block);
  17372. #elif defined(__MINGW32__)
  17373. mg_snprintf(NULL,
  17374. NULL,
  17375. block,
  17376. sizeof(block),
  17377. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17378. eol,
  17379. (unsigned)__MINGW32_MAJOR_VERSION,
  17380. (unsigned)__MINGW32_MINOR_VERSION);
  17381. system_info_length += mg_str_append(&buffer, end, block);
  17382. #elif defined(__clang__)
  17383. mg_snprintf(NULL,
  17384. NULL,
  17385. block,
  17386. sizeof(block),
  17387. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17388. eol,
  17389. __clang_major__,
  17390. __clang_minor__,
  17391. __clang_patchlevel__,
  17392. __clang_version__);
  17393. system_info_length += mg_str_append(&buffer, end, block);
  17394. #elif defined(__GNUC__)
  17395. mg_snprintf(NULL,
  17396. NULL,
  17397. block,
  17398. sizeof(block),
  17399. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17400. eol,
  17401. (unsigned)__GNUC__,
  17402. (unsigned)__GNUC_MINOR__,
  17403. (unsigned)__GNUC_PATCHLEVEL__);
  17404. system_info_length += mg_str_append(&buffer, end, block);
  17405. #elif defined(__INTEL_COMPILER)
  17406. mg_snprintf(NULL,
  17407. NULL,
  17408. block,
  17409. sizeof(block),
  17410. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17411. eol,
  17412. (unsigned)__INTEL_COMPILER);
  17413. system_info_length += mg_str_append(&buffer, end, block);
  17414. #elif defined(__BORLANDC__)
  17415. mg_snprintf(NULL,
  17416. NULL,
  17417. block,
  17418. sizeof(block),
  17419. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17420. eol,
  17421. (unsigned)__BORLANDC__);
  17422. system_info_length += mg_str_append(&buffer, end, block);
  17423. #elif defined(__SUNPRO_C)
  17424. mg_snprintf(NULL,
  17425. NULL,
  17426. block,
  17427. sizeof(block),
  17428. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17429. eol,
  17430. (unsigned)__SUNPRO_C);
  17431. system_info_length += mg_str_append(&buffer, end, block);
  17432. #else
  17433. mg_snprintf(NULL,
  17434. NULL,
  17435. block,
  17436. sizeof(block),
  17437. ",%s\"compiler\" : \"other\"",
  17438. eol);
  17439. system_info_length += mg_str_append(&buffer, end, block);
  17440. #endif
  17441. }
  17442. /* Determine 32/64 bit data mode.
  17443. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17444. {
  17445. mg_snprintf(NULL,
  17446. NULL,
  17447. block,
  17448. sizeof(block),
  17449. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17450. "char:%u/%u, "
  17451. "ptr:%u, size:%u, time:%u\"",
  17452. eol,
  17453. (unsigned)sizeof(short),
  17454. (unsigned)sizeof(int),
  17455. (unsigned)sizeof(long),
  17456. (unsigned)sizeof(long long),
  17457. (unsigned)sizeof(float),
  17458. (unsigned)sizeof(double),
  17459. (unsigned)sizeof(long double),
  17460. (unsigned)sizeof(char),
  17461. (unsigned)sizeof(wchar_t),
  17462. (unsigned)sizeof(void *),
  17463. (unsigned)sizeof(size_t),
  17464. (unsigned)sizeof(time_t));
  17465. system_info_length += mg_str_append(&buffer, end, block);
  17466. }
  17467. /* Terminate string */
  17468. if (append_eoobj) {
  17469. strcat(append_eoobj, eoobj);
  17470. }
  17471. system_info_length += sizeof(eoobj) - 1;
  17472. return (int)system_info_length;
  17473. }
  17474. /* Get context information. It can be printed or stored by the caller.
  17475. * Return the size of available information. */
  17476. int
  17477. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17478. {
  17479. #if defined(USE_SERVER_STATS)
  17480. char *end, *append_eoobj = NULL, block[256];
  17481. size_t context_info_length = 0;
  17482. #if defined(_WIN32)
  17483. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17484. #else
  17485. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17486. #endif
  17487. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17488. if ((buffer == NULL) || (buflen < 1)) {
  17489. buflen = 0;
  17490. end = buffer;
  17491. } else {
  17492. *buffer = 0;
  17493. end = buffer + buflen;
  17494. }
  17495. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17496. /* has enough space to append eoobj */
  17497. append_eoobj = buffer;
  17498. end -= sizeof(eoobj) - 1;
  17499. }
  17500. context_info_length += mg_str_append(&buffer, end, "{");
  17501. if (ms) { /* <-- should be always true */
  17502. /* Memory information */
  17503. mg_snprintf(NULL,
  17504. NULL,
  17505. block,
  17506. sizeof(block),
  17507. "%s\"memory\" : {%s"
  17508. "\"blocks\" : %i,%s"
  17509. "\"used\" : %" INT64_FMT ",%s"
  17510. "\"maxUsed\" : %" INT64_FMT "%s"
  17511. "}",
  17512. eol,
  17513. eol,
  17514. ms->blockCount,
  17515. eol,
  17516. ms->totalMemUsed,
  17517. eol,
  17518. ms->maxMemUsed,
  17519. eol);
  17520. context_info_length += mg_str_append(&buffer, end, block);
  17521. }
  17522. if (ctx) {
  17523. /* Declare all variables at begin of the block, to comply
  17524. * with old C standards. */
  17525. char start_time_str[64] = {0};
  17526. char now_str[64] = {0};
  17527. time_t start_time = ctx->start_time;
  17528. time_t now = time(NULL);
  17529. /* Connections information */
  17530. mg_snprintf(NULL,
  17531. NULL,
  17532. block,
  17533. sizeof(block),
  17534. ",%s\"connections\" : {%s"
  17535. "\"active\" : %i,%s"
  17536. "\"maxActive\" : %i,%s"
  17537. "\"total\" : %" INT64_FMT "%s"
  17538. "}",
  17539. eol,
  17540. eol,
  17541. ctx->active_connections,
  17542. eol,
  17543. ctx->max_active_connections,
  17544. eol,
  17545. ctx->total_connections,
  17546. eol);
  17547. context_info_length += mg_str_append(&buffer, end, block);
  17548. /* Queue information */
  17549. #if !defined(ALTERNATIVE_QUEUE)
  17550. mg_snprintf(NULL,
  17551. NULL,
  17552. block,
  17553. sizeof(block),
  17554. ",%s\"queue\" : {%s"
  17555. "\"length\" : %i,%s"
  17556. "\"filled\" : %i,%s"
  17557. "\"maxFilled\" : %i,%s"
  17558. "\"full\" : %s%s"
  17559. "}",
  17560. eol,
  17561. eol,
  17562. ctx->sq_size,
  17563. eol,
  17564. ctx->sq_head - ctx->sq_tail,
  17565. eol,
  17566. ctx->sq_max_fill,
  17567. eol,
  17568. (ctx->sq_blocked ? "true" : "false"),
  17569. eol);
  17570. context_info_length += mg_str_append(&buffer, end, block);
  17571. #endif
  17572. /* Requests information */
  17573. mg_snprintf(NULL,
  17574. NULL,
  17575. block,
  17576. sizeof(block),
  17577. ",%s\"requests\" : {%s"
  17578. "\"total\" : %" INT64_FMT "%s"
  17579. "}",
  17580. eol,
  17581. eol,
  17582. ctx->total_requests,
  17583. eol);
  17584. context_info_length += mg_str_append(&buffer, end, block);
  17585. /* Data information */
  17586. mg_snprintf(NULL,
  17587. NULL,
  17588. block,
  17589. sizeof(block),
  17590. ",%s\"data\" : {%s"
  17591. "\"read\" : %" INT64_FMT ",%s"
  17592. "\"written\" : %" INT64_FMT "%s"
  17593. "}",
  17594. eol,
  17595. eol,
  17596. ctx->total_data_read,
  17597. eol,
  17598. ctx->total_data_written,
  17599. eol);
  17600. context_info_length += mg_str_append(&buffer, end, block);
  17601. /* Execution time information */
  17602. gmt_time_string(start_time_str,
  17603. sizeof(start_time_str) - 1,
  17604. &start_time);
  17605. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17606. mg_snprintf(NULL,
  17607. NULL,
  17608. block,
  17609. sizeof(block),
  17610. ",%s\"time\" : {%s"
  17611. "\"uptime\" : %.0f,%s"
  17612. "\"start\" : \"%s\",%s"
  17613. "\"now\" : \"%s\"%s"
  17614. "}",
  17615. eol,
  17616. eol,
  17617. difftime(now, start_time),
  17618. eol,
  17619. start_time_str,
  17620. eol,
  17621. now_str,
  17622. eol);
  17623. context_info_length += mg_str_append(&buffer, end, block);
  17624. }
  17625. /* Terminate string */
  17626. if (append_eoobj) {
  17627. strcat(append_eoobj, eoobj);
  17628. }
  17629. context_info_length += sizeof(eoobj) - 1;
  17630. return (int)context_info_length;
  17631. #else
  17632. (void)ctx;
  17633. if ((buffer != NULL) && (buflen > 0)) {
  17634. *buffer = 0;
  17635. }
  17636. return 0;
  17637. #endif
  17638. }
  17639. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17640. /* Get connection information. It can be printed or stored by the caller.
  17641. * Return the size of available information. */
  17642. int
  17643. mg_get_connection_info(const struct mg_context *ctx,
  17644. int idx,
  17645. char *buffer,
  17646. int buflen)
  17647. {
  17648. const struct mg_connection *conn;
  17649. const struct mg_request_info *ri;
  17650. char *end, *append_eoobj = NULL, block[256];
  17651. size_t connection_info_length = 0;
  17652. int state = 0;
  17653. const char *state_str = "unknown";
  17654. #if defined(_WIN32)
  17655. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17656. #else
  17657. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17658. #endif
  17659. if ((buffer == NULL) || (buflen < 1)) {
  17660. buflen = 0;
  17661. end = buffer;
  17662. } else {
  17663. *buffer = 0;
  17664. end = buffer + buflen;
  17665. }
  17666. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17667. /* has enough space to append eoobj */
  17668. append_eoobj = buffer;
  17669. end -= sizeof(eoobj) - 1;
  17670. }
  17671. if ((ctx == NULL) || (idx < 0)) {
  17672. /* Parameter error */
  17673. return 0;
  17674. }
  17675. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  17676. /* Out of range */
  17677. return 0;
  17678. }
  17679. /* Take connection [idx]. This connection is not locked in
  17680. * any way, so some other thread might use it. */
  17681. conn = (ctx->worker_connections) + idx;
  17682. /* Initialize output string */
  17683. connection_info_length += mg_str_append(&buffer, end, "{");
  17684. /* Init variables */
  17685. ri = &(conn->request_info);
  17686. #if defined(USE_SERVER_STATS)
  17687. state = conn->conn_state;
  17688. /* State as string */
  17689. switch (state) {
  17690. case 0:
  17691. state_str = "undefined";
  17692. break;
  17693. case 1:
  17694. state_str = "not used";
  17695. break;
  17696. case 2:
  17697. state_str = "init";
  17698. break;
  17699. case 3:
  17700. state_str = "ready";
  17701. break;
  17702. case 4:
  17703. state_str = "processing";
  17704. break;
  17705. case 5:
  17706. state_str = "processed";
  17707. break;
  17708. case 6:
  17709. state_str = "to close";
  17710. break;
  17711. case 7:
  17712. state_str = "closing";
  17713. break;
  17714. case 8:
  17715. state_str = "closed";
  17716. break;
  17717. case 9:
  17718. state_str = "done";
  17719. break;
  17720. }
  17721. #endif
  17722. /* Connection info */
  17723. if ((state >= 3) && (state < 9)) {
  17724. mg_snprintf(NULL,
  17725. NULL,
  17726. block,
  17727. sizeof(block),
  17728. "%s\"connection\" : {%s"
  17729. "\"remote\" : {%s"
  17730. "\"protocol\" : \"%s\",%s"
  17731. "\"addr\" : \"%s\",%s"
  17732. "\"port\" : %u%s"
  17733. "},%s"
  17734. "\"handled_requests\" : %u%s"
  17735. "}",
  17736. eol,
  17737. eol,
  17738. eol,
  17739. get_proto_name(conn),
  17740. eol,
  17741. ri->remote_addr,
  17742. eol,
  17743. ri->remote_port,
  17744. eol,
  17745. eol,
  17746. conn->handled_requests,
  17747. eol);
  17748. connection_info_length += mg_str_append(&buffer, end, block);
  17749. }
  17750. /* Request info */
  17751. if ((state >= 4) && (state < 6)) {
  17752. mg_snprintf(NULL,
  17753. NULL,
  17754. block,
  17755. sizeof(block),
  17756. "%s%s\"request_info\" : {%s"
  17757. "\"method\" : \"%s\",%s"
  17758. "\"uri\" : \"%s\",%s"
  17759. "\"query\" : %s%s%s%s"
  17760. "}",
  17761. (connection_info_length > 1 ? "," : ""),
  17762. eol,
  17763. eol,
  17764. ri->request_method,
  17765. eol,
  17766. ri->request_uri,
  17767. eol,
  17768. ri->query_string ? "\"" : "",
  17769. ri->query_string ? ri->query_string : "null",
  17770. ri->query_string ? "\"" : "",
  17771. eol);
  17772. connection_info_length += mg_str_append(&buffer, end, block);
  17773. }
  17774. /* Execution time information */
  17775. if ((state >= 2) && (state < 9)) {
  17776. char start_time_str[64] = {0};
  17777. char close_time_str[64] = {0};
  17778. time_t start_time = conn->conn_birth_time;
  17779. time_t close_time = conn->conn_close_time;
  17780. double time_diff;
  17781. gmt_time_string(start_time_str,
  17782. sizeof(start_time_str) - 1,
  17783. &start_time);
  17784. if (close_time != 0) {
  17785. time_diff = difftime(close_time, start_time);
  17786. gmt_time_string(close_time_str,
  17787. sizeof(close_time_str) - 1,
  17788. &close_time);
  17789. } else {
  17790. time_t now = time(NULL);
  17791. time_diff = difftime(now, start_time);
  17792. close_time_str[0] = 0; /* or use "now" ? */
  17793. }
  17794. mg_snprintf(NULL,
  17795. NULL,
  17796. block,
  17797. sizeof(block),
  17798. "%s%s\"time\" : {%s"
  17799. "\"uptime\" : %.0f,%s"
  17800. "\"start\" : \"%s\",%s"
  17801. "\"closed\" : \"%s\"%s"
  17802. "}",
  17803. (connection_info_length > 1 ? "," : ""),
  17804. eol,
  17805. eol,
  17806. time_diff,
  17807. eol,
  17808. start_time_str,
  17809. eol,
  17810. close_time_str,
  17811. eol);
  17812. connection_info_length += mg_str_append(&buffer, end, block);
  17813. }
  17814. /* Remote user name */
  17815. if ((ri->remote_user) && (state < 9)) {
  17816. mg_snprintf(NULL,
  17817. NULL,
  17818. block,
  17819. sizeof(block),
  17820. "%s%s\"user\" : {%s"
  17821. "\"name\" : \"%s\",%s"
  17822. "}",
  17823. (connection_info_length > 1 ? "," : ""),
  17824. eol,
  17825. eol,
  17826. ri->remote_user,
  17827. eol);
  17828. connection_info_length += mg_str_append(&buffer, end, block);
  17829. }
  17830. /* Data block */
  17831. if (state >= 3) {
  17832. mg_snprintf(NULL,
  17833. NULL,
  17834. block,
  17835. sizeof(block),
  17836. "%s%s\"data\" : {%s"
  17837. "\"read\" : %" INT64_FMT ",%s"
  17838. "\"written\" : %" INT64_FMT "%s"
  17839. "}",
  17840. (connection_info_length > 1 ? "," : ""),
  17841. eol,
  17842. eol,
  17843. conn->consumed_content,
  17844. eol,
  17845. conn->num_bytes_sent,
  17846. eol);
  17847. connection_info_length += mg_str_append(&buffer, end, block);
  17848. }
  17849. /* State */
  17850. mg_snprintf(NULL,
  17851. NULL,
  17852. block,
  17853. sizeof(block),
  17854. "%s%s\"state\" : \"%s\"",
  17855. (connection_info_length > 1 ? "," : ""),
  17856. eol,
  17857. state_str);
  17858. connection_info_length += mg_str_append(&buffer, end, block);
  17859. /* Terminate string */
  17860. if (append_eoobj) {
  17861. strcat(append_eoobj, eoobj);
  17862. }
  17863. connection_info_length += sizeof(eoobj) - 1;
  17864. return (int)connection_info_length;
  17865. }
  17866. #endif
  17867. /* Initialize this library. This function does not need to be thread safe.
  17868. */
  17869. unsigned
  17870. mg_init_library(unsigned features)
  17871. {
  17872. #if !defined(NO_SSL)
  17873. char ebuf[128];
  17874. #endif
  17875. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17876. unsigned features_inited = features_to_init;
  17877. if (mg_init_library_called <= 0) {
  17878. /* Not initialized yet */
  17879. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17880. return 0;
  17881. }
  17882. }
  17883. mg_global_lock();
  17884. if (mg_init_library_called <= 0) {
  17885. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17886. /* Fatal error - abort start. However, this situation should
  17887. * never occur in practice. */
  17888. mg_global_unlock();
  17889. return 0;
  17890. }
  17891. #if defined(_WIN32)
  17892. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  17893. #else
  17894. pthread_mutexattr_init(&pthread_mutex_attr);
  17895. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17896. #endif
  17897. #if defined(USE_LUA)
  17898. lua_init_optional_libraries();
  17899. #endif
  17900. }
  17901. mg_global_unlock();
  17902. #if !defined(NO_SSL)
  17903. if (features_to_init & MG_FEATURES_SSL) {
  17904. if (!mg_ssl_initialized) {
  17905. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17906. mg_ssl_initialized = 1;
  17907. } else {
  17908. (void)ebuf;
  17909. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17910. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17911. }
  17912. } else {
  17913. /* ssl already initialized */
  17914. }
  17915. }
  17916. #endif
  17917. /* Start WinSock for Windows */
  17918. mg_global_lock();
  17919. if (mg_init_library_called <= 0) {
  17920. #if defined(_WIN32)
  17921. WSADATA data;
  17922. WSAStartup(MAKEWORD(2, 2), &data);
  17923. #endif /* _WIN32 */
  17924. mg_init_library_called = 1;
  17925. } else {
  17926. mg_init_library_called++;
  17927. }
  17928. mg_global_unlock();
  17929. return features_inited;
  17930. }
  17931. /* Un-initialize this library. */
  17932. unsigned
  17933. mg_exit_library(void)
  17934. {
  17935. if (mg_init_library_called <= 0) {
  17936. return 0;
  17937. }
  17938. mg_global_lock();
  17939. mg_init_library_called--;
  17940. if (mg_init_library_called == 0) {
  17941. #if defined(_WIN32)
  17942. (void)WSACleanup();
  17943. #endif /* _WIN32 */
  17944. #if !defined(NO_SSL)
  17945. if (mg_ssl_initialized) {
  17946. uninitialize_ssl();
  17947. mg_ssl_initialized = 0;
  17948. }
  17949. #endif
  17950. #if defined(_WIN32)
  17951. (void)pthread_mutex_destroy(&global_log_file_lock);
  17952. #else
  17953. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17954. #endif
  17955. (void)pthread_key_delete(sTlsKey);
  17956. #if defined(USE_LUA)
  17957. lua_exit_optional_libraries();
  17958. #endif
  17959. mg_global_unlock();
  17960. (void)pthread_mutex_destroy(&global_lock_mutex);
  17961. return 1;
  17962. }
  17963. mg_global_unlock();
  17964. return 1;
  17965. }
  17966. /* End of civetweb.c */