civetweb.c 569 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210
  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__) || defined(__sun)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE 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. #ifndef DEBUG_TRACE_STREAM
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #define DEBUG_ASSERT(cond) \
  220. do { \
  221. if (!(cond)) { \
  222. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  223. exit(2); /* Exit with error */ \
  224. } \
  225. } while (0)
  226. #else
  227. #define DEBUG_ASSERT(cond)
  228. #endif /* DEBUG */
  229. #endif
  230. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  231. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  232. __attribute__((no_instrument_function));
  233. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  234. __attribute__((no_instrument_function));
  235. void
  236. __cyg_profile_func_enter(void *this_fn, void *call_site)
  237. {
  238. if ((void *)this_fn != (void *)printf) {
  239. printf("E %p %p\n", this_fn, call_site);
  240. }
  241. }
  242. void
  243. __cyg_profile_func_exit(void *this_fn, void *call_site)
  244. {
  245. if ((void *)this_fn != (void *)printf) {
  246. printf("X %p %p\n", this_fn, call_site);
  247. }
  248. }
  249. #endif
  250. #if !defined(IGNORE_UNUSED_RESULT)
  251. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  252. #endif
  253. #if defined(__GNUC__) || defined(__MINGW32__)
  254. /* GCC unused function attribute seems fundamentally broken.
  255. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  256. * OR UNUSED" for individual functions failed.
  257. * Either the compiler creates an "unused-function" warning if a
  258. * function is not marked with __attribute__((unused)).
  259. * On the other hand, if the function is marked with this attribute,
  260. * but is used, the compiler raises a completely idiotic
  261. * "used-but-marked-unused" warning - and
  262. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  263. * raises error: unknown option after "#pragma GCC diagnostic".
  264. * Disable this warning completely, until the GCC guys sober up
  265. * again.
  266. */
  267. #pragma GCC diagnostic ignored "-Wunused-function"
  268. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  269. #else
  270. #define FUNCTION_MAY_BE_UNUSED
  271. #endif
  272. /* Some ANSI #includes are not available on Windows CE */
  273. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  274. #include <errno.h>
  275. #include <fcntl.h>
  276. #include <signal.h>
  277. #include <stdlib.h>
  278. #include <sys/stat.h>
  279. #include <sys/types.h>
  280. #endif /* !_WIN32_WCE */
  281. #if defined(__clang__)
  282. /* When using -Weverything, clang does not accept it's own headers
  283. * in a release build configuration. Disable what is too much in
  284. * -Weverything. */
  285. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  286. #endif
  287. #if defined(__GNUC__) || defined(__MINGW32__)
  288. /* Who on earth came to the conclusion, using __DATE__ should rise
  289. * an "expansion of date or time macro is not reproducible"
  290. * warning. That's exactly what was intended by using this macro.
  291. * Just disable this nonsense warning. */
  292. /* And disabling them does not work either:
  293. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  294. * #pragma clang diagnostic ignored "-Wdate-time"
  295. * So we just have to disable ALL warnings for some lines
  296. * of code.
  297. * This seems to be a known GCC bug, not resolved since 2012:
  298. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  299. */
  300. #endif
  301. #if defined(__MACH__) /* Apple OSX section */
  302. #if defined(__clang__)
  303. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  304. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  305. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  306. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  307. #endif
  308. #endif
  309. #define CLOCK_MONOTONIC (1)
  310. #define CLOCK_REALTIME (2)
  311. #include <mach/clock.h>
  312. #include <mach/mach.h>
  313. #include <mach/mach_time.h>
  314. #include <sys/errno.h>
  315. #include <sys/time.h>
  316. /* clock_gettime is not implemented on OSX prior to 10.12 */
  317. static int
  318. _civet_clock_gettime(int clk_id, struct timespec *t)
  319. {
  320. memset(t, 0, sizeof(*t));
  321. if (clk_id == CLOCK_REALTIME) {
  322. struct timeval now;
  323. int rv = gettimeofday(&now, NULL);
  324. if (rv) {
  325. return rv;
  326. }
  327. t->tv_sec = now.tv_sec;
  328. t->tv_nsec = now.tv_usec * 1000;
  329. return 0;
  330. } else if (clk_id == CLOCK_MONOTONIC) {
  331. static uint64_t clock_start_time = 0;
  332. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  333. uint64_t now = mach_absolute_time();
  334. if (clock_start_time == 0) {
  335. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  336. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  337. /* appease "unused variable" warning for release builds */
  338. (void)mach_status;
  339. clock_start_time = now;
  340. }
  341. now = (uint64_t)((double)(now - clock_start_time)
  342. * (double)timebase_ifo.numer
  343. / (double)timebase_ifo.denom);
  344. t->tv_sec = now / 1000000000;
  345. t->tv_nsec = now % 1000000000;
  346. return 0;
  347. }
  348. return -1; /* EINVAL - Clock ID is unknown */
  349. }
  350. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  351. #if defined(__CLOCK_AVAILABILITY)
  352. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  353. * declared but it may be NULL at runtime. So we need to check before using
  354. * it. */
  355. static int
  356. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  357. {
  358. if (clock_gettime) {
  359. return clock_gettime(clk_id, t);
  360. }
  361. return _civet_clock_gettime(clk_id, t);
  362. }
  363. #define clock_gettime _civet_safe_clock_gettime
  364. #else
  365. #define clock_gettime _civet_clock_gettime
  366. #endif
  367. #endif
  368. /********************************************************************/
  369. /* CivetWeb configuration defines */
  370. /********************************************************************/
  371. /* Maximum number of threads that can be configured.
  372. * The number of threads actually created depends on the "num_threads"
  373. * configuration parameter, but this is the upper limit. */
  374. #if !defined(MAX_WORKER_THREADS)
  375. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  376. #endif
  377. /* Timeout interval for select/poll calls.
  378. * The timeouts depend on "*_timeout_ms" configuration values, but long
  379. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  380. * This reduces the time required to stop the server. */
  381. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  382. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  383. #endif
  384. /* Do not try to compress files smaller than this limit. */
  385. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  386. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  387. #endif
  388. #if !defined(PASSWORDS_FILE_NAME)
  389. #define PASSWORDS_FILE_NAME ".htpasswd"
  390. #endif
  391. /* Initial buffer size for all CGI environment variables. In case there is
  392. * not enough space, another block is allocated. */
  393. #if !defined(CGI_ENVIRONMENT_SIZE)
  394. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  395. #endif
  396. /* Maximum number of environment variables. */
  397. #if !defined(MAX_CGI_ENVIR_VARS)
  398. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  399. #endif
  400. /* General purpose buffer size. */
  401. #if !defined(MG_BUF_LEN) /* in bytes */
  402. #define MG_BUF_LEN (1024 * 8)
  403. #endif
  404. /********************************************************************/
  405. /* Helper makros */
  406. #if !defined(ARRAY_SIZE)
  407. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  408. #endif
  409. #include <stdint.h>
  410. /* Standard defines */
  411. #if !defined(INT64_MAX)
  412. #define INT64_MAX (9223372036854775807)
  413. #endif
  414. #define SHUTDOWN_RD (0)
  415. #define SHUTDOWN_WR (1)
  416. #define SHUTDOWN_BOTH (2)
  417. mg_static_assert(MAX_WORKER_THREADS >= 1,
  418. "worker threads must be a positive number");
  419. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  420. "size_t data type size check");
  421. #if defined(_WIN32) /* WINDOWS include block */
  422. #include <malloc.h> /* *alloc( */
  423. #include <stdlib.h> /* *alloc( */
  424. #include <time.h> /* struct timespec */
  425. #include <windows.h>
  426. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  427. #include <ws2tcpip.h>
  428. typedef const char *SOCK_OPT_TYPE;
  429. #if !defined(PATH_MAX)
  430. #define W_PATH_MAX (MAX_PATH)
  431. /* at most three UTF-8 chars per wchar_t */
  432. #define PATH_MAX (W_PATH_MAX * 3)
  433. #else
  434. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  435. #endif
  436. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  437. #if !defined(_IN_PORT_T)
  438. #if !defined(in_port_t)
  439. #define in_port_t u_short
  440. #endif
  441. #endif
  442. #if !defined(_WIN32_WCE)
  443. #include <direct.h>
  444. #include <io.h>
  445. #include <process.h>
  446. #else /* _WIN32_WCE */
  447. #define NO_CGI /* WinCE has no pipes */
  448. #define NO_POPEN /* WinCE has no popen */
  449. typedef long off_t;
  450. #define errno ((int)(GetLastError()))
  451. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  452. #endif /* _WIN32_WCE */
  453. #define MAKEUQUAD(lo, hi) \
  454. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  455. #define RATE_DIFF (10000000) /* 100 nsecs */
  456. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  457. #define SYS2UNIX_TIME(lo, hi) \
  458. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  459. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  460. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  461. * Also use _strtoui64 on modern M$ compilers */
  462. #if defined(_MSC_VER)
  463. #if (_MSC_VER < 1300)
  464. #define STRX(x) #x
  465. #define STR(x) STRX(x)
  466. #define __func__ __FILE__ ":" STR(__LINE__)
  467. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  468. #define strtoll(x, y, z) (_atoi64(x))
  469. #else
  470. #define __func__ __FUNCTION__
  471. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  472. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  473. #endif
  474. #endif /* _MSC_VER */
  475. #define ERRNO ((int)(GetLastError()))
  476. #define NO_SOCKLEN_T
  477. #if defined(_WIN64) || defined(__MINGW64__)
  478. #if !defined(SSL_LIB)
  479. #if defined(OPENSSL_API_1_1)
  480. #define SSL_LIB "libssl-1_1-x64.dll"
  481. #else /* OPENSSL_API_1_1 */
  482. #define SSL_LIB "ssleay64.dll"
  483. #endif /* OPENSSL_API_1_1 */
  484. #endif /* SSL_LIB */
  485. #if !defined(CRYPTO_LIB)
  486. #if defined(OPENSSL_API_1_1)
  487. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  488. #else /* OPENSSL_API_1_1 */
  489. #define CRYPTO_LIB "libeay64.dll"
  490. #endif /* OPENSSL_API_1_1 */
  491. #endif /* CRYPTO_LIB */
  492. #else /* defined(_WIN64) || defined(__MINGW64__) */
  493. #if !defined(SSL_LIB)
  494. #if defined(OPENSSL_API_1_1)
  495. #define SSL_LIB "libssl-1_1.dll"
  496. #else
  497. #define SSL_LIB "ssleay32.dll"
  498. #endif
  499. #endif /* SSL_LIB */
  500. #if !defined(CRYPTO_LIB)
  501. #if defined(OPENSSL_API_1_1)
  502. #define CRYPTO_LIB "libcrypto-1_1.dll"
  503. #else
  504. #define CRYPTO_LIB "libeay32.dll"
  505. #endif
  506. #endif /* CRYPTO_LIB */
  507. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  508. #define O_NONBLOCK (0)
  509. #if !defined(W_OK)
  510. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  511. #endif
  512. #define _POSIX_
  513. #define INT64_FMT "I64d"
  514. #define UINT64_FMT "I64u"
  515. #define WINCDECL __cdecl
  516. #define vsnprintf_impl _vsnprintf
  517. #define access _access
  518. #define mg_sleep(x) (Sleep(x))
  519. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  520. #if !defined(popen)
  521. #define popen(x, y) (_popen(x, y))
  522. #endif
  523. #if !defined(pclose)
  524. #define pclose(x) (_pclose(x))
  525. #endif
  526. #define close(x) (_close(x))
  527. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  528. #define RTLD_LAZY (0)
  529. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  530. #define fdopen(x, y) (_fdopen((x), (y)))
  531. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  532. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  533. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  534. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  535. #define sleep(x) (Sleep((x)*1000))
  536. #define rmdir(x) (_rmdir(x))
  537. #if defined(_WIN64) || !defined(__MINGW32__)
  538. /* Only MinGW 32 bit is missing this function */
  539. #define timegm(x) (_mkgmtime(x))
  540. #else
  541. time_t timegm(struct tm *tm);
  542. #define NEED_TIMEGM
  543. #endif
  544. #if !defined(fileno)
  545. #define fileno(x) (_fileno(x))
  546. #endif /* !fileno MINGW #defines fileno */
  547. typedef struct {
  548. CRITICAL_SECTION sec; /* Immovable */
  549. } pthread_mutex_t;
  550. typedef DWORD pthread_key_t;
  551. typedef HANDLE pthread_t;
  552. typedef struct {
  553. pthread_mutex_t threadIdSec;
  554. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  555. } pthread_cond_t;
  556. #if !defined(__clockid_t_defined)
  557. typedef DWORD clockid_t;
  558. #endif
  559. #if !defined(CLOCK_MONOTONIC)
  560. #define CLOCK_MONOTONIC (1)
  561. #endif
  562. #if !defined(CLOCK_REALTIME)
  563. #define CLOCK_REALTIME (2)
  564. #endif
  565. #if !defined(CLOCK_THREAD)
  566. #define CLOCK_THREAD (3)
  567. #endif
  568. #if !defined(CLOCK_PROCESS)
  569. #define CLOCK_PROCESS (4)
  570. #endif
  571. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  572. #define _TIMESPEC_DEFINED
  573. #endif
  574. #if !defined(_TIMESPEC_DEFINED)
  575. struct timespec {
  576. time_t tv_sec; /* seconds */
  577. long tv_nsec; /* nanoseconds */
  578. };
  579. #endif
  580. #if !defined(WIN_PTHREADS_TIME_H)
  581. #define MUST_IMPLEMENT_CLOCK_GETTIME
  582. #endif
  583. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  584. #define clock_gettime mg_clock_gettime
  585. static int
  586. clock_gettime(clockid_t clk_id, struct timespec *tp)
  587. {
  588. FILETIME ft;
  589. ULARGE_INTEGER li, li2;
  590. BOOL ok = FALSE;
  591. double d;
  592. static double perfcnt_per_sec = 0.0;
  593. static BOOL initialized = FALSE;
  594. if (!initialized) {
  595. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  596. perfcnt_per_sec = 1.0 / li.QuadPart;
  597. initialized = TRUE;
  598. }
  599. if (tp) {
  600. memset(tp, 0, sizeof(*tp));
  601. if (clk_id == CLOCK_REALTIME) {
  602. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  603. GetSystemTimeAsFileTime(&ft);
  604. li.LowPart = ft.dwLowDateTime;
  605. li.HighPart = ft.dwHighDateTime;
  606. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  607. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  608. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  609. ok = TRUE;
  610. /* END: CLOCK_REALTIME */
  611. } else if (clk_id == CLOCK_MONOTONIC) {
  612. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  613. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  614. d = li.QuadPart * perfcnt_per_sec;
  615. tp->tv_sec = (time_t)d;
  616. d -= (double)tp->tv_sec;
  617. tp->tv_nsec = (long)(d * 1.0E9);
  618. ok = TRUE;
  619. /* END: CLOCK_MONOTONIC */
  620. } else if (clk_id == CLOCK_THREAD) {
  621. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  622. FILETIME t_create, t_exit, t_kernel, t_user;
  623. if (GetThreadTimes(GetCurrentThread(),
  624. &t_create,
  625. &t_exit,
  626. &t_kernel,
  627. &t_user)) {
  628. li.LowPart = t_user.dwLowDateTime;
  629. li.HighPart = t_user.dwHighDateTime;
  630. li2.LowPart = t_kernel.dwLowDateTime;
  631. li2.HighPart = t_kernel.dwHighDateTime;
  632. li.QuadPart += li2.QuadPart;
  633. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  634. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  635. ok = TRUE;
  636. }
  637. /* END: CLOCK_THREAD */
  638. } else if (clk_id == CLOCK_PROCESS) {
  639. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  640. FILETIME t_create, t_exit, t_kernel, t_user;
  641. if (GetProcessTimes(GetCurrentProcess(),
  642. &t_create,
  643. &t_exit,
  644. &t_kernel,
  645. &t_user)) {
  646. li.LowPart = t_user.dwLowDateTime;
  647. li.HighPart = t_user.dwHighDateTime;
  648. li2.LowPart = t_kernel.dwLowDateTime;
  649. li2.HighPart = t_kernel.dwHighDateTime;
  650. li.QuadPart += li2.QuadPart;
  651. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  652. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  653. ok = TRUE;
  654. }
  655. /* END: CLOCK_PROCESS */
  656. } else {
  657. /* BEGIN: unknown clock */
  658. /* ok = FALSE; already set by init */
  659. /* END: unknown clock */
  660. }
  661. }
  662. return ok ? 0 : -1;
  663. }
  664. #endif
  665. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  666. static int pthread_mutex_lock(pthread_mutex_t *);
  667. static int pthread_mutex_unlock(pthread_mutex_t *);
  668. static void path_to_unicode(const struct mg_connection *conn,
  669. const char *path,
  670. wchar_t *wbuf,
  671. size_t wbuf_len);
  672. /* All file operations need to be rewritten to solve #246. */
  673. struct mg_file;
  674. static const char *
  675. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  676. /* POSIX dirent interface */
  677. struct dirent {
  678. char d_name[PATH_MAX];
  679. };
  680. typedef struct DIR {
  681. HANDLE handle;
  682. WIN32_FIND_DATAW info;
  683. struct dirent result;
  684. } DIR;
  685. #if defined(HAVE_POLL)
  686. #define mg_pollfd pollfd
  687. #else
  688. struct mg_pollfd {
  689. SOCKET fd;
  690. short events;
  691. short revents;
  692. };
  693. #endif
  694. /* Mark required libraries */
  695. #if defined(_MSC_VER)
  696. #pragma comment(lib, "Ws2_32.lib")
  697. #endif
  698. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  699. #include <inttypes.h>
  700. typedef const void *SOCK_OPT_TYPE;
  701. #if defined(ANDROID)
  702. typedef unsigned short int in_port_t;
  703. #endif
  704. #if !defined(__ZEPHYR__)
  705. #include <arpa/inet.h>
  706. #include <ctype.h>
  707. #include <dirent.h>
  708. #include <grp.h>
  709. #include <limits.h>
  710. #include <netdb.h>
  711. #include <netinet/in.h>
  712. #include <netinet/tcp.h>
  713. #include <pthread.h>
  714. #include <pwd.h>
  715. #include <stdarg.h>
  716. #include <stddef.h>
  717. #include <stdio.h>
  718. #include <stdlib.h>
  719. #include <string.h>
  720. #include <sys/poll.h>
  721. #include <sys/socket.h>
  722. #include <sys/time.h>
  723. #include <sys/utsname.h>
  724. #include <sys/wait.h>
  725. #include <time.h>
  726. #include <unistd.h>
  727. #endif
  728. #define vsnprintf_impl vsnprintf
  729. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  730. #include <dlfcn.h>
  731. #endif
  732. #if defined(__MACH__)
  733. #define SSL_LIB "libssl.dylib"
  734. #define CRYPTO_LIB "libcrypto.dylib"
  735. #else
  736. #if !defined(SSL_LIB)
  737. #define SSL_LIB "libssl.so"
  738. #endif
  739. #if !defined(CRYPTO_LIB)
  740. #define CRYPTO_LIB "libcrypto.so"
  741. #endif
  742. #endif
  743. #if !defined(O_BINARY)
  744. #define O_BINARY (0)
  745. #endif /* O_BINARY */
  746. #define closesocket(a) (close(a))
  747. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  748. #define mg_remove(conn, x) (remove(x))
  749. #define mg_sleep(x) (usleep((x)*1000))
  750. #define mg_opendir(conn, x) (opendir(x))
  751. #define mg_closedir(x) (closedir(x))
  752. #define mg_readdir(x) (readdir(x))
  753. #define ERRNO (errno)
  754. #define INVALID_SOCKET (-1)
  755. #define INT64_FMT PRId64
  756. #define UINT64_FMT PRIu64
  757. typedef int SOCKET;
  758. #define WINCDECL
  759. #if defined(__hpux)
  760. /* HPUX 11 does not have monotonic, fall back to realtime */
  761. #if !defined(CLOCK_MONOTONIC)
  762. #define CLOCK_MONOTONIC CLOCK_REALTIME
  763. #endif
  764. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  765. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  766. * the prototypes use int* rather than socklen_t* which matches the
  767. * actual library expectation. When called with the wrong size arg
  768. * accept() returns a zero client inet addr and check_acl() always
  769. * fails. Since socklen_t is widely used below, just force replace
  770. * their typedef with int. - DTL
  771. */
  772. #define socklen_t int
  773. #endif /* hpux */
  774. #define mg_pollfd pollfd
  775. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  776. /* In case our C library is missing "timegm", provide an implementation */
  777. #if defined(NEED_TIMEGM)
  778. static inline int
  779. is_leap(int y)
  780. {
  781. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  782. }
  783. static inline int
  784. count_leap(int y)
  785. {
  786. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  787. }
  788. time_t
  789. timegm(struct tm *tm)
  790. {
  791. static const unsigned short ydays[] = {
  792. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  793. int year = tm->tm_year + 1900;
  794. int mon = tm->tm_mon;
  795. int mday = tm->tm_mday - 1;
  796. int hour = tm->tm_hour;
  797. int min = tm->tm_min;
  798. int sec = tm->tm_sec;
  799. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  800. || (mday >= ydays[mon + 1] - ydays[mon]
  801. + (mon == 1 && is_leap(year) ? 1 : 0))
  802. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  803. return -1;
  804. time_t res = year - 1970;
  805. res *= 365;
  806. res += mday;
  807. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  808. res += count_leap(year);
  809. res *= 24;
  810. res += hour;
  811. res *= 60;
  812. res += min;
  813. res *= 60;
  814. res += sec;
  815. return res;
  816. }
  817. #endif /* NEED_TIMEGM */
  818. /* va_copy should always be a macro, C99 and C++11 - DTL */
  819. #if !defined(va_copy)
  820. #define va_copy(x, y) ((x) = (y))
  821. #endif
  822. #if defined(_WIN32)
  823. /* Create substitutes for POSIX functions in Win32. */
  824. #if defined(GCC_DIAGNOSTIC)
  825. /* Show no warning in case system functions are not used. */
  826. #pragma GCC diagnostic push
  827. #pragma GCC diagnostic ignored "-Wunused-function"
  828. #endif
  829. static pthread_mutex_t global_log_file_lock;
  830. FUNCTION_MAY_BE_UNUSED
  831. static DWORD
  832. pthread_self(void)
  833. {
  834. return GetCurrentThreadId();
  835. }
  836. FUNCTION_MAY_BE_UNUSED
  837. static int
  838. pthread_key_create(
  839. pthread_key_t *key,
  840. void (*_ignored)(void *) /* destructor not supported for Windows */
  841. )
  842. {
  843. (void)_ignored;
  844. if ((key != 0)) {
  845. *key = TlsAlloc();
  846. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  847. }
  848. return -2;
  849. }
  850. FUNCTION_MAY_BE_UNUSED
  851. static int
  852. pthread_key_delete(pthread_key_t key)
  853. {
  854. return TlsFree(key) ? 0 : 1;
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static int
  858. pthread_setspecific(pthread_key_t key, void *value)
  859. {
  860. return TlsSetValue(key, value) ? 0 : 1;
  861. }
  862. FUNCTION_MAY_BE_UNUSED
  863. static void *
  864. pthread_getspecific(pthread_key_t key)
  865. {
  866. return TlsGetValue(key);
  867. }
  868. #if defined(GCC_DIAGNOSTIC)
  869. /* Enable unused function warning again */
  870. #pragma GCC diagnostic pop
  871. #endif
  872. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  873. #else
  874. static pthread_mutexattr_t pthread_mutex_attr;
  875. #endif /* _WIN32 */
  876. #if defined(_WIN32_WCE)
  877. /* Create substitutes for POSIX functions in Win32. */
  878. #if defined(GCC_DIAGNOSTIC)
  879. /* Show no warning in case system functions are not used. */
  880. #pragma GCC diagnostic push
  881. #pragma GCC diagnostic ignored "-Wunused-function"
  882. #endif
  883. FUNCTION_MAY_BE_UNUSED
  884. static time_t
  885. time(time_t *ptime)
  886. {
  887. time_t t;
  888. SYSTEMTIME st;
  889. FILETIME ft;
  890. GetSystemTime(&st);
  891. SystemTimeToFileTime(&st, &ft);
  892. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  893. if (ptime != NULL) {
  894. *ptime = t;
  895. }
  896. return t;
  897. }
  898. FUNCTION_MAY_BE_UNUSED
  899. static struct tm *
  900. localtime_s(const time_t *ptime, struct tm *ptm)
  901. {
  902. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  903. FILETIME ft, lft;
  904. SYSTEMTIME st;
  905. TIME_ZONE_INFORMATION tzinfo;
  906. if (ptm == NULL) {
  907. return NULL;
  908. }
  909. *(int64_t *)&ft = t;
  910. FileTimeToLocalFileTime(&ft, &lft);
  911. FileTimeToSystemTime(&lft, &st);
  912. ptm->tm_year = st.wYear - 1900;
  913. ptm->tm_mon = st.wMonth - 1;
  914. ptm->tm_wday = st.wDayOfWeek;
  915. ptm->tm_mday = st.wDay;
  916. ptm->tm_hour = st.wHour;
  917. ptm->tm_min = st.wMinute;
  918. ptm->tm_sec = st.wSecond;
  919. ptm->tm_yday = 0; /* hope nobody uses this */
  920. ptm->tm_isdst =
  921. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  922. return ptm;
  923. }
  924. FUNCTION_MAY_BE_UNUSED
  925. static struct tm *
  926. gmtime_s(const time_t *ptime, struct tm *ptm)
  927. {
  928. /* FIXME(lsm): fix this. */
  929. return localtime_s(ptime, ptm);
  930. }
  931. static ptrdiff_t mg_atomic_inc(volatile ptrdiff_t *addr);
  932. static struct tm tm_array[MAX_WORKER_THREADS]; /* Must be 2^n */
  933. static volatile ptrdiff_t tm_index = 0;
  934. FUNCTION_MAY_BE_UNUSED
  935. static struct tm *
  936. localtime(const time_t *ptime)
  937. {
  938. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  939. return localtime_s(ptime, tm_array + i);
  940. }
  941. FUNCTION_MAY_BE_UNUSED
  942. static struct tm *
  943. gmtime(const time_t *ptime)
  944. {
  945. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  946. return gmtime_s(ptime, tm_array + i);
  947. }
  948. FUNCTION_MAY_BE_UNUSED
  949. static size_t
  950. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  951. {
  952. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  953. * for WinCE"); */
  954. return 0;
  955. }
  956. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  957. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  958. #define remove(f) mg_remove(NULL, f)
  959. FUNCTION_MAY_BE_UNUSED
  960. static int
  961. rename(const char *a, const char *b)
  962. {
  963. wchar_t wa[W_PATH_MAX];
  964. wchar_t wb[W_PATH_MAX];
  965. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  966. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  967. return MoveFileW(wa, wb) ? 0 : -1;
  968. }
  969. struct stat {
  970. int64_t st_size;
  971. time_t st_mtime;
  972. };
  973. FUNCTION_MAY_BE_UNUSED
  974. static int
  975. stat(const char *name, struct stat *st)
  976. {
  977. wchar_t wbuf[W_PATH_MAX];
  978. WIN32_FILE_ATTRIBUTE_DATA attr;
  979. time_t creation_time, write_time;
  980. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  981. memset(&attr, 0, sizeof(attr));
  982. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  983. st->st_size =
  984. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  985. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  986. attr.ftLastWriteTime.dwHighDateTime);
  987. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  988. attr.ftCreationTime.dwHighDateTime);
  989. if (creation_time > write_time) {
  990. st->st_mtime = creation_time;
  991. } else {
  992. st->st_mtime = write_time;
  993. }
  994. return 0;
  995. }
  996. #define access(x, a) 1 /* not required anyway */
  997. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  998. /* Values from errno.h in Windows SDK (Visual Studio). */
  999. #define EEXIST 17
  1000. #define EACCES 13
  1001. #define ENOENT 2
  1002. #if defined(GCC_DIAGNOSTIC)
  1003. /* Enable unused function warning again */
  1004. #pragma GCC diagnostic pop
  1005. #endif
  1006. #endif /* defined(_WIN32_WCE) */
  1007. #if defined(GCC_DIAGNOSTIC)
  1008. /* Show no warning in case system functions are not used. */
  1009. #pragma GCC diagnostic push
  1010. #pragma GCC diagnostic ignored "-Wunused-function"
  1011. #endif /* defined(GCC_DIAGNOSTIC) */
  1012. #if defined(__clang__)
  1013. /* Show no warning in case system functions are not used. */
  1014. #pragma clang diagnostic push
  1015. #pragma clang diagnostic ignored "-Wunused-function"
  1016. #endif
  1017. static pthread_mutex_t global_lock_mutex;
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static void
  1020. mg_global_lock(void)
  1021. {
  1022. (void)pthread_mutex_lock(&global_lock_mutex);
  1023. }
  1024. FUNCTION_MAY_BE_UNUSED
  1025. static void
  1026. mg_global_unlock(void)
  1027. {
  1028. (void)pthread_mutex_unlock(&global_lock_mutex);
  1029. }
  1030. #if defined(_WIN64)
  1031. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  1032. #elif defined(_WIN32)
  1033. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  1034. #endif
  1035. /* Atomic functions working on ptrdiff_t ("signed size_t").
  1036. * Operations: Increment, Decrement, Add, Maximum.
  1037. * Up to size_t, they do not an atomic "load" operation.
  1038. */
  1039. FUNCTION_MAY_BE_UNUSED
  1040. static ptrdiff_t
  1041. mg_atomic_inc(volatile ptrdiff_t *addr)
  1042. {
  1043. ptrdiff_t ret;
  1044. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1045. ret = InterlockedIncrement64(addr);
  1046. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1047. ret = InterlockedIncrement(addr);
  1048. #elif defined(__GNUC__) \
  1049. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1050. && !defined(NO_ATOMICS)
  1051. ret = __sync_add_and_fetch(addr, 1);
  1052. #else
  1053. mg_global_lock();
  1054. ret = (++(*addr));
  1055. mg_global_unlock();
  1056. #endif
  1057. return ret;
  1058. }
  1059. FUNCTION_MAY_BE_UNUSED
  1060. static ptrdiff_t
  1061. mg_atomic_dec(volatile ptrdiff_t *addr)
  1062. {
  1063. ptrdiff_t ret;
  1064. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1065. ret = InterlockedDecrement64(addr);
  1066. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1067. ret = InterlockedDecrement(addr);
  1068. #elif defined(__GNUC__) \
  1069. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1070. && !defined(NO_ATOMICS)
  1071. ret = __sync_sub_and_fetch(addr, 1);
  1072. #else
  1073. mg_global_lock();
  1074. ret = (--(*addr));
  1075. mg_global_unlock();
  1076. #endif
  1077. return ret;
  1078. }
  1079. #if defined(USE_SERVER_STATS)
  1080. static ptrdiff_t
  1081. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1082. {
  1083. ptrdiff_t ret;
  1084. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1085. ret = InterlockedAdd64(addr, value);
  1086. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1087. ret = InterlockedAdd(addr, value);
  1088. #elif defined(__GNUC__) \
  1089. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1090. && !defined(NO_ATOMICS)
  1091. ret = __sync_add_and_fetch(addr, value);
  1092. #else
  1093. mg_global_lock();
  1094. *addr += value;
  1095. ret = (*addr);
  1096. mg_global_unlock();
  1097. #endif
  1098. return ret;
  1099. }
  1100. static void
  1101. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1102. {
  1103. ptrdiff_t register tmp = *addr;
  1104. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1105. while (tmp < value) {
  1106. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1107. }
  1108. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1109. while (tmp < value) {
  1110. tmp = InterlockedCompareExchange(addr, value, tmp);
  1111. }
  1112. #elif defined(__GNUC__) \
  1113. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1114. && !defined(NO_ATOMICS)
  1115. while (tmp < value) {
  1116. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1117. }
  1118. #else
  1119. mg_global_lock();
  1120. if (*addr < value) {
  1121. *addr = value;
  1122. }
  1123. mg_global_unlock();
  1124. #endif
  1125. }
  1126. static int64_t
  1127. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1128. {
  1129. int64_t ret;
  1130. #if (defined(_WIN64) || defined(_WIN32)) && !defined(NO_ATOMICS)
  1131. ret = InterlockedAdd64(addr, value);
  1132. #elif defined(__GNUC__) \
  1133. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1134. && !defined(NO_ATOMICS)
  1135. ret = __sync_add_and_fetch(addr, value);
  1136. #else
  1137. mg_global_lock();
  1138. *addr += value;
  1139. ret = (*addr);
  1140. mg_global_unlock();
  1141. #endif
  1142. return ret;
  1143. }
  1144. #endif
  1145. #if defined(GCC_DIAGNOSTIC)
  1146. /* Show no warning in case system functions are not used. */
  1147. #pragma GCC diagnostic pop
  1148. #endif /* defined(GCC_DIAGNOSTIC) */
  1149. #if defined(__clang__)
  1150. /* Show no warning in case system functions are not used. */
  1151. #pragma clang diagnostic pop
  1152. #endif
  1153. #if defined(USE_SERVER_STATS)
  1154. struct mg_memory_stat {
  1155. volatile ptrdiff_t totalMemUsed;
  1156. volatile ptrdiff_t maxMemUsed;
  1157. volatile ptrdiff_t blockCount;
  1158. };
  1159. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1160. static void *
  1161. mg_malloc_ex(size_t size,
  1162. struct mg_context *ctx,
  1163. const char *file,
  1164. unsigned line)
  1165. {
  1166. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1167. void *memory = 0;
  1168. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1169. #if defined(MEMORY_DEBUGGING)
  1170. char mallocStr[256];
  1171. #else
  1172. (void)file;
  1173. (void)line;
  1174. #endif
  1175. if (data) {
  1176. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1177. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1178. mg_atomic_inc(&mstat->blockCount);
  1179. ((uintptr_t *)data)[0] = size;
  1180. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1181. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1182. }
  1183. #if defined(MEMORY_DEBUGGING)
  1184. sprintf(mallocStr,
  1185. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1186. memory,
  1187. (unsigned long)size,
  1188. (unsigned long)mstat->totalMemUsed,
  1189. (unsigned long)mstat->blockCount,
  1190. file,
  1191. line);
  1192. #if defined(_WIN32)
  1193. OutputDebugStringA(mallocStr);
  1194. #else
  1195. DEBUG_TRACE("%s", mallocStr);
  1196. #endif
  1197. #endif
  1198. return memory;
  1199. }
  1200. static void *
  1201. mg_calloc_ex(size_t count,
  1202. size_t size,
  1203. struct mg_context *ctx,
  1204. const char *file,
  1205. unsigned line)
  1206. {
  1207. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1208. if (data) {
  1209. memset(data, 0, size * count);
  1210. }
  1211. return data;
  1212. }
  1213. static void
  1214. mg_free_ex(void *memory, const char *file, unsigned line)
  1215. {
  1216. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1217. #if defined(MEMORY_DEBUGGING)
  1218. char mallocStr[256];
  1219. #else
  1220. (void)file;
  1221. (void)line;
  1222. #endif
  1223. if (memory) {
  1224. uintptr_t size = ((uintptr_t *)data)[0];
  1225. struct mg_memory_stat *mstat =
  1226. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1227. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1228. mg_atomic_dec(&mstat->blockCount);
  1229. #if defined(MEMORY_DEBUGGING)
  1230. sprintf(mallocStr,
  1231. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1232. memory,
  1233. (unsigned long)size,
  1234. (unsigned long)mstat->totalMemUsed,
  1235. (unsigned long)mstat->blockCount,
  1236. file,
  1237. line);
  1238. #if defined(_WIN32)
  1239. OutputDebugStringA(mallocStr);
  1240. #else
  1241. DEBUG_TRACE("%s", mallocStr);
  1242. #endif
  1243. #endif
  1244. free(data);
  1245. }
  1246. }
  1247. static void *
  1248. mg_realloc_ex(void *memory,
  1249. size_t newsize,
  1250. struct mg_context *ctx,
  1251. const char *file,
  1252. unsigned line)
  1253. {
  1254. void *data;
  1255. void *_realloc;
  1256. uintptr_t oldsize;
  1257. #if defined(MEMORY_DEBUGGING)
  1258. char mallocStr[256];
  1259. #else
  1260. (void)file;
  1261. (void)line;
  1262. #endif
  1263. if (newsize) {
  1264. if (memory) {
  1265. /* Reallocate existing block */
  1266. struct mg_memory_stat *mstat;
  1267. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1268. oldsize = ((uintptr_t *)data)[0];
  1269. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1270. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1271. if (_realloc) {
  1272. data = _realloc;
  1273. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1274. #if defined(MEMORY_DEBUGGING)
  1275. sprintf(mallocStr,
  1276. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1277. memory,
  1278. (unsigned long)oldsize,
  1279. (unsigned long)mstat->totalMemUsed,
  1280. (unsigned long)mstat->blockCount,
  1281. file,
  1282. line);
  1283. #if defined(_WIN32)
  1284. OutputDebugStringA(mallocStr);
  1285. #else
  1286. DEBUG_TRACE("%s", mallocStr);
  1287. #endif
  1288. #endif
  1289. mg_atomic_add(&mstat->totalMemUsed, newsize);
  1290. #if defined(MEMORY_DEBUGGING)
  1291. sprintf(mallocStr,
  1292. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1293. memory,
  1294. (unsigned long)newsize,
  1295. (unsigned long)mstat->totalMemUsed,
  1296. (unsigned long)mstat->blockCount,
  1297. file,
  1298. line);
  1299. #if defined(_WIN32)
  1300. OutputDebugStringA(mallocStr);
  1301. #else
  1302. DEBUG_TRACE("%s", mallocStr);
  1303. #endif
  1304. #endif
  1305. *(uintptr_t *)data = newsize;
  1306. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1307. } else {
  1308. #if defined(MEMORY_DEBUGGING)
  1309. #if defined(_WIN32)
  1310. OutputDebugStringA("MEM: realloc failed\n");
  1311. #else
  1312. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1313. #endif
  1314. #endif
  1315. return _realloc;
  1316. }
  1317. } else {
  1318. /* Allocate new block */
  1319. data = mg_malloc_ex(newsize, ctx, file, line);
  1320. }
  1321. } else {
  1322. /* Free existing block */
  1323. data = 0;
  1324. mg_free_ex(memory, file, line);
  1325. }
  1326. return data;
  1327. }
  1328. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1329. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1330. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1331. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1332. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1333. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1334. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1335. #else /* USE_SERVER_STATS */
  1336. static __inline void *
  1337. mg_malloc(size_t a)
  1338. {
  1339. return malloc(a);
  1340. }
  1341. static __inline void *
  1342. mg_calloc(size_t a, size_t b)
  1343. {
  1344. return calloc(a, b);
  1345. }
  1346. static __inline void *
  1347. mg_realloc(void *a, size_t b)
  1348. {
  1349. return realloc(a, b);
  1350. }
  1351. static __inline void
  1352. mg_free(void *a)
  1353. {
  1354. free(a);
  1355. }
  1356. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1357. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1358. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1359. #define mg_free_ctx(a, c) mg_free(a)
  1360. #endif /* USE_SERVER_STATS */
  1361. static void mg_vsnprintf(const struct mg_connection *conn,
  1362. int *truncated,
  1363. char *buf,
  1364. size_t buflen,
  1365. const char *fmt,
  1366. va_list ap);
  1367. static void mg_snprintf(const struct mg_connection *conn,
  1368. int *truncated,
  1369. char *buf,
  1370. size_t buflen,
  1371. PRINTF_FORMAT_STRING(const char *fmt),
  1372. ...) PRINTF_ARGS(5, 6);
  1373. /* This following lines are just meant as a reminder to use the mg-functions
  1374. * for memory management */
  1375. #if defined(malloc)
  1376. #undef malloc
  1377. #endif
  1378. #if defined(calloc)
  1379. #undef calloc
  1380. #endif
  1381. #if defined(realloc)
  1382. #undef realloc
  1383. #endif
  1384. #if defined(free)
  1385. #undef free
  1386. #endif
  1387. #if defined(snprintf)
  1388. #undef snprintf
  1389. #endif
  1390. #if defined(vsnprintf)
  1391. #undef vsnprintf
  1392. #endif
  1393. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1394. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1395. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1396. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1397. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1398. #if defined(_WIN32)
  1399. /* vsnprintf must not be used in any system,
  1400. * but this define only works well for Windows. */
  1401. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1402. #endif
  1403. /* mg_init_library counter */
  1404. static int mg_init_library_called = 0;
  1405. #if !defined(NO_SSL)
  1406. static int mg_ssl_initialized = 0;
  1407. #endif
  1408. static pthread_key_t sTlsKey; /* Thread local storage index */
  1409. static volatile ptrdiff_t thread_idx_max = 0;
  1410. #if defined(MG_LEGACY_INTERFACE)
  1411. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1412. #endif
  1413. struct mg_workerTLS {
  1414. int is_master;
  1415. unsigned long thread_idx;
  1416. void *user_ptr;
  1417. #if defined(_WIN32)
  1418. HANDLE pthread_cond_helper_mutex;
  1419. struct mg_workerTLS *next_waiting_thread;
  1420. #endif
  1421. const char *alpn_proto;
  1422. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1423. char txtbuf[4];
  1424. #endif
  1425. };
  1426. #if defined(GCC_DIAGNOSTIC)
  1427. /* Show no warning in case system functions are not used. */
  1428. #pragma GCC diagnostic push
  1429. #pragma GCC diagnostic ignored "-Wunused-function"
  1430. #endif /* defined(GCC_DIAGNOSTIC) */
  1431. #if defined(__clang__)
  1432. /* Show no warning in case system functions are not used. */
  1433. #pragma clang diagnostic push
  1434. #pragma clang diagnostic ignored "-Wunused-function"
  1435. #endif
  1436. /* Get a unique thread ID as unsigned long, independent from the data type
  1437. * of thread IDs defined by the operating system API.
  1438. * If two calls to mg_current_thread_id return the same value, they calls
  1439. * are done from the same thread. If they return different values, they are
  1440. * done from different threads. (Provided this function is used in the same
  1441. * process context and threads are not repeatedly created and deleted, but
  1442. * CivetWeb does not do that).
  1443. * This function must match the signature required for SSL id callbacks:
  1444. * CRYPTO_set_id_callback
  1445. */
  1446. FUNCTION_MAY_BE_UNUSED
  1447. static unsigned long
  1448. mg_current_thread_id(void)
  1449. {
  1450. #if defined(_WIN32)
  1451. return GetCurrentThreadId();
  1452. #else
  1453. #if defined(__clang__)
  1454. #pragma clang diagnostic push
  1455. #pragma clang diagnostic ignored "-Wunreachable-code"
  1456. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1457. * or not, so one of the two conditions will be unreachable by construction.
  1458. * Unfortunately the C standard does not define a way to check this at
  1459. * compile time, since the #if preprocessor conditions can not use the sizeof
  1460. * operator as an argument. */
  1461. #endif
  1462. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1463. /* This is the problematic case for CRYPTO_set_id_callback:
  1464. * The OS pthread_t can not be cast to unsigned long. */
  1465. struct mg_workerTLS *tls =
  1466. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1467. if (tls == NULL) {
  1468. /* SSL called from an unknown thread: Create some thread index.
  1469. */
  1470. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1471. tls->is_master = -2; /* -2 means "3rd party thread" */
  1472. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1473. pthread_setspecific(sTlsKey, tls);
  1474. }
  1475. return tls->thread_idx;
  1476. } else {
  1477. /* pthread_t may be any data type, so a simple cast to unsigned long
  1478. * can rise a warning/error, depending on the platform.
  1479. * Here memcpy is used as an anything-to-anything cast. */
  1480. unsigned long ret = 0;
  1481. pthread_t t = pthread_self();
  1482. memcpy(&ret, &t, sizeof(pthread_t));
  1483. return ret;
  1484. }
  1485. #if defined(__clang__)
  1486. #pragma clang diagnostic pop
  1487. #endif
  1488. #endif
  1489. }
  1490. FUNCTION_MAY_BE_UNUSED
  1491. static uint64_t
  1492. mg_get_current_time_ns(void)
  1493. {
  1494. struct timespec tsnow;
  1495. clock_gettime(CLOCK_REALTIME, &tsnow);
  1496. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1497. }
  1498. #if defined(GCC_DIAGNOSTIC)
  1499. /* Show no warning in case system functions are not used. */
  1500. #pragma GCC diagnostic pop
  1501. #endif /* defined(GCC_DIAGNOSTIC) */
  1502. #if defined(__clang__)
  1503. /* Show no warning in case system functions are not used. */
  1504. #pragma clang diagnostic pop
  1505. #endif
  1506. #if defined(NEED_DEBUG_TRACE_FUNC)
  1507. static void
  1508. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1509. {
  1510. va_list args;
  1511. struct timespec tsnow;
  1512. /* Get some operating system independent thread id */
  1513. unsigned long thread_id = mg_current_thread_id();
  1514. clock_gettime(CLOCK_REALTIME, &tsnow);
  1515. flockfile(DEBUG_TRACE_STREAM);
  1516. fprintf(DEBUG_TRACE_STREAM,
  1517. "*** %lu.%09lu %lu %s:%u: ",
  1518. (unsigned long)tsnow.tv_sec,
  1519. (unsigned long)tsnow.tv_nsec,
  1520. thread_id,
  1521. func,
  1522. line);
  1523. va_start(args, fmt);
  1524. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1525. va_end(args);
  1526. putc('\n', DEBUG_TRACE_STREAM);
  1527. fflush(DEBUG_TRACE_STREAM);
  1528. funlockfile(DEBUG_TRACE_STREAM);
  1529. }
  1530. #endif /* NEED_DEBUG_TRACE_FUNC */
  1531. #define MD5_STATIC static
  1532. #include "md5.inl"
  1533. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1534. #if defined(NO_SOCKLEN_T)
  1535. typedef int socklen_t;
  1536. #endif /* NO_SOCKLEN_T */
  1537. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1538. #if !defined(MSG_NOSIGNAL)
  1539. #define MSG_NOSIGNAL (0)
  1540. #endif
  1541. #if defined(NO_SSL)
  1542. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1543. typedef struct SSL_CTX SSL_CTX;
  1544. #else
  1545. #if defined(NO_SSL_DL)
  1546. #include <openssl/bn.h>
  1547. #include <openssl/conf.h>
  1548. #include <openssl/crypto.h>
  1549. #include <openssl/dh.h>
  1550. #include <openssl/engine.h>
  1551. #include <openssl/err.h>
  1552. #include <openssl/opensslv.h>
  1553. #include <openssl/pem.h>
  1554. #include <openssl/ssl.h>
  1555. #include <openssl/tls1.h>
  1556. #include <openssl/x509.h>
  1557. #if defined(WOLFSSL_VERSION)
  1558. /* Additional defines for WolfSSL, see
  1559. * https://github.com/civetweb/civetweb/issues/583 */
  1560. #include "wolfssl_extras.inl"
  1561. #endif
  1562. #if defined(OPENSSL_IS_BORINGSSL)
  1563. /* From boringssl/src/include/openssl/mem.h:
  1564. *
  1565. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1566. * However, that was written in a time before Valgrind and ASAN. Since we now
  1567. * have those tools, the OpenSSL allocation functions are simply macros around
  1568. * the standard memory functions.
  1569. *
  1570. * #define OPENSSL_free free */
  1571. #define free free
  1572. // disable for boringssl
  1573. #define CONF_modules_unload(a) ((void)0)
  1574. #define ENGINE_cleanup() ((void)0)
  1575. #endif
  1576. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1577. /* If OpenSSL headers are included, automatically select the API version */
  1578. #if !defined(OPENSSL_API_1_1)
  1579. #define OPENSSL_API_1_1
  1580. #endif
  1581. #define OPENSSL_REMOVE_THREAD_STATE()
  1582. #else
  1583. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1584. #endif
  1585. #else
  1586. /* SSL loaded dynamically from DLL.
  1587. * I put the prototypes here to be independent from OpenSSL source
  1588. * installation. */
  1589. typedef struct ssl_st SSL;
  1590. typedef struct ssl_method_st SSL_METHOD;
  1591. typedef struct ssl_ctx_st SSL_CTX;
  1592. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1593. typedef struct x509_name X509_NAME;
  1594. typedef struct asn1_integer ASN1_INTEGER;
  1595. typedef struct bignum BIGNUM;
  1596. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1597. typedef struct evp_md EVP_MD;
  1598. typedef struct x509 X509;
  1599. #define SSL_CTRL_OPTIONS (32)
  1600. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1601. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1602. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1603. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1604. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1605. #define SSL_VERIFY_NONE (0)
  1606. #define SSL_VERIFY_PEER (1)
  1607. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1608. #define SSL_VERIFY_CLIENT_ONCE (4)
  1609. #define SSL_OP_ALL (0x80000BFFul)
  1610. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1611. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1612. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1613. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1614. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1615. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1616. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1617. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1618. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1619. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1620. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1621. #define SSL_CB_HANDSHAKE_START (0x10)
  1622. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1623. #define SSL_ERROR_NONE (0)
  1624. #define SSL_ERROR_SSL (1)
  1625. #define SSL_ERROR_WANT_READ (2)
  1626. #define SSL_ERROR_WANT_WRITE (3)
  1627. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1628. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1629. #define SSL_ERROR_ZERO_RETURN (6)
  1630. #define SSL_ERROR_WANT_CONNECT (7)
  1631. #define SSL_ERROR_WANT_ACCEPT (8)
  1632. #define TLSEXT_TYPE_server_name (0)
  1633. #define TLSEXT_NAMETYPE_host_name (0)
  1634. #define SSL_TLSEXT_ERR_OK (0)
  1635. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1636. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1637. #define SSL_TLSEXT_ERR_NOACK (3)
  1638. enum ssl_func_category {
  1639. TLS_Mandatory, /* required for HTTPS */
  1640. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1641. TLS_END_OF_LIST
  1642. };
  1643. /* Check if all TLS functions/features are available */
  1644. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1645. struct ssl_func {
  1646. const char *name; /* SSL function name */
  1647. union {
  1648. enum ssl_func_category required; /* Mandatory or optional */
  1649. void (*ptr)(void); /* Function pointer */
  1650. };
  1651. };
  1652. #if defined(OPENSSL_API_1_1)
  1653. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1654. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1655. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1656. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1657. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1658. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1659. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1660. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1661. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1662. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1663. #define OPENSSL_init_ssl \
  1664. (*(int (*)(uint64_t opts, \
  1665. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1666. .ptr)
  1667. #define SSL_CTX_use_PrivateKey_file \
  1668. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1669. #define SSL_CTX_use_certificate_file \
  1670. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1671. #define SSL_CTX_set_default_passwd_cb \
  1672. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1673. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1674. #define SSL_CTX_use_certificate_chain_file \
  1675. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1676. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1677. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1678. #define SSL_CTX_set_verify \
  1679. (*(void (*)(SSL_CTX *, \
  1680. int, \
  1681. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1682. .ptr)
  1683. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1684. #define SSL_CTX_load_verify_locations \
  1685. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1686. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1687. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1688. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1689. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1690. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1691. #define SSL_CIPHER_get_name \
  1692. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1693. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1694. #define SSL_CTX_set_session_id_context \
  1695. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1696. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1697. #define SSL_CTX_set_cipher_list \
  1698. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1699. #define SSL_CTX_set_options \
  1700. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1701. #define SSL_CTX_set_info_callback \
  1702. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1703. ssl_sw[32] \
  1704. .ptr)
  1705. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1706. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1707. #define SSL_CTX_callback_ctrl \
  1708. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1709. #define SSL_get_servername \
  1710. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1711. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1712. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1713. #define SSL_CTX_set_alpn_protos \
  1714. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1715. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1716. const unsigned char **out,
  1717. unsigned char *outlen,
  1718. const unsigned char *in,
  1719. unsigned int inlen,
  1720. void *arg);
  1721. #define SSL_CTX_set_alpn_select_cb \
  1722. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1723. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1724. const unsigned char **out,
  1725. unsigned int *outlen,
  1726. void *arg);
  1727. #define SSL_CTX_set_next_protos_advertised_cb \
  1728. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1729. .ptr)
  1730. #define SSL_CTX_clear_options(ctx, op) \
  1731. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1732. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1733. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1734. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1735. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1736. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1737. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1738. SSL_CTX_callback_ctrl(ctx, \
  1739. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1740. (void (*)(void))cb)
  1741. #define SSL_set_tlsext_host_name(ctx, arg) \
  1742. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1743. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1744. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1745. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1746. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1747. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1748. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1749. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1750. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1751. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1752. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1753. #define X509_NAME_oneline \
  1754. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1755. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1756. #define EVP_get_digestbyname \
  1757. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1758. #define EVP_Digest \
  1759. (*(int (*)( \
  1760. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1761. crypto_sw[9] \
  1762. .ptr)
  1763. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1764. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1765. #define ASN1_INTEGER_to_BN \
  1766. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1767. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1768. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1769. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1770. #define OPENSSL_free(a) CRYPTO_free(a)
  1771. #define OPENSSL_REMOVE_THREAD_STATE()
  1772. /* init_ssl_ctx() function updates this array.
  1773. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1774. * of respective functions. The macros above (like SSL_connect()) are really
  1775. * just calling these functions indirectly via the pointer. */
  1776. static struct ssl_func ssl_sw[] = {
  1777. {"SSL_free", {TLS_Mandatory}},
  1778. {"SSL_accept", {TLS_Mandatory}},
  1779. {"SSL_connect", {TLS_Mandatory}},
  1780. {"SSL_read", {TLS_Mandatory}},
  1781. {"SSL_write", {TLS_Mandatory}},
  1782. {"SSL_get_error", {TLS_Mandatory}},
  1783. {"SSL_set_fd", {TLS_Mandatory}},
  1784. {"SSL_new", {TLS_Mandatory}},
  1785. {"SSL_CTX_new", {TLS_Mandatory}},
  1786. {"TLS_server_method", {TLS_Mandatory}},
  1787. {"OPENSSL_init_ssl", {TLS_Mandatory}},
  1788. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1789. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1790. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1791. {"SSL_CTX_free", {TLS_Mandatory}},
  1792. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1793. {"TLS_client_method", {TLS_Mandatory}},
  1794. {"SSL_pending", {TLS_Mandatory}},
  1795. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1796. {"SSL_shutdown", {TLS_Mandatory}},
  1797. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1798. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1799. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1800. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1801. {"SSL_get_version", {TLS_Mandatory}},
  1802. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1803. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1804. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1805. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1806. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1807. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1808. {"SSL_CTX_set_options", {TLS_Mandatory}},
  1809. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1810. {"SSL_get_ex_data", {TLS_Mandatory}},
  1811. {"SSL_set_ex_data", {TLS_Mandatory}},
  1812. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1813. {"SSL_get_servername", {TLS_Mandatory}},
  1814. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1815. {"SSL_ctrl", {TLS_Mandatory}},
  1816. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1817. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1818. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1819. {NULL, {TLS_END_OF_LIST}}};
  1820. /* Similar array as ssl_sw. These functions could be located in different
  1821. * lib. */
  1822. static struct ssl_func crypto_sw[] = {{"ERR_get_error", {TLS_Mandatory}},
  1823. {"ERR_error_string", {TLS_Mandatory}},
  1824. {"CONF_modules_unload", {TLS_Mandatory}},
  1825. {"X509_free", {TLS_Mandatory}},
  1826. {"X509_get_subject_name",
  1827. {TLS_Mandatory}},
  1828. {"X509_get_issuer_name", {TLS_Mandatory}},
  1829. {"X509_NAME_oneline", {TLS_Mandatory}},
  1830. {"X509_get_serialNumber",
  1831. {TLS_Mandatory}},
  1832. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1833. {"EVP_Digest", {TLS_Mandatory}},
  1834. {"i2d_X509", {TLS_Mandatory}},
  1835. {"BN_bn2hex", {TLS_Mandatory}},
  1836. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1837. {"BN_free", {TLS_Mandatory}},
  1838. {"CRYPTO_free", {TLS_Mandatory}},
  1839. {"ERR_clear_error", {TLS_Mandatory}},
  1840. {NULL, {TLS_END_OF_LIST}}};
  1841. #else
  1842. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1843. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1844. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1845. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1846. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1847. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1848. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1849. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1850. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1851. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1852. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1853. #define SSL_CTX_use_PrivateKey_file \
  1854. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1855. #define SSL_CTX_use_certificate_file \
  1856. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1857. #define SSL_CTX_set_default_passwd_cb \
  1858. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1859. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1860. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1861. #define SSL_CTX_use_certificate_chain_file \
  1862. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1863. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1864. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1865. #define SSL_CTX_set_verify \
  1866. (*(void (*)(SSL_CTX *, \
  1867. int, \
  1868. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1869. .ptr)
  1870. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1871. #define SSL_CTX_load_verify_locations \
  1872. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1873. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1874. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1875. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1876. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1877. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1878. #define SSL_CIPHER_get_name \
  1879. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1880. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1881. #define SSL_CTX_set_session_id_context \
  1882. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1883. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1884. #define SSL_CTX_set_cipher_list \
  1885. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1886. #define SSL_CTX_set_info_callback \
  1887. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1888. .ptr)
  1889. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1890. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1891. #define SSL_CTX_callback_ctrl \
  1892. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1893. #define SSL_get_servername \
  1894. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1895. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1896. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1897. #define SSL_CTX_set_alpn_protos \
  1898. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1899. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1900. const unsigned char **out,
  1901. unsigned char *outlen,
  1902. const unsigned char *in,
  1903. unsigned int inlen,
  1904. void *arg);
  1905. #define SSL_CTX_set_alpn_select_cb \
  1906. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1907. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1908. const unsigned char **out,
  1909. unsigned int *outlen,
  1910. void *arg);
  1911. #define SSL_CTX_set_next_protos_advertised_cb \
  1912. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1913. .ptr)
  1914. #define SSL_CTX_set_options(ctx, op) \
  1915. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1916. #define SSL_CTX_clear_options(ctx, op) \
  1917. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1918. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1919. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1920. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1921. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1922. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1923. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1924. SSL_CTX_callback_ctrl(ctx, \
  1925. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1926. (void (*)(void))cb)
  1927. #define SSL_set_tlsext_host_name(ctx, arg) \
  1928. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1929. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1930. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1931. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1932. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1933. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1934. #define CRYPTO_set_locking_callback \
  1935. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1936. #define CRYPTO_set_id_callback \
  1937. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1938. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1939. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1940. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1941. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1942. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1943. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1944. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1945. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1946. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1947. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1948. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1949. #define X509_NAME_oneline \
  1950. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1951. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1952. #define i2c_ASN1_INTEGER \
  1953. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1954. #define EVP_get_digestbyname \
  1955. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1956. #define EVP_Digest \
  1957. (*(int (*)( \
  1958. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1959. crypto_sw[18] \
  1960. .ptr)
  1961. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1962. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1963. #define ASN1_INTEGER_to_BN \
  1964. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1965. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1966. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1967. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1968. #define OPENSSL_free(a) CRYPTO_free(a)
  1969. /* use here ERR_remove_state,
  1970. * while on some platforms function is not included into library due to
  1971. * deprication */
  1972. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1973. /* init_ssl_ctx() function updates this array.
  1974. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1975. * of respective functions. The macros above (like SSL_connect()) are really
  1976. * just calling these functions indirectly via the pointer. */
  1977. static struct ssl_func ssl_sw[] = {
  1978. {"SSL_free", {TLS_Mandatory}},
  1979. {"SSL_accept", {TLS_Mandatory}},
  1980. {"SSL_connect", {TLS_Mandatory}},
  1981. {"SSL_read", {TLS_Mandatory}},
  1982. {"SSL_write", {TLS_Mandatory}},
  1983. {"SSL_get_error", {TLS_Mandatory}},
  1984. {"SSL_set_fd", {TLS_Mandatory}},
  1985. {"SSL_new", {TLS_Mandatory}},
  1986. {"SSL_CTX_new", {TLS_Mandatory}},
  1987. {"SSLv23_server_method", {TLS_Mandatory}},
  1988. {"SSL_library_init", {TLS_Mandatory}},
  1989. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1990. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1991. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1992. {"SSL_CTX_free", {TLS_Mandatory}},
  1993. {"SSL_load_error_strings", {TLS_Mandatory}},
  1994. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1995. {"SSLv23_client_method", {TLS_Mandatory}},
  1996. {"SSL_pending", {TLS_Mandatory}},
  1997. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1998. {"SSL_shutdown", {TLS_Mandatory}},
  1999. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  2000. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  2001. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  2002. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  2003. {"SSL_get_version", {TLS_Mandatory}},
  2004. {"SSL_get_current_cipher", {TLS_Mandatory}},
  2005. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  2006. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  2007. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  2008. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  2009. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  2010. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  2011. {"SSL_get_ex_data", {TLS_Mandatory}},
  2012. {"SSL_set_ex_data", {TLS_Mandatory}},
  2013. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  2014. {"SSL_get_servername", {TLS_Mandatory}},
  2015. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  2016. {"SSL_ctrl", {TLS_Mandatory}},
  2017. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  2018. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  2019. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  2020. {NULL, {TLS_END_OF_LIST}}};
  2021. /* Similar array as ssl_sw. These functions could be located in different
  2022. * lib. */
  2023. static struct ssl_func crypto_sw[] = {
  2024. {"CRYPTO_num_locks", {TLS_Mandatory}},
  2025. {"CRYPTO_set_locking_callback", {TLS_Mandatory}},
  2026. {"CRYPTO_set_id_callback", {TLS_Mandatory}},
  2027. {"ERR_get_error", {TLS_Mandatory}},
  2028. {"ERR_error_string", {TLS_Mandatory}},
  2029. {"ERR_remove_state", {TLS_Mandatory}},
  2030. {"ERR_free_strings", {TLS_Mandatory}},
  2031. {"ENGINE_cleanup", {TLS_Mandatory}},
  2032. {"CONF_modules_unload", {TLS_Mandatory}},
  2033. {"CRYPTO_cleanup_all_ex_data", {TLS_Mandatory}},
  2034. {"EVP_cleanup", {TLS_Mandatory}},
  2035. {"X509_free", {TLS_Mandatory}},
  2036. {"X509_get_subject_name", {TLS_Mandatory}},
  2037. {"X509_get_issuer_name", {TLS_Mandatory}},
  2038. {"X509_NAME_oneline", {TLS_Mandatory}},
  2039. {"X509_get_serialNumber", {TLS_Mandatory}},
  2040. {"i2c_ASN1_INTEGER", {TLS_Mandatory}},
  2041. {"EVP_get_digestbyname", {TLS_Mandatory}},
  2042. {"EVP_Digest", {TLS_Mandatory}},
  2043. {"i2d_X509", {TLS_Mandatory}},
  2044. {"BN_bn2hex", {TLS_Mandatory}},
  2045. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  2046. {"BN_free", {TLS_Mandatory}},
  2047. {"CRYPTO_free", {TLS_Mandatory}},
  2048. {"ERR_clear_error", {TLS_Mandatory}},
  2049. {NULL, {TLS_END_OF_LIST}}};
  2050. #endif /* OPENSSL_API_1_1 */
  2051. #endif /* NO_SSL_DL */
  2052. #endif /* NO_SSL */
  2053. #if !defined(NO_CACHING)
  2054. static const char month_names[][4] = {"Jan",
  2055. "Feb",
  2056. "Mar",
  2057. "Apr",
  2058. "May",
  2059. "Jun",
  2060. "Jul",
  2061. "Aug",
  2062. "Sep",
  2063. "Oct",
  2064. "Nov",
  2065. "Dec"};
  2066. #endif /* !NO_CACHING */
  2067. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2068. * the union u. */
  2069. union usa {
  2070. struct sockaddr sa;
  2071. struct sockaddr_in sin;
  2072. #if defined(USE_IPV6)
  2073. struct sockaddr_in6 sin6;
  2074. #endif
  2075. };
  2076. /* Describes a string (chunk of memory). */
  2077. struct vec {
  2078. const char *ptr;
  2079. size_t len;
  2080. };
  2081. struct mg_file_stat {
  2082. /* File properties filled by mg_stat: */
  2083. uint64_t size;
  2084. time_t last_modified;
  2085. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2086. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2087. * case we need a "Content-Eencoding: gzip" header */
  2088. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2089. };
  2090. struct mg_file_in_memory {
  2091. char *p;
  2092. uint32_t pos;
  2093. char mode;
  2094. };
  2095. struct mg_file_access {
  2096. /* File properties filled by mg_fopen: */
  2097. FILE *fp;
  2098. #if defined(MG_USE_OPEN_FILE)
  2099. /* TODO (low): Remove obsolete "file in memory" implementation.
  2100. * In an "early 2017" discussion at Google groups
  2101. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2102. * we decided to get rid of this feature (after some fade-out
  2103. * phase). */
  2104. const char *membuf;
  2105. #endif
  2106. };
  2107. struct mg_file {
  2108. struct mg_file_stat stat;
  2109. struct mg_file_access access;
  2110. };
  2111. #if defined(MG_USE_OPEN_FILE)
  2112. #define STRUCT_FILE_INITIALIZER \
  2113. { \
  2114. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2115. { \
  2116. (FILE *)NULL, (const char *)NULL \
  2117. } \
  2118. }
  2119. #else
  2120. #define STRUCT_FILE_INITIALIZER \
  2121. { \
  2122. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2123. { \
  2124. (FILE *)NULL \
  2125. } \
  2126. }
  2127. #endif
  2128. /* Describes listening socket, or socket which was accept()-ed by the master
  2129. * thread and queued for future handling by the worker thread. */
  2130. struct socket {
  2131. SOCKET sock; /* Listening socket */
  2132. union usa lsa; /* Local socket address */
  2133. union usa rsa; /* Remote socket address */
  2134. unsigned char is_ssl; /* Is port SSL-ed */
  2135. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2136. * port */
  2137. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2138. };
  2139. /* Enum const for all options must be in sync with
  2140. * static struct mg_option config_options[]
  2141. * This is tested in the unit test (test/private.c)
  2142. * "Private Config Options"
  2143. */
  2144. enum {
  2145. /* Once for each server */
  2146. LISTENING_PORTS,
  2147. NUM_THREADS,
  2148. RUN_AS_USER,
  2149. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2150. * socket option typedef TCP_NODELAY. */
  2151. MAX_REQUEST_SIZE,
  2152. LINGER_TIMEOUT,
  2153. CONNECTION_QUEUE_SIZE,
  2154. LISTEN_BACKLOG_SIZE,
  2155. #if defined(__linux__)
  2156. ALLOW_SENDFILE_CALL,
  2157. #endif
  2158. #if defined(_WIN32)
  2159. CASE_SENSITIVE_FILES,
  2160. #endif
  2161. THROTTLE,
  2162. ACCESS_LOG_FILE,
  2163. ERROR_LOG_FILE,
  2164. ENABLE_KEEP_ALIVE,
  2165. REQUEST_TIMEOUT,
  2166. KEEP_ALIVE_TIMEOUT,
  2167. #if defined(USE_WEBSOCKET)
  2168. WEBSOCKET_TIMEOUT,
  2169. ENABLE_WEBSOCKET_PING_PONG,
  2170. #endif
  2171. DECODE_URL,
  2172. #if defined(USE_LUA)
  2173. LUA_BACKGROUND_SCRIPT,
  2174. LUA_BACKGROUND_SCRIPT_PARAMS,
  2175. #endif
  2176. #if defined(USE_TIMERS)
  2177. CGI_TIMEOUT,
  2178. #endif
  2179. /* Once for each domain */
  2180. DOCUMENT_ROOT,
  2181. CGI_EXTENSIONS,
  2182. CGI_ENVIRONMENT,
  2183. PUT_DELETE_PASSWORDS_FILE,
  2184. CGI_INTERPRETER,
  2185. CGI_INTERPRETER_ARGS,
  2186. PROTECT_URI,
  2187. AUTHENTICATION_DOMAIN,
  2188. ENABLE_AUTH_DOMAIN_CHECK,
  2189. SSI_EXTENSIONS,
  2190. ENABLE_DIRECTORY_LISTING,
  2191. GLOBAL_PASSWORDS_FILE,
  2192. INDEX_FILES,
  2193. ACCESS_CONTROL_LIST,
  2194. EXTRA_MIME_TYPES,
  2195. SSL_CERTIFICATE,
  2196. SSL_CERTIFICATE_CHAIN,
  2197. URL_REWRITE_PATTERN,
  2198. HIDE_FILES,
  2199. SSL_DO_VERIFY_PEER,
  2200. SSL_CA_PATH,
  2201. SSL_CA_FILE,
  2202. SSL_VERIFY_DEPTH,
  2203. SSL_DEFAULT_VERIFY_PATHS,
  2204. SSL_CIPHER_LIST,
  2205. SSL_PROTOCOL_VERSION,
  2206. SSL_SHORT_TRUST,
  2207. #if defined(USE_LUA)
  2208. LUA_PRELOAD_FILE,
  2209. LUA_SCRIPT_EXTENSIONS,
  2210. LUA_SERVER_PAGE_EXTENSIONS,
  2211. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2212. LUA_DEBUG_PARAMS,
  2213. #endif
  2214. #endif
  2215. #if defined(USE_DUKTAPE)
  2216. DUKTAPE_SCRIPT_EXTENSIONS,
  2217. #endif
  2218. #if defined(USE_WEBSOCKET)
  2219. WEBSOCKET_ROOT,
  2220. #endif
  2221. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2222. LUA_WEBSOCKET_EXTENSIONS,
  2223. #endif
  2224. ACCESS_CONTROL_ALLOW_ORIGIN,
  2225. ACCESS_CONTROL_ALLOW_METHODS,
  2226. ACCESS_CONTROL_ALLOW_HEADERS,
  2227. ERROR_PAGES,
  2228. #if !defined(NO_CACHING)
  2229. STATIC_FILE_MAX_AGE,
  2230. STATIC_FILE_CACHE_CONTROL,
  2231. #endif
  2232. #if !defined(NO_SSL)
  2233. STRICT_HTTPS_MAX_AGE,
  2234. #endif
  2235. ADDITIONAL_HEADER,
  2236. ALLOW_INDEX_SCRIPT_SUB_RES,
  2237. #if defined(DAEMONIZE)
  2238. ENABLE_DAEMONIZE,
  2239. #endif
  2240. NUM_OPTIONS
  2241. };
  2242. /* Config option name, config types, default value.
  2243. * Must be in the same order as the enum const above.
  2244. */
  2245. static const struct mg_option config_options[] = {
  2246. /* Once for each server */
  2247. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2248. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2249. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2250. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2251. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2252. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2253. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2254. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2255. #if defined(__linux__)
  2256. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2257. #endif
  2258. #if defined(_WIN32)
  2259. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2260. #endif
  2261. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2262. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2263. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2264. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2265. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2266. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2267. #if defined(USE_WEBSOCKET)
  2268. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2269. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2270. #endif
  2271. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2272. #if defined(USE_LUA)
  2273. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2274. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2275. #endif
  2276. #if defined(USE_TIMERS)
  2277. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2278. #endif
  2279. /* Once for each domain */
  2280. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2281. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2282. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2283. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2284. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2285. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2286. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2287. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2288. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2289. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2290. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2291. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2292. {"index_files",
  2293. MG_CONFIG_TYPE_STRING_LIST,
  2294. #if defined(USE_LUA)
  2295. "index.xhtml,index.html,index.htm,"
  2296. "index.lp,index.lsp,index.lua,index.cgi,"
  2297. "index.shtml,index.php"},
  2298. #else
  2299. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2300. #endif
  2301. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2302. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2303. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2304. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2305. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2306. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2307. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2308. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2309. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2310. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2311. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2312. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2313. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2314. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2315. #if defined(USE_LUA)
  2316. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2317. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2318. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2319. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2320. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2321. #endif
  2322. #endif
  2323. #if defined(USE_DUKTAPE)
  2324. /* The support for duktape is still in alpha version state.
  2325. * The name of this config option might change. */
  2326. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2327. #endif
  2328. #if defined(USE_WEBSOCKET)
  2329. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2330. #endif
  2331. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2332. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2333. #endif
  2334. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2335. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2336. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2337. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2338. #if !defined(NO_CACHING)
  2339. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2340. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2341. #endif
  2342. #if !defined(NO_SSL)
  2343. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2344. #endif
  2345. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2346. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2347. #if defined(DAEMONIZE)
  2348. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2349. #endif
  2350. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2351. /* Check if the config_options and the corresponding enum have compatible
  2352. * sizes. */
  2353. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2354. == (NUM_OPTIONS + 1),
  2355. "config_options and enum not sync");
  2356. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2357. struct mg_handler_info {
  2358. /* Name/Pattern of the URI. */
  2359. char *uri;
  2360. size_t uri_len;
  2361. /* handler type */
  2362. int handler_type;
  2363. /* Handler for http/https or authorization requests. */
  2364. mg_request_handler handler;
  2365. unsigned int refcount;
  2366. int removing;
  2367. /* Handler for ws/wss (websocket) requests. */
  2368. mg_websocket_connect_handler connect_handler;
  2369. mg_websocket_ready_handler ready_handler;
  2370. mg_websocket_data_handler data_handler;
  2371. mg_websocket_close_handler close_handler;
  2372. /* accepted subprotocols for ws/wss requests. */
  2373. struct mg_websocket_subprotocols *subprotocols;
  2374. /* Handler for authorization requests */
  2375. mg_authorization_handler auth_handler;
  2376. /* User supplied argument for the handler function. */
  2377. void *cbdata;
  2378. /* next handler in a linked list */
  2379. struct mg_handler_info *next;
  2380. };
  2381. enum {
  2382. CONTEXT_INVALID,
  2383. CONTEXT_SERVER,
  2384. CONTEXT_HTTP_CLIENT,
  2385. CONTEXT_WS_CLIENT
  2386. };
  2387. struct mg_domain_context {
  2388. SSL_CTX *ssl_ctx; /* SSL context */
  2389. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2390. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2391. int64_t ssl_cert_last_mtime;
  2392. /* Server nonce */
  2393. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2394. unsigned long nonce_count; /* Used nonces, used for authentication */
  2395. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2396. /* linked list of shared lua websockets */
  2397. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2398. #endif
  2399. /* Linked list of domains */
  2400. struct mg_domain_context *next;
  2401. };
  2402. /* Stop flag can be "volatile" or require a lock */
  2403. typedef int volatile stop_flag_t;
  2404. #ifdef STOP_FLAG_NEEDS_LOCK
  2405. static int
  2406. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2407. {
  2408. int r;
  2409. mg_global_lock();
  2410. r = ((*f) == 0);
  2411. mg_global_unlock();
  2412. return r;
  2413. }
  2414. static int
  2415. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2416. {
  2417. int r;
  2418. mg_global_lock();
  2419. r = ((*f) == 2);
  2420. mg_global_unlock();
  2421. return r;
  2422. }
  2423. static void
  2424. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2425. {
  2426. mg_global_lock();
  2427. (*f) = v;
  2428. mg_global_unlock();
  2429. }
  2430. #else /* STOP_FLAG_NEEDS_LOCK */
  2431. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2432. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2433. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2434. #endif /* STOP_FLAG_NEEDS_LOCK */
  2435. struct mg_context {
  2436. /* Part 1 - Physical context:
  2437. * This holds threads, ports, timeouts, ...
  2438. * set for the entire server, independent from the
  2439. * addressed hostname.
  2440. */
  2441. /* Connection related */
  2442. int context_type; /* See CONTEXT_* above */
  2443. struct socket *listening_sockets;
  2444. struct mg_pollfd *listening_socket_fds;
  2445. unsigned int num_listening_sockets;
  2446. struct mg_connection *worker_connections; /* The connection struct, pre-
  2447. * allocated for each worker */
  2448. #if defined(USE_SERVER_STATS)
  2449. volatile ptrdiff_t active_connections;
  2450. volatile ptrdiff_t max_active_connections;
  2451. volatile ptrdiff_t total_connections;
  2452. volatile ptrdiff_t total_requests;
  2453. volatile int64_t total_data_read;
  2454. volatile int64_t total_data_written;
  2455. #endif
  2456. /* Thread related */
  2457. stop_flag_t stop_flag; /* Should we stop event loop */
  2458. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2459. pthread_t masterthreadid; /* The master thread ID */
  2460. unsigned int
  2461. cfg_worker_threads; /* The number of configured worker threads. */
  2462. pthread_t *worker_threadids; /* The worker thread IDs */
  2463. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2464. /* Connection to thread dispatching */
  2465. #if defined(ALTERNATIVE_QUEUE)
  2466. struct socket *client_socks;
  2467. void **client_wait_events;
  2468. #else
  2469. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2470. worker thread */
  2471. volatile int sq_head; /* Head of the socket queue */
  2472. volatile int sq_tail; /* Tail of the socket queue */
  2473. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2474. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2475. volatile int sq_blocked; /* Status information: sq is full */
  2476. int sq_size; /* No of elements in socket queue */
  2477. #if defined(USE_SERVER_STATS)
  2478. int sq_max_fill;
  2479. #endif /* USE_SERVER_STATS */
  2480. #endif /* ALTERNATIVE_QUEUE */
  2481. /* Memory related */
  2482. unsigned int max_request_size; /* The max request size */
  2483. #if defined(USE_SERVER_STATS)
  2484. struct mg_memory_stat ctx_memory;
  2485. #endif
  2486. /* Operating system related */
  2487. char *systemName; /* What operating system is running */
  2488. time_t start_time; /* Server start time, used for authentication
  2489. * and for diagnstics. */
  2490. #if defined(USE_TIMERS)
  2491. struct ttimers *timers;
  2492. #endif
  2493. /* Lua specific: Background operations and shared websockets */
  2494. #if defined(USE_LUA)
  2495. void *lua_background_state;
  2496. #endif
  2497. /* Server nonce */
  2498. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2499. * ssl_cert_last_mtime, nonce_count, and
  2500. * next (linked list) */
  2501. /* Server callbacks */
  2502. struct mg_callbacks callbacks; /* User-defined callback function */
  2503. void *user_data; /* User-defined data */
  2504. /* Part 2 - Logical domain:
  2505. * This holds hostname, TLS certificate, document root, ...
  2506. * set for a domain hosted at the server.
  2507. * There may be multiple domains hosted at one physical server.
  2508. * The default domain "dd" is the first element of a list of
  2509. * domains.
  2510. */
  2511. struct mg_domain_context dd; /* default domain */
  2512. };
  2513. #if defined(USE_SERVER_STATS)
  2514. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2515. static struct mg_memory_stat *
  2516. get_memory_stat(struct mg_context *ctx)
  2517. {
  2518. if (ctx) {
  2519. return &(ctx->ctx_memory);
  2520. }
  2521. return &mg_common_memory;
  2522. }
  2523. #endif
  2524. enum {
  2525. CONNECTION_TYPE_INVALID,
  2526. CONNECTION_TYPE_REQUEST,
  2527. CONNECTION_TYPE_RESPONSE
  2528. };
  2529. enum {
  2530. PROTOCOL_TYPE_HTTP1 = 0,
  2531. PROTOCOL_TYPE_WEBSOCKET = 1,
  2532. PROTOCOL_TYPE_HTTP2 = 2
  2533. };
  2534. struct mg_connection {
  2535. int connection_type; /* see CONNECTION_TYPE_* above */
  2536. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2537. struct mg_request_info request_info;
  2538. struct mg_response_info response_info;
  2539. struct mg_context *phys_ctx;
  2540. struct mg_domain_context *dom_ctx;
  2541. #if defined(USE_SERVER_STATS)
  2542. int conn_state; /* 0 = undef, numerical value may change in different
  2543. * versions. For the current definition, see
  2544. * mg_get_connection_info_impl */
  2545. #endif
  2546. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2547. SSL *ssl; /* SSL descriptor */
  2548. struct socket client; /* Connected client */
  2549. time_t conn_birth_time; /* Time (wall clock) when connection was
  2550. * established */
  2551. #if defined(USE_SERVER_STATS)
  2552. time_t conn_close_time; /* Time (wall clock) when connection was
  2553. * closed (or 0 if still open) */
  2554. #endif
  2555. struct timespec req_time; /* Time (since system start) when the request
  2556. * was received */
  2557. int64_t num_bytes_sent; /* Total bytes sent to client */
  2558. int64_t content_len; /* How many bytes of content can be read
  2559. * !is_chunked: Content-Length header value
  2560. * or -1 (until connection closed,
  2561. * not allowed for a request)
  2562. * is_chunked: >= 0, appended gradually
  2563. */
  2564. int64_t consumed_content; /* How many bytes of content have been read */
  2565. int is_chunked; /* Transfer-Encoding is chunked:
  2566. * 0 = not chunked,
  2567. * 1 = chunked, not yet, or some data read,
  2568. * 2 = chunked, has error,
  2569. * 3 = chunked, all data read except trailer,
  2570. * 4 = chunked, all data read
  2571. */
  2572. char *buf; /* Buffer for received data */
  2573. char *path_info; /* PATH_INFO part of the URL */
  2574. int must_close; /* 1 if connection must be closed */
  2575. int accept_gzip; /* 1 if gzip encoding is accepted */
  2576. int in_error_handler; /* 1 if in handler for user defined error
  2577. * pages */
  2578. #if defined(USE_WEBSOCKET)
  2579. int in_websocket_handling; /* 1 if in read_websocket */
  2580. #endif
  2581. int handled_requests; /* Number of requests handled by this connection
  2582. */
  2583. int buf_size; /* Buffer size */
  2584. int request_len; /* Size of the request + headers in a buffer */
  2585. int data_len; /* Total size of data in a buffer */
  2586. int status_code; /* HTTP reply status code, e.g. 200 */
  2587. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2588. * throttle */
  2589. time_t last_throttle_time; /* Last time throttled data was sent */
  2590. int last_throttle_bytes; /* Bytes sent this second */
  2591. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2592. * atomic transmissions for websockets */
  2593. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2594. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2595. #endif
  2596. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2597. * for quick access */
  2598. };
  2599. /* Directory entry */
  2600. struct de {
  2601. struct mg_connection *conn;
  2602. char *file_name;
  2603. struct mg_file_stat file;
  2604. };
  2605. #define mg_cry_internal(conn, fmt, ...) \
  2606. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2607. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2608. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2609. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2610. struct mg_context *ctx,
  2611. const char *func,
  2612. unsigned line,
  2613. const char *fmt,
  2614. ...) PRINTF_ARGS(5, 6);
  2615. #if !defined(NO_THREAD_NAME)
  2616. #if defined(_WIN32) && defined(_MSC_VER)
  2617. /* Set the thread name for debugging purposes in Visual Studio
  2618. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2619. */
  2620. #pragma pack(push, 8)
  2621. typedef struct tagTHREADNAME_INFO {
  2622. DWORD dwType; /* Must be 0x1000. */
  2623. LPCSTR szName; /* Pointer to name (in user addr space). */
  2624. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2625. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2626. } THREADNAME_INFO;
  2627. #pragma pack(pop)
  2628. #elif defined(__linux__)
  2629. #include <sys/prctl.h>
  2630. #include <sys/sendfile.h>
  2631. #if defined(ALTERNATIVE_QUEUE)
  2632. #include <sys/eventfd.h>
  2633. #endif /* ALTERNATIVE_QUEUE */
  2634. #if defined(ALTERNATIVE_QUEUE)
  2635. static void *
  2636. event_create(void)
  2637. {
  2638. int evhdl = eventfd(0, EFD_CLOEXEC);
  2639. int *ret;
  2640. if (evhdl == -1) {
  2641. /* Linux uses -1 on error, Windows NULL. */
  2642. /* However, Linux does not return 0 on success either. */
  2643. return 0;
  2644. }
  2645. ret = (int *)mg_malloc(sizeof(int));
  2646. if (ret) {
  2647. *ret = evhdl;
  2648. } else {
  2649. (void)close(evhdl);
  2650. }
  2651. return (void *)ret;
  2652. }
  2653. static int
  2654. event_wait(void *eventhdl)
  2655. {
  2656. uint64_t u;
  2657. int evhdl, s;
  2658. if (!eventhdl) {
  2659. /* error */
  2660. return 0;
  2661. }
  2662. evhdl = *(int *)eventhdl;
  2663. s = (int)read(evhdl, &u, sizeof(u));
  2664. if (s != sizeof(u)) {
  2665. /* error */
  2666. return 0;
  2667. }
  2668. (void)u; /* the value is not required */
  2669. return 1;
  2670. }
  2671. static int
  2672. event_signal(void *eventhdl)
  2673. {
  2674. uint64_t u = 1;
  2675. int evhdl, s;
  2676. if (!eventhdl) {
  2677. /* error */
  2678. return 0;
  2679. }
  2680. evhdl = *(int *)eventhdl;
  2681. s = (int)write(evhdl, &u, sizeof(u));
  2682. if (s != sizeof(u)) {
  2683. /* error */
  2684. return 0;
  2685. }
  2686. return 1;
  2687. }
  2688. static void
  2689. event_destroy(void *eventhdl)
  2690. {
  2691. int evhdl;
  2692. if (!eventhdl) {
  2693. /* error */
  2694. return;
  2695. }
  2696. evhdl = *(int *)eventhdl;
  2697. close(evhdl);
  2698. mg_free(eventhdl);
  2699. }
  2700. #endif
  2701. #endif
  2702. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2703. struct posix_event {
  2704. pthread_mutex_t mutex;
  2705. pthread_cond_t cond;
  2706. int signaled;
  2707. };
  2708. static void *
  2709. event_create(void)
  2710. {
  2711. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2712. if (ret == 0) {
  2713. /* out of memory */
  2714. return 0;
  2715. }
  2716. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2717. /* pthread mutex not available */
  2718. mg_free(ret);
  2719. return 0;
  2720. }
  2721. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2722. /* pthread cond not available */
  2723. pthread_mutex_destroy(&(ret->mutex));
  2724. mg_free(ret);
  2725. return 0;
  2726. }
  2727. ret->signaled = 0;
  2728. return (void *)ret;
  2729. }
  2730. static int
  2731. event_wait(void *eventhdl)
  2732. {
  2733. struct posix_event *ev = (struct posix_event *)eventhdl;
  2734. pthread_mutex_lock(&(ev->mutex));
  2735. while (!ev->signaled) {
  2736. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2737. }
  2738. ev->signaled = 0;
  2739. pthread_mutex_unlock(&(ev->mutex));
  2740. return 1;
  2741. }
  2742. static int
  2743. event_signal(void *eventhdl)
  2744. {
  2745. struct posix_event *ev = (struct posix_event *)eventhdl;
  2746. pthread_mutex_lock(&(ev->mutex));
  2747. pthread_cond_signal(&(ev->cond));
  2748. ev->signaled = 1;
  2749. pthread_mutex_unlock(&(ev->mutex));
  2750. return 1;
  2751. }
  2752. static void
  2753. event_destroy(void *eventhdl)
  2754. {
  2755. struct posix_event *ev = (struct posix_event *)eventhdl;
  2756. pthread_cond_destroy(&(ev->cond));
  2757. pthread_mutex_destroy(&(ev->mutex));
  2758. mg_free(ev);
  2759. }
  2760. #endif
  2761. static void
  2762. mg_set_thread_name(const char *name)
  2763. {
  2764. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2765. mg_snprintf(
  2766. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2767. #if defined(_WIN32)
  2768. #if defined(_MSC_VER)
  2769. /* Windows and Visual Studio Compiler */
  2770. __try {
  2771. THREADNAME_INFO info;
  2772. info.dwType = 0x1000;
  2773. info.szName = threadName;
  2774. info.dwThreadID = ~0U;
  2775. info.dwFlags = 0;
  2776. RaiseException(0x406D1388,
  2777. 0,
  2778. sizeof(info) / sizeof(ULONG_PTR),
  2779. (ULONG_PTR *)&info);
  2780. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2781. }
  2782. #elif defined(__MINGW32__)
  2783. /* No option known to set thread name for MinGW known */
  2784. #endif
  2785. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2786. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2787. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2788. #if defined(__MACH__)
  2789. /* OS X only current thread name can be changed */
  2790. (void)pthread_setname_np(threadName);
  2791. #else
  2792. (void)pthread_setname_np(pthread_self(), threadName);
  2793. #endif
  2794. #elif defined(__linux__)
  2795. /* On Linux we can use the prctl function.
  2796. * When building for Linux Standard Base (LSB) use
  2797. * NO_THREAD_NAME. However, thread names are a big
  2798. * help for debugging, so the stadard is to set them.
  2799. */
  2800. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2801. #endif
  2802. }
  2803. #else /* !defined(NO_THREAD_NAME) */
  2804. void
  2805. mg_set_thread_name(const char *threadName)
  2806. {
  2807. }
  2808. #endif
  2809. #if defined(MG_LEGACY_INTERFACE)
  2810. const char **
  2811. mg_get_valid_option_names(void)
  2812. {
  2813. /* This function is deprecated. Use mg_get_valid_options instead. */
  2814. static const char
  2815. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2816. int i;
  2817. for (i = 0; config_options[i].name != NULL; i++) {
  2818. data[i * 2] = config_options[i].name;
  2819. data[i * 2 + 1] = config_options[i].default_value;
  2820. }
  2821. return data;
  2822. }
  2823. #endif
  2824. const struct mg_option *
  2825. mg_get_valid_options(void)
  2826. {
  2827. return config_options;
  2828. }
  2829. /* Do not open file (used in is_file_in_memory) */
  2830. #define MG_FOPEN_MODE_NONE (0)
  2831. /* Open file for read only access */
  2832. #define MG_FOPEN_MODE_READ (1)
  2833. /* Open file for writing, create and overwrite */
  2834. #define MG_FOPEN_MODE_WRITE (2)
  2835. /* Open file for writing, create and append */
  2836. #define MG_FOPEN_MODE_APPEND (4)
  2837. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2838. * output filep and return 1, otherwise return 0 and don't modify anything.
  2839. */
  2840. static int
  2841. open_file_in_memory(const struct mg_connection *conn,
  2842. const char *path,
  2843. struct mg_file *filep,
  2844. int mode)
  2845. {
  2846. #if defined(MG_USE_OPEN_FILE)
  2847. size_t size = 0;
  2848. const char *buf = NULL;
  2849. if (!conn) {
  2850. return 0;
  2851. }
  2852. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2853. return 0;
  2854. }
  2855. if (conn->phys_ctx->callbacks.open_file) {
  2856. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2857. if (buf != NULL) {
  2858. if (filep == NULL) {
  2859. /* This is a file in memory, but we cannot store the
  2860. * properties
  2861. * now.
  2862. * Called from "is_file_in_memory" function. */
  2863. return 1;
  2864. }
  2865. /* NOTE: override filep->size only on success. Otherwise, it
  2866. * might
  2867. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2868. filep->access.membuf = buf;
  2869. filep->access.fp = NULL;
  2870. /* Size was set by the callback */
  2871. filep->stat.size = size;
  2872. /* Assume the data may change during runtime by setting
  2873. * last_modified = now */
  2874. filep->stat.last_modified = time(NULL);
  2875. filep->stat.is_directory = 0;
  2876. filep->stat.is_gzipped = 0;
  2877. }
  2878. }
  2879. return (buf != NULL);
  2880. #else
  2881. (void)conn;
  2882. (void)path;
  2883. (void)filep;
  2884. (void)mode;
  2885. return 0;
  2886. #endif
  2887. }
  2888. static int
  2889. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2890. {
  2891. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2892. }
  2893. static int
  2894. is_file_opened(const struct mg_file_access *fileacc)
  2895. {
  2896. if (!fileacc) {
  2897. return 0;
  2898. }
  2899. #if defined(MG_USE_OPEN_FILE)
  2900. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2901. #else
  2902. return (fileacc->fp != NULL);
  2903. #endif
  2904. }
  2905. #if !defined(NO_FILESYSTEMS)
  2906. static int mg_stat(const struct mg_connection *conn,
  2907. const char *path,
  2908. struct mg_file_stat *filep);
  2909. /* mg_fopen will open a file either in memory or on the disk.
  2910. * The input parameter path is a string in UTF-8 encoding.
  2911. * The input parameter mode is MG_FOPEN_MODE_*
  2912. * On success, either fp or membuf will be set in the output
  2913. * struct file. All status members will also be set.
  2914. * The function returns 1 on success, 0 on error. */
  2915. static int
  2916. mg_fopen(const struct mg_connection *conn,
  2917. const char *path,
  2918. int mode,
  2919. struct mg_file *filep)
  2920. {
  2921. int found;
  2922. if (!filep) {
  2923. return 0;
  2924. }
  2925. filep->access.fp = NULL;
  2926. #if defined(MG_USE_OPEN_FILE)
  2927. filep->access.membuf = NULL;
  2928. #endif
  2929. if (!is_file_in_memory(conn, path)) {
  2930. /* filep is initialized in mg_stat: all fields with memset to,
  2931. * some fields like size and modification date with values */
  2932. found = mg_stat(conn, path, &(filep->stat));
  2933. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2934. /* file does not exist and will not be created */
  2935. return 0;
  2936. }
  2937. #if defined(_WIN32)
  2938. {
  2939. wchar_t wbuf[W_PATH_MAX];
  2940. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2941. switch (mode) {
  2942. case MG_FOPEN_MODE_READ:
  2943. filep->access.fp = _wfopen(wbuf, L"rb");
  2944. break;
  2945. case MG_FOPEN_MODE_WRITE:
  2946. filep->access.fp = _wfopen(wbuf, L"wb");
  2947. break;
  2948. case MG_FOPEN_MODE_APPEND:
  2949. filep->access.fp = _wfopen(wbuf, L"ab");
  2950. break;
  2951. }
  2952. }
  2953. #else
  2954. /* Linux et al already use unicode. No need to convert. */
  2955. switch (mode) {
  2956. case MG_FOPEN_MODE_READ:
  2957. filep->access.fp = fopen(path, "r");
  2958. break;
  2959. case MG_FOPEN_MODE_WRITE:
  2960. filep->access.fp = fopen(path, "w");
  2961. break;
  2962. case MG_FOPEN_MODE_APPEND:
  2963. filep->access.fp = fopen(path, "a");
  2964. break;
  2965. }
  2966. #endif
  2967. if (!found) {
  2968. /* File did not exist before fopen was called.
  2969. * Maybe it has been created now. Get stat info
  2970. * like creation time now. */
  2971. found = mg_stat(conn, path, &(filep->stat));
  2972. (void)found;
  2973. }
  2974. /* file is on disk */
  2975. return (filep->access.fp != NULL);
  2976. } else {
  2977. #if defined(MG_USE_OPEN_FILE)
  2978. /* is_file_in_memory returned true */
  2979. if (open_file_in_memory(conn, path, filep, mode)) {
  2980. /* file is in memory */
  2981. return (filep->access.membuf != NULL);
  2982. }
  2983. #endif
  2984. }
  2985. /* Open failed */
  2986. return 0;
  2987. }
  2988. /* return 0 on success, just like fclose */
  2989. static int
  2990. mg_fclose(struct mg_file_access *fileacc)
  2991. {
  2992. int ret = -1;
  2993. if (fileacc != NULL) {
  2994. if (fileacc->fp != NULL) {
  2995. ret = fclose(fileacc->fp);
  2996. #if defined(MG_USE_OPEN_FILE)
  2997. } else if (fileacc->membuf != NULL) {
  2998. ret = 0;
  2999. #endif
  3000. }
  3001. /* reset all members of fileacc */
  3002. memset(fileacc, 0, sizeof(*fileacc));
  3003. }
  3004. return ret;
  3005. }
  3006. #endif /* NO_FILESYSTEMS */
  3007. static void
  3008. mg_strlcpy(register char *dst, register const char *src, size_t n)
  3009. {
  3010. for (; *src != '\0' && n > 1; n--) {
  3011. *dst++ = *src++;
  3012. }
  3013. *dst = '\0';
  3014. }
  3015. static int
  3016. lowercase(const char *s)
  3017. {
  3018. return tolower((unsigned char)*s);
  3019. }
  3020. int
  3021. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  3022. {
  3023. int diff = 0;
  3024. if (len > 0) {
  3025. do {
  3026. diff = lowercase(s1++) - lowercase(s2++);
  3027. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  3028. }
  3029. return diff;
  3030. }
  3031. int
  3032. mg_strcasecmp(const char *s1, const char *s2)
  3033. {
  3034. int diff;
  3035. do {
  3036. diff = lowercase(s1++) - lowercase(s2++);
  3037. } while (diff == 0 && s1[-1] != '\0');
  3038. return diff;
  3039. }
  3040. static char *
  3041. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3042. {
  3043. char *p;
  3044. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3045. * defined */
  3046. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3047. mg_strlcpy(p, ptr, len + 1);
  3048. }
  3049. return p;
  3050. }
  3051. static char *
  3052. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3053. {
  3054. return mg_strndup_ctx(str, strlen(str), ctx);
  3055. }
  3056. static char *
  3057. mg_strdup(const char *str)
  3058. {
  3059. return mg_strndup_ctx(str, strlen(str), NULL);
  3060. }
  3061. static const char *
  3062. mg_strcasestr(const char *big_str, const char *small_str)
  3063. {
  3064. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3065. if (big_len >= small_len) {
  3066. for (i = 0; i <= (big_len - small_len); i++) {
  3067. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3068. return big_str + i;
  3069. }
  3070. }
  3071. }
  3072. return NULL;
  3073. }
  3074. /* Return null terminated string of given maximum length.
  3075. * Report errors if length is exceeded. */
  3076. static void
  3077. mg_vsnprintf(const struct mg_connection *conn,
  3078. int *truncated,
  3079. char *buf,
  3080. size_t buflen,
  3081. const char *fmt,
  3082. va_list ap)
  3083. {
  3084. int n, ok;
  3085. if (buflen == 0) {
  3086. if (truncated) {
  3087. *truncated = 1;
  3088. }
  3089. return;
  3090. }
  3091. #if defined(__clang__)
  3092. #pragma clang diagnostic push
  3093. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3094. /* Using fmt as a non-literal is intended here, since it is mostly called
  3095. * indirectly by mg_snprintf */
  3096. #endif
  3097. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3098. ok = (n >= 0) && ((size_t)n < buflen);
  3099. #if defined(__clang__)
  3100. #pragma clang diagnostic pop
  3101. #endif
  3102. if (ok) {
  3103. if (truncated) {
  3104. *truncated = 0;
  3105. }
  3106. } else {
  3107. if (truncated) {
  3108. *truncated = 1;
  3109. }
  3110. mg_cry_internal(conn,
  3111. "truncating vsnprintf buffer: [%.*s]",
  3112. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3113. buf);
  3114. n = (int)buflen - 1;
  3115. }
  3116. buf[n] = '\0';
  3117. }
  3118. static void
  3119. mg_snprintf(const struct mg_connection *conn,
  3120. int *truncated,
  3121. char *buf,
  3122. size_t buflen,
  3123. const char *fmt,
  3124. ...)
  3125. {
  3126. va_list ap;
  3127. va_start(ap, fmt);
  3128. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3129. va_end(ap);
  3130. }
  3131. static int
  3132. get_option_index(const char *name)
  3133. {
  3134. int i;
  3135. for (i = 0; config_options[i].name != NULL; i++) {
  3136. if (strcmp(config_options[i].name, name) == 0) {
  3137. return i;
  3138. }
  3139. }
  3140. return -1;
  3141. }
  3142. const char *
  3143. mg_get_option(const struct mg_context *ctx, const char *name)
  3144. {
  3145. int i;
  3146. if ((i = get_option_index(name)) == -1) {
  3147. return NULL;
  3148. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3149. return "";
  3150. } else {
  3151. return ctx->dd.config[i];
  3152. }
  3153. }
  3154. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3155. struct mg_context *
  3156. mg_get_context(const struct mg_connection *conn)
  3157. {
  3158. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3159. }
  3160. void *
  3161. mg_get_user_data(const struct mg_context *ctx)
  3162. {
  3163. return (ctx == NULL) ? NULL : ctx->user_data;
  3164. }
  3165. void *
  3166. mg_get_user_context_data(const struct mg_connection *conn)
  3167. {
  3168. return mg_get_user_data(mg_get_context(conn));
  3169. }
  3170. void *
  3171. mg_get_thread_pointer(const struct mg_connection *conn)
  3172. {
  3173. /* both methods should return the same pointer */
  3174. if (conn) {
  3175. /* quick access, in case conn is known */
  3176. return conn->tls_user_ptr;
  3177. } else {
  3178. /* otherwise get pointer from thread local storage (TLS) */
  3179. struct mg_workerTLS *tls =
  3180. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3181. return tls->user_ptr;
  3182. }
  3183. }
  3184. void
  3185. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3186. {
  3187. if (conn != NULL) {
  3188. conn->request_info.conn_data = data;
  3189. }
  3190. }
  3191. void *
  3192. mg_get_user_connection_data(const struct mg_connection *conn)
  3193. {
  3194. if (conn != NULL) {
  3195. return conn->request_info.conn_data;
  3196. }
  3197. return NULL;
  3198. }
  3199. #if defined(MG_LEGACY_INTERFACE)
  3200. /* Deprecated: Use mg_get_server_ports instead. */
  3201. size_t
  3202. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3203. {
  3204. size_t i;
  3205. if (!ctx) {
  3206. return 0;
  3207. }
  3208. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3209. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3210. ports[i] =
  3211. #if defined(USE_IPV6)
  3212. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3213. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3214. :
  3215. #endif
  3216. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3217. }
  3218. return i;
  3219. }
  3220. #endif
  3221. int
  3222. mg_get_server_ports(const struct mg_context *ctx,
  3223. int size,
  3224. struct mg_server_port *ports)
  3225. {
  3226. int i, cnt = 0;
  3227. if (size <= 0) {
  3228. return -1;
  3229. }
  3230. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3231. if (!ctx) {
  3232. return -1;
  3233. }
  3234. if (!ctx->listening_sockets) {
  3235. return -1;
  3236. }
  3237. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3238. ports[cnt].port =
  3239. #if defined(USE_IPV6)
  3240. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3241. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3242. :
  3243. #endif
  3244. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3245. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3246. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3247. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3248. /* IPv4 */
  3249. ports[cnt].protocol = 1;
  3250. cnt++;
  3251. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3252. /* IPv6 */
  3253. ports[cnt].protocol = 3;
  3254. cnt++;
  3255. }
  3256. }
  3257. return cnt;
  3258. }
  3259. static void
  3260. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3261. {
  3262. buf[0] = '\0';
  3263. if (!usa) {
  3264. return;
  3265. }
  3266. if (usa->sa.sa_family == AF_INET) {
  3267. getnameinfo(&usa->sa,
  3268. sizeof(usa->sin),
  3269. buf,
  3270. (unsigned)len,
  3271. NULL,
  3272. 0,
  3273. NI_NUMERICHOST);
  3274. }
  3275. #if defined(USE_IPV6)
  3276. else if (usa->sa.sa_family == AF_INET6) {
  3277. getnameinfo(&usa->sa,
  3278. sizeof(usa->sin6),
  3279. buf,
  3280. (unsigned)len,
  3281. NULL,
  3282. 0,
  3283. NI_NUMERICHOST);
  3284. }
  3285. #endif
  3286. }
  3287. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3288. * included in all responses other than 100, 101, 5xx. */
  3289. static void
  3290. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3291. {
  3292. #if !defined(REENTRANT_TIME)
  3293. struct tm *tm;
  3294. tm = ((t != NULL) ? gmtime(t) : NULL);
  3295. if (tm != NULL) {
  3296. #else
  3297. struct tm _tm;
  3298. struct tm *tm = &_tm;
  3299. if (t != NULL) {
  3300. gmtime_r(t, tm);
  3301. #endif
  3302. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3303. } else {
  3304. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3305. buf[buf_len - 1] = '\0';
  3306. }
  3307. }
  3308. /* difftime for struct timespec. Return value is in seconds. */
  3309. static double
  3310. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3311. {
  3312. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3313. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3314. }
  3315. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3316. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3317. const char *func,
  3318. unsigned line,
  3319. const char *fmt,
  3320. va_list ap);
  3321. #include "external_mg_cry_internal_impl.inl"
  3322. #elif !defined(NO_FILESYSTEMS)
  3323. /* Print error message to the opened error log stream. */
  3324. static void
  3325. mg_cry_internal_impl(const struct mg_connection *conn,
  3326. const char *func,
  3327. unsigned line,
  3328. const char *fmt,
  3329. va_list ap)
  3330. {
  3331. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3332. struct mg_file fi;
  3333. time_t timestamp;
  3334. /* Unused, in the RELEASE build */
  3335. (void)func;
  3336. (void)line;
  3337. #if defined(GCC_DIAGNOSTIC)
  3338. #pragma GCC diagnostic push
  3339. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3340. #endif
  3341. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3342. #if defined(GCC_DIAGNOSTIC)
  3343. #pragma GCC diagnostic pop
  3344. #endif
  3345. buf[sizeof(buf) - 1] = 0;
  3346. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3347. if (!conn) {
  3348. puts(buf);
  3349. return;
  3350. }
  3351. /* Do not lock when getting the callback value, here and below.
  3352. * I suppose this is fine, since function cannot disappear in the
  3353. * same way string option can. */
  3354. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3355. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3356. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3357. if (mg_fopen(conn,
  3358. conn->dom_ctx->config[ERROR_LOG_FILE],
  3359. MG_FOPEN_MODE_APPEND,
  3360. &fi)
  3361. == 0) {
  3362. fi.access.fp = NULL;
  3363. }
  3364. } else {
  3365. fi.access.fp = NULL;
  3366. }
  3367. if (fi.access.fp != NULL) {
  3368. flockfile(fi.access.fp);
  3369. timestamp = time(NULL);
  3370. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3371. fprintf(fi.access.fp,
  3372. "[%010lu] [error] [client %s] ",
  3373. (unsigned long)timestamp,
  3374. src_addr);
  3375. if (conn->request_info.request_method != NULL) {
  3376. fprintf(fi.access.fp,
  3377. "%s %s: ",
  3378. conn->request_info.request_method,
  3379. conn->request_info.request_uri
  3380. ? conn->request_info.request_uri
  3381. : "");
  3382. }
  3383. fprintf(fi.access.fp, "%s", buf);
  3384. fputc('\n', fi.access.fp);
  3385. fflush(fi.access.fp);
  3386. funlockfile(fi.access.fp);
  3387. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3388. * mg_cry here anyway ;-) */
  3389. }
  3390. }
  3391. }
  3392. #else
  3393. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3394. #endif /* Externally provided function */
  3395. /* Construct fake connection structure. Used for logging, if connection
  3396. * is not applicable at the moment of logging. */
  3397. static struct mg_connection *
  3398. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3399. {
  3400. static const struct mg_connection conn_zero = {0};
  3401. *fc = conn_zero;
  3402. fc->phys_ctx = ctx;
  3403. fc->dom_ctx = &(ctx->dd);
  3404. return fc;
  3405. }
  3406. static void
  3407. mg_cry_internal_wrap(const struct mg_connection *conn,
  3408. struct mg_context *ctx,
  3409. const char *func,
  3410. unsigned line,
  3411. const char *fmt,
  3412. ...)
  3413. {
  3414. va_list ap;
  3415. va_start(ap, fmt);
  3416. if (!conn && ctx) {
  3417. struct mg_connection fc;
  3418. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3419. } else {
  3420. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3421. }
  3422. va_end(ap);
  3423. }
  3424. void
  3425. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3426. {
  3427. va_list ap;
  3428. va_start(ap, fmt);
  3429. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3430. va_end(ap);
  3431. }
  3432. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3433. const char *
  3434. mg_version(void)
  3435. {
  3436. return CIVETWEB_VERSION;
  3437. }
  3438. const struct mg_request_info *
  3439. mg_get_request_info(const struct mg_connection *conn)
  3440. {
  3441. if (!conn) {
  3442. return NULL;
  3443. }
  3444. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3445. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3446. char txt[16];
  3447. struct mg_workerTLS *tls =
  3448. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3449. sprintf(txt, "%03i", conn->response_info.status_code);
  3450. if (strlen(txt) == 3) {
  3451. memcpy(tls->txtbuf, txt, 4);
  3452. } else {
  3453. strcpy(tls->txtbuf, "ERR");
  3454. }
  3455. ((struct mg_connection *)conn)->request_info.local_uri =
  3456. ((struct mg_connection *)conn)->request_info.request_uri =
  3457. tls->txtbuf; /* use thread safe buffer */
  3458. ((struct mg_connection *)conn)->request_info.num_headers =
  3459. conn->response_info.num_headers;
  3460. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3461. conn->response_info.http_headers,
  3462. sizeof(conn->response_info.http_headers));
  3463. } else
  3464. #endif
  3465. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3466. return NULL;
  3467. }
  3468. return &conn->request_info;
  3469. }
  3470. const struct mg_response_info *
  3471. mg_get_response_info(const struct mg_connection *conn)
  3472. {
  3473. if (!conn) {
  3474. return NULL;
  3475. }
  3476. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3477. return NULL;
  3478. }
  3479. return &conn->response_info;
  3480. }
  3481. static const char *
  3482. get_proto_name(const struct mg_connection *conn)
  3483. {
  3484. #if defined(__clang__)
  3485. #pragma clang diagnostic push
  3486. #pragma clang diagnostic ignored "-Wunreachable-code"
  3487. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3488. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3489. * unreachable, but splitting into four different #ifdef clauses here is more
  3490. * complicated.
  3491. */
  3492. #endif
  3493. const struct mg_request_info *ri = &conn->request_info;
  3494. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3495. ? (ri->is_ssl ? "wss" : "ws")
  3496. : (ri->is_ssl ? "https" : "http"));
  3497. return proto;
  3498. #if defined(__clang__)
  3499. #pragma clang diagnostic pop
  3500. #endif
  3501. }
  3502. int
  3503. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3504. {
  3505. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3506. return -1;
  3507. } else {
  3508. int truncated = 0;
  3509. const struct mg_request_info *ri = &conn->request_info;
  3510. const char *proto = get_proto_name(conn);
  3511. if (ri->local_uri == NULL) {
  3512. return -1;
  3513. }
  3514. if ((ri->request_uri != NULL)
  3515. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3516. /* The request uri is different from the local uri.
  3517. * This is usually if an absolute URI, including server
  3518. * name has been provided. */
  3519. mg_snprintf(conn,
  3520. &truncated,
  3521. buf,
  3522. buflen,
  3523. "%s://%s",
  3524. proto,
  3525. ri->request_uri);
  3526. if (truncated) {
  3527. return -1;
  3528. }
  3529. return 0;
  3530. } else {
  3531. /* The common case is a relative URI, so we have to
  3532. * construct an absolute URI from server name and port */
  3533. #if defined(USE_IPV6)
  3534. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3535. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3536. : htons(conn->client.lsa.sin.sin_port);
  3537. #else
  3538. int port = htons(conn->client.lsa.sin.sin_port);
  3539. #endif
  3540. int def_port = ri->is_ssl ? 443 : 80;
  3541. int auth_domain_check_enabled =
  3542. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3543. && (!mg_strcasecmp(
  3544. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3545. const char *server_domain =
  3546. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3547. char portstr[16];
  3548. char server_ip[48];
  3549. if (port != def_port) {
  3550. sprintf(portstr, ":%u", (unsigned)port);
  3551. } else {
  3552. portstr[0] = 0;
  3553. }
  3554. if (!auth_domain_check_enabled || !server_domain) {
  3555. sockaddr_to_string(server_ip,
  3556. sizeof(server_ip),
  3557. &conn->client.lsa);
  3558. server_domain = server_ip;
  3559. }
  3560. mg_snprintf(conn,
  3561. &truncated,
  3562. buf,
  3563. buflen,
  3564. "%s://%s%s%s",
  3565. proto,
  3566. server_domain,
  3567. portstr,
  3568. ri->local_uri);
  3569. if (truncated) {
  3570. return -1;
  3571. }
  3572. return 0;
  3573. }
  3574. }
  3575. }
  3576. /* Skip the characters until one of the delimiters characters found.
  3577. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3578. * Advance pointer to buffer to the next word. Return found 0-terminated
  3579. * word.
  3580. * Delimiters can be quoted with quotechar. */
  3581. static char *
  3582. skip_quoted(char **buf,
  3583. const char *delimiters,
  3584. const char *whitespace,
  3585. char quotechar)
  3586. {
  3587. char *p, *begin_word, *end_word, *end_whitespace;
  3588. begin_word = *buf;
  3589. end_word = begin_word + strcspn(begin_word, delimiters);
  3590. /* Check for quotechar */
  3591. if (end_word > begin_word) {
  3592. p = end_word - 1;
  3593. while (*p == quotechar) {
  3594. /* While the delimiter is quoted, look for the next delimiter.
  3595. */
  3596. /* This happens, e.g., in calls from parse_auth_header,
  3597. * if the user name contains a " character. */
  3598. /* If there is anything beyond end_word, copy it. */
  3599. if (*end_word != '\0') {
  3600. size_t end_off = strcspn(end_word + 1, delimiters);
  3601. memmove(p, end_word, end_off + 1);
  3602. p += end_off; /* p must correspond to end_word - 1 */
  3603. end_word += end_off + 1;
  3604. } else {
  3605. *p = '\0';
  3606. break;
  3607. }
  3608. }
  3609. for (p++; p < end_word; p++) {
  3610. *p = '\0';
  3611. }
  3612. }
  3613. if (*end_word == '\0') {
  3614. *buf = end_word;
  3615. } else {
  3616. #if defined(GCC_DIAGNOSTIC)
  3617. /* Disable spurious conversion warning for GCC */
  3618. #pragma GCC diagnostic push
  3619. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3620. #endif /* defined(GCC_DIAGNOSTIC) */
  3621. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3622. #if defined(GCC_DIAGNOSTIC)
  3623. #pragma GCC diagnostic pop
  3624. #endif /* defined(GCC_DIAGNOSTIC) */
  3625. for (p = end_word; p < end_whitespace; p++) {
  3626. *p = '\0';
  3627. }
  3628. *buf = end_whitespace;
  3629. }
  3630. return begin_word;
  3631. }
  3632. /* Return HTTP header value, or NULL if not found. */
  3633. static const char *
  3634. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3635. {
  3636. int i;
  3637. for (i = 0; i < num_hdr; i++) {
  3638. if (!mg_strcasecmp(name, hdr[i].name)) {
  3639. return hdr[i].value;
  3640. }
  3641. }
  3642. return NULL;
  3643. }
  3644. #if defined(USE_WEBSOCKET)
  3645. /* Retrieve requested HTTP header multiple values, and return the number of
  3646. * found occurrences */
  3647. static int
  3648. get_req_headers(const struct mg_request_info *ri,
  3649. const char *name,
  3650. const char **output,
  3651. int output_max_size)
  3652. {
  3653. int i;
  3654. int cnt = 0;
  3655. if (ri) {
  3656. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3657. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3658. output[cnt++] = ri->http_headers[i].value;
  3659. }
  3660. }
  3661. }
  3662. return cnt;
  3663. }
  3664. #endif
  3665. const char *
  3666. mg_get_header(const struct mg_connection *conn, const char *name)
  3667. {
  3668. if (!conn) {
  3669. return NULL;
  3670. }
  3671. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3672. return get_header(conn->request_info.http_headers,
  3673. conn->request_info.num_headers,
  3674. name);
  3675. }
  3676. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3677. return get_header(conn->response_info.http_headers,
  3678. conn->response_info.num_headers,
  3679. name);
  3680. }
  3681. return NULL;
  3682. }
  3683. static const char *
  3684. get_http_version(const struct mg_connection *conn)
  3685. {
  3686. if (!conn) {
  3687. return NULL;
  3688. }
  3689. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3690. return conn->request_info.http_version;
  3691. }
  3692. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3693. return conn->response_info.http_version;
  3694. }
  3695. return NULL;
  3696. }
  3697. /* A helper function for traversing a comma separated list of values.
  3698. * It returns a list pointer shifted to the next value, or NULL if the end
  3699. * of the list found.
  3700. * Value is stored in val vector. If value has form "x=y", then eq_val
  3701. * vector is initialized to point to the "y" part, and val vector length
  3702. * is adjusted to point only to "x". */
  3703. static const char *
  3704. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3705. {
  3706. int end;
  3707. reparse:
  3708. if (val == NULL || list == NULL || *list == '\0') {
  3709. /* End of the list */
  3710. return NULL;
  3711. }
  3712. /* Skip over leading LWS */
  3713. while (*list == ' ' || *list == '\t')
  3714. list++;
  3715. val->ptr = list;
  3716. if ((list = strchr(val->ptr, ',')) != NULL) {
  3717. /* Comma found. Store length and shift the list ptr */
  3718. val->len = ((size_t)(list - val->ptr));
  3719. list++;
  3720. } else {
  3721. /* This value is the last one */
  3722. list = val->ptr + strlen(val->ptr);
  3723. val->len = ((size_t)(list - val->ptr));
  3724. }
  3725. /* Adjust length for trailing LWS */
  3726. end = (int)val->len - 1;
  3727. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3728. end--;
  3729. val->len = (size_t)(end) + (size_t)(1);
  3730. if (val->len == 0) {
  3731. /* Ignore any empty entries. */
  3732. goto reparse;
  3733. }
  3734. if (eq_val != NULL) {
  3735. /* Value has form "x=y", adjust pointers and lengths
  3736. * so that val points to "x", and eq_val points to "y". */
  3737. eq_val->len = 0;
  3738. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3739. if (eq_val->ptr != NULL) {
  3740. eq_val->ptr++; /* Skip over '=' character */
  3741. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3742. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3743. }
  3744. }
  3745. return list;
  3746. }
  3747. /* A helper function for checking if a comma separated list of values
  3748. * contains
  3749. * the given option (case insensitvely).
  3750. * 'header' can be NULL, in which case false is returned. */
  3751. static int
  3752. header_has_option(const char *header, const char *option)
  3753. {
  3754. struct vec opt_vec;
  3755. struct vec eq_vec;
  3756. DEBUG_ASSERT(option != NULL);
  3757. DEBUG_ASSERT(option[0] != '\0');
  3758. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3759. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3760. return 1;
  3761. }
  3762. return 0;
  3763. }
  3764. /* Perform case-insensitive match of string against pattern */
  3765. static ptrdiff_t
  3766. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3767. {
  3768. const char *or_str;
  3769. ptrdiff_t i, j, len, res;
  3770. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3771. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3772. return (res > 0) ? res
  3773. : match_prefix(or_str + 1,
  3774. (size_t)((pattern + pattern_len)
  3775. - (or_str + 1)),
  3776. str);
  3777. }
  3778. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3779. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3780. continue;
  3781. } else if (pattern[i] == '$') {
  3782. return (str[j] == '\0') ? j : -1;
  3783. } else if (pattern[i] == '*') {
  3784. i++;
  3785. if (pattern[i] == '*') {
  3786. i++;
  3787. len = (ptrdiff_t)strlen(str + j);
  3788. } else {
  3789. len = (ptrdiff_t)strcspn(str + j, "/");
  3790. }
  3791. if (i == (ptrdiff_t)pattern_len) {
  3792. return j + len;
  3793. }
  3794. do {
  3795. res = match_prefix(pattern + i,
  3796. (pattern_len - (size_t)i),
  3797. str + j + len);
  3798. } while (res == -1 && len-- > 0);
  3799. return (res == -1) ? -1 : j + res + len;
  3800. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3801. return -1;
  3802. }
  3803. }
  3804. return (ptrdiff_t)j;
  3805. }
  3806. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3807. * This function must tolerate situations when connection info is not
  3808. * set up, for example if request parsing failed. */
  3809. static int
  3810. should_keep_alive(const struct mg_connection *conn)
  3811. {
  3812. const char *http_version;
  3813. const char *header;
  3814. /* First satisfy needs of the server */
  3815. if ((conn == NULL) || conn->must_close) {
  3816. /* Close, if civetweb framework needs to close */
  3817. return 0;
  3818. }
  3819. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3820. /* Close, if keep alive is not enabled */
  3821. return 0;
  3822. }
  3823. /* Check explicit wish of the client */
  3824. header = mg_get_header(conn, "Connection");
  3825. if (header) {
  3826. /* If there is a connection header from the client, obey */
  3827. if (header_has_option(header, "keep-alive")) {
  3828. return 1;
  3829. }
  3830. return 0;
  3831. }
  3832. /* Use default of the standard */
  3833. http_version = get_http_version(conn);
  3834. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3835. /* HTTP 1.1 default is keep alive */
  3836. return 1;
  3837. }
  3838. /* HTTP 1.0 (and earlier) default is to close the connection */
  3839. return 0;
  3840. }
  3841. static int
  3842. should_decode_url(const struct mg_connection *conn)
  3843. {
  3844. if (!conn || !conn->dom_ctx) {
  3845. return 0;
  3846. }
  3847. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3848. }
  3849. static const char *
  3850. suggest_connection_header(const struct mg_connection *conn)
  3851. {
  3852. return should_keep_alive(conn) ? "keep-alive" : "close";
  3853. }
  3854. static int
  3855. send_no_cache_header(struct mg_connection *conn)
  3856. {
  3857. /* Send all current and obsolete cache opt-out directives. */
  3858. return mg_printf(conn,
  3859. "Cache-Control: no-cache, no-store, "
  3860. "must-revalidate, private, max-age=0\r\n"
  3861. "Pragma: no-cache\r\n"
  3862. "Expires: 0\r\n");
  3863. }
  3864. static int
  3865. send_static_cache_header(struct mg_connection *conn)
  3866. {
  3867. #if !defined(NO_CACHING)
  3868. int max_age;
  3869. const char *cache_control =
  3870. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3871. if (cache_control != NULL) {
  3872. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3873. }
  3874. /* Read the server config to check how long a file may be cached.
  3875. * The configuration is in seconds. */
  3876. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3877. if (max_age <= 0) {
  3878. /* 0 means "do not cache". All values <0 are reserved
  3879. * and may be used differently in the future. */
  3880. /* If a file should not be cached, do not only send
  3881. * max-age=0, but also pragmas and Expires headers. */
  3882. return send_no_cache_header(conn);
  3883. }
  3884. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3885. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3886. /* See also https://www.mnot.net/cache_docs/ */
  3887. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3888. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3889. * leap
  3890. * year to 31622400 seconds. For the moment, we just send whatever has
  3891. * been configured, still the behavior for >1 year should be considered
  3892. * as undefined. */
  3893. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3894. #else /* NO_CACHING */
  3895. return send_no_cache_header(conn);
  3896. #endif /* !NO_CACHING */
  3897. }
  3898. static int
  3899. send_additional_header(struct mg_connection *conn)
  3900. {
  3901. int i = 0;
  3902. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3903. #if !defined(NO_SSL)
  3904. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3905. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3906. if (max_age >= 0) {
  3907. i += mg_printf(conn,
  3908. "Strict-Transport-Security: max-age=%u\r\n",
  3909. (unsigned)max_age);
  3910. }
  3911. }
  3912. #endif
  3913. if (header && header[0]) {
  3914. i += mg_printf(conn, "%s\r\n", header);
  3915. }
  3916. return i;
  3917. }
  3918. #if !defined(NO_FILESYSTEMS)
  3919. static void handle_file_based_request(struct mg_connection *conn,
  3920. const char *path,
  3921. struct mg_file *filep);
  3922. #endif /* NO_FILESYSTEMS */
  3923. const char *
  3924. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3925. {
  3926. /* See IANA HTTP status code assignment:
  3927. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3928. */
  3929. switch (response_code) {
  3930. /* RFC2616 Section 10.1 - Informational 1xx */
  3931. case 100:
  3932. return "Continue"; /* RFC2616 Section 10.1.1 */
  3933. case 101:
  3934. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3935. case 102:
  3936. return "Processing"; /* RFC2518 Section 10.1 */
  3937. /* RFC2616 Section 10.2 - Successful 2xx */
  3938. case 200:
  3939. return "OK"; /* RFC2616 Section 10.2.1 */
  3940. case 201:
  3941. return "Created"; /* RFC2616 Section 10.2.2 */
  3942. case 202:
  3943. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3944. case 203:
  3945. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3946. case 204:
  3947. return "No Content"; /* RFC2616 Section 10.2.5 */
  3948. case 205:
  3949. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3950. case 206:
  3951. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3952. case 207:
  3953. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3954. */
  3955. case 208:
  3956. return "Already Reported"; /* RFC5842 Section 7.1 */
  3957. case 226:
  3958. return "IM used"; /* RFC3229 Section 10.4.1 */
  3959. /* RFC2616 Section 10.3 - Redirection 3xx */
  3960. case 300:
  3961. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3962. case 301:
  3963. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3964. case 302:
  3965. return "Found"; /* RFC2616 Section 10.3.3 */
  3966. case 303:
  3967. return "See Other"; /* RFC2616 Section 10.3.4 */
  3968. case 304:
  3969. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3970. case 305:
  3971. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3972. case 307:
  3973. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3974. case 308:
  3975. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3976. /* RFC2616 Section 10.4 - Client Error 4xx */
  3977. case 400:
  3978. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3979. case 401:
  3980. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3981. case 402:
  3982. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3983. case 403:
  3984. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3985. case 404:
  3986. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3987. case 405:
  3988. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3989. case 406:
  3990. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3991. case 407:
  3992. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3993. case 408:
  3994. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3995. case 409:
  3996. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3997. case 410:
  3998. return "Gone"; /* RFC2616 Section 10.4.11 */
  3999. case 411:
  4000. return "Length Required"; /* RFC2616 Section 10.4.12 */
  4001. case 412:
  4002. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  4003. case 413:
  4004. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  4005. case 414:
  4006. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  4007. case 415:
  4008. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  4009. case 416:
  4010. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  4011. */
  4012. case 417:
  4013. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  4014. case 421:
  4015. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  4016. case 422:
  4017. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  4018. * Section 11.2 */
  4019. case 423:
  4020. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  4021. case 424:
  4022. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  4023. * Section 11.4 */
  4024. case 426:
  4025. return "Upgrade Required"; /* RFC 2817 Section 4 */
  4026. case 428:
  4027. return "Precondition Required"; /* RFC 6585, Section 3 */
  4028. case 429:
  4029. return "Too Many Requests"; /* RFC 6585, Section 4 */
  4030. case 431:
  4031. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  4032. case 451:
  4033. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  4034. * Section 3 */
  4035. /* RFC2616 Section 10.5 - Server Error 5xx */
  4036. case 500:
  4037. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  4038. case 501:
  4039. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  4040. case 502:
  4041. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4042. case 503:
  4043. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4044. case 504:
  4045. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4046. case 505:
  4047. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4048. case 506:
  4049. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4050. case 507:
  4051. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4052. * Section 11.5 */
  4053. case 508:
  4054. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4055. case 510:
  4056. return "Not Extended"; /* RFC 2774, Section 7 */
  4057. case 511:
  4058. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4059. /* Other status codes, not shown in the IANA HTTP status code
  4060. * assignment.
  4061. * E.g., "de facto" standards due to common use, ... */
  4062. case 418:
  4063. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4064. case 419:
  4065. return "Authentication Timeout"; /* common use */
  4066. case 420:
  4067. return "Enhance Your Calm"; /* common use */
  4068. case 440:
  4069. return "Login Timeout"; /* common use */
  4070. case 509:
  4071. return "Bandwidth Limit Exceeded"; /* common use */
  4072. default:
  4073. /* This error code is unknown. This should not happen. */
  4074. if (conn) {
  4075. mg_cry_internal(conn,
  4076. "Unknown HTTP response code: %u",
  4077. response_code);
  4078. }
  4079. /* Return at least a category according to RFC 2616 Section 10. */
  4080. if (response_code >= 100 && response_code < 200) {
  4081. /* Unknown informational status code */
  4082. return "Information";
  4083. }
  4084. if (response_code >= 200 && response_code < 300) {
  4085. /* Unknown success code */
  4086. return "Success";
  4087. }
  4088. if (response_code >= 300 && response_code < 400) {
  4089. /* Unknown redirection code */
  4090. return "Redirection";
  4091. }
  4092. if (response_code >= 400 && response_code < 500) {
  4093. /* Unknown request error code */
  4094. return "Client Error";
  4095. }
  4096. if (response_code >= 500 && response_code < 600) {
  4097. /* Unknown server error code */
  4098. return "Server Error";
  4099. }
  4100. /* Response code not even within reasonable range */
  4101. return "";
  4102. }
  4103. }
  4104. static int
  4105. mg_send_http_error_impl(struct mg_connection *conn,
  4106. int status,
  4107. const char *fmt,
  4108. va_list args)
  4109. {
  4110. char errmsg_buf[MG_BUF_LEN];
  4111. va_list ap;
  4112. int has_body;
  4113. char date[64];
  4114. time_t curtime = time(NULL);
  4115. #if !defined(NO_FILESYSTEMS)
  4116. char path_buf[PATH_MAX];
  4117. int len, i, page_handler_found, scope, truncated;
  4118. const char *error_handler = NULL;
  4119. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4120. const char *error_page_file_ext, *tstr;
  4121. #endif /* NO_FILESYSTEMS */
  4122. int handled_by_callback = 0;
  4123. const char *status_text = mg_get_response_code_text(conn, status);
  4124. if ((conn == NULL) || (fmt == NULL)) {
  4125. return -2;
  4126. }
  4127. /* Set status (for log) */
  4128. conn->status_code = status;
  4129. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4130. has_body = ((status > 199) && (status != 204) && (status != 304));
  4131. /* Prepare message in buf, if required */
  4132. if (has_body
  4133. || (!conn->in_error_handler
  4134. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4135. /* Store error message in errmsg_buf */
  4136. va_copy(ap, args);
  4137. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4138. va_end(ap);
  4139. /* In a debug build, print all html errors */
  4140. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4141. }
  4142. /* If there is a http_error callback, call it.
  4143. * But don't do it recursively, if callback calls mg_send_http_error again.
  4144. */
  4145. if (!conn->in_error_handler
  4146. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4147. /* Mark in_error_handler to avoid recursion and call user callback. */
  4148. conn->in_error_handler = 1;
  4149. handled_by_callback =
  4150. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4151. == 0);
  4152. conn->in_error_handler = 0;
  4153. }
  4154. if (!handled_by_callback) {
  4155. /* Check for recursion */
  4156. if (conn->in_error_handler) {
  4157. DEBUG_TRACE(
  4158. "Recursion when handling error %u - fall back to default",
  4159. status);
  4160. #if !defined(NO_FILESYSTEMS)
  4161. } else {
  4162. /* Send user defined error pages, if defined */
  4163. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4164. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4165. page_handler_found = 0;
  4166. if (error_handler != NULL) {
  4167. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4168. switch (scope) {
  4169. case 1: /* Handler for specific error, e.g. 404 error */
  4170. mg_snprintf(conn,
  4171. &truncated,
  4172. path_buf,
  4173. sizeof(path_buf) - 32,
  4174. "%serror%03u.",
  4175. error_handler,
  4176. status);
  4177. break;
  4178. case 2: /* Handler for error group, e.g., 5xx error
  4179. * handler
  4180. * for all server errors (500-599) */
  4181. mg_snprintf(conn,
  4182. &truncated,
  4183. path_buf,
  4184. sizeof(path_buf) - 32,
  4185. "%serror%01uxx.",
  4186. error_handler,
  4187. status / 100);
  4188. break;
  4189. default: /* Handler for all errors */
  4190. mg_snprintf(conn,
  4191. &truncated,
  4192. path_buf,
  4193. sizeof(path_buf) - 32,
  4194. "%serror.",
  4195. error_handler);
  4196. break;
  4197. }
  4198. /* String truncation in buf may only occur if
  4199. * error_handler is too long. This string is
  4200. * from the config, not from a client. */
  4201. (void)truncated;
  4202. /* The following code is redundant, but it should avoid
  4203. * false positives in static source code analyzers and
  4204. * vulnerability scanners.
  4205. */
  4206. path_buf[sizeof(path_buf) - 32] = 0;
  4207. len = (int)strlen(path_buf);
  4208. if (len > (int)sizeof(path_buf) - 32) {
  4209. len = (int)sizeof(path_buf) - 32;
  4210. }
  4211. /* Start with the file extenstion from the configuration. */
  4212. tstr = strchr(error_page_file_ext, '.');
  4213. while (tstr) {
  4214. for (i = 1;
  4215. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4216. i++) {
  4217. /* buffer overrun is not possible here, since
  4218. * (i < 32) && (len < sizeof(path_buf) - 32)
  4219. * ==> (i + len) < sizeof(path_buf) */
  4220. path_buf[len + i - 1] = tstr[i];
  4221. }
  4222. /* buffer overrun is not possible here, since
  4223. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4224. * ==> (i + len) <= sizeof(path_buf) */
  4225. path_buf[len + i - 1] = 0;
  4226. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4227. DEBUG_TRACE("Check error page %s - found",
  4228. path_buf);
  4229. page_handler_found = 1;
  4230. break;
  4231. }
  4232. DEBUG_TRACE("Check error page %s - not found",
  4233. path_buf);
  4234. /* Continue with the next file extenstion from the
  4235. * configuration (if there is a next one). */
  4236. tstr = strchr(tstr + i, '.');
  4237. }
  4238. }
  4239. }
  4240. if (page_handler_found) {
  4241. conn->in_error_handler = 1;
  4242. handle_file_based_request(conn, path_buf, &error_page_file);
  4243. conn->in_error_handler = 0;
  4244. return 0;
  4245. }
  4246. #endif /* NO_FILESYSTEMS */
  4247. }
  4248. /* No custom error page. Send default error page. */
  4249. gmt_time_string(date, sizeof(date), &curtime);
  4250. conn->must_close = 1;
  4251. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4252. send_no_cache_header(conn);
  4253. send_additional_header(conn);
  4254. if (has_body) {
  4255. mg_printf(conn,
  4256. "%s",
  4257. "Content-Type: text/plain; charset=utf-8\r\n");
  4258. }
  4259. mg_printf(conn,
  4260. "Date: %s\r\n"
  4261. "Connection: close\r\n\r\n",
  4262. date);
  4263. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4264. if (has_body) {
  4265. /* For other errors, send a generic error message. */
  4266. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4267. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4268. } else {
  4269. /* No body allowed. Close the connection. */
  4270. DEBUG_TRACE("Error %i", status);
  4271. }
  4272. }
  4273. return 0;
  4274. }
  4275. int
  4276. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4277. {
  4278. va_list ap;
  4279. int ret;
  4280. va_start(ap, fmt);
  4281. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4282. va_end(ap);
  4283. return ret;
  4284. }
  4285. int
  4286. mg_send_http_ok(struct mg_connection *conn,
  4287. const char *mime_type,
  4288. long long content_length)
  4289. {
  4290. char date[64];
  4291. time_t curtime = time(NULL);
  4292. if ((mime_type == NULL) || (*mime_type == 0)) {
  4293. /* No content type defined: default to text/html */
  4294. mime_type = "text/html";
  4295. }
  4296. gmt_time_string(date, sizeof(date), &curtime);
  4297. mg_printf(conn,
  4298. "HTTP/1.1 200 OK\r\n"
  4299. "Content-Type: %s\r\n"
  4300. "Date: %s\r\n"
  4301. "Connection: %s\r\n",
  4302. mime_type,
  4303. date,
  4304. suggest_connection_header(conn));
  4305. send_no_cache_header(conn);
  4306. send_additional_header(conn);
  4307. if (content_length < 0) {
  4308. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4309. } else {
  4310. mg_printf(conn,
  4311. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4312. (uint64_t)content_length);
  4313. }
  4314. return 0;
  4315. }
  4316. int
  4317. mg_send_http_redirect(struct mg_connection *conn,
  4318. const char *target_url,
  4319. int redirect_code)
  4320. {
  4321. /* Send a 30x redirect response.
  4322. *
  4323. * Redirect types (status codes):
  4324. *
  4325. * Status | Perm/Temp | Method | Version
  4326. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4327. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4328. * 303 | temporary | always use GET | HTTP/1.1
  4329. * 307 | temporary | always keep method | HTTP/1.1
  4330. * 308 | permanent | always keep method | HTTP/1.1
  4331. */
  4332. const char *redirect_text;
  4333. int ret;
  4334. size_t content_len = 0;
  4335. char reply[MG_BUF_LEN];
  4336. /* In case redirect_code=0, use 307. */
  4337. if (redirect_code == 0) {
  4338. redirect_code = 307;
  4339. }
  4340. /* In case redirect_code is none of the above, return error. */
  4341. if ((redirect_code != 301) && (redirect_code != 302)
  4342. && (redirect_code != 303) && (redirect_code != 307)
  4343. && (redirect_code != 308)) {
  4344. /* Parameter error */
  4345. return -2;
  4346. }
  4347. /* Get proper text for response code */
  4348. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4349. /* If target_url is not defined, redirect to "/". */
  4350. if ((target_url == NULL) || (*target_url == 0)) {
  4351. target_url = "/";
  4352. }
  4353. #if defined(MG_SEND_REDIRECT_BODY)
  4354. /* TODO: condition name? */
  4355. /* Prepare a response body with a hyperlink.
  4356. *
  4357. * According to RFC2616 (and RFC1945 before):
  4358. * Unless the request method was HEAD, the entity of the
  4359. * response SHOULD contain a short hypertext note with a hyperlink to
  4360. * the new URI(s).
  4361. *
  4362. * However, this response body is not useful in M2M communication.
  4363. * Probably the original reason in the RFC was, clients not supporting
  4364. * a 30x HTTP redirect could still show the HTML page and let the user
  4365. * press the link. Since current browsers support 30x HTTP, the additional
  4366. * HTML body does not seem to make sense anymore.
  4367. *
  4368. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4369. * but it only notes:
  4370. * The server's response payload usually contains a short
  4371. * hypertext note with a hyperlink to the new URI(s).
  4372. *
  4373. * Deactivated by default. If you need the 30x body, set the define.
  4374. */
  4375. mg_snprintf(
  4376. conn,
  4377. NULL /* ignore truncation */,
  4378. reply,
  4379. sizeof(reply),
  4380. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4381. redirect_text,
  4382. target_url,
  4383. target_url);
  4384. content_len = strlen(reply);
  4385. #else
  4386. reply[0] = 0;
  4387. #endif
  4388. /* Do not send any additional header. For all other options,
  4389. * including caching, there are suitable defaults. */
  4390. ret = mg_printf(conn,
  4391. "HTTP/1.1 %i %s\r\n"
  4392. "Location: %s\r\n"
  4393. "Content-Length: %u\r\n"
  4394. "Connection: %s\r\n\r\n",
  4395. redirect_code,
  4396. redirect_text,
  4397. target_url,
  4398. (unsigned int)content_len,
  4399. suggest_connection_header(conn));
  4400. /* Send response body */
  4401. if (ret > 0) {
  4402. /* ... unless it is a HEAD request */
  4403. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4404. ret = mg_write(conn, reply, content_len);
  4405. }
  4406. }
  4407. return (ret > 0) ? ret : -1;
  4408. }
  4409. #if defined(_WIN32)
  4410. /* Create substitutes for POSIX functions in Win32. */
  4411. #if defined(GCC_DIAGNOSTIC)
  4412. /* Show no warning in case system functions are not used. */
  4413. #pragma GCC diagnostic push
  4414. #pragma GCC diagnostic ignored "-Wunused-function"
  4415. #endif
  4416. static int
  4417. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4418. {
  4419. (void)unused;
  4420. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4421. InitializeCriticalSection(&mutex->sec);
  4422. return 0;
  4423. }
  4424. static int
  4425. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4426. {
  4427. DeleteCriticalSection(&mutex->sec);
  4428. return 0;
  4429. }
  4430. static int
  4431. pthread_mutex_lock(pthread_mutex_t *mutex)
  4432. {
  4433. EnterCriticalSection(&mutex->sec);
  4434. return 0;
  4435. }
  4436. static int
  4437. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4438. {
  4439. LeaveCriticalSection(&mutex->sec);
  4440. return 0;
  4441. }
  4442. FUNCTION_MAY_BE_UNUSED
  4443. static int
  4444. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4445. {
  4446. (void)unused;
  4447. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4448. cv->waiting_thread = NULL;
  4449. return 0;
  4450. }
  4451. FUNCTION_MAY_BE_UNUSED
  4452. static int
  4453. pthread_cond_timedwait(pthread_cond_t *cv,
  4454. pthread_mutex_t *mutex,
  4455. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4456. {
  4457. struct mg_workerTLS **ptls,
  4458. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4459. int ok;
  4460. int64_t nsnow, nswaitabs, nswaitrel;
  4461. DWORD mswaitrel;
  4462. pthread_mutex_lock(&cv->threadIdSec);
  4463. /* Add this thread to cv's waiting list */
  4464. ptls = &cv->waiting_thread;
  4465. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4466. ;
  4467. tls->next_waiting_thread = NULL;
  4468. *ptls = tls;
  4469. pthread_mutex_unlock(&cv->threadIdSec);
  4470. if (abstime) {
  4471. nsnow = mg_get_current_time_ns();
  4472. nswaitabs =
  4473. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4474. nswaitrel = nswaitabs - nsnow;
  4475. if (nswaitrel < 0) {
  4476. nswaitrel = 0;
  4477. }
  4478. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4479. } else {
  4480. mswaitrel = (DWORD)INFINITE;
  4481. }
  4482. pthread_mutex_unlock(mutex);
  4483. ok = (WAIT_OBJECT_0
  4484. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4485. if (!ok) {
  4486. ok = 1;
  4487. pthread_mutex_lock(&cv->threadIdSec);
  4488. ptls = &cv->waiting_thread;
  4489. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4490. if (*ptls == tls) {
  4491. *ptls = tls->next_waiting_thread;
  4492. ok = 0;
  4493. break;
  4494. }
  4495. }
  4496. pthread_mutex_unlock(&cv->threadIdSec);
  4497. if (ok) {
  4498. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4499. (DWORD)INFINITE);
  4500. }
  4501. }
  4502. /* This thread has been removed from cv's waiting list */
  4503. pthread_mutex_lock(mutex);
  4504. return ok ? 0 : -1;
  4505. }
  4506. FUNCTION_MAY_BE_UNUSED
  4507. static int
  4508. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4509. {
  4510. return pthread_cond_timedwait(cv, mutex, NULL);
  4511. }
  4512. FUNCTION_MAY_BE_UNUSED
  4513. static int
  4514. pthread_cond_signal(pthread_cond_t *cv)
  4515. {
  4516. HANDLE wkup = NULL;
  4517. BOOL ok = FALSE;
  4518. pthread_mutex_lock(&cv->threadIdSec);
  4519. if (cv->waiting_thread) {
  4520. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4521. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4522. ok = SetEvent(wkup);
  4523. DEBUG_ASSERT(ok);
  4524. }
  4525. pthread_mutex_unlock(&cv->threadIdSec);
  4526. return ok ? 0 : 1;
  4527. }
  4528. FUNCTION_MAY_BE_UNUSED
  4529. static int
  4530. pthread_cond_broadcast(pthread_cond_t *cv)
  4531. {
  4532. pthread_mutex_lock(&cv->threadIdSec);
  4533. while (cv->waiting_thread) {
  4534. pthread_cond_signal(cv);
  4535. }
  4536. pthread_mutex_unlock(&cv->threadIdSec);
  4537. return 0;
  4538. }
  4539. FUNCTION_MAY_BE_UNUSED
  4540. static int
  4541. pthread_cond_destroy(pthread_cond_t *cv)
  4542. {
  4543. pthread_mutex_lock(&cv->threadIdSec);
  4544. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4545. pthread_mutex_unlock(&cv->threadIdSec);
  4546. pthread_mutex_destroy(&cv->threadIdSec);
  4547. return 0;
  4548. }
  4549. #if defined(ALTERNATIVE_QUEUE)
  4550. FUNCTION_MAY_BE_UNUSED
  4551. static void *
  4552. event_create(void)
  4553. {
  4554. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4555. }
  4556. FUNCTION_MAY_BE_UNUSED
  4557. static int
  4558. event_wait(void *eventhdl)
  4559. {
  4560. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4561. return (res == WAIT_OBJECT_0);
  4562. }
  4563. FUNCTION_MAY_BE_UNUSED
  4564. static int
  4565. event_signal(void *eventhdl)
  4566. {
  4567. return (int)SetEvent((HANDLE)eventhdl);
  4568. }
  4569. FUNCTION_MAY_BE_UNUSED
  4570. static void
  4571. event_destroy(void *eventhdl)
  4572. {
  4573. CloseHandle((HANDLE)eventhdl);
  4574. }
  4575. #endif
  4576. #if defined(GCC_DIAGNOSTIC)
  4577. /* Enable unused function warning again */
  4578. #pragma GCC diagnostic pop
  4579. #endif
  4580. /* For Windows, change all slashes to backslashes in path names. */
  4581. static void
  4582. change_slashes_to_backslashes(char *path)
  4583. {
  4584. int i;
  4585. for (i = 0; path[i] != '\0'; i++) {
  4586. if (path[i] == '/') {
  4587. path[i] = '\\';
  4588. }
  4589. /* remove double backslash (check i > 0 to preserve UNC paths,
  4590. * like \\server\file.txt) */
  4591. if ((i > 0) && (path[i] == '\\')) {
  4592. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4593. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4594. }
  4595. }
  4596. }
  4597. }
  4598. static int
  4599. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4600. {
  4601. int diff;
  4602. do {
  4603. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4604. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4605. s1++;
  4606. s2++;
  4607. } while ((diff == 0) && (s1[-1] != L'\0'));
  4608. return diff;
  4609. }
  4610. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4611. * wbuf and wbuf_len is a target buffer and its length. */
  4612. static void
  4613. path_to_unicode(const struct mg_connection *conn,
  4614. const char *path,
  4615. wchar_t *wbuf,
  4616. size_t wbuf_len)
  4617. {
  4618. char buf[PATH_MAX], buf2[PATH_MAX];
  4619. wchar_t wbuf2[W_PATH_MAX + 1];
  4620. DWORD long_len, err;
  4621. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4622. mg_strlcpy(buf, path, sizeof(buf));
  4623. change_slashes_to_backslashes(buf);
  4624. /* Convert to Unicode and back. If doubly-converted string does not
  4625. * match the original, something is fishy, reject. */
  4626. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4627. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4628. WideCharToMultiByte(
  4629. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4630. if (strcmp(buf, buf2) != 0) {
  4631. wbuf[0] = L'\0';
  4632. }
  4633. /* Windows file systems are not case sensitive, but you can still use
  4634. * uppercase and lowercase letters (on all modern file systems).
  4635. * The server can check if the URI uses the same upper/lowercase
  4636. * letters an the file system, effectively making Windows servers
  4637. * case sensitive (like Linux servers are). It is still not possible
  4638. * to use two files with the same name in different cases on Windows
  4639. * (like /a and /A) - this would be possible in Linux.
  4640. * As a default, Windows is not case sensitive, but the case sensitive
  4641. * file name check can be activated by an additional configuration. */
  4642. if (conn) {
  4643. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4644. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4645. "yes")) {
  4646. /* Use case sensitive compare function */
  4647. fcompare = wcscmp;
  4648. }
  4649. }
  4650. (void)conn; /* conn is currently unused */
  4651. #if !defined(_WIN32_WCE)
  4652. /* Only accept a full file path, not a Windows short (8.3) path. */
  4653. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4654. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4655. if (long_len == 0) {
  4656. err = GetLastError();
  4657. if (err == ERROR_FILE_NOT_FOUND) {
  4658. /* File does not exist. This is not always a problem here. */
  4659. return;
  4660. }
  4661. }
  4662. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4663. /* Short name is used. */
  4664. wbuf[0] = L'\0';
  4665. }
  4666. #else
  4667. (void)long_len;
  4668. (void)wbuf2;
  4669. (void)err;
  4670. if (strchr(path, '~')) {
  4671. wbuf[0] = L'\0';
  4672. }
  4673. #endif
  4674. }
  4675. #if !defined(NO_FILESYSTEMS)
  4676. static int
  4677. mg_stat(const struct mg_connection *conn,
  4678. const char *path,
  4679. struct mg_file_stat *filep)
  4680. {
  4681. wchar_t wbuf[W_PATH_MAX];
  4682. WIN32_FILE_ATTRIBUTE_DATA info;
  4683. time_t creation_time;
  4684. size_t len;
  4685. if (!filep) {
  4686. return 0;
  4687. }
  4688. memset(filep, 0, sizeof(*filep));
  4689. if (conn && is_file_in_memory(conn, path)) {
  4690. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4691. * memset */
  4692. /* Quick fix (for 1.9.x): */
  4693. /* mg_stat must fill all fields, also for files in memory */
  4694. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4695. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4696. filep->size = tmp_file.stat.size;
  4697. filep->location = 2;
  4698. /* TODO: for 1.10: restructure how files in memory are handled */
  4699. /* The "file in memory" feature is a candidate for deletion.
  4700. * Please join the discussion at
  4701. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4702. */
  4703. filep->last_modified = time(NULL); /* TODO */
  4704. /* last_modified = now ... assumes the file may change during
  4705. * runtime,
  4706. * so every mg_fopen call may return different data */
  4707. /* last_modified = conn->phys_ctx.start_time;
  4708. * May be used it the data does not change during runtime. This
  4709. * allows
  4710. * browser caching. Since we do not know, we have to assume the file
  4711. * in memory may change. */
  4712. return 1;
  4713. }
  4714. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4715. /* Windows happily opens files with some garbage at the end of file name.
  4716. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4717. * "a.cgi", despite one would expect an error back. */
  4718. len = strlen(path);
  4719. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4720. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4721. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4722. filep->last_modified =
  4723. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4724. info.ftLastWriteTime.dwHighDateTime);
  4725. /* On Windows, the file creation time can be higher than the
  4726. * modification time, e.g. when a file is copied.
  4727. * Since the Last-Modified timestamp is used for caching
  4728. * it should be based on the most recent timestamp. */
  4729. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4730. info.ftCreationTime.dwHighDateTime);
  4731. if (creation_time > filep->last_modified) {
  4732. filep->last_modified = creation_time;
  4733. }
  4734. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4735. return 1;
  4736. }
  4737. return 0;
  4738. }
  4739. #endif
  4740. static int
  4741. mg_remove(const struct mg_connection *conn, const char *path)
  4742. {
  4743. wchar_t wbuf[W_PATH_MAX];
  4744. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4745. return DeleteFileW(wbuf) ? 0 : -1;
  4746. }
  4747. static int
  4748. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4749. {
  4750. wchar_t wbuf[W_PATH_MAX];
  4751. (void)mode;
  4752. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4753. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4754. }
  4755. /* Create substitutes for POSIX functions in Win32. */
  4756. #if defined(GCC_DIAGNOSTIC)
  4757. /* Show no warning in case system functions are not used. */
  4758. #pragma GCC diagnostic push
  4759. #pragma GCC diagnostic ignored "-Wunused-function"
  4760. #endif
  4761. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4762. FUNCTION_MAY_BE_UNUSED
  4763. static DIR *
  4764. mg_opendir(const struct mg_connection *conn, const char *name)
  4765. {
  4766. DIR *dir = NULL;
  4767. wchar_t wpath[W_PATH_MAX];
  4768. DWORD attrs;
  4769. if (name == NULL) {
  4770. SetLastError(ERROR_BAD_ARGUMENTS);
  4771. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4772. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4773. } else {
  4774. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4775. attrs = GetFileAttributesW(wpath);
  4776. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4777. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4778. (void)wcscat(wpath, L"\\*");
  4779. dir->handle = FindFirstFileW(wpath, &dir->info);
  4780. dir->result.d_name[0] = '\0';
  4781. } else {
  4782. mg_free(dir);
  4783. dir = NULL;
  4784. }
  4785. }
  4786. return dir;
  4787. }
  4788. FUNCTION_MAY_BE_UNUSED
  4789. static int
  4790. mg_closedir(DIR *dir)
  4791. {
  4792. int result = 0;
  4793. if (dir != NULL) {
  4794. if (dir->handle != INVALID_HANDLE_VALUE)
  4795. result = FindClose(dir->handle) ? 0 : -1;
  4796. mg_free(dir);
  4797. } else {
  4798. result = -1;
  4799. SetLastError(ERROR_BAD_ARGUMENTS);
  4800. }
  4801. return result;
  4802. }
  4803. FUNCTION_MAY_BE_UNUSED
  4804. static struct dirent *
  4805. mg_readdir(DIR *dir)
  4806. {
  4807. struct dirent *result = 0;
  4808. if (dir) {
  4809. if (dir->handle != INVALID_HANDLE_VALUE) {
  4810. result = &dir->result;
  4811. (void)WideCharToMultiByte(CP_UTF8,
  4812. 0,
  4813. dir->info.cFileName,
  4814. -1,
  4815. result->d_name,
  4816. sizeof(result->d_name),
  4817. NULL,
  4818. NULL);
  4819. if (!FindNextFileW(dir->handle, &dir->info)) {
  4820. (void)FindClose(dir->handle);
  4821. dir->handle = INVALID_HANDLE_VALUE;
  4822. }
  4823. } else {
  4824. SetLastError(ERROR_FILE_NOT_FOUND);
  4825. }
  4826. } else {
  4827. SetLastError(ERROR_BAD_ARGUMENTS);
  4828. }
  4829. return result;
  4830. }
  4831. #if !defined(HAVE_POLL)
  4832. #undef POLLIN
  4833. #undef POLLPRI
  4834. #undef POLLOUT
  4835. #define POLLIN (1) /* Data ready - read will not block. */
  4836. #define POLLPRI (2) /* Priority data ready. */
  4837. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4838. FUNCTION_MAY_BE_UNUSED
  4839. static int
  4840. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4841. {
  4842. struct timeval tv;
  4843. fd_set rset;
  4844. fd_set wset;
  4845. unsigned int i;
  4846. int result;
  4847. SOCKET maxfd = 0;
  4848. memset(&tv, 0, sizeof(tv));
  4849. tv.tv_sec = milliseconds / 1000;
  4850. tv.tv_usec = (milliseconds % 1000) * 1000;
  4851. FD_ZERO(&rset);
  4852. FD_ZERO(&wset);
  4853. for (i = 0; i < n; i++) {
  4854. if (pfd[i].events & POLLIN) {
  4855. FD_SET(pfd[i].fd, &rset);
  4856. }
  4857. if (pfd[i].events & POLLOUT) {
  4858. FD_SET(pfd[i].fd, &wset);
  4859. }
  4860. pfd[i].revents = 0;
  4861. if (pfd[i].fd > maxfd) {
  4862. maxfd = pfd[i].fd;
  4863. }
  4864. }
  4865. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4866. for (i = 0; i < n; i++) {
  4867. if (FD_ISSET(pfd[i].fd, &rset)) {
  4868. pfd[i].revents |= POLLIN;
  4869. }
  4870. if (FD_ISSET(pfd[i].fd, &wset)) {
  4871. pfd[i].revents |= POLLOUT;
  4872. }
  4873. }
  4874. }
  4875. /* We should subtract the time used in select from remaining
  4876. * "milliseconds", in particular if called from mg_poll with a
  4877. * timeout quantum.
  4878. * Unfortunately, the remaining time is not stored in "tv" in all
  4879. * implementations, so the result in "tv" must be considered undefined.
  4880. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4881. return result;
  4882. }
  4883. #endif /* HAVE_POLL */
  4884. #if defined(GCC_DIAGNOSTIC)
  4885. /* Enable unused function warning again */
  4886. #pragma GCC diagnostic pop
  4887. #endif
  4888. static void
  4889. set_close_on_exec(SOCKET sock,
  4890. const struct mg_connection *conn /* may be null */,
  4891. struct mg_context *ctx /* may be null */)
  4892. {
  4893. (void)conn; /* Unused. */
  4894. (void)ctx;
  4895. #if defined(_WIN32_WCE)
  4896. (void)sock;
  4897. #else
  4898. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4899. #endif
  4900. }
  4901. int
  4902. mg_start_thread(mg_thread_func_t f, void *p)
  4903. {
  4904. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4905. /* Compile-time option to control stack size, e.g.
  4906. * -DUSE_STACK_SIZE=16384
  4907. */
  4908. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4909. == ((uintptr_t)(-1L)))
  4910. ? -1
  4911. : 0);
  4912. #else
  4913. return (
  4914. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4915. ? -1
  4916. : 0);
  4917. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4918. }
  4919. /* Start a thread storing the thread context. */
  4920. static int
  4921. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4922. void *p,
  4923. pthread_t *threadidptr)
  4924. {
  4925. uintptr_t uip;
  4926. HANDLE threadhandle;
  4927. int result = -1;
  4928. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4929. threadhandle = (HANDLE)uip;
  4930. if ((uip != 0) && (threadidptr != NULL)) {
  4931. *threadidptr = threadhandle;
  4932. result = 0;
  4933. }
  4934. return result;
  4935. }
  4936. /* Wait for a thread to finish. */
  4937. static int
  4938. mg_join_thread(pthread_t threadid)
  4939. {
  4940. int result;
  4941. DWORD dwevent;
  4942. result = -1;
  4943. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4944. if (dwevent == WAIT_FAILED) {
  4945. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4946. } else {
  4947. if (dwevent == WAIT_OBJECT_0) {
  4948. CloseHandle(threadid);
  4949. result = 0;
  4950. }
  4951. }
  4952. return result;
  4953. }
  4954. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4955. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4956. /* Create substitutes for POSIX functions in Win32. */
  4957. #if defined(GCC_DIAGNOSTIC)
  4958. /* Show no warning in case system functions are not used. */
  4959. #pragma GCC diagnostic push
  4960. #pragma GCC diagnostic ignored "-Wunused-function"
  4961. #endif
  4962. FUNCTION_MAY_BE_UNUSED
  4963. static HANDLE
  4964. dlopen(const char *dll_name, int flags)
  4965. {
  4966. wchar_t wbuf[W_PATH_MAX];
  4967. (void)flags;
  4968. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4969. return LoadLibraryW(wbuf);
  4970. }
  4971. FUNCTION_MAY_BE_UNUSED
  4972. static int
  4973. dlclose(void *handle)
  4974. {
  4975. int result;
  4976. if (FreeLibrary((HMODULE)handle) != 0) {
  4977. result = 0;
  4978. } else {
  4979. result = -1;
  4980. }
  4981. return result;
  4982. }
  4983. #if defined(GCC_DIAGNOSTIC)
  4984. /* Enable unused function warning again */
  4985. #pragma GCC diagnostic pop
  4986. #endif
  4987. #endif
  4988. #if !defined(NO_CGI)
  4989. #define SIGKILL (0)
  4990. static int
  4991. kill(pid_t pid, int sig_num)
  4992. {
  4993. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4994. (void)CloseHandle((HANDLE)pid);
  4995. return 0;
  4996. }
  4997. #if !defined(WNOHANG)
  4998. #define WNOHANG (1)
  4999. #endif
  5000. static pid_t
  5001. waitpid(pid_t pid, int *status, int flags)
  5002. {
  5003. DWORD timeout = INFINITE;
  5004. DWORD waitres;
  5005. (void)status; /* Currently not used by any client here */
  5006. if ((flags | WNOHANG) == WNOHANG) {
  5007. timeout = 0;
  5008. }
  5009. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  5010. if (waitres == WAIT_OBJECT_0) {
  5011. return pid;
  5012. }
  5013. if (waitres == WAIT_TIMEOUT) {
  5014. return 0;
  5015. }
  5016. return (pid_t)-1;
  5017. }
  5018. static void
  5019. trim_trailing_whitespaces(char *s)
  5020. {
  5021. char *e = s + strlen(s);
  5022. while ((e > s) && isspace((unsigned char)e[-1])) {
  5023. *(--e) = '\0';
  5024. }
  5025. }
  5026. static pid_t
  5027. spawn_process(struct mg_connection *conn,
  5028. const char *prog,
  5029. char *envblk,
  5030. char *envp[],
  5031. int fdin[2],
  5032. int fdout[2],
  5033. int fderr[2],
  5034. const char *dir)
  5035. {
  5036. HANDLE me;
  5037. char *p, *interp;
  5038. char *interp_arg = 0;
  5039. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  5040. buf[PATH_MAX];
  5041. int truncated;
  5042. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5043. STARTUPINFOA si;
  5044. PROCESS_INFORMATION pi = {0};
  5045. (void)envp;
  5046. memset(&si, 0, sizeof(si));
  5047. si.cb = sizeof(si);
  5048. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5049. si.wShowWindow = SW_HIDE;
  5050. me = GetCurrentProcess();
  5051. DuplicateHandle(me,
  5052. (HANDLE)_get_osfhandle(fdin[0]),
  5053. me,
  5054. &si.hStdInput,
  5055. 0,
  5056. TRUE,
  5057. DUPLICATE_SAME_ACCESS);
  5058. DuplicateHandle(me,
  5059. (HANDLE)_get_osfhandle(fdout[1]),
  5060. me,
  5061. &si.hStdOutput,
  5062. 0,
  5063. TRUE,
  5064. DUPLICATE_SAME_ACCESS);
  5065. DuplicateHandle(me,
  5066. (HANDLE)_get_osfhandle(fderr[1]),
  5067. me,
  5068. &si.hStdError,
  5069. 0,
  5070. TRUE,
  5071. DUPLICATE_SAME_ACCESS);
  5072. /* Mark handles that should not be inherited. See
  5073. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5074. */
  5075. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5076. HANDLE_FLAG_INHERIT,
  5077. 0);
  5078. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5079. HANDLE_FLAG_INHERIT,
  5080. 0);
  5081. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5082. HANDLE_FLAG_INHERIT,
  5083. 0);
  5084. /* First check, if there is a CGI interpreter configured for all CGI
  5085. * scripts. */
  5086. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5087. if (interp != NULL) {
  5088. /* If there is a configured interpreter, check for additional arguments
  5089. */
  5090. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5091. } else {
  5092. /* Otherwise, the interpreter must be stated in the first line of the
  5093. * CGI script file, after a #! (shebang) mark. */
  5094. buf[0] = buf[1] = '\0';
  5095. /* Get the full script path */
  5096. mg_snprintf(
  5097. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5098. if (truncated) {
  5099. pi.hProcess = (pid_t)-1;
  5100. goto spawn_cleanup;
  5101. }
  5102. /* Open the script file, to read the first line */
  5103. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5104. #if defined(MG_USE_OPEN_FILE)
  5105. p = (char *)file.access.membuf;
  5106. #else
  5107. p = (char *)NULL;
  5108. #endif
  5109. /* Read the first line of the script into the buffer */
  5110. mg_fgets(buf, sizeof(buf), &file, &p);
  5111. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5112. buf[sizeof(buf) - 1] = '\0';
  5113. }
  5114. if ((buf[0] == '#') && (buf[1] == '!')) {
  5115. trim_trailing_whitespaces(buf + 2);
  5116. } else {
  5117. buf[2] = '\0';
  5118. }
  5119. interp = buf + 2;
  5120. }
  5121. if (interp[0] != '\0') {
  5122. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5123. interp = full_interp;
  5124. }
  5125. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5126. if (interp[0] != '\0') {
  5127. /* This is an interpreted script file. We must call the interpreter. */
  5128. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5129. mg_snprintf(conn,
  5130. &truncated,
  5131. cmdline,
  5132. sizeof(cmdline),
  5133. "\"%s\" %s \"%s\\%s\"",
  5134. interp,
  5135. interp_arg,
  5136. full_dir,
  5137. prog);
  5138. } else {
  5139. mg_snprintf(conn,
  5140. &truncated,
  5141. cmdline,
  5142. sizeof(cmdline),
  5143. "\"%s\" \"%s\\%s\"",
  5144. interp,
  5145. full_dir,
  5146. prog);
  5147. }
  5148. } else {
  5149. /* This is (probably) a compiled program. We call it directly. */
  5150. mg_snprintf(conn,
  5151. &truncated,
  5152. cmdline,
  5153. sizeof(cmdline),
  5154. "\"%s\\%s\"",
  5155. full_dir,
  5156. prog);
  5157. }
  5158. if (truncated) {
  5159. pi.hProcess = (pid_t)-1;
  5160. goto spawn_cleanup;
  5161. }
  5162. DEBUG_TRACE("Running [%s]", cmdline);
  5163. if (CreateProcessA(NULL,
  5164. cmdline,
  5165. NULL,
  5166. NULL,
  5167. TRUE,
  5168. CREATE_NEW_PROCESS_GROUP,
  5169. envblk,
  5170. NULL,
  5171. &si,
  5172. &pi)
  5173. == 0) {
  5174. mg_cry_internal(
  5175. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5176. pi.hProcess = (pid_t)-1;
  5177. /* goto spawn_cleanup; */
  5178. }
  5179. spawn_cleanup:
  5180. (void)CloseHandle(si.hStdOutput);
  5181. (void)CloseHandle(si.hStdError);
  5182. (void)CloseHandle(si.hStdInput);
  5183. if (pi.hThread != NULL) {
  5184. (void)CloseHandle(pi.hThread);
  5185. }
  5186. return (pid_t)pi.hProcess;
  5187. }
  5188. #endif /* !NO_CGI */
  5189. static int
  5190. set_blocking_mode(SOCKET sock)
  5191. {
  5192. unsigned long non_blocking = 0;
  5193. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5194. }
  5195. static int
  5196. set_non_blocking_mode(SOCKET sock)
  5197. {
  5198. unsigned long non_blocking = 1;
  5199. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5200. }
  5201. #else
  5202. #if !defined(NO_FILESYSTEMS)
  5203. static int
  5204. mg_stat(const struct mg_connection *conn,
  5205. const char *path,
  5206. struct mg_file_stat *filep)
  5207. {
  5208. struct stat st;
  5209. if (!filep) {
  5210. return 0;
  5211. }
  5212. memset(filep, 0, sizeof(*filep));
  5213. if (conn && is_file_in_memory(conn, path)) {
  5214. /* Quick fix (for 1.9.x): */
  5215. /* mg_stat must fill all fields, also for files in memory */
  5216. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5217. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5218. filep->size = tmp_file.stat.size;
  5219. filep->last_modified = time(NULL);
  5220. filep->location = 2;
  5221. /* TODO: remove legacy "files in memory" feature */
  5222. return 1;
  5223. }
  5224. if (0 == stat(path, &st)) {
  5225. filep->size = (uint64_t)(st.st_size);
  5226. filep->last_modified = st.st_mtime;
  5227. filep->is_directory = S_ISDIR(st.st_mode);
  5228. return 1;
  5229. }
  5230. return 0;
  5231. }
  5232. #endif /* NO_FILESYSTEMS */
  5233. static void
  5234. set_close_on_exec(int fd,
  5235. const struct mg_connection *conn /* may be null */,
  5236. struct mg_context *ctx /* may be null */)
  5237. {
  5238. #if defined(__ZEPHYR__)
  5239. (void)fd;
  5240. (void)conn;
  5241. (void)ctx;
  5242. #else
  5243. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5244. if (conn || ctx) {
  5245. struct mg_connection fc;
  5246. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5247. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5248. __func__,
  5249. strerror(ERRNO));
  5250. }
  5251. }
  5252. #endif
  5253. }
  5254. int
  5255. mg_start_thread(mg_thread_func_t func, void *param)
  5256. {
  5257. pthread_t thread_id;
  5258. pthread_attr_t attr;
  5259. int result;
  5260. (void)pthread_attr_init(&attr);
  5261. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5262. #if defined(__ZEPHYR__)
  5263. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5264. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5265. /* Compile-time option to control stack size,
  5266. * e.g. -DUSE_STACK_SIZE=16384 */
  5267. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5268. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5269. result = pthread_create(&thread_id, &attr, func, param);
  5270. pthread_attr_destroy(&attr);
  5271. return result;
  5272. }
  5273. /* Start a thread storing the thread context. */
  5274. static int
  5275. mg_start_thread_with_id(mg_thread_func_t func,
  5276. void *param,
  5277. pthread_t *threadidptr)
  5278. {
  5279. pthread_t thread_id;
  5280. pthread_attr_t attr;
  5281. int result;
  5282. (void)pthread_attr_init(&attr);
  5283. #if defined(__ZEPHYR__)
  5284. pthread_attr_setstack(&attr,
  5285. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5286. ZEPHYR_STACK_SIZE);
  5287. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5288. /* Compile-time option to control stack size,
  5289. * e.g. -DUSE_STACK_SIZE=16384 */
  5290. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5291. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5292. result = pthread_create(&thread_id, &attr, func, param);
  5293. pthread_attr_destroy(&attr);
  5294. if ((result == 0) && (threadidptr != NULL)) {
  5295. *threadidptr = thread_id;
  5296. }
  5297. return result;
  5298. }
  5299. /* Wait for a thread to finish. */
  5300. static int
  5301. mg_join_thread(pthread_t threadid)
  5302. {
  5303. int result;
  5304. result = pthread_join(threadid, NULL);
  5305. return result;
  5306. }
  5307. #if !defined(NO_CGI)
  5308. static pid_t
  5309. spawn_process(struct mg_connection *conn,
  5310. const char *prog,
  5311. char *envblk,
  5312. char *envp[],
  5313. int fdin[2],
  5314. int fdout[2],
  5315. int fderr[2],
  5316. const char *dir)
  5317. {
  5318. pid_t pid;
  5319. const char *interp;
  5320. (void)envblk;
  5321. if ((pid = fork()) == -1) {
  5322. /* Parent */
  5323. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5324. } else if (pid != 0) {
  5325. /* Make sure children close parent-side descriptors.
  5326. * The caller will close the child-side immediately. */
  5327. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5328. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5329. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5330. } else {
  5331. /* Child */
  5332. if (chdir(dir) != 0) {
  5333. mg_cry_internal(
  5334. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5335. } else if (dup2(fdin[0], 0) == -1) {
  5336. mg_cry_internal(conn,
  5337. "%s: dup2(%d, 0): %s",
  5338. __func__,
  5339. fdin[0],
  5340. strerror(ERRNO));
  5341. } else if (dup2(fdout[1], 1) == -1) {
  5342. mg_cry_internal(conn,
  5343. "%s: dup2(%d, 1): %s",
  5344. __func__,
  5345. fdout[1],
  5346. strerror(ERRNO));
  5347. } else if (dup2(fderr[1], 2) == -1) {
  5348. mg_cry_internal(conn,
  5349. "%s: dup2(%d, 2): %s",
  5350. __func__,
  5351. fderr[1],
  5352. strerror(ERRNO));
  5353. } else {
  5354. struct sigaction sa;
  5355. /* Keep stderr and stdout in two different pipes.
  5356. * Stdout will be sent back to the client,
  5357. * stderr should go into a server error log. */
  5358. (void)close(fdin[0]);
  5359. (void)close(fdout[1]);
  5360. (void)close(fderr[1]);
  5361. /* Close write end fdin and read end fdout and fderr */
  5362. (void)close(fdin[1]);
  5363. (void)close(fdout[0]);
  5364. (void)close(fderr[0]);
  5365. /* After exec, all signal handlers are restored to their default
  5366. * values, with one exception of SIGCHLD. According to
  5367. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5368. * will leave unchanged after exec if it was set to be ignored.
  5369. * Restore it to default action. */
  5370. memset(&sa, 0, sizeof(sa));
  5371. sa.sa_handler = SIG_DFL;
  5372. sigaction(SIGCHLD, &sa, NULL);
  5373. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5374. if (interp == NULL) {
  5375. /* no interpreter configured, call the programm directly */
  5376. (void)execle(prog, prog, NULL, envp);
  5377. mg_cry_internal(conn,
  5378. "%s: execle(%s): %s",
  5379. __func__,
  5380. prog,
  5381. strerror(ERRNO));
  5382. } else {
  5383. /* call the configured interpreter */
  5384. const char *interp_args =
  5385. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5386. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5387. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5388. } else {
  5389. (void)execle(interp, interp, prog, NULL, envp);
  5390. }
  5391. mg_cry_internal(conn,
  5392. "%s: execle(%s %s): %s",
  5393. __func__,
  5394. interp,
  5395. prog,
  5396. strerror(ERRNO));
  5397. }
  5398. }
  5399. exit(EXIT_FAILURE);
  5400. }
  5401. return pid;
  5402. }
  5403. #endif /* !NO_CGI */
  5404. static int
  5405. set_non_blocking_mode(SOCKET sock)
  5406. {
  5407. int flags = fcntl(sock, F_GETFL, 0);
  5408. if (flags < 0) {
  5409. return -1;
  5410. }
  5411. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5412. return -1;
  5413. }
  5414. return 0;
  5415. }
  5416. static int
  5417. set_blocking_mode(SOCKET sock)
  5418. {
  5419. int flags = fcntl(sock, F_GETFL, 0);
  5420. if (flags < 0) {
  5421. return -1;
  5422. }
  5423. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5424. return -1;
  5425. }
  5426. return 0;
  5427. }
  5428. #endif /* _WIN32 / else */
  5429. /* End of initial operating system specific define block. */
  5430. /* Get a random number (independent of C rand function) */
  5431. static uint64_t
  5432. get_random(void)
  5433. {
  5434. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5435. static uint64_t lcg = 0; /* Linear congruential generator */
  5436. uint64_t now = mg_get_current_time_ns();
  5437. if (lfsr == 0) {
  5438. /* lfsr will be only 0 if has not been initialized,
  5439. * so this code is called only once. */
  5440. lfsr = mg_get_current_time_ns();
  5441. lcg = mg_get_current_time_ns();
  5442. } else {
  5443. /* Get the next step of both random number generators. */
  5444. lfsr = (lfsr >> 1)
  5445. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5446. << 63);
  5447. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5448. }
  5449. /* Combining two pseudo-random number generators and a high resolution
  5450. * part
  5451. * of the current server time will make it hard (impossible?) to guess
  5452. * the
  5453. * next number. */
  5454. return (lfsr ^ lcg ^ now);
  5455. }
  5456. static int
  5457. mg_poll(struct mg_pollfd *pfd,
  5458. unsigned int n,
  5459. int milliseconds,
  5460. stop_flag_t *stop_flag)
  5461. {
  5462. /* Call poll, but only for a maximum time of a few seconds.
  5463. * This will allow to stop the server after some seconds, instead
  5464. * of having to wait for a long socket timeout. */
  5465. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5466. do {
  5467. int result;
  5468. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5469. /* Shut down signal */
  5470. return -2;
  5471. }
  5472. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5473. ms_now = milliseconds;
  5474. }
  5475. result = poll(pfd, n, ms_now);
  5476. if (result != 0) {
  5477. /* Poll returned either success (1) or error (-1).
  5478. * Forward both to the caller. */
  5479. return result;
  5480. }
  5481. /* Poll returned timeout (0). */
  5482. if (milliseconds > 0) {
  5483. milliseconds -= ms_now;
  5484. }
  5485. } while (milliseconds != 0);
  5486. /* timeout: return 0 */
  5487. return 0;
  5488. }
  5489. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5490. * descriptor.
  5491. * Return value:
  5492. * >=0 .. number of bytes successfully written
  5493. * -1 .. timeout
  5494. * -2 .. error
  5495. */
  5496. static int
  5497. push_inner(struct mg_context *ctx,
  5498. FILE *fp,
  5499. SOCKET sock,
  5500. SSL *ssl,
  5501. const char *buf,
  5502. int len,
  5503. double timeout)
  5504. {
  5505. uint64_t start = 0, now = 0, timeout_ns = 0;
  5506. int n, err;
  5507. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5508. #if defined(_WIN32)
  5509. typedef int len_t;
  5510. #else
  5511. typedef size_t len_t;
  5512. #endif
  5513. if (timeout > 0) {
  5514. now = mg_get_current_time_ns();
  5515. start = now;
  5516. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5517. }
  5518. if (ctx == NULL) {
  5519. return -2;
  5520. }
  5521. #if defined(NO_SSL)
  5522. if (ssl) {
  5523. return -2;
  5524. }
  5525. #endif
  5526. /* Try to read until it succeeds, fails, times out, or the server
  5527. * shuts down. */
  5528. for (;;) {
  5529. #if !defined(NO_SSL)
  5530. if (ssl != NULL) {
  5531. ERR_clear_error();
  5532. n = SSL_write(ssl, buf, len);
  5533. if (n <= 0) {
  5534. err = SSL_get_error(ssl, n);
  5535. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5536. err = ERRNO;
  5537. } else if ((err == SSL_ERROR_WANT_READ)
  5538. || (err == SSL_ERROR_WANT_WRITE)) {
  5539. n = 0;
  5540. } else {
  5541. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5542. ERR_clear_error();
  5543. return -2;
  5544. }
  5545. ERR_clear_error();
  5546. } else {
  5547. err = 0;
  5548. }
  5549. } else
  5550. #endif
  5551. if (fp != NULL) {
  5552. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5553. if (ferror(fp)) {
  5554. n = -1;
  5555. err = ERRNO;
  5556. } else {
  5557. err = 0;
  5558. }
  5559. } else {
  5560. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5561. err = (n < 0) ? ERRNO : 0;
  5562. #if defined(_WIN32)
  5563. if (err == WSAEWOULDBLOCK) {
  5564. err = 0;
  5565. n = 0;
  5566. }
  5567. #else
  5568. if (err == EWOULDBLOCK) {
  5569. err = 0;
  5570. n = 0;
  5571. }
  5572. #endif
  5573. if (n < 0) {
  5574. /* shutdown of the socket at client side */
  5575. return -2;
  5576. }
  5577. }
  5578. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5579. return -2;
  5580. }
  5581. if ((n > 0) || ((n == 0) && (len == 0))) {
  5582. /* some data has been read, or no data was requested */
  5583. return n;
  5584. }
  5585. if (n < 0) {
  5586. /* socket error - check errno */
  5587. DEBUG_TRACE("send() failed, error %d", err);
  5588. /* TODO (mid): error handling depending on the error code.
  5589. * These codes are different between Windows and Linux.
  5590. * Currently there is no problem with failing send calls,
  5591. * if there is a reproducible situation, it should be
  5592. * investigated in detail.
  5593. */
  5594. return -2;
  5595. }
  5596. /* Only in case n=0 (timeout), repeat calling the write function */
  5597. /* If send failed, wait before retry */
  5598. if (fp != NULL) {
  5599. /* For files, just wait a fixed time.
  5600. * Maybe it helps, maybe not. */
  5601. mg_sleep(5);
  5602. } else {
  5603. /* For sockets, wait for the socket using poll */
  5604. struct mg_pollfd pfd[1];
  5605. int pollres;
  5606. pfd[0].fd = sock;
  5607. pfd[0].events = POLLOUT;
  5608. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5609. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5610. return -2;
  5611. }
  5612. if (pollres > 0) {
  5613. continue;
  5614. }
  5615. }
  5616. if (timeout > 0) {
  5617. now = mg_get_current_time_ns();
  5618. if ((now - start) > timeout_ns) {
  5619. /* Timeout */
  5620. break;
  5621. }
  5622. }
  5623. }
  5624. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5625. used */
  5626. return -1;
  5627. }
  5628. static int
  5629. push_all(struct mg_context *ctx,
  5630. FILE *fp,
  5631. SOCKET sock,
  5632. SSL *ssl,
  5633. const char *buf,
  5634. int len)
  5635. {
  5636. double timeout = -1.0;
  5637. int n, nwritten = 0;
  5638. if (ctx == NULL) {
  5639. return -1;
  5640. }
  5641. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5642. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5643. }
  5644. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5645. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5646. if (n < 0) {
  5647. if (nwritten == 0) {
  5648. nwritten = -1; /* Propagate the error */
  5649. }
  5650. break;
  5651. } else if (n == 0) {
  5652. break; /* No more data to write */
  5653. } else {
  5654. nwritten += n;
  5655. len -= n;
  5656. }
  5657. }
  5658. return nwritten;
  5659. }
  5660. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5661. * Return value:
  5662. * >=0 .. number of bytes successfully read
  5663. * -1 .. timeout
  5664. * -2 .. error
  5665. */
  5666. static int
  5667. pull_inner(FILE *fp,
  5668. struct mg_connection *conn,
  5669. char *buf,
  5670. int len,
  5671. double timeout)
  5672. {
  5673. int nread, err = 0;
  5674. #if defined(_WIN32)
  5675. typedef int len_t;
  5676. #else
  5677. typedef size_t len_t;
  5678. #endif
  5679. /* We need an additional wait loop around this, because in some cases
  5680. * with TLSwe may get data from the socket but not from SSL_read.
  5681. * In this case we need to repeat at least once.
  5682. */
  5683. if (fp != NULL) {
  5684. #if !defined(_WIN32_WCE)
  5685. /* Use read() instead of fread(), because if we're reading from the
  5686. * CGI pipe, fread() may block until IO buffer is filled up. We
  5687. * cannot afford to block and must pass all read bytes immediately
  5688. * to the client. */
  5689. nread = (int)read(fileno(fp), buf, (size_t)len);
  5690. #else
  5691. /* WinCE does not support CGI pipes */
  5692. nread = (int)fread(buf, 1, (size_t)len, fp);
  5693. #endif
  5694. err = (nread < 0) ? ERRNO : 0;
  5695. if ((nread == 0) && (len > 0)) {
  5696. /* Should get data, but got EOL */
  5697. return -2;
  5698. }
  5699. #if !defined(NO_SSL)
  5700. } else if (conn->ssl != NULL) {
  5701. int ssl_pending;
  5702. struct mg_pollfd pfd[1];
  5703. int pollres;
  5704. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5705. /* We already know there is no more data buffered in conn->buf
  5706. * but there is more available in the SSL layer. So don't poll
  5707. * conn->client.sock yet. */
  5708. if (ssl_pending > len) {
  5709. ssl_pending = len;
  5710. }
  5711. pollres = 1;
  5712. } else {
  5713. pfd[0].fd = conn->client.sock;
  5714. pfd[0].events = POLLIN;
  5715. pollres = mg_poll(pfd,
  5716. 1,
  5717. (int)(timeout * 1000.0),
  5718. &(conn->phys_ctx->stop_flag));
  5719. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5720. return -2;
  5721. }
  5722. }
  5723. if (pollres > 0) {
  5724. ERR_clear_error();
  5725. nread = SSL_read(conn->ssl, buf,
  5726. (ssl_pending > 0) ? ssl_pending : len);
  5727. if (nread <= 0) {
  5728. err = SSL_get_error(conn->ssl, nread);
  5729. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5730. err = ERRNO;
  5731. } else if ((err == SSL_ERROR_WANT_READ)
  5732. || (err == SSL_ERROR_WANT_WRITE)) {
  5733. nread = 0;
  5734. } else {
  5735. /* All errors should return -2 */
  5736. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5737. ERR_clear_error();
  5738. return -2;
  5739. }
  5740. ERR_clear_error();
  5741. } else {
  5742. err = 0;
  5743. }
  5744. } else if (pollres < 0) {
  5745. /* Error */
  5746. return -2;
  5747. } else {
  5748. /* pollres = 0 means timeout */
  5749. nread = 0;
  5750. }
  5751. #endif
  5752. } else {
  5753. struct mg_pollfd pfd[1];
  5754. int pollres;
  5755. pfd[0].fd = conn->client.sock;
  5756. pfd[0].events = POLLIN;
  5757. pollres = mg_poll(pfd,
  5758. 1,
  5759. (int)(timeout * 1000.0),
  5760. &(conn->phys_ctx->stop_flag));
  5761. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5762. return -2;
  5763. }
  5764. if (pollres > 0) {
  5765. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5766. err = (nread < 0) ? ERRNO : 0;
  5767. if (nread <= 0) {
  5768. /* shutdown of the socket at client side */
  5769. return -2;
  5770. }
  5771. } else if (pollres < 0) {
  5772. /* error callint poll */
  5773. return -2;
  5774. } else {
  5775. /* pollres = 0 means timeout */
  5776. nread = 0;
  5777. }
  5778. }
  5779. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5780. return -2;
  5781. }
  5782. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5783. /* some data has been read, or no data was requested */
  5784. return nread;
  5785. }
  5786. if (nread < 0) {
  5787. /* socket error - check errno */
  5788. #if defined(_WIN32)
  5789. if (err == WSAEWOULDBLOCK) {
  5790. /* TODO (low): check if this is still required */
  5791. /* standard case if called from close_socket_gracefully */
  5792. return -2;
  5793. } else if (err == WSAETIMEDOUT) {
  5794. /* TODO (low): check if this is still required */
  5795. /* timeout is handled by the while loop */
  5796. return 0;
  5797. } else if (err == WSAECONNABORTED) {
  5798. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5799. return -2;
  5800. } else {
  5801. DEBUG_TRACE("recv() failed, error %d", err);
  5802. return -2;
  5803. }
  5804. #else
  5805. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5806. * if the timeout is reached and if the socket was set to non-
  5807. * blocking in close_socket_gracefully, so we can not distinguish
  5808. * here. We have to wait for the timeout in both cases for now.
  5809. */
  5810. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5811. /* TODO (low): check if this is still required */
  5812. /* EAGAIN/EWOULDBLOCK:
  5813. * standard case if called from close_socket_gracefully
  5814. * => should return -1 */
  5815. /* or timeout occurred
  5816. * => the code must stay in the while loop */
  5817. /* EINTR can be generated on a socket with a timeout set even
  5818. * when SA_RESTART is effective for all relevant signals
  5819. * (see signal(7)).
  5820. * => stay in the while loop */
  5821. } else {
  5822. DEBUG_TRACE("recv() failed, error %d", err);
  5823. return -2;
  5824. }
  5825. #endif
  5826. }
  5827. /* Timeout occurred, but no data available. */
  5828. return -1;
  5829. }
  5830. static int
  5831. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5832. {
  5833. int n, nread = 0;
  5834. double timeout = -1.0;
  5835. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5836. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5837. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5838. }
  5839. if (timeout >= 0.0) {
  5840. start_time = mg_get_current_time_ns();
  5841. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5842. }
  5843. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5844. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5845. if (n == -2) {
  5846. if (nread == 0) {
  5847. nread = -1; /* Propagate the error */
  5848. }
  5849. break;
  5850. } else if (n == -1) {
  5851. /* timeout */
  5852. if (timeout >= 0.0) {
  5853. now = mg_get_current_time_ns();
  5854. if ((now - start_time) <= timeout_ns) {
  5855. continue;
  5856. }
  5857. }
  5858. break;
  5859. } else if (n == 0) {
  5860. break; /* No more data to read */
  5861. } else {
  5862. nread += n;
  5863. len -= n;
  5864. }
  5865. }
  5866. return nread;
  5867. }
  5868. static void
  5869. discard_unread_request_data(struct mg_connection *conn)
  5870. {
  5871. char buf[MG_BUF_LEN];
  5872. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5873. ;
  5874. }
  5875. static int
  5876. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5877. {
  5878. int64_t content_len, n, buffered_len, nread;
  5879. int64_t len64 =
  5880. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5881. * int, we may not read more
  5882. * bytes */
  5883. const char *body;
  5884. if (conn == NULL) {
  5885. return 0;
  5886. }
  5887. /* If Content-Length is not set for a response with body data,
  5888. * we do not know in advance how much data should be read. */
  5889. content_len = conn->content_len;
  5890. if (content_len < 0) {
  5891. /* The body data is completed when the connection is closed. */
  5892. content_len = INT64_MAX;
  5893. }
  5894. nread = 0;
  5895. if (conn->consumed_content < content_len) {
  5896. /* Adjust number of bytes to read. */
  5897. int64_t left_to_read = content_len - conn->consumed_content;
  5898. if (left_to_read < len64) {
  5899. /* Do not read more than the total content length of the
  5900. * request.
  5901. */
  5902. len64 = left_to_read;
  5903. }
  5904. /* Return buffered data */
  5905. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5906. - conn->consumed_content;
  5907. if (buffered_len > 0) {
  5908. if (len64 < buffered_len) {
  5909. buffered_len = len64;
  5910. }
  5911. body = conn->buf + conn->request_len + conn->consumed_content;
  5912. memcpy(buf, body, (size_t)buffered_len);
  5913. len64 -= buffered_len;
  5914. conn->consumed_content += buffered_len;
  5915. nread += buffered_len;
  5916. buf = (char *)buf + buffered_len;
  5917. }
  5918. /* We have returned all buffered data. Read new data from the remote
  5919. * socket.
  5920. */
  5921. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5922. conn->consumed_content += n;
  5923. nread += n;
  5924. } else {
  5925. nread = ((nread > 0) ? nread : n);
  5926. }
  5927. }
  5928. return (int)nread;
  5929. }
  5930. int
  5931. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5932. {
  5933. if (len > INT_MAX) {
  5934. len = INT_MAX;
  5935. }
  5936. if (conn == NULL) {
  5937. return 0;
  5938. }
  5939. if (conn->is_chunked) {
  5940. size_t all_read = 0;
  5941. while (len > 0) {
  5942. if (conn->is_chunked >= 3) {
  5943. /* No more data left to read */
  5944. return 0;
  5945. }
  5946. if (conn->is_chunked != 1) {
  5947. /* Has error */
  5948. return -1;
  5949. }
  5950. if (conn->consumed_content != conn->content_len) {
  5951. /* copy from the current chunk */
  5952. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5953. if (read_ret < 1) {
  5954. /* read error */
  5955. conn->is_chunked = 2;
  5956. return -1;
  5957. }
  5958. all_read += (size_t)read_ret;
  5959. len -= (size_t)read_ret;
  5960. if (conn->consumed_content == conn->content_len) {
  5961. /* Add data bytes in the current chunk have been read,
  5962. * so we are expecting \r\n now. */
  5963. char x[2];
  5964. conn->content_len += 2;
  5965. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5966. || (x[1] != '\n')) {
  5967. /* Protocol violation */
  5968. conn->is_chunked = 2;
  5969. return -1;
  5970. }
  5971. }
  5972. } else {
  5973. /* fetch a new chunk */
  5974. size_t i;
  5975. char lenbuf[64];
  5976. char *end = NULL;
  5977. unsigned long chunkSize = 0;
  5978. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5979. conn->content_len++;
  5980. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5981. lenbuf[i] = 0;
  5982. }
  5983. if ((i > 0) && (lenbuf[i] == '\r')
  5984. && (lenbuf[i - 1] != '\r')) {
  5985. continue;
  5986. }
  5987. if ((i > 1) && (lenbuf[i] == '\n')
  5988. && (lenbuf[i - 1] == '\r')) {
  5989. lenbuf[i + 1] = 0;
  5990. chunkSize = strtoul(lenbuf, &end, 16);
  5991. if (chunkSize == 0) {
  5992. /* regular end of content */
  5993. conn->is_chunked = 3;
  5994. }
  5995. break;
  5996. }
  5997. if (!isxdigit((unsigned char)lenbuf[i])) {
  5998. /* illegal character for chunk length */
  5999. conn->is_chunked = 2;
  6000. return -1;
  6001. }
  6002. }
  6003. if ((end == NULL) || (*end != '\r')) {
  6004. /* chunksize not set correctly */
  6005. conn->is_chunked = 2;
  6006. return -1;
  6007. }
  6008. if (chunkSize == 0) {
  6009. /* try discarding trailer for keep-alive */
  6010. conn->content_len += 2;
  6011. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  6012. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  6013. conn->is_chunked = 4;
  6014. }
  6015. break;
  6016. }
  6017. /* append a new chunk */
  6018. conn->content_len += (int64_t)chunkSize;
  6019. }
  6020. }
  6021. return (int)all_read;
  6022. }
  6023. return mg_read_inner(conn, buf, len);
  6024. }
  6025. int
  6026. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  6027. {
  6028. time_t now;
  6029. int n, total, allowed;
  6030. if (conn == NULL) {
  6031. return 0;
  6032. }
  6033. if (len > INT_MAX) {
  6034. return -1;
  6035. }
  6036. if (conn->throttle > 0) {
  6037. if ((now = time(NULL)) != conn->last_throttle_time) {
  6038. conn->last_throttle_time = now;
  6039. conn->last_throttle_bytes = 0;
  6040. }
  6041. allowed = conn->throttle - conn->last_throttle_bytes;
  6042. if (allowed > (int)len) {
  6043. allowed = (int)len;
  6044. }
  6045. if ((total = push_all(conn->phys_ctx,
  6046. NULL,
  6047. conn->client.sock,
  6048. conn->ssl,
  6049. (const char *)buf,
  6050. allowed))
  6051. == allowed) {
  6052. buf = (const char *)buf + total;
  6053. conn->last_throttle_bytes += total;
  6054. while ((total < (int)len)
  6055. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6056. allowed = (conn->throttle > ((int)len - total))
  6057. ? (int)len - total
  6058. : conn->throttle;
  6059. if ((n = push_all(conn->phys_ctx,
  6060. NULL,
  6061. conn->client.sock,
  6062. conn->ssl,
  6063. (const char *)buf,
  6064. allowed))
  6065. != allowed) {
  6066. break;
  6067. }
  6068. sleep(1);
  6069. conn->last_throttle_bytes = allowed;
  6070. conn->last_throttle_time = time(NULL);
  6071. buf = (const char *)buf + n;
  6072. total += n;
  6073. }
  6074. }
  6075. } else {
  6076. total = push_all(conn->phys_ctx,
  6077. NULL,
  6078. conn->client.sock,
  6079. conn->ssl,
  6080. (const char *)buf,
  6081. (int)len);
  6082. }
  6083. if (total > 0) {
  6084. conn->num_bytes_sent += total;
  6085. }
  6086. return total;
  6087. }
  6088. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6089. int
  6090. mg_send_chunk(struct mg_connection *conn,
  6091. const char *chunk,
  6092. unsigned int chunk_len)
  6093. {
  6094. char lenbuf[16];
  6095. size_t lenbuf_len;
  6096. int ret;
  6097. int t;
  6098. /* First store the length information in a text buffer. */
  6099. sprintf(lenbuf, "%x\r\n", chunk_len);
  6100. lenbuf_len = strlen(lenbuf);
  6101. /* Then send length information, chunk and terminating \r\n. */
  6102. ret = mg_write(conn, lenbuf, lenbuf_len);
  6103. if (ret != (int)lenbuf_len) {
  6104. return -1;
  6105. }
  6106. t = ret;
  6107. ret = mg_write(conn, chunk, chunk_len);
  6108. if (ret != (int)chunk_len) {
  6109. return -1;
  6110. }
  6111. t += ret;
  6112. ret = mg_write(conn, "\r\n", 2);
  6113. if (ret != 2) {
  6114. return -1;
  6115. }
  6116. t += ret;
  6117. return t;
  6118. }
  6119. #if defined(GCC_DIAGNOSTIC)
  6120. /* This block forwards format strings to printf implementations,
  6121. * so we need to disable the format-nonliteral warning. */
  6122. #pragma GCC diagnostic push
  6123. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6124. #endif
  6125. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6126. static int
  6127. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6128. {
  6129. va_list ap_copy;
  6130. size_t size = MG_BUF_LEN / 4;
  6131. int len = -1;
  6132. *buf = NULL;
  6133. while (len < 0) {
  6134. if (*buf) {
  6135. mg_free(*buf);
  6136. }
  6137. size *= 4;
  6138. *buf = (char *)mg_malloc(size);
  6139. if (!*buf) {
  6140. break;
  6141. }
  6142. va_copy(ap_copy, ap);
  6143. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6144. va_end(ap_copy);
  6145. (*buf)[size - 1] = 0;
  6146. }
  6147. return len;
  6148. }
  6149. /* Print message to buffer. If buffer is large enough to hold the message,
  6150. * return buffer. If buffer is to small, allocate large enough buffer on
  6151. * heap,
  6152. * and return allocated buffer. */
  6153. static int
  6154. alloc_vprintf(char **out_buf,
  6155. char *prealloc_buf,
  6156. size_t prealloc_size,
  6157. const char *fmt,
  6158. va_list ap)
  6159. {
  6160. va_list ap_copy;
  6161. int len;
  6162. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6163. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6164. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6165. * Therefore, we make two passes: on first pass, get required message
  6166. * length.
  6167. * On second pass, actually print the message. */
  6168. va_copy(ap_copy, ap);
  6169. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6170. va_end(ap_copy);
  6171. if (len < 0) {
  6172. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6173. * Switch to alternative code path that uses incremental
  6174. * allocations.
  6175. */
  6176. va_copy(ap_copy, ap);
  6177. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6178. va_end(ap_copy);
  6179. } else if ((size_t)(len) >= prealloc_size) {
  6180. /* The pre-allocated buffer not large enough. */
  6181. /* Allocate a new buffer. */
  6182. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6183. if (!*out_buf) {
  6184. /* Allocation failed. Return -1 as "out of memory" error. */
  6185. return -1;
  6186. }
  6187. /* Buffer allocation successful. Store the string there. */
  6188. va_copy(ap_copy, ap);
  6189. IGNORE_UNUSED_RESULT(
  6190. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6191. va_end(ap_copy);
  6192. } else {
  6193. /* The pre-allocated buffer is large enough.
  6194. * Use it to store the string and return the address. */
  6195. va_copy(ap_copy, ap);
  6196. IGNORE_UNUSED_RESULT(
  6197. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6198. va_end(ap_copy);
  6199. *out_buf = prealloc_buf;
  6200. }
  6201. return len;
  6202. }
  6203. #if defined(GCC_DIAGNOSTIC)
  6204. /* Enable format-nonliteral warning again. */
  6205. #pragma GCC diagnostic pop
  6206. #endif
  6207. static int
  6208. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6209. {
  6210. char mem[MG_BUF_LEN];
  6211. char *buf = NULL;
  6212. int len;
  6213. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6214. len = mg_write(conn, buf, (size_t)len);
  6215. }
  6216. if (buf != mem) {
  6217. mg_free(buf);
  6218. }
  6219. return len;
  6220. }
  6221. int
  6222. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6223. {
  6224. va_list ap;
  6225. int result;
  6226. va_start(ap, fmt);
  6227. result = mg_vprintf(conn, fmt, ap);
  6228. va_end(ap);
  6229. return result;
  6230. }
  6231. int
  6232. mg_url_decode(const char *src,
  6233. int src_len,
  6234. char *dst,
  6235. int dst_len,
  6236. int is_form_url_encoded)
  6237. {
  6238. int i, j, a, b;
  6239. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6240. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6241. if ((i < src_len - 2) && (src[i] == '%')
  6242. && isxdigit((unsigned char)src[i + 1])
  6243. && isxdigit((unsigned char)src[i + 2])) {
  6244. a = tolower((unsigned char)src[i + 1]);
  6245. b = tolower((unsigned char)src[i + 2]);
  6246. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6247. i += 2;
  6248. } else if (is_form_url_encoded && (src[i] == '+')) {
  6249. dst[j] = ' ';
  6250. } else {
  6251. dst[j] = src[i];
  6252. }
  6253. }
  6254. dst[j] = '\0'; /* Null-terminate the destination */
  6255. return (i >= src_len) ? j : -1;
  6256. }
  6257. /* form url decoding of an entire string */
  6258. static void
  6259. url_decode_in_place(char *buf)
  6260. {
  6261. int len = (int)strlen(buf);
  6262. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6263. }
  6264. int
  6265. mg_get_var(const char *data,
  6266. size_t data_len,
  6267. const char *name,
  6268. char *dst,
  6269. size_t dst_len)
  6270. {
  6271. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6272. }
  6273. int
  6274. mg_get_var2(const char *data,
  6275. size_t data_len,
  6276. const char *name,
  6277. char *dst,
  6278. size_t dst_len,
  6279. size_t occurrence)
  6280. {
  6281. const char *p, *e, *s;
  6282. size_t name_len;
  6283. int len;
  6284. if ((dst == NULL) || (dst_len == 0)) {
  6285. len = -2;
  6286. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6287. len = -1;
  6288. dst[0] = '\0';
  6289. } else {
  6290. name_len = strlen(name);
  6291. e = data + data_len;
  6292. len = -1;
  6293. dst[0] = '\0';
  6294. /* data is "var1=val1&var2=val2...". Find variable first */
  6295. for (p = data; p + name_len < e; p++) {
  6296. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6297. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6298. /* Point p to variable value */
  6299. p += name_len + 1;
  6300. /* Point s to the end of the value */
  6301. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6302. if (s == NULL) {
  6303. s = e;
  6304. }
  6305. DEBUG_ASSERT(s >= p);
  6306. if (s < p) {
  6307. return -3;
  6308. }
  6309. /* Decode variable into destination buffer */
  6310. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6311. /* Redirect error code from -1 to -2 (destination buffer too
  6312. * small). */
  6313. if (len == -1) {
  6314. len = -2;
  6315. }
  6316. break;
  6317. }
  6318. }
  6319. }
  6320. return len;
  6321. }
  6322. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6323. int
  6324. mg_split_form_urlencoded(char *data,
  6325. struct mg_header *form_fields,
  6326. unsigned num_form_fields)
  6327. {
  6328. char *b;
  6329. int i;
  6330. int num = 0;
  6331. if (data == NULL) {
  6332. /* parameter error */
  6333. return -1;
  6334. }
  6335. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6336. /* determine the number of expected fields */
  6337. if (data[0] == 0) {
  6338. return 0;
  6339. }
  6340. /* count number of & to return the number of key-value-pairs */
  6341. num = 1;
  6342. while (*data) {
  6343. if (*data == '&') {
  6344. num++;
  6345. }
  6346. data++;
  6347. }
  6348. return num;
  6349. }
  6350. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6351. /* parameter error */
  6352. return -1;
  6353. }
  6354. for (i = 0; i < (int)num_form_fields; i++) {
  6355. /* extract key-value pairs from input data */
  6356. while ((*data == ' ') || (*data == '\t')) {
  6357. /* skip initial spaces */
  6358. data++;
  6359. }
  6360. if (*data == 0) {
  6361. /* end of string reached */
  6362. break;
  6363. }
  6364. form_fields[num].name = data;
  6365. /* find & or = */
  6366. b = data;
  6367. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6368. b++;
  6369. }
  6370. if (*b == 0) {
  6371. /* last key without value */
  6372. form_fields[num].value = NULL;
  6373. } else if (*b == '&') {
  6374. /* mid key without value */
  6375. form_fields[num].value = NULL;
  6376. } else {
  6377. /* terminate string */
  6378. *b = 0;
  6379. /* value starts after '=' */
  6380. data = b + 1;
  6381. form_fields[num].value = data;
  6382. }
  6383. /* new field is stored */
  6384. num++;
  6385. /* find a next key */
  6386. b = strchr(data, '&');
  6387. if (b == 0) {
  6388. /* no more data */
  6389. break;
  6390. } else {
  6391. /* terminate value of last field at '&' */
  6392. *b = 0;
  6393. /* next key-value-pairs starts after '&' */
  6394. data = b + 1;
  6395. }
  6396. }
  6397. /* Decode all values */
  6398. for (i = 0; i < num; i++) {
  6399. if (form_fields[i].name) {
  6400. url_decode_in_place((char *)form_fields[i].name);
  6401. }
  6402. if (form_fields[i].value) {
  6403. url_decode_in_place((char *)form_fields[i].value);
  6404. }
  6405. }
  6406. /* return number of fields found */
  6407. return num;
  6408. }
  6409. /* HCP24: some changes to compare hole var_name */
  6410. int
  6411. mg_get_cookie(const char *cookie_header,
  6412. const char *var_name,
  6413. char *dst,
  6414. size_t dst_size)
  6415. {
  6416. const char *s, *p, *end;
  6417. int name_len, len = -1;
  6418. if ((dst == NULL) || (dst_size == 0)) {
  6419. return -2;
  6420. }
  6421. dst[0] = '\0';
  6422. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6423. return -1;
  6424. }
  6425. name_len = (int)strlen(var_name);
  6426. end = s + strlen(s);
  6427. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6428. if (s[name_len] == '=') {
  6429. /* HCP24: now check is it a substring or a full cookie name */
  6430. if ((s == cookie_header) || (s[-1] == ' ')) {
  6431. s += name_len + 1;
  6432. if ((p = strchr(s, ' ')) == NULL) {
  6433. p = end;
  6434. }
  6435. if (p[-1] == ';') {
  6436. p--;
  6437. }
  6438. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6439. s++;
  6440. p--;
  6441. }
  6442. if ((size_t)(p - s) < dst_size) {
  6443. len = (int)(p - s);
  6444. mg_strlcpy(dst, s, (size_t)len + 1);
  6445. } else {
  6446. len = -3;
  6447. }
  6448. break;
  6449. }
  6450. }
  6451. }
  6452. return len;
  6453. }
  6454. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6455. static void
  6456. base64_encode(const unsigned char *src, int src_len, char *dst)
  6457. {
  6458. static const char *b64 =
  6459. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6460. int i, j, a, b, c;
  6461. for (i = j = 0; i < src_len; i += 3) {
  6462. a = src[i];
  6463. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6464. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6465. dst[j++] = b64[a >> 2];
  6466. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6467. if (i + 1 < src_len) {
  6468. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6469. }
  6470. if (i + 2 < src_len) {
  6471. dst[j++] = b64[c & 63];
  6472. }
  6473. }
  6474. while (j % 4 != 0) {
  6475. dst[j++] = '=';
  6476. }
  6477. dst[j++] = '\0';
  6478. }
  6479. #endif
  6480. #if defined(USE_LUA)
  6481. static unsigned char
  6482. b64reverse(char letter)
  6483. {
  6484. if ((letter >= 'A') && (letter <= 'Z')) {
  6485. return letter - 'A';
  6486. }
  6487. if ((letter >= 'a') && (letter <= 'z')) {
  6488. return letter - 'a' + 26;
  6489. }
  6490. if ((letter >= '0') && (letter <= '9')) {
  6491. return letter - '0' + 52;
  6492. }
  6493. if (letter == '+') {
  6494. return 62;
  6495. }
  6496. if (letter == '/') {
  6497. return 63;
  6498. }
  6499. if (letter == '=') {
  6500. return 255; /* normal end */
  6501. }
  6502. return 254; /* error */
  6503. }
  6504. static int
  6505. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6506. {
  6507. int i;
  6508. unsigned char a, b, c, d;
  6509. *dst_len = 0;
  6510. for (i = 0; i < src_len; i += 4) {
  6511. a = b64reverse(src[i]);
  6512. if (a >= 254) {
  6513. return i;
  6514. }
  6515. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6516. if (b >= 254) {
  6517. return i + 1;
  6518. }
  6519. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6520. if (c == 254) {
  6521. return i + 2;
  6522. }
  6523. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6524. if (d == 254) {
  6525. return i + 3;
  6526. }
  6527. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6528. if (c != 255) {
  6529. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6530. if (d != 255) {
  6531. dst[(*dst_len)++] = (c << 6) + d;
  6532. }
  6533. }
  6534. }
  6535. return -1;
  6536. }
  6537. #endif
  6538. static int
  6539. is_put_or_delete_method(const struct mg_connection *conn)
  6540. {
  6541. if (conn) {
  6542. const char *s = conn->request_info.request_method;
  6543. return (s != NULL)
  6544. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6545. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6546. }
  6547. return 0;
  6548. }
  6549. #if !defined(NO_FILES)
  6550. static int
  6551. extention_matches_script(
  6552. struct mg_connection *conn, /* in: request (must be valid) */
  6553. const char *filename /* in: filename (must be valid) */
  6554. )
  6555. {
  6556. #if !defined(NO_CGI)
  6557. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6558. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6559. filename)
  6560. > 0) {
  6561. return 1;
  6562. }
  6563. #endif
  6564. #if defined(USE_LUA)
  6565. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6566. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6567. filename)
  6568. > 0) {
  6569. return 1;
  6570. }
  6571. #endif
  6572. #if defined(USE_DUKTAPE)
  6573. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6574. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6575. filename)
  6576. > 0) {
  6577. return 1;
  6578. }
  6579. #endif
  6580. /* filename and conn could be unused, if all preocessor conditions
  6581. * are false (no script language supported). */
  6582. (void)filename;
  6583. (void)conn;
  6584. return 0;
  6585. }
  6586. /* For given directory path, substitute it to valid index file.
  6587. * Return 1 if index file has been found, 0 if not found.
  6588. * If the file is found, it's stats is returned in stp. */
  6589. static int
  6590. substitute_index_file(struct mg_connection *conn,
  6591. char *path,
  6592. size_t path_len,
  6593. struct mg_file_stat *filestat)
  6594. {
  6595. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6596. struct vec filename_vec;
  6597. size_t n = strlen(path);
  6598. int found = 0;
  6599. /* The 'path' given to us points to the directory. Remove all trailing
  6600. * directory separator characters from the end of the path, and
  6601. * then append single directory separator character. */
  6602. while ((n > 0) && (path[n - 1] == '/')) {
  6603. n--;
  6604. }
  6605. path[n] = '/';
  6606. /* Traverse index files list. For each entry, append it to the given
  6607. * path and see if the file exists. If it exists, break the loop */
  6608. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6609. /* Ignore too long entries that may overflow path buffer */
  6610. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6611. continue;
  6612. }
  6613. /* Prepare full path to the index file */
  6614. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6615. /* Does it exist? */
  6616. if (mg_stat(conn, path, filestat)) {
  6617. /* Yes it does, break the loop */
  6618. found = 1;
  6619. break;
  6620. }
  6621. }
  6622. /* If no index file exists, restore directory path */
  6623. if (!found) {
  6624. path[n] = '\0';
  6625. }
  6626. return found;
  6627. }
  6628. #endif
  6629. static void
  6630. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6631. char *filename, /* out: filename */
  6632. size_t filename_buf_len, /* in: size of filename buffer */
  6633. struct mg_file_stat *filestat, /* out: file status structure */
  6634. int *is_found, /* out: file found (directly) */
  6635. int *is_script_resource, /* out: handled by a script? */
  6636. int *is_websocket_request, /* out: websocket connetion? */
  6637. int *is_put_or_delete_request /* out: put/delete a file? */
  6638. )
  6639. {
  6640. char const *accept_encoding;
  6641. #if !defined(NO_FILES)
  6642. const char *uri = conn->request_info.local_uri;
  6643. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6644. const char *rewrite;
  6645. struct vec a, b;
  6646. ptrdiff_t match_len;
  6647. char gz_path[PATH_MAX];
  6648. int truncated;
  6649. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6650. char *tmp_str;
  6651. size_t tmp_str_len, sep_pos;
  6652. int allow_substitute_script_subresources;
  6653. #endif
  6654. #else
  6655. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6656. #endif
  6657. /* Step 1: Set all initially unknown outputs to zero */
  6658. memset(filestat, 0, sizeof(*filestat));
  6659. *filename = 0;
  6660. *is_found = 0;
  6661. *is_script_resource = 0;
  6662. /* Step 2: Check if the request attempts to modify the file system */
  6663. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6664. /* Step 3: Check if it is a websocket request, and modify the document
  6665. * root if required */
  6666. #if defined(USE_WEBSOCKET)
  6667. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6668. #if !defined(NO_FILES)
  6669. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6670. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6671. }
  6672. #endif /* !NO_FILES */
  6673. #else /* USE_WEBSOCKET */
  6674. *is_websocket_request = 0;
  6675. #endif /* USE_WEBSOCKET */
  6676. /* Step 4: Check if gzip encoded response is allowed */
  6677. conn->accept_gzip = 0;
  6678. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6679. if (strstr(accept_encoding, "gzip") != NULL) {
  6680. conn->accept_gzip = 1;
  6681. }
  6682. }
  6683. #if !defined(NO_FILES)
  6684. /* Step 5: If there is no root directory, don't look for files. */
  6685. /* Note that root == NULL is a regular use case here. This occurs,
  6686. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6687. * config is not required. */
  6688. if (root == NULL) {
  6689. /* all file related outputs have already been set to 0, just return
  6690. */
  6691. return;
  6692. }
  6693. /* Step 6: Determine the local file path from the root path and the
  6694. * request uri. */
  6695. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6696. * part of the path one byte on the right. */
  6697. mg_snprintf(
  6698. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6699. if (truncated) {
  6700. goto interpret_cleanup;
  6701. }
  6702. /* Step 7: URI rewriting */
  6703. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6704. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6705. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6706. mg_snprintf(conn,
  6707. &truncated,
  6708. filename,
  6709. filename_buf_len - 1,
  6710. "%.*s%s",
  6711. (int)b.len,
  6712. b.ptr,
  6713. uri + match_len);
  6714. break;
  6715. }
  6716. }
  6717. if (truncated) {
  6718. goto interpret_cleanup;
  6719. }
  6720. /* Step 8: Check if the file exists at the server */
  6721. /* Local file path and name, corresponding to requested URI
  6722. * is now stored in "filename" variable. */
  6723. if (mg_stat(conn, filename, filestat)) {
  6724. int uri_len = (int)strlen(uri);
  6725. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6726. /* 8.1: File exists. */
  6727. *is_found = 1;
  6728. /* 8.2: Check if it is a script type. */
  6729. if (extention_matches_script(conn, filename)) {
  6730. /* The request addresses a CGI resource, Lua script or
  6731. * server-side javascript.
  6732. * The URI corresponds to the script itself (like
  6733. * /path/script.cgi), and there is no additional resource
  6734. * path (like /path/script.cgi/something).
  6735. * Requests that modify (replace or delete) a resource, like
  6736. * PUT and DELETE requests, should replace/delete the script
  6737. * file.
  6738. * Requests that read or write from/to a resource, like GET and
  6739. * POST requests, should call the script and return the
  6740. * generated response. */
  6741. *is_script_resource = (!*is_put_or_delete_request);
  6742. }
  6743. /* 8.3: If the request target is a directory, there could be
  6744. * a substitute file (index.html, index.cgi, ...). */
  6745. if (filestat->is_directory && is_uri_end_slash) {
  6746. /* Use a local copy here, since substitute_index_file will
  6747. * change the content of the file status */
  6748. struct mg_file_stat tmp_filestat;
  6749. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6750. if (substitute_index_file(
  6751. conn, filename, filename_buf_len, &tmp_filestat)) {
  6752. /* Substitute file found. Copy stat to the output, then
  6753. * check if the file is a script file */
  6754. *filestat = tmp_filestat;
  6755. if (extention_matches_script(conn, filename)) {
  6756. /* Substitute file is a script file */
  6757. *is_script_resource = 1;
  6758. } else {
  6759. /* Substitute file is a regular file */
  6760. *is_script_resource = 0;
  6761. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6762. }
  6763. }
  6764. /* If there is no substitute file, the server could return
  6765. * a directory listing in a later step */
  6766. }
  6767. return;
  6768. }
  6769. /* Step 9: Check for zipped files: */
  6770. /* If we can't find the actual file, look for the file
  6771. * with the same name but a .gz extension. If we find it,
  6772. * use that and set the gzipped flag in the file struct
  6773. * to indicate that the response need to have the content-
  6774. * encoding: gzip header.
  6775. * We can only do this if the browser declares support. */
  6776. if (conn->accept_gzip) {
  6777. mg_snprintf(
  6778. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6779. if (truncated) {
  6780. goto interpret_cleanup;
  6781. }
  6782. if (mg_stat(conn, gz_path, filestat)) {
  6783. if (filestat) {
  6784. filestat->is_gzipped = 1;
  6785. *is_found = 1;
  6786. }
  6787. /* Currently gz files can not be scripts. */
  6788. return;
  6789. }
  6790. }
  6791. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6792. /* Step 10: Script resources may handle sub-resources */
  6793. /* Support PATH_INFO for CGI scripts. */
  6794. tmp_str_len = strlen(filename);
  6795. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6796. if (!tmp_str) {
  6797. /* Out of memory */
  6798. goto interpret_cleanup;
  6799. }
  6800. memcpy(tmp_str, filename, tmp_str_len + 1);
  6801. /* Check config, if index scripts may have sub-resources */
  6802. allow_substitute_script_subresources =
  6803. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6804. "yes");
  6805. sep_pos = tmp_str_len;
  6806. while (sep_pos > 0) {
  6807. sep_pos--;
  6808. if (tmp_str[sep_pos] == '/') {
  6809. int is_script = 0, does_exist = 0;
  6810. tmp_str[sep_pos] = 0;
  6811. if (tmp_str[0]) {
  6812. is_script = extention_matches_script(conn, tmp_str);
  6813. does_exist = mg_stat(conn, tmp_str, filestat);
  6814. }
  6815. if (does_exist && is_script) {
  6816. filename[sep_pos] = 0;
  6817. memmove(filename + sep_pos + 2,
  6818. filename + sep_pos + 1,
  6819. strlen(filename + sep_pos + 1) + 1);
  6820. conn->path_info = filename + sep_pos + 1;
  6821. filename[sep_pos + 1] = '/';
  6822. *is_script_resource = 1;
  6823. *is_found = 1;
  6824. break;
  6825. }
  6826. if (allow_substitute_script_subresources) {
  6827. if (substitute_index_file(
  6828. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6829. /* some intermediate directory has an index file */
  6830. if (extention_matches_script(conn, tmp_str)) {
  6831. DEBUG_TRACE("Substitute script %s serving path %s",
  6832. tmp_str,
  6833. filename);
  6834. /* this index file is a script */
  6835. mg_snprintf(conn,
  6836. &truncated,
  6837. filename,
  6838. filename_buf_len,
  6839. "%s//%s",
  6840. tmp_str,
  6841. filename + sep_pos + 1);
  6842. if (truncated) {
  6843. mg_free(tmp_str);
  6844. goto interpret_cleanup;
  6845. }
  6846. sep_pos = strlen(tmp_str);
  6847. filename[sep_pos] = 0;
  6848. conn->path_info = filename + sep_pos + 1;
  6849. *is_script_resource = 1;
  6850. *is_found = 1;
  6851. break;
  6852. } else {
  6853. DEBUG_TRACE("Substitute file %s serving path %s",
  6854. tmp_str,
  6855. filename);
  6856. /* non-script files will not have sub-resources */
  6857. filename[sep_pos] = 0;
  6858. conn->path_info = 0;
  6859. *is_script_resource = 0;
  6860. *is_found = 0;
  6861. break;
  6862. }
  6863. }
  6864. }
  6865. tmp_str[sep_pos] = '/';
  6866. }
  6867. }
  6868. mg_free(tmp_str);
  6869. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6870. #endif /* !defined(NO_FILES) */
  6871. return;
  6872. #if !defined(NO_FILES)
  6873. /* Reset all outputs */
  6874. interpret_cleanup:
  6875. memset(filestat, 0, sizeof(*filestat));
  6876. *filename = 0;
  6877. *is_found = 0;
  6878. *is_script_resource = 0;
  6879. *is_websocket_request = 0;
  6880. *is_put_or_delete_request = 0;
  6881. #endif /* !defined(NO_FILES) */
  6882. }
  6883. /* Check whether full request is buffered. Return:
  6884. * -1 if request or response is malformed
  6885. * 0 if request or response is not yet fully buffered
  6886. * >0 actual request length, including last \r\n\r\n */
  6887. static int
  6888. get_http_header_len(const char *buf, int buflen)
  6889. {
  6890. int i;
  6891. for (i = 0; i < buflen; i++) {
  6892. /* Do an unsigned comparison in some conditions below */
  6893. const unsigned char c = (unsigned char)buf[i];
  6894. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6895. && !isprint(c)) {
  6896. /* abort scan as soon as one malformed character is found */
  6897. return -1;
  6898. }
  6899. if (i < buflen - 1) {
  6900. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6901. /* Two newline, no carriage return - not standard compliant,
  6902. * but it should be accepted */
  6903. return i + 2;
  6904. }
  6905. }
  6906. if (i < buflen - 3) {
  6907. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6908. && (buf[i + 3] == '\n')) {
  6909. /* Two \r\n - standard compliant */
  6910. return i + 4;
  6911. }
  6912. }
  6913. }
  6914. return 0;
  6915. }
  6916. #if !defined(NO_CACHING)
  6917. /* Convert month to the month number. Return -1 on error, or month number */
  6918. static int
  6919. get_month_index(const char *s)
  6920. {
  6921. size_t i;
  6922. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6923. if (!strcmp(s, month_names[i])) {
  6924. return (int)i;
  6925. }
  6926. }
  6927. return -1;
  6928. }
  6929. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6930. static time_t
  6931. parse_date_string(const char *datetime)
  6932. {
  6933. char month_str[32] = {0};
  6934. int second, minute, hour, day, month, year;
  6935. time_t result = (time_t)0;
  6936. struct tm tm;
  6937. if ((sscanf(datetime,
  6938. "%d/%3s/%d %d:%d:%d",
  6939. &day,
  6940. month_str,
  6941. &year,
  6942. &hour,
  6943. &minute,
  6944. &second)
  6945. == 6)
  6946. || (sscanf(datetime,
  6947. "%d %3s %d %d:%d:%d",
  6948. &day,
  6949. month_str,
  6950. &year,
  6951. &hour,
  6952. &minute,
  6953. &second)
  6954. == 6)
  6955. || (sscanf(datetime,
  6956. "%*3s, %d %3s %d %d:%d:%d",
  6957. &day,
  6958. month_str,
  6959. &year,
  6960. &hour,
  6961. &minute,
  6962. &second)
  6963. == 6)
  6964. || (sscanf(datetime,
  6965. "%d-%3s-%d %d:%d:%d",
  6966. &day,
  6967. month_str,
  6968. &year,
  6969. &hour,
  6970. &minute,
  6971. &second)
  6972. == 6)) {
  6973. month = get_month_index(month_str);
  6974. if ((month >= 0) && (year >= 1970)) {
  6975. memset(&tm, 0, sizeof(tm));
  6976. tm.tm_year = year - 1900;
  6977. tm.tm_mon = month;
  6978. tm.tm_mday = day;
  6979. tm.tm_hour = hour;
  6980. tm.tm_min = minute;
  6981. tm.tm_sec = second;
  6982. result = timegm(&tm);
  6983. }
  6984. }
  6985. return result;
  6986. }
  6987. #endif /* !NO_CACHING */
  6988. /* Pre-process URIs according to RFC + protect against directory disclosure
  6989. * attacks by removing '..', excessive '/' and '\' characters */
  6990. static void
  6991. remove_dot_segments(char *inout)
  6992. {
  6993. /* Windows backend protection
  6994. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6995. * in URI by slash */
  6996. char *out_end = inout;
  6997. char *in = inout;
  6998. if (!in) {
  6999. /* Param error. */
  7000. return;
  7001. }
  7002. while (*in) {
  7003. if (*in == '\\') {
  7004. *in = '/';
  7005. }
  7006. in++;
  7007. }
  7008. /* Algorithm "remove_dot_segments" from
  7009. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7010. /* Step 1:
  7011. * The input buffer is initialized.
  7012. * The output buffer is initialized to the empty string.
  7013. */
  7014. in = inout;
  7015. /* Step 2:
  7016. * While the input buffer is not empty, loop as follows:
  7017. */
  7018. /* Less than out_end of the inout buffer is used as output, so keep
  7019. * condition: out_end <= in */
  7020. while (*in) {
  7021. /* Step 2a:
  7022. * If the input buffer begins with a prefix of "../" or "./",
  7023. * then remove that prefix from the input buffer;
  7024. */
  7025. if (!strncmp(in, "../", 3)) {
  7026. in += 3;
  7027. } else if (!strncmp(in, "./", 2)) {
  7028. in += 2;
  7029. }
  7030. /* otherwise */
  7031. /* Step 2b:
  7032. * if the input buffer begins with a prefix of "/./" or "/.",
  7033. * where "." is a complete path segment, then replace that
  7034. * prefix with "/" in the input buffer;
  7035. */
  7036. else if (!strncmp(in, "/./", 3)) {
  7037. in += 2;
  7038. } else if (!strcmp(in, "/.")) {
  7039. in[1] = 0;
  7040. }
  7041. /* otherwise */
  7042. /* Step 2c:
  7043. * if the input buffer begins with a prefix of "/../" or "/..",
  7044. * where ".." is a complete path segment, then replace that
  7045. * prefix with "/" in the input buffer and remove the last
  7046. * segment and its preceding "/" (if any) from the output
  7047. * buffer;
  7048. */
  7049. else if (!strncmp(in, "/../", 4)) {
  7050. in += 3;
  7051. if (inout != out_end) {
  7052. /* remove last segment */
  7053. do {
  7054. out_end--;
  7055. } while ((inout != out_end) && (*out_end != '/'));
  7056. }
  7057. } else if (!strcmp(in, "/..")) {
  7058. in[1] = 0;
  7059. if (inout != out_end) {
  7060. /* remove last segment */
  7061. do {
  7062. out_end--;
  7063. } while ((inout != out_end) && (*out_end != '/'));
  7064. }
  7065. }
  7066. /* otherwise */
  7067. /* Step 2d:
  7068. * if the input buffer consists only of "." or "..", then remove
  7069. * that from the input buffer;
  7070. */
  7071. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7072. *in = 0;
  7073. }
  7074. /* otherwise */
  7075. /* Step 2e:
  7076. * move the first path segment in the input buffer to the end of
  7077. * the output buffer, including the initial "/" character (if
  7078. * any) and any subsequent characters up to, but not including,
  7079. * the next "/" character or the end of the input buffer.
  7080. */
  7081. else {
  7082. do {
  7083. *out_end = *in;
  7084. out_end++;
  7085. in++;
  7086. } while ((*in != 0) && (*in != '/'));
  7087. }
  7088. }
  7089. /* Step 3:
  7090. * Finally, the output buffer is returned as the result of
  7091. * remove_dot_segments.
  7092. */
  7093. /* Terminate output */
  7094. *out_end = 0;
  7095. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7096. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7097. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7098. * or "//" anymore.
  7099. */
  7100. out_end = in = inout;
  7101. while (*in) {
  7102. if (*in == '.') {
  7103. /* remove . at the end or preceding of / */
  7104. char *in_ahead = in;
  7105. do {
  7106. in_ahead++;
  7107. } while (*in_ahead == '.');
  7108. if (*in_ahead == '/') {
  7109. in = in_ahead;
  7110. if ((out_end != inout) && (out_end[-1] == '/')) {
  7111. /* remove generated // */
  7112. out_end--;
  7113. }
  7114. } else if (*in_ahead == 0) {
  7115. in = in_ahead;
  7116. } else {
  7117. do {
  7118. *out_end++ = '.';
  7119. in++;
  7120. } while (in != in_ahead);
  7121. }
  7122. } else if (*in == '/') {
  7123. /* replace // by / */
  7124. *out_end++ = '/';
  7125. do {
  7126. in++;
  7127. } while (*in == '/');
  7128. } else {
  7129. *out_end++ = *in;
  7130. in++;
  7131. }
  7132. }
  7133. *out_end = 0;
  7134. }
  7135. static const struct {
  7136. const char *extension;
  7137. size_t ext_len;
  7138. const char *mime_type;
  7139. } builtin_mime_types[] = {
  7140. /* IANA registered MIME types
  7141. * (http://www.iana.org/assignments/media-types)
  7142. * application types */
  7143. {".doc", 4, "application/msword"},
  7144. {".eps", 4, "application/postscript"},
  7145. {".exe", 4, "application/octet-stream"},
  7146. {".js", 3, "application/javascript"},
  7147. {".json", 5, "application/json"},
  7148. {".pdf", 4, "application/pdf"},
  7149. {".ps", 3, "application/postscript"},
  7150. {".rtf", 4, "application/rtf"},
  7151. {".xhtml", 6, "application/xhtml+xml"},
  7152. {".xsl", 4, "application/xml"},
  7153. {".xslt", 5, "application/xml"},
  7154. /* fonts */
  7155. {".ttf", 4, "application/font-sfnt"},
  7156. {".cff", 4, "application/font-sfnt"},
  7157. {".otf", 4, "application/font-sfnt"},
  7158. {".aat", 4, "application/font-sfnt"},
  7159. {".sil", 4, "application/font-sfnt"},
  7160. {".pfr", 4, "application/font-tdpfr"},
  7161. {".woff", 5, "application/font-woff"},
  7162. /* audio */
  7163. {".mp3", 4, "audio/mpeg"},
  7164. {".oga", 4, "audio/ogg"},
  7165. {".ogg", 4, "audio/ogg"},
  7166. /* image */
  7167. {".gif", 4, "image/gif"},
  7168. {".ief", 4, "image/ief"},
  7169. {".jpeg", 5, "image/jpeg"},
  7170. {".jpg", 4, "image/jpeg"},
  7171. {".jpm", 4, "image/jpm"},
  7172. {".jpx", 4, "image/jpx"},
  7173. {".png", 4, "image/png"},
  7174. {".svg", 4, "image/svg+xml"},
  7175. {".tif", 4, "image/tiff"},
  7176. {".tiff", 5, "image/tiff"},
  7177. /* model */
  7178. {".wrl", 4, "model/vrml"},
  7179. /* text */
  7180. {".css", 4, "text/css"},
  7181. {".csv", 4, "text/csv"},
  7182. {".htm", 4, "text/html"},
  7183. {".html", 5, "text/html"},
  7184. {".sgm", 4, "text/sgml"},
  7185. {".shtm", 5, "text/html"},
  7186. {".shtml", 6, "text/html"},
  7187. {".txt", 4, "text/plain"},
  7188. {".xml", 4, "text/xml"},
  7189. /* video */
  7190. {".mov", 4, "video/quicktime"},
  7191. {".mp4", 4, "video/mp4"},
  7192. {".mpeg", 5, "video/mpeg"},
  7193. {".mpg", 4, "video/mpeg"},
  7194. {".ogv", 4, "video/ogg"},
  7195. {".qt", 3, "video/quicktime"},
  7196. /* not registered types
  7197. * (http://reference.sitepoint.com/html/mime-types-full,
  7198. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7199. {".arj", 4, "application/x-arj-compressed"},
  7200. {".gz", 3, "application/x-gunzip"},
  7201. {".rar", 4, "application/x-arj-compressed"},
  7202. {".swf", 4, "application/x-shockwave-flash"},
  7203. {".tar", 4, "application/x-tar"},
  7204. {".tgz", 4, "application/x-tar-gz"},
  7205. {".torrent", 8, "application/x-bittorrent"},
  7206. {".ppt", 4, "application/x-mspowerpoint"},
  7207. {".xls", 4, "application/x-msexcel"},
  7208. {".zip", 4, "application/x-zip-compressed"},
  7209. {".aac",
  7210. 4,
  7211. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7212. {".aif", 4, "audio/x-aif"},
  7213. {".m3u", 4, "audio/x-mpegurl"},
  7214. {".mid", 4, "audio/x-midi"},
  7215. {".ra", 3, "audio/x-pn-realaudio"},
  7216. {".ram", 4, "audio/x-pn-realaudio"},
  7217. {".wav", 4, "audio/x-wav"},
  7218. {".bmp", 4, "image/bmp"},
  7219. {".ico", 4, "image/x-icon"},
  7220. {".pct", 4, "image/x-pct"},
  7221. {".pict", 5, "image/pict"},
  7222. {".rgb", 4, "image/x-rgb"},
  7223. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7224. {".asf", 4, "video/x-ms-asf"},
  7225. {".avi", 4, "video/x-msvideo"},
  7226. {".m4v", 4, "video/x-m4v"},
  7227. {NULL, 0, NULL}};
  7228. const char *
  7229. mg_get_builtin_mime_type(const char *path)
  7230. {
  7231. const char *ext;
  7232. size_t i, path_len;
  7233. path_len = strlen(path);
  7234. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7235. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7236. if ((path_len > builtin_mime_types[i].ext_len)
  7237. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7238. return builtin_mime_types[i].mime_type;
  7239. }
  7240. }
  7241. return "text/plain";
  7242. }
  7243. /* Look at the "path" extension and figure what mime type it has.
  7244. * Store mime type in the vector. */
  7245. static void
  7246. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7247. {
  7248. struct vec ext_vec, mime_vec;
  7249. const char *list, *ext;
  7250. size_t path_len;
  7251. path_len = strlen(path);
  7252. if ((conn == NULL) || (vec == NULL)) {
  7253. if (vec != NULL) {
  7254. memset(vec, '\0', sizeof(struct vec));
  7255. }
  7256. return;
  7257. }
  7258. /* Scan user-defined mime types first, in case user wants to
  7259. * override default mime types. */
  7260. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7261. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7262. /* ext now points to the path suffix */
  7263. ext = path + path_len - ext_vec.len;
  7264. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7265. *vec = mime_vec;
  7266. return;
  7267. }
  7268. }
  7269. vec->ptr = mg_get_builtin_mime_type(path);
  7270. vec->len = strlen(vec->ptr);
  7271. }
  7272. /* Stringify binary data. Output buffer must be twice as big as input,
  7273. * because each byte takes 2 bytes in string representation */
  7274. static void
  7275. bin2str(char *to, const unsigned char *p, size_t len)
  7276. {
  7277. static const char *hex = "0123456789abcdef";
  7278. for (; len--; p++) {
  7279. *to++ = hex[p[0] >> 4];
  7280. *to++ = hex[p[0] & 0x0f];
  7281. }
  7282. *to = '\0';
  7283. }
  7284. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7285. */
  7286. char *
  7287. mg_md5(char buf[33], ...)
  7288. {
  7289. md5_byte_t hash[16];
  7290. const char *p;
  7291. va_list ap;
  7292. md5_state_t ctx;
  7293. md5_init(&ctx);
  7294. va_start(ap, buf);
  7295. while ((p = va_arg(ap, const char *)) != NULL) {
  7296. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7297. }
  7298. va_end(ap);
  7299. md5_finish(&ctx, hash);
  7300. bin2str(buf, hash, sizeof(hash));
  7301. return buf;
  7302. }
  7303. /* Check the user's password, return 1 if OK */
  7304. static int
  7305. check_password(const char *method,
  7306. const char *ha1,
  7307. const char *uri,
  7308. const char *nonce,
  7309. const char *nc,
  7310. const char *cnonce,
  7311. const char *qop,
  7312. const char *response)
  7313. {
  7314. char ha2[32 + 1], expected_response[32 + 1];
  7315. /* Some of the parameters may be NULL */
  7316. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7317. || (qop == NULL) || (response == NULL)) {
  7318. return 0;
  7319. }
  7320. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7321. if (strlen(response) != 32) {
  7322. return 0;
  7323. }
  7324. mg_md5(ha2, method, ":", uri, NULL);
  7325. mg_md5(expected_response,
  7326. ha1,
  7327. ":",
  7328. nonce,
  7329. ":",
  7330. nc,
  7331. ":",
  7332. cnonce,
  7333. ":",
  7334. qop,
  7335. ":",
  7336. ha2,
  7337. NULL);
  7338. return mg_strcasecmp(response, expected_response) == 0;
  7339. }
  7340. #if !defined(NO_FILESYSTEMS)
  7341. /* Use the global passwords file, if specified by auth_gpass option,
  7342. * or search for .htpasswd in the requested directory. */
  7343. static void
  7344. open_auth_file(struct mg_connection *conn,
  7345. const char *path,
  7346. struct mg_file *filep)
  7347. {
  7348. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7349. char name[PATH_MAX];
  7350. const char *p, *e,
  7351. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7352. int truncated;
  7353. if (gpass != NULL) {
  7354. /* Use global passwords file */
  7355. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7356. #if defined(DEBUG)
  7357. /* Use mg_cry_internal here, since gpass has been
  7358. * configured. */
  7359. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7360. #endif
  7361. }
  7362. /* Important: using local struct mg_file to test path for
  7363. * is_directory flag. If filep is used, mg_stat() makes it
  7364. * appear as if auth file was opened.
  7365. * TODO(mid): Check if this is still required after rewriting
  7366. * mg_stat */
  7367. } else if (mg_stat(conn, path, &filep->stat)
  7368. && filep->stat.is_directory) {
  7369. mg_snprintf(conn,
  7370. &truncated,
  7371. name,
  7372. sizeof(name),
  7373. "%s/%s",
  7374. path,
  7375. PASSWORDS_FILE_NAME);
  7376. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7377. #if defined(DEBUG)
  7378. /* Don't use mg_cry_internal here, but only a trace, since
  7379. * this is a typical case. It will occur for every directory
  7380. * without a password file. */
  7381. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7382. #endif
  7383. }
  7384. } else {
  7385. /* Try to find .htpasswd in requested directory. */
  7386. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7387. if (e[0] == '/') {
  7388. break;
  7389. }
  7390. }
  7391. mg_snprintf(conn,
  7392. &truncated,
  7393. name,
  7394. sizeof(name),
  7395. "%.*s/%s",
  7396. (int)(e - p),
  7397. p,
  7398. PASSWORDS_FILE_NAME);
  7399. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7400. #if defined(DEBUG)
  7401. /* Don't use mg_cry_internal here, but only a trace, since
  7402. * this is a typical case. It will occur for every directory
  7403. * without a password file. */
  7404. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7405. #endif
  7406. }
  7407. }
  7408. }
  7409. }
  7410. #endif /* NO_FILESYSTEMS */
  7411. /* Parsed Authorization header */
  7412. struct ah {
  7413. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7414. };
  7415. /* Return 1 on success. Always initializes the ah structure. */
  7416. static int
  7417. parse_auth_header(struct mg_connection *conn,
  7418. char *buf,
  7419. size_t buf_size,
  7420. struct ah *ah)
  7421. {
  7422. char *name, *value, *s;
  7423. const char *auth_header;
  7424. uint64_t nonce;
  7425. if (!ah || !conn) {
  7426. return 0;
  7427. }
  7428. (void)memset(ah, 0, sizeof(*ah));
  7429. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7430. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7431. return 0;
  7432. }
  7433. /* Make modifiable copy of the auth header */
  7434. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7435. s = buf;
  7436. /* Parse authorization header */
  7437. for (;;) {
  7438. /* Gobble initial spaces */
  7439. while (isspace((unsigned char)*s)) {
  7440. s++;
  7441. }
  7442. name = skip_quoted(&s, "=", " ", 0);
  7443. /* Value is either quote-delimited, or ends at first comma or space.
  7444. */
  7445. if (s[0] == '\"') {
  7446. s++;
  7447. value = skip_quoted(&s, "\"", " ", '\\');
  7448. if (s[0] == ',') {
  7449. s++;
  7450. }
  7451. } else {
  7452. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7453. * uses spaces */
  7454. }
  7455. if (*name == '\0') {
  7456. break;
  7457. }
  7458. if (!strcmp(name, "username")) {
  7459. ah->user = value;
  7460. } else if (!strcmp(name, "cnonce")) {
  7461. ah->cnonce = value;
  7462. } else if (!strcmp(name, "response")) {
  7463. ah->response = value;
  7464. } else if (!strcmp(name, "uri")) {
  7465. ah->uri = value;
  7466. } else if (!strcmp(name, "qop")) {
  7467. ah->qop = value;
  7468. } else if (!strcmp(name, "nc")) {
  7469. ah->nc = value;
  7470. } else if (!strcmp(name, "nonce")) {
  7471. ah->nonce = value;
  7472. }
  7473. }
  7474. #if !defined(NO_NONCE_CHECK)
  7475. /* Read the nonce from the response. */
  7476. if (ah->nonce == NULL) {
  7477. return 0;
  7478. }
  7479. s = NULL;
  7480. nonce = strtoull(ah->nonce, &s, 10);
  7481. if ((s == NULL) || (*s != 0)) {
  7482. return 0;
  7483. }
  7484. /* Convert the nonce from the client to a number. */
  7485. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7486. /* The converted number corresponds to the time the nounce has been
  7487. * created. This should not be earlier than the server start. */
  7488. /* Server side nonce check is valuable in all situations but one:
  7489. * if the server restarts frequently, but the client should not see
  7490. * that, so the server should accept nonces from previous starts. */
  7491. /* However, the reasonable default is to not accept a nonce from a
  7492. * previous start, so if anyone changed the access rights between
  7493. * two restarts, a new login is required. */
  7494. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7495. /* nonce is from a previous start of the server and no longer valid
  7496. * (replay attack?) */
  7497. return 0;
  7498. }
  7499. /* Check if the nonce is too high, so it has not (yet) been used by the
  7500. * server. */
  7501. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7502. + conn->dom_ctx->nonce_count)) {
  7503. return 0;
  7504. }
  7505. #else
  7506. (void)nonce;
  7507. #endif
  7508. /* CGI needs it as REMOTE_USER */
  7509. if (ah->user != NULL) {
  7510. conn->request_info.remote_user =
  7511. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7512. } else {
  7513. return 0;
  7514. }
  7515. return 1;
  7516. }
  7517. static const char *
  7518. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7519. {
  7520. #if defined(MG_USE_OPEN_FILE)
  7521. const char *eof;
  7522. size_t len;
  7523. const char *memend;
  7524. #else
  7525. (void)p; /* parameter is unused */
  7526. #endif
  7527. if (!filep) {
  7528. return NULL;
  7529. }
  7530. #if defined(MG_USE_OPEN_FILE)
  7531. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7532. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7533. /* Search for \n from p till the end of stream */
  7534. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7535. if (eof != NULL) {
  7536. eof += 1; /* Include \n */
  7537. } else {
  7538. eof = memend; /* Copy remaining data */
  7539. }
  7540. len =
  7541. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7542. memcpy(buf, *p, len);
  7543. buf[len] = '\0';
  7544. *p += len;
  7545. return len ? eof : NULL;
  7546. } else /* filep->access.fp block below */
  7547. #endif
  7548. if (filep->access.fp != NULL) {
  7549. return fgets(buf, (int)size, filep->access.fp);
  7550. } else {
  7551. return NULL;
  7552. }
  7553. }
  7554. /* Define the initial recursion depth for procesesing htpasswd files that
  7555. * include other htpasswd
  7556. * (or even the same) files. It is not difficult to provide a file or files
  7557. * s.t. they force civetweb
  7558. * to infinitely recurse and then crash.
  7559. */
  7560. #define INITIAL_DEPTH 9
  7561. #if INITIAL_DEPTH <= 0
  7562. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7563. #endif
  7564. #if !defined(NO_FILESYSTEMS)
  7565. struct read_auth_file_struct {
  7566. struct mg_connection *conn;
  7567. struct ah ah;
  7568. const char *domain;
  7569. char buf[256 + 256 + 40];
  7570. const char *f_user;
  7571. const char *f_domain;
  7572. const char *f_ha1;
  7573. };
  7574. static int
  7575. read_auth_file(struct mg_file *filep,
  7576. struct read_auth_file_struct *workdata,
  7577. int depth)
  7578. {
  7579. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7580. int is_authorized = 0;
  7581. struct mg_file fp;
  7582. size_t l;
  7583. if (!filep || !workdata || (0 == depth)) {
  7584. return 0;
  7585. }
  7586. /* Loop over passwords file */
  7587. #if defined(MG_USE_OPEN_FILE)
  7588. p = (char *)filep->access.membuf;
  7589. #endif
  7590. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7591. l = strlen(workdata->buf);
  7592. while (l > 0) {
  7593. if (isspace((unsigned char)workdata->buf[l - 1])
  7594. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7595. l--;
  7596. workdata->buf[l] = 0;
  7597. } else
  7598. break;
  7599. }
  7600. if (l < 1) {
  7601. continue;
  7602. }
  7603. workdata->f_user = workdata->buf;
  7604. if (workdata->f_user[0] == ':') {
  7605. /* user names may not contain a ':' and may not be empty,
  7606. * so lines starting with ':' may be used for a special purpose
  7607. */
  7608. if (workdata->f_user[1] == '#') {
  7609. /* :# is a comment */
  7610. continue;
  7611. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7612. if (mg_fopen(workdata->conn,
  7613. workdata->f_user + 9,
  7614. MG_FOPEN_MODE_READ,
  7615. &fp)) {
  7616. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7617. (void)mg_fclose(
  7618. &fp.access); /* ignore error on read only file */
  7619. /* No need to continue processing files once we have a
  7620. * match, since nothing will reset it back
  7621. * to 0.
  7622. */
  7623. if (is_authorized) {
  7624. return is_authorized;
  7625. }
  7626. } else {
  7627. mg_cry_internal(workdata->conn,
  7628. "%s: cannot open authorization file: %s",
  7629. __func__,
  7630. workdata->buf);
  7631. }
  7632. continue;
  7633. }
  7634. /* everything is invalid for the moment (might change in the
  7635. * future) */
  7636. mg_cry_internal(workdata->conn,
  7637. "%s: syntax error in authorization file: %s",
  7638. __func__,
  7639. workdata->buf);
  7640. continue;
  7641. }
  7642. workdata->f_domain = strchr(workdata->f_user, ':');
  7643. if (workdata->f_domain == NULL) {
  7644. mg_cry_internal(workdata->conn,
  7645. "%s: syntax error in authorization file: %s",
  7646. __func__,
  7647. workdata->buf);
  7648. continue;
  7649. }
  7650. *(char *)(workdata->f_domain) = 0;
  7651. (workdata->f_domain)++;
  7652. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7653. if (workdata->f_ha1 == NULL) {
  7654. mg_cry_internal(workdata->conn,
  7655. "%s: syntax error in authorization file: %s",
  7656. __func__,
  7657. workdata->buf);
  7658. continue;
  7659. }
  7660. *(char *)(workdata->f_ha1) = 0;
  7661. (workdata->f_ha1)++;
  7662. if (!strcmp(workdata->ah.user, workdata->f_user)
  7663. && !strcmp(workdata->domain, workdata->f_domain)) {
  7664. return check_password(workdata->conn->request_info.request_method,
  7665. workdata->f_ha1,
  7666. workdata->ah.uri,
  7667. workdata->ah.nonce,
  7668. workdata->ah.nc,
  7669. workdata->ah.cnonce,
  7670. workdata->ah.qop,
  7671. workdata->ah.response);
  7672. }
  7673. }
  7674. return is_authorized;
  7675. }
  7676. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7677. static int
  7678. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7679. {
  7680. struct read_auth_file_struct workdata;
  7681. char buf[MG_BUF_LEN];
  7682. if (!conn || !conn->dom_ctx) {
  7683. return 0;
  7684. }
  7685. memset(&workdata, 0, sizeof(workdata));
  7686. workdata.conn = conn;
  7687. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7688. return 0;
  7689. }
  7690. if (realm) {
  7691. workdata.domain = realm;
  7692. } else {
  7693. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7694. }
  7695. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7696. }
  7697. /* Public function to check http digest authentication header */
  7698. int
  7699. mg_check_digest_access_authentication(struct mg_connection *conn,
  7700. const char *realm,
  7701. const char *filename)
  7702. {
  7703. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7704. int auth;
  7705. if (!conn || !filename) {
  7706. return -1;
  7707. }
  7708. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7709. return -2;
  7710. }
  7711. auth = authorize(conn, &file, realm);
  7712. mg_fclose(&file.access);
  7713. return auth;
  7714. }
  7715. #endif /* NO_FILESYSTEMS */
  7716. /* Return 1 if request is authorised, 0 otherwise. */
  7717. static int
  7718. check_authorization(struct mg_connection *conn, const char *path)
  7719. {
  7720. #if !defined(NO_FILESYSTEMS)
  7721. char fname[PATH_MAX];
  7722. struct vec uri_vec, filename_vec;
  7723. const char *list;
  7724. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7725. int authorized = 1, truncated;
  7726. if (!conn || !conn->dom_ctx) {
  7727. return 0;
  7728. }
  7729. list = conn->dom_ctx->config[PROTECT_URI];
  7730. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7731. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7732. mg_snprintf(conn,
  7733. &truncated,
  7734. fname,
  7735. sizeof(fname),
  7736. "%.*s",
  7737. (int)filename_vec.len,
  7738. filename_vec.ptr);
  7739. if (truncated
  7740. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7741. mg_cry_internal(conn,
  7742. "%s: cannot open %s: %s",
  7743. __func__,
  7744. fname,
  7745. strerror(errno));
  7746. }
  7747. break;
  7748. }
  7749. }
  7750. if (!is_file_opened(&file.access)) {
  7751. open_auth_file(conn, path, &file);
  7752. }
  7753. if (is_file_opened(&file.access)) {
  7754. authorized = authorize(conn, &file, NULL);
  7755. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7756. }
  7757. return authorized;
  7758. #else
  7759. (void)conn;
  7760. (void)path;
  7761. return 1;
  7762. #endif /* NO_FILESYSTEMS */
  7763. }
  7764. /* Internal function. Assumes conn is valid */
  7765. static void
  7766. send_authorization_request(struct mg_connection *conn, const char *realm)
  7767. {
  7768. char date[64];
  7769. time_t curtime = time(NULL);
  7770. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7771. if (!realm) {
  7772. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7773. }
  7774. mg_lock_context(conn->phys_ctx);
  7775. nonce += conn->dom_ctx->nonce_count;
  7776. ++conn->dom_ctx->nonce_count;
  7777. mg_unlock_context(conn->phys_ctx);
  7778. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7779. conn->status_code = 401;
  7780. conn->must_close = 1;
  7781. gmt_time_string(date, sizeof(date), &curtime);
  7782. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7783. send_no_cache_header(conn);
  7784. send_additional_header(conn);
  7785. mg_printf(conn,
  7786. "Date: %s\r\n"
  7787. "Connection: %s\r\n"
  7788. "Content-Length: 0\r\n"
  7789. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7790. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7791. date,
  7792. suggest_connection_header(conn),
  7793. realm,
  7794. nonce);
  7795. }
  7796. /* Interface function. Parameters are provided by the user, so do
  7797. * at least some basic checks.
  7798. */
  7799. int
  7800. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7801. const char *realm)
  7802. {
  7803. if (conn && conn->dom_ctx) {
  7804. send_authorization_request(conn, realm);
  7805. return 0;
  7806. }
  7807. return -1;
  7808. }
  7809. #if !defined(NO_FILES)
  7810. static int
  7811. is_authorized_for_put(struct mg_connection *conn)
  7812. {
  7813. if (conn) {
  7814. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7815. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7816. int ret = 0;
  7817. if (passfile != NULL
  7818. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7819. ret = authorize(conn, &file, NULL);
  7820. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7821. }
  7822. return ret;
  7823. }
  7824. return 0;
  7825. }
  7826. #endif
  7827. int
  7828. mg_modify_passwords_file(const char *fname,
  7829. const char *domain,
  7830. const char *user,
  7831. const char *pass)
  7832. {
  7833. int found, i;
  7834. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7835. FILE *fp, *fp2;
  7836. found = 0;
  7837. fp = fp2 = NULL;
  7838. /* Regard empty password as no password - remove user record. */
  7839. if ((pass != NULL) && (pass[0] == '\0')) {
  7840. pass = NULL;
  7841. }
  7842. /* Other arguments must not be empty */
  7843. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7844. return 0;
  7845. }
  7846. /* Using the given file format, user name and domain must not contain
  7847. * ':'
  7848. */
  7849. if (strchr(user, ':') != NULL) {
  7850. return 0;
  7851. }
  7852. if (strchr(domain, ':') != NULL) {
  7853. return 0;
  7854. }
  7855. /* Do not allow control characters like newline in user name and domain.
  7856. * Do not allow excessively long names either. */
  7857. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7858. if (iscntrl((unsigned char)user[i])) {
  7859. return 0;
  7860. }
  7861. }
  7862. if (user[i]) {
  7863. return 0;
  7864. }
  7865. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7866. if (iscntrl((unsigned char)domain[i])) {
  7867. return 0;
  7868. }
  7869. }
  7870. if (domain[i]) {
  7871. return 0;
  7872. }
  7873. /* The maximum length of the path to the password file is limited */
  7874. if ((strlen(fname) + 4) >= PATH_MAX) {
  7875. return 0;
  7876. }
  7877. /* Create a temporary file name. Length has been checked before. */
  7878. strcpy(tmp, fname);
  7879. strcat(tmp, ".tmp");
  7880. /* Create the file if does not exist */
  7881. /* Use of fopen here is OK, since fname is only ASCII */
  7882. if ((fp = fopen(fname, "a+")) != NULL) {
  7883. (void)fclose(fp);
  7884. }
  7885. /* Open the given file and temporary file */
  7886. if ((fp = fopen(fname, "r")) == NULL) {
  7887. return 0;
  7888. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7889. fclose(fp);
  7890. return 0;
  7891. }
  7892. /* Copy the stuff to temporary file */
  7893. while (fgets(line, sizeof(line), fp) != NULL) {
  7894. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7895. continue;
  7896. }
  7897. u[255] = 0;
  7898. d[255] = 0;
  7899. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7900. found++;
  7901. if (pass != NULL) {
  7902. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7903. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7904. }
  7905. } else {
  7906. fprintf(fp2, "%s", line);
  7907. }
  7908. }
  7909. /* If new user, just add it */
  7910. if (!found && (pass != NULL)) {
  7911. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7912. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7913. }
  7914. /* Close files */
  7915. fclose(fp);
  7916. fclose(fp2);
  7917. /* Put the temp file in place of real file */
  7918. IGNORE_UNUSED_RESULT(remove(fname));
  7919. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7920. return 1;
  7921. }
  7922. static int
  7923. is_valid_port(unsigned long port)
  7924. {
  7925. return (port <= 0xffff);
  7926. }
  7927. static int
  7928. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7929. {
  7930. struct addrinfo hints, *res, *ressave;
  7931. int func_ret = 0;
  7932. int gai_ret;
  7933. memset(&hints, 0, sizeof(struct addrinfo));
  7934. hints.ai_family = af;
  7935. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7936. if (gai_ret != 0) {
  7937. /* gai_strerror could be used to convert gai_ret to a string */
  7938. /* POSIX return values: see
  7939. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7940. */
  7941. /* Windows return values: see
  7942. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7943. */
  7944. return 0;
  7945. }
  7946. ressave = res;
  7947. while (res) {
  7948. if (dstlen >= (size_t)res->ai_addrlen) {
  7949. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7950. func_ret = 1;
  7951. }
  7952. res = res->ai_next;
  7953. }
  7954. freeaddrinfo(ressave);
  7955. return func_ret;
  7956. }
  7957. static int
  7958. connect_socket(struct mg_context *ctx /* may be NULL */,
  7959. const char *host,
  7960. int port,
  7961. int use_ssl,
  7962. char *ebuf,
  7963. size_t ebuf_len,
  7964. SOCKET *sock /* output: socket, must not be NULL */,
  7965. union usa *sa /* output: socket address, must not be NULL */
  7966. )
  7967. {
  7968. int ip_ver = 0;
  7969. int conn_ret = -1;
  7970. int sockerr = 0;
  7971. *sock = INVALID_SOCKET;
  7972. memset(sa, 0, sizeof(*sa));
  7973. if (ebuf_len > 0) {
  7974. *ebuf = 0;
  7975. }
  7976. if (host == NULL) {
  7977. mg_snprintf(NULL,
  7978. NULL, /* No truncation check for ebuf */
  7979. ebuf,
  7980. ebuf_len,
  7981. "%s",
  7982. "NULL host");
  7983. return 0;
  7984. }
  7985. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7986. mg_snprintf(NULL,
  7987. NULL, /* No truncation check for ebuf */
  7988. ebuf,
  7989. ebuf_len,
  7990. "%s",
  7991. "invalid port");
  7992. return 0;
  7993. }
  7994. #if !defined(NO_SSL)
  7995. #if !defined(NO_SSL_DL)
  7996. #if defined(OPENSSL_API_1_1)
  7997. if (use_ssl && (TLS_client_method == NULL)) {
  7998. mg_snprintf(NULL,
  7999. NULL, /* No truncation check for ebuf */
  8000. ebuf,
  8001. ebuf_len,
  8002. "%s",
  8003. "SSL is not initialized");
  8004. return 0;
  8005. }
  8006. #else
  8007. if (use_ssl && (SSLv23_client_method == NULL)) {
  8008. mg_snprintf(NULL,
  8009. NULL, /* No truncation check for ebuf */
  8010. ebuf,
  8011. ebuf_len,
  8012. "%s",
  8013. "SSL is not initialized");
  8014. return 0;
  8015. }
  8016. #endif /* OPENSSL_API_1_1 */
  8017. #else
  8018. (void)use_ssl;
  8019. #endif /* NO_SSL_DL */
  8020. #else
  8021. (void)use_ssl;
  8022. #endif /* !defined(NO_SSL) */
  8023. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  8024. sa->sin.sin_family = AF_INET;
  8025. sa->sin.sin_port = htons((uint16_t)port);
  8026. ip_ver = 4;
  8027. #if defined(USE_IPV6)
  8028. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  8029. sa->sin6.sin6_family = AF_INET6;
  8030. sa->sin6.sin6_port = htons((uint16_t)port);
  8031. ip_ver = 6;
  8032. } else if (host[0] == '[') {
  8033. /* While getaddrinfo on Windows will work with [::1],
  8034. * getaddrinfo on Linux only works with ::1 (without []). */
  8035. size_t l = strlen(host + 1);
  8036. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8037. if (h) {
  8038. h[l - 1] = 0;
  8039. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  8040. sa->sin6.sin6_family = AF_INET6;
  8041. sa->sin6.sin6_port = htons((uint16_t)port);
  8042. ip_ver = 6;
  8043. }
  8044. mg_free(h);
  8045. }
  8046. #endif
  8047. }
  8048. if (ip_ver == 0) {
  8049. mg_snprintf(NULL,
  8050. NULL, /* No truncation check for ebuf */
  8051. ebuf,
  8052. ebuf_len,
  8053. "%s",
  8054. "host not found");
  8055. return 0;
  8056. }
  8057. if (ip_ver == 4) {
  8058. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8059. }
  8060. #if defined(USE_IPV6)
  8061. else if (ip_ver == 6) {
  8062. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8063. }
  8064. #endif
  8065. if (*sock == INVALID_SOCKET) {
  8066. mg_snprintf(NULL,
  8067. NULL, /* No truncation check for ebuf */
  8068. ebuf,
  8069. ebuf_len,
  8070. "socket(): %s",
  8071. strerror(ERRNO));
  8072. return 0;
  8073. }
  8074. if (0 != set_non_blocking_mode(*sock)) {
  8075. mg_snprintf(NULL,
  8076. NULL, /* No truncation check for ebuf */
  8077. ebuf,
  8078. ebuf_len,
  8079. "Cannot set socket to non-blocking: %s",
  8080. strerror(ERRNO));
  8081. closesocket(*sock);
  8082. *sock = INVALID_SOCKET;
  8083. return 0;
  8084. }
  8085. set_close_on_exec(*sock, NULL, ctx);
  8086. if (ip_ver == 4) {
  8087. /* connected with IPv4 */
  8088. conn_ret = connect(*sock,
  8089. (struct sockaddr *)((void *)&sa->sin),
  8090. sizeof(sa->sin));
  8091. }
  8092. #if defined(USE_IPV6)
  8093. else if (ip_ver == 6) {
  8094. /* connected with IPv6 */
  8095. conn_ret = connect(*sock,
  8096. (struct sockaddr *)((void *)&sa->sin6),
  8097. sizeof(sa->sin6));
  8098. }
  8099. #endif
  8100. if (conn_ret != 0) {
  8101. sockerr = ERRNO;
  8102. }
  8103. #if defined(_WIN32)
  8104. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8105. #else
  8106. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8107. #endif
  8108. /* Data for getsockopt */
  8109. void *psockerr = &sockerr;
  8110. int ret;
  8111. #if defined(_WIN32)
  8112. int len = (int)sizeof(sockerr);
  8113. #else
  8114. socklen_t len = (socklen_t)sizeof(sockerr);
  8115. #endif
  8116. /* Data for poll */
  8117. struct mg_pollfd pfd[1];
  8118. int pollres;
  8119. int ms_wait = 10000; /* 10 second timeout */
  8120. stop_flag_t nonstop;
  8121. STOP_FLAG_ASSIGN(&nonstop, 0);
  8122. /* For a non-blocking socket, the connect sequence is:
  8123. * 1) call connect (will not block)
  8124. * 2) wait until the socket is ready for writing (select or poll)
  8125. * 3) check connection state with getsockopt
  8126. */
  8127. pfd[0].fd = *sock;
  8128. pfd[0].events = POLLOUT;
  8129. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8130. if (pollres != 1) {
  8131. /* Not connected */
  8132. mg_snprintf(NULL,
  8133. NULL, /* No truncation check for ebuf */
  8134. ebuf,
  8135. ebuf_len,
  8136. "connect(%s:%d): timeout",
  8137. host,
  8138. port);
  8139. closesocket(*sock);
  8140. *sock = INVALID_SOCKET;
  8141. return 0;
  8142. }
  8143. #if defined(_WIN32)
  8144. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8145. #else
  8146. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8147. #endif
  8148. if ((ret == 0) && (sockerr == 0)) {
  8149. conn_ret = 0;
  8150. }
  8151. }
  8152. if (conn_ret != 0) {
  8153. /* Not connected */
  8154. mg_snprintf(NULL,
  8155. NULL, /* No truncation check for ebuf */
  8156. ebuf,
  8157. ebuf_len,
  8158. "connect(%s:%d): error %s",
  8159. host,
  8160. port,
  8161. strerror(sockerr));
  8162. closesocket(*sock);
  8163. *sock = INVALID_SOCKET;
  8164. return 0;
  8165. }
  8166. return 1;
  8167. }
  8168. int
  8169. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8170. {
  8171. static const char *dont_escape = "._-$,;~()";
  8172. static const char *hex = "0123456789abcdef";
  8173. char *pos = dst;
  8174. const char *end = dst + dst_len - 1;
  8175. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8176. if (isalnum((unsigned char)*src)
  8177. || (strchr(dont_escape, *src) != NULL)) {
  8178. *pos = *src;
  8179. } else if (pos + 2 < end) {
  8180. pos[0] = '%';
  8181. pos[1] = hex[(unsigned char)*src >> 4];
  8182. pos[2] = hex[(unsigned char)*src & 0xf];
  8183. pos += 2;
  8184. } else {
  8185. break;
  8186. }
  8187. }
  8188. *pos = '\0';
  8189. return (*src == '\0') ? (int)(pos - dst) : -1;
  8190. }
  8191. /* Return 0 on success, non-zero if an error occurs. */
  8192. static int
  8193. print_dir_entry(struct de *de)
  8194. {
  8195. size_t namesize, escsize, i;
  8196. char *href, *esc, *p;
  8197. char size[64], mod[64];
  8198. #if defined(REENTRANT_TIME)
  8199. struct tm _tm;
  8200. struct tm *tm = &_tm;
  8201. #else
  8202. struct tm *tm;
  8203. #endif
  8204. /* Estimate worst case size for encoding and escaping */
  8205. namesize = strlen(de->file_name) + 1;
  8206. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8207. href = (char *)mg_malloc(namesize * 3 + escsize);
  8208. if (href == NULL) {
  8209. return -1;
  8210. }
  8211. mg_url_encode(de->file_name, href, namesize * 3);
  8212. esc = NULL;
  8213. if (escsize > 0) {
  8214. /* HTML escaping needed */
  8215. esc = href + namesize * 3;
  8216. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8217. mg_strlcpy(p, de->file_name + i, 2);
  8218. if (*p == '&') {
  8219. strcpy(p, "&amp;");
  8220. } else if (*p == '<') {
  8221. strcpy(p, "&lt;");
  8222. } else if (*p == '>') {
  8223. strcpy(p, "&gt;");
  8224. }
  8225. }
  8226. }
  8227. if (de->file.is_directory) {
  8228. mg_snprintf(de->conn,
  8229. NULL, /* Buffer is big enough */
  8230. size,
  8231. sizeof(size),
  8232. "%s",
  8233. "[DIRECTORY]");
  8234. } else {
  8235. /* We use (signed) cast below because MSVC 6 compiler cannot
  8236. * convert unsigned __int64 to double. Sigh. */
  8237. if (de->file.size < 1024) {
  8238. mg_snprintf(de->conn,
  8239. NULL, /* Buffer is big enough */
  8240. size,
  8241. sizeof(size),
  8242. "%d",
  8243. (int)de->file.size);
  8244. } else if (de->file.size < 0x100000) {
  8245. mg_snprintf(de->conn,
  8246. NULL, /* Buffer is big enough */
  8247. size,
  8248. sizeof(size),
  8249. "%.1fk",
  8250. (double)de->file.size / 1024.0);
  8251. } else if (de->file.size < 0x40000000) {
  8252. mg_snprintf(de->conn,
  8253. NULL, /* Buffer is big enough */
  8254. size,
  8255. sizeof(size),
  8256. "%.1fM",
  8257. (double)de->file.size / 1048576);
  8258. } else {
  8259. mg_snprintf(de->conn,
  8260. NULL, /* Buffer is big enough */
  8261. size,
  8262. sizeof(size),
  8263. "%.1fG",
  8264. (double)de->file.size / 1073741824);
  8265. }
  8266. }
  8267. /* Note: mg_snprintf will not cause a buffer overflow above.
  8268. * So, string truncation checks are not required here. */
  8269. #if defined(REENTRANT_TIME)
  8270. localtime_r(&de->file.last_modified, tm);
  8271. #else
  8272. tm = localtime(&de->file.last_modified);
  8273. #endif
  8274. if (tm != NULL) {
  8275. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8276. } else {
  8277. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8278. mod[sizeof(mod) - 1] = '\0';
  8279. }
  8280. mg_printf(de->conn,
  8281. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8282. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8283. href,
  8284. de->file.is_directory ? "/" : "",
  8285. esc ? esc : de->file_name,
  8286. de->file.is_directory ? "/" : "",
  8287. mod,
  8288. size);
  8289. mg_free(href);
  8290. return 0;
  8291. }
  8292. /* This function is called from send_directory() and used for
  8293. * sorting directory entries by size, or name, or modification time.
  8294. * On windows, __cdecl specification is needed in case if project is built
  8295. * with __stdcall convention. qsort always requires __cdels callback. */
  8296. static int WINCDECL
  8297. compare_dir_entries(const void *p1, const void *p2)
  8298. {
  8299. if (p1 && p2) {
  8300. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8301. const char *query_string = a->conn->request_info.query_string;
  8302. int cmp_result = 0;
  8303. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8304. query_string = "n";
  8305. }
  8306. if (a->file.is_directory && !b->file.is_directory) {
  8307. return -1; /* Always put directories on top */
  8308. } else if (!a->file.is_directory && b->file.is_directory) {
  8309. return 1; /* Always put directories on top */
  8310. } else if (*query_string == 'n') {
  8311. cmp_result = strcmp(a->file_name, b->file_name);
  8312. } else if (*query_string == 's') {
  8313. cmp_result = (a->file.size == b->file.size)
  8314. ? 0
  8315. : ((a->file.size > b->file.size) ? 1 : -1);
  8316. } else if (*query_string == 'd') {
  8317. cmp_result =
  8318. (a->file.last_modified == b->file.last_modified)
  8319. ? 0
  8320. : ((a->file.last_modified > b->file.last_modified) ? 1
  8321. : -1);
  8322. }
  8323. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8324. }
  8325. return 0;
  8326. }
  8327. static int
  8328. must_hide_file(struct mg_connection *conn, const char *path)
  8329. {
  8330. if (conn && conn->dom_ctx) {
  8331. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8332. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8333. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8334. || ((pattern != NULL)
  8335. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8336. }
  8337. return 0;
  8338. }
  8339. #if !defined(NO_FILESYSTEMS)
  8340. static int
  8341. scan_directory(struct mg_connection *conn,
  8342. const char *dir,
  8343. void *data,
  8344. int (*cb)(struct de *, void *))
  8345. {
  8346. char path[PATH_MAX];
  8347. struct dirent *dp;
  8348. DIR *dirp;
  8349. struct de de;
  8350. int truncated;
  8351. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8352. return 0;
  8353. } else {
  8354. de.conn = conn;
  8355. while ((dp = mg_readdir(dirp)) != NULL) {
  8356. /* Do not show current dir and hidden files */
  8357. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8358. || must_hide_file(conn, dp->d_name)) {
  8359. continue;
  8360. }
  8361. mg_snprintf(
  8362. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8363. /* If we don't memset stat structure to zero, mtime will have
  8364. * garbage and strftime() will segfault later on in
  8365. * print_dir_entry(). memset is required only if mg_stat()
  8366. * fails. For more details, see
  8367. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8368. memset(&de.file, 0, sizeof(de.file));
  8369. if (truncated) {
  8370. /* If the path is not complete, skip processing. */
  8371. continue;
  8372. }
  8373. if (!mg_stat(conn, path, &de.file)) {
  8374. mg_cry_internal(conn,
  8375. "%s: mg_stat(%s) failed: %s",
  8376. __func__,
  8377. path,
  8378. strerror(ERRNO));
  8379. }
  8380. de.file_name = dp->d_name;
  8381. cb(&de, data);
  8382. }
  8383. (void)mg_closedir(dirp);
  8384. }
  8385. return 1;
  8386. }
  8387. #endif /* NO_FILESYSTEMS */
  8388. #if !defined(NO_FILES)
  8389. static int
  8390. remove_directory(struct mg_connection *conn, const char *dir)
  8391. {
  8392. char path[PATH_MAX];
  8393. struct dirent *dp;
  8394. DIR *dirp;
  8395. struct de de;
  8396. int truncated;
  8397. int ok = 1;
  8398. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8399. return 0;
  8400. } else {
  8401. de.conn = conn;
  8402. while ((dp = mg_readdir(dirp)) != NULL) {
  8403. /* Do not show current dir (but show hidden files as they will
  8404. * also be removed) */
  8405. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8406. continue;
  8407. }
  8408. mg_snprintf(
  8409. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8410. /* If we don't memset stat structure to zero, mtime will have
  8411. * garbage and strftime() will segfault later on in
  8412. * print_dir_entry(). memset is required only if mg_stat()
  8413. * fails. For more details, see
  8414. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8415. memset(&de.file, 0, sizeof(de.file));
  8416. if (truncated) {
  8417. /* Do not delete anything shorter */
  8418. ok = 0;
  8419. continue;
  8420. }
  8421. if (!mg_stat(conn, path, &de.file)) {
  8422. mg_cry_internal(conn,
  8423. "%s: mg_stat(%s) failed: %s",
  8424. __func__,
  8425. path,
  8426. strerror(ERRNO));
  8427. ok = 0;
  8428. }
  8429. if (de.file.is_directory) {
  8430. if (remove_directory(conn, path) == 0) {
  8431. ok = 0;
  8432. }
  8433. } else {
  8434. /* This will fail file is the file is in memory */
  8435. if (mg_remove(conn, path) == 0) {
  8436. ok = 0;
  8437. }
  8438. }
  8439. }
  8440. (void)mg_closedir(dirp);
  8441. IGNORE_UNUSED_RESULT(rmdir(dir));
  8442. }
  8443. return ok;
  8444. }
  8445. #endif
  8446. struct dir_scan_data {
  8447. struct de *entries;
  8448. unsigned int num_entries;
  8449. unsigned int arr_size;
  8450. };
  8451. /* Behaves like realloc(), but frees original pointer on failure */
  8452. static void *
  8453. realloc2(void *ptr, size_t size)
  8454. {
  8455. void *new_ptr = mg_realloc(ptr, size);
  8456. if ((new_ptr == NULL) && (size > 0)) {
  8457. mg_free(ptr);
  8458. }
  8459. return new_ptr;
  8460. }
  8461. #if !defined(NO_FILESYSTEMS)
  8462. static int
  8463. dir_scan_callback(struct de *de, void *data)
  8464. {
  8465. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8466. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8467. dsd->arr_size *= 2;
  8468. dsd->entries =
  8469. (struct de *)realloc2(dsd->entries,
  8470. dsd->arr_size * sizeof(dsd->entries[0]));
  8471. }
  8472. if (dsd->entries == NULL) {
  8473. /* TODO(lsm, low): propagate an error to the caller */
  8474. dsd->num_entries = 0;
  8475. } else {
  8476. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8477. dsd->entries[dsd->num_entries].file = de->file;
  8478. dsd->entries[dsd->num_entries].conn = de->conn;
  8479. dsd->num_entries++;
  8480. }
  8481. return 0;
  8482. }
  8483. static void
  8484. handle_directory_request(struct mg_connection *conn, const char *dir)
  8485. {
  8486. unsigned int i;
  8487. int sort_direction;
  8488. struct dir_scan_data data = {NULL, 0, 128};
  8489. char date[64], *esc, *p;
  8490. const char *title;
  8491. time_t curtime = time(NULL);
  8492. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8493. mg_send_http_error(conn,
  8494. 500,
  8495. "Error: Cannot open directory\nopendir(%s): %s",
  8496. dir,
  8497. strerror(ERRNO));
  8498. return;
  8499. }
  8500. gmt_time_string(date, sizeof(date), &curtime);
  8501. if (!conn) {
  8502. return;
  8503. }
  8504. esc = NULL;
  8505. title = conn->request_info.local_uri;
  8506. if (title[strcspn(title, "&<>")]) {
  8507. /* HTML escaping needed */
  8508. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8509. if (esc) {
  8510. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8511. mg_strlcpy(p, title + i, 2);
  8512. if (*p == '&') {
  8513. strcpy(p, "&amp;");
  8514. } else if (*p == '<') {
  8515. strcpy(p, "&lt;");
  8516. } else if (*p == '>') {
  8517. strcpy(p, "&gt;");
  8518. }
  8519. }
  8520. } else {
  8521. title = "";
  8522. }
  8523. }
  8524. sort_direction = ((conn->request_info.query_string != NULL)
  8525. && (conn->request_info.query_string[0] != '\0')
  8526. && (conn->request_info.query_string[1] == 'd'))
  8527. ? 'a'
  8528. : 'd';
  8529. conn->must_close = 1;
  8530. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8531. send_static_cache_header(conn);
  8532. send_additional_header(conn);
  8533. mg_printf(conn,
  8534. "Date: %s\r\n"
  8535. "Connection: close\r\n"
  8536. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8537. date);
  8538. mg_printf(conn,
  8539. "<html><head><title>Index of %s</title>"
  8540. "<style>th {text-align: left;}</style></head>"
  8541. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8542. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8543. "<th><a href=\"?d%c\">Modified</a></th>"
  8544. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8545. "<tr><td colspan=\"3\"><hr></td></tr>",
  8546. esc ? esc : title,
  8547. esc ? esc : title,
  8548. sort_direction,
  8549. sort_direction,
  8550. sort_direction);
  8551. mg_free(esc);
  8552. /* Print first entry - link to a parent directory */
  8553. mg_printf(conn,
  8554. "<tr><td><a href=\"%s\">%s</a></td>"
  8555. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8556. "..",
  8557. "Parent directory",
  8558. "-",
  8559. "-");
  8560. /* Sort and print directory entries */
  8561. if (data.entries != NULL) {
  8562. qsort(data.entries,
  8563. (size_t)data.num_entries,
  8564. sizeof(data.entries[0]),
  8565. compare_dir_entries);
  8566. for (i = 0; i < data.num_entries; i++) {
  8567. print_dir_entry(&data.entries[i]);
  8568. mg_free(data.entries[i].file_name);
  8569. }
  8570. mg_free(data.entries);
  8571. }
  8572. mg_printf(conn, "%s", "</table></pre></body></html>");
  8573. conn->status_code = 200;
  8574. }
  8575. #endif /* NO_FILESYSTEMS */
  8576. /* Send len bytes from the opened file to the client. */
  8577. static void
  8578. send_file_data(struct mg_connection *conn,
  8579. struct mg_file *filep,
  8580. int64_t offset,
  8581. int64_t len)
  8582. {
  8583. char buf[MG_BUF_LEN];
  8584. int to_read, num_read, num_written;
  8585. int64_t size;
  8586. if (!filep || !conn) {
  8587. return;
  8588. }
  8589. /* Sanity check the offset */
  8590. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8591. : (int64_t)(filep->stat.size);
  8592. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8593. #if defined(MG_USE_OPEN_FILE)
  8594. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8595. /* file stored in memory */
  8596. if (len > size - offset) {
  8597. len = size - offset;
  8598. }
  8599. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8600. } else /* else block below */
  8601. #endif
  8602. if (len > 0 && filep->access.fp != NULL) {
  8603. /* file stored on disk */
  8604. #if defined(__linux__)
  8605. /* sendfile is only available for Linux */
  8606. if ((conn->ssl == 0) && (conn->throttle == 0)
  8607. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8608. "yes"))) {
  8609. off_t sf_offs = (off_t)offset;
  8610. ssize_t sf_sent;
  8611. int sf_file = fileno(filep->access.fp);
  8612. int loop_cnt = 0;
  8613. do {
  8614. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8615. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8616. size_t sf_tosend =
  8617. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8618. sf_sent =
  8619. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8620. if (sf_sent > 0) {
  8621. len -= sf_sent;
  8622. offset += sf_sent;
  8623. } else if (loop_cnt == 0) {
  8624. /* This file can not be sent using sendfile.
  8625. * This might be the case for pseudo-files in the
  8626. * /sys/ and /proc/ file system.
  8627. * Use the regular user mode copy code instead. */
  8628. break;
  8629. } else if (sf_sent == 0) {
  8630. /* No error, but 0 bytes sent. May be EOF? */
  8631. return;
  8632. }
  8633. loop_cnt++;
  8634. } while ((len > 0) && (sf_sent >= 0));
  8635. if (sf_sent > 0) {
  8636. return; /* OK */
  8637. }
  8638. /* sf_sent<0 means error, thus fall back to the classic way */
  8639. /* This is always the case, if sf_file is not a "normal" file,
  8640. * e.g., for sending data from the output of a CGI process. */
  8641. offset = (int64_t)sf_offs;
  8642. }
  8643. #endif
  8644. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8645. mg_cry_internal(conn,
  8646. "%s: fseeko() failed: %s",
  8647. __func__,
  8648. strerror(ERRNO));
  8649. mg_send_http_error(
  8650. conn,
  8651. 500,
  8652. "%s",
  8653. "Error: Unable to access file at requested position.");
  8654. } else {
  8655. while (len > 0) {
  8656. /* Calculate how much to read from the file in the buffer */
  8657. to_read = sizeof(buf);
  8658. if ((int64_t)to_read > len) {
  8659. to_read = (int)len;
  8660. }
  8661. /* Read from file, exit the loop on error */
  8662. if ((num_read =
  8663. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8664. <= 0) {
  8665. break;
  8666. }
  8667. /* Send read bytes to the client, exit the loop on error */
  8668. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8669. != num_read) {
  8670. break;
  8671. }
  8672. /* Both read and were successful, adjust counters */
  8673. len -= num_written;
  8674. }
  8675. }
  8676. }
  8677. }
  8678. static int
  8679. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8680. {
  8681. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8682. }
  8683. static void
  8684. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8685. {
  8686. if ((filestat != NULL) && (buf != NULL)) {
  8687. mg_snprintf(NULL,
  8688. NULL, /* All calls to construct_etag use 64 byte buffer */
  8689. buf,
  8690. buf_len,
  8691. "\"%lx.%" INT64_FMT "\"",
  8692. (unsigned long)filestat->last_modified,
  8693. filestat->size);
  8694. }
  8695. }
  8696. static void
  8697. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8698. {
  8699. if (filep != NULL && filep->fp != NULL) {
  8700. #if defined(_WIN32)
  8701. (void)conn; /* Unused. */
  8702. #else
  8703. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8704. mg_cry_internal(conn,
  8705. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8706. __func__,
  8707. strerror(ERRNO));
  8708. }
  8709. #endif
  8710. }
  8711. }
  8712. #if defined(USE_ZLIB)
  8713. #include "mod_zlib.inl"
  8714. #endif
  8715. #if !defined(NO_FILESYSTEMS)
  8716. static void
  8717. handle_static_file_request(struct mg_connection *conn,
  8718. const char *path,
  8719. struct mg_file *filep,
  8720. const char *mime_type,
  8721. const char *additional_headers)
  8722. {
  8723. char date[64], lm[64], etag[64];
  8724. char range[128]; /* large enough, so there will be no overflow */
  8725. const char *msg = "OK";
  8726. const char *range_hdr;
  8727. time_t curtime = time(NULL);
  8728. int64_t cl, r1, r2;
  8729. struct vec mime_vec;
  8730. int n, truncated;
  8731. char gz_path[PATH_MAX];
  8732. const char *encoding = "";
  8733. const char *origin_hdr;
  8734. const char *cors_orig_cfg;
  8735. const char *cors1, *cors2, *cors3;
  8736. int is_head_request;
  8737. #if defined(USE_ZLIB)
  8738. /* Compression is allowed, unless there is a reason not to use
  8739. * compression. If the file is already compressed, too small or a
  8740. * "range" request was made, on the fly compression is not possible. */
  8741. int allow_on_the_fly_compression = 1;
  8742. #endif
  8743. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8744. return;
  8745. }
  8746. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8747. if (mime_type == NULL) {
  8748. get_mime_type(conn, path, &mime_vec);
  8749. } else {
  8750. mime_vec.ptr = mime_type;
  8751. mime_vec.len = strlen(mime_type);
  8752. }
  8753. if (filep->stat.size > INT64_MAX) {
  8754. mg_send_http_error(conn,
  8755. 500,
  8756. "Error: File size is too large to send\n%" INT64_FMT,
  8757. filep->stat.size);
  8758. return;
  8759. }
  8760. cl = (int64_t)filep->stat.size;
  8761. conn->status_code = 200;
  8762. range[0] = '\0';
  8763. #if defined(USE_ZLIB)
  8764. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8765. * it's important to rewrite the filename after resolving
  8766. * the mime type from it, to preserve the actual file's type */
  8767. if (!conn->accept_gzip) {
  8768. allow_on_the_fly_compression = 0;
  8769. }
  8770. #endif
  8771. /* Check if there is a range header */
  8772. range_hdr = mg_get_header(conn, "Range");
  8773. /* For gzipped files, add *.gz */
  8774. if (filep->stat.is_gzipped) {
  8775. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8776. if (truncated) {
  8777. mg_send_http_error(conn,
  8778. 500,
  8779. "Error: Path of zipped file too long (%s)",
  8780. path);
  8781. return;
  8782. }
  8783. path = gz_path;
  8784. encoding = "Content-Encoding: gzip\r\n";
  8785. #if defined(USE_ZLIB)
  8786. /* File is already compressed. No "on the fly" compression. */
  8787. allow_on_the_fly_compression = 0;
  8788. #endif
  8789. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8790. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8791. struct mg_file_stat file_stat;
  8792. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8793. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8794. && !file_stat.is_directory) {
  8795. file_stat.is_gzipped = 1;
  8796. filep->stat = file_stat;
  8797. cl = (int64_t)filep->stat.size;
  8798. path = gz_path;
  8799. encoding = "Content-Encoding: gzip\r\n";
  8800. #if defined(USE_ZLIB)
  8801. /* File is already compressed. No "on the fly" compression. */
  8802. allow_on_the_fly_compression = 0;
  8803. #endif
  8804. }
  8805. }
  8806. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8807. mg_send_http_error(conn,
  8808. 500,
  8809. "Error: Cannot open file\nfopen(%s): %s",
  8810. path,
  8811. strerror(ERRNO));
  8812. return;
  8813. }
  8814. fclose_on_exec(&filep->access, conn);
  8815. /* If "Range" request was made: parse header, send only selected part
  8816. * of the file. */
  8817. r1 = r2 = 0;
  8818. if ((range_hdr != NULL)
  8819. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8820. && (r2 >= 0)) {
  8821. /* actually, range requests don't play well with a pre-gzipped
  8822. * file (since the range is specified in the uncompressed space) */
  8823. if (filep->stat.is_gzipped) {
  8824. mg_send_http_error(
  8825. conn,
  8826. 416, /* 416 = Range Not Satisfiable */
  8827. "%s",
  8828. "Error: Range requests in gzipped files are not supported");
  8829. (void)mg_fclose(
  8830. &filep->access); /* ignore error on read only file */
  8831. return;
  8832. }
  8833. conn->status_code = 206;
  8834. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8835. mg_snprintf(conn,
  8836. NULL, /* range buffer is big enough */
  8837. range,
  8838. sizeof(range),
  8839. "Content-Range: bytes "
  8840. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8841. r1,
  8842. r1 + cl - 1,
  8843. filep->stat.size);
  8844. msg = "Partial Content";
  8845. #if defined(USE_ZLIB)
  8846. /* Do not compress ranges. */
  8847. allow_on_the_fly_compression = 0;
  8848. #endif
  8849. }
  8850. /* Do not compress small files. Small files do not benefit from file
  8851. * compression, but there is still some overhead. */
  8852. #if defined(USE_ZLIB)
  8853. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8854. /* File is below the size limit. */
  8855. allow_on_the_fly_compression = 0;
  8856. }
  8857. #endif
  8858. /* Standard CORS header */
  8859. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8860. origin_hdr = mg_get_header(conn, "Origin");
  8861. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8862. /* Cross-origin resource sharing (CORS), see
  8863. * http://www.html5rocks.com/en/tutorials/cors/,
  8864. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8865. * -
  8866. * preflight is not supported for files. */
  8867. cors1 = "Access-Control-Allow-Origin: ";
  8868. cors2 = cors_orig_cfg;
  8869. cors3 = "\r\n";
  8870. } else {
  8871. cors1 = cors2 = cors3 = "";
  8872. }
  8873. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8874. * according to
  8875. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8876. gmt_time_string(date, sizeof(date), &curtime);
  8877. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8878. construct_etag(etag, sizeof(etag), &filep->stat);
  8879. /* Send header */
  8880. (void)mg_printf(conn,
  8881. "HTTP/1.1 %d %s\r\n"
  8882. "%s%s%s" /* CORS */
  8883. "Date: %s\r\n"
  8884. "Last-Modified: %s\r\n"
  8885. "Etag: %s\r\n"
  8886. "Content-Type: %.*s\r\n"
  8887. "Connection: %s\r\n",
  8888. conn->status_code,
  8889. msg,
  8890. cors1,
  8891. cors2,
  8892. cors3,
  8893. date,
  8894. lm,
  8895. etag,
  8896. (int)mime_vec.len,
  8897. mime_vec.ptr,
  8898. suggest_connection_header(conn));
  8899. send_static_cache_header(conn);
  8900. send_additional_header(conn);
  8901. #if defined(USE_ZLIB)
  8902. /* On the fly compression allowed */
  8903. if (allow_on_the_fly_compression) {
  8904. /* For on the fly compression, we don't know the content size in
  8905. * advance, so we have to use chunked encoding */
  8906. (void)mg_printf(conn,
  8907. "Content-Encoding: gzip\r\n"
  8908. "Transfer-Encoding: chunked\r\n");
  8909. } else
  8910. #endif
  8911. {
  8912. /* Without on-the-fly compression, we know the content-length
  8913. * and we can use ranges (with on-the-fly compression we cannot).
  8914. * So we send these response headers only in this case. */
  8915. (void)mg_printf(conn,
  8916. "Content-Length: %" INT64_FMT "\r\n"
  8917. "Accept-Ranges: bytes\r\n"
  8918. "%s" /* range */
  8919. "%s" /* encoding */,
  8920. cl,
  8921. range,
  8922. encoding);
  8923. }
  8924. /* The previous code must not add any header starting with X- to make
  8925. * sure no one of the additional_headers is included twice */
  8926. if (additional_headers != NULL) {
  8927. (void)mg_printf(conn,
  8928. "%.*s\r\n\r\n",
  8929. (int)strlen(additional_headers),
  8930. additional_headers);
  8931. } else {
  8932. (void)mg_printf(conn, "\r\n");
  8933. }
  8934. if (!is_head_request) {
  8935. #if defined(USE_ZLIB)
  8936. if (allow_on_the_fly_compression) {
  8937. /* Compress and send */
  8938. send_compressed_data(conn, filep);
  8939. } else
  8940. #endif
  8941. {
  8942. /* Send file directly */
  8943. send_file_data(conn, filep, r1, cl);
  8944. }
  8945. }
  8946. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8947. }
  8948. int
  8949. mg_send_file_body(struct mg_connection *conn, const char *path)
  8950. {
  8951. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8952. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8953. return -1;
  8954. }
  8955. fclose_on_exec(&file.access, conn);
  8956. send_file_data(conn, &file, 0, INT64_MAX);
  8957. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8958. return 0; /* >= 0 for OK */
  8959. }
  8960. #endif /* NO_FILESYSTEMS */
  8961. #if !defined(NO_CACHING)
  8962. /* Return True if we should reply 304 Not Modified. */
  8963. static int
  8964. is_not_modified(const struct mg_connection *conn,
  8965. const struct mg_file_stat *filestat)
  8966. {
  8967. char etag[64];
  8968. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8969. const char *inm = mg_get_header(conn, "If-None-Match");
  8970. construct_etag(etag, sizeof(etag), filestat);
  8971. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8972. || ((ims != NULL)
  8973. && (filestat->last_modified <= parse_date_string(ims)));
  8974. }
  8975. static void
  8976. handle_not_modified_static_file_request(struct mg_connection *conn,
  8977. struct mg_file *filep)
  8978. {
  8979. char date[64], lm[64], etag[64];
  8980. time_t curtime = time(NULL);
  8981. if ((conn == NULL) || (filep == NULL)) {
  8982. return;
  8983. }
  8984. conn->status_code = 304;
  8985. gmt_time_string(date, sizeof(date), &curtime);
  8986. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8987. construct_etag(etag, sizeof(etag), &filep->stat);
  8988. (void)mg_printf(conn,
  8989. "HTTP/1.1 %d %s\r\n"
  8990. "Date: %s\r\n",
  8991. conn->status_code,
  8992. mg_get_response_code_text(conn, conn->status_code),
  8993. date);
  8994. send_static_cache_header(conn);
  8995. send_additional_header(conn);
  8996. (void)mg_printf(conn,
  8997. "Last-Modified: %s\r\n"
  8998. "Etag: %s\r\n"
  8999. "Connection: %s\r\n"
  9000. "\r\n",
  9001. lm,
  9002. etag,
  9003. suggest_connection_header(conn));
  9004. }
  9005. #endif
  9006. #if !defined(NO_FILESYSTEMS)
  9007. void
  9008. mg_send_file(struct mg_connection *conn, const char *path)
  9009. {
  9010. mg_send_mime_file2(conn, path, NULL, NULL);
  9011. }
  9012. void
  9013. mg_send_mime_file(struct mg_connection *conn,
  9014. const char *path,
  9015. const char *mime_type)
  9016. {
  9017. mg_send_mime_file2(conn, path, mime_type, NULL);
  9018. }
  9019. void
  9020. mg_send_mime_file2(struct mg_connection *conn,
  9021. const char *path,
  9022. const char *mime_type,
  9023. const char *additional_headers)
  9024. {
  9025. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9026. if (!conn) {
  9027. /* No conn */
  9028. return;
  9029. }
  9030. if (mg_stat(conn, path, &file.stat)) {
  9031. #if !defined(NO_CACHING)
  9032. if (is_not_modified(conn, &file.stat)) {
  9033. /* Send 304 "Not Modified" - this must not send any body data */
  9034. handle_not_modified_static_file_request(conn, &file);
  9035. } else
  9036. #endif /* NO_CACHING */
  9037. if (file.stat.is_directory) {
  9038. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9039. "yes")) {
  9040. handle_directory_request(conn, path);
  9041. } else {
  9042. mg_send_http_error(conn,
  9043. 403,
  9044. "%s",
  9045. "Error: Directory listing denied");
  9046. }
  9047. } else {
  9048. handle_static_file_request(
  9049. conn, path, &file, mime_type, additional_headers);
  9050. }
  9051. } else {
  9052. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9053. }
  9054. }
  9055. /* For a given PUT path, create all intermediate subdirectories.
  9056. * Return 0 if the path itself is a directory.
  9057. * Return 1 if the path leads to a file.
  9058. * Return -1 for if the path is too long.
  9059. * Return -2 if path can not be created.
  9060. */
  9061. static int
  9062. put_dir(struct mg_connection *conn, const char *path)
  9063. {
  9064. char buf[PATH_MAX];
  9065. const char *s, *p;
  9066. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9067. size_t len;
  9068. int res = 1;
  9069. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9070. len = (size_t)(p - path);
  9071. if (len >= sizeof(buf)) {
  9072. /* path too long */
  9073. res = -1;
  9074. break;
  9075. }
  9076. memcpy(buf, path, len);
  9077. buf[len] = '\0';
  9078. /* Try to create intermediate directory */
  9079. DEBUG_TRACE("mkdir(%s)", buf);
  9080. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9081. /* path does not exixt and can not be created */
  9082. res = -2;
  9083. break;
  9084. }
  9085. /* Is path itself a directory? */
  9086. if (p[1] == '\0') {
  9087. res = 0;
  9088. }
  9089. }
  9090. return res;
  9091. }
  9092. static void
  9093. remove_bad_file(const struct mg_connection *conn, const char *path)
  9094. {
  9095. int r = mg_remove(conn, path);
  9096. if (r != 0) {
  9097. mg_cry_internal(conn,
  9098. "%s: Cannot remove invalid file %s",
  9099. __func__,
  9100. path);
  9101. }
  9102. }
  9103. long long
  9104. mg_store_body(struct mg_connection *conn, const char *path)
  9105. {
  9106. char buf[MG_BUF_LEN];
  9107. long long len = 0;
  9108. int ret, n;
  9109. struct mg_file fi;
  9110. if (conn->consumed_content != 0) {
  9111. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9112. return -11;
  9113. }
  9114. ret = put_dir(conn, path);
  9115. if (ret < 0) {
  9116. /* -1 for path too long,
  9117. * -2 for path can not be created. */
  9118. return ret;
  9119. }
  9120. if (ret != 1) {
  9121. /* Return 0 means, path itself is a directory. */
  9122. return 0;
  9123. }
  9124. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9125. return -12;
  9126. }
  9127. ret = mg_read(conn, buf, sizeof(buf));
  9128. while (ret > 0) {
  9129. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9130. if (n != ret) {
  9131. (void)mg_fclose(
  9132. &fi.access); /* File is bad and will be removed anyway. */
  9133. remove_bad_file(conn, path);
  9134. return -13;
  9135. }
  9136. len += ret;
  9137. ret = mg_read(conn, buf, sizeof(buf));
  9138. }
  9139. /* File is open for writing. If fclose fails, there was probably an
  9140. * error flushing the buffer to disk, so the file on disk might be
  9141. * broken. Delete it and return an error to the caller. */
  9142. if (mg_fclose(&fi.access) != 0) {
  9143. remove_bad_file(conn, path);
  9144. return -14;
  9145. }
  9146. return len;
  9147. }
  9148. #endif /* NO_FILESYSTEMS */
  9149. /* Parse a buffer:
  9150. * Forward the string pointer till the end of a word, then
  9151. * terminate it and forward till the begin of the next word.
  9152. */
  9153. static int
  9154. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9155. {
  9156. /* Forward until a space is found - use isgraph here */
  9157. /* See http://www.cplusplus.com/reference/cctype/ */
  9158. while (isgraph((unsigned char)**ppw)) {
  9159. (*ppw)++;
  9160. }
  9161. /* Check end of word */
  9162. if (eol) {
  9163. /* must be a end of line */
  9164. if ((**ppw != '\r') && (**ppw != '\n')) {
  9165. return -1;
  9166. }
  9167. } else {
  9168. /* must be a end of a word, but not a line */
  9169. if (**ppw != ' ') {
  9170. return -1;
  9171. }
  9172. }
  9173. /* Terminate and forward to the next word */
  9174. do {
  9175. **ppw = 0;
  9176. (*ppw)++;
  9177. } while (isspace((unsigned char)**ppw));
  9178. /* Check after term */
  9179. if (!eol) {
  9180. /* if it's not the end of line, there must be a next word */
  9181. if (!isgraph((unsigned char)**ppw)) {
  9182. return -1;
  9183. }
  9184. }
  9185. /* ok */
  9186. return 1;
  9187. }
  9188. /* Parse HTTP headers from the given buffer, advance buf pointer
  9189. * to the point where parsing stopped.
  9190. * All parameters must be valid pointers (not NULL).
  9191. * Return <0 on error. */
  9192. static int
  9193. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9194. {
  9195. int i;
  9196. int num_headers = 0;
  9197. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9198. char *dp = *buf;
  9199. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9200. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9201. dp++;
  9202. }
  9203. if (dp == *buf) {
  9204. /* End of headers reached. */
  9205. break;
  9206. }
  9207. if (*dp != ':') {
  9208. /* This is not a valid field. */
  9209. return -1;
  9210. }
  9211. /* End of header key (*dp == ':') */
  9212. /* Truncate here and set the key name */
  9213. *dp = 0;
  9214. hdr[i].name = *buf;
  9215. /* Skip all spaces */
  9216. do {
  9217. dp++;
  9218. } while ((*dp == ' ') || (*dp == '\t'));
  9219. /* The rest of the line is the value */
  9220. hdr[i].value = dp;
  9221. /* Find end of line */
  9222. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9223. dp++;
  9224. };
  9225. /* eliminate \r */
  9226. if (*dp == '\r') {
  9227. *dp = 0;
  9228. dp++;
  9229. if (*dp != '\n') {
  9230. /* This is not a valid line. */
  9231. return -1;
  9232. }
  9233. }
  9234. /* here *dp is either 0 or '\n' */
  9235. /* in any case, we have a new header */
  9236. num_headers = i + 1;
  9237. if (*dp) {
  9238. *dp = 0;
  9239. dp++;
  9240. *buf = dp;
  9241. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9242. /* This is the end of the header */
  9243. break;
  9244. }
  9245. } else {
  9246. *buf = dp;
  9247. break;
  9248. }
  9249. }
  9250. return num_headers;
  9251. }
  9252. struct mg_http_method_info {
  9253. const char *name;
  9254. int request_has_body;
  9255. int response_has_body;
  9256. int is_safe;
  9257. int is_idempotent;
  9258. int is_cacheable;
  9259. };
  9260. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9261. static const struct mg_http_method_info http_methods[] = {
  9262. /* HTTP (RFC 2616) */
  9263. {"GET", 0, 1, 1, 1, 1},
  9264. {"POST", 1, 1, 0, 0, 0},
  9265. {"PUT", 1, 0, 0, 1, 0},
  9266. {"DELETE", 0, 0, 0, 1, 0},
  9267. {"HEAD", 0, 0, 1, 1, 1},
  9268. {"OPTIONS", 0, 0, 1, 1, 0},
  9269. {"CONNECT", 1, 1, 0, 0, 0},
  9270. /* TRACE method (RFC 2616) is not supported for security reasons */
  9271. /* PATCH method (RFC 5789) */
  9272. {"PATCH", 1, 0, 0, 0, 0},
  9273. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9274. /* WEBDAV (RFC 2518) */
  9275. {"PROPFIND", 0, 1, 1, 1, 0},
  9276. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9277. * Some PROPFIND results MAY be cached, with care,
  9278. * as there is no cache validation mechanism for
  9279. * most properties. This method is both safe and
  9280. * idempotent (see Section 9.1 of [RFC2616]). */
  9281. {"MKCOL", 0, 0, 0, 1, 0},
  9282. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9283. * When MKCOL is invoked without a request body,
  9284. * the newly created collection SHOULD have no
  9285. * members. A MKCOL request message may contain
  9286. * a message body. The precise behavior of a MKCOL
  9287. * request when the body is present is undefined,
  9288. * ... ==> We do not support MKCOL with body data.
  9289. * This method is idempotent, but not safe (see
  9290. * Section 9.1 of [RFC2616]). Responses to this
  9291. * method MUST NOT be cached. */
  9292. /* Unsupported WEBDAV Methods: */
  9293. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9294. /* + 11 methods from RFC 3253 */
  9295. /* ORDERPATCH (RFC 3648) */
  9296. /* ACL (RFC 3744) */
  9297. /* SEARCH (RFC 5323) */
  9298. /* + MicroSoft extensions
  9299. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9300. /* REPORT method (RFC 3253) */
  9301. {"REPORT", 1, 1, 1, 1, 1},
  9302. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9303. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9304. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9305. * to be useful for REST in case a "GET request with body" is
  9306. * required. */
  9307. {NULL, 0, 0, 0, 0, 0}
  9308. /* end of list */
  9309. };
  9310. static const struct mg_http_method_info *
  9311. get_http_method_info(const char *method)
  9312. {
  9313. /* Check if the method is known to the server. The list of all known
  9314. * HTTP methods can be found here at
  9315. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9316. */
  9317. const struct mg_http_method_info *m = http_methods;
  9318. while (m->name) {
  9319. if (!strcmp(m->name, method)) {
  9320. return m;
  9321. }
  9322. m++;
  9323. }
  9324. return NULL;
  9325. }
  9326. static int
  9327. is_valid_http_method(const char *method)
  9328. {
  9329. return (get_http_method_info(method) != NULL);
  9330. }
  9331. /* Parse HTTP request, fill in mg_request_info structure.
  9332. * This function modifies the buffer by NUL-terminating
  9333. * HTTP request components, header names and header values.
  9334. * Parameters:
  9335. * buf (in/out): pointer to the HTTP header to parse and split
  9336. * len (in): length of HTTP header buffer
  9337. * re (out): parsed header as mg_request_info
  9338. * buf and ri must be valid pointers (not NULL), len>0.
  9339. * Returns <0 on error. */
  9340. static int
  9341. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9342. {
  9343. int request_length;
  9344. int init_skip = 0;
  9345. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9346. * remote_port */
  9347. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9348. NULL;
  9349. ri->num_headers = 0;
  9350. /* RFC says that all initial whitespaces should be ingored */
  9351. /* This included all leading \r and \n (isspace) */
  9352. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9353. while ((len > 0) && isspace((unsigned char)*buf)) {
  9354. buf++;
  9355. len--;
  9356. init_skip++;
  9357. }
  9358. if (len == 0) {
  9359. /* Incomplete request */
  9360. return 0;
  9361. }
  9362. /* Control characters are not allowed, including zero */
  9363. if (iscntrl((unsigned char)*buf)) {
  9364. return -1;
  9365. }
  9366. /* Find end of HTTP header */
  9367. request_length = get_http_header_len(buf, len);
  9368. if (request_length <= 0) {
  9369. return request_length;
  9370. }
  9371. buf[request_length - 1] = '\0';
  9372. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9373. return -1;
  9374. }
  9375. /* The first word has to be the HTTP method */
  9376. ri->request_method = buf;
  9377. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9378. return -1;
  9379. }
  9380. /* Check for a valid http method */
  9381. if (!is_valid_http_method(ri->request_method)) {
  9382. return -1;
  9383. }
  9384. /* The second word is the URI */
  9385. ri->request_uri = buf;
  9386. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9387. return -1;
  9388. }
  9389. /* Next would be the HTTP version */
  9390. ri->http_version = buf;
  9391. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9392. return -1;
  9393. }
  9394. /* Check for a valid HTTP version key */
  9395. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9396. /* Invalid request */
  9397. return -1;
  9398. }
  9399. ri->http_version += 5;
  9400. /* Parse all HTTP headers */
  9401. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9402. if (ri->num_headers < 0) {
  9403. /* Error while parsing headers */
  9404. return -1;
  9405. }
  9406. return request_length + init_skip;
  9407. }
  9408. static int
  9409. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9410. {
  9411. int response_length;
  9412. int init_skip = 0;
  9413. char *tmp, *tmp2;
  9414. long l;
  9415. /* Initialize elements. */
  9416. ri->http_version = ri->status_text = NULL;
  9417. ri->num_headers = ri->status_code = 0;
  9418. /* RFC says that all initial whitespaces should be ingored */
  9419. /* This included all leading \r and \n (isspace) */
  9420. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9421. while ((len > 0) && isspace((unsigned char)*buf)) {
  9422. buf++;
  9423. len--;
  9424. init_skip++;
  9425. }
  9426. if (len == 0) {
  9427. /* Incomplete request */
  9428. return 0;
  9429. }
  9430. /* Control characters are not allowed, including zero */
  9431. if (iscntrl((unsigned char)*buf)) {
  9432. return -1;
  9433. }
  9434. /* Find end of HTTP header */
  9435. response_length = get_http_header_len(buf, len);
  9436. if (response_length <= 0) {
  9437. return response_length;
  9438. }
  9439. buf[response_length - 1] = '\0';
  9440. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9441. return -1;
  9442. }
  9443. /* The first word is the HTTP version */
  9444. /* Check for a valid HTTP version key */
  9445. if (strncmp(buf, "HTTP/", 5) != 0) {
  9446. /* Invalid request */
  9447. return -1;
  9448. }
  9449. buf += 5;
  9450. if (!isgraph((unsigned char)buf[0])) {
  9451. /* Invalid request */
  9452. return -1;
  9453. }
  9454. ri->http_version = buf;
  9455. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9456. return -1;
  9457. }
  9458. /* The second word is the status as a number */
  9459. tmp = buf;
  9460. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9461. return -1;
  9462. }
  9463. l = strtol(tmp, &tmp2, 10);
  9464. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9465. /* Everything else but a 3 digit code is invalid */
  9466. return -1;
  9467. }
  9468. ri->status_code = (int)l;
  9469. /* The rest of the line is the status text */
  9470. ri->status_text = buf;
  9471. /* Find end of status text */
  9472. /* isgraph or isspace = isprint */
  9473. while (isprint((unsigned char)*buf)) {
  9474. buf++;
  9475. }
  9476. if ((*buf != '\r') && (*buf != '\n')) {
  9477. return -1;
  9478. }
  9479. /* Terminate string and forward buf to next line */
  9480. do {
  9481. *buf = 0;
  9482. buf++;
  9483. } while (isspace((unsigned char)*buf));
  9484. /* Parse all HTTP headers */
  9485. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9486. if (ri->num_headers < 0) {
  9487. /* Error while parsing headers */
  9488. return -1;
  9489. }
  9490. return response_length + init_skip;
  9491. }
  9492. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9493. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9494. * buffer (which marks the end of HTTP request). Buffer buf may already
  9495. * have some data. The length of the data is stored in nread.
  9496. * Upon every read operation, increase nread by the number of bytes read. */
  9497. static int
  9498. read_message(FILE *fp,
  9499. struct mg_connection *conn,
  9500. char *buf,
  9501. int bufsiz,
  9502. int *nread)
  9503. {
  9504. int request_len, n = 0;
  9505. struct timespec last_action_time;
  9506. double request_timeout;
  9507. if (!conn) {
  9508. return 0;
  9509. }
  9510. memset(&last_action_time, 0, sizeof(last_action_time));
  9511. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9512. /* value of request_timeout is in seconds, config in milliseconds */
  9513. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9514. } else {
  9515. request_timeout = -1.0;
  9516. }
  9517. if (conn->handled_requests > 0) {
  9518. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9519. request_timeout =
  9520. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9521. }
  9522. }
  9523. request_len = get_http_header_len(buf, *nread);
  9524. while (request_len == 0) {
  9525. /* Full request not yet received */
  9526. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9527. /* Server is to be stopped. */
  9528. return -1;
  9529. }
  9530. if (*nread >= bufsiz) {
  9531. /* Request too long */
  9532. return -2;
  9533. }
  9534. n = pull_inner(
  9535. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9536. if (n == -2) {
  9537. /* Receive error */
  9538. return -1;
  9539. }
  9540. /* update clock after every read request */
  9541. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9542. if (n > 0) {
  9543. *nread += n;
  9544. request_len = get_http_header_len(buf, *nread);
  9545. }
  9546. if ((request_len == 0) && (request_timeout >= 0)) {
  9547. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9548. > request_timeout) {
  9549. /* Timeout */
  9550. return -1;
  9551. }
  9552. }
  9553. }
  9554. return request_len;
  9555. }
  9556. #if !defined(NO_CGI) || !defined(NO_FILES)
  9557. static int
  9558. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9559. {
  9560. const char *expect;
  9561. char buf[MG_BUF_LEN];
  9562. int success = 0;
  9563. if (!conn) {
  9564. return 0;
  9565. }
  9566. expect = mg_get_header(conn, "Expect");
  9567. DEBUG_ASSERT(fp != NULL);
  9568. if (!fp) {
  9569. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9570. return 0;
  9571. }
  9572. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9573. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9574. */
  9575. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9576. } else {
  9577. if (expect != NULL) {
  9578. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9579. conn->status_code = 100;
  9580. } else {
  9581. conn->status_code = 200;
  9582. }
  9583. DEBUG_ASSERT(conn->consumed_content == 0);
  9584. if (conn->consumed_content != 0) {
  9585. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9586. return 0;
  9587. }
  9588. for (;;) {
  9589. int nread = mg_read(conn, buf, sizeof(buf));
  9590. if (nread <= 0) {
  9591. success = (nread == 0);
  9592. break;
  9593. }
  9594. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9595. break;
  9596. }
  9597. }
  9598. /* Each error code path in this function must send an error */
  9599. if (!success) {
  9600. /* NOTE: Maybe some data has already been sent. */
  9601. /* TODO (low): If some data has been sent, a correct error
  9602. * reply can no longer be sent, so just close the connection */
  9603. mg_send_http_error(conn, 500, "%s", "");
  9604. }
  9605. }
  9606. return success;
  9607. }
  9608. #endif
  9609. #if defined(USE_TIMERS)
  9610. #define TIMER_API static
  9611. #include "timer.inl"
  9612. #endif /* USE_TIMERS */
  9613. #if !defined(NO_CGI)
  9614. /* This structure helps to create an environment for the spawned CGI
  9615. * program.
  9616. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9617. * last element must be NULL.
  9618. * However, on Windows there is a requirement that all these
  9619. * VARIABLE=VALUE\0
  9620. * strings must reside in a contiguous buffer. The end of the buffer is
  9621. * marked by two '\0' characters.
  9622. * We satisfy both worlds: we create an envp array (which is vars), all
  9623. * entries are actually pointers inside buf. */
  9624. struct cgi_environment {
  9625. struct mg_connection *conn;
  9626. /* Data block */
  9627. char *buf; /* Environment buffer */
  9628. size_t buflen; /* Space available in buf */
  9629. size_t bufused; /* Space taken in buf */
  9630. /* Index block */
  9631. char **var; /* char **envp */
  9632. size_t varlen; /* Number of variables available in var */
  9633. size_t varused; /* Number of variables stored in var */
  9634. };
  9635. static void addenv(struct cgi_environment *env,
  9636. PRINTF_FORMAT_STRING(const char *fmt),
  9637. ...) PRINTF_ARGS(2, 3);
  9638. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9639. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9640. static void
  9641. addenv(struct cgi_environment *env, const char *fmt, ...)
  9642. {
  9643. size_t i, n, space;
  9644. int truncated = 0;
  9645. char *added;
  9646. va_list ap;
  9647. if ((env->varlen - env->varused) < 2) {
  9648. mg_cry_internal(env->conn,
  9649. "%s: Cannot register CGI variable [%s]",
  9650. __func__,
  9651. fmt);
  9652. return;
  9653. }
  9654. /* Calculate how much space is left in the buffer */
  9655. space = (env->buflen - env->bufused);
  9656. do {
  9657. /* Space for "\0\0" is always needed. */
  9658. if (space <= 2) {
  9659. /* Allocate new buffer */
  9660. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9661. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9662. if (!added) {
  9663. /* Out of memory */
  9664. mg_cry_internal(
  9665. env->conn,
  9666. "%s: Cannot allocate memory for CGI variable [%s]",
  9667. __func__,
  9668. fmt);
  9669. return;
  9670. }
  9671. /* Retarget pointers */
  9672. env->buf = added;
  9673. env->buflen = n;
  9674. for (i = 0, n = 0; i < env->varused; i++) {
  9675. env->var[i] = added + n;
  9676. n += strlen(added + n) + 1;
  9677. }
  9678. space = (env->buflen - env->bufused);
  9679. }
  9680. /* Make a pointer to the free space int the buffer */
  9681. added = env->buf + env->bufused;
  9682. /* Copy VARIABLE=VALUE\0 string into the free space */
  9683. va_start(ap, fmt);
  9684. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9685. va_end(ap);
  9686. /* Do not add truncated strings to the environment */
  9687. if (truncated) {
  9688. /* Reallocate the buffer */
  9689. space = 0;
  9690. }
  9691. } while (truncated);
  9692. /* Calculate number of bytes added to the environment */
  9693. n = strlen(added) + 1;
  9694. env->bufused += n;
  9695. /* Append a pointer to the added string into the envp array */
  9696. env->var[env->varused] = added;
  9697. env->varused++;
  9698. }
  9699. /* Return 0 on success, non-zero if an error occurs. */
  9700. static int
  9701. prepare_cgi_environment(struct mg_connection *conn,
  9702. const char *prog,
  9703. struct cgi_environment *env)
  9704. {
  9705. const char *s;
  9706. struct vec var_vec;
  9707. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9708. int i, truncated, uri_len;
  9709. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9710. return -1;
  9711. }
  9712. env->conn = conn;
  9713. env->buflen = CGI_ENVIRONMENT_SIZE;
  9714. env->bufused = 0;
  9715. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9716. if (env->buf == NULL) {
  9717. mg_cry_internal(conn,
  9718. "%s: Not enough memory for environmental buffer",
  9719. __func__);
  9720. return -1;
  9721. }
  9722. env->varlen = MAX_CGI_ENVIR_VARS;
  9723. env->varused = 0;
  9724. env->var =
  9725. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9726. if (env->var == NULL) {
  9727. mg_cry_internal(conn,
  9728. "%s: Not enough memory for environmental variables",
  9729. __func__);
  9730. mg_free(env->buf);
  9731. return -1;
  9732. }
  9733. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9734. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9735. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9736. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9737. /* Prepare the environment block */
  9738. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9739. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9740. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9741. #if defined(USE_IPV6)
  9742. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9743. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9744. } else
  9745. #endif
  9746. {
  9747. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9748. }
  9749. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9750. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9751. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9752. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9753. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9754. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9755. /* SCRIPT_NAME */
  9756. uri_len = (int)strlen(conn->request_info.local_uri);
  9757. if (conn->path_info == NULL) {
  9758. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9759. /* URI: /path_to_script/script.cgi */
  9760. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9761. } else {
  9762. /* URI: /path_to_script/ ... using index.cgi */
  9763. const char *index_file = strrchr(prog, '/');
  9764. if (index_file) {
  9765. addenv(env,
  9766. "SCRIPT_NAME=%s%s",
  9767. conn->request_info.local_uri,
  9768. index_file + 1);
  9769. }
  9770. }
  9771. } else {
  9772. /* URI: /path_to_script/script.cgi/path_info */
  9773. addenv(env,
  9774. "SCRIPT_NAME=%.*s",
  9775. uri_len - (int)strlen(conn->path_info),
  9776. conn->request_info.local_uri);
  9777. }
  9778. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9779. if (conn->path_info == NULL) {
  9780. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9781. } else {
  9782. addenv(env,
  9783. "PATH_TRANSLATED=%s%s",
  9784. conn->dom_ctx->config[DOCUMENT_ROOT],
  9785. conn->path_info);
  9786. }
  9787. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9788. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9789. addenv(env, "CONTENT_TYPE=%s", s);
  9790. }
  9791. if (conn->request_info.query_string != NULL) {
  9792. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9793. }
  9794. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9795. addenv(env, "CONTENT_LENGTH=%s", s);
  9796. }
  9797. if ((s = getenv("PATH")) != NULL) {
  9798. addenv(env, "PATH=%s", s);
  9799. }
  9800. if (conn->path_info != NULL) {
  9801. addenv(env, "PATH_INFO=%s", conn->path_info);
  9802. }
  9803. if (conn->status_code > 0) {
  9804. /* CGI error handler should show the status code */
  9805. addenv(env, "STATUS=%d", conn->status_code);
  9806. }
  9807. #if defined(_WIN32)
  9808. if ((s = getenv("COMSPEC")) != NULL) {
  9809. addenv(env, "COMSPEC=%s", s);
  9810. }
  9811. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9812. addenv(env, "SYSTEMROOT=%s", s);
  9813. }
  9814. if ((s = getenv("SystemDrive")) != NULL) {
  9815. addenv(env, "SystemDrive=%s", s);
  9816. }
  9817. if ((s = getenv("ProgramFiles")) != NULL) {
  9818. addenv(env, "ProgramFiles=%s", s);
  9819. }
  9820. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9821. addenv(env, "ProgramFiles(x86)=%s", s);
  9822. }
  9823. #else
  9824. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9825. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9826. }
  9827. #endif /* _WIN32 */
  9828. if ((s = getenv("PERLLIB")) != NULL) {
  9829. addenv(env, "PERLLIB=%s", s);
  9830. }
  9831. if (conn->request_info.remote_user != NULL) {
  9832. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9833. addenv(env, "%s", "AUTH_TYPE=Digest");
  9834. }
  9835. /* Add all headers as HTTP_* variables */
  9836. for (i = 0; i < conn->request_info.num_headers; i++) {
  9837. (void)mg_snprintf(conn,
  9838. &truncated,
  9839. http_var_name,
  9840. sizeof(http_var_name),
  9841. "HTTP_%s",
  9842. conn->request_info.http_headers[i].name);
  9843. if (truncated) {
  9844. mg_cry_internal(conn,
  9845. "%s: HTTP header variable too long [%s]",
  9846. __func__,
  9847. conn->request_info.http_headers[i].name);
  9848. continue;
  9849. }
  9850. /* Convert variable name into uppercase, and change - to _ */
  9851. for (p = http_var_name; *p != '\0'; p++) {
  9852. if (*p == '-') {
  9853. *p = '_';
  9854. }
  9855. *p = (char)toupper((unsigned char)*p);
  9856. }
  9857. addenv(env,
  9858. "%s=%s",
  9859. http_var_name,
  9860. conn->request_info.http_headers[i].value);
  9861. }
  9862. /* Add user-specified variables */
  9863. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9864. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9865. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9866. }
  9867. env->var[env->varused] = NULL;
  9868. env->buf[env->bufused] = '\0';
  9869. return 0;
  9870. }
  9871. /* Data for CGI process control: PID and number of references */
  9872. struct process_control_data {
  9873. pid_t pid;
  9874. ptrdiff_t references;
  9875. };
  9876. static int
  9877. abort_process(void *data)
  9878. {
  9879. /* Waitpid checks for child status and won't work for a pid that does
  9880. * not identify a child of the current process. Thus, if the pid is
  9881. * reused, we will not affect a different process. */
  9882. struct process_control_data *proc = (struct process_control_data *)data;
  9883. int status = 0;
  9884. ptrdiff_t refs;
  9885. pid_t ret_pid;
  9886. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9887. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9888. /* Stop child process */
  9889. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9890. kill(proc->pid, SIGABRT);
  9891. /* Wait until process is terminated (don't leave zombies) */
  9892. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9893. ;
  9894. } else {
  9895. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9896. }
  9897. /* Dec reference counter */
  9898. refs = mg_atomic_dec(&proc->references);
  9899. if (refs == 0) {
  9900. /* no more references - free data */
  9901. mg_free(data);
  9902. }
  9903. return 0;
  9904. }
  9905. /* Local (static) function assumes all arguments are valid. */
  9906. static void
  9907. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9908. {
  9909. char *buf;
  9910. size_t buflen;
  9911. int headers_len, data_len, i, truncated;
  9912. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9913. const char *status, *status_text, *connection_state;
  9914. char *pbuf, dir[PATH_MAX], *p;
  9915. struct mg_request_info ri;
  9916. struct cgi_environment blk;
  9917. FILE *in = NULL, *out = NULL, *err = NULL;
  9918. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9919. pid_t pid = (pid_t)-1;
  9920. struct process_control_data *proc = NULL;
  9921. #if defined(USE_TIMERS)
  9922. double cgi_timeout = -1.0;
  9923. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9924. /* Get timeout in seconds */
  9925. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9926. }
  9927. #endif
  9928. buf = NULL;
  9929. buflen = conn->phys_ctx->max_request_size;
  9930. i = prepare_cgi_environment(conn, prog, &blk);
  9931. if (i != 0) {
  9932. blk.buf = NULL;
  9933. blk.var = NULL;
  9934. goto done;
  9935. }
  9936. /* CGI must be executed in its own directory. 'dir' must point to the
  9937. * directory containing executable program, 'p' must point to the
  9938. * executable program name relative to 'dir'. */
  9939. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9940. if (truncated) {
  9941. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9942. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9943. goto done;
  9944. }
  9945. if ((p = strrchr(dir, '/')) != NULL) {
  9946. *p++ = '\0';
  9947. } else {
  9948. dir[0] = '.';
  9949. dir[1] = '\0';
  9950. p = (char *)prog;
  9951. }
  9952. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9953. status = strerror(ERRNO);
  9954. mg_cry_internal(
  9955. conn,
  9956. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9957. prog,
  9958. status);
  9959. mg_send_http_error(conn,
  9960. 500,
  9961. "Error: Cannot create CGI pipe: %s",
  9962. status);
  9963. goto done;
  9964. }
  9965. proc = (struct process_control_data *)
  9966. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9967. if (proc == NULL) {
  9968. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9969. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9970. goto done;
  9971. }
  9972. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9973. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9974. if (pid == (pid_t)-1) {
  9975. status = strerror(ERRNO);
  9976. mg_cry_internal(
  9977. conn,
  9978. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9979. prog,
  9980. status);
  9981. mg_send_http_error(conn,
  9982. 500,
  9983. "Error: Cannot spawn CGI process [%s]: %s",
  9984. prog,
  9985. status);
  9986. mg_free(proc);
  9987. proc = NULL;
  9988. goto done;
  9989. }
  9990. /* Store data in shared process_control_data */
  9991. proc->pid = pid;
  9992. proc->references = 1;
  9993. #if defined(USE_TIMERS)
  9994. if (cgi_timeout > 0.0) {
  9995. proc->references = 2;
  9996. // Start a timer for CGI
  9997. timer_add(conn->phys_ctx,
  9998. cgi_timeout /* in seconds */,
  9999. 0.0,
  10000. 1,
  10001. abort_process,
  10002. (void *)proc);
  10003. }
  10004. #endif
  10005. /* Parent closes only one side of the pipes.
  10006. * If we don't mark them as closed, close() attempt before
  10007. * return from this function throws an exception on Windows.
  10008. * Windows does not like when closed descriptor is closed again. */
  10009. (void)close(fdin[0]);
  10010. (void)close(fdout[1]);
  10011. (void)close(fderr[1]);
  10012. fdin[0] = fdout[1] = fderr[1] = -1;
  10013. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10014. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10015. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10016. status = strerror(ERRNO);
  10017. mg_cry_internal(conn,
  10018. "Error: CGI program \"%s\": Can not open fd: %s",
  10019. prog,
  10020. status);
  10021. mg_send_http_error(conn,
  10022. 500,
  10023. "Error: CGI can not open fd\nfdopen: %s",
  10024. status);
  10025. goto done;
  10026. }
  10027. setbuf(in, NULL);
  10028. setbuf(out, NULL);
  10029. setbuf(err, NULL);
  10030. fout.access.fp = out;
  10031. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10032. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10033. conn->content_len);
  10034. /* This is a POST/PUT request, or another request with body data. */
  10035. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10036. /* Error sending the body data */
  10037. mg_cry_internal(
  10038. conn,
  10039. "Error: CGI program \"%s\": Forward body data failed",
  10040. prog);
  10041. goto done;
  10042. }
  10043. }
  10044. /* Close so child gets an EOF. */
  10045. fclose(in);
  10046. in = NULL;
  10047. fdin[1] = -1;
  10048. /* Now read CGI reply into a buffer. We need to set correct
  10049. * status code, thus we need to see all HTTP headers first.
  10050. * Do not send anything back to client, until we buffer in all
  10051. * HTTP headers. */
  10052. data_len = 0;
  10053. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10054. if (buf == NULL) {
  10055. mg_send_http_error(conn,
  10056. 500,
  10057. "Error: Not enough memory for CGI buffer (%u bytes)",
  10058. (unsigned int)buflen);
  10059. mg_cry_internal(
  10060. conn,
  10061. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10062. "bytes)",
  10063. prog,
  10064. (unsigned int)buflen);
  10065. goto done;
  10066. }
  10067. DEBUG_TRACE("CGI: %s", "wait for response");
  10068. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10069. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10070. if (headers_len <= 0) {
  10071. /* Could not parse the CGI response. Check if some error message on
  10072. * stderr. */
  10073. i = pull_all(err, conn, buf, (int)buflen);
  10074. if (i > 0) {
  10075. /* CGI program explicitly sent an error */
  10076. /* Write the error message to the internal log */
  10077. mg_cry_internal(conn,
  10078. "Error: CGI program \"%s\" sent error "
  10079. "message: [%.*s]",
  10080. prog,
  10081. i,
  10082. buf);
  10083. /* Don't send the error message back to the client */
  10084. mg_send_http_error(conn,
  10085. 500,
  10086. "Error: CGI program \"%s\" failed.",
  10087. prog);
  10088. } else {
  10089. /* CGI program did not explicitly send an error, but a broken
  10090. * respon header */
  10091. mg_cry_internal(conn,
  10092. "Error: CGI program sent malformed or too big "
  10093. "(>%u bytes) HTTP headers: [%.*s]",
  10094. (unsigned)buflen,
  10095. data_len,
  10096. buf);
  10097. mg_send_http_error(conn,
  10098. 500,
  10099. "Error: CGI program sent malformed or too big "
  10100. "(>%u bytes) HTTP headers: [%.*s]",
  10101. (unsigned)buflen,
  10102. data_len,
  10103. buf);
  10104. }
  10105. /* in both cases, abort processing CGI */
  10106. goto done;
  10107. }
  10108. pbuf = buf;
  10109. buf[headers_len - 1] = '\0';
  10110. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10111. /* Make up and send the status line */
  10112. status_text = "OK";
  10113. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10114. != NULL) {
  10115. conn->status_code = atoi(status);
  10116. status_text = status;
  10117. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10118. status_text++;
  10119. }
  10120. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10121. != NULL) {
  10122. conn->status_code = 307;
  10123. } else {
  10124. conn->status_code = 200;
  10125. }
  10126. connection_state =
  10127. get_header(ri.http_headers, ri.num_headers, "Connection");
  10128. if (!header_has_option(connection_state, "keep-alive")) {
  10129. conn->must_close = 1;
  10130. }
  10131. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10132. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10133. /* Send headers */
  10134. for (i = 0; i < ri.num_headers; i++) {
  10135. DEBUG_TRACE("CGI header: %s: %s",
  10136. ri.http_headers[i].name,
  10137. ri.http_headers[i].value);
  10138. mg_printf(conn,
  10139. "%s: %s\r\n",
  10140. ri.http_headers[i].name,
  10141. ri.http_headers[i].value);
  10142. }
  10143. mg_write(conn, "\r\n", 2);
  10144. /* Send chunk of data that may have been read after the headers */
  10145. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10146. /* Read the rest of CGI output and send to the client */
  10147. DEBUG_TRACE("CGI: %s", "forward all data");
  10148. send_file_data(conn, &fout, 0, INT64_MAX);
  10149. DEBUG_TRACE("CGI: %s", "all data sent");
  10150. done:
  10151. mg_free(blk.var);
  10152. mg_free(blk.buf);
  10153. if (pid != (pid_t)-1) {
  10154. abort_process((void *)proc);
  10155. }
  10156. if (fdin[0] != -1) {
  10157. close(fdin[0]);
  10158. }
  10159. if (fdout[1] != -1) {
  10160. close(fdout[1]);
  10161. }
  10162. if (fderr[1] != -1) {
  10163. close(fderr[1]);
  10164. }
  10165. if (in != NULL) {
  10166. fclose(in);
  10167. } else if (fdin[1] != -1) {
  10168. close(fdin[1]);
  10169. }
  10170. if (out != NULL) {
  10171. fclose(out);
  10172. } else if (fdout[0] != -1) {
  10173. close(fdout[0]);
  10174. }
  10175. if (err != NULL) {
  10176. fclose(err);
  10177. } else if (fderr[0] != -1) {
  10178. close(fderr[0]);
  10179. }
  10180. mg_free(buf);
  10181. }
  10182. #endif /* !NO_CGI */
  10183. #if !defined(NO_FILES)
  10184. static void
  10185. mkcol(struct mg_connection *conn, const char *path)
  10186. {
  10187. int rc, body_len;
  10188. struct de de;
  10189. char date[64];
  10190. time_t curtime = time(NULL);
  10191. if (conn == NULL) {
  10192. return;
  10193. }
  10194. /* TODO (mid): Check the mg_send_http_error situations in this function
  10195. */
  10196. memset(&de.file, 0, sizeof(de.file));
  10197. if (!mg_stat(conn, path, &de.file)) {
  10198. mg_cry_internal(conn,
  10199. "%s: mg_stat(%s) failed: %s",
  10200. __func__,
  10201. path,
  10202. strerror(ERRNO));
  10203. }
  10204. if (de.file.last_modified) {
  10205. /* TODO (mid): This check does not seem to make any sense ! */
  10206. /* TODO (mid): Add a webdav unit test first, before changing
  10207. * anything here. */
  10208. mg_send_http_error(
  10209. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10210. return;
  10211. }
  10212. body_len = conn->data_len - conn->request_len;
  10213. if (body_len > 0) {
  10214. mg_send_http_error(
  10215. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10216. return;
  10217. }
  10218. rc = mg_mkdir(conn, path, 0755);
  10219. if (rc == 0) {
  10220. conn->status_code = 201;
  10221. gmt_time_string(date, sizeof(date), &curtime);
  10222. mg_printf(conn,
  10223. "HTTP/1.1 %d Created\r\n"
  10224. "Date: %s\r\n",
  10225. conn->status_code,
  10226. date);
  10227. send_static_cache_header(conn);
  10228. send_additional_header(conn);
  10229. mg_printf(conn,
  10230. "Content-Length: 0\r\n"
  10231. "Connection: %s\r\n\r\n",
  10232. suggest_connection_header(conn));
  10233. } else {
  10234. if (errno == EEXIST) {
  10235. mg_send_http_error(
  10236. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10237. } else if (errno == EACCES) {
  10238. mg_send_http_error(
  10239. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10240. } else if (errno == ENOENT) {
  10241. mg_send_http_error(
  10242. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10243. } else {
  10244. mg_send_http_error(
  10245. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10246. }
  10247. }
  10248. }
  10249. static void
  10250. put_file(struct mg_connection *conn, const char *path)
  10251. {
  10252. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10253. const char *range;
  10254. int64_t r1, r2;
  10255. int rc;
  10256. char date[64];
  10257. time_t curtime = time(NULL);
  10258. if (conn == NULL) {
  10259. return;
  10260. }
  10261. if (mg_stat(conn, path, &file.stat)) {
  10262. /* File already exists */
  10263. conn->status_code = 200;
  10264. if (file.stat.is_directory) {
  10265. /* This is an already existing directory,
  10266. * so there is nothing to do for the server. */
  10267. rc = 0;
  10268. } else {
  10269. /* File exists and is not a directory. */
  10270. /* Can it be replaced? */
  10271. #if defined(MG_USE_OPEN_FILE)
  10272. if (file.access.membuf != NULL) {
  10273. /* This is an "in-memory" file, that can not be replaced */
  10274. mg_send_http_error(conn,
  10275. 405,
  10276. "Error: Put not possible\nReplacing %s "
  10277. "is not supported",
  10278. path);
  10279. return;
  10280. }
  10281. #endif
  10282. /* Check if the server may write this file */
  10283. if (access(path, W_OK) == 0) {
  10284. /* Access granted */
  10285. rc = 1;
  10286. } else {
  10287. mg_send_http_error(
  10288. conn,
  10289. 403,
  10290. "Error: Put not possible\nReplacing %s is not allowed",
  10291. path);
  10292. return;
  10293. }
  10294. }
  10295. } else {
  10296. /* File should be created */
  10297. conn->status_code = 201;
  10298. rc = put_dir(conn, path);
  10299. }
  10300. if (rc == 0) {
  10301. /* put_dir returns 0 if path is a directory */
  10302. gmt_time_string(date, sizeof(date), &curtime);
  10303. mg_printf(conn,
  10304. "HTTP/1.1 %d %s\r\n",
  10305. conn->status_code,
  10306. mg_get_response_code_text(NULL, conn->status_code));
  10307. send_no_cache_header(conn);
  10308. send_additional_header(conn);
  10309. mg_printf(conn,
  10310. "Date: %s\r\n"
  10311. "Content-Length: 0\r\n"
  10312. "Connection: %s\r\n\r\n",
  10313. date,
  10314. suggest_connection_header(conn));
  10315. /* Request to create a directory has been fulfilled successfully.
  10316. * No need to put a file. */
  10317. return;
  10318. }
  10319. if (rc == -1) {
  10320. /* put_dir returns -1 if the path is too long */
  10321. mg_send_http_error(conn,
  10322. 414,
  10323. "Error: Path too long\nput_dir(%s): %s",
  10324. path,
  10325. strerror(ERRNO));
  10326. return;
  10327. }
  10328. if (rc == -2) {
  10329. /* put_dir returns -2 if the directory can not be created */
  10330. mg_send_http_error(conn,
  10331. 500,
  10332. "Error: Can not create directory\nput_dir(%s): %s",
  10333. path,
  10334. strerror(ERRNO));
  10335. return;
  10336. }
  10337. /* A file should be created or overwritten. */
  10338. /* Currently CivetWeb does not nead read+write access. */
  10339. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10340. || file.access.fp == NULL) {
  10341. (void)mg_fclose(&file.access);
  10342. mg_send_http_error(conn,
  10343. 500,
  10344. "Error: Can not create file\nfopen(%s): %s",
  10345. path,
  10346. strerror(ERRNO));
  10347. return;
  10348. }
  10349. fclose_on_exec(&file.access, conn);
  10350. range = mg_get_header(conn, "Content-Range");
  10351. r1 = r2 = 0;
  10352. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10353. conn->status_code = 206; /* Partial content */
  10354. fseeko(file.access.fp, r1, SEEK_SET);
  10355. }
  10356. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10357. /* forward_body_data failed.
  10358. * The error code has already been sent to the client,
  10359. * and conn->status_code is already set. */
  10360. (void)mg_fclose(&file.access);
  10361. return;
  10362. }
  10363. if (mg_fclose(&file.access) != 0) {
  10364. /* fclose failed. This might have different reasons, but a likely
  10365. * one is "no space on disk", http 507. */
  10366. conn->status_code = 507;
  10367. }
  10368. gmt_time_string(date, sizeof(date), &curtime);
  10369. mg_printf(conn,
  10370. "HTTP/1.1 %d %s\r\n",
  10371. conn->status_code,
  10372. mg_get_response_code_text(NULL, conn->status_code));
  10373. send_no_cache_header(conn);
  10374. send_additional_header(conn);
  10375. mg_printf(conn,
  10376. "Date: %s\r\n"
  10377. "Content-Length: 0\r\n"
  10378. "Connection: %s\r\n\r\n",
  10379. date,
  10380. suggest_connection_header(conn));
  10381. }
  10382. static void
  10383. delete_file(struct mg_connection *conn, const char *path)
  10384. {
  10385. struct de de;
  10386. memset(&de.file, 0, sizeof(de.file));
  10387. if (!mg_stat(conn, path, &de.file)) {
  10388. /* mg_stat returns 0 if the file does not exist */
  10389. mg_send_http_error(conn,
  10390. 404,
  10391. "Error: Cannot delete file\nFile %s not found",
  10392. path);
  10393. return;
  10394. }
  10395. #if 0 /* Ignore if a file in memory is inside a folder */
  10396. if (de.access.membuf != NULL) {
  10397. /* the file is cached in memory */
  10398. mg_send_http_error(
  10399. conn,
  10400. 405,
  10401. "Error: Delete not possible\nDeleting %s is not supported",
  10402. path);
  10403. return;
  10404. }
  10405. #endif
  10406. if (de.file.is_directory) {
  10407. if (remove_directory(conn, path)) {
  10408. /* Delete is successful: Return 204 without content. */
  10409. mg_send_http_error(conn, 204, "%s", "");
  10410. } else {
  10411. /* Delete is not successful: Return 500 (Server error). */
  10412. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10413. }
  10414. return;
  10415. }
  10416. /* This is an existing file (not a directory).
  10417. * Check if write permission is granted. */
  10418. if (access(path, W_OK) != 0) {
  10419. /* File is read only */
  10420. mg_send_http_error(
  10421. conn,
  10422. 403,
  10423. "Error: Delete not possible\nDeleting %s is not allowed",
  10424. path);
  10425. return;
  10426. }
  10427. /* Try to delete it. */
  10428. if (mg_remove(conn, path) == 0) {
  10429. /* Delete was successful: Return 204 without content. */
  10430. mg_send_http_error(conn, 204, "%s", "");
  10431. } else {
  10432. /* Delete not successful (file locked). */
  10433. mg_send_http_error(conn,
  10434. 423,
  10435. "Error: Cannot delete file\nremove(%s): %s",
  10436. path,
  10437. strerror(ERRNO));
  10438. }
  10439. }
  10440. #endif /* !NO_FILES */
  10441. #if !defined(NO_FILESYSTEMS)
  10442. static void
  10443. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10444. static void
  10445. do_ssi_include(struct mg_connection *conn,
  10446. const char *ssi,
  10447. char *tag,
  10448. int include_level)
  10449. {
  10450. char file_name[MG_BUF_LEN], path[512], *p;
  10451. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10452. size_t len;
  10453. int truncated = 0;
  10454. if (conn == NULL) {
  10455. return;
  10456. }
  10457. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10458. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10459. * always < MG_BUF_LEN. */
  10460. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10461. /* File name is relative to the webserver root */
  10462. file_name[511] = 0;
  10463. (void)mg_snprintf(conn,
  10464. &truncated,
  10465. path,
  10466. sizeof(path),
  10467. "%s/%s",
  10468. conn->dom_ctx->config[DOCUMENT_ROOT],
  10469. file_name);
  10470. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10471. /* File name is relative to the webserver working directory
  10472. * or it is absolute system path */
  10473. file_name[511] = 0;
  10474. (void)
  10475. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10476. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10477. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10478. /* File name is relative to the currect document */
  10479. file_name[511] = 0;
  10480. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10481. if (!truncated) {
  10482. if ((p = strrchr(path, '/')) != NULL) {
  10483. p[1] = '\0';
  10484. }
  10485. len = strlen(path);
  10486. (void)mg_snprintf(conn,
  10487. &truncated,
  10488. path + len,
  10489. sizeof(path) - len,
  10490. "%s",
  10491. file_name);
  10492. }
  10493. } else {
  10494. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10495. return;
  10496. }
  10497. if (truncated) {
  10498. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10499. return;
  10500. }
  10501. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10502. mg_cry_internal(conn,
  10503. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10504. tag,
  10505. path,
  10506. strerror(ERRNO));
  10507. } else {
  10508. fclose_on_exec(&file.access, conn);
  10509. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10510. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10511. path)
  10512. > 0) {
  10513. send_ssi_file(conn, path, &file, include_level + 1);
  10514. } else {
  10515. send_file_data(conn, &file, 0, INT64_MAX);
  10516. }
  10517. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10518. }
  10519. }
  10520. #if !defined(NO_POPEN)
  10521. static void
  10522. do_ssi_exec(struct mg_connection *conn, char *tag)
  10523. {
  10524. char cmd[1024] = "";
  10525. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10526. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10527. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10528. } else {
  10529. cmd[1023] = 0;
  10530. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10531. mg_cry_internal(conn,
  10532. "Cannot SSI #exec: [%s]: %s",
  10533. cmd,
  10534. strerror(ERRNO));
  10535. } else {
  10536. send_file_data(conn, &file, 0, INT64_MAX);
  10537. pclose(file.access.fp);
  10538. }
  10539. }
  10540. }
  10541. #endif /* !NO_POPEN */
  10542. static int
  10543. mg_fgetc(struct mg_file *filep, int offset)
  10544. {
  10545. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10546. if (filep == NULL) {
  10547. return EOF;
  10548. }
  10549. #if defined(MG_USE_OPEN_FILE)
  10550. if ((filep->access.membuf != NULL) && (offset >= 0)
  10551. && (((unsigned int)(offset)) < filep->stat.size)) {
  10552. return ((const unsigned char *)filep->access.membuf)[offset];
  10553. } else /* else block below */
  10554. #endif
  10555. if (filep->access.fp != NULL) {
  10556. return fgetc(filep->access.fp);
  10557. } else {
  10558. return EOF;
  10559. }
  10560. }
  10561. static void
  10562. send_ssi_file(struct mg_connection *conn,
  10563. const char *path,
  10564. struct mg_file *filep,
  10565. int include_level)
  10566. {
  10567. char buf[MG_BUF_LEN];
  10568. int ch, offset, len, in_tag, in_ssi_tag;
  10569. if (include_level > 10) {
  10570. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10571. return;
  10572. }
  10573. in_tag = in_ssi_tag = len = offset = 0;
  10574. /* Read file, byte by byte, and look for SSI include tags */
  10575. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10576. if (in_tag) {
  10577. /* We are in a tag, either SSI tag or html tag */
  10578. if (ch == '>') {
  10579. /* Tag is closing */
  10580. buf[len++] = '>';
  10581. if (in_ssi_tag) {
  10582. /* Handle SSI tag */
  10583. buf[len] = 0;
  10584. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10585. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10586. #if !defined(NO_POPEN)
  10587. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10588. do_ssi_exec(conn, buf + 9);
  10589. #endif /* !NO_POPEN */
  10590. } else {
  10591. mg_cry_internal(conn,
  10592. "%s: unknown SSI "
  10593. "command: \"%s\"",
  10594. path,
  10595. buf);
  10596. }
  10597. len = 0;
  10598. in_ssi_tag = in_tag = 0;
  10599. } else {
  10600. /* Not an SSI tag */
  10601. /* Flush buffer */
  10602. (void)mg_write(conn, buf, (size_t)len);
  10603. len = 0;
  10604. in_tag = 0;
  10605. }
  10606. } else {
  10607. /* Tag is still open */
  10608. buf[len++] = (char)(ch & 0xff);
  10609. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10610. /* All SSI tags start with <!--# */
  10611. in_ssi_tag = 1;
  10612. }
  10613. if ((len + 2) > (int)sizeof(buf)) {
  10614. /* Tag to long for buffer */
  10615. mg_cry_internal(conn, "%s: tag is too large", path);
  10616. return;
  10617. }
  10618. }
  10619. } else {
  10620. /* We are not in a tag yet. */
  10621. if (ch == '<') {
  10622. /* Tag is opening */
  10623. in_tag = 1;
  10624. if (len > 0) {
  10625. /* Flush current buffer.
  10626. * Buffer is filled with "len" bytes. */
  10627. (void)mg_write(conn, buf, (size_t)len);
  10628. }
  10629. /* Store the < */
  10630. len = 1;
  10631. buf[0] = '<';
  10632. } else {
  10633. /* No Tag */
  10634. /* Add data to buffer */
  10635. buf[len++] = (char)(ch & 0xff);
  10636. /* Flush if buffer is full */
  10637. if (len == (int)sizeof(buf)) {
  10638. mg_write(conn, buf, (size_t)len);
  10639. len = 0;
  10640. }
  10641. }
  10642. }
  10643. }
  10644. /* Send the rest of buffered data */
  10645. if (len > 0) {
  10646. mg_write(conn, buf, (size_t)len);
  10647. }
  10648. }
  10649. static void
  10650. handle_ssi_file_request(struct mg_connection *conn,
  10651. const char *path,
  10652. struct mg_file *filep)
  10653. {
  10654. char date[64];
  10655. time_t curtime = time(NULL);
  10656. const char *cors_orig_cfg;
  10657. const char *cors1, *cors2, *cors3;
  10658. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10659. return;
  10660. }
  10661. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10662. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10663. /* Cross-origin resource sharing (CORS). */
  10664. cors1 = "Access-Control-Allow-Origin: ";
  10665. cors2 = cors_orig_cfg;
  10666. cors3 = "\r\n";
  10667. } else {
  10668. cors1 = cors2 = cors3 = "";
  10669. }
  10670. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10671. /* File exists (precondition for calling this function),
  10672. * but can not be opened by the server. */
  10673. mg_send_http_error(conn,
  10674. 500,
  10675. "Error: Cannot read file\nfopen(%s): %s",
  10676. path,
  10677. strerror(ERRNO));
  10678. } else {
  10679. conn->must_close = 1;
  10680. gmt_time_string(date, sizeof(date), &curtime);
  10681. fclose_on_exec(&filep->access, conn);
  10682. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10683. send_no_cache_header(conn);
  10684. send_additional_header(conn);
  10685. mg_printf(conn,
  10686. "%s%s%s"
  10687. "Date: %s\r\n"
  10688. "Content-Type: text/html\r\n"
  10689. "Connection: %s\r\n\r\n",
  10690. cors1,
  10691. cors2,
  10692. cors3,
  10693. date,
  10694. suggest_connection_header(conn));
  10695. send_ssi_file(conn, path, filep, 0);
  10696. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10697. }
  10698. }
  10699. #endif /* NO_FILESYSTEMS */
  10700. #if !defined(NO_FILES)
  10701. static void
  10702. send_options(struct mg_connection *conn)
  10703. {
  10704. char date[64];
  10705. time_t curtime = time(NULL);
  10706. if (!conn) {
  10707. return;
  10708. }
  10709. conn->status_code = 200;
  10710. conn->must_close = 1;
  10711. gmt_time_string(date, sizeof(date), &curtime);
  10712. /* We do not set a "Cache-Control" header here, but leave the default.
  10713. * Since browsers do not send an OPTIONS request, we can not test the
  10714. * effect anyway. */
  10715. mg_printf(conn,
  10716. "HTTP/1.1 200 OK\r\n"
  10717. "Date: %s\r\n"
  10718. "Connection: %s\r\n"
  10719. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10720. "PROPFIND, MKCOL\r\n"
  10721. "DAV: 1\r\n",
  10722. date,
  10723. suggest_connection_header(conn));
  10724. send_additional_header(conn);
  10725. mg_printf(conn, "\r\n");
  10726. }
  10727. /* Writes PROPFIND properties for a collection element */
  10728. static int
  10729. print_props(struct mg_connection *conn,
  10730. const char *uri,
  10731. const char *name,
  10732. struct mg_file_stat *filep)
  10733. {
  10734. size_t href_size, i, j;
  10735. int len;
  10736. char *href, mtime[64];
  10737. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10738. return 0;
  10739. }
  10740. /* Estimate worst case size for encoding */
  10741. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10742. href = (char *)mg_malloc(href_size);
  10743. if (href == NULL) {
  10744. return 0;
  10745. }
  10746. len = mg_url_encode(uri, href, href_size);
  10747. if (len >= 0) {
  10748. /* Append an extra string */
  10749. mg_url_encode(name, href + len, href_size - (size_t)len);
  10750. }
  10751. /* Directory separator should be preserved. */
  10752. for (i = j = 0; href[i]; j++) {
  10753. if (!strncmp(href + i, "%2f", 3)) {
  10754. href[j] = '/';
  10755. i += 3;
  10756. } else {
  10757. href[j] = href[i++];
  10758. }
  10759. }
  10760. href[j] = '\0';
  10761. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10762. mg_printf(conn,
  10763. "<d:response>"
  10764. "<d:href>%s</d:href>"
  10765. "<d:propstat>"
  10766. "<d:prop>"
  10767. "<d:resourcetype>%s</d:resourcetype>"
  10768. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10769. "<d:getlastmodified>%s</d:getlastmodified>"
  10770. "</d:prop>"
  10771. "<d:status>HTTP/1.1 200 OK</d:status>"
  10772. "</d:propstat>"
  10773. "</d:response>\n",
  10774. href,
  10775. filep->is_directory ? "<d:collection/>" : "",
  10776. filep->size,
  10777. mtime);
  10778. mg_free(href);
  10779. return 1;
  10780. }
  10781. static int
  10782. print_dav_dir_entry(struct de *de, void *data)
  10783. {
  10784. struct mg_connection *conn = (struct mg_connection *)data;
  10785. if (!de || !conn
  10786. || !print_props(
  10787. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10788. return -1;
  10789. }
  10790. return 0;
  10791. }
  10792. static void
  10793. handle_propfind(struct mg_connection *conn,
  10794. const char *path,
  10795. struct mg_file_stat *filep)
  10796. {
  10797. const char *depth = mg_get_header(conn, "Depth");
  10798. char date[64];
  10799. time_t curtime = time(NULL);
  10800. gmt_time_string(date, sizeof(date), &curtime);
  10801. if (!conn || !path || !filep || !conn->dom_ctx) {
  10802. return;
  10803. }
  10804. conn->must_close = 1;
  10805. conn->status_code = 207;
  10806. mg_printf(conn,
  10807. "HTTP/1.1 207 Multi-Status\r\n"
  10808. "Date: %s\r\n",
  10809. date);
  10810. send_static_cache_header(conn);
  10811. send_additional_header(conn);
  10812. mg_printf(conn,
  10813. "Connection: %s\r\n"
  10814. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10815. suggest_connection_header(conn));
  10816. mg_printf(conn,
  10817. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10818. "<d:multistatus xmlns:d='DAV:'>\n");
  10819. /* Print properties for the requested resource itself */
  10820. print_props(conn, conn->request_info.local_uri, "", filep);
  10821. /* If it is a directory, print directory entries too if Depth is not 0
  10822. */
  10823. if (filep->is_directory
  10824. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10825. "yes")
  10826. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10827. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10828. }
  10829. mg_printf(conn, "%s\n", "</d:multistatus>");
  10830. }
  10831. #endif
  10832. void
  10833. mg_lock_connection(struct mg_connection *conn)
  10834. {
  10835. if (conn) {
  10836. (void)pthread_mutex_lock(&conn->mutex);
  10837. }
  10838. }
  10839. void
  10840. mg_unlock_connection(struct mg_connection *conn)
  10841. {
  10842. if (conn) {
  10843. (void)pthread_mutex_unlock(&conn->mutex);
  10844. }
  10845. }
  10846. void
  10847. mg_lock_context(struct mg_context *ctx)
  10848. {
  10849. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10850. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10851. }
  10852. }
  10853. void
  10854. mg_unlock_context(struct mg_context *ctx)
  10855. {
  10856. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10857. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10858. }
  10859. }
  10860. #if defined(USE_LUA)
  10861. #include "mod_lua.inl"
  10862. #endif /* USE_LUA */
  10863. #if defined(USE_DUKTAPE)
  10864. #include "mod_duktape.inl"
  10865. #endif /* USE_DUKTAPE */
  10866. #if defined(USE_WEBSOCKET)
  10867. #if !defined(NO_SSL_DL)
  10868. #define SHA_API static
  10869. #include "sha1.inl"
  10870. #endif
  10871. static int
  10872. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10873. {
  10874. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10875. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10876. SHA_CTX sha_ctx;
  10877. int truncated;
  10878. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10879. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10880. if (truncated) {
  10881. conn->must_close = 1;
  10882. return 0;
  10883. }
  10884. DEBUG_TRACE("%s", "Send websocket handshake");
  10885. SHA1_Init(&sha_ctx);
  10886. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10887. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10888. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10889. mg_printf(conn,
  10890. "HTTP/1.1 101 Switching Protocols\r\n"
  10891. "Upgrade: websocket\r\n"
  10892. "Connection: Upgrade\r\n"
  10893. "Sec-WebSocket-Accept: %s\r\n",
  10894. b64_sha);
  10895. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10896. mg_printf(conn,
  10897. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10898. conn->request_info.acceptedWebSocketSubprotocol);
  10899. } else {
  10900. mg_printf(conn, "%s", "\r\n");
  10901. }
  10902. return 1;
  10903. }
  10904. #if !defined(MG_MAX_UNANSWERED_PING)
  10905. /* Configuration of the maximum number of websocket PINGs that might
  10906. * stay unanswered before the connection is considered broken.
  10907. * Note: The name of this define may still change (until it is
  10908. * defined as a compile parameter in a documentation).
  10909. */
  10910. #define MG_MAX_UNANSWERED_PING (5)
  10911. #endif
  10912. static void
  10913. read_websocket(struct mg_connection *conn,
  10914. mg_websocket_data_handler ws_data_handler,
  10915. void *callback_data)
  10916. {
  10917. /* Pointer to the beginning of the portion of the incoming websocket
  10918. * message queue.
  10919. * The original websocket upgrade request is never removed, so the queue
  10920. * begins after it. */
  10921. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10922. int n, error, exit_by_callback;
  10923. int ret;
  10924. /* body_len is the length of the entire queue in bytes
  10925. * len is the length of the current message
  10926. * data_len is the length of the current message's data payload
  10927. * header_len is the length of the current message's header */
  10928. size_t i, len, mask_len = 0, header_len, body_len;
  10929. uint64_t data_len = 0;
  10930. /* "The masking key is a 32-bit value chosen at random by the client."
  10931. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10932. */
  10933. unsigned char mask[4];
  10934. /* data points to the place where the message is stored when passed to
  10935. * the websocket_data callback. This is either mem on the stack, or a
  10936. * dynamically allocated buffer if it is too large. */
  10937. unsigned char mem[4096];
  10938. unsigned char mop; /* mask flag and opcode */
  10939. /* Variables used for connection monitoring */
  10940. double timeout = -1.0;
  10941. int enable_ping_pong = 0;
  10942. int ping_count = 0;
  10943. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10944. enable_ping_pong =
  10945. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10946. "yes");
  10947. }
  10948. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10949. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10950. }
  10951. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10952. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10953. }
  10954. /* Enter data processing loop */
  10955. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10956. conn->request_info.remote_addr,
  10957. conn->request_info.remote_port);
  10958. conn->in_websocket_handling = 1;
  10959. mg_set_thread_name("wsock");
  10960. /* Loop continuously, reading messages from the socket, invoking the
  10961. * callback, and waiting repeatedly until an error occurs. */
  10962. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10963. && (!conn->must_close)) {
  10964. header_len = 0;
  10965. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10966. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10967. len = buf[1] & 127;
  10968. mask_len = (buf[1] & 128) ? 4 : 0;
  10969. if ((len < 126) && (body_len >= mask_len)) {
  10970. /* inline 7-bit length field */
  10971. data_len = len;
  10972. header_len = 2 + mask_len;
  10973. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10974. /* 16-bit length field */
  10975. header_len = 4 + mask_len;
  10976. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10977. } else if (body_len >= (10 + mask_len)) {
  10978. /* 64-bit length field */
  10979. uint32_t l1, l2;
  10980. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10981. memcpy(&l2, &buf[6], 4);
  10982. header_len = 10 + mask_len;
  10983. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10984. if (data_len > (uint64_t)0x7FFF0000ul) {
  10985. /* no can do */
  10986. mg_cry_internal(
  10987. conn,
  10988. "%s",
  10989. "websocket out of memory; closing connection");
  10990. break;
  10991. }
  10992. }
  10993. }
  10994. if ((header_len > 0) && (body_len >= header_len)) {
  10995. /* Allocate space to hold websocket payload */
  10996. unsigned char *data = mem;
  10997. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10998. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10999. conn->phys_ctx);
  11000. if (data == NULL) {
  11001. /* Allocation failed, exit the loop and then close the
  11002. * connection */
  11003. mg_cry_internal(
  11004. conn,
  11005. "%s",
  11006. "websocket out of memory; closing connection");
  11007. break;
  11008. }
  11009. }
  11010. /* Copy the mask before we shift the queue and destroy it */
  11011. if (mask_len > 0) {
  11012. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11013. } else {
  11014. memset(mask, 0, sizeof(mask));
  11015. }
  11016. /* Read frame payload from the first message in the queue into
  11017. * data and advance the queue by moving the memory in place. */
  11018. DEBUG_ASSERT(body_len >= header_len);
  11019. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11020. mop = buf[0]; /* current mask and opcode */
  11021. /* Overflow case */
  11022. len = body_len - header_len;
  11023. memcpy(data, buf + header_len, len);
  11024. error = 0;
  11025. while ((uint64_t)len < data_len) {
  11026. n = pull_inner(NULL,
  11027. conn,
  11028. (char *)(data + len),
  11029. (int)(data_len - len),
  11030. timeout);
  11031. if (n <= -2) {
  11032. error = 1;
  11033. break;
  11034. } else if (n > 0) {
  11035. len += (size_t)n;
  11036. } else {
  11037. /* Timeout: should retry */
  11038. /* TODO: retry condition */
  11039. }
  11040. }
  11041. if (error) {
  11042. mg_cry_internal(
  11043. conn,
  11044. "%s",
  11045. "Websocket pull failed; closing connection");
  11046. if (data != mem) {
  11047. mg_free(data);
  11048. }
  11049. break;
  11050. }
  11051. conn->data_len = conn->request_len;
  11052. } else {
  11053. mop = buf[0]; /* current mask and opcode, overwritten by
  11054. * memmove() */
  11055. /* Length of the message being read at the front of the
  11056. * queue. Cast to 31 bit is OK, since we limited
  11057. * data_len before. */
  11058. len = (size_t)data_len + header_len;
  11059. /* Copy the data payload into the data pointer for the
  11060. * callback. Cast to 31 bit is OK, since we
  11061. * limited data_len */
  11062. memcpy(data, buf + header_len, (size_t)data_len);
  11063. /* Move the queue forward len bytes */
  11064. memmove(buf, buf + len, body_len - len);
  11065. /* Mark the queue as advanced */
  11066. conn->data_len -= (int)len;
  11067. }
  11068. /* Apply mask if necessary */
  11069. if (mask_len > 0) {
  11070. for (i = 0; i < (size_t)data_len; i++) {
  11071. data[i] ^= mask[i & 3];
  11072. }
  11073. }
  11074. exit_by_callback = 0;
  11075. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11076. /* filter PONG messages */
  11077. DEBUG_TRACE("PONG from %s:%u",
  11078. conn->request_info.remote_addr,
  11079. conn->request_info.remote_port);
  11080. /* No unanwered PINGs left */
  11081. ping_count = 0;
  11082. } else if (enable_ping_pong
  11083. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11084. /* reply PING messages */
  11085. DEBUG_TRACE("Reply PING from %s:%u",
  11086. conn->request_info.remote_addr,
  11087. conn->request_info.remote_port);
  11088. ret = mg_websocket_write(conn,
  11089. MG_WEBSOCKET_OPCODE_PONG,
  11090. (char *)data,
  11091. (size_t)data_len);
  11092. if (ret <= 0) {
  11093. /* Error: send failed */
  11094. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11095. break;
  11096. }
  11097. } else {
  11098. /* Exit the loop if callback signals to exit (server side),
  11099. * or "connection close" opcode received (client side). */
  11100. if ((ws_data_handler != NULL)
  11101. && !ws_data_handler(conn,
  11102. mop,
  11103. (char *)data,
  11104. (size_t)data_len,
  11105. callback_data)) {
  11106. exit_by_callback = 1;
  11107. }
  11108. }
  11109. /* It a buffer has been allocated, free it again */
  11110. if (data != mem) {
  11111. mg_free(data);
  11112. }
  11113. if (exit_by_callback) {
  11114. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11115. conn->request_info.remote_addr,
  11116. conn->request_info.remote_port);
  11117. break;
  11118. }
  11119. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11120. /* Opcode == 8, connection close */
  11121. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11122. conn->request_info.remote_addr,
  11123. conn->request_info.remote_port);
  11124. break;
  11125. }
  11126. /* Not breaking the loop, process next websocket frame. */
  11127. } else {
  11128. /* Read from the socket into the next available location in the
  11129. * message queue. */
  11130. n = pull_inner(NULL,
  11131. conn,
  11132. conn->buf + conn->data_len,
  11133. conn->buf_size - conn->data_len,
  11134. timeout);
  11135. if (n <= -2) {
  11136. /* Error, no bytes read */
  11137. DEBUG_TRACE("PULL from %s:%u failed",
  11138. conn->request_info.remote_addr,
  11139. conn->request_info.remote_port);
  11140. break;
  11141. }
  11142. if (n > 0) {
  11143. conn->data_len += n;
  11144. /* Reset open PING count */
  11145. ping_count = 0;
  11146. } else {
  11147. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11148. && (!conn->must_close)) {
  11149. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11150. /* Stop sending PING */
  11151. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11152. "- closing connection",
  11153. ping_count,
  11154. conn->request_info.remote_addr,
  11155. conn->request_info.remote_port);
  11156. break;
  11157. }
  11158. if (enable_ping_pong) {
  11159. /* Send Websocket PING message */
  11160. DEBUG_TRACE("PING to %s:%u",
  11161. conn->request_info.remote_addr,
  11162. conn->request_info.remote_port);
  11163. ret = mg_websocket_write(conn,
  11164. MG_WEBSOCKET_OPCODE_PING,
  11165. NULL,
  11166. 0);
  11167. if (ret <= 0) {
  11168. /* Error: send failed */
  11169. DEBUG_TRACE("Send PING failed (%i)", ret);
  11170. break;
  11171. }
  11172. ping_count++;
  11173. }
  11174. }
  11175. /* Timeout: should retry */
  11176. /* TODO: get timeout def */
  11177. }
  11178. }
  11179. }
  11180. /* Leave data processing loop */
  11181. mg_set_thread_name("worker");
  11182. conn->in_websocket_handling = 0;
  11183. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11184. conn->request_info.remote_addr,
  11185. conn->request_info.remote_port);
  11186. }
  11187. static int
  11188. mg_websocket_write_exec(struct mg_connection *conn,
  11189. int opcode,
  11190. const char *data,
  11191. size_t dataLen,
  11192. uint32_t masking_key)
  11193. {
  11194. unsigned char header[14];
  11195. size_t headerLen;
  11196. int retval;
  11197. #if defined(GCC_DIAGNOSTIC)
  11198. /* Disable spurious conversion warning for GCC */
  11199. #pragma GCC diagnostic push
  11200. #pragma GCC diagnostic ignored "-Wconversion"
  11201. #endif
  11202. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11203. #if defined(GCC_DIAGNOSTIC)
  11204. #pragma GCC diagnostic pop
  11205. #endif
  11206. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11207. if (dataLen < 126) {
  11208. /* inline 7-bit length field */
  11209. header[1] = (unsigned char)dataLen;
  11210. headerLen = 2;
  11211. } else if (dataLen <= 0xFFFF) {
  11212. /* 16-bit length field */
  11213. uint16_t len = htons((uint16_t)dataLen);
  11214. header[1] = 126;
  11215. memcpy(header + 2, &len, 2);
  11216. headerLen = 4;
  11217. } else {
  11218. /* 64-bit length field */
  11219. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11220. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11221. header[1] = 127;
  11222. memcpy(header + 2, &len1, 4);
  11223. memcpy(header + 6, &len2, 4);
  11224. headerLen = 10;
  11225. }
  11226. if (masking_key) {
  11227. /* add mask */
  11228. header[1] |= 0x80;
  11229. memcpy(header + headerLen, &masking_key, 4);
  11230. headerLen += 4;
  11231. }
  11232. /* Note that POSIX/Winsock's send() is threadsafe
  11233. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11234. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11235. * push(), although that is only a problem if the packet is large or
  11236. * outgoing buffer is full). */
  11237. /* TODO: Check if this lock should be moved to user land.
  11238. * Currently the server sets this lock for websockets, but
  11239. * not for any other connection. It must be set for every
  11240. * conn read/written by more than one thread, no matter if
  11241. * it is a websocket or regular connection. */
  11242. (void)mg_lock_connection(conn);
  11243. retval = mg_write(conn, header, headerLen);
  11244. if (retval != (int)headerLen) {
  11245. /* Did not send complete header */
  11246. retval = -1;
  11247. } else {
  11248. if (dataLen > 0) {
  11249. retval = mg_write(conn, data, dataLen);
  11250. }
  11251. /* if dataLen == 0, the header length (2) is returned */
  11252. }
  11253. /* TODO: Remove this unlock as well, when lock is removed. */
  11254. mg_unlock_connection(conn);
  11255. return retval;
  11256. }
  11257. int
  11258. mg_websocket_write(struct mg_connection *conn,
  11259. int opcode,
  11260. const char *data,
  11261. size_t dataLen)
  11262. {
  11263. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11264. }
  11265. static void
  11266. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11267. {
  11268. size_t i = 0;
  11269. i = 0;
  11270. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11271. /* Convert in 32 bit words, if data is 4 byte aligned */
  11272. while (i < (in_len - 3)) {
  11273. *(uint32_t *)(void *)(out + i) =
  11274. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11275. i += 4;
  11276. }
  11277. }
  11278. if (i != in_len) {
  11279. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11280. while (i < in_len) {
  11281. *(uint8_t *)(void *)(out + i) =
  11282. *(uint8_t *)(void *)(in + i)
  11283. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11284. i++;
  11285. }
  11286. }
  11287. }
  11288. int
  11289. mg_websocket_client_write(struct mg_connection *conn,
  11290. int opcode,
  11291. const char *data,
  11292. size_t dataLen)
  11293. {
  11294. int retval = -1;
  11295. char *masked_data =
  11296. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11297. uint32_t masking_key = 0;
  11298. if (masked_data == NULL) {
  11299. /* Return -1 in an error case */
  11300. mg_cry_internal(conn,
  11301. "%s",
  11302. "Cannot allocate buffer for masked websocket response: "
  11303. "Out of memory");
  11304. return -1;
  11305. }
  11306. do {
  11307. /* Get a masking key - but not 0 */
  11308. masking_key = (uint32_t)get_random();
  11309. } while (masking_key == 0);
  11310. mask_data(data, dataLen, masking_key, masked_data);
  11311. retval = mg_websocket_write_exec(
  11312. conn, opcode, masked_data, dataLen, masking_key);
  11313. mg_free(masked_data);
  11314. return retval;
  11315. }
  11316. static void
  11317. handle_websocket_request(struct mg_connection *conn,
  11318. const char *path,
  11319. int is_callback_resource,
  11320. struct mg_websocket_subprotocols *subprotocols,
  11321. mg_websocket_connect_handler ws_connect_handler,
  11322. mg_websocket_ready_handler ws_ready_handler,
  11323. mg_websocket_data_handler ws_data_handler,
  11324. mg_websocket_close_handler ws_close_handler,
  11325. void *cbData)
  11326. {
  11327. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11328. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11329. ptrdiff_t lua_websock = 0;
  11330. #if !defined(USE_LUA)
  11331. (void)path;
  11332. #endif
  11333. /* Step 1: Check websocket protocol version. */
  11334. /* Step 1.1: Check Sec-WebSocket-Key. */
  11335. if (!websock_key) {
  11336. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11337. * requires a Sec-WebSocket-Key header.
  11338. */
  11339. /* It could be the hixie draft version
  11340. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11341. */
  11342. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11343. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11344. char key3[8];
  11345. if ((key1 != NULL) && (key2 != NULL)) {
  11346. /* This version uses 8 byte body data in a GET request */
  11347. conn->content_len = 8;
  11348. if (8 == mg_read(conn, key3, 8)) {
  11349. /* This is the hixie version */
  11350. mg_send_http_error(conn,
  11351. 426,
  11352. "%s",
  11353. "Protocol upgrade to RFC 6455 required");
  11354. return;
  11355. }
  11356. }
  11357. /* This is an unknown version */
  11358. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11359. return;
  11360. }
  11361. /* Step 1.2: Check websocket protocol version. */
  11362. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11363. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11364. /* Reject wrong versions */
  11365. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11366. return;
  11367. }
  11368. /* Step 1.3: Could check for "Host", but we do not really nead this
  11369. * value for anything, so just ignore it. */
  11370. /* Step 2: If a callback is responsible, call it. */
  11371. if (is_callback_resource) {
  11372. /* Step 2.1 check and select subprotocol */
  11373. const char *protocols[64]; // max 64 headers
  11374. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11375. "Sec-WebSocket-Protocol",
  11376. protocols,
  11377. 64);
  11378. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11379. int cnt = 0;
  11380. int idx;
  11381. unsigned long len;
  11382. const char *sep, *curSubProtocol,
  11383. *acceptedWebSocketSubprotocol = NULL;
  11384. /* look for matching subprotocol */
  11385. do {
  11386. const char *protocol = protocols[cnt];
  11387. do {
  11388. sep = strchr(protocol, ',');
  11389. curSubProtocol = protocol;
  11390. len = sep ? (unsigned long)(sep - protocol)
  11391. : (unsigned long)strlen(protocol);
  11392. while (sep && isspace((unsigned char)*++sep))
  11393. ; // ignore leading whitespaces
  11394. protocol = sep;
  11395. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11396. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11397. && (strncmp(curSubProtocol,
  11398. subprotocols->subprotocols[idx],
  11399. len)
  11400. == 0)) {
  11401. acceptedWebSocketSubprotocol =
  11402. subprotocols->subprotocols[idx];
  11403. break;
  11404. }
  11405. }
  11406. } while (sep && !acceptedWebSocketSubprotocol);
  11407. } while (++cnt < nbSubprotocolHeader
  11408. && !acceptedWebSocketSubprotocol);
  11409. conn->request_info.acceptedWebSocketSubprotocol =
  11410. acceptedWebSocketSubprotocol;
  11411. } else if (nbSubprotocolHeader > 0) {
  11412. /* keep legacy behavior */
  11413. const char *protocol = protocols[0];
  11414. /* The protocol is a comma separated list of names. */
  11415. /* The server must only return one value from this list. */
  11416. /* First check if it is a list or just a single value. */
  11417. const char *sep = strrchr(protocol, ',');
  11418. if (sep == NULL) {
  11419. /* Just a single protocol -> accept it. */
  11420. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11421. } else {
  11422. /* Multiple protocols -> accept the last one. */
  11423. /* This is just a quick fix if the client offers multiple
  11424. * protocols. The handler should have a list of accepted
  11425. * protocols on his own
  11426. * and use it to select one protocol among those the client
  11427. * has
  11428. * offered.
  11429. */
  11430. while (isspace((unsigned char)*++sep)) {
  11431. ; /* ignore leading whitespaces */
  11432. }
  11433. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11434. }
  11435. }
  11436. if ((ws_connect_handler != NULL)
  11437. && (ws_connect_handler(conn, cbData) != 0)) {
  11438. /* C callback has returned non-zero, do not proceed with
  11439. * handshake.
  11440. */
  11441. /* Note that C callbacks are no longer called when Lua is
  11442. * responsible, so C can no longer filter callbacks for Lua. */
  11443. return;
  11444. }
  11445. }
  11446. #if defined(USE_LUA)
  11447. /* Step 3: No callback. Check if Lua is responsible. */
  11448. else {
  11449. /* Step 3.1: Check if Lua is responsible. */
  11450. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11451. lua_websock = match_prefix(
  11452. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11453. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11454. path);
  11455. }
  11456. if (lua_websock) {
  11457. /* Step 3.2: Lua is responsible: call it. */
  11458. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11459. if (!conn->lua_websocket_state) {
  11460. /* Lua rejected the new client */
  11461. return;
  11462. }
  11463. }
  11464. }
  11465. #endif
  11466. /* Step 4: Check if there is a responsible websocket handler. */
  11467. if (!is_callback_resource && !lua_websock) {
  11468. /* There is no callback, and Lua is not responsible either. */
  11469. /* Reply with a 404 Not Found. We are still at a standard
  11470. * HTTP request here, before the websocket handshake, so
  11471. * we can still send standard HTTP error replies. */
  11472. mg_send_http_error(conn, 404, "%s", "Not found");
  11473. return;
  11474. }
  11475. /* Step 5: The websocket connection has been accepted */
  11476. if (!send_websocket_handshake(conn, websock_key)) {
  11477. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11478. return;
  11479. }
  11480. /* Step 6: Call the ready handler */
  11481. if (is_callback_resource) {
  11482. if (ws_ready_handler != NULL) {
  11483. ws_ready_handler(conn, cbData);
  11484. }
  11485. #if defined(USE_LUA)
  11486. } else if (lua_websock) {
  11487. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11488. /* the ready handler returned false */
  11489. return;
  11490. }
  11491. #endif
  11492. }
  11493. /* Step 7: Enter the read loop */
  11494. if (is_callback_resource) {
  11495. read_websocket(conn, ws_data_handler, cbData);
  11496. #if defined(USE_LUA)
  11497. } else if (lua_websock) {
  11498. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11499. #endif
  11500. }
  11501. /* Step 8: Call the close handler */
  11502. if (ws_close_handler) {
  11503. ws_close_handler(conn, cbData);
  11504. }
  11505. }
  11506. #endif /* !USE_WEBSOCKET */
  11507. /* Is upgrade request:
  11508. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11509. * 1 = upgrade to websocket
  11510. * 2 = upgrade to HTTP/2
  11511. * -1 = upgrade to unknown protocol
  11512. */
  11513. static int
  11514. should_switch_to_protocol(const struct mg_connection *conn)
  11515. {
  11516. const char *upgrade, *connection;
  11517. /* A websocket protocoll has the following HTTP headers:
  11518. *
  11519. * Connection: Upgrade
  11520. * Upgrade: Websocket
  11521. */
  11522. connection = mg_get_header(conn, "Connection");
  11523. if (connection == NULL) {
  11524. return PROTOCOL_TYPE_HTTP1;
  11525. }
  11526. if (!mg_strcasestr(connection, "upgrade")) {
  11527. return PROTOCOL_TYPE_HTTP1;
  11528. }
  11529. upgrade = mg_get_header(conn, "Upgrade");
  11530. if (upgrade == NULL) {
  11531. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11532. return -1;
  11533. }
  11534. /* Upgrade to ... */
  11535. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11536. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11537. * "Sec-WebSocket-Version" are also required.
  11538. * Don't check them here, since even an unsupported websocket protocol
  11539. * request still IS a websocket request (in contrast to a standard HTTP
  11540. * request). It will fail later in handle_websocket_request.
  11541. */
  11542. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11543. }
  11544. if (0 != mg_strcasestr(upgrade, "h2")) {
  11545. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11546. }
  11547. /* Upgrade to another protocol */
  11548. return -1;
  11549. }
  11550. static int
  11551. isbyte(int n)
  11552. {
  11553. return (n >= 0) && (n <= 255);
  11554. }
  11555. static int
  11556. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11557. {
  11558. int n, a, b, c, d, slash = 32, len = 0;
  11559. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11560. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11561. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11562. && (slash < 33)) {
  11563. len = n;
  11564. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11565. | (uint32_t)d;
  11566. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11567. }
  11568. return len;
  11569. }
  11570. static int
  11571. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11572. {
  11573. int throttle = 0;
  11574. struct vec vec, val;
  11575. uint32_t net, mask;
  11576. char mult;
  11577. double v;
  11578. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11579. mult = ',';
  11580. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11581. || (v < 0)
  11582. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11583. && (mult != ','))) {
  11584. continue;
  11585. }
  11586. v *= (lowercase(&mult) == 'k')
  11587. ? 1024
  11588. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11589. if (vec.len == 1 && vec.ptr[0] == '*') {
  11590. throttle = (int)v;
  11591. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11592. if ((remote_ip & mask) == net) {
  11593. throttle = (int)v;
  11594. }
  11595. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11596. throttle = (int)v;
  11597. }
  11598. }
  11599. return throttle;
  11600. }
  11601. static uint32_t
  11602. get_remote_ip(const struct mg_connection *conn)
  11603. {
  11604. if (!conn) {
  11605. return 0;
  11606. }
  11607. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11608. }
  11609. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11610. #include "handle_form.inl"
  11611. #if defined(MG_LEGACY_INTERFACE)
  11612. /* Implement the deprecated mg_upload function by calling the new
  11613. * mg_handle_form_request function. While mg_upload could only handle
  11614. * HTML forms sent as POST request in multipart/form-data format
  11615. * containing only file input elements, mg_handle_form_request can
  11616. * handle all form input elements and all standard request methods. */
  11617. struct mg_upload_user_data {
  11618. struct mg_connection *conn;
  11619. const char *destination_dir;
  11620. int num_uploaded_files;
  11621. };
  11622. /* Helper function for deprecated mg_upload. */
  11623. static int
  11624. mg_upload_field_found(const char *key,
  11625. const char *filename,
  11626. char *path,
  11627. size_t pathlen,
  11628. void *user_data)
  11629. {
  11630. int truncated = 0;
  11631. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11632. (void)key;
  11633. if (!filename) {
  11634. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11635. return FORM_FIELD_STORAGE_ABORT;
  11636. }
  11637. mg_snprintf(fud->conn,
  11638. &truncated,
  11639. path,
  11640. pathlen - 1,
  11641. "%s/%s",
  11642. fud->destination_dir,
  11643. filename);
  11644. if (truncated) {
  11645. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11646. return FORM_FIELD_STORAGE_ABORT;
  11647. }
  11648. return FORM_FIELD_STORAGE_STORE;
  11649. }
  11650. /* Helper function for deprecated mg_upload. */
  11651. static int
  11652. mg_upload_field_get(const char *key,
  11653. const char *value,
  11654. size_t value_size,
  11655. void *user_data)
  11656. {
  11657. /* Function should never be called */
  11658. (void)key;
  11659. (void)value;
  11660. (void)value_size;
  11661. (void)user_data;
  11662. return 0;
  11663. }
  11664. /* Helper function for deprecated mg_upload. */
  11665. static int
  11666. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11667. {
  11668. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11669. (void)file_size;
  11670. fud->num_uploaded_files++;
  11671. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11672. return 0;
  11673. }
  11674. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11675. int
  11676. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11677. {
  11678. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11679. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11680. mg_upload_field_get,
  11681. mg_upload_field_stored,
  11682. 0};
  11683. int ret;
  11684. fdh.user_data = (void *)&fud;
  11685. ret = mg_handle_form_request(conn, &fdh);
  11686. if (ret < 0) {
  11687. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11688. }
  11689. return fud.num_uploaded_files;
  11690. }
  11691. #endif
  11692. static int
  11693. get_first_ssl_listener_index(const struct mg_context *ctx)
  11694. {
  11695. unsigned int i;
  11696. int idx = -1;
  11697. if (ctx) {
  11698. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11699. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11700. }
  11701. }
  11702. return idx;
  11703. }
  11704. /* Return host (without port) */
  11705. /* Use mg_free to free the result */
  11706. static const char *
  11707. alloc_get_host(struct mg_connection *conn)
  11708. {
  11709. char buf[1025];
  11710. size_t buflen = sizeof(buf);
  11711. const char *host_header = get_header(conn->request_info.http_headers,
  11712. conn->request_info.num_headers,
  11713. "Host");
  11714. char *host;
  11715. if (host_header != NULL) {
  11716. char *pos;
  11717. /* Create a local copy of the "Host" header, since it might be
  11718. * modified here. */
  11719. mg_strlcpy(buf, host_header, buflen);
  11720. buf[buflen - 1] = '\0';
  11721. host = buf;
  11722. while (isspace((unsigned char)*host)) {
  11723. host++;
  11724. }
  11725. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11726. * is found. */
  11727. if (*host == '[') {
  11728. pos = strchr(host, ']');
  11729. if (!pos) {
  11730. /* Malformed hostname starts with '[', but no ']' found */
  11731. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11732. return NULL;
  11733. }
  11734. /* terminate after ']' */
  11735. pos[1] = 0;
  11736. } else {
  11737. /* Otherwise, a ':' separates hostname and port number */
  11738. pos = strchr(host, ':');
  11739. if (pos != NULL) {
  11740. *pos = '\0';
  11741. }
  11742. }
  11743. if (conn->ssl) {
  11744. /* This is a HTTPS connection, maybe we have a hostname
  11745. * from SNI (set in ssl_servername_callback). */
  11746. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11747. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11748. /* We are not using the default domain */
  11749. if (mg_strcasecmp(host, sslhost)) {
  11750. /* Mismatch between SNI domain and HTTP domain */
  11751. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11752. sslhost,
  11753. host);
  11754. return NULL;
  11755. }
  11756. }
  11757. DEBUG_TRACE("HTTPS Host: %s", host);
  11758. } else {
  11759. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11760. while (dom) {
  11761. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11762. /* Found matching domain */
  11763. DEBUG_TRACE("HTTP domain %s found",
  11764. dom->config[AUTHENTICATION_DOMAIN]);
  11765. /* TODO: Check if this is a HTTP or HTTPS domain */
  11766. conn->dom_ctx = dom;
  11767. break;
  11768. }
  11769. mg_lock_context(conn->phys_ctx);
  11770. dom = dom->next;
  11771. mg_unlock_context(conn->phys_ctx);
  11772. }
  11773. DEBUG_TRACE("HTTP Host: %s", host);
  11774. }
  11775. } else {
  11776. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11777. host = buf;
  11778. DEBUG_TRACE("IP: %s", host);
  11779. }
  11780. return mg_strdup_ctx(host, conn->phys_ctx);
  11781. }
  11782. static void
  11783. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11784. {
  11785. char target_url[MG_BUF_LEN];
  11786. int truncated = 0;
  11787. conn->must_close = 1;
  11788. /* Send host, port, uri and (if it exists) ?query_string */
  11789. if (conn->host) {
  11790. /* Use "308 Permanent Redirect" */
  11791. int redirect_code = 308;
  11792. /* Create target URL */
  11793. mg_snprintf(
  11794. conn,
  11795. &truncated,
  11796. target_url,
  11797. sizeof(target_url),
  11798. "https://%s:%d%s%s%s",
  11799. conn->host,
  11800. #if defined(USE_IPV6)
  11801. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11802. == AF_INET6)
  11803. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11804. .lsa.sin6.sin6_port)
  11805. :
  11806. #endif
  11807. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11808. .lsa.sin.sin_port),
  11809. conn->request_info.local_uri,
  11810. (conn->request_info.query_string == NULL) ? "" : "?",
  11811. (conn->request_info.query_string == NULL)
  11812. ? ""
  11813. : conn->request_info.query_string);
  11814. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11815. * is used as buffer size) */
  11816. if (truncated) {
  11817. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11818. return;
  11819. }
  11820. /* Use redirect helper function */
  11821. mg_send_http_redirect(conn, target_url, redirect_code);
  11822. }
  11823. }
  11824. static void
  11825. mg_set_handler_type(struct mg_context *phys_ctx,
  11826. struct mg_domain_context *dom_ctx,
  11827. const char *uri,
  11828. int handler_type,
  11829. int is_delete_request,
  11830. mg_request_handler handler,
  11831. struct mg_websocket_subprotocols *subprotocols,
  11832. mg_websocket_connect_handler connect_handler,
  11833. mg_websocket_ready_handler ready_handler,
  11834. mg_websocket_data_handler data_handler,
  11835. mg_websocket_close_handler close_handler,
  11836. mg_authorization_handler auth_handler,
  11837. void *cbdata)
  11838. {
  11839. struct mg_handler_info *tmp_rh, **lastref;
  11840. size_t urilen = strlen(uri);
  11841. if (handler_type == WEBSOCKET_HANDLER) {
  11842. DEBUG_ASSERT(handler == NULL);
  11843. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11844. || ready_handler != NULL || data_handler != NULL
  11845. || close_handler != NULL);
  11846. DEBUG_ASSERT(auth_handler == NULL);
  11847. if (handler != NULL) {
  11848. return;
  11849. }
  11850. if (!is_delete_request && (connect_handler == NULL)
  11851. && (ready_handler == NULL) && (data_handler == NULL)
  11852. && (close_handler == NULL)) {
  11853. return;
  11854. }
  11855. if (auth_handler != NULL) {
  11856. return;
  11857. }
  11858. } else if (handler_type == REQUEST_HANDLER) {
  11859. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11860. && data_handler == NULL && close_handler == NULL);
  11861. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11862. DEBUG_ASSERT(auth_handler == NULL);
  11863. if ((connect_handler != NULL) || (ready_handler != NULL)
  11864. || (data_handler != NULL) || (close_handler != NULL)) {
  11865. return;
  11866. }
  11867. if (!is_delete_request && (handler == NULL)) {
  11868. return;
  11869. }
  11870. if (auth_handler != NULL) {
  11871. return;
  11872. }
  11873. } else { /* AUTH_HANDLER */
  11874. DEBUG_ASSERT(handler == NULL);
  11875. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11876. && data_handler == NULL && close_handler == NULL);
  11877. DEBUG_ASSERT(auth_handler != NULL);
  11878. if (handler != NULL) {
  11879. return;
  11880. }
  11881. if ((connect_handler != NULL) || (ready_handler != NULL)
  11882. || (data_handler != NULL) || (close_handler != NULL)) {
  11883. return;
  11884. }
  11885. if (!is_delete_request && (auth_handler == NULL)) {
  11886. return;
  11887. }
  11888. }
  11889. if (!phys_ctx || !dom_ctx) {
  11890. return;
  11891. }
  11892. mg_lock_context(phys_ctx);
  11893. /* first try to find an existing handler */
  11894. do {
  11895. lastref = &(dom_ctx->handlers);
  11896. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11897. if (tmp_rh->handler_type == handler_type
  11898. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11899. if (!is_delete_request) {
  11900. /* update existing handler */
  11901. if (handler_type == REQUEST_HANDLER) {
  11902. /* Wait for end of use before updating */
  11903. if (tmp_rh->refcount) {
  11904. mg_unlock_context(phys_ctx);
  11905. mg_sleep(1);
  11906. mg_lock_context(phys_ctx);
  11907. /* tmp_rh might have been freed, search again. */
  11908. break;
  11909. }
  11910. /* Ok, the handler is no more use -> Update it */
  11911. tmp_rh->handler = handler;
  11912. } else if (handler_type == WEBSOCKET_HANDLER) {
  11913. tmp_rh->subprotocols = subprotocols;
  11914. tmp_rh->connect_handler = connect_handler;
  11915. tmp_rh->ready_handler = ready_handler;
  11916. tmp_rh->data_handler = data_handler;
  11917. tmp_rh->close_handler = close_handler;
  11918. } else { /* AUTH_HANDLER */
  11919. tmp_rh->auth_handler = auth_handler;
  11920. }
  11921. tmp_rh->cbdata = cbdata;
  11922. } else {
  11923. /* remove existing handler */
  11924. if (handler_type == REQUEST_HANDLER) {
  11925. /* Wait for end of use before removing */
  11926. if (tmp_rh->refcount) {
  11927. tmp_rh->removing = 1;
  11928. mg_unlock_context(phys_ctx);
  11929. mg_sleep(1);
  11930. mg_lock_context(phys_ctx);
  11931. /* tmp_rh might have been freed, search again. */
  11932. break;
  11933. }
  11934. /* Ok, the handler is no more used */
  11935. }
  11936. *lastref = tmp_rh->next;
  11937. mg_free(tmp_rh->uri);
  11938. mg_free(tmp_rh);
  11939. }
  11940. mg_unlock_context(phys_ctx);
  11941. return;
  11942. }
  11943. lastref = &(tmp_rh->next);
  11944. }
  11945. } while (tmp_rh != NULL);
  11946. if (is_delete_request) {
  11947. /* no handler to set, this was a remove request to a non-existing
  11948. * handler */
  11949. mg_unlock_context(phys_ctx);
  11950. return;
  11951. }
  11952. tmp_rh =
  11953. (struct mg_handler_info *)mg_calloc_ctx(1,
  11954. sizeof(struct mg_handler_info),
  11955. phys_ctx);
  11956. if (tmp_rh == NULL) {
  11957. mg_unlock_context(phys_ctx);
  11958. mg_cry_ctx_internal(phys_ctx,
  11959. "%s",
  11960. "Cannot create new request handler struct, OOM");
  11961. return;
  11962. }
  11963. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11964. if (!tmp_rh->uri) {
  11965. mg_unlock_context(phys_ctx);
  11966. mg_free(tmp_rh);
  11967. mg_cry_ctx_internal(phys_ctx,
  11968. "%s",
  11969. "Cannot create new request handler struct, OOM");
  11970. return;
  11971. }
  11972. tmp_rh->uri_len = urilen;
  11973. if (handler_type == REQUEST_HANDLER) {
  11974. tmp_rh->refcount = 0;
  11975. tmp_rh->removing = 0;
  11976. tmp_rh->handler = handler;
  11977. } else if (handler_type == WEBSOCKET_HANDLER) {
  11978. tmp_rh->subprotocols = subprotocols;
  11979. tmp_rh->connect_handler = connect_handler;
  11980. tmp_rh->ready_handler = ready_handler;
  11981. tmp_rh->data_handler = data_handler;
  11982. tmp_rh->close_handler = close_handler;
  11983. } else { /* AUTH_HANDLER */
  11984. tmp_rh->auth_handler = auth_handler;
  11985. }
  11986. tmp_rh->cbdata = cbdata;
  11987. tmp_rh->handler_type = handler_type;
  11988. tmp_rh->next = NULL;
  11989. *lastref = tmp_rh;
  11990. mg_unlock_context(phys_ctx);
  11991. }
  11992. void
  11993. mg_set_request_handler(struct mg_context *ctx,
  11994. const char *uri,
  11995. mg_request_handler handler,
  11996. void *cbdata)
  11997. {
  11998. mg_set_handler_type(ctx,
  11999. &(ctx->dd),
  12000. uri,
  12001. REQUEST_HANDLER,
  12002. handler == NULL,
  12003. handler,
  12004. NULL,
  12005. NULL,
  12006. NULL,
  12007. NULL,
  12008. NULL,
  12009. NULL,
  12010. cbdata);
  12011. }
  12012. void
  12013. mg_set_websocket_handler(struct mg_context *ctx,
  12014. const char *uri,
  12015. mg_websocket_connect_handler connect_handler,
  12016. mg_websocket_ready_handler ready_handler,
  12017. mg_websocket_data_handler data_handler,
  12018. mg_websocket_close_handler close_handler,
  12019. void *cbdata)
  12020. {
  12021. mg_set_websocket_handler_with_subprotocols(ctx,
  12022. uri,
  12023. NULL,
  12024. connect_handler,
  12025. ready_handler,
  12026. data_handler,
  12027. close_handler,
  12028. cbdata);
  12029. }
  12030. void
  12031. mg_set_websocket_handler_with_subprotocols(
  12032. struct mg_context *ctx,
  12033. const char *uri,
  12034. struct mg_websocket_subprotocols *subprotocols,
  12035. mg_websocket_connect_handler connect_handler,
  12036. mg_websocket_ready_handler ready_handler,
  12037. mg_websocket_data_handler data_handler,
  12038. mg_websocket_close_handler close_handler,
  12039. void *cbdata)
  12040. {
  12041. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12042. && (data_handler == NULL)
  12043. && (close_handler == NULL);
  12044. mg_set_handler_type(ctx,
  12045. &(ctx->dd),
  12046. uri,
  12047. WEBSOCKET_HANDLER,
  12048. is_delete_request,
  12049. NULL,
  12050. subprotocols,
  12051. connect_handler,
  12052. ready_handler,
  12053. data_handler,
  12054. close_handler,
  12055. NULL,
  12056. cbdata);
  12057. }
  12058. void
  12059. mg_set_auth_handler(struct mg_context *ctx,
  12060. const char *uri,
  12061. mg_authorization_handler handler,
  12062. void *cbdata)
  12063. {
  12064. mg_set_handler_type(ctx,
  12065. &(ctx->dd),
  12066. uri,
  12067. AUTH_HANDLER,
  12068. handler == NULL,
  12069. NULL,
  12070. NULL,
  12071. NULL,
  12072. NULL,
  12073. NULL,
  12074. NULL,
  12075. handler,
  12076. cbdata);
  12077. }
  12078. static int
  12079. get_request_handler(struct mg_connection *conn,
  12080. int handler_type,
  12081. mg_request_handler *handler,
  12082. struct mg_websocket_subprotocols **subprotocols,
  12083. mg_websocket_connect_handler *connect_handler,
  12084. mg_websocket_ready_handler *ready_handler,
  12085. mg_websocket_data_handler *data_handler,
  12086. mg_websocket_close_handler *close_handler,
  12087. mg_authorization_handler *auth_handler,
  12088. void **cbdata,
  12089. struct mg_handler_info **handler_info)
  12090. {
  12091. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12092. if (request_info) {
  12093. const char *uri = request_info->local_uri;
  12094. size_t urilen = strlen(uri);
  12095. struct mg_handler_info *tmp_rh;
  12096. int step, matched;
  12097. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12098. return 0;
  12099. }
  12100. mg_lock_context(conn->phys_ctx);
  12101. for (step = 0; step < 3; step++) {
  12102. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12103. tmp_rh = tmp_rh->next) {
  12104. if (tmp_rh->handler_type != handler_type) {
  12105. continue;
  12106. }
  12107. if (step == 0) {
  12108. /* first try for an exact match */
  12109. matched = (tmp_rh->uri_len == urilen)
  12110. && (strcmp(tmp_rh->uri, uri) == 0);
  12111. } else if (step == 1) {
  12112. /* next try for a partial match, we will accept
  12113. uri/something */
  12114. matched = (tmp_rh->uri_len < urilen)
  12115. && (uri[tmp_rh->uri_len] == '/')
  12116. && (memcmp(tmp_rh->uri, uri,
  12117. tmp_rh->uri_len) == 0);
  12118. } else {
  12119. /* finally try for pattern match */
  12120. matched = match_prefix(tmp_rh->uri,
  12121. tmp_rh->uri_len, uri) > 0;
  12122. }
  12123. if (matched) {
  12124. if (handler_type == WEBSOCKET_HANDLER) {
  12125. *subprotocols = tmp_rh->subprotocols;
  12126. *connect_handler = tmp_rh->connect_handler;
  12127. *ready_handler = tmp_rh->ready_handler;
  12128. *data_handler = tmp_rh->data_handler;
  12129. *close_handler = tmp_rh->close_handler;
  12130. } else if (handler_type == REQUEST_HANDLER) {
  12131. if (tmp_rh->removing) {
  12132. /* Treat as none found */
  12133. step = 2;
  12134. break;
  12135. }
  12136. *handler = tmp_rh->handler;
  12137. /* Acquire handler and give it back */
  12138. tmp_rh->refcount++;
  12139. *handler_info = tmp_rh;
  12140. } else { /* AUTH_HANDLER */
  12141. *auth_handler = tmp_rh->auth_handler;
  12142. }
  12143. *cbdata = tmp_rh->cbdata;
  12144. mg_unlock_context(conn->phys_ctx);
  12145. return 1;
  12146. }
  12147. }
  12148. }
  12149. mg_unlock_context(conn->phys_ctx);
  12150. }
  12151. return 0; /* none found */
  12152. }
  12153. /* Check if the script file is in a path, allowed for script files.
  12154. * This can be used if uploading files is possible not only for the server
  12155. * admin, and the upload mechanism does not check the file extension.
  12156. */
  12157. static int
  12158. is_in_script_path(const struct mg_connection *conn, const char *path)
  12159. {
  12160. /* TODO (Feature): Add config value for allowed script path.
  12161. * Default: All allowed. */
  12162. (void)conn;
  12163. (void)path;
  12164. return 1;
  12165. }
  12166. #if defined(USE_WEBSOCKET) \
  12167. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12168. static int
  12169. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12170. void *cbdata)
  12171. {
  12172. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12173. if (pcallbacks->websocket_connect) {
  12174. return pcallbacks->websocket_connect(conn);
  12175. }
  12176. /* No handler set - assume "OK" */
  12177. return 0;
  12178. }
  12179. static void
  12180. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12181. {
  12182. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12183. if (pcallbacks->websocket_ready) {
  12184. pcallbacks->websocket_ready(conn);
  12185. }
  12186. }
  12187. static int
  12188. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12189. int bits,
  12190. char *data,
  12191. size_t len,
  12192. void *cbdata)
  12193. {
  12194. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12195. if (pcallbacks->websocket_data) {
  12196. return pcallbacks->websocket_data(conn, bits, data, len);
  12197. }
  12198. /* No handler set - assume "OK" */
  12199. return 1;
  12200. }
  12201. static void
  12202. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12203. void *cbdata)
  12204. {
  12205. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12206. if (pcallbacks->connection_close) {
  12207. pcallbacks->connection_close(conn);
  12208. }
  12209. }
  12210. #endif
  12211. /* This is the heart of the Civetweb's logic.
  12212. * This function is called when the request is read, parsed and validated,
  12213. * and Civetweb must decide what action to take: serve a file, or
  12214. * a directory, or call embedded function, etcetera. */
  12215. static void
  12216. handle_request(struct mg_connection *conn)
  12217. {
  12218. struct mg_request_info *ri = &conn->request_info;
  12219. char path[PATH_MAX];
  12220. int uri_len, ssl_index;
  12221. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12222. is_put_or_delete_request = 0, is_callback_resource = 0;
  12223. int i;
  12224. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12225. mg_request_handler callback_handler = NULL;
  12226. struct mg_handler_info *handler_info = NULL;
  12227. struct mg_websocket_subprotocols *subprotocols;
  12228. mg_websocket_connect_handler ws_connect_handler = NULL;
  12229. mg_websocket_ready_handler ws_ready_handler = NULL;
  12230. mg_websocket_data_handler ws_data_handler = NULL;
  12231. mg_websocket_close_handler ws_close_handler = NULL;
  12232. void *callback_data = NULL;
  12233. mg_authorization_handler auth_handler = NULL;
  12234. void *auth_callback_data = NULL;
  12235. int handler_type;
  12236. time_t curtime = time(NULL);
  12237. char date[64];
  12238. path[0] = 0;
  12239. /* 1. get the request url */
  12240. /* 1.1. split into url and query string */
  12241. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12242. != NULL) {
  12243. *((char *)conn->request_info.query_string++) = '\0';
  12244. }
  12245. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12246. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12247. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12248. if (ssl_index >= 0) {
  12249. redirect_to_https_port(conn, ssl_index);
  12250. } else {
  12251. /* A http to https forward port has been specified,
  12252. * but no https port to forward to. */
  12253. mg_send_http_error(conn,
  12254. 503,
  12255. "%s",
  12256. "Error: SSL forward not configured properly");
  12257. mg_cry_internal(conn,
  12258. "%s",
  12259. "Can not redirect to SSL, no SSL port available");
  12260. }
  12261. return;
  12262. }
  12263. uri_len = (int)strlen(ri->local_uri);
  12264. /* 1.3. decode url (if config says so) */
  12265. if (should_decode_url(conn)) {
  12266. mg_url_decode(
  12267. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12268. }
  12269. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12270. * not possible */
  12271. remove_dot_segments((char *)ri->local_uri);
  12272. /* step 1. completed, the url is known now */
  12273. uri_len = (int)strlen(ri->local_uri);
  12274. DEBUG_TRACE("URL: %s", ri->local_uri);
  12275. /* 2. if this ip has limited speed, set it for this connection */
  12276. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12277. get_remote_ip(conn),
  12278. ri->local_uri);
  12279. /* 3. call a "handle everything" callback, if registered */
  12280. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12281. /* Note that since V1.7 the "begin_request" function is called
  12282. * before an authorization check. If an authorization check is
  12283. * required, use a request_handler instead. */
  12284. i = conn->phys_ctx->callbacks.begin_request(conn);
  12285. if (i > 0) {
  12286. /* callback already processed the request. Store the
  12287. return value as a status code for the access log. */
  12288. conn->status_code = i;
  12289. if (!conn->must_close) {
  12290. discard_unread_request_data(conn);
  12291. }
  12292. return;
  12293. } else if (i == 0) {
  12294. /* civetweb should process the request */
  12295. } else {
  12296. /* unspecified - may change with the next version */
  12297. return;
  12298. }
  12299. }
  12300. /* request not yet handled by a handler or redirect, so the request
  12301. * is processed here */
  12302. /* 4. Check for CORS preflight requests and handle them (if configured).
  12303. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12304. */
  12305. if (!strcmp(ri->request_method, "OPTIONS")) {
  12306. /* Send a response to CORS preflights only if
  12307. * access_control_allow_methods is not NULL and not an empty string.
  12308. * In this case, scripts can still handle CORS. */
  12309. const char *cors_meth_cfg =
  12310. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12311. const char *cors_orig_cfg =
  12312. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12313. const char *cors_origin =
  12314. get_header(ri->http_headers, ri->num_headers, "Origin");
  12315. const char *cors_acrm = get_header(ri->http_headers,
  12316. ri->num_headers,
  12317. "Access-Control-Request-Method");
  12318. /* Todo: check if cors_origin is in cors_orig_cfg.
  12319. * Or, let the client check this. */
  12320. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12321. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12322. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12323. /* This is a valid CORS preflight, and the server is configured
  12324. * to
  12325. * handle it automatically. */
  12326. const char *cors_acrh =
  12327. get_header(ri->http_headers,
  12328. ri->num_headers,
  12329. "Access-Control-Request-Headers");
  12330. gmt_time_string(date, sizeof(date), &curtime);
  12331. mg_printf(conn,
  12332. "HTTP/1.1 200 OK\r\n"
  12333. "Date: %s\r\n"
  12334. "Access-Control-Allow-Origin: %s\r\n"
  12335. "Access-Control-Allow-Methods: %s\r\n"
  12336. "Content-Length: 0\r\n"
  12337. "Connection: %s\r\n",
  12338. date,
  12339. cors_orig_cfg,
  12340. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12341. suggest_connection_header(conn));
  12342. if (cors_acrh != NULL) {
  12343. /* CORS request is asking for additional headers */
  12344. const char *cors_hdr_cfg =
  12345. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12346. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12347. /* Allow only if access_control_allow_headers is
  12348. * not NULL and not an empty string. If this
  12349. * configuration is set to *, allow everything.
  12350. * Otherwise this configuration must be a list
  12351. * of allowed HTTP header names. */
  12352. mg_printf(conn,
  12353. "Access-Control-Allow-Headers: %s\r\n",
  12354. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12355. : cors_hdr_cfg));
  12356. }
  12357. }
  12358. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12359. mg_printf(conn, "\r\n");
  12360. return;
  12361. }
  12362. }
  12363. /* 5. interpret the url to find out how the request must be handled
  12364. */
  12365. /* 5.1. first test, if the request targets the regular http(s)://
  12366. * protocol namespace or the websocket ws(s):// protocol namespace.
  12367. */
  12368. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12369. #if defined(USE_WEBSOCKET)
  12370. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12371. #else
  12372. handler_type = REQUEST_HANDLER;
  12373. #endif /* defined(USE_WEBSOCKET) */
  12374. /* 5.2. check if the request will be handled by a callback */
  12375. if (get_request_handler(conn,
  12376. handler_type,
  12377. &callback_handler,
  12378. &subprotocols,
  12379. &ws_connect_handler,
  12380. &ws_ready_handler,
  12381. &ws_data_handler,
  12382. &ws_close_handler,
  12383. NULL,
  12384. &callback_data,
  12385. &handler_info)) {
  12386. /* 5.2.1. A callback will handle this request. All requests
  12387. * handled
  12388. * by a callback have to be considered as requests to a script
  12389. * resource. */
  12390. is_callback_resource = 1;
  12391. is_script_resource = 1;
  12392. is_put_or_delete_request = is_put_or_delete_method(conn);
  12393. } else {
  12394. no_callback_resource:
  12395. /* 5.2.2. No callback is responsible for this request. The URI
  12396. * addresses a file based resource (static content or Lua/cgi
  12397. * scripts in the file system). */
  12398. is_callback_resource = 0;
  12399. interpret_uri(conn,
  12400. path,
  12401. sizeof(path),
  12402. &file.stat,
  12403. &is_found,
  12404. &is_script_resource,
  12405. &is_websocket_request,
  12406. &is_put_or_delete_request);
  12407. }
  12408. /* 6. authorization check */
  12409. /* 6.1. a custom authorization handler is installed */
  12410. if (get_request_handler(conn,
  12411. AUTH_HANDLER,
  12412. NULL,
  12413. NULL,
  12414. NULL,
  12415. NULL,
  12416. NULL,
  12417. NULL,
  12418. &auth_handler,
  12419. &auth_callback_data,
  12420. NULL)) {
  12421. if (!auth_handler(conn, auth_callback_data)) {
  12422. return;
  12423. }
  12424. } else if (is_put_or_delete_request && !is_script_resource
  12425. && !is_callback_resource) {
  12426. /* 6.2. this request is a PUT/DELETE to a real file */
  12427. /* 6.2.1. thus, the server must have real files */
  12428. #if defined(NO_FILES)
  12429. if (1) {
  12430. #else
  12431. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12432. #endif
  12433. /* This server does not have any real files, thus the
  12434. * PUT/DELETE methods are not valid. */
  12435. mg_send_http_error(conn,
  12436. 405,
  12437. "%s method not allowed",
  12438. conn->request_info.request_method);
  12439. return;
  12440. }
  12441. #if !defined(NO_FILES)
  12442. /* 6.2.2. Check if put authorization for static files is
  12443. * available.
  12444. */
  12445. if (!is_authorized_for_put(conn)) {
  12446. send_authorization_request(conn, NULL);
  12447. return;
  12448. }
  12449. #endif
  12450. } else {
  12451. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12452. * or it is a PUT or DELETE request to a resource that does not
  12453. * correspond to a file. Check authorization. */
  12454. if (!check_authorization(conn, path)) {
  12455. send_authorization_request(conn, NULL);
  12456. return;
  12457. }
  12458. }
  12459. /* request is authorized or does not need authorization */
  12460. /* 7. check if there are request handlers for this uri */
  12461. if (is_callback_resource) {
  12462. if (!is_websocket_request) {
  12463. i = callback_handler(conn, callback_data);
  12464. /* Callback handler will not be used anymore. Release it */
  12465. mg_lock_context(conn->phys_ctx);
  12466. handler_info->refcount--;
  12467. mg_unlock_context(conn->phys_ctx);
  12468. if (i > 0) {
  12469. /* Do nothing, callback has served the request. Store
  12470. * then return value as status code for the log and discard
  12471. * all data from the client not used by the callback. */
  12472. conn->status_code = i;
  12473. if (!conn->must_close) {
  12474. discard_unread_request_data(conn);
  12475. }
  12476. } else {
  12477. /* The handler did NOT handle the request. */
  12478. /* Some proper reactions would be:
  12479. * a) close the connections without sending anything
  12480. * b) send a 404 not found
  12481. * c) try if there is a file matching the URI
  12482. * It would be possible to do a, b or c in the callback
  12483. * implementation, and return 1 - we cannot do anything
  12484. * here, that is not possible in the callback.
  12485. *
  12486. * TODO: What would be the best reaction here?
  12487. * (Note: The reaction may change, if there is a better
  12488. *idea.)
  12489. */
  12490. /* For the moment, use option c: We look for a proper file,
  12491. * but since a file request is not always a script resource,
  12492. * the authorization check might be different. */
  12493. interpret_uri(conn,
  12494. path,
  12495. sizeof(path),
  12496. &file.stat,
  12497. &is_found,
  12498. &is_script_resource,
  12499. &is_websocket_request,
  12500. &is_put_or_delete_request);
  12501. callback_handler = NULL;
  12502. /* Here we are at a dead end:
  12503. * According to URI matching, a callback should be
  12504. * responsible for handling the request,
  12505. * we called it, but the callback declared itself
  12506. * not responsible.
  12507. * We use a goto here, to get out of this dead end,
  12508. * and continue with the default handling.
  12509. * A goto here is simpler and better to understand
  12510. * than some curious loop. */
  12511. goto no_callback_resource;
  12512. }
  12513. } else {
  12514. #if defined(USE_WEBSOCKET)
  12515. handle_websocket_request(conn,
  12516. path,
  12517. is_callback_resource,
  12518. subprotocols,
  12519. ws_connect_handler,
  12520. ws_ready_handler,
  12521. ws_data_handler,
  12522. ws_close_handler,
  12523. callback_data);
  12524. #endif
  12525. }
  12526. return;
  12527. }
  12528. /* 8. handle websocket requests */
  12529. #if defined(USE_WEBSOCKET)
  12530. if (is_websocket_request) {
  12531. if (is_script_resource) {
  12532. if (is_in_script_path(conn, path)) {
  12533. /* Websocket Lua script */
  12534. handle_websocket_request(conn,
  12535. path,
  12536. 0 /* Lua Script */,
  12537. NULL,
  12538. NULL,
  12539. NULL,
  12540. NULL,
  12541. NULL,
  12542. conn->phys_ctx->user_data);
  12543. } else {
  12544. /* Script was in an illegal path */
  12545. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12546. }
  12547. } else {
  12548. #if defined(MG_LEGACY_INTERFACE)
  12549. handle_websocket_request(
  12550. conn,
  12551. path,
  12552. !is_script_resource /* could be deprecated global callback
  12553. */
  12554. ,
  12555. NULL,
  12556. deprecated_websocket_connect_wrapper,
  12557. deprecated_websocket_ready_wrapper,
  12558. deprecated_websocket_data_wrapper,
  12559. NULL,
  12560. conn->phys_ctx->callbacks);
  12561. #else
  12562. mg_send_http_error(conn, 404, "%s", "Not found");
  12563. #endif
  12564. }
  12565. return;
  12566. } else
  12567. #endif
  12568. #if defined(NO_FILES)
  12569. /* 9a. In case the server uses only callbacks, this uri is
  12570. * unknown.
  12571. * Then, all request handling ends here. */
  12572. mg_send_http_error(conn, 404, "%s", "Not Found");
  12573. #else
  12574. /* 9b. This request is either for a static file or resource handled
  12575. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12576. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12577. mg_send_http_error(conn, 404, "%s", "Not Found");
  12578. return;
  12579. }
  12580. /* 10. Request is handled by a script */
  12581. if (is_script_resource) {
  12582. handle_file_based_request(conn, path, &file);
  12583. return;
  12584. }
  12585. /* 11. Handle put/delete/mkcol requests */
  12586. if (is_put_or_delete_request) {
  12587. /* 11.1. PUT method */
  12588. if (!strcmp(ri->request_method, "PUT")) {
  12589. put_file(conn, path);
  12590. return;
  12591. }
  12592. /* 11.2. DELETE method */
  12593. if (!strcmp(ri->request_method, "DELETE")) {
  12594. delete_file(conn, path);
  12595. return;
  12596. }
  12597. /* 11.3. MKCOL method */
  12598. if (!strcmp(ri->request_method, "MKCOL")) {
  12599. mkcol(conn, path);
  12600. return;
  12601. }
  12602. /* 11.4. PATCH method
  12603. * This method is not supported for static resources,
  12604. * only for scripts (Lua, CGI) and callbacks. */
  12605. mg_send_http_error(conn,
  12606. 405,
  12607. "%s method not allowed",
  12608. conn->request_info.request_method);
  12609. return;
  12610. }
  12611. /* 11. File does not exist, or it was configured that it should be
  12612. * hidden */
  12613. if (!is_found || (must_hide_file(conn, path))) {
  12614. mg_send_http_error(conn, 404, "%s", "Not found");
  12615. return;
  12616. }
  12617. /* 12. Directory uris should end with a slash */
  12618. if (file.stat.is_directory && (uri_len > 0)
  12619. && (ri->local_uri[uri_len - 1] != '/')) {
  12620. gmt_time_string(date, sizeof(date), &curtime);
  12621. mg_printf(conn,
  12622. "HTTP/1.1 301 Moved Permanently\r\n"
  12623. "Location: %s/\r\n"
  12624. "Date: %s\r\n"
  12625. /* "Cache-Control: private\r\n" (= default) */
  12626. "Content-Length: 0\r\n"
  12627. "Connection: %s\r\n",
  12628. ri->request_uri,
  12629. date,
  12630. suggest_connection_header(conn));
  12631. send_additional_header(conn);
  12632. mg_printf(conn, "\r\n");
  12633. return;
  12634. }
  12635. /* 13. Handle other methods than GET/HEAD */
  12636. /* 13.1. Handle PROPFIND */
  12637. if (!strcmp(ri->request_method, "PROPFIND")) {
  12638. handle_propfind(conn, path, &file.stat);
  12639. return;
  12640. }
  12641. /* 13.2. Handle OPTIONS for files */
  12642. if (!strcmp(ri->request_method, "OPTIONS")) {
  12643. /* This standard handler is only used for real files.
  12644. * Scripts should support the OPTIONS method themselves, to allow a
  12645. * maximum flexibility.
  12646. * Lua and CGI scripts may fully support CORS this way (including
  12647. * preflights). */
  12648. send_options(conn);
  12649. return;
  12650. }
  12651. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12652. if ((0 != strcmp(ri->request_method, "GET"))
  12653. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12654. mg_send_http_error(conn,
  12655. 405,
  12656. "%s method not allowed",
  12657. conn->request_info.request_method);
  12658. return;
  12659. }
  12660. /* 14. directories */
  12661. if (file.stat.is_directory) {
  12662. /* Substitute files have already been handled above. */
  12663. /* Here we can either generate and send a directory listing,
  12664. * or send an "access denied" error. */
  12665. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12666. "yes")) {
  12667. handle_directory_request(conn, path);
  12668. } else {
  12669. mg_send_http_error(conn,
  12670. 403,
  12671. "%s",
  12672. "Error: Directory listing denied");
  12673. }
  12674. return;
  12675. }
  12676. /* 15. read a normal file with GET or HEAD */
  12677. handle_file_based_request(conn, path, &file);
  12678. #endif /* !defined(NO_FILES) */
  12679. }
  12680. /* Include HTTP/2 modules */
  12681. #ifdef USE_HTTP2
  12682. #if defined(NO_SSL)
  12683. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  12684. #endif
  12685. #include "mod_http2.inl"
  12686. #endif
  12687. #if !defined(NO_FILESYSTEMS)
  12688. static void
  12689. handle_file_based_request(struct mg_connection *conn,
  12690. const char *path,
  12691. struct mg_file *file)
  12692. {
  12693. if (!conn || !conn->dom_ctx) {
  12694. return;
  12695. }
  12696. if (0) {
  12697. #if defined(USE_LUA)
  12698. } else if (match_prefix(
  12699. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12700. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12701. path)
  12702. > 0) {
  12703. if (is_in_script_path(conn, path)) {
  12704. /* Lua server page: an SSI like page containing mostly plain
  12705. * html
  12706. * code
  12707. * plus some tags with server generated contents. */
  12708. handle_lsp_request(conn, path, file, NULL);
  12709. } else {
  12710. /* Script was in an illegal path */
  12711. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12712. }
  12713. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12714. strlen(
  12715. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12716. path)
  12717. > 0) {
  12718. if (is_in_script_path(conn, path)) {
  12719. /* Lua in-server module script: a CGI like script used to
  12720. * generate
  12721. * the
  12722. * entire reply. */
  12723. mg_exec_lua_script(conn, path, NULL);
  12724. } else {
  12725. /* Script was in an illegal path */
  12726. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12727. }
  12728. #endif
  12729. #if defined(USE_DUKTAPE)
  12730. } else if (match_prefix(
  12731. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12732. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12733. path)
  12734. > 0) {
  12735. if (is_in_script_path(conn, path)) {
  12736. /* Call duktape to generate the page */
  12737. mg_exec_duktape_script(conn, path);
  12738. } else {
  12739. /* Script was in an illegal path */
  12740. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12741. }
  12742. #endif
  12743. #if !defined(NO_CGI)
  12744. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12745. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12746. path)
  12747. > 0) {
  12748. if (is_in_script_path(conn, path)) {
  12749. /* CGI scripts may support all HTTP methods */
  12750. handle_cgi_request(conn, path);
  12751. } else {
  12752. /* Script was in an illegal path */
  12753. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12754. }
  12755. #endif /* !NO_CGI */
  12756. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12757. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12758. path)
  12759. > 0) {
  12760. if (is_in_script_path(conn, path)) {
  12761. handle_ssi_file_request(conn, path, file);
  12762. } else {
  12763. /* Script was in an illegal path */
  12764. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12765. }
  12766. #if !defined(NO_CACHING)
  12767. } else if ((!conn->in_error_handler)
  12768. && is_not_modified(conn, &file->stat)) {
  12769. /* Send 304 "Not Modified" - this must not send any body data */
  12770. handle_not_modified_static_file_request(conn, file);
  12771. #endif /* !NO_CACHING */
  12772. } else {
  12773. handle_static_file_request(conn, path, file, NULL, NULL);
  12774. }
  12775. }
  12776. #endif /* NO_FILESYSTEMS */
  12777. static void
  12778. close_all_listening_sockets(struct mg_context *ctx)
  12779. {
  12780. unsigned int i;
  12781. if (!ctx) {
  12782. return;
  12783. }
  12784. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12785. closesocket(ctx->listening_sockets[i].sock);
  12786. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12787. }
  12788. mg_free(ctx->listening_sockets);
  12789. ctx->listening_sockets = NULL;
  12790. mg_free(ctx->listening_socket_fds);
  12791. ctx->listening_socket_fds = NULL;
  12792. }
  12793. /* Valid listening port specification is: [ip_address:]port[s]
  12794. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12795. * Examples for IPv6: [::]:80, [::1]:80,
  12796. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12797. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12798. * In order to bind to both, IPv4 and IPv6, you can either add
  12799. * both ports using 8080,[::]:8080, or the short form +8080.
  12800. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12801. * one only accepting IPv4 the other only IPv6. +8080 creates
  12802. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12803. * environment, they might work differently, or might not work
  12804. * at all - it must be tested what options work best in the
  12805. * relevant network environment.
  12806. */
  12807. static int
  12808. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12809. {
  12810. unsigned int a, b, c, d;
  12811. unsigned port;
  12812. unsigned long portUL;
  12813. int ch, len;
  12814. const char *cb;
  12815. char *endptr;
  12816. #if defined(USE_IPV6)
  12817. char buf[100] = {0};
  12818. #endif
  12819. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12820. * Also, all-zeroes in the socket address means binding to all addresses
  12821. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12822. memset(so, 0, sizeof(*so));
  12823. so->lsa.sin.sin_family = AF_INET;
  12824. *ip_version = 0;
  12825. /* Initialize port and len as invalid. */
  12826. port = 0;
  12827. len = 0;
  12828. /* Test for different ways to format this string */
  12829. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12830. == 5) {
  12831. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12832. so->lsa.sin.sin_addr.s_addr =
  12833. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12834. so->lsa.sin.sin_port = htons((uint16_t)port);
  12835. *ip_version = 4;
  12836. #if defined(USE_IPV6)
  12837. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12838. && mg_inet_pton(
  12839. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12840. /* IPv6 address, examples: see above */
  12841. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12842. */
  12843. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12844. *ip_version = 6;
  12845. #endif
  12846. } else if ((vec->ptr[0] == '+')
  12847. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12848. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12849. /* Add 1 to len for the + character we skipped before */
  12850. len++;
  12851. #if defined(USE_IPV6)
  12852. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12853. so->lsa.sin6.sin6_family = AF_INET6;
  12854. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12855. *ip_version = 4 + 6;
  12856. #else
  12857. /* Bind to IPv4 only, since IPv6 is not built in. */
  12858. so->lsa.sin.sin_port = htons((uint16_t)port);
  12859. *ip_version = 4;
  12860. #endif
  12861. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12862. && (vec->ptr != endptr)) {
  12863. len = (int)(endptr - vec->ptr);
  12864. port = (uint16_t)portUL;
  12865. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12866. so->lsa.sin.sin_port = htons((uint16_t)port);
  12867. *ip_version = 4;
  12868. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12869. /* String could be a hostname. This check algotithm
  12870. * will only work for RFC 952 compliant hostnames,
  12871. * starting with a letter, containing only letters,
  12872. * digits and hyphen ('-'). Newer specs may allow
  12873. * more, but this is not guaranteed here, since it
  12874. * may interfere with rules for port option lists. */
  12875. /* According to RFC 1035, hostnames are restricted to 255 characters
  12876. * in total (63 between two dots). */
  12877. char hostname[256];
  12878. size_t hostnlen = (size_t)(cb - vec->ptr);
  12879. if (hostnlen >= sizeof(hostname)) {
  12880. /* This would be invalid in any case */
  12881. *ip_version = 0;
  12882. return 0;
  12883. }
  12884. memcpy(hostname, vec->ptr, hostnlen);
  12885. hostname[hostnlen] = 0;
  12886. if (mg_inet_pton(
  12887. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12888. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12889. *ip_version = 4;
  12890. so->lsa.sin.sin_family = AF_INET;
  12891. so->lsa.sin.sin_port = htons((uint16_t)port);
  12892. len += (int)(hostnlen + 1);
  12893. } else {
  12894. port = 0;
  12895. len = 0;
  12896. }
  12897. #if defined(USE_IPV6)
  12898. } else if (mg_inet_pton(AF_INET6,
  12899. hostname,
  12900. &so->lsa.sin6,
  12901. sizeof(so->lsa.sin6))) {
  12902. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12903. *ip_version = 6;
  12904. so->lsa.sin6.sin6_family = AF_INET6;
  12905. so->lsa.sin.sin_port = htons((uint16_t)port);
  12906. len += (int)(hostnlen + 1);
  12907. } else {
  12908. port = 0;
  12909. len = 0;
  12910. }
  12911. #endif
  12912. }
  12913. } else {
  12914. /* Parsing failure. */
  12915. }
  12916. /* sscanf and the option splitting code ensure the following condition
  12917. */
  12918. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12919. *ip_version = 0;
  12920. return 0;
  12921. }
  12922. ch = vec->ptr[len]; /* Next character after the port number */
  12923. so->is_ssl = (ch == 's');
  12924. so->ssl_redir = (ch == 'r');
  12925. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12926. if (is_valid_port(port)
  12927. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12928. return 1;
  12929. }
  12930. /* Reset ip_version to 0 if there is an error */
  12931. *ip_version = 0;
  12932. return 0;
  12933. }
  12934. /* Is there any SSL port in use? */
  12935. static int
  12936. is_ssl_port_used(const char *ports)
  12937. {
  12938. if (ports) {
  12939. /* There are several different allowed syntax variants:
  12940. * - "80" for a single port using every network interface
  12941. * - "localhost:80" for a single port using only localhost
  12942. * - "80,localhost:8080" for two ports, one bound to localhost
  12943. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12944. * to IPv4 localhost, one to IPv6 localhost
  12945. * - "+80" use port 80 for IPv4 and IPv6
  12946. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12947. * for both: IPv4 and IPv4
  12948. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12949. * additionally port 8080 bound to localhost connections
  12950. *
  12951. * If we just look for 's' anywhere in the string, "localhost:80"
  12952. * will be detected as SSL (false positive).
  12953. * Looking for 's' after a digit may cause false positives in
  12954. * "my24service:8080".
  12955. * Looking from 's' backward if there are only ':' and numbers
  12956. * before will not work for "24service:8080" (non SSL, port 8080)
  12957. * or "24s" (SSL, port 24).
  12958. *
  12959. * Remark: Initially hostnames were not allowed to start with a
  12960. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12961. * Section 2.1).
  12962. *
  12963. * To get this correct, the entire string must be parsed as a whole,
  12964. * reading it as a list element for element and parsing with an
  12965. * algorithm equivalent to parse_port_string.
  12966. *
  12967. * In fact, we use local interface names here, not arbitrary
  12968. * hostnames, so in most cases the only name will be "localhost".
  12969. *
  12970. * So, for now, we use this simple algorithm, that may still return
  12971. * a false positive in bizarre cases.
  12972. */
  12973. int i;
  12974. int portslen = (int)strlen(ports);
  12975. char prevIsNumber = 0;
  12976. for (i = 0; i < portslen; i++) {
  12977. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12978. return 1;
  12979. }
  12980. if (ports[i] >= '0' && ports[i] <= '9') {
  12981. prevIsNumber = 1;
  12982. } else {
  12983. prevIsNumber = 0;
  12984. }
  12985. }
  12986. }
  12987. return 0;
  12988. }
  12989. static int
  12990. set_ports_option(struct mg_context *phys_ctx)
  12991. {
  12992. const char *list;
  12993. int on = 1;
  12994. #if defined(USE_IPV6)
  12995. int off = 0;
  12996. #endif
  12997. struct vec vec;
  12998. struct socket so, *ptr;
  12999. struct mg_pollfd *pfd;
  13000. union usa usa;
  13001. socklen_t len;
  13002. int ip_version;
  13003. int portsTotal = 0;
  13004. int portsOk = 0;
  13005. const char *opt_txt;
  13006. long opt_listen_backlog;
  13007. if (!phys_ctx) {
  13008. return 0;
  13009. }
  13010. memset(&so, 0, sizeof(so));
  13011. memset(&usa, 0, sizeof(usa));
  13012. len = sizeof(usa);
  13013. list = phys_ctx->dd.config[LISTENING_PORTS];
  13014. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13015. portsTotal++;
  13016. if (!parse_port_string(&vec, &so, &ip_version)) {
  13017. mg_cry_ctx_internal(
  13018. phys_ctx,
  13019. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13020. (int)vec.len,
  13021. vec.ptr,
  13022. portsTotal,
  13023. "[IP_ADDRESS:]PORT[s|r]");
  13024. continue;
  13025. }
  13026. #if !defined(NO_SSL)
  13027. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13028. mg_cry_ctx_internal(phys_ctx,
  13029. "Cannot add SSL socket (entry %i)",
  13030. portsTotal);
  13031. continue;
  13032. }
  13033. #endif
  13034. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  13035. == INVALID_SOCKET) {
  13036. mg_cry_ctx_internal(phys_ctx,
  13037. "cannot create socket (entry %i)",
  13038. portsTotal);
  13039. continue;
  13040. }
  13041. #if defined(_WIN32)
  13042. /* Windows SO_REUSEADDR lets many procs binds to a
  13043. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13044. * if someone already has the socket -- DTL */
  13045. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13046. * Windows might need a few seconds before
  13047. * the same port can be used again in the
  13048. * same process, so a short Sleep may be
  13049. * required between mg_stop and mg_start.
  13050. */
  13051. if (setsockopt(so.sock,
  13052. SOL_SOCKET,
  13053. SO_EXCLUSIVEADDRUSE,
  13054. (SOCK_OPT_TYPE)&on,
  13055. sizeof(on))
  13056. != 0) {
  13057. /* Set reuse option, but don't abort on errors. */
  13058. mg_cry_ctx_internal(
  13059. phys_ctx,
  13060. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13061. portsTotal);
  13062. }
  13063. #else
  13064. if (setsockopt(so.sock,
  13065. SOL_SOCKET,
  13066. SO_REUSEADDR,
  13067. (SOCK_OPT_TYPE)&on,
  13068. sizeof(on))
  13069. != 0) {
  13070. /* Set reuse option, but don't abort on errors. */
  13071. mg_cry_ctx_internal(
  13072. phys_ctx,
  13073. "cannot set socket option SO_REUSEADDR (entry %i)",
  13074. portsTotal);
  13075. }
  13076. #endif
  13077. if (ip_version > 4) {
  13078. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13079. #if defined(USE_IPV6)
  13080. if (ip_version > 6) {
  13081. if (so.lsa.sa.sa_family == AF_INET6
  13082. && setsockopt(so.sock,
  13083. IPPROTO_IPV6,
  13084. IPV6_V6ONLY,
  13085. (void *)&off,
  13086. sizeof(off))
  13087. != 0) {
  13088. /* Set IPv6 only option, but don't abort on errors. */
  13089. mg_cry_ctx_internal(phys_ctx,
  13090. "cannot set socket option "
  13091. "IPV6_V6ONLY=off (entry %i)",
  13092. portsTotal);
  13093. }
  13094. } else {
  13095. if (so.lsa.sa.sa_family == AF_INET6
  13096. && setsockopt(so.sock,
  13097. IPPROTO_IPV6,
  13098. IPV6_V6ONLY,
  13099. (void *)&on,
  13100. sizeof(on))
  13101. != 0) {
  13102. /* Set IPv6 only option, but don't abort on errors. */
  13103. mg_cry_ctx_internal(phys_ctx,
  13104. "cannot set socket option "
  13105. "IPV6_V6ONLY=on (entry %i)",
  13106. portsTotal);
  13107. }
  13108. }
  13109. #else
  13110. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13111. closesocket(so.sock);
  13112. so.sock = INVALID_SOCKET;
  13113. continue;
  13114. #endif
  13115. }
  13116. if (so.lsa.sa.sa_family == AF_INET) {
  13117. len = sizeof(so.lsa.sin);
  13118. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13119. mg_cry_ctx_internal(phys_ctx,
  13120. "cannot bind to %.*s: %d (%s)",
  13121. (int)vec.len,
  13122. vec.ptr,
  13123. (int)ERRNO,
  13124. strerror(errno));
  13125. closesocket(so.sock);
  13126. so.sock = INVALID_SOCKET;
  13127. continue;
  13128. }
  13129. }
  13130. #if defined(USE_IPV6)
  13131. else if (so.lsa.sa.sa_family == AF_INET6) {
  13132. len = sizeof(so.lsa.sin6);
  13133. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13134. mg_cry_ctx_internal(phys_ctx,
  13135. "cannot bind to IPv6 %.*s: %d (%s)",
  13136. (int)vec.len,
  13137. vec.ptr,
  13138. (int)ERRNO,
  13139. strerror(errno));
  13140. closesocket(so.sock);
  13141. so.sock = INVALID_SOCKET;
  13142. continue;
  13143. }
  13144. }
  13145. #endif
  13146. else {
  13147. mg_cry_ctx_internal(
  13148. phys_ctx,
  13149. "cannot bind: address family not supported (entry %i)",
  13150. portsTotal);
  13151. closesocket(so.sock);
  13152. so.sock = INVALID_SOCKET;
  13153. continue;
  13154. }
  13155. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13156. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13157. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13158. mg_cry_ctx_internal(phys_ctx,
  13159. "%s value \"%s\" is invalid",
  13160. config_options[LISTEN_BACKLOG_SIZE].name,
  13161. opt_txt);
  13162. closesocket(so.sock);
  13163. so.sock = INVALID_SOCKET;
  13164. continue;
  13165. }
  13166. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13167. mg_cry_ctx_internal(phys_ctx,
  13168. "cannot listen to %.*s: %d (%s)",
  13169. (int)vec.len,
  13170. vec.ptr,
  13171. (int)ERRNO,
  13172. strerror(errno));
  13173. closesocket(so.sock);
  13174. so.sock = INVALID_SOCKET;
  13175. continue;
  13176. }
  13177. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13178. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13179. int err = (int)ERRNO;
  13180. mg_cry_ctx_internal(phys_ctx,
  13181. "call to getsockname failed %.*s: %d (%s)",
  13182. (int)vec.len,
  13183. vec.ptr,
  13184. err,
  13185. strerror(errno));
  13186. closesocket(so.sock);
  13187. so.sock = INVALID_SOCKET;
  13188. continue;
  13189. }
  13190. /* Update lsa port in case of random free ports */
  13191. #if defined(USE_IPV6)
  13192. if (so.lsa.sa.sa_family == AF_INET6) {
  13193. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13194. } else
  13195. #endif
  13196. {
  13197. so.lsa.sin.sin_port = usa.sin.sin_port;
  13198. }
  13199. if ((ptr = (struct socket *)
  13200. mg_realloc_ctx(phys_ctx->listening_sockets,
  13201. (phys_ctx->num_listening_sockets + 1)
  13202. * sizeof(phys_ctx->listening_sockets[0]),
  13203. phys_ctx))
  13204. == NULL) {
  13205. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13206. closesocket(so.sock);
  13207. so.sock = INVALID_SOCKET;
  13208. continue;
  13209. }
  13210. if ((pfd = (struct mg_pollfd *)
  13211. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13212. (phys_ctx->num_listening_sockets + 1)
  13213. * sizeof(phys_ctx->listening_socket_fds[0]),
  13214. phys_ctx))
  13215. == NULL) {
  13216. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13217. closesocket(so.sock);
  13218. so.sock = INVALID_SOCKET;
  13219. mg_free(ptr);
  13220. continue;
  13221. }
  13222. set_close_on_exec(so.sock, NULL, phys_ctx);
  13223. phys_ctx->listening_sockets = ptr;
  13224. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13225. phys_ctx->listening_socket_fds = pfd;
  13226. phys_ctx->num_listening_sockets++;
  13227. portsOk++;
  13228. }
  13229. if (portsOk != portsTotal) {
  13230. close_all_listening_sockets(phys_ctx);
  13231. portsOk = 0;
  13232. }
  13233. return portsOk;
  13234. }
  13235. static const char *
  13236. header_val(const struct mg_connection *conn, const char *header)
  13237. {
  13238. const char *header_value;
  13239. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13240. return "-";
  13241. } else {
  13242. return header_value;
  13243. }
  13244. }
  13245. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13246. static void log_access(const struct mg_connection *conn);
  13247. #include "external_log_access.inl"
  13248. #elif !defined(NO_FILESYSTEMS)
  13249. static void
  13250. log_access(const struct mg_connection *conn)
  13251. {
  13252. const struct mg_request_info *ri;
  13253. struct mg_file fi;
  13254. char date[64], src_addr[IP_ADDR_STR_LEN];
  13255. struct tm *tm;
  13256. const char *referer;
  13257. const char *user_agent;
  13258. char buf[4096];
  13259. if (!conn || !conn->dom_ctx) {
  13260. return;
  13261. }
  13262. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13263. if (mg_fopen(conn,
  13264. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13265. MG_FOPEN_MODE_APPEND,
  13266. &fi)
  13267. == 0) {
  13268. fi.access.fp = NULL;
  13269. }
  13270. } else {
  13271. fi.access.fp = NULL;
  13272. }
  13273. /* Log is written to a file and/or a callback. If both are not set,
  13274. * executing the rest of the function is pointless. */
  13275. if ((fi.access.fp == NULL)
  13276. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13277. return;
  13278. }
  13279. tm = localtime(&conn->conn_birth_time);
  13280. if (tm != NULL) {
  13281. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13282. } else {
  13283. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13284. date[sizeof(date) - 1] = '\0';
  13285. }
  13286. ri = &conn->request_info;
  13287. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13288. referer = header_val(conn, "Referer");
  13289. user_agent = header_val(conn, "User-Agent");
  13290. mg_snprintf(conn,
  13291. NULL, /* Ignore truncation in access log */
  13292. buf,
  13293. sizeof(buf),
  13294. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13295. src_addr,
  13296. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13297. date,
  13298. ri->request_method ? ri->request_method : "-",
  13299. ri->request_uri ? ri->request_uri : "-",
  13300. ri->query_string ? "?" : "",
  13301. ri->query_string ? ri->query_string : "",
  13302. ri->http_version,
  13303. conn->status_code,
  13304. conn->num_bytes_sent,
  13305. referer,
  13306. user_agent);
  13307. if (conn->phys_ctx->callbacks.log_access) {
  13308. conn->phys_ctx->callbacks.log_access(conn, buf);
  13309. }
  13310. if (fi.access.fp) {
  13311. int ok = 1;
  13312. flockfile(fi.access.fp);
  13313. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13314. ok = 0;
  13315. }
  13316. if (fflush(fi.access.fp) != 0) {
  13317. ok = 0;
  13318. }
  13319. funlockfile(fi.access.fp);
  13320. if (mg_fclose(&fi.access) != 0) {
  13321. ok = 0;
  13322. }
  13323. if (!ok) {
  13324. mg_cry_internal(conn,
  13325. "Error writing log file %s",
  13326. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13327. }
  13328. }
  13329. }
  13330. #else
  13331. #error Must either enable filesystems or provide a custom log_access implementation
  13332. #endif /* Externally provided function */
  13333. /* Verify given socket address against the ACL.
  13334. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13335. */
  13336. static int
  13337. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13338. {
  13339. int allowed, flag;
  13340. uint32_t net, mask;
  13341. struct vec vec;
  13342. if (phys_ctx) {
  13343. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13344. /* If any ACL is set, deny by default */
  13345. allowed = (list == NULL) ? '+' : '-';
  13346. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13347. flag = vec.ptr[0];
  13348. if ((flag != '+' && flag != '-')
  13349. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13350. mg_cry_ctx_internal(phys_ctx,
  13351. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13352. __func__);
  13353. return -1;
  13354. }
  13355. if (net == (remote_ip & mask)) {
  13356. allowed = flag;
  13357. }
  13358. }
  13359. return allowed == '+';
  13360. }
  13361. return -1;
  13362. }
  13363. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13364. static int
  13365. set_uid_option(struct mg_context *phys_ctx)
  13366. {
  13367. int success = 0;
  13368. if (phys_ctx) {
  13369. /* We are currently running as curr_uid. */
  13370. const uid_t curr_uid = getuid();
  13371. /* If set, we want to run as run_as_user. */
  13372. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13373. const struct passwd *to_pw = NULL;
  13374. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13375. /* run_as_user does not exist on the system. We can't proceed
  13376. * further. */
  13377. mg_cry_ctx_internal(phys_ctx,
  13378. "%s: unknown user [%s]",
  13379. __func__,
  13380. run_as_user);
  13381. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13382. /* There was either no request to change user, or we're already
  13383. * running as run_as_user. Nothing else to do.
  13384. */
  13385. success = 1;
  13386. } else {
  13387. /* Valid change request. */
  13388. if (setgid(to_pw->pw_gid) == -1) {
  13389. mg_cry_ctx_internal(phys_ctx,
  13390. "%s: setgid(%s): %s",
  13391. __func__,
  13392. run_as_user,
  13393. strerror(errno));
  13394. } else if (setgroups(0, NULL) == -1) {
  13395. mg_cry_ctx_internal(phys_ctx,
  13396. "%s: setgroups(): %s",
  13397. __func__,
  13398. strerror(errno));
  13399. } else if (setuid(to_pw->pw_uid) == -1) {
  13400. mg_cry_ctx_internal(phys_ctx,
  13401. "%s: setuid(%s): %s",
  13402. __func__,
  13403. run_as_user,
  13404. strerror(errno));
  13405. } else {
  13406. success = 1;
  13407. }
  13408. }
  13409. }
  13410. return success;
  13411. }
  13412. #endif /* !_WIN32 */
  13413. static void
  13414. tls_dtor(void *key)
  13415. {
  13416. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13417. /* key == pthread_getspecific(sTlsKey); */
  13418. if (tls) {
  13419. if (tls->is_master == 2) {
  13420. tls->is_master = -3; /* Mark memory as dead */
  13421. mg_free(tls);
  13422. }
  13423. }
  13424. pthread_setspecific(sTlsKey, NULL);
  13425. }
  13426. #if !defined(NO_SSL)
  13427. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13428. struct mg_domain_context *dom_ctx,
  13429. const char *pem,
  13430. const char *chain);
  13431. static const char *ssl_error(void);
  13432. static int
  13433. refresh_trust(struct mg_connection *conn)
  13434. {
  13435. struct stat cert_buf;
  13436. int64_t t = 0;
  13437. const char *pem;
  13438. const char *chain;
  13439. int should_verify_peer;
  13440. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13441. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13442. * refresh_trust still can not work. */
  13443. return 0;
  13444. }
  13445. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13446. if (chain == NULL) {
  13447. /* pem is not NULL here */
  13448. chain = pem;
  13449. }
  13450. if (*chain == 0) {
  13451. chain = NULL;
  13452. }
  13453. if (stat(pem, &cert_buf) != -1) {
  13454. t = (int64_t)cert_buf.st_mtime;
  13455. }
  13456. mg_lock_context(conn->phys_ctx);
  13457. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13458. conn->dom_ctx->ssl_cert_last_mtime = t;
  13459. should_verify_peer = 0;
  13460. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13461. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13462. == 0) {
  13463. should_verify_peer = 1;
  13464. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13465. "optional")
  13466. == 0) {
  13467. should_verify_peer = 1;
  13468. }
  13469. }
  13470. if (should_verify_peer) {
  13471. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13472. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13473. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13474. ca_file,
  13475. ca_path)
  13476. != 1) {
  13477. mg_unlock_context(conn->phys_ctx);
  13478. mg_cry_ctx_internal(
  13479. conn->phys_ctx,
  13480. "SSL_CTX_load_verify_locations error: %s "
  13481. "ssl_verify_peer requires setting "
  13482. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13483. "present in "
  13484. "the .conf file?",
  13485. ssl_error());
  13486. return 0;
  13487. }
  13488. }
  13489. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13490. == 0) {
  13491. mg_unlock_context(conn->phys_ctx);
  13492. return 0;
  13493. }
  13494. }
  13495. mg_unlock_context(conn->phys_ctx);
  13496. return 1;
  13497. }
  13498. #if defined(OPENSSL_API_1_1)
  13499. #else
  13500. static pthread_mutex_t *ssl_mutexes;
  13501. #endif /* OPENSSL_API_1_1 */
  13502. static int
  13503. sslize(struct mg_connection *conn,
  13504. int (*func)(SSL *),
  13505. const struct mg_client_options *client_options)
  13506. {
  13507. int ret, err;
  13508. int short_trust;
  13509. unsigned timeout = 1024;
  13510. unsigned i;
  13511. if (!conn) {
  13512. return 0;
  13513. }
  13514. short_trust =
  13515. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13516. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13517. if (short_trust) {
  13518. int trust_ret = refresh_trust(conn);
  13519. if (!trust_ret) {
  13520. return trust_ret;
  13521. }
  13522. }
  13523. mg_lock_context(conn->phys_ctx);
  13524. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13525. mg_unlock_context(conn->phys_ctx);
  13526. if (conn->ssl == NULL) {
  13527. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13528. OPENSSL_REMOVE_THREAD_STATE();
  13529. return 0;
  13530. }
  13531. SSL_set_app_data(conn->ssl, (char *)conn);
  13532. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13533. if (ret != 1) {
  13534. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13535. SSL_free(conn->ssl);
  13536. conn->ssl = NULL;
  13537. OPENSSL_REMOVE_THREAD_STATE();
  13538. return 0;
  13539. }
  13540. if (client_options) {
  13541. if (client_options->host_name) {
  13542. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13543. }
  13544. }
  13545. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13546. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13547. /* NOTE: The loop below acts as a back-off, so we can end
  13548. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13549. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13550. if (to >= 0) {
  13551. timeout = (unsigned)to;
  13552. }
  13553. }
  13554. /* SSL functions may fail and require to be called again:
  13555. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13556. * Here "func" could be SSL_connect or SSL_accept. */
  13557. for (i = 0; i <= timeout; i += 50) {
  13558. ERR_clear_error();
  13559. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13560. ret = func(conn->ssl);
  13561. if (ret != 1) {
  13562. err = SSL_get_error(conn->ssl, ret);
  13563. if ((err == SSL_ERROR_WANT_CONNECT)
  13564. || (err == SSL_ERROR_WANT_ACCEPT)
  13565. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13566. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13567. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13568. /* Don't wait if the server is going to be stopped. */
  13569. break;
  13570. }
  13571. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13572. /* Simply retry the function call. */
  13573. mg_sleep(50);
  13574. } else {
  13575. /* Need to retry the function call "later".
  13576. * See https://linux.die.net/man/3/ssl_get_error
  13577. * This is typical for non-blocking sockets. */
  13578. struct mg_pollfd pfd;
  13579. int pollres;
  13580. pfd.fd = conn->client.sock;
  13581. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13582. || (err == SSL_ERROR_WANT_WRITE))
  13583. ? POLLOUT
  13584. : POLLIN;
  13585. pollres = mg_poll(&pfd, 1, 50,
  13586. &(conn->phys_ctx->stop_flag));
  13587. if (pollres < 0) {
  13588. /* Break if error occured (-1)
  13589. * or server shutdown (-2) */
  13590. break;
  13591. }
  13592. }
  13593. } else if (err == SSL_ERROR_SYSCALL) {
  13594. /* This is an IO error. Look at errno. */
  13595. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13596. break;
  13597. } else {
  13598. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13599. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13600. break;
  13601. }
  13602. } else {
  13603. /* success */
  13604. break;
  13605. }
  13606. }
  13607. ERR_clear_error();
  13608. if (ret != 1) {
  13609. SSL_free(conn->ssl);
  13610. conn->ssl = NULL;
  13611. OPENSSL_REMOVE_THREAD_STATE();
  13612. return 0;
  13613. }
  13614. return 1;
  13615. }
  13616. /* Return OpenSSL error message (from CRYPTO lib) */
  13617. static const char *
  13618. ssl_error(void)
  13619. {
  13620. unsigned long err;
  13621. err = ERR_get_error();
  13622. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13623. }
  13624. static int
  13625. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13626. {
  13627. int i;
  13628. const char hexdigit[] = "0123456789abcdef";
  13629. if ((memlen <= 0) || (buflen <= 0)) {
  13630. return 0;
  13631. }
  13632. if (buflen < (3 * memlen)) {
  13633. return 0;
  13634. }
  13635. for (i = 0; i < memlen; i++) {
  13636. if (i > 0) {
  13637. buf[3 * i - 1] = ' ';
  13638. }
  13639. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13640. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13641. }
  13642. buf[3 * memlen - 1] = 0;
  13643. return 1;
  13644. }
  13645. static int
  13646. ssl_get_client_cert_info(const struct mg_connection *conn,
  13647. struct mg_client_cert *client_cert)
  13648. {
  13649. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13650. if (cert) {
  13651. char str_buf[1024];
  13652. unsigned char buf[256];
  13653. char *str_serial = NULL;
  13654. unsigned int ulen;
  13655. int ilen;
  13656. unsigned char *tmp_buf;
  13657. unsigned char *tmp_p;
  13658. /* Handle to algorithm used for fingerprint */
  13659. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13660. /* Get Subject and issuer */
  13661. X509_NAME *subj = X509_get_subject_name(cert);
  13662. X509_NAME *iss = X509_get_issuer_name(cert);
  13663. /* Get serial number */
  13664. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13665. /* Translate serial number to a hex string */
  13666. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13667. if (serial_bn) {
  13668. str_serial = BN_bn2hex(serial_bn);
  13669. BN_free(serial_bn);
  13670. }
  13671. client_cert->serial =
  13672. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13673. /* Translate subject and issuer to a string */
  13674. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13675. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13676. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13677. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13678. /* Calculate SHA1 fingerprint and store as a hex string */
  13679. ulen = 0;
  13680. /* ASN1_digest is deprecated. Do the calculation manually,
  13681. * using EVP_Digest. */
  13682. ilen = i2d_X509(cert, NULL);
  13683. tmp_buf = (ilen > 0)
  13684. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13685. conn->phys_ctx)
  13686. : NULL;
  13687. if (tmp_buf) {
  13688. tmp_p = tmp_buf;
  13689. (void)i2d_X509(cert, &tmp_p);
  13690. if (!EVP_Digest(
  13691. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13692. ulen = 0;
  13693. }
  13694. mg_free(tmp_buf);
  13695. }
  13696. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13697. *str_buf = 0;
  13698. }
  13699. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13700. client_cert->peer_cert = (void *)cert;
  13701. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13702. * see https://linux.die.net/man/3/bn_bn2hex */
  13703. OPENSSL_free(str_serial);
  13704. return 1;
  13705. }
  13706. return 0;
  13707. }
  13708. #if defined(OPENSSL_API_1_1)
  13709. #else
  13710. static void
  13711. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13712. {
  13713. (void)line;
  13714. (void)file;
  13715. if (mode & 1) {
  13716. /* 1 is CRYPTO_LOCK */
  13717. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13718. } else {
  13719. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13720. }
  13721. }
  13722. #endif /* OPENSSL_API_1_1 */
  13723. #if !defined(NO_SSL_DL)
  13724. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13725. static void *
  13726. load_tls_dll(char *ebuf,
  13727. size_t ebuf_len,
  13728. const char *dll_name,
  13729. struct ssl_func *sw)
  13730. {
  13731. union {
  13732. void *p;
  13733. void (*fp)(void);
  13734. } u;
  13735. void *dll_handle;
  13736. struct ssl_func *fp;
  13737. int ok;
  13738. int truncated = 0;
  13739. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13740. mg_snprintf(NULL,
  13741. NULL, /* No truncation check for ebuf */
  13742. ebuf,
  13743. ebuf_len,
  13744. "%s: cannot load %s",
  13745. __func__,
  13746. dll_name);
  13747. return NULL;
  13748. }
  13749. ok = 1;
  13750. for (fp = sw; fp->name != NULL; fp++) {
  13751. enum ssl_func_category req = fp->required;
  13752. #if defined(_WIN32)
  13753. /* GetProcAddress() returns pointer to function */
  13754. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13755. #else
  13756. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13757. * pointers to function pointers. We need to use a union to make a
  13758. * cast. */
  13759. u.p = dlsym(dll_handle, fp->name);
  13760. #endif /* _WIN32 */
  13761. /* Set pointer (might be NULL) */
  13762. fp->ptr = u.fp;
  13763. if (u.fp == NULL) {
  13764. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13765. tls_feature_missing[req]++;
  13766. if (req == TLS_Mandatory) {
  13767. /* Mandatory function is missing */
  13768. if (ok) {
  13769. /* This is the first missing function.
  13770. * Create a new error message. */
  13771. mg_snprintf(NULL,
  13772. &truncated,
  13773. ebuf,
  13774. ebuf_len,
  13775. "%s: %s: cannot find %s",
  13776. __func__,
  13777. dll_name,
  13778. fp->name);
  13779. ok = 0;
  13780. } else {
  13781. /* This is yet anothermissing function.
  13782. * Append existing error message. */
  13783. size_t cur_len = strlen(ebuf);
  13784. if (!truncated) {
  13785. mg_snprintf(NULL,
  13786. &truncated,
  13787. ebuf + cur_len,
  13788. ebuf_len - cur_len - 3,
  13789. ", %s",
  13790. fp->name);
  13791. if (truncated) {
  13792. /* If truncated, add "..." */
  13793. strcat(ebuf, "...");
  13794. }
  13795. }
  13796. }
  13797. }
  13798. }
  13799. }
  13800. if (!ok) {
  13801. (void)dlclose(dll_handle);
  13802. return NULL;
  13803. }
  13804. return dll_handle;
  13805. }
  13806. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13807. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13808. #endif /* NO_SSL_DL */
  13809. #if defined(SSL_ALREADY_INITIALIZED)
  13810. static volatile ptrdiff_t cryptolib_users =
  13811. 1; /* Reference counter for crypto library. */
  13812. #else
  13813. static volatile ptrdiff_t cryptolib_users =
  13814. 0; /* Reference counter for crypto library. */
  13815. #endif
  13816. static int
  13817. initialize_ssl(char *ebuf, size_t ebuf_len)
  13818. {
  13819. #if defined(OPENSSL_API_1_1)
  13820. if (ebuf_len > 0) {
  13821. ebuf[0] = 0;
  13822. }
  13823. #if !defined(NO_SSL_DL)
  13824. if (!cryptolib_dll_handle) {
  13825. cryptolib_dll_handle =
  13826. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13827. if (!cryptolib_dll_handle) {
  13828. mg_snprintf(NULL,
  13829. NULL, /* No truncation check for ebuf */
  13830. ebuf,
  13831. ebuf_len,
  13832. "%s: error loading library %s",
  13833. __func__,
  13834. CRYPTO_LIB);
  13835. DEBUG_TRACE("%s", ebuf);
  13836. return 0;
  13837. }
  13838. }
  13839. #endif /* NO_SSL_DL */
  13840. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13841. return 1;
  13842. }
  13843. #else /* not OPENSSL_API_1_1 */
  13844. int i, num_locks;
  13845. size_t size;
  13846. if (ebuf_len > 0) {
  13847. ebuf[0] = 0;
  13848. }
  13849. #if !defined(NO_SSL_DL)
  13850. if (!cryptolib_dll_handle) {
  13851. cryptolib_dll_handle =
  13852. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13853. if (!cryptolib_dll_handle) {
  13854. mg_snprintf(NULL,
  13855. NULL, /* No truncation check for ebuf */
  13856. ebuf,
  13857. ebuf_len,
  13858. "%s: error loading library %s",
  13859. __func__,
  13860. CRYPTO_LIB);
  13861. DEBUG_TRACE("%s", ebuf);
  13862. return 0;
  13863. }
  13864. }
  13865. #endif /* NO_SSL_DL */
  13866. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13867. return 1;
  13868. }
  13869. /* Initialize locking callbacks, needed for thread safety.
  13870. * http://www.openssl.org/support/faq.html#PROG1
  13871. */
  13872. num_locks = CRYPTO_num_locks();
  13873. if (num_locks < 0) {
  13874. num_locks = 0;
  13875. }
  13876. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13877. /* allocate mutex array, if required */
  13878. if (num_locks == 0) {
  13879. /* No mutex array required */
  13880. ssl_mutexes = NULL;
  13881. } else {
  13882. /* Mutex array required - allocate it */
  13883. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13884. /* Check OOM */
  13885. if (ssl_mutexes == NULL) {
  13886. mg_snprintf(NULL,
  13887. NULL, /* No truncation check for ebuf */
  13888. ebuf,
  13889. ebuf_len,
  13890. "%s: cannot allocate mutexes: %s",
  13891. __func__,
  13892. ssl_error());
  13893. DEBUG_TRACE("%s", ebuf);
  13894. return 0;
  13895. }
  13896. /* initialize mutex array */
  13897. for (i = 0; i < num_locks; i++) {
  13898. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13899. mg_snprintf(NULL,
  13900. NULL, /* No truncation check for ebuf */
  13901. ebuf,
  13902. ebuf_len,
  13903. "%s: error initializing mutex %i of %i",
  13904. __func__,
  13905. i,
  13906. num_locks);
  13907. DEBUG_TRACE("%s", ebuf);
  13908. mg_free(ssl_mutexes);
  13909. return 0;
  13910. }
  13911. }
  13912. }
  13913. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13914. CRYPTO_set_id_callback(&mg_current_thread_id);
  13915. #endif /* OPENSSL_API_1_1 */
  13916. #if !defined(NO_SSL_DL)
  13917. if (!ssllib_dll_handle) {
  13918. ssllib_dll_handle = load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13919. if (!ssllib_dll_handle) {
  13920. #if !defined(OPENSSL_API_1_1)
  13921. mg_free(ssl_mutexes);
  13922. #endif
  13923. DEBUG_TRACE("%s", ebuf);
  13924. return 0;
  13925. }
  13926. }
  13927. #endif /* NO_SSL_DL */
  13928. #if defined(OPENSSL_API_1_1)
  13929. /* Initialize SSL library */
  13930. OPENSSL_init_ssl(0, NULL);
  13931. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13932. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13933. NULL);
  13934. #else
  13935. /* Initialize SSL library */
  13936. SSL_library_init();
  13937. SSL_load_error_strings();
  13938. #endif
  13939. return 1;
  13940. }
  13941. static int
  13942. ssl_use_pem_file(struct mg_context *phys_ctx,
  13943. struct mg_domain_context *dom_ctx,
  13944. const char *pem,
  13945. const char *chain)
  13946. {
  13947. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13948. mg_cry_ctx_internal(phys_ctx,
  13949. "%s: cannot open certificate file %s: %s",
  13950. __func__,
  13951. pem,
  13952. ssl_error());
  13953. return 0;
  13954. }
  13955. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13956. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13957. mg_cry_ctx_internal(phys_ctx,
  13958. "%s: cannot open private key file %s: %s",
  13959. __func__,
  13960. pem,
  13961. ssl_error());
  13962. return 0;
  13963. }
  13964. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13965. mg_cry_ctx_internal(phys_ctx,
  13966. "%s: certificate and private key do not match: %s",
  13967. __func__,
  13968. pem);
  13969. return 0;
  13970. }
  13971. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13972. * chain files that contain private keys and certificates in
  13973. * SSL_CTX_use_certificate_chain_file.
  13974. * The CivetWeb-Server used pem-Files that contained both information.
  13975. * In order to make wolfSSL work, it is split in two files.
  13976. * One file that contains key and certificate used by the server and
  13977. * an optional chain file for the ssl stack.
  13978. */
  13979. if (chain) {
  13980. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13981. mg_cry_ctx_internal(phys_ctx,
  13982. "%s: cannot use certificate chain file %s: %s",
  13983. __func__,
  13984. chain,
  13985. ssl_error());
  13986. return 0;
  13987. }
  13988. }
  13989. return 1;
  13990. }
  13991. #if defined(OPENSSL_API_1_1)
  13992. static unsigned long
  13993. ssl_get_protocol(int version_id)
  13994. {
  13995. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13996. if (version_id > 0)
  13997. ret |= SSL_OP_NO_SSLv2;
  13998. if (version_id > 1)
  13999. ret |= SSL_OP_NO_SSLv3;
  14000. if (version_id > 2)
  14001. ret |= SSL_OP_NO_TLSv1;
  14002. if (version_id > 3)
  14003. ret |= SSL_OP_NO_TLSv1_1;
  14004. if (version_id > 4)
  14005. ret |= SSL_OP_NO_TLSv1_2;
  14006. #if defined(SSL_OP_NO_TLSv1_3)
  14007. if (version_id > 5)
  14008. ret |= SSL_OP_NO_TLSv1_3;
  14009. #endif
  14010. return ret;
  14011. }
  14012. #else
  14013. static long
  14014. ssl_get_protocol(int version_id)
  14015. {
  14016. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14017. if (version_id > 0)
  14018. ret |= SSL_OP_NO_SSLv2;
  14019. if (version_id > 1)
  14020. ret |= SSL_OP_NO_SSLv3;
  14021. if (version_id > 2)
  14022. ret |= SSL_OP_NO_TLSv1;
  14023. if (version_id > 3)
  14024. ret |= SSL_OP_NO_TLSv1_1;
  14025. if (version_id > 4)
  14026. ret |= SSL_OP_NO_TLSv1_2;
  14027. #if defined(SSL_OP_NO_TLSv1_3)
  14028. if (version_id > 5)
  14029. ret |= SSL_OP_NO_TLSv1_3;
  14030. #endif
  14031. return (long)ret;
  14032. }
  14033. #endif /* OPENSSL_API_1_1 */
  14034. /* SSL callback documentation:
  14035. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14036. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14037. * https://linux.die.net/man/3/ssl_set_info_callback */
  14038. /* Note: There is no "const" for the first argument in the documentation
  14039. * examples, however some (maybe most, but not all) headers of OpenSSL
  14040. * versions / OpenSSL compatibility layers have it. Having a different
  14041. * definition will cause a warning in C and an error in C++. Use "const SSL
  14042. * *", while automatical conversion from "SSL *" works for all compilers,
  14043. * but not other way around */
  14044. static void
  14045. ssl_info_callback(const SSL *ssl, int what, int ret)
  14046. {
  14047. (void)ret;
  14048. if (what & SSL_CB_HANDSHAKE_START) {
  14049. SSL_get_app_data(ssl);
  14050. }
  14051. if (what & SSL_CB_HANDSHAKE_DONE) {
  14052. /* TODO: check for openSSL 1.1 */
  14053. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14054. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14055. }
  14056. }
  14057. static int
  14058. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14059. {
  14060. #if defined(GCC_DIAGNOSTIC)
  14061. #pragma GCC diagnostic push
  14062. #pragma GCC diagnostic ignored "-Wcast-align"
  14063. #endif /* defined(GCC_DIAGNOSTIC) */
  14064. /* We used an aligned pointer in SSL_set_app_data */
  14065. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14066. #if defined(GCC_DIAGNOSTIC)
  14067. #pragma GCC diagnostic pop
  14068. #endif /* defined(GCC_DIAGNOSTIC) */
  14069. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14070. (void)ad;
  14071. (void)arg;
  14072. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14073. DEBUG_ASSERT(0);
  14074. return SSL_TLSEXT_ERR_NOACK;
  14075. }
  14076. conn->dom_ctx = &(conn->phys_ctx->dd);
  14077. /* Old clients (Win XP) will not support SNI. Then, there
  14078. * is no server name available in the request - we can
  14079. * only work with the default certificate.
  14080. * Multiple HTTPS hosts on one IP+port are only possible
  14081. * with a certificate containing all alternative names.
  14082. */
  14083. if ((servername == NULL) || (*servername == 0)) {
  14084. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14085. mg_lock_context(conn->phys_ctx);
  14086. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14087. mg_unlock_context(conn->phys_ctx);
  14088. return SSL_TLSEXT_ERR_NOACK;
  14089. }
  14090. DEBUG_TRACE("TLS connection to host %s", servername);
  14091. while (conn->dom_ctx) {
  14092. if (!mg_strcasecmp(servername,
  14093. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14094. /* Found matching domain */
  14095. DEBUG_TRACE("TLS domain %s found",
  14096. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14097. break;
  14098. }
  14099. mg_lock_context(conn->phys_ctx);
  14100. conn->dom_ctx = conn->dom_ctx->next;
  14101. mg_unlock_context(conn->phys_ctx);
  14102. }
  14103. if (conn->dom_ctx == NULL) {
  14104. /* Default domain */
  14105. DEBUG_TRACE("TLS default domain %s used",
  14106. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14107. conn->dom_ctx = &(conn->phys_ctx->dd);
  14108. }
  14109. mg_lock_context(conn->phys_ctx);
  14110. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14111. mg_unlock_context(conn->phys_ctx);
  14112. return SSL_TLSEXT_ERR_OK;
  14113. }
  14114. #if defined(USE_HTTP2)
  14115. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14116. static const char *alpn_proto_order[] = {alpn_proto_list,
  14117. alpn_proto_list + 3,
  14118. alpn_proto_list + 3 + 8,
  14119. NULL};
  14120. #else
  14121. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14122. static const char *alpn_proto_order[] = {alpn_proto_list,
  14123. alpn_proto_list + 8,
  14124. NULL};
  14125. #endif
  14126. static int
  14127. alpn_select_cb(SSL *ssl,
  14128. const unsigned char **out,
  14129. unsigned char *outlen,
  14130. const unsigned char *in,
  14131. unsigned int inlen,
  14132. void *arg)
  14133. {
  14134. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14135. unsigned int i, j;
  14136. struct mg_workerTLS *tls =
  14137. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14138. (void)ssl;
  14139. (void)dom_ctx;
  14140. if (tls == NULL) {
  14141. /* Need to store protocol in Thread Local Storage */
  14142. /* If there is no Thread Local Storage, don't use ALPN */
  14143. return SSL_TLSEXT_ERR_NOACK;
  14144. }
  14145. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14146. /* check all accepted protocols in this order */
  14147. const char *alpn_proto = alpn_proto_order[j];
  14148. /* search input for matching protocol */
  14149. for (i = 0; i < inlen; i++) {
  14150. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14151. *out = in + i + 1;
  14152. *outlen = in[i];
  14153. tls->alpn_proto = alpn_proto;
  14154. return SSL_TLSEXT_ERR_OK;
  14155. }
  14156. }
  14157. }
  14158. /* Nothing found */
  14159. return SSL_TLSEXT_ERR_NOACK;
  14160. }
  14161. static int
  14162. next_protos_advertised_cb(SSL *ssl,
  14163. const unsigned char **data,
  14164. unsigned int *len,
  14165. void *arg)
  14166. {
  14167. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14168. *data = (const unsigned char *)alpn_proto_list;
  14169. *len = (unsigned int)strlen((const char *)data);
  14170. (void)ssl;
  14171. (void)dom_ctx;
  14172. return SSL_TLSEXT_ERR_OK;
  14173. }
  14174. static int
  14175. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14176. {
  14177. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14178. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14179. (const unsigned char *)alpn_proto_list,
  14180. alpn_len);
  14181. if (ret != 0) {
  14182. mg_cry_ctx_internal(phys_ctx,
  14183. "SSL_CTX_set_alpn_protos error: %s",
  14184. ssl_error());
  14185. }
  14186. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14187. alpn_select_cb,
  14188. (void *)dom_ctx);
  14189. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14190. next_protos_advertised_cb,
  14191. (void *)dom_ctx);
  14192. return ret;
  14193. }
  14194. /* Setup SSL CTX as required by CivetWeb */
  14195. static int
  14196. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14197. struct mg_domain_context *dom_ctx,
  14198. const char *pem,
  14199. const char *chain)
  14200. {
  14201. int callback_ret;
  14202. int should_verify_peer;
  14203. int peer_certificate_optional;
  14204. const char *ca_path;
  14205. const char *ca_file;
  14206. int use_default_verify_paths;
  14207. int verify_depth;
  14208. struct timespec now_mt;
  14209. md5_byte_t ssl_context_id[16];
  14210. md5_state_t md5state;
  14211. int protocol_ver;
  14212. #if defined(OPENSSL_API_1_1)
  14213. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14214. mg_cry_ctx_internal(phys_ctx,
  14215. "SSL_CTX_new (server) error: %s",
  14216. ssl_error());
  14217. return 0;
  14218. }
  14219. #else
  14220. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14221. mg_cry_ctx_internal(phys_ctx,
  14222. "SSL_CTX_new (server) error: %s",
  14223. ssl_error());
  14224. return 0;
  14225. }
  14226. #endif /* OPENSSL_API_1_1 */
  14227. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14228. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14229. | SSL_OP_NO_TLSv1_1);
  14230. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14231. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14232. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14233. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14234. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14235. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14236. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14237. #if defined(SSL_OP_NO_RENEGOTIATION)
  14238. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14239. #endif
  14240. #if !defined(NO_SSL_DL)
  14241. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14242. #endif /* NO_SSL_DL */
  14243. /* In SSL documentation examples callback defined without const
  14244. * specifier 'void (*)(SSL *, int, int)' See:
  14245. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14246. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14247. * But in the source code const SSL is used:
  14248. * 'void (*)(const SSL *, int, int)' See:
  14249. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14250. * Problem about wrong documentation described, but not resolved:
  14251. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14252. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14253. * But when compiled with modern C++ compiler, correct const should be
  14254. * provided
  14255. */
  14256. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14257. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14258. ssl_servername_callback);
  14259. /* If a callback has been specified, call it. */
  14260. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14261. ? 0
  14262. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14263. phys_ctx->user_data));
  14264. /* If callback returns 0, civetweb sets up the SSL certificate.
  14265. * If it returns 1, civetweb assumes the calback already did this.
  14266. * If it returns -1, initializing ssl fails. */
  14267. if (callback_ret < 0) {
  14268. mg_cry_ctx_internal(phys_ctx,
  14269. "SSL callback returned error: %i",
  14270. callback_ret);
  14271. return 0;
  14272. }
  14273. if (callback_ret > 0) {
  14274. /* Callback did everything. */
  14275. return 1;
  14276. }
  14277. /* If a domain callback has been specified, call it. */
  14278. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14279. ? 0
  14280. : (phys_ctx->callbacks.init_ssl_domain(
  14281. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14282. dom_ctx->ssl_ctx,
  14283. phys_ctx->user_data));
  14284. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14285. * If it returns 1, civetweb assumes the calback already did this.
  14286. * If it returns -1, initializing ssl fails. */
  14287. if (callback_ret < 0) {
  14288. mg_cry_ctx_internal(phys_ctx,
  14289. "Domain SSL callback returned error: %i",
  14290. callback_ret);
  14291. return 0;
  14292. }
  14293. if (callback_ret > 0) {
  14294. /* Domain callback did everything. */
  14295. return 1;
  14296. }
  14297. /* Use some combination of start time, domain and port as a SSL
  14298. * context ID. This should be unique on the current machine. */
  14299. md5_init(&md5state);
  14300. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14301. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14302. md5_append(&md5state,
  14303. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14304. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14305. md5_append(&md5state,
  14306. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14307. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14308. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14309. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14310. md5_finish(&md5state, ssl_context_id);
  14311. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14312. (unsigned char *)ssl_context_id,
  14313. sizeof(ssl_context_id));
  14314. if (pem != NULL) {
  14315. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14316. return 0;
  14317. }
  14318. }
  14319. /* Should we support client certificates? */
  14320. /* Default is "no". */
  14321. should_verify_peer = 0;
  14322. peer_certificate_optional = 0;
  14323. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14324. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14325. /* Yes, they are mandatory */
  14326. should_verify_peer = 1;
  14327. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14328. "optional")
  14329. == 0) {
  14330. /* Yes, they are optional */
  14331. should_verify_peer = 1;
  14332. peer_certificate_optional = 1;
  14333. }
  14334. }
  14335. use_default_verify_paths =
  14336. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14337. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14338. == 0);
  14339. if (should_verify_peer) {
  14340. ca_path = dom_ctx->config[SSL_CA_PATH];
  14341. ca_file = dom_ctx->config[SSL_CA_FILE];
  14342. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14343. != 1) {
  14344. mg_cry_ctx_internal(phys_ctx,
  14345. "SSL_CTX_load_verify_locations error: %s "
  14346. "ssl_verify_peer requires setting "
  14347. "either ssl_ca_path or ssl_ca_file. "
  14348. "Is any of them present in the "
  14349. ".conf file?",
  14350. ssl_error());
  14351. return 0;
  14352. }
  14353. if (peer_certificate_optional) {
  14354. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14355. } else {
  14356. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14357. SSL_VERIFY_PEER
  14358. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14359. NULL);
  14360. }
  14361. if (use_default_verify_paths
  14362. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14363. mg_cry_ctx_internal(phys_ctx,
  14364. "SSL_CTX_set_default_verify_paths error: %s",
  14365. ssl_error());
  14366. return 0;
  14367. }
  14368. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14369. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14370. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14371. }
  14372. }
  14373. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14374. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14375. dom_ctx->config[SSL_CIPHER_LIST])
  14376. != 1) {
  14377. mg_cry_ctx_internal(phys_ctx,
  14378. "SSL_CTX_set_cipher_list error: %s",
  14379. ssl_error());
  14380. }
  14381. }
  14382. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14383. #if !defined(NO_SSL_DL)
  14384. if (!tls_feature_missing[TLS_ALPN])
  14385. #endif
  14386. {
  14387. init_alpn(phys_ctx, dom_ctx);
  14388. }
  14389. return 1;
  14390. }
  14391. /* Check if SSL is required.
  14392. * If so, dynamically load SSL library
  14393. * and set up ctx->ssl_ctx pointer. */
  14394. static int
  14395. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14396. {
  14397. void *ssl_ctx = 0;
  14398. int callback_ret;
  14399. const char *pem;
  14400. const char *chain;
  14401. char ebuf[128];
  14402. if (!phys_ctx) {
  14403. return 0;
  14404. }
  14405. if (!dom_ctx) {
  14406. dom_ctx = &(phys_ctx->dd);
  14407. }
  14408. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14409. /* No SSL port is set. No need to setup SSL. */
  14410. return 1;
  14411. }
  14412. /* Check for external SSL_CTX */
  14413. callback_ret =
  14414. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14415. ? 0
  14416. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14417. phys_ctx->user_data));
  14418. if (callback_ret < 0) {
  14419. mg_cry_ctx_internal(phys_ctx,
  14420. "external_ssl_ctx callback returned error: %i",
  14421. callback_ret);
  14422. return 0;
  14423. } else if (callback_ret > 0) {
  14424. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14425. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14426. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14427. return 0;
  14428. }
  14429. return 1;
  14430. }
  14431. /* Check for external domain SSL_CTX */
  14432. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14433. ? 0
  14434. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14435. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14436. &ssl_ctx,
  14437. phys_ctx->user_data));
  14438. if (callback_ret < 0) {
  14439. mg_cry_ctx_internal(
  14440. phys_ctx,
  14441. "external_ssl_ctx_domain callback returned error: %i",
  14442. callback_ret);
  14443. return 0;
  14444. } else if (callback_ret > 0) {
  14445. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14446. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14447. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14448. return 0;
  14449. }
  14450. return 1;
  14451. }
  14452. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14453. * 0, CivetWeb should continue initializing SSL */
  14454. /* If PEM file is not specified and the init_ssl callbacks
  14455. * are not specified, setup will fail. */
  14456. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14457. && (phys_ctx->callbacks.init_ssl == NULL)
  14458. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14459. /* No certificate and no init_ssl callbacks:
  14460. * Essential data to set up TLS is missing.
  14461. */
  14462. mg_cry_ctx_internal(phys_ctx,
  14463. "Initializing SSL failed: -%s is not set",
  14464. config_options[SSL_CERTIFICATE].name);
  14465. return 0;
  14466. }
  14467. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14468. if (chain == NULL) {
  14469. chain = pem;
  14470. }
  14471. if ((chain != NULL) && (*chain == 0)) {
  14472. chain = NULL;
  14473. }
  14474. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14475. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14476. return 0;
  14477. }
  14478. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14479. }
  14480. static void
  14481. uninitialize_ssl(void)
  14482. {
  14483. #if defined(OPENSSL_API_1_1)
  14484. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14485. /* Shutdown according to
  14486. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14487. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14488. */
  14489. CONF_modules_unload(1);
  14490. #else
  14491. int i;
  14492. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14493. /* Shutdown according to
  14494. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14495. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14496. */
  14497. CRYPTO_set_locking_callback(NULL);
  14498. CRYPTO_set_id_callback(NULL);
  14499. ENGINE_cleanup();
  14500. CONF_modules_unload(1);
  14501. ERR_free_strings();
  14502. EVP_cleanup();
  14503. CRYPTO_cleanup_all_ex_data();
  14504. OPENSSL_REMOVE_THREAD_STATE();
  14505. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14506. pthread_mutex_destroy(&ssl_mutexes[i]);
  14507. }
  14508. mg_free(ssl_mutexes);
  14509. ssl_mutexes = NULL;
  14510. #endif /* OPENSSL_API_1_1 */
  14511. }
  14512. }
  14513. #endif /* !NO_SSL */
  14514. #if !defined(NO_FILESYSTEMS)
  14515. static int
  14516. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14517. {
  14518. if (phys_ctx) {
  14519. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14520. const char *path;
  14521. struct mg_connection fc;
  14522. if (!dom_ctx) {
  14523. dom_ctx = &(phys_ctx->dd);
  14524. }
  14525. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14526. if ((path != NULL)
  14527. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14528. mg_cry_ctx_internal(phys_ctx,
  14529. "Cannot open %s: %s",
  14530. path,
  14531. strerror(ERRNO));
  14532. return 0;
  14533. }
  14534. return 1;
  14535. }
  14536. return 0;
  14537. }
  14538. #endif /* NO_FILESYSTEMS */
  14539. static int
  14540. set_acl_option(struct mg_context *phys_ctx)
  14541. {
  14542. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14543. }
  14544. static void
  14545. reset_per_request_attributes(struct mg_connection *conn)
  14546. {
  14547. if (!conn) {
  14548. return;
  14549. }
  14550. conn->connection_type =
  14551. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14552. conn->num_bytes_sent = conn->consumed_content = 0;
  14553. conn->path_info = NULL;
  14554. conn->status_code = -1;
  14555. conn->content_len = -1;
  14556. conn->is_chunked = 0;
  14557. conn->must_close = 0;
  14558. conn->request_len = 0;
  14559. conn->throttle = 0;
  14560. conn->accept_gzip = 0;
  14561. conn->response_info.content_length = conn->request_info.content_length = -1;
  14562. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14563. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14564. conn->response_info.status_text = NULL;
  14565. conn->response_info.status_code = 0;
  14566. conn->request_info.remote_user = NULL;
  14567. conn->request_info.request_method = NULL;
  14568. conn->request_info.request_uri = NULL;
  14569. conn->request_info.local_uri = NULL;
  14570. #if defined(MG_LEGACY_INTERFACE)
  14571. /* Legacy before split into local_uri and request_uri */
  14572. conn->request_info.uri = NULL;
  14573. #endif
  14574. }
  14575. static int
  14576. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14577. {
  14578. if (setsockopt(sock,
  14579. IPPROTO_TCP,
  14580. TCP_NODELAY,
  14581. (SOCK_OPT_TYPE)&nodelay_on,
  14582. sizeof(nodelay_on))
  14583. != 0) {
  14584. /* Error */
  14585. return 1;
  14586. }
  14587. /* OK */
  14588. return 0;
  14589. }
  14590. #if !defined(__ZEPHYR__)
  14591. static void
  14592. close_socket_gracefully(struct mg_connection *conn)
  14593. {
  14594. #if defined(_WIN32)
  14595. char buf[MG_BUF_LEN];
  14596. int n;
  14597. #endif
  14598. struct linger linger;
  14599. int error_code = 0;
  14600. int linger_timeout = -2;
  14601. socklen_t opt_len = sizeof(error_code);
  14602. if (!conn) {
  14603. return;
  14604. }
  14605. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14606. * "Note that enabling a nonzero timeout on a nonblocking socket
  14607. * is not recommended.", so set it to blocking now */
  14608. set_blocking_mode(conn->client.sock);
  14609. /* Send FIN to the client */
  14610. shutdown(conn->client.sock, SHUTDOWN_WR);
  14611. #if defined(_WIN32)
  14612. /* Read and discard pending incoming data. If we do not do that and
  14613. * close
  14614. * the socket, the data in the send buffer may be discarded. This
  14615. * behaviour is seen on Windows, when client keeps sending data
  14616. * when server decides to close the connection; then when client
  14617. * does recv() it gets no data back. */
  14618. do {
  14619. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14620. } while (n > 0);
  14621. #endif
  14622. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14623. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14624. }
  14625. /* Set linger option according to configuration */
  14626. if (linger_timeout >= 0) {
  14627. /* Set linger option to avoid socket hanging out after close. This
  14628. * prevent ephemeral port exhaust problem under high QPS. */
  14629. linger.l_onoff = 1;
  14630. #if defined(_MSC_VER)
  14631. #pragma warning(push)
  14632. #pragma warning(disable : 4244)
  14633. #endif
  14634. #if defined(GCC_DIAGNOSTIC)
  14635. #pragma GCC diagnostic push
  14636. #pragma GCC diagnostic ignored "-Wconversion"
  14637. #endif
  14638. /* Data type of linger structure elements may differ,
  14639. * so we don't know what cast we need here.
  14640. * Disable type conversion warnings. */
  14641. linger.l_linger = (linger_timeout + 999) / 1000;
  14642. #if defined(GCC_DIAGNOSTIC)
  14643. #pragma GCC diagnostic pop
  14644. #endif
  14645. #if defined(_MSC_VER)
  14646. #pragma warning(pop)
  14647. #endif
  14648. } else {
  14649. linger.l_onoff = 0;
  14650. linger.l_linger = 0;
  14651. }
  14652. if (linger_timeout < -1) {
  14653. /* Default: don't configure any linger */
  14654. } else if (getsockopt(conn->client.sock,
  14655. SOL_SOCKET,
  14656. SO_ERROR,
  14657. #if defined(_WIN32) /* WinSock uses different data type here */
  14658. (char *)&error_code,
  14659. #else
  14660. &error_code,
  14661. #endif
  14662. &opt_len)
  14663. != 0) {
  14664. /* Cannot determine if socket is already closed. This should
  14665. * not occur and never did in a test. Log an error message
  14666. * and continue. */
  14667. mg_cry_internal(conn,
  14668. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14669. __func__,
  14670. strerror(ERRNO));
  14671. #if defined(_WIN32)
  14672. } else if (error_code == WSAECONNRESET) {
  14673. #else
  14674. } else if (error_code == ECONNRESET) {
  14675. #endif
  14676. /* Socket already closed by client/peer, close socket without linger
  14677. */
  14678. } else {
  14679. /* Set linger timeout */
  14680. if (setsockopt(conn->client.sock,
  14681. SOL_SOCKET,
  14682. SO_LINGER,
  14683. (char *)&linger,
  14684. sizeof(linger))
  14685. != 0) {
  14686. mg_cry_internal(
  14687. conn,
  14688. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14689. __func__,
  14690. linger.l_onoff,
  14691. linger.l_linger,
  14692. strerror(ERRNO));
  14693. }
  14694. }
  14695. /* Now we know that our FIN is ACK-ed, safe to close */
  14696. closesocket(conn->client.sock);
  14697. conn->client.sock = INVALID_SOCKET;
  14698. }
  14699. #endif
  14700. static void
  14701. close_connection(struct mg_connection *conn)
  14702. {
  14703. #if defined(USE_SERVER_STATS)
  14704. conn->conn_state = 6; /* to close */
  14705. #endif
  14706. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14707. if (conn->lua_websocket_state) {
  14708. lua_websocket_close(conn, conn->lua_websocket_state);
  14709. conn->lua_websocket_state = NULL;
  14710. }
  14711. #endif
  14712. mg_lock_connection(conn);
  14713. /* Set close flag, so keep-alive loops will stop */
  14714. conn->must_close = 1;
  14715. /* call the connection_close callback if assigned */
  14716. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14717. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14718. conn->phys_ctx->callbacks.connection_close(conn);
  14719. }
  14720. }
  14721. /* Reset user data, after close callback is called.
  14722. * Do not reuse it. If the user needs a destructor,
  14723. * it must be done in the connection_close callback. */
  14724. mg_set_user_connection_data(conn, NULL);
  14725. #if defined(USE_SERVER_STATS)
  14726. conn->conn_state = 7; /* closing */
  14727. #endif
  14728. #if !defined(NO_SSL)
  14729. if (conn->ssl != NULL) {
  14730. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14731. */
  14732. SSL_shutdown(conn->ssl);
  14733. SSL_free(conn->ssl);
  14734. OPENSSL_REMOVE_THREAD_STATE();
  14735. conn->ssl = NULL;
  14736. }
  14737. #endif
  14738. if (conn->client.sock != INVALID_SOCKET) {
  14739. #if defined(__ZEPHYR__)
  14740. closesocket(conn->client.sock);
  14741. #else
  14742. close_socket_gracefully(conn);
  14743. #endif
  14744. conn->client.sock = INVALID_SOCKET;
  14745. }
  14746. if (conn->host) {
  14747. mg_free((void *)conn->host);
  14748. conn->host = NULL;
  14749. }
  14750. mg_unlock_connection(conn);
  14751. #if defined(USE_SERVER_STATS)
  14752. conn->conn_state = 8; /* closed */
  14753. #endif
  14754. }
  14755. void
  14756. mg_close_connection(struct mg_connection *conn)
  14757. {
  14758. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14759. return;
  14760. }
  14761. #if defined(USE_WEBSOCKET)
  14762. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14763. if (conn->in_websocket_handling) {
  14764. /* Set close flag, so the server thread can exit. */
  14765. conn->must_close = 1;
  14766. return;
  14767. }
  14768. }
  14769. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14770. unsigned int i;
  14771. /* client context: loops must end */
  14772. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14773. conn->must_close = 1;
  14774. /* We need to get the client thread out of the select/recv call
  14775. * here. */
  14776. /* Since we use a sleep quantum of some seconds to check for recv
  14777. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14778. /* join worker thread */
  14779. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14780. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14781. }
  14782. }
  14783. #endif /* defined(USE_WEBSOCKET) */
  14784. close_connection(conn);
  14785. #if !defined(NO_SSL)
  14786. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14787. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14788. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14789. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14790. }
  14791. #endif
  14792. #if defined(USE_WEBSOCKET)
  14793. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14794. mg_free(conn->phys_ctx->worker_threadids);
  14795. (void)pthread_mutex_destroy(&conn->mutex);
  14796. mg_free(conn);
  14797. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14798. (void)pthread_mutex_destroy(&conn->mutex);
  14799. mg_free(conn);
  14800. }
  14801. #else
  14802. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14803. (void)pthread_mutex_destroy(&conn->mutex);
  14804. mg_free(conn);
  14805. }
  14806. #endif /* defined(USE_WEBSOCKET) */
  14807. }
  14808. static struct mg_connection *
  14809. mg_connect_client_impl(const struct mg_client_options *client_options,
  14810. int use_ssl,
  14811. char *ebuf,
  14812. size_t ebuf_len)
  14813. {
  14814. struct mg_connection *conn = NULL;
  14815. SOCKET sock;
  14816. union usa sa;
  14817. struct sockaddr *psa;
  14818. socklen_t len;
  14819. unsigned max_req_size =
  14820. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14821. /* Size of structures, aligned to 8 bytes */
  14822. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14823. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14824. conn =
  14825. (struct mg_connection *)mg_calloc(1,
  14826. conn_size + ctx_size + max_req_size);
  14827. if (conn == NULL) {
  14828. mg_snprintf(NULL,
  14829. NULL, /* No truncation check for ebuf */
  14830. ebuf,
  14831. ebuf_len,
  14832. "calloc(): %s",
  14833. strerror(ERRNO));
  14834. return NULL;
  14835. }
  14836. #if defined(GCC_DIAGNOSTIC)
  14837. #pragma GCC diagnostic push
  14838. #pragma GCC diagnostic ignored "-Wcast-align"
  14839. #endif /* defined(GCC_DIAGNOSTIC) */
  14840. /* conn_size is aligned to 8 bytes */
  14841. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14842. #if defined(GCC_DIAGNOSTIC)
  14843. #pragma GCC diagnostic pop
  14844. #endif /* defined(GCC_DIAGNOSTIC) */
  14845. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14846. conn->buf_size = (int)max_req_size;
  14847. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14848. conn->dom_ctx = &(conn->phys_ctx->dd);
  14849. if (!connect_socket(conn->phys_ctx,
  14850. client_options->host,
  14851. client_options->port,
  14852. use_ssl,
  14853. ebuf,
  14854. ebuf_len,
  14855. &sock,
  14856. &sa)) {
  14857. /* ebuf is set by connect_socket,
  14858. * free all memory and return NULL; */
  14859. mg_free(conn);
  14860. return NULL;
  14861. }
  14862. #if !defined(NO_SSL)
  14863. #if defined(OPENSSL_API_1_1)
  14864. if (use_ssl
  14865. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14866. == NULL) {
  14867. mg_snprintf(NULL,
  14868. NULL, /* No truncation check for ebuf */
  14869. ebuf,
  14870. ebuf_len,
  14871. "SSL_CTX_new error: %s",
  14872. ssl_error());
  14873. closesocket(sock);
  14874. mg_free(conn);
  14875. return NULL;
  14876. }
  14877. #else
  14878. if (use_ssl
  14879. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14880. == NULL) {
  14881. mg_snprintf(NULL,
  14882. NULL, /* No truncation check for ebuf */
  14883. ebuf,
  14884. ebuf_len,
  14885. "SSL_CTX_new error: %s",
  14886. ssl_error());
  14887. closesocket(sock);
  14888. mg_free(conn);
  14889. return NULL;
  14890. }
  14891. #endif /* OPENSSL_API_1_1 */
  14892. #endif /* NO_SSL */
  14893. #if defined(USE_IPV6)
  14894. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14895. : sizeof(conn->client.rsa.sin6);
  14896. psa = (sa.sa.sa_family == AF_INET)
  14897. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14898. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14899. #else
  14900. len = sizeof(conn->client.rsa.sin);
  14901. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14902. #endif
  14903. conn->client.sock = sock;
  14904. conn->client.lsa = sa;
  14905. if (getsockname(sock, psa, &len) != 0) {
  14906. mg_cry_internal(conn,
  14907. "%s: getsockname() failed: %s",
  14908. __func__,
  14909. strerror(ERRNO));
  14910. }
  14911. conn->client.is_ssl = use_ssl ? 1 : 0;
  14912. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14913. mg_snprintf(NULL,
  14914. NULL, /* No truncation check for ebuf */
  14915. ebuf,
  14916. ebuf_len,
  14917. "Can not create mutex");
  14918. #if !defined(NO_SSL)
  14919. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14920. #endif
  14921. closesocket(sock);
  14922. mg_free(conn);
  14923. return NULL;
  14924. }
  14925. #if !defined(NO_SSL)
  14926. if (use_ssl) {
  14927. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14928. * SSL_CTX_set_verify call is needed to switch off server
  14929. * certificate checking, which is off by default in OpenSSL and
  14930. * on in yaSSL. */
  14931. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14932. * SSL_VERIFY_PEER, verify_ssl_server); */
  14933. if (client_options->client_cert) {
  14934. if (!ssl_use_pem_file(conn->phys_ctx,
  14935. conn->dom_ctx,
  14936. client_options->client_cert,
  14937. NULL)) {
  14938. mg_snprintf(NULL,
  14939. NULL, /* No truncation check for ebuf */
  14940. ebuf,
  14941. ebuf_len,
  14942. "Can not use SSL client certificate");
  14943. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14944. closesocket(sock);
  14945. mg_free(conn);
  14946. return NULL;
  14947. }
  14948. }
  14949. if (client_options->server_cert) {
  14950. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14951. client_options->server_cert,
  14952. NULL)
  14953. != 1) {
  14954. mg_cry_internal(conn,
  14955. "SSL_CTX_load_verify_locations error: %s ",
  14956. ssl_error());
  14957. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14958. closesocket(sock);
  14959. mg_free(conn);
  14960. return NULL;
  14961. }
  14962. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14963. } else {
  14964. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14965. }
  14966. if (!sslize(conn,
  14967. SSL_connect,
  14968. client_options)) {
  14969. mg_snprintf(NULL,
  14970. NULL, /* No truncation check for ebuf */
  14971. ebuf,
  14972. ebuf_len,
  14973. "SSL connection error");
  14974. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14975. closesocket(sock);
  14976. mg_free(conn);
  14977. return NULL;
  14978. }
  14979. }
  14980. #endif
  14981. return conn;
  14982. }
  14983. CIVETWEB_API struct mg_connection *
  14984. mg_connect_client_secure(const struct mg_client_options *client_options,
  14985. char *error_buffer,
  14986. size_t error_buffer_size)
  14987. {
  14988. return mg_connect_client_impl(client_options,
  14989. 1,
  14990. error_buffer,
  14991. error_buffer_size);
  14992. }
  14993. struct mg_connection *
  14994. mg_connect_client(const char *host,
  14995. int port,
  14996. int use_ssl,
  14997. char *error_buffer,
  14998. size_t error_buffer_size)
  14999. {
  15000. struct mg_client_options opts;
  15001. memset(&opts, 0, sizeof(opts));
  15002. opts.host = host;
  15003. opts.port = port;
  15004. return mg_connect_client_impl(&opts,
  15005. use_ssl,
  15006. error_buffer,
  15007. error_buffer_size);
  15008. }
  15009. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15010. struct mg_connection *
  15011. mg_connect_client2(const char *host,
  15012. const char *protocol,
  15013. int port,
  15014. const char *path,
  15015. struct mg_init_data *init,
  15016. struct mg_error_data *error)
  15017. {
  15018. int is_ssl, is_ws;
  15019. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15020. if (error != NULL) {
  15021. error->code = 0;
  15022. if (error->text_buffer_size > 0) {
  15023. *error->text = 0;
  15024. }
  15025. }
  15026. if ((host == NULL) || (protocol == NULL)) {
  15027. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15028. mg_snprintf(NULL,
  15029. NULL, /* No truncation check for error buffers */
  15030. error->text,
  15031. error->text_buffer_size,
  15032. "%s",
  15033. "Invalid parameters");
  15034. }
  15035. return NULL;
  15036. }
  15037. /* check all known protocolls */
  15038. if (!mg_strcasecmp(protocol, "http")) {
  15039. is_ssl = 0;
  15040. is_ws = 0;
  15041. } else if (!mg_strcasecmp(protocol, "https")) {
  15042. is_ssl = 1;
  15043. is_ws = 0;
  15044. #if defined(USE_WEBSOCKET)
  15045. } else if (!mg_strcasecmp(protocol, "ws")) {
  15046. is_ssl = 0;
  15047. is_ws = 1;
  15048. } else if (!mg_strcasecmp(protocol, "wss")) {
  15049. is_ssl = 1;
  15050. is_ws = 1;
  15051. #endif
  15052. } else {
  15053. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15054. mg_snprintf(NULL,
  15055. NULL, /* No truncation check for error buffers */
  15056. error->text,
  15057. error->text_buffer_size,
  15058. "Protocol %s not supported",
  15059. protocol);
  15060. }
  15061. return NULL;
  15062. }
  15063. /* TODO: The current implementation here just calls the old
  15064. * implementations, without using any new options. This is just a first
  15065. * step to test the new interfaces. */
  15066. #if defined(USE_WEBSOCKET)
  15067. if (is_ws) {
  15068. /* TODO: implement all options */
  15069. return mg_connect_websocket_client(
  15070. host,
  15071. port,
  15072. is_ssl,
  15073. ((error != NULL) ? error->text : NULL),
  15074. ((error != NULL) ? error->text_buffer_size : 0),
  15075. (path ? path : ""),
  15076. NULL /* TODO: origin */,
  15077. deprecated_websocket_data_wrapper,
  15078. deprecated_websocket_close_wrapper,
  15079. (void *)init->callbacks);
  15080. }
  15081. #endif
  15082. /* TODO: all additional options */
  15083. struct mg_client_options opts;
  15084. memset(&opts, 0, sizeof(opts));
  15085. opts.host = host;
  15086. opts.port = port;
  15087. return mg_connect_client_impl(&opts,
  15088. is_ssl,
  15089. ((error != NULL) ? error->text : NULL),
  15090. ((error != NULL) ? error->text_buffer_size
  15091. : 0));
  15092. }
  15093. #endif
  15094. static const struct {
  15095. const char *proto;
  15096. size_t proto_len;
  15097. unsigned default_port;
  15098. } abs_uri_protocols[] = {{"http://", 7, 80},
  15099. {"https://", 8, 443},
  15100. {"ws://", 5, 80},
  15101. {"wss://", 6, 443},
  15102. {NULL, 0, 0}};
  15103. /* Check if the uri is valid.
  15104. * return 0 for invalid uri,
  15105. * return 1 for *,
  15106. * return 2 for relative uri,
  15107. * return 3 for absolute uri without port,
  15108. * return 4 for absolute uri with port */
  15109. static int
  15110. get_uri_type(const char *uri)
  15111. {
  15112. int i;
  15113. const char *hostend, *portbegin;
  15114. char *portend;
  15115. unsigned long port;
  15116. /* According to the HTTP standard
  15117. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15118. * URI can be an asterisk (*) or should start with slash (relative uri),
  15119. * or it should start with the protocol (absolute uri). */
  15120. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15121. /* asterisk */
  15122. return 1;
  15123. }
  15124. /* Valid URIs according to RFC 3986
  15125. * (https://www.ietf.org/rfc/rfc3986.txt)
  15126. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15127. * and unreserved characters A-Z a-z 0-9 and -._~
  15128. * and % encoded symbols.
  15129. */
  15130. for (i = 0; uri[i] != 0; i++) {
  15131. if (uri[i] < 33) {
  15132. /* control characters and spaces are invalid */
  15133. return 0;
  15134. }
  15135. if (uri[i] > 126) {
  15136. /* non-ascii characters must be % encoded */
  15137. return 0;
  15138. } else {
  15139. switch (uri[i]) {
  15140. case '"': /* 34 */
  15141. case '<': /* 60 */
  15142. case '>': /* 62 */
  15143. case '\\': /* 92 */
  15144. case '^': /* 94 */
  15145. case '`': /* 96 */
  15146. case '{': /* 123 */
  15147. case '|': /* 124 */
  15148. case '}': /* 125 */
  15149. return 0;
  15150. default:
  15151. /* character is ok */
  15152. break;
  15153. }
  15154. }
  15155. }
  15156. /* A relative uri starts with a / character */
  15157. if (uri[0] == '/') {
  15158. /* relative uri */
  15159. return 2;
  15160. }
  15161. /* It could be an absolute uri: */
  15162. /* This function only checks if the uri is valid, not if it is
  15163. * addressing the current server. So civetweb can also be used
  15164. * as a proxy server. */
  15165. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15166. if (mg_strncasecmp(uri,
  15167. abs_uri_protocols[i].proto,
  15168. abs_uri_protocols[i].proto_len)
  15169. == 0) {
  15170. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15171. if (!hostend) {
  15172. return 0;
  15173. }
  15174. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15175. if (!portbegin) {
  15176. return 3;
  15177. }
  15178. port = strtoul(portbegin + 1, &portend, 10);
  15179. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15180. return 0;
  15181. }
  15182. return 4;
  15183. }
  15184. }
  15185. return 0;
  15186. }
  15187. /* Return NULL or the relative uri at the current server */
  15188. static const char *
  15189. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15190. {
  15191. const char *server_domain;
  15192. size_t server_domain_len;
  15193. size_t request_domain_len = 0;
  15194. unsigned long port = 0;
  15195. int i, auth_domain_check_enabled;
  15196. const char *hostbegin = NULL;
  15197. const char *hostend = NULL;
  15198. const char *portbegin;
  15199. char *portend;
  15200. auth_domain_check_enabled =
  15201. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15202. /* DNS is case insensitive, so use case insensitive string compare here
  15203. */
  15204. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15205. if (mg_strncasecmp(uri,
  15206. abs_uri_protocols[i].proto,
  15207. abs_uri_protocols[i].proto_len)
  15208. == 0) {
  15209. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15210. hostend = strchr(hostbegin, '/');
  15211. if (!hostend) {
  15212. return 0;
  15213. }
  15214. portbegin = strchr(hostbegin, ':');
  15215. if ((!portbegin) || (portbegin > hostend)) {
  15216. port = abs_uri_protocols[i].default_port;
  15217. request_domain_len = (size_t)(hostend - hostbegin);
  15218. } else {
  15219. port = strtoul(portbegin + 1, &portend, 10);
  15220. if ((portend != hostend) || (port <= 0)
  15221. || !is_valid_port(port)) {
  15222. return 0;
  15223. }
  15224. request_domain_len = (size_t)(portbegin - hostbegin);
  15225. }
  15226. /* protocol found, port set */
  15227. break;
  15228. }
  15229. }
  15230. if (!port) {
  15231. /* port remains 0 if the protocol is not found */
  15232. return 0;
  15233. }
  15234. /* Check if the request is directed to a different server. */
  15235. /* First check if the port is the same (IPv4 and IPv6). */
  15236. #if defined(USE_IPV6)
  15237. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  15238. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  15239. /* Request is directed to a different port */
  15240. return 0;
  15241. }
  15242. } else
  15243. #endif
  15244. {
  15245. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  15246. /* Request is directed to a different port */
  15247. return 0;
  15248. }
  15249. }
  15250. /* Finally check if the server corresponds to the authentication
  15251. * domain of the server (the server domain).
  15252. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15253. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15254. * but do not allow substrings (like
  15255. * http://notmydomain.com/path/file.ext
  15256. * or http://mydomain.com.fake/path/file.ext).
  15257. */
  15258. if (auth_domain_check_enabled) {
  15259. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15260. server_domain_len = strlen(server_domain);
  15261. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15262. return 0;
  15263. }
  15264. if ((request_domain_len == server_domain_len)
  15265. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15266. /* Request is directed to this server - full name match. */
  15267. } else {
  15268. if (request_domain_len < (server_domain_len + 2)) {
  15269. /* Request is directed to another server: The server name
  15270. * is longer than the request name.
  15271. * Drop this case here to avoid overflows in the
  15272. * following checks. */
  15273. return 0;
  15274. }
  15275. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15276. /* Request is directed to another server: It could be a
  15277. * substring
  15278. * like notmyserver.com */
  15279. return 0;
  15280. }
  15281. if (0
  15282. != memcmp(server_domain,
  15283. hostbegin + request_domain_len - server_domain_len,
  15284. server_domain_len)) {
  15285. /* Request is directed to another server:
  15286. * The server name is different. */
  15287. return 0;
  15288. }
  15289. }
  15290. }
  15291. return hostend;
  15292. }
  15293. static int
  15294. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15295. {
  15296. if (ebuf_len > 0) {
  15297. ebuf[0] = '\0';
  15298. }
  15299. *err = 0;
  15300. reset_per_request_attributes(conn);
  15301. if (!conn) {
  15302. mg_snprintf(conn,
  15303. NULL, /* No truncation check for ebuf */
  15304. ebuf,
  15305. ebuf_len,
  15306. "%s",
  15307. "Internal error");
  15308. *err = 500;
  15309. return 0;
  15310. }
  15311. /* Set the time the request was received. This value should be used for
  15312. * timeouts. */
  15313. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15314. conn->request_len =
  15315. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15316. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15317. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15318. mg_snprintf(conn,
  15319. NULL, /* No truncation check for ebuf */
  15320. ebuf,
  15321. ebuf_len,
  15322. "%s",
  15323. "Invalid message size");
  15324. *err = 500;
  15325. return 0;
  15326. }
  15327. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15328. mg_snprintf(conn,
  15329. NULL, /* No truncation check for ebuf */
  15330. ebuf,
  15331. ebuf_len,
  15332. "%s",
  15333. "Message too large");
  15334. *err = 413;
  15335. return 0;
  15336. }
  15337. if (conn->request_len <= 0) {
  15338. if (conn->data_len > 0) {
  15339. mg_snprintf(conn,
  15340. NULL, /* No truncation check for ebuf */
  15341. ebuf,
  15342. ebuf_len,
  15343. "%s",
  15344. "Malformed message");
  15345. *err = 400;
  15346. } else {
  15347. /* Server did not recv anything -> just close the connection */
  15348. conn->must_close = 1;
  15349. mg_snprintf(conn,
  15350. NULL, /* No truncation check for ebuf */
  15351. ebuf,
  15352. ebuf_len,
  15353. "%s",
  15354. "No data received");
  15355. *err = 0;
  15356. }
  15357. return 0;
  15358. }
  15359. return 1;
  15360. }
  15361. static int
  15362. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15363. {
  15364. const char *cl;
  15365. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15366. return 0;
  15367. }
  15368. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15369. <= 0) {
  15370. mg_snprintf(conn,
  15371. NULL, /* No truncation check for ebuf */
  15372. ebuf,
  15373. ebuf_len,
  15374. "%s",
  15375. "Bad request");
  15376. *err = 400;
  15377. return 0;
  15378. }
  15379. /* Message is a valid request */
  15380. /* Is there a "host" ? */
  15381. if (conn->host != NULL) {
  15382. mg_free((void *)conn->host);
  15383. }
  15384. conn->host = alloc_get_host(conn);
  15385. if (!conn->host) {
  15386. mg_snprintf(conn,
  15387. NULL, /* No truncation check for ebuf */
  15388. ebuf,
  15389. ebuf_len,
  15390. "%s",
  15391. "Bad request: Host mismatch");
  15392. *err = 400;
  15393. return 0;
  15394. }
  15395. if (((cl = get_header(conn->request_info.http_headers,
  15396. conn->request_info.num_headers,
  15397. "Transfer-Encoding"))
  15398. != NULL)
  15399. && mg_strcasecmp(cl, "identity")) {
  15400. if (mg_strcasecmp(cl, "chunked")) {
  15401. mg_snprintf(conn,
  15402. NULL, /* No truncation check for ebuf */
  15403. ebuf,
  15404. ebuf_len,
  15405. "%s",
  15406. "Bad request");
  15407. *err = 400;
  15408. return 0;
  15409. }
  15410. conn->is_chunked = 1;
  15411. conn->content_len = 0; /* not yet read */
  15412. } else if ((cl = get_header(conn->request_info.http_headers,
  15413. conn->request_info.num_headers,
  15414. "Content-Length"))
  15415. != NULL) {
  15416. /* Request has content length set */
  15417. char *endptr = NULL;
  15418. conn->content_len = strtoll(cl, &endptr, 10);
  15419. if ((endptr == cl) || (conn->content_len < 0)) {
  15420. mg_snprintf(conn,
  15421. NULL, /* No truncation check for ebuf */
  15422. ebuf,
  15423. ebuf_len,
  15424. "%s",
  15425. "Bad request");
  15426. *err = 411;
  15427. return 0;
  15428. }
  15429. /* Publish the content length back to the request info. */
  15430. conn->request_info.content_length = conn->content_len;
  15431. } else {
  15432. /* There is no exception, see RFC7230. */
  15433. conn->content_len = 0;
  15434. }
  15435. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15436. return 1;
  15437. }
  15438. /* conn is assumed to be valid in this internal function */
  15439. static int
  15440. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15441. {
  15442. const char *cl;
  15443. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15444. return 0;
  15445. }
  15446. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15447. <= 0) {
  15448. mg_snprintf(conn,
  15449. NULL, /* No truncation check for ebuf */
  15450. ebuf,
  15451. ebuf_len,
  15452. "%s",
  15453. "Bad response");
  15454. *err = 400;
  15455. return 0;
  15456. }
  15457. /* Message is a valid response */
  15458. if (((cl = get_header(conn->response_info.http_headers,
  15459. conn->response_info.num_headers,
  15460. "Transfer-Encoding"))
  15461. != NULL)
  15462. && mg_strcasecmp(cl, "identity")) {
  15463. if (mg_strcasecmp(cl, "chunked")) {
  15464. mg_snprintf(conn,
  15465. NULL, /* No truncation check for ebuf */
  15466. ebuf,
  15467. ebuf_len,
  15468. "%s",
  15469. "Bad request");
  15470. *err = 400;
  15471. return 0;
  15472. }
  15473. conn->is_chunked = 1;
  15474. conn->content_len = 0; /* not yet read */
  15475. } else if ((cl = get_header(conn->response_info.http_headers,
  15476. conn->response_info.num_headers,
  15477. "Content-Length"))
  15478. != NULL) {
  15479. char *endptr = NULL;
  15480. conn->content_len = strtoll(cl, &endptr, 10);
  15481. if ((endptr == cl) || (conn->content_len < 0)) {
  15482. mg_snprintf(conn,
  15483. NULL, /* No truncation check for ebuf */
  15484. ebuf,
  15485. ebuf_len,
  15486. "%s",
  15487. "Bad request");
  15488. *err = 411;
  15489. return 0;
  15490. }
  15491. /* Publish the content length back to the response info. */
  15492. conn->response_info.content_length = conn->content_len;
  15493. /* TODO: check if it is still used in response_info */
  15494. conn->request_info.content_length = conn->content_len;
  15495. /* TODO: we should also consider HEAD method */
  15496. if (conn->response_info.status_code == 304) {
  15497. conn->content_len = 0;
  15498. }
  15499. } else {
  15500. /* TODO: we should also consider HEAD method */
  15501. if (((conn->response_info.status_code >= 100)
  15502. && (conn->response_info.status_code <= 199))
  15503. || (conn->response_info.status_code == 204)
  15504. || (conn->response_info.status_code == 304)) {
  15505. conn->content_len = 0;
  15506. } else {
  15507. conn->content_len = -1; /* unknown content length */
  15508. }
  15509. }
  15510. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15511. return 1;
  15512. }
  15513. int
  15514. mg_get_response(struct mg_connection *conn,
  15515. char *ebuf,
  15516. size_t ebuf_len,
  15517. int timeout)
  15518. {
  15519. int err, ret;
  15520. char txt[32]; /* will not overflow */
  15521. char *save_timeout;
  15522. char *new_timeout;
  15523. if (ebuf_len > 0) {
  15524. ebuf[0] = '\0';
  15525. }
  15526. if (!conn) {
  15527. mg_snprintf(conn,
  15528. NULL, /* No truncation check for ebuf */
  15529. ebuf,
  15530. ebuf_len,
  15531. "%s",
  15532. "Parameter error");
  15533. return -1;
  15534. }
  15535. /* Reset the previous responses */
  15536. conn->data_len = 0;
  15537. /* Implementation of API function for HTTP clients */
  15538. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15539. if (timeout >= 0) {
  15540. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15541. new_timeout = txt;
  15542. } else {
  15543. new_timeout = NULL;
  15544. }
  15545. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15546. ret = get_response(conn, ebuf, ebuf_len, &err);
  15547. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15548. #if defined(MG_LEGACY_INTERFACE)
  15549. /* TODO: 1) uri is deprecated;
  15550. * 2) here, ri.uri is the http response code */
  15551. conn->request_info.uri = conn->request_info.request_uri;
  15552. #endif
  15553. conn->request_info.local_uri = conn->request_info.request_uri;
  15554. /* TODO (mid): Define proper return values - maybe return length?
  15555. * For the first test use <0 for error and >0 for OK */
  15556. return (ret == 0) ? -1 : +1;
  15557. }
  15558. struct mg_connection *
  15559. mg_download(const char *host,
  15560. int port,
  15561. int use_ssl,
  15562. char *ebuf,
  15563. size_t ebuf_len,
  15564. const char *fmt,
  15565. ...)
  15566. {
  15567. struct mg_connection *conn;
  15568. va_list ap;
  15569. int i;
  15570. int reqerr;
  15571. if (ebuf_len > 0) {
  15572. ebuf[0] = '\0';
  15573. }
  15574. va_start(ap, fmt);
  15575. /* open a connection */
  15576. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15577. if (conn != NULL) {
  15578. i = mg_vprintf(conn, fmt, ap);
  15579. if (i <= 0) {
  15580. mg_snprintf(conn,
  15581. NULL, /* No truncation check for ebuf */
  15582. ebuf,
  15583. ebuf_len,
  15584. "%s",
  15585. "Error sending request");
  15586. } else {
  15587. /* make sure the buffer is clear */
  15588. conn->data_len = 0;
  15589. get_response(conn, ebuf, ebuf_len, &reqerr);
  15590. #if defined(MG_LEGACY_INTERFACE)
  15591. /* TODO: 1) uri is deprecated;
  15592. * 2) here, ri.uri is the http response code */
  15593. conn->request_info.uri = conn->request_info.request_uri;
  15594. #endif
  15595. conn->request_info.local_uri = conn->request_info.request_uri;
  15596. }
  15597. }
  15598. /* if an error occurred, close the connection */
  15599. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15600. mg_close_connection(conn);
  15601. conn = NULL;
  15602. }
  15603. va_end(ap);
  15604. return conn;
  15605. }
  15606. struct websocket_client_thread_data {
  15607. struct mg_connection *conn;
  15608. mg_websocket_data_handler data_handler;
  15609. mg_websocket_close_handler close_handler;
  15610. void *callback_data;
  15611. };
  15612. #if defined(USE_WEBSOCKET)
  15613. #if defined(_WIN32)
  15614. static unsigned __stdcall websocket_client_thread(void *data)
  15615. #else
  15616. static void *
  15617. websocket_client_thread(void *data)
  15618. #endif
  15619. {
  15620. struct websocket_client_thread_data *cdata =
  15621. (struct websocket_client_thread_data *)data;
  15622. void *user_thread_ptr = NULL;
  15623. #if !defined(_WIN32)
  15624. struct sigaction sa;
  15625. /* Ignore SIGPIPE */
  15626. memset(&sa, 0, sizeof(sa));
  15627. sa.sa_handler = SIG_IGN;
  15628. sigaction(SIGPIPE, &sa, NULL);
  15629. #endif
  15630. mg_set_thread_name("ws-clnt");
  15631. if (cdata->conn->phys_ctx) {
  15632. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15633. /* 3 indicates a websocket client thread */
  15634. /* TODO: check if conn->phys_ctx can be set */
  15635. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15636. cdata->conn->phys_ctx, 3);
  15637. }
  15638. }
  15639. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15640. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15641. if (cdata->close_handler != NULL) {
  15642. cdata->close_handler(cdata->conn, cdata->callback_data);
  15643. }
  15644. /* The websocket_client context has only this thread. If it runs out,
  15645. set the stop_flag to 2 (= "stopped"). */
  15646. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15647. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15648. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15649. 3,
  15650. user_thread_ptr);
  15651. }
  15652. mg_free((void *)cdata);
  15653. #if defined(_WIN32)
  15654. return 0;
  15655. #else
  15656. return NULL;
  15657. #endif
  15658. }
  15659. #endif
  15660. static struct mg_connection *
  15661. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15662. int use_ssl,
  15663. char *error_buffer,
  15664. size_t error_buffer_size,
  15665. const char *path,
  15666. const char *origin,
  15667. mg_websocket_data_handler data_func,
  15668. mg_websocket_close_handler close_func,
  15669. void *user_data)
  15670. {
  15671. struct mg_connection *conn = NULL;
  15672. #if defined(USE_WEBSOCKET)
  15673. struct websocket_client_thread_data *thread_data;
  15674. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15675. const char *handshake_req;
  15676. int port = client_options->port;
  15677. const char *host = client_options->host;
  15678. int i;
  15679. if (origin != NULL) {
  15680. handshake_req = "GET %s HTTP/1.1\r\n"
  15681. "Host: %s\r\n"
  15682. "Upgrade: websocket\r\n"
  15683. "Connection: Upgrade\r\n"
  15684. "Sec-WebSocket-Key: %s\r\n"
  15685. "Sec-WebSocket-Version: 13\r\n"
  15686. "Origin: %s\r\n"
  15687. "\r\n";
  15688. } else {
  15689. handshake_req = "GET %s HTTP/1.1\r\n"
  15690. "Host: %s\r\n"
  15691. "Upgrade: websocket\r\n"
  15692. "Connection: Upgrade\r\n"
  15693. "Sec-WebSocket-Key: %s\r\n"
  15694. "Sec-WebSocket-Version: 13\r\n"
  15695. "\r\n";
  15696. }
  15697. #if defined(__clang__)
  15698. #pragma clang diagnostic push
  15699. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15700. #endif
  15701. /* Establish the client connection and request upgrade */
  15702. conn =
  15703. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15704. if (conn == NULL) {
  15705. /* error_buffer already filled */
  15706. return NULL;
  15707. }
  15708. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15709. if (i <= 0) {
  15710. mg_snprintf(conn,
  15711. NULL, /* No truncation check for ebuf */
  15712. error_buffer,
  15713. error_buffer_size,
  15714. "%s",
  15715. "Error sending request");
  15716. mg_close_connection(conn);
  15717. return NULL;
  15718. }
  15719. conn->data_len = 0;
  15720. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15721. mg_close_connection(conn);
  15722. return NULL;
  15723. }
  15724. conn->request_info.local_uri = conn->request_info.request_uri;
  15725. #if defined(__clang__)
  15726. #pragma clang diagnostic pop
  15727. #endif
  15728. /* Connection object will be null if something goes wrong */
  15729. if (conn == NULL) {
  15730. if (!*error_buffer) {
  15731. /* There should be already an error message */
  15732. mg_snprintf(conn,
  15733. NULL, /* No truncation check for ebuf */
  15734. error_buffer,
  15735. error_buffer_size,
  15736. "Unexpected error");
  15737. }
  15738. return NULL;
  15739. }
  15740. if (conn->response_info.status_code != 101) {
  15741. /* We sent an "upgrade" request. For a correct websocket
  15742. * protocol handshake, we expect a "101 Continue" response.
  15743. * Otherwise it is a protocol violation. Maybe the HTTP
  15744. * Server does not know websockets. */
  15745. if (!*error_buffer) {
  15746. /* set an error, if not yet set */
  15747. mg_snprintf(conn,
  15748. NULL, /* No truncation check for ebuf */
  15749. error_buffer,
  15750. error_buffer_size,
  15751. "Unexpected server reply");
  15752. }
  15753. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15754. mg_close_connection(conn);
  15755. return NULL;
  15756. }
  15757. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15758. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15759. if (!thread_data) {
  15760. DEBUG_TRACE("%s\r\n", "Out of memory");
  15761. mg_close_connection(conn);
  15762. return NULL;
  15763. }
  15764. thread_data->conn = conn;
  15765. thread_data->data_handler = data_func;
  15766. thread_data->close_handler = close_func;
  15767. thread_data->callback_data = user_data;
  15768. conn->phys_ctx->worker_threadids =
  15769. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15770. if (!conn->phys_ctx->worker_threadids) {
  15771. DEBUG_TRACE("%s\r\n", "Out of memory");
  15772. mg_free(thread_data);
  15773. mg_close_connection(conn);
  15774. return NULL;
  15775. }
  15776. /* Now upgrade to ws/wss client context */
  15777. conn->phys_ctx->user_data = user_data;
  15778. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15779. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15780. /* Start a thread to read the websocket client connection
  15781. * This thread will automatically stop when mg_disconnect is
  15782. * called on the client connection */
  15783. if (mg_start_thread_with_id(websocket_client_thread,
  15784. thread_data,
  15785. conn->phys_ctx->worker_threadids)
  15786. != 0) {
  15787. conn->phys_ctx->cfg_worker_threads = 0;
  15788. mg_free(thread_data);
  15789. mg_close_connection(conn);
  15790. conn = NULL;
  15791. DEBUG_TRACE("%s",
  15792. "Websocket client connect thread could not be started\r\n");
  15793. }
  15794. #else
  15795. /* Appease "unused parameter" warnings */
  15796. (void)client_options;
  15797. (void)use_ssl;
  15798. (void)error_buffer;
  15799. (void)error_buffer_size;
  15800. (void)path;
  15801. (void)origin;
  15802. (void)user_data;
  15803. (void)data_func;
  15804. (void)close_func;
  15805. #endif
  15806. return conn;
  15807. }
  15808. struct mg_connection *
  15809. mg_connect_websocket_client(const char *host,
  15810. int port,
  15811. int use_ssl,
  15812. char *error_buffer,
  15813. size_t error_buffer_size,
  15814. const char *path,
  15815. const char *origin,
  15816. mg_websocket_data_handler data_func,
  15817. mg_websocket_close_handler close_func,
  15818. void *user_data)
  15819. {
  15820. struct mg_client_options client_options;
  15821. memset(&client_options, 0, sizeof(client_options));
  15822. client_options.host = host;
  15823. client_options.port = port;
  15824. return mg_connect_websocket_client_impl(&client_options,
  15825. use_ssl,
  15826. error_buffer,
  15827. error_buffer_size,
  15828. path,
  15829. origin,
  15830. data_func,
  15831. close_func,
  15832. user_data);
  15833. }
  15834. struct mg_connection *
  15835. mg_connect_websocket_client_secure(
  15836. const struct mg_client_options *client_options,
  15837. char *error_buffer,
  15838. size_t error_buffer_size,
  15839. const char *path,
  15840. const char *origin,
  15841. mg_websocket_data_handler data_func,
  15842. mg_websocket_close_handler close_func,
  15843. void *user_data)
  15844. {
  15845. if (!client_options) {
  15846. return NULL;
  15847. }
  15848. return mg_connect_websocket_client_impl(client_options,
  15849. 1,
  15850. error_buffer,
  15851. error_buffer_size,
  15852. path,
  15853. origin,
  15854. data_func,
  15855. close_func,
  15856. user_data);
  15857. }
  15858. /* Prepare connection data structure */
  15859. static void
  15860. init_connection(struct mg_connection *conn)
  15861. {
  15862. /* Is keep alive allowed by the server */
  15863. int keep_alive_enabled =
  15864. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15865. if (!keep_alive_enabled) {
  15866. conn->must_close = 1;
  15867. }
  15868. /* Important: on new connection, reset the receiving buffer. Credit
  15869. * goes to crule42. */
  15870. conn->data_len = 0;
  15871. conn->handled_requests = 0;
  15872. mg_set_user_connection_data(conn, NULL);
  15873. #if defined(USE_SERVER_STATS)
  15874. conn->conn_state = 2; /* init */
  15875. #endif
  15876. /* call the init_connection callback if assigned */
  15877. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15878. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15879. void *conn_data = NULL;
  15880. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15881. mg_set_user_connection_data(conn, conn_data);
  15882. }
  15883. }
  15884. }
  15885. /* Process a connection - may handle multiple requests
  15886. * using the same connection.
  15887. * Must be called with a valid connection (conn and
  15888. * conn->phys_ctx must be valid).
  15889. */
  15890. static void
  15891. process_new_connection(struct mg_connection *conn)
  15892. {
  15893. struct mg_request_info *ri = &conn->request_info;
  15894. int keep_alive, discard_len;
  15895. char ebuf[100];
  15896. const char *hostend;
  15897. int reqerr, uri_type;
  15898. #if defined(USE_SERVER_STATS)
  15899. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15900. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15901. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  15902. #endif
  15903. init_connection(conn);
  15904. DEBUG_TRACE("Start processing connection from %s",
  15905. conn->request_info.remote_addr);
  15906. /* Loop over multiple requests sent using the same connection
  15907. * (while "keep alive"). */
  15908. do {
  15909. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15910. conn->handled_requests + 1);
  15911. #if defined(USE_SERVER_STATS)
  15912. conn->conn_state = 3; /* ready */
  15913. #endif
  15914. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15915. /* The request sent by the client could not be understood by
  15916. * the server, or it was incomplete or a timeout. Send an
  15917. * error message and close the connection. */
  15918. if (reqerr > 0) {
  15919. DEBUG_ASSERT(ebuf[0] != '\0');
  15920. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15921. }
  15922. } else if (strcmp(ri->http_version, "1.0")
  15923. && strcmp(ri->http_version, "1.1")) {
  15924. /* HTTP/2 is not allowed here */
  15925. mg_snprintf(conn,
  15926. NULL, /* No truncation check for ebuf */
  15927. ebuf,
  15928. sizeof(ebuf),
  15929. "Bad HTTP version: [%s]",
  15930. ri->http_version);
  15931. mg_send_http_error(conn, 505, "%s", ebuf);
  15932. }
  15933. if (ebuf[0] == '\0') {
  15934. uri_type = get_uri_type(conn->request_info.request_uri);
  15935. switch (uri_type) {
  15936. case 1:
  15937. /* Asterisk */
  15938. conn->request_info.local_uri = 0;
  15939. /* TODO: Deal with '*'. */
  15940. break;
  15941. case 2:
  15942. /* relative uri */
  15943. conn->request_info.local_uri = conn->request_info.request_uri;
  15944. break;
  15945. case 3:
  15946. case 4:
  15947. /* absolute uri (with/without port) */
  15948. hostend = get_rel_url_at_current_server(
  15949. conn->request_info.request_uri, conn);
  15950. if (hostend) {
  15951. conn->request_info.local_uri = hostend;
  15952. } else {
  15953. conn->request_info.local_uri = NULL;
  15954. }
  15955. break;
  15956. default:
  15957. mg_snprintf(conn,
  15958. NULL, /* No truncation check for ebuf */
  15959. ebuf,
  15960. sizeof(ebuf),
  15961. "Invalid URI");
  15962. mg_send_http_error(conn, 400, "%s", ebuf);
  15963. conn->request_info.local_uri = NULL;
  15964. break;
  15965. }
  15966. #if defined(MG_LEGACY_INTERFACE)
  15967. /* Legacy before split into local_uri and request_uri */
  15968. conn->request_info.uri = conn->request_info.local_uri;
  15969. #endif
  15970. }
  15971. if (ebuf[0] != '\0') {
  15972. conn->protocol_type = -1;
  15973. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  15974. /* HTTP/1 allows protocol upgrade */
  15975. conn->protocol_type = should_switch_to_protocol(conn);
  15976. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15977. /* This will occur, if a HTTP/1.1 request should be upgraded
  15978. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15979. * Since most (all?) major browsers only support HTTP/2 using
  15980. * ALPN, this is hard to test and very low priority.
  15981. * Deactivate it (at least for now).
  15982. */
  15983. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15984. }
  15985. }
  15986. DEBUG_TRACE("http: %s, error: %s",
  15987. (ri->http_version ? ri->http_version : "none"),
  15988. (ebuf[0] ? ebuf : "none"));
  15989. if (ebuf[0] == '\0') {
  15990. if (conn->request_info.local_uri) {
  15991. /* handle request to local server */
  15992. #if defined(USE_SERVER_STATS)
  15993. conn->conn_state = 4; /* processing */
  15994. #endif
  15995. handle_request(conn);
  15996. #if defined(USE_SERVER_STATS)
  15997. conn->conn_state = 5; /* processed */
  15998. mg_atomic_add64(&(conn->phys_ctx->total_data_read),
  15999. conn->consumed_content);
  16000. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  16001. conn->num_bytes_sent);
  16002. #endif
  16003. DEBUG_TRACE("%s", "handle_request done");
  16004. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16005. conn->phys_ctx->callbacks.end_request(conn,
  16006. conn->status_code);
  16007. DEBUG_TRACE("%s", "end_request callback done");
  16008. }
  16009. log_access(conn);
  16010. } else {
  16011. /* TODO: handle non-local request (PROXY) */
  16012. conn->must_close = 1;
  16013. }
  16014. } else {
  16015. conn->must_close = 1;
  16016. }
  16017. if (ri->remote_user != NULL) {
  16018. mg_free((void *)ri->remote_user);
  16019. /* Important! When having connections with and without auth
  16020. * would cause double free and then crash */
  16021. ri->remote_user = NULL;
  16022. }
  16023. /* NOTE(lsm): order is important here. should_keep_alive() call
  16024. * is using parsed request, which will be invalid after
  16025. * memmove's below.
  16026. * Therefore, memorize should_keep_alive() result now for later
  16027. * use in loop exit condition. */
  16028. /* Enable it only if this request is completely discardable. */
  16029. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16030. && should_keep_alive(conn) && (conn->content_len >= 0)
  16031. && (conn->request_len > 0)
  16032. && ((conn->is_chunked == 4)
  16033. || (!conn->is_chunked
  16034. && ((conn->consumed_content == conn->content_len)
  16035. || ((conn->request_len + conn->content_len)
  16036. <= conn->data_len))))
  16037. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16038. if (keep_alive) {
  16039. /* Discard all buffered data for this request */
  16040. discard_len =
  16041. ((conn->request_len + conn->content_len) < conn->data_len)
  16042. ? (int)(conn->request_len + conn->content_len)
  16043. : conn->data_len;
  16044. conn->data_len -= discard_len;
  16045. if (conn->data_len > 0) {
  16046. DEBUG_TRACE("discard_len = %d", discard_len);
  16047. memmove(conn->buf,
  16048. conn->buf + discard_len,
  16049. (size_t)conn->data_len);
  16050. }
  16051. }
  16052. DEBUG_ASSERT(conn->data_len >= 0);
  16053. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16054. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16055. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16056. (long int)conn->data_len,
  16057. (long int)conn->buf_size);
  16058. break;
  16059. }
  16060. conn->handled_requests++;
  16061. } while (keep_alive);
  16062. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16063. conn->request_info.remote_addr,
  16064. difftime(time(NULL), conn->conn_birth_time));
  16065. close_connection(conn);
  16066. #if defined(USE_SERVER_STATS)
  16067. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16068. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16069. #endif
  16070. }
  16071. #if defined(ALTERNATIVE_QUEUE)
  16072. static void
  16073. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16074. {
  16075. unsigned int i;
  16076. while (!ctx->stop_flag) {
  16077. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16078. /* find a free worker slot and signal it */
  16079. if (ctx->client_socks[i].in_use == 2) {
  16080. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16081. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16082. ctx->client_socks[i] = *sp;
  16083. ctx->client_socks[i].in_use = 1;
  16084. /* socket has been moved to the consumer */
  16085. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16086. (void)event_signal(ctx->client_wait_events[i]);
  16087. return;
  16088. }
  16089. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16090. }
  16091. }
  16092. /* queue is full */
  16093. mg_sleep(1);
  16094. }
  16095. /* must consume */
  16096. set_blocking_mode(sp->sock);
  16097. closesocket(sp->sock);
  16098. }
  16099. static int
  16100. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16101. {
  16102. DEBUG_TRACE("%s", "going idle");
  16103. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16104. ctx->client_socks[thread_index].in_use = 2;
  16105. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16106. event_wait(ctx->client_wait_events[thread_index]);
  16107. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16108. *sp = ctx->client_socks[thread_index];
  16109. if (ctx->stop_flag) {
  16110. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16111. if (sp->in_use == 1) {
  16112. /* must consume */
  16113. set_blocking_mode(sp->sock);
  16114. closesocket(sp->sock);
  16115. }
  16116. return 0;
  16117. }
  16118. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16119. if (sp->in_use == 1) {
  16120. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16121. return 1;
  16122. }
  16123. /* must not reach here */
  16124. DEBUG_ASSERT(0);
  16125. return 0;
  16126. }
  16127. #else /* ALTERNATIVE_QUEUE */
  16128. /* Worker threads take accepted socket from the queue */
  16129. static int
  16130. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16131. {
  16132. (void)thread_index;
  16133. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16134. DEBUG_TRACE("%s", "going idle");
  16135. /* If the queue is empty, wait. We're idle at this point. */
  16136. while ((ctx->sq_head == ctx->sq_tail)
  16137. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16138. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16139. }
  16140. /* If we're stopping, sq_head may be equal to sq_tail. */
  16141. if (ctx->sq_head > ctx->sq_tail) {
  16142. /* Copy socket from the queue and increment tail */
  16143. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16144. ctx->sq_tail++;
  16145. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16146. /* Wrap pointers if needed */
  16147. while (ctx->sq_tail > ctx->sq_size) {
  16148. ctx->sq_tail -= ctx->sq_size;
  16149. ctx->sq_head -= ctx->sq_size;
  16150. }
  16151. }
  16152. (void)pthread_cond_signal(&ctx->sq_empty);
  16153. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16154. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16155. }
  16156. /* Master thread adds accepted socket to a queue */
  16157. static void
  16158. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16159. {
  16160. int queue_filled;
  16161. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16162. queue_filled = ctx->sq_head - ctx->sq_tail;
  16163. /* If the queue is full, wait */
  16164. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16165. && (queue_filled >= ctx->sq_size)) {
  16166. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16167. #if defined(USE_SERVER_STATS)
  16168. if (queue_filled > ctx->sq_max_fill) {
  16169. ctx->sq_max_fill = queue_filled;
  16170. }
  16171. #endif
  16172. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16173. ctx->sq_blocked = 0; /* Not blocked now */
  16174. queue_filled = ctx->sq_head - ctx->sq_tail;
  16175. }
  16176. if (queue_filled < ctx->sq_size) {
  16177. /* Copy socket to the queue and increment head */
  16178. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16179. ctx->sq_head++;
  16180. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16181. }
  16182. queue_filled = ctx->sq_head - ctx->sq_tail;
  16183. #if defined(USE_SERVER_STATS)
  16184. if (queue_filled > ctx->sq_max_fill) {
  16185. ctx->sq_max_fill = queue_filled;
  16186. }
  16187. #endif
  16188. (void)pthread_cond_signal(&ctx->sq_full);
  16189. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16190. }
  16191. #endif /* ALTERNATIVE_QUEUE */
  16192. static void
  16193. worker_thread_run(struct mg_connection *conn)
  16194. {
  16195. struct mg_context *ctx = conn->phys_ctx;
  16196. int thread_index;
  16197. struct mg_workerTLS tls;
  16198. #if defined(MG_LEGACY_INTERFACE)
  16199. uint32_t addr;
  16200. #endif
  16201. mg_set_thread_name("worker");
  16202. tls.is_master = 0;
  16203. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16204. #if defined(_WIN32)
  16205. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16206. #endif
  16207. /* Initialize thread local storage before calling any callback */
  16208. pthread_setspecific(sTlsKey, &tls);
  16209. /* Check if there is a user callback */
  16210. if (ctx->callbacks.init_thread) {
  16211. /* call init_thread for a worker thread (type 1), and store the
  16212. * return value */
  16213. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16214. } else {
  16215. /* No callback: set user pointer to NULL */
  16216. tls.user_ptr = NULL;
  16217. }
  16218. /* Connection structure has been pre-allocated */
  16219. thread_index = (int)(conn - ctx->worker_connections);
  16220. if ((thread_index < 0)
  16221. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16222. mg_cry_ctx_internal(ctx,
  16223. "Internal error: Invalid worker index %i",
  16224. thread_index);
  16225. return;
  16226. }
  16227. /* Request buffers are not pre-allocated. They are private to the
  16228. * request and do not contain any state information that might be
  16229. * of interest to anyone observing a server status. */
  16230. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16231. if (conn->buf == NULL) {
  16232. mg_cry_ctx_internal(
  16233. ctx,
  16234. "Out of memory: Cannot allocate buffer for worker %i",
  16235. thread_index);
  16236. return;
  16237. }
  16238. conn->buf_size = (int)ctx->max_request_size;
  16239. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16240. conn->host = NULL; /* until we have more information. */
  16241. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16242. conn->request_info.user_data = ctx->user_data;
  16243. /* Allocate a mutex for this connection to allow communication both
  16244. * within the request handler and from elsewhere in the application
  16245. */
  16246. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16247. mg_free(conn->buf);
  16248. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16249. return;
  16250. }
  16251. #if defined(USE_SERVER_STATS)
  16252. conn->conn_state = 1; /* not consumed */
  16253. #endif
  16254. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16255. * signal sq_empty condvar to wake up the master waiting in
  16256. * produce_socket() */
  16257. while (consume_socket(ctx, &conn->client, thread_index)) {
  16258. /* New connections must start with new protocol negotiation */
  16259. tls.alpn_proto = NULL;
  16260. #if defined(USE_SERVER_STATS)
  16261. conn->conn_close_time = 0;
  16262. #endif
  16263. conn->conn_birth_time = time(NULL);
  16264. /* Fill in IP, port info early so even if SSL setup below fails,
  16265. * error handler would have the corresponding info.
  16266. * Thanks to Johannes Winkelmann for the patch.
  16267. */
  16268. #if defined(USE_IPV6)
  16269. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  16270. conn->request_info.remote_port =
  16271. ntohs(conn->client.rsa.sin6.sin6_port);
  16272. } else
  16273. #endif
  16274. {
  16275. conn->request_info.remote_port =
  16276. ntohs(conn->client.rsa.sin.sin_port);
  16277. }
  16278. sockaddr_to_string(conn->request_info.remote_addr,
  16279. sizeof(conn->request_info.remote_addr),
  16280. &conn->client.rsa);
  16281. DEBUG_TRACE("Start processing connection from %s",
  16282. conn->request_info.remote_addr);
  16283. conn->request_info.is_ssl = conn->client.is_ssl;
  16284. if (conn->client.is_ssl) {
  16285. #if !defined(NO_SSL)
  16286. /* HTTPS connection */
  16287. if (sslize(conn,
  16288. SSL_accept,
  16289. NULL)) {
  16290. /* conn->dom_ctx is set in get_request */
  16291. /* Get SSL client certificate information (if set) */
  16292. struct mg_client_cert client_cert;
  16293. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16294. conn->request_info.client_cert = &client_cert;
  16295. }
  16296. /* process HTTPS connection */
  16297. #if defined(USE_HTTP2)
  16298. if ((tls.alpn_proto != NULL)
  16299. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16300. /* process HTTPS/2 connection */
  16301. init_connection(conn);
  16302. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16303. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16304. conn->content_len = -1;
  16305. conn->is_chunked = 0;
  16306. process_new_http2_connection(conn);
  16307. } else
  16308. #endif
  16309. {
  16310. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16311. process_new_connection(conn);
  16312. }
  16313. /* Free client certificate info */
  16314. if (conn->request_info.client_cert) {
  16315. mg_free((void *)(conn->request_info.client_cert->subject));
  16316. mg_free((void *)(conn->request_info.client_cert->issuer));
  16317. mg_free((void *)(conn->request_info.client_cert->serial));
  16318. mg_free((void *)(conn->request_info.client_cert->finger));
  16319. /* Free certificate memory */
  16320. X509_free(
  16321. (X509 *)conn->request_info.client_cert->peer_cert);
  16322. conn->request_info.client_cert->peer_cert = 0;
  16323. conn->request_info.client_cert->subject = 0;
  16324. conn->request_info.client_cert->issuer = 0;
  16325. conn->request_info.client_cert->serial = 0;
  16326. conn->request_info.client_cert->finger = 0;
  16327. conn->request_info.client_cert = 0;
  16328. }
  16329. } else {
  16330. /* make sure the connection is cleaned up on SSL failure */
  16331. close_connection(conn);
  16332. }
  16333. #endif
  16334. } else {
  16335. /* process HTTP connection */
  16336. process_new_connection(conn);
  16337. }
  16338. DEBUG_TRACE("%s", "Connection closed");
  16339. #if defined(USE_SERVER_STATS)
  16340. conn->conn_close_time = time(NULL);
  16341. #endif
  16342. }
  16343. /* Call exit thread user callback */
  16344. if (ctx->callbacks.exit_thread) {
  16345. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16346. }
  16347. /* delete thread local storage objects */
  16348. pthread_setspecific(sTlsKey, NULL);
  16349. #if defined(_WIN32)
  16350. CloseHandle(tls.pthread_cond_helper_mutex);
  16351. #endif
  16352. pthread_mutex_destroy(&conn->mutex);
  16353. /* Free the request buffer. */
  16354. conn->buf_size = 0;
  16355. mg_free(conn->buf);
  16356. conn->buf = NULL;
  16357. #if defined(USE_SERVER_STATS)
  16358. conn->conn_state = 9; /* done */
  16359. #endif
  16360. DEBUG_TRACE("%s", "exiting");
  16361. }
  16362. /* Threads have different return types on Windows and Unix. */
  16363. #if defined(_WIN32)
  16364. static unsigned __stdcall worker_thread(void *thread_func_param)
  16365. {
  16366. worker_thread_run((struct mg_connection *)thread_func_param);
  16367. return 0;
  16368. }
  16369. #else
  16370. static void *
  16371. worker_thread(void *thread_func_param)
  16372. {
  16373. #if !defined(__ZEPHYR__)
  16374. struct sigaction sa;
  16375. /* Ignore SIGPIPE */
  16376. memset(&sa, 0, sizeof(sa));
  16377. sa.sa_handler = SIG_IGN;
  16378. sigaction(SIGPIPE, &sa, NULL);
  16379. #endif
  16380. worker_thread_run((struct mg_connection *)thread_func_param);
  16381. return NULL;
  16382. }
  16383. #endif /* _WIN32 */
  16384. /* This is an internal function, thus all arguments are expected to be
  16385. * valid - a NULL check is not required. */
  16386. static void
  16387. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16388. {
  16389. struct socket so;
  16390. char src_addr[IP_ADDR_STR_LEN];
  16391. socklen_t len = sizeof(so.rsa);
  16392. #if !defined(__ZEPHYR__)
  16393. int on = 1;
  16394. #endif
  16395. memset(&so, 0, sizeof(so));
  16396. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16397. == INVALID_SOCKET) {
  16398. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16399. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16400. mg_cry_ctx_internal(ctx,
  16401. "%s: %s is not allowed to connect",
  16402. __func__,
  16403. src_addr);
  16404. closesocket(so.sock);
  16405. } else {
  16406. /* Put so socket structure into the queue */
  16407. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16408. set_close_on_exec(so.sock, NULL, ctx);
  16409. so.is_ssl = listener->is_ssl;
  16410. so.ssl_redir = listener->ssl_redir;
  16411. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16412. mg_cry_ctx_internal(ctx,
  16413. "%s: getsockname() failed: %s",
  16414. __func__,
  16415. strerror(ERRNO));
  16416. }
  16417. #if !defined(__ZEPHYR__)
  16418. /* Set TCP keep-alive. This is needed because if HTTP-level
  16419. * keep-alive
  16420. * is enabled, and client resets the connection, server won't get
  16421. * TCP FIN or RST and will keep the connection open forever. With
  16422. * TCP keep-alive, next keep-alive handshake will figure out that
  16423. * the client is down and will close the server end.
  16424. * Thanks to Igor Klopov who suggested the patch. */
  16425. if (setsockopt(so.sock,
  16426. SOL_SOCKET,
  16427. SO_KEEPALIVE,
  16428. (SOCK_OPT_TYPE)&on,
  16429. sizeof(on))
  16430. != 0) {
  16431. mg_cry_ctx_internal(
  16432. ctx,
  16433. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16434. __func__,
  16435. strerror(ERRNO));
  16436. }
  16437. #endif
  16438. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16439. * to effectively fill up the underlying IP packet payload and
  16440. * reduce the overhead of sending lots of small buffers. However
  16441. * this hurts the server's throughput (ie. operations per second)
  16442. * when HTTP 1.1 persistent connections are used and the responses
  16443. * are relatively small (eg. less than 1400 bytes).
  16444. */
  16445. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16446. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16447. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16448. mg_cry_ctx_internal(
  16449. ctx,
  16450. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16451. __func__,
  16452. strerror(ERRNO));
  16453. }
  16454. }
  16455. /* The "non blocking" property should already be
  16456. * inherited from the parent socket. Set it for
  16457. * non-compliant socket implementations. */
  16458. set_non_blocking_mode(so.sock);
  16459. so.in_use = 0;
  16460. produce_socket(ctx, &so);
  16461. }
  16462. }
  16463. static void
  16464. master_thread_run(struct mg_context *ctx)
  16465. {
  16466. struct mg_workerTLS tls;
  16467. struct mg_pollfd *pfd;
  16468. unsigned int i;
  16469. unsigned int workerthreadcount;
  16470. if (!ctx) {
  16471. return;
  16472. }
  16473. mg_set_thread_name("master");
  16474. /* Increase priority of the master thread */
  16475. #if defined(_WIN32)
  16476. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16477. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16478. int min_prio = sched_get_priority_min(SCHED_RR);
  16479. int max_prio = sched_get_priority_max(SCHED_RR);
  16480. if ((min_prio >= 0) && (max_prio >= 0)
  16481. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16482. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16483. struct sched_param sched_param = {0};
  16484. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16485. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16486. }
  16487. #endif
  16488. /* Initialize thread local storage */
  16489. #if defined(_WIN32)
  16490. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16491. #endif
  16492. tls.is_master = 1;
  16493. pthread_setspecific(sTlsKey, &tls);
  16494. if (ctx->callbacks.init_thread) {
  16495. /* Callback for the master thread (type 0) */
  16496. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16497. } else {
  16498. tls.user_ptr = NULL;
  16499. }
  16500. /* Server starts *now* */
  16501. ctx->start_time = time(NULL);
  16502. /* Start the server */
  16503. pfd = ctx->listening_socket_fds;
  16504. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16505. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16506. pfd[i].fd = ctx->listening_sockets[i].sock;
  16507. pfd[i].events = POLLIN;
  16508. }
  16509. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16510. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16511. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16512. * successful poll, and POLLIN is defined as
  16513. * (POLLRDNORM | POLLRDBAND)
  16514. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16515. * pfd[i].revents == POLLIN. */
  16516. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16517. && (pfd[i].revents & POLLIN)) {
  16518. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16519. }
  16520. }
  16521. }
  16522. }
  16523. /* Here stop_flag is 1 - Initiate shutdown. */
  16524. DEBUG_TRACE("%s", "stopping workers");
  16525. /* Stop signal received: somebody called mg_stop. Quit. */
  16526. close_all_listening_sockets(ctx);
  16527. /* Wakeup workers that are waiting for connections to handle. */
  16528. #if defined(ALTERNATIVE_QUEUE)
  16529. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16530. event_signal(ctx->client_wait_events[i]);
  16531. }
  16532. #else
  16533. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16534. pthread_cond_broadcast(&ctx->sq_full);
  16535. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16536. #endif
  16537. /* Join all worker threads to avoid leaking threads. */
  16538. workerthreadcount = ctx->cfg_worker_threads;
  16539. for (i = 0; i < workerthreadcount; i++) {
  16540. if (ctx->worker_threadids[i] != 0) {
  16541. mg_join_thread(ctx->worker_threadids[i]);
  16542. }
  16543. }
  16544. #if defined(USE_LUA)
  16545. /* Free Lua state of lua background task */
  16546. if (ctx->lua_background_state) {
  16547. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16548. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16549. if (lua_istable(lstate, -1)) {
  16550. reg_boolean(lstate, "shutdown", 1);
  16551. lua_pop(lstate, 1);
  16552. mg_sleep(2);
  16553. }
  16554. lua_close(lstate);
  16555. ctx->lua_background_state = 0;
  16556. }
  16557. #endif
  16558. DEBUG_TRACE("%s", "exiting");
  16559. /* call exit thread callback */
  16560. if (ctx->callbacks.exit_thread) {
  16561. /* Callback for the master thread (type 0) */
  16562. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16563. }
  16564. #if defined(_WIN32)
  16565. CloseHandle(tls.pthread_cond_helper_mutex);
  16566. #endif
  16567. pthread_setspecific(sTlsKey, NULL);
  16568. /* Signal mg_stop() that we're done.
  16569. * WARNING: This must be the very last thing this
  16570. * thread does, as ctx becomes invalid after this line. */
  16571. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16572. }
  16573. /* Threads have different return types on Windows and Unix. */
  16574. #if defined(_WIN32)
  16575. static unsigned __stdcall master_thread(void *thread_func_param)
  16576. {
  16577. master_thread_run((struct mg_context *)thread_func_param);
  16578. return 0;
  16579. }
  16580. #else
  16581. static void *
  16582. master_thread(void *thread_func_param)
  16583. {
  16584. #if !defined(__ZEPHYR__)
  16585. struct sigaction sa;
  16586. /* Ignore SIGPIPE */
  16587. memset(&sa, 0, sizeof(sa));
  16588. sa.sa_handler = SIG_IGN;
  16589. sigaction(SIGPIPE, &sa, NULL);
  16590. #endif
  16591. master_thread_run((struct mg_context *)thread_func_param);
  16592. return NULL;
  16593. }
  16594. #endif /* _WIN32 */
  16595. static void
  16596. free_context(struct mg_context *ctx)
  16597. {
  16598. int i;
  16599. struct mg_handler_info *tmp_rh;
  16600. if (ctx == NULL) {
  16601. return;
  16602. }
  16603. if (ctx->callbacks.exit_context) {
  16604. ctx->callbacks.exit_context(ctx);
  16605. }
  16606. /* All threads exited, no sync is needed. Destroy thread mutex and
  16607. * condvars
  16608. */
  16609. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16610. #if defined(ALTERNATIVE_QUEUE)
  16611. mg_free(ctx->client_socks);
  16612. if (ctx->client_wait_events != NULL) {
  16613. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16614. event_destroy(ctx->client_wait_events[i]);
  16615. }
  16616. mg_free(ctx->client_wait_events);
  16617. }
  16618. #else
  16619. (void)pthread_cond_destroy(&ctx->sq_empty);
  16620. (void)pthread_cond_destroy(&ctx->sq_full);
  16621. mg_free(ctx->squeue);
  16622. #endif
  16623. /* Destroy other context global data structures mutex */
  16624. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16625. #if defined(USE_TIMERS)
  16626. timers_exit(ctx);
  16627. #endif
  16628. /* Deallocate config parameters */
  16629. for (i = 0; i < NUM_OPTIONS; i++) {
  16630. if (ctx->dd.config[i] != NULL) {
  16631. #if defined(_MSC_VER)
  16632. #pragma warning(suppress : 6001)
  16633. #endif
  16634. mg_free(ctx->dd.config[i]);
  16635. }
  16636. }
  16637. /* Deallocate request handlers */
  16638. while (ctx->dd.handlers) {
  16639. tmp_rh = ctx->dd.handlers;
  16640. ctx->dd.handlers = tmp_rh->next;
  16641. mg_free(tmp_rh->uri);
  16642. mg_free(tmp_rh);
  16643. }
  16644. #if !defined(NO_SSL)
  16645. /* Deallocate SSL context */
  16646. if (ctx->dd.ssl_ctx != NULL) {
  16647. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16648. int callback_ret =
  16649. (ctx->callbacks.external_ssl_ctx == NULL)
  16650. ? 0
  16651. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16652. if (callback_ret == 0) {
  16653. SSL_CTX_free(ctx->dd.ssl_ctx);
  16654. }
  16655. /* else: ignore error and ommit SSL_CTX_free in case
  16656. * callback_ret is 1 */
  16657. }
  16658. #endif /* !NO_SSL */
  16659. /* Deallocate worker thread ID array */
  16660. mg_free(ctx->worker_threadids);
  16661. /* Deallocate worker thread ID array */
  16662. mg_free(ctx->worker_connections);
  16663. /* deallocate system name string */
  16664. mg_free(ctx->systemName);
  16665. /* Deallocate context itself */
  16666. mg_free(ctx);
  16667. }
  16668. void
  16669. mg_stop(struct mg_context *ctx)
  16670. {
  16671. pthread_t mt;
  16672. if (!ctx) {
  16673. return;
  16674. }
  16675. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16676. * two threads is not allowed. */
  16677. mt = ctx->masterthreadid;
  16678. if (mt == 0) {
  16679. return;
  16680. }
  16681. ctx->masterthreadid = 0;
  16682. /* Set stop flag, so all threads know they have to exit. */
  16683. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16684. /* Wait until everything has stopped. */
  16685. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16686. (void)mg_sleep(10);
  16687. }
  16688. mg_join_thread(mt);
  16689. free_context(ctx);
  16690. #if defined(_WIN32)
  16691. (void)WSACleanup();
  16692. #endif /* _WIN32 */
  16693. }
  16694. static void
  16695. get_system_name(char **sysName)
  16696. {
  16697. #if defined(_WIN32)
  16698. #if defined(_WIN32_WCE)
  16699. *sysName = mg_strdup("WinCE");
  16700. #else
  16701. char name[128];
  16702. DWORD dwVersion = 0;
  16703. DWORD dwMajorVersion = 0;
  16704. DWORD dwMinorVersion = 0;
  16705. DWORD dwBuild = 0;
  16706. BOOL wowRet, isWoW = FALSE;
  16707. #if defined(_MSC_VER)
  16708. #pragma warning(push)
  16709. /* GetVersion was declared deprecated */
  16710. #pragma warning(disable : 4996)
  16711. #endif
  16712. dwVersion = GetVersion();
  16713. #if defined(_MSC_VER)
  16714. #pragma warning(pop)
  16715. #endif
  16716. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16717. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16718. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16719. (void)dwBuild;
  16720. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16721. sprintf(name,
  16722. "Windows %u.%u%s",
  16723. (unsigned)dwMajorVersion,
  16724. (unsigned)dwMinorVersion,
  16725. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16726. *sysName = mg_strdup(name);
  16727. #endif
  16728. #elif defined(__ZEPHYR__)
  16729. *sysName = mg_strdup("Zephyr OS");
  16730. #else
  16731. struct utsname name;
  16732. memset(&name, 0, sizeof(name));
  16733. uname(&name);
  16734. *sysName = mg_strdup(name.sysname);
  16735. #endif
  16736. }
  16737. static void
  16738. legacy_init(const char **options)
  16739. {
  16740. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16741. if (options) {
  16742. const char **run_options = options;
  16743. const char *optname = config_options[LISTENING_PORTS].name;
  16744. /* Try to find the "listening_ports" option */
  16745. while (*run_options) {
  16746. if (!strcmp(*run_options, optname)) {
  16747. ports_option = run_options[1];
  16748. }
  16749. run_options += 2;
  16750. }
  16751. }
  16752. if (is_ssl_port_used(ports_option)) {
  16753. /* Initialize with SSL support */
  16754. mg_init_library(MG_FEATURES_TLS);
  16755. } else {
  16756. /* Initialize without SSL support */
  16757. mg_init_library(MG_FEATURES_DEFAULT);
  16758. }
  16759. }
  16760. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16761. static
  16762. #endif
  16763. struct mg_context *
  16764. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16765. {
  16766. struct mg_context *ctx;
  16767. const char *name, *value, *default_value;
  16768. int idx, ok, workerthreadcount;
  16769. unsigned int i;
  16770. int itmp;
  16771. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16772. const char **options =
  16773. ((init != NULL) ? (init->configuration_options) : (NULL));
  16774. struct mg_workerTLS tls;
  16775. #if defined(_WIN32)
  16776. WSADATA data;
  16777. WSAStartup(MAKEWORD(2, 2), &data);
  16778. #endif /* _WIN32 */
  16779. if (error != NULL) {
  16780. error->code = 0;
  16781. if (error->text_buffer_size > 0) {
  16782. *error->text = 0;
  16783. }
  16784. }
  16785. if (mg_init_library_called == 0) {
  16786. /* Legacy INIT, if mg_start is called without mg_init_library.
  16787. * Note: This will cause a memory leak when unloading the library.
  16788. */
  16789. legacy_init(options);
  16790. }
  16791. if (mg_init_library_called == 0) {
  16792. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16793. mg_snprintf(NULL,
  16794. NULL, /* No truncation check for error buffers */
  16795. error->text,
  16796. error->text_buffer_size,
  16797. "%s",
  16798. "Library uninitialized");
  16799. }
  16800. return NULL;
  16801. }
  16802. /* Allocate context and initialize reasonable general case defaults. */
  16803. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16804. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16805. mg_snprintf(NULL,
  16806. NULL, /* No truncation check for error buffers */
  16807. error->text,
  16808. error->text_buffer_size,
  16809. "%s",
  16810. "Out of memory");
  16811. }
  16812. return NULL;
  16813. }
  16814. /* Random number generator will initialize at the first call */
  16815. ctx->dd.auth_nonce_mask =
  16816. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16817. /* Save started thread index to reuse in other external API calls
  16818. * For the sake of thread synchronization all non-civetweb threads
  16819. * can be considered as single external thread */
  16820. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16821. tls.is_master = -1; /* Thread calling mg_start */
  16822. tls.thread_idx = ctx->starter_thread_idx;
  16823. #if defined(_WIN32)
  16824. tls.pthread_cond_helper_mutex = NULL;
  16825. #endif
  16826. pthread_setspecific(sTlsKey, &tls);
  16827. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16828. #if !defined(ALTERNATIVE_QUEUE)
  16829. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16830. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16831. ctx->sq_blocked = 0;
  16832. #endif
  16833. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16834. if (!ok) {
  16835. const char *err_msg =
  16836. "Cannot initialize thread synchronization objects";
  16837. /* Fatal error - abort start. However, this situation should never
  16838. * occur in practice. */
  16839. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16840. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16841. mg_snprintf(NULL,
  16842. NULL, /* No truncation check for error buffers */
  16843. error->text,
  16844. error->text_buffer_size,
  16845. "%s",
  16846. err_msg);
  16847. }
  16848. mg_free(ctx);
  16849. pthread_setspecific(sTlsKey, NULL);
  16850. return NULL;
  16851. }
  16852. if ((init != NULL) && (init->callbacks != NULL)) {
  16853. /* Set all callbacks except exit_context. */
  16854. ctx->callbacks = *init->callbacks;
  16855. exit_callback = init->callbacks->exit_context;
  16856. /* The exit callback is activated once the context is successfully
  16857. * created. It should not be called, if an incomplete context object
  16858. * is deleted during a failed initialization. */
  16859. ctx->callbacks.exit_context = 0;
  16860. }
  16861. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16862. ctx->dd.handlers = NULL;
  16863. ctx->dd.next = NULL;
  16864. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16865. ctx->dd.shared_lua_websockets = NULL;
  16866. #endif
  16867. /* Store options */
  16868. while (options && (name = *options++) != NULL) {
  16869. if ((idx = get_option_index(name)) == -1) {
  16870. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16871. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16872. mg_snprintf(NULL,
  16873. NULL, /* No truncation check for error buffers */
  16874. error->text,
  16875. error->text_buffer_size,
  16876. "Invalid configuration option: %s",
  16877. name);
  16878. }
  16879. free_context(ctx);
  16880. pthread_setspecific(sTlsKey, NULL);
  16881. return NULL;
  16882. } else if ((value = *options++) == NULL) {
  16883. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16884. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16885. mg_snprintf(NULL,
  16886. NULL, /* No truncation check for error buffers */
  16887. error->text,
  16888. error->text_buffer_size,
  16889. "Invalid configuration option value: %s",
  16890. name);
  16891. }
  16892. free_context(ctx);
  16893. pthread_setspecific(sTlsKey, NULL);
  16894. return NULL;
  16895. }
  16896. if (ctx->dd.config[idx] != NULL) {
  16897. /* A duplicate configuration option is not an error - the last
  16898. * option value will be used. */
  16899. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16900. mg_free(ctx->dd.config[idx]);
  16901. }
  16902. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16903. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16904. }
  16905. /* Set default value if needed */
  16906. for (i = 0; config_options[i].name != NULL; i++) {
  16907. default_value = config_options[i].default_value;
  16908. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16909. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16910. }
  16911. }
  16912. /* Request size option */
  16913. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16914. if (itmp < 1024) {
  16915. mg_cry_ctx_internal(ctx,
  16916. "%s too small",
  16917. config_options[MAX_REQUEST_SIZE].name);
  16918. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16919. mg_snprintf(NULL,
  16920. NULL, /* No truncation check for error buffers */
  16921. error->text,
  16922. error->text_buffer_size,
  16923. "Invalid configuration option value: %s",
  16924. config_options[MAX_REQUEST_SIZE].name);
  16925. }
  16926. free_context(ctx);
  16927. pthread_setspecific(sTlsKey, NULL);
  16928. return NULL;
  16929. }
  16930. ctx->max_request_size = (unsigned)itmp;
  16931. /* Queue length */
  16932. #if !defined(ALTERNATIVE_QUEUE)
  16933. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16934. if (itmp < 1) {
  16935. mg_cry_ctx_internal(ctx,
  16936. "%s too small",
  16937. config_options[CONNECTION_QUEUE_SIZE].name);
  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. "Invalid configuration option value: %s",
  16944. config_options[CONNECTION_QUEUE_SIZE].name);
  16945. }
  16946. free_context(ctx);
  16947. pthread_setspecific(sTlsKey, NULL);
  16948. return NULL;
  16949. }
  16950. ctx->squeue =
  16951. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16952. if (ctx->squeue == NULL) {
  16953. mg_cry_ctx_internal(ctx,
  16954. "Out of memory: Cannot allocate %s",
  16955. config_options[CONNECTION_QUEUE_SIZE].name);
  16956. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16957. mg_snprintf(NULL,
  16958. NULL, /* No truncation check for error buffers */
  16959. error->text,
  16960. error->text_buffer_size,
  16961. "Out of memory: Cannot allocate %s",
  16962. config_options[CONNECTION_QUEUE_SIZE].name);
  16963. }
  16964. free_context(ctx);
  16965. pthread_setspecific(sTlsKey, NULL);
  16966. return NULL;
  16967. }
  16968. ctx->sq_size = itmp;
  16969. #endif
  16970. /* Worker thread count option */
  16971. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16972. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16973. if (workerthreadcount <= 0) {
  16974. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16975. } else {
  16976. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16977. }
  16978. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16979. mg_snprintf(NULL,
  16980. NULL, /* No truncation check for error buffers */
  16981. error->text,
  16982. error->text_buffer_size,
  16983. "Invalid configuration option value: %s",
  16984. config_options[NUM_THREADS].name);
  16985. }
  16986. free_context(ctx);
  16987. pthread_setspecific(sTlsKey, NULL);
  16988. return NULL;
  16989. }
  16990. /* Document root */
  16991. #if defined(NO_FILES)
  16992. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16993. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16994. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16995. mg_snprintf(NULL,
  16996. NULL, /* No truncation check for error buffers */
  16997. error->text,
  16998. error->text_buffer_size,
  16999. "Invalid configuration option value: %s",
  17000. config_options[DOCUMENT_ROOT].name);
  17001. }
  17002. free_context(ctx);
  17003. pthread_setspecific(sTlsKey, NULL);
  17004. return NULL;
  17005. }
  17006. #endif
  17007. get_system_name(&ctx->systemName);
  17008. #if defined(USE_LUA)
  17009. /* If a Lua background script has been configured, start it. */
  17010. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17011. char ebuf[256];
  17012. struct vec opt_vec;
  17013. struct vec eq_vec;
  17014. const char *sparams;
  17015. lua_State *state = mg_prepare_lua_context_script(
  17016. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17017. if (!state) {
  17018. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  17019. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17020. mg_snprintf(NULL,
  17021. NULL, /* No truncation check for error buffers */
  17022. error->text,
  17023. error->text_buffer_size,
  17024. "Error in script %s: %s",
  17025. config_options[DOCUMENT_ROOT].name,
  17026. ebuf);
  17027. }
  17028. free_context(ctx);
  17029. pthread_setspecific(sTlsKey, NULL);
  17030. return NULL;
  17031. }
  17032. ctx->lua_background_state = (void *)state;
  17033. lua_newtable(state);
  17034. reg_boolean(state, "shutdown", 0);
  17035. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17036. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17037. reg_llstring(
  17038. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17039. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17040. break;
  17041. }
  17042. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17043. } else {
  17044. ctx->lua_background_state = 0;
  17045. }
  17046. #endif
  17047. /* Step by step initialization of ctx - depending on build options */
  17048. #if !defined(NO_FILESYSTEMS)
  17049. if (!set_gpass_option(ctx, NULL)) {
  17050. const char *err_msg = "Invalid global password file";
  17051. /* Fatal error - abort start. */
  17052. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17053. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17054. mg_snprintf(NULL,
  17055. NULL, /* No truncation check for error buffers */
  17056. error->text,
  17057. error->text_buffer_size,
  17058. "%s",
  17059. err_msg);
  17060. }
  17061. free_context(ctx);
  17062. pthread_setspecific(sTlsKey, NULL);
  17063. return NULL;
  17064. }
  17065. #endif
  17066. #if !defined(NO_SSL)
  17067. if (!init_ssl_ctx(ctx, NULL)) {
  17068. const char *err_msg = "Error initializing SSL context";
  17069. /* Fatal error - abort start. */
  17070. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17071. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17072. mg_snprintf(NULL,
  17073. NULL, /* No truncation check for error buffers */
  17074. error->text,
  17075. error->text_buffer_size,
  17076. "%s",
  17077. err_msg);
  17078. }
  17079. free_context(ctx);
  17080. pthread_setspecific(sTlsKey, NULL);
  17081. return NULL;
  17082. }
  17083. #endif
  17084. if (!set_ports_option(ctx)) {
  17085. const char *err_msg = "Failed to setup server ports";
  17086. /* Fatal error - abort start. */
  17087. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17088. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17089. mg_snprintf(NULL,
  17090. NULL, /* No truncation check for error buffers */
  17091. error->text,
  17092. error->text_buffer_size,
  17093. "%s",
  17094. err_msg);
  17095. }
  17096. free_context(ctx);
  17097. pthread_setspecific(sTlsKey, NULL);
  17098. return NULL;
  17099. }
  17100. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17101. if (!set_uid_option(ctx)) {
  17102. const char *err_msg = "Failed to run as configured user";
  17103. /* Fatal error - abort start. */
  17104. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17105. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17106. mg_snprintf(NULL,
  17107. NULL, /* No truncation check for error buffers */
  17108. error->text,
  17109. error->text_buffer_size,
  17110. "%s",
  17111. err_msg);
  17112. }
  17113. free_context(ctx);
  17114. pthread_setspecific(sTlsKey, NULL);
  17115. return NULL;
  17116. }
  17117. #endif
  17118. if (!set_acl_option(ctx)) {
  17119. const char *err_msg = "Failed to setup access control list";
  17120. /* Fatal error - abort start. */
  17121. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17122. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17123. mg_snprintf(NULL,
  17124. NULL, /* No truncation check for error buffers */
  17125. error->text,
  17126. error->text_buffer_size,
  17127. "%s",
  17128. err_msg);
  17129. }
  17130. free_context(ctx);
  17131. pthread_setspecific(sTlsKey, NULL);
  17132. return NULL;
  17133. }
  17134. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17135. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17136. sizeof(pthread_t),
  17137. ctx);
  17138. if (ctx->worker_threadids == NULL) {
  17139. const char *err_msg = "Not enough memory for worker thread ID array";
  17140. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17141. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17142. mg_snprintf(NULL,
  17143. NULL, /* No truncation check for error buffers */
  17144. error->text,
  17145. error->text_buffer_size,
  17146. "%s",
  17147. err_msg);
  17148. }
  17149. free_context(ctx);
  17150. pthread_setspecific(sTlsKey, NULL);
  17151. return NULL;
  17152. }
  17153. ctx->worker_connections =
  17154. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17155. sizeof(struct mg_connection),
  17156. ctx);
  17157. if (ctx->worker_connections == NULL) {
  17158. const char *err_msg =
  17159. "Not enough memory for worker thread connection array";
  17160. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17161. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17162. mg_snprintf(NULL,
  17163. NULL, /* No truncation check for error buffers */
  17164. error->text,
  17165. error->text_buffer_size,
  17166. "%s",
  17167. err_msg);
  17168. }
  17169. free_context(ctx);
  17170. pthread_setspecific(sTlsKey, NULL);
  17171. return NULL;
  17172. }
  17173. #if defined(ALTERNATIVE_QUEUE)
  17174. ctx->client_wait_events =
  17175. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17176. sizeof(ctx->client_wait_events[0]),
  17177. ctx);
  17178. if (ctx->client_wait_events == NULL) {
  17179. const char *err_msg = "Not enough memory for worker event array";
  17180. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17181. mg_free(ctx->worker_threadids);
  17182. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17183. mg_snprintf(NULL,
  17184. NULL, /* No truncation check for error buffers */
  17185. error->text,
  17186. error->text_buffer_size,
  17187. "%s",
  17188. err_msg);
  17189. }
  17190. free_context(ctx);
  17191. pthread_setspecific(sTlsKey, NULL);
  17192. return NULL;
  17193. }
  17194. ctx->client_socks =
  17195. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17196. sizeof(ctx->client_socks[0]),
  17197. ctx);
  17198. if (ctx->client_socks == NULL) {
  17199. const char *err_msg = "Not enough memory for worker socket array";
  17200. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17201. mg_free(ctx->client_wait_events);
  17202. mg_free(ctx->worker_threadids);
  17203. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17204. mg_snprintf(NULL,
  17205. NULL, /* No truncation check for error buffers */
  17206. error->text,
  17207. error->text_buffer_size,
  17208. "%s",
  17209. err_msg);
  17210. }
  17211. free_context(ctx);
  17212. pthread_setspecific(sTlsKey, NULL);
  17213. return NULL;
  17214. }
  17215. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17216. ctx->client_wait_events[i] = event_create();
  17217. if (ctx->client_wait_events[i] == 0) {
  17218. const char *err_msg = "Error creating worker event %i";
  17219. mg_cry_ctx_internal(ctx, err_msg, i);
  17220. while (i > 0) {
  17221. i--;
  17222. event_destroy(ctx->client_wait_events[i]);
  17223. }
  17224. mg_free(ctx->client_socks);
  17225. mg_free(ctx->client_wait_events);
  17226. mg_free(ctx->worker_threadids);
  17227. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17228. mg_snprintf(NULL,
  17229. NULL, /* No truncation check for error buffers */
  17230. error->text,
  17231. error->text_buffer_size,
  17232. err_msg,
  17233. i);
  17234. }
  17235. free_context(ctx);
  17236. pthread_setspecific(sTlsKey, NULL);
  17237. return NULL;
  17238. }
  17239. }
  17240. #endif
  17241. #if defined(USE_TIMERS)
  17242. if (timers_init(ctx) != 0) {
  17243. const char *err_msg = "Error creating timers";
  17244. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17245. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17246. mg_snprintf(NULL,
  17247. NULL, /* No truncation check for error buffers */
  17248. error->text,
  17249. error->text_buffer_size,
  17250. "%s",
  17251. err_msg);
  17252. }
  17253. free_context(ctx);
  17254. pthread_setspecific(sTlsKey, NULL);
  17255. return NULL;
  17256. }
  17257. #endif
  17258. /* Context has been created - init user libraries */
  17259. if (ctx->callbacks.init_context) {
  17260. ctx->callbacks.init_context(ctx);
  17261. }
  17262. /* From now, the context is successfully created.
  17263. * When it is destroyed, the exit callback should be called. */
  17264. ctx->callbacks.exit_context = exit_callback;
  17265. ctx->context_type = CONTEXT_SERVER; /* server context */
  17266. /* Start worker threads */
  17267. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17268. /* worker_thread sets up the other fields */
  17269. ctx->worker_connections[i].phys_ctx = ctx;
  17270. if (mg_start_thread_with_id(worker_thread,
  17271. &ctx->worker_connections[i],
  17272. &ctx->worker_threadids[i])
  17273. != 0) {
  17274. long error_no = (long)ERRNO;
  17275. /* thread was not created */
  17276. if (i > 0) {
  17277. /* If the second, third, ... thread cannot be created, set a
  17278. * warning, but keep running. */
  17279. mg_cry_ctx_internal(ctx,
  17280. "Cannot start worker thread %i: error %ld",
  17281. i + 1,
  17282. error_no);
  17283. /* If the server initialization should stop here, all
  17284. * threads that have already been created must be stopped
  17285. * first, before any free_context(ctx) call.
  17286. */
  17287. } else {
  17288. /* If the first worker thread cannot be created, stop
  17289. * initialization and free the entire server context. */
  17290. mg_cry_ctx_internal(ctx,
  17291. "Cannot create threads: error %ld",
  17292. error_no);
  17293. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17294. mg_snprintf(
  17295. NULL,
  17296. NULL, /* No truncation check for error buffers */
  17297. error->text,
  17298. error->text_buffer_size,
  17299. "Cannot create first worker thread: error %ld",
  17300. error_no);
  17301. }
  17302. free_context(ctx);
  17303. pthread_setspecific(sTlsKey, NULL);
  17304. return NULL;
  17305. }
  17306. break;
  17307. }
  17308. }
  17309. /* Start master (listening) thread */
  17310. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17311. pthread_setspecific(sTlsKey, NULL);
  17312. return ctx;
  17313. }
  17314. struct mg_context *
  17315. mg_start(const struct mg_callbacks *callbacks,
  17316. void *user_data,
  17317. const char **options)
  17318. {
  17319. struct mg_init_data init = {0};
  17320. init.callbacks = callbacks;
  17321. init.user_data = user_data;
  17322. init.configuration_options = options;
  17323. return mg_start2(&init, NULL);
  17324. }
  17325. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17326. /* Add an additional domain to an already running web server. */
  17327. int
  17328. mg_start_domain2(struct mg_context *ctx,
  17329. const char **options,
  17330. struct mg_error_data *error)
  17331. {
  17332. const char *name;
  17333. const char *value;
  17334. const char *default_value;
  17335. struct mg_domain_context *new_dom;
  17336. struct mg_domain_context *dom;
  17337. int idx, i;
  17338. if (error != NULL) {
  17339. error->code = 0;
  17340. if (error->text_buffer_size > 0) {
  17341. *error->text = 0;
  17342. }
  17343. }
  17344. if ((ctx == NULL) || (options == NULL)) {
  17345. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17346. mg_snprintf(NULL,
  17347. NULL, /* No truncation check for error buffers */
  17348. error->text,
  17349. error->text_buffer_size,
  17350. "%s",
  17351. "Invalid parameters");
  17352. }
  17353. return -1;
  17354. }
  17355. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17356. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17357. mg_snprintf(NULL,
  17358. NULL, /* No truncation check for error buffers */
  17359. error->text,
  17360. error->text_buffer_size,
  17361. "%s",
  17362. "Server already stopped");
  17363. }
  17364. return -1;
  17365. }
  17366. new_dom = (struct mg_domain_context *)
  17367. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17368. if (!new_dom) {
  17369. /* Out of memory */
  17370. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17371. mg_snprintf(NULL,
  17372. NULL, /* No truncation check for error buffers */
  17373. error->text,
  17374. error->text_buffer_size,
  17375. "%s",
  17376. "Out or memory");
  17377. }
  17378. return -6;
  17379. }
  17380. /* Store options - TODO: unite duplicate code */
  17381. while (options && (name = *options++) != NULL) {
  17382. if ((idx = get_option_index(name)) == -1) {
  17383. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17384. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17385. mg_snprintf(NULL,
  17386. NULL, /* No truncation check for error buffers */
  17387. error->text,
  17388. error->text_buffer_size,
  17389. "Invalid option: %s",
  17390. name);
  17391. }
  17392. mg_free(new_dom);
  17393. return -2;
  17394. } else if ((value = *options++) == NULL) {
  17395. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17396. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17397. mg_snprintf(NULL,
  17398. NULL, /* No truncation check for error buffers */
  17399. error->text,
  17400. error->text_buffer_size,
  17401. "Invalid option value: %s",
  17402. name);
  17403. }
  17404. mg_free(new_dom);
  17405. return -2;
  17406. }
  17407. if (new_dom->config[idx] != NULL) {
  17408. /* Duplicate option: Later values overwrite earlier ones. */
  17409. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17410. mg_free(new_dom->config[idx]);
  17411. }
  17412. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17413. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17414. }
  17415. /* Authentication domain is mandatory */
  17416. /* TODO: Maybe use a new option hostname? */
  17417. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17418. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17419. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17420. mg_snprintf(NULL,
  17421. NULL, /* No truncation check for error buffers */
  17422. error->text,
  17423. error->text_buffer_size,
  17424. "Mandatory option %s missing",
  17425. config_options[AUTHENTICATION_DOMAIN].name);
  17426. }
  17427. mg_free(new_dom);
  17428. return -4;
  17429. }
  17430. /* Set default value if needed. Take the config value from
  17431. * ctx as a default value. */
  17432. for (i = 0; config_options[i].name != NULL; i++) {
  17433. default_value = ctx->dd.config[i];
  17434. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17435. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17436. }
  17437. }
  17438. new_dom->handlers = NULL;
  17439. new_dom->next = NULL;
  17440. new_dom->nonce_count = 0;
  17441. new_dom->auth_nonce_mask =
  17442. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17443. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17444. new_dom->shared_lua_websockets = NULL;
  17445. #endif
  17446. if (!init_ssl_ctx(ctx, new_dom)) {
  17447. /* Init SSL failed */
  17448. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17449. mg_snprintf(NULL,
  17450. NULL, /* No truncation check for error buffers */
  17451. error->text,
  17452. error->text_buffer_size,
  17453. "%s",
  17454. "Initializing SSL context failed");
  17455. }
  17456. mg_free(new_dom);
  17457. return -3;
  17458. }
  17459. /* Add element to linked list. */
  17460. mg_lock_context(ctx);
  17461. idx = 0;
  17462. dom = &(ctx->dd);
  17463. for (;;) {
  17464. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17465. dom->config[AUTHENTICATION_DOMAIN])) {
  17466. /* Domain collision */
  17467. mg_cry_ctx_internal(ctx,
  17468. "domain %s already in use",
  17469. new_dom->config[AUTHENTICATION_DOMAIN]);
  17470. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17471. mg_snprintf(NULL,
  17472. NULL, /* No truncation check for error buffers */
  17473. error->text,
  17474. error->text_buffer_size,
  17475. "Domain %s specified by %s is already in use",
  17476. new_dom->config[AUTHENTICATION_DOMAIN],
  17477. config_options[AUTHENTICATION_DOMAIN].name);
  17478. }
  17479. mg_free(new_dom);
  17480. mg_unlock_context(ctx);
  17481. return -5;
  17482. }
  17483. /* Count number of domains */
  17484. idx++;
  17485. if (dom->next == NULL) {
  17486. dom->next = new_dom;
  17487. break;
  17488. }
  17489. dom = dom->next;
  17490. }
  17491. mg_unlock_context(ctx);
  17492. /* Return domain number */
  17493. return idx;
  17494. }
  17495. int
  17496. mg_start_domain(struct mg_context *ctx, const char **options)
  17497. {
  17498. return mg_start_domain2(ctx, options, NULL);
  17499. }
  17500. #endif
  17501. /* Feature check API function */
  17502. unsigned
  17503. mg_check_feature(unsigned feature)
  17504. {
  17505. static const unsigned feature_set = 0
  17506. /* Set bits for available features according to API documentation.
  17507. * This bit mask is created at compile time, according to the active
  17508. * preprocessor defines. It is a single const value at runtime. */
  17509. #if !defined(NO_FILES)
  17510. | MG_FEATURES_FILES
  17511. #endif
  17512. #if !defined(NO_SSL)
  17513. | MG_FEATURES_SSL
  17514. #endif
  17515. #if !defined(NO_CGI)
  17516. | MG_FEATURES_CGI
  17517. #endif
  17518. #if defined(USE_IPV6)
  17519. | MG_FEATURES_IPV6
  17520. #endif
  17521. #if defined(USE_WEBSOCKET)
  17522. | MG_FEATURES_WEBSOCKET
  17523. #endif
  17524. #if defined(USE_LUA)
  17525. | MG_FEATURES_LUA
  17526. #endif
  17527. #if defined(USE_DUKTAPE)
  17528. | MG_FEATURES_SSJS
  17529. #endif
  17530. #if !defined(NO_CACHING)
  17531. | MG_FEATURES_CACHE
  17532. #endif
  17533. #if defined(USE_SERVER_STATS)
  17534. | MG_FEATURES_STATS
  17535. #endif
  17536. #if defined(USE_ZLIB)
  17537. | MG_FEATURES_COMPRESSION
  17538. #endif
  17539. /* Set some extra bits not defined in the API documentation.
  17540. * These bits may change without further notice. */
  17541. #if defined(MG_LEGACY_INTERFACE)
  17542. | 0x00008000u
  17543. #endif
  17544. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17545. | 0x00004000u
  17546. #endif
  17547. #if defined(MEMORY_DEBUGGING)
  17548. | 0x00001000u
  17549. #endif
  17550. #if defined(USE_TIMERS)
  17551. | 0x00020000u
  17552. #endif
  17553. #if !defined(NO_NONCE_CHECK)
  17554. | 0x00040000u
  17555. #endif
  17556. #if !defined(NO_POPEN)
  17557. | 0x00080000u
  17558. #endif
  17559. ;
  17560. return (feature & feature_set);
  17561. }
  17562. static size_t
  17563. mg_str_append(char **dst, char *end, const char *src)
  17564. {
  17565. size_t len = strlen(src);
  17566. if (*dst != end) {
  17567. /* Append src if enough space, or close dst. */
  17568. if ((size_t)(end - *dst) > len) {
  17569. strcpy(*dst, src);
  17570. *dst += len;
  17571. } else {
  17572. *dst = end;
  17573. }
  17574. }
  17575. return len;
  17576. }
  17577. /* Get system information. It can be printed or stored by the caller.
  17578. * Return the size of available information. */
  17579. int
  17580. mg_get_system_info(char *buffer, int buflen)
  17581. {
  17582. char *end, *append_eoobj = NULL, block[256];
  17583. size_t system_info_length = 0;
  17584. #if defined(_WIN32)
  17585. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17586. #else
  17587. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17588. #endif
  17589. if ((buffer == NULL) || (buflen < 1)) {
  17590. buflen = 0;
  17591. end = buffer;
  17592. } else {
  17593. *buffer = 0;
  17594. end = buffer + buflen;
  17595. }
  17596. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17597. /* has enough space to append eoobj */
  17598. append_eoobj = buffer;
  17599. if (end) {
  17600. end -= sizeof(eoobj) - 1;
  17601. }
  17602. }
  17603. system_info_length += mg_str_append(&buffer, end, "{");
  17604. /* Server version */
  17605. {
  17606. const char *version = mg_version();
  17607. mg_snprintf(NULL,
  17608. NULL,
  17609. block,
  17610. sizeof(block),
  17611. "%s\"version\" : \"%s\"",
  17612. eol,
  17613. version);
  17614. system_info_length += mg_str_append(&buffer, end, block);
  17615. }
  17616. /* System info */
  17617. {
  17618. #if defined(_WIN32)
  17619. DWORD dwVersion = 0;
  17620. DWORD dwMajorVersion = 0;
  17621. DWORD dwMinorVersion = 0;
  17622. SYSTEM_INFO si;
  17623. GetSystemInfo(&si);
  17624. #if defined(_MSC_VER)
  17625. #pragma warning(push)
  17626. /* GetVersion was declared deprecated */
  17627. #pragma warning(disable : 4996)
  17628. #endif
  17629. dwVersion = GetVersion();
  17630. #if defined(_MSC_VER)
  17631. #pragma warning(pop)
  17632. #endif
  17633. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17634. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17635. mg_snprintf(NULL,
  17636. NULL,
  17637. block,
  17638. sizeof(block),
  17639. ",%s\"os\" : \"Windows %u.%u\"",
  17640. eol,
  17641. (unsigned)dwMajorVersion,
  17642. (unsigned)dwMinorVersion);
  17643. system_info_length += mg_str_append(&buffer, end, block);
  17644. mg_snprintf(NULL,
  17645. NULL,
  17646. block,
  17647. sizeof(block),
  17648. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17649. eol,
  17650. (unsigned)si.wProcessorArchitecture,
  17651. (unsigned)si.dwNumberOfProcessors,
  17652. (unsigned)si.dwActiveProcessorMask);
  17653. system_info_length += mg_str_append(&buffer, end, block);
  17654. #elif defined(__ZEPHYR__)
  17655. mg_snprintf(NULL,
  17656. NULL,
  17657. block,
  17658. sizeof(block),
  17659. ",%s\"os\" : \"%s %s\"",
  17660. eol,
  17661. "Zephyr OS",
  17662. ZEPHYR_VERSION);
  17663. system_info_length += mg_str_append(&buffer, end, block);
  17664. #else
  17665. struct utsname name;
  17666. memset(&name, 0, sizeof(name));
  17667. uname(&name);
  17668. mg_snprintf(NULL,
  17669. NULL,
  17670. block,
  17671. sizeof(block),
  17672. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17673. eol,
  17674. name.sysname,
  17675. name.version,
  17676. name.release,
  17677. name.machine);
  17678. system_info_length += mg_str_append(&buffer, end, block);
  17679. #endif
  17680. }
  17681. /* Features */
  17682. {
  17683. mg_snprintf(NULL,
  17684. NULL,
  17685. block,
  17686. sizeof(block),
  17687. ",%s\"features\" : %lu"
  17688. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17689. eol,
  17690. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17691. eol,
  17692. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17693. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17694. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17695. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17696. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17697. : "",
  17698. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17699. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17700. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17701. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17702. system_info_length += mg_str_append(&buffer, end, block);
  17703. #if defined(USE_LUA)
  17704. mg_snprintf(NULL,
  17705. NULL,
  17706. block,
  17707. sizeof(block),
  17708. ",%s\"lua_version\" : \"%u (%s)\"",
  17709. eol,
  17710. (unsigned)LUA_VERSION_NUM,
  17711. LUA_RELEASE);
  17712. system_info_length += mg_str_append(&buffer, end, block);
  17713. #endif
  17714. #if defined(USE_DUKTAPE)
  17715. mg_snprintf(NULL,
  17716. NULL,
  17717. block,
  17718. sizeof(block),
  17719. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17720. eol,
  17721. (unsigned)DUK_VERSION / 10000,
  17722. ((unsigned)DUK_VERSION / 100) % 100,
  17723. (unsigned)DUK_VERSION % 100);
  17724. system_info_length += mg_str_append(&buffer, end, block);
  17725. #endif
  17726. }
  17727. /* Build date */
  17728. {
  17729. #if defined(GCC_DIAGNOSTIC)
  17730. #if GCC_VERSION >= 40900
  17731. #pragma GCC diagnostic push
  17732. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17733. #pragma GCC diagnostic ignored "-Wdate-time"
  17734. #endif
  17735. #endif
  17736. mg_snprintf(NULL,
  17737. NULL,
  17738. block,
  17739. sizeof(block),
  17740. ",%s\"build\" : \"%s\"",
  17741. eol,
  17742. __DATE__);
  17743. #if defined(GCC_DIAGNOSTIC)
  17744. #if GCC_VERSION >= 40900
  17745. #pragma GCC diagnostic pop
  17746. #endif
  17747. #endif
  17748. system_info_length += mg_str_append(&buffer, end, block);
  17749. }
  17750. /* Compiler information */
  17751. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17752. {
  17753. #if defined(_MSC_VER)
  17754. mg_snprintf(NULL,
  17755. NULL,
  17756. block,
  17757. sizeof(block),
  17758. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17759. eol,
  17760. (unsigned)_MSC_VER,
  17761. (unsigned)_MSC_FULL_VER);
  17762. system_info_length += mg_str_append(&buffer, end, block);
  17763. #elif defined(__MINGW64__)
  17764. mg_snprintf(NULL,
  17765. NULL,
  17766. block,
  17767. sizeof(block),
  17768. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17769. eol,
  17770. (unsigned)__MINGW64_VERSION_MAJOR,
  17771. (unsigned)__MINGW64_VERSION_MINOR);
  17772. system_info_length += mg_str_append(&buffer, end, block);
  17773. mg_snprintf(NULL,
  17774. NULL,
  17775. block,
  17776. sizeof(block),
  17777. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17778. eol,
  17779. (unsigned)__MINGW32_MAJOR_VERSION,
  17780. (unsigned)__MINGW32_MINOR_VERSION);
  17781. system_info_length += mg_str_append(&buffer, end, block);
  17782. #elif defined(__MINGW32__)
  17783. mg_snprintf(NULL,
  17784. NULL,
  17785. block,
  17786. sizeof(block),
  17787. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17788. eol,
  17789. (unsigned)__MINGW32_MAJOR_VERSION,
  17790. (unsigned)__MINGW32_MINOR_VERSION);
  17791. system_info_length += mg_str_append(&buffer, end, block);
  17792. #elif defined(__clang__)
  17793. mg_snprintf(NULL,
  17794. NULL,
  17795. block,
  17796. sizeof(block),
  17797. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17798. eol,
  17799. __clang_major__,
  17800. __clang_minor__,
  17801. __clang_patchlevel__,
  17802. __clang_version__);
  17803. system_info_length += mg_str_append(&buffer, end, block);
  17804. #elif defined(__GNUC__)
  17805. mg_snprintf(NULL,
  17806. NULL,
  17807. block,
  17808. sizeof(block),
  17809. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17810. eol,
  17811. (unsigned)__GNUC__,
  17812. (unsigned)__GNUC_MINOR__,
  17813. (unsigned)__GNUC_PATCHLEVEL__);
  17814. system_info_length += mg_str_append(&buffer, end, block);
  17815. #elif defined(__INTEL_COMPILER)
  17816. mg_snprintf(NULL,
  17817. NULL,
  17818. block,
  17819. sizeof(block),
  17820. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17821. eol,
  17822. (unsigned)__INTEL_COMPILER);
  17823. system_info_length += mg_str_append(&buffer, end, block);
  17824. #elif defined(__BORLANDC__)
  17825. mg_snprintf(NULL,
  17826. NULL,
  17827. block,
  17828. sizeof(block),
  17829. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17830. eol,
  17831. (unsigned)__BORLANDC__);
  17832. system_info_length += mg_str_append(&buffer, end, block);
  17833. #elif defined(__SUNPRO_C)
  17834. mg_snprintf(NULL,
  17835. NULL,
  17836. block,
  17837. sizeof(block),
  17838. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17839. eol,
  17840. (unsigned)__SUNPRO_C);
  17841. system_info_length += mg_str_append(&buffer, end, block);
  17842. #else
  17843. mg_snprintf(NULL,
  17844. NULL,
  17845. block,
  17846. sizeof(block),
  17847. ",%s\"compiler\" : \"other\"",
  17848. eol);
  17849. system_info_length += mg_str_append(&buffer, end, block);
  17850. #endif
  17851. }
  17852. /* Determine 32/64 bit data mode.
  17853. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17854. {
  17855. mg_snprintf(NULL,
  17856. NULL,
  17857. block,
  17858. sizeof(block),
  17859. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17860. "char:%u/%u, "
  17861. "ptr:%u, size:%u, time:%u\"",
  17862. eol,
  17863. (unsigned)sizeof(short),
  17864. (unsigned)sizeof(int),
  17865. (unsigned)sizeof(long),
  17866. (unsigned)sizeof(long long),
  17867. (unsigned)sizeof(float),
  17868. (unsigned)sizeof(double),
  17869. (unsigned)sizeof(long double),
  17870. (unsigned)sizeof(char),
  17871. (unsigned)sizeof(wchar_t),
  17872. (unsigned)sizeof(void *),
  17873. (unsigned)sizeof(size_t),
  17874. (unsigned)sizeof(time_t));
  17875. system_info_length += mg_str_append(&buffer, end, block);
  17876. }
  17877. /* Terminate string */
  17878. if (append_eoobj) {
  17879. strcat(append_eoobj, eoobj);
  17880. }
  17881. system_info_length += sizeof(eoobj) - 1;
  17882. return (int)system_info_length;
  17883. }
  17884. /* Get context information. It can be printed or stored by the caller.
  17885. * Return the size of available information. */
  17886. int
  17887. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17888. {
  17889. #if defined(USE_SERVER_STATS)
  17890. char *end, *append_eoobj = NULL, block[256];
  17891. size_t context_info_length = 0;
  17892. #if defined(_WIN32)
  17893. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17894. #else
  17895. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17896. #endif
  17897. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17898. if ((buffer == NULL) || (buflen < 1)) {
  17899. buflen = 0;
  17900. end = buffer;
  17901. } else {
  17902. *buffer = 0;
  17903. end = buffer + buflen;
  17904. }
  17905. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17906. /* has enough space to append eoobj */
  17907. append_eoobj = buffer;
  17908. end -= sizeof(eoobj) - 1;
  17909. }
  17910. context_info_length += mg_str_append(&buffer, end, "{");
  17911. if (ms) { /* <-- should be always true */
  17912. /* Memory information */
  17913. int blockCount = (int)ms->blockCount;
  17914. int64_t totalMemUsed = ms->totalMemUsed;
  17915. int64_t maxMemUsed = ms->maxMemUsed;
  17916. if (totalMemUsed > maxMemUsed) {
  17917. maxMemUsed = totalMemUsed;
  17918. }
  17919. mg_snprintf(NULL,
  17920. NULL,
  17921. block,
  17922. sizeof(block),
  17923. "%s\"memory\" : {%s"
  17924. "\"blocks\" : %i,%s"
  17925. "\"used\" : %" INT64_FMT ",%s"
  17926. "\"maxUsed\" : %" INT64_FMT "%s"
  17927. "}",
  17928. eol,
  17929. eol,
  17930. blockCount,
  17931. eol,
  17932. totalMemUsed,
  17933. eol,
  17934. maxMemUsed,
  17935. eol);
  17936. context_info_length += mg_str_append(&buffer, end, block);
  17937. }
  17938. if (ctx) {
  17939. /* Declare all variables at begin of the block, to comply
  17940. * with old C standards. */
  17941. char start_time_str[64] = {0};
  17942. char now_str[64] = {0};
  17943. time_t start_time = ctx->start_time;
  17944. time_t now = time(NULL);
  17945. int64_t total_data_read, total_data_written;
  17946. int active_connections = (int)ctx->active_connections;
  17947. int max_active_connections = (int)ctx->max_active_connections;
  17948. int total_connections = (int)ctx->total_connections;
  17949. if (active_connections > max_active_connections) {
  17950. max_active_connections = active_connections;
  17951. }
  17952. if (active_connections > total_connections) {
  17953. total_connections = active_connections;
  17954. }
  17955. /* Connections information */
  17956. mg_snprintf(NULL,
  17957. NULL,
  17958. block,
  17959. sizeof(block),
  17960. ",%s\"connections\" : {%s"
  17961. "\"active\" : %i,%s"
  17962. "\"maxActive\" : %i,%s"
  17963. "\"total\" : %i%s"
  17964. "}",
  17965. eol,
  17966. eol,
  17967. active_connections,
  17968. eol,
  17969. max_active_connections,
  17970. eol,
  17971. total_connections,
  17972. eol);
  17973. context_info_length += mg_str_append(&buffer, end, block);
  17974. /* Queue information */
  17975. #if !defined(ALTERNATIVE_QUEUE)
  17976. mg_snprintf(NULL,
  17977. NULL,
  17978. block,
  17979. sizeof(block),
  17980. ",%s\"queue\" : {%s"
  17981. "\"length\" : %i,%s"
  17982. "\"filled\" : %i,%s"
  17983. "\"maxFilled\" : %i,%s"
  17984. "\"full\" : %s%s"
  17985. "}",
  17986. eol,
  17987. eol,
  17988. ctx->sq_size,
  17989. eol,
  17990. ctx->sq_head - ctx->sq_tail,
  17991. eol,
  17992. ctx->sq_max_fill,
  17993. eol,
  17994. (ctx->sq_blocked ? "true" : "false"),
  17995. eol);
  17996. context_info_length += mg_str_append(&buffer, end, block);
  17997. #endif
  17998. /* Requests information */
  17999. mg_snprintf(NULL,
  18000. NULL,
  18001. block,
  18002. sizeof(block),
  18003. ",%s\"requests\" : {%s"
  18004. "\"total\" : %i%s"
  18005. "}",
  18006. eol,
  18007. eol,
  18008. ctx->total_requests,
  18009. eol);
  18010. context_info_length += mg_str_append(&buffer, end, block);
  18011. /* Data information */
  18012. total_data_read =
  18013. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18014. total_data_written =
  18015. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18016. mg_snprintf(NULL,
  18017. NULL,
  18018. block,
  18019. sizeof(block),
  18020. ",%s\"data\" : {%s"
  18021. "\"read\" : %" INT64_FMT ",%s"
  18022. "\"written\" : %" INT64_FMT "%s"
  18023. "}",
  18024. eol,
  18025. eol,
  18026. total_data_read,
  18027. eol,
  18028. total_data_written,
  18029. eol);
  18030. context_info_length += mg_str_append(&buffer, end, block);
  18031. /* Execution time information */
  18032. gmt_time_string(start_time_str,
  18033. sizeof(start_time_str) - 1,
  18034. &start_time);
  18035. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18036. mg_snprintf(NULL,
  18037. NULL,
  18038. block,
  18039. sizeof(block),
  18040. ",%s\"time\" : {%s"
  18041. "\"uptime\" : %.0f,%s"
  18042. "\"start\" : \"%s\",%s"
  18043. "\"now\" : \"%s\"%s"
  18044. "}",
  18045. eol,
  18046. eol,
  18047. difftime(now, start_time),
  18048. eol,
  18049. start_time_str,
  18050. eol,
  18051. now_str,
  18052. eol);
  18053. context_info_length += mg_str_append(&buffer, end, block);
  18054. }
  18055. /* Terminate string */
  18056. if (append_eoobj) {
  18057. strcat(append_eoobj, eoobj);
  18058. }
  18059. context_info_length += sizeof(eoobj) - 1;
  18060. return (int)context_info_length;
  18061. #else
  18062. (void)ctx;
  18063. if ((buffer != NULL) && (buflen > 0)) {
  18064. *buffer = 0;
  18065. }
  18066. return 0;
  18067. #endif
  18068. }
  18069. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18070. /* Get connection information. It can be printed or stored by the caller.
  18071. * Return the size of available information. */
  18072. int
  18073. mg_get_connection_info(const struct mg_context *ctx,
  18074. int idx,
  18075. char *buffer,
  18076. int buflen)
  18077. {
  18078. const struct mg_connection *conn;
  18079. const struct mg_request_info *ri;
  18080. char *end, *append_eoobj = NULL, block[256];
  18081. size_t connection_info_length = 0;
  18082. int state = 0;
  18083. const char *state_str = "unknown";
  18084. #if defined(_WIN32)
  18085. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18086. #else
  18087. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18088. #endif
  18089. if ((buffer == NULL) || (buflen < 1)) {
  18090. buflen = 0;
  18091. end = buffer;
  18092. } else {
  18093. *buffer = 0;
  18094. end = buffer + buflen;
  18095. }
  18096. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18097. /* has enough space to append eoobj */
  18098. append_eoobj = buffer;
  18099. end -= sizeof(eoobj) - 1;
  18100. }
  18101. if ((ctx == NULL) || (idx < 0)) {
  18102. /* Parameter error */
  18103. return 0;
  18104. }
  18105. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18106. /* Out of range */
  18107. return 0;
  18108. }
  18109. /* Take connection [idx]. This connection is not locked in
  18110. * any way, so some other thread might use it. */
  18111. conn = (ctx->worker_connections) + idx;
  18112. /* Initialize output string */
  18113. connection_info_length += mg_str_append(&buffer, end, "{");
  18114. /* Init variables */
  18115. ri = &(conn->request_info);
  18116. #if defined(USE_SERVER_STATS)
  18117. state = conn->conn_state;
  18118. /* State as string */
  18119. switch (state) {
  18120. case 0:
  18121. state_str = "undefined";
  18122. break;
  18123. case 1:
  18124. state_str = "not used";
  18125. break;
  18126. case 2:
  18127. state_str = "init";
  18128. break;
  18129. case 3:
  18130. state_str = "ready";
  18131. break;
  18132. case 4:
  18133. state_str = "processing";
  18134. break;
  18135. case 5:
  18136. state_str = "processed";
  18137. break;
  18138. case 6:
  18139. state_str = "to close";
  18140. break;
  18141. case 7:
  18142. state_str = "closing";
  18143. break;
  18144. case 8:
  18145. state_str = "closed";
  18146. break;
  18147. case 9:
  18148. state_str = "done";
  18149. break;
  18150. }
  18151. #endif
  18152. /* Connection info */
  18153. if ((state >= 3) && (state < 9)) {
  18154. mg_snprintf(NULL,
  18155. NULL,
  18156. block,
  18157. sizeof(block),
  18158. "%s\"connection\" : {%s"
  18159. "\"remote\" : {%s"
  18160. "\"protocol\" : \"%s\",%s"
  18161. "\"addr\" : \"%s\",%s"
  18162. "\"port\" : %u%s"
  18163. "},%s"
  18164. "\"handled_requests\" : %u%s"
  18165. "}",
  18166. eol,
  18167. eol,
  18168. eol,
  18169. get_proto_name(conn),
  18170. eol,
  18171. ri->remote_addr,
  18172. eol,
  18173. ri->remote_port,
  18174. eol,
  18175. eol,
  18176. conn->handled_requests,
  18177. eol);
  18178. connection_info_length += mg_str_append(&buffer, end, block);
  18179. }
  18180. /* Request info */
  18181. if ((state >= 4) && (state < 6)) {
  18182. mg_snprintf(NULL,
  18183. NULL,
  18184. block,
  18185. sizeof(block),
  18186. "%s%s\"request_info\" : {%s"
  18187. "\"method\" : \"%s\",%s"
  18188. "\"uri\" : \"%s\",%s"
  18189. "\"query\" : %s%s%s%s"
  18190. "}",
  18191. (connection_info_length > 1 ? "," : ""),
  18192. eol,
  18193. eol,
  18194. ri->request_method,
  18195. eol,
  18196. ri->request_uri,
  18197. eol,
  18198. ri->query_string ? "\"" : "",
  18199. ri->query_string ? ri->query_string : "null",
  18200. ri->query_string ? "\"" : "",
  18201. eol);
  18202. connection_info_length += mg_str_append(&buffer, end, block);
  18203. }
  18204. /* Execution time information */
  18205. if ((state >= 2) && (state < 9)) {
  18206. char start_time_str[64] = {0};
  18207. char close_time_str[64] = {0};
  18208. time_t start_time = conn->conn_birth_time;
  18209. time_t close_time = conn->conn_close_time;
  18210. double time_diff;
  18211. gmt_time_string(start_time_str,
  18212. sizeof(start_time_str) - 1,
  18213. &start_time);
  18214. if (close_time != 0) {
  18215. time_diff = difftime(close_time, start_time);
  18216. gmt_time_string(close_time_str,
  18217. sizeof(close_time_str) - 1,
  18218. &close_time);
  18219. } else {
  18220. time_t now = time(NULL);
  18221. time_diff = difftime(now, start_time);
  18222. close_time_str[0] = 0; /* or use "now" ? */
  18223. }
  18224. mg_snprintf(NULL,
  18225. NULL,
  18226. block,
  18227. sizeof(block),
  18228. "%s%s\"time\" : {%s"
  18229. "\"uptime\" : %.0f,%s"
  18230. "\"start\" : \"%s\",%s"
  18231. "\"closed\" : \"%s\"%s"
  18232. "}",
  18233. (connection_info_length > 1 ? "," : ""),
  18234. eol,
  18235. eol,
  18236. time_diff,
  18237. eol,
  18238. start_time_str,
  18239. eol,
  18240. close_time_str,
  18241. eol);
  18242. connection_info_length += mg_str_append(&buffer, end, block);
  18243. }
  18244. /* Remote user name */
  18245. if ((ri->remote_user) && (state < 9)) {
  18246. mg_snprintf(NULL,
  18247. NULL,
  18248. block,
  18249. sizeof(block),
  18250. "%s%s\"user\" : {%s"
  18251. "\"name\" : \"%s\",%s"
  18252. "}",
  18253. (connection_info_length > 1 ? "," : ""),
  18254. eol,
  18255. eol,
  18256. ri->remote_user,
  18257. eol);
  18258. connection_info_length += mg_str_append(&buffer, end, block);
  18259. }
  18260. /* Data block */
  18261. if (state >= 3) {
  18262. mg_snprintf(NULL,
  18263. NULL,
  18264. block,
  18265. sizeof(block),
  18266. "%s%s\"data\" : {%s"
  18267. "\"read\" : %" INT64_FMT ",%s"
  18268. "\"written\" : %" INT64_FMT "%s"
  18269. "}",
  18270. (connection_info_length > 1 ? "," : ""),
  18271. eol,
  18272. eol,
  18273. conn->consumed_content,
  18274. eol,
  18275. conn->num_bytes_sent,
  18276. eol);
  18277. connection_info_length += mg_str_append(&buffer, end, block);
  18278. }
  18279. /* State */
  18280. mg_snprintf(NULL,
  18281. NULL,
  18282. block,
  18283. sizeof(block),
  18284. "%s%s\"state\" : \"%s\"",
  18285. (connection_info_length > 1 ? "," : ""),
  18286. eol,
  18287. state_str);
  18288. connection_info_length += mg_str_append(&buffer, end, block);
  18289. /* Terminate string */
  18290. if (append_eoobj) {
  18291. strcat(append_eoobj, eoobj);
  18292. }
  18293. connection_info_length += sizeof(eoobj) - 1;
  18294. return (int)connection_info_length;
  18295. }
  18296. #endif
  18297. /* Initialize this library. This function does not need to be thread safe.
  18298. */
  18299. unsigned
  18300. mg_init_library(unsigned features)
  18301. {
  18302. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18303. unsigned features_inited = features_to_init;
  18304. if (mg_init_library_called <= 0) {
  18305. /* Not initialized yet */
  18306. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18307. return 0;
  18308. }
  18309. }
  18310. mg_global_lock();
  18311. if (mg_init_library_called <= 0) {
  18312. #if defined(_WIN32)
  18313. int file_mutex_init = 1;
  18314. int wsa = 1;
  18315. #else
  18316. int mutexattr_init = 1;
  18317. #endif
  18318. int failed = 1;
  18319. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18320. if (key_create == 0) {
  18321. #if defined(_WIN32)
  18322. file_mutex_init = pthread_mutex_init(&global_log_file_lock,
  18323. &pthread_mutex_attr);
  18324. if (file_mutex_init == 0) {
  18325. /* Start WinSock */
  18326. WSADATA data;
  18327. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18328. }
  18329. #else
  18330. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18331. if (mutexattr_init == 0) {
  18332. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18333. PTHREAD_MUTEX_RECURSIVE);
  18334. }
  18335. #endif
  18336. }
  18337. if (failed) {
  18338. #if defined(_WIN32)
  18339. if (wsa == 0) {
  18340. (void)WSACleanup();
  18341. }
  18342. if (file_mutex_init == 0) {
  18343. (void)pthread_mutex_destroy(&global_log_file_lock);
  18344. }
  18345. #else
  18346. if (mutexattr_init == 0) {
  18347. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18348. }
  18349. #endif
  18350. if (key_create == 0) {
  18351. (void)pthread_key_delete(sTlsKey);
  18352. }
  18353. mg_global_unlock();
  18354. (void)pthread_mutex_destroy(&global_lock_mutex);
  18355. return 0;
  18356. }
  18357. #if defined(USE_LUA)
  18358. lua_init_optional_libraries();
  18359. #endif
  18360. }
  18361. mg_global_unlock();
  18362. #if !defined(NO_SSL)
  18363. if (features_to_init & MG_FEATURES_SSL) {
  18364. if (!mg_ssl_initialized) {
  18365. char ebuf[128];
  18366. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18367. mg_ssl_initialized = 1;
  18368. } else {
  18369. (void)ebuf;
  18370. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18371. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18372. }
  18373. } else {
  18374. /* ssl already initialized */
  18375. }
  18376. }
  18377. #endif
  18378. mg_global_lock();
  18379. if (mg_init_library_called <= 0) {
  18380. mg_init_library_called = 1;
  18381. } else {
  18382. mg_init_library_called++;
  18383. }
  18384. mg_global_unlock();
  18385. return features_inited;
  18386. }
  18387. /* Un-initialize this library. */
  18388. unsigned
  18389. mg_exit_library(void)
  18390. {
  18391. if (mg_init_library_called <= 0) {
  18392. return 0;
  18393. }
  18394. mg_global_lock();
  18395. mg_init_library_called--;
  18396. if (mg_init_library_called == 0) {
  18397. #if !defined(NO_SSL)
  18398. if (mg_ssl_initialized) {
  18399. uninitialize_ssl();
  18400. mg_ssl_initialized = 0;
  18401. }
  18402. #endif
  18403. #if defined(_WIN32)
  18404. (void)WSACleanup();
  18405. (void)pthread_mutex_destroy(&global_log_file_lock);
  18406. #else
  18407. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18408. #endif
  18409. (void)pthread_key_delete(sTlsKey);
  18410. #if defined(USE_LUA)
  18411. lua_exit_optional_libraries();
  18412. #endif
  18413. mg_global_unlock();
  18414. (void)pthread_mutex_destroy(&global_lock_mutex);
  18415. return 1;
  18416. }
  18417. mg_global_unlock();
  18418. return 1;
  18419. }
  18420. /* End of civetweb.c */