civetweb.c 569 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263
  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. uint64_t nsnow;
  1512. static uint64_t nslast;
  1513. struct timespec tsnow;
  1514. /* Get some operating system independent thread id */
  1515. unsigned long thread_id = mg_current_thread_id();
  1516. clock_gettime(CLOCK_REALTIME, &tsnow);
  1517. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1518. + ((uint64_t)tsnow.tv_nsec);
  1519. if (!nslast) {
  1520. nslast = nsnow;
  1521. }
  1522. flockfile(DEBUG_TRACE_STREAM);
  1523. fprintf(DEBUG_TRACE_STREAM,
  1524. "*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1525. (unsigned long)tsnow.tv_sec,
  1526. (unsigned long)tsnow.tv_nsec,
  1527. nsnow - nslast,
  1528. thread_id,
  1529. func,
  1530. line);
  1531. va_start(args, fmt);
  1532. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1533. va_end(args);
  1534. putc('\n', DEBUG_TRACE_STREAM);
  1535. fflush(DEBUG_TRACE_STREAM);
  1536. funlockfile(DEBUG_TRACE_STREAM);
  1537. nslast = nsnow;
  1538. }
  1539. #endif /* NEED_DEBUG_TRACE_FUNC */
  1540. #define MD5_STATIC static
  1541. #include "md5.inl"
  1542. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1543. #if defined(NO_SOCKLEN_T)
  1544. typedef int socklen_t;
  1545. #endif /* NO_SOCKLEN_T */
  1546. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1547. #if !defined(MSG_NOSIGNAL)
  1548. #define MSG_NOSIGNAL (0)
  1549. #endif
  1550. #if defined(NO_SSL)
  1551. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1552. typedef struct SSL_CTX SSL_CTX;
  1553. #else
  1554. #if defined(NO_SSL_DL)
  1555. #include <openssl/bn.h>
  1556. #include <openssl/conf.h>
  1557. #include <openssl/crypto.h>
  1558. #include <openssl/dh.h>
  1559. #include <openssl/engine.h>
  1560. #include <openssl/err.h>
  1561. #include <openssl/opensslv.h>
  1562. #include <openssl/pem.h>
  1563. #include <openssl/ssl.h>
  1564. #include <openssl/tls1.h>
  1565. #include <openssl/x509.h>
  1566. #if defined(WOLFSSL_VERSION)
  1567. /* Additional defines for WolfSSL, see
  1568. * https://github.com/civetweb/civetweb/issues/583 */
  1569. #include "wolfssl_extras.inl"
  1570. #endif
  1571. #if defined(OPENSSL_IS_BORINGSSL)
  1572. /* From boringssl/src/include/openssl/mem.h:
  1573. *
  1574. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1575. * However, that was written in a time before Valgrind and ASAN. Since we now
  1576. * have those tools, the OpenSSL allocation functions are simply macros around
  1577. * the standard memory functions.
  1578. *
  1579. * #define OPENSSL_free free */
  1580. #define free free
  1581. // disable for boringssl
  1582. #define CONF_modules_unload(a) ((void)0)
  1583. #define ENGINE_cleanup() ((void)0)
  1584. #endif
  1585. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1586. /* If OpenSSL headers are included, automatically select the API version */
  1587. #if !defined(OPENSSL_API_1_1)
  1588. #define OPENSSL_API_1_1
  1589. #endif
  1590. #define OPENSSL_REMOVE_THREAD_STATE()
  1591. #else
  1592. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1593. #endif
  1594. #else
  1595. /* SSL loaded dynamically from DLL.
  1596. * I put the prototypes here to be independent from OpenSSL source
  1597. * installation. */
  1598. typedef struct ssl_st SSL;
  1599. typedef struct ssl_method_st SSL_METHOD;
  1600. typedef struct ssl_ctx_st SSL_CTX;
  1601. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1602. typedef struct x509_name X509_NAME;
  1603. typedef struct asn1_integer ASN1_INTEGER;
  1604. typedef struct bignum BIGNUM;
  1605. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1606. typedef struct evp_md EVP_MD;
  1607. typedef struct x509 X509;
  1608. #define SSL_CTRL_OPTIONS (32)
  1609. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1610. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1611. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1612. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1613. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1614. #define SSL_VERIFY_NONE (0)
  1615. #define SSL_VERIFY_PEER (1)
  1616. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1617. #define SSL_VERIFY_CLIENT_ONCE (4)
  1618. #define SSL_OP_ALL (0x80000BFFul)
  1619. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1620. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1621. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1622. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1623. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1624. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1625. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1626. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1627. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1628. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1629. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1630. #define SSL_CB_HANDSHAKE_START (0x10)
  1631. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1632. #define SSL_ERROR_NONE (0)
  1633. #define SSL_ERROR_SSL (1)
  1634. #define SSL_ERROR_WANT_READ (2)
  1635. #define SSL_ERROR_WANT_WRITE (3)
  1636. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1637. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1638. #define SSL_ERROR_ZERO_RETURN (6)
  1639. #define SSL_ERROR_WANT_CONNECT (7)
  1640. #define SSL_ERROR_WANT_ACCEPT (8)
  1641. #define TLSEXT_TYPE_server_name (0)
  1642. #define TLSEXT_NAMETYPE_host_name (0)
  1643. #define SSL_TLSEXT_ERR_OK (0)
  1644. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1645. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1646. #define SSL_TLSEXT_ERR_NOACK (3)
  1647. enum ssl_func_category {
  1648. TLS_Mandatory, /* required for HTTPS */
  1649. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1650. TLS_END_OF_LIST
  1651. };
  1652. /* Check if all TLS functions/features are available */
  1653. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1654. struct ssl_func {
  1655. const char *name; /* SSL function name */
  1656. union {
  1657. enum ssl_func_category required; /* Mandatory or optional */
  1658. void (*ptr)(void); /* Function pointer */
  1659. };
  1660. };
  1661. #if defined(OPENSSL_API_1_1)
  1662. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1663. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1664. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1665. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1666. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1667. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1668. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1669. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1670. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1671. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1672. #define OPENSSL_init_ssl \
  1673. (*(int (*)(uint64_t opts, \
  1674. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1675. .ptr)
  1676. #define SSL_CTX_use_PrivateKey_file \
  1677. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1678. #define SSL_CTX_use_certificate_file \
  1679. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1680. #define SSL_CTX_set_default_passwd_cb \
  1681. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1682. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1683. #define SSL_CTX_use_certificate_chain_file \
  1684. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1685. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1686. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1687. #define SSL_CTX_set_verify \
  1688. (*(void (*)(SSL_CTX *, \
  1689. int, \
  1690. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1691. .ptr)
  1692. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1693. #define SSL_CTX_load_verify_locations \
  1694. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1695. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1696. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1697. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1698. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1699. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1700. #define SSL_CIPHER_get_name \
  1701. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1702. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1703. #define SSL_CTX_set_session_id_context \
  1704. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1705. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1706. #define SSL_CTX_set_cipher_list \
  1707. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1708. #define SSL_CTX_set_options \
  1709. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1710. #define SSL_CTX_set_info_callback \
  1711. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1712. ssl_sw[32] \
  1713. .ptr)
  1714. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1715. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1716. #define SSL_CTX_callback_ctrl \
  1717. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1718. #define SSL_get_servername \
  1719. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1720. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1721. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1722. #define SSL_CTX_set_alpn_protos \
  1723. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1724. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1725. const unsigned char **out,
  1726. unsigned char *outlen,
  1727. const unsigned char *in,
  1728. unsigned int inlen,
  1729. void *arg);
  1730. #define SSL_CTX_set_alpn_select_cb \
  1731. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1732. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1733. const unsigned char **out,
  1734. unsigned int *outlen,
  1735. void *arg);
  1736. #define SSL_CTX_set_next_protos_advertised_cb \
  1737. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1738. .ptr)
  1739. #define SSL_CTX_clear_options(ctx, op) \
  1740. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1741. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1742. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1743. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1744. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1745. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1746. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1747. SSL_CTX_callback_ctrl(ctx, \
  1748. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1749. (void (*)(void))cb)
  1750. #define SSL_set_tlsext_host_name(ctx, arg) \
  1751. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1752. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1753. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1754. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1755. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1756. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1757. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1758. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1759. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1760. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1761. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1762. #define X509_NAME_oneline \
  1763. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1764. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1765. #define EVP_get_digestbyname \
  1766. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1767. #define EVP_Digest \
  1768. (*(int (*)( \
  1769. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1770. crypto_sw[9] \
  1771. .ptr)
  1772. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1773. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1774. #define ASN1_INTEGER_to_BN \
  1775. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1776. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1777. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1778. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1779. #define OPENSSL_free(a) CRYPTO_free(a)
  1780. #define OPENSSL_REMOVE_THREAD_STATE()
  1781. /* init_ssl_ctx() function updates this array.
  1782. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1783. * of respective functions. The macros above (like SSL_connect()) are really
  1784. * just calling these functions indirectly via the pointer. */
  1785. static struct ssl_func ssl_sw[] = {
  1786. {"SSL_free", {TLS_Mandatory}},
  1787. {"SSL_accept", {TLS_Mandatory}},
  1788. {"SSL_connect", {TLS_Mandatory}},
  1789. {"SSL_read", {TLS_Mandatory}},
  1790. {"SSL_write", {TLS_Mandatory}},
  1791. {"SSL_get_error", {TLS_Mandatory}},
  1792. {"SSL_set_fd", {TLS_Mandatory}},
  1793. {"SSL_new", {TLS_Mandatory}},
  1794. {"SSL_CTX_new", {TLS_Mandatory}},
  1795. {"TLS_server_method", {TLS_Mandatory}},
  1796. {"OPENSSL_init_ssl", {TLS_Mandatory}},
  1797. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1798. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1799. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1800. {"SSL_CTX_free", {TLS_Mandatory}},
  1801. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1802. {"TLS_client_method", {TLS_Mandatory}},
  1803. {"SSL_pending", {TLS_Mandatory}},
  1804. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1805. {"SSL_shutdown", {TLS_Mandatory}},
  1806. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1807. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1808. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1809. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1810. {"SSL_get_version", {TLS_Mandatory}},
  1811. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1812. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1813. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1814. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1815. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1816. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1817. {"SSL_CTX_set_options", {TLS_Mandatory}},
  1818. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1819. {"SSL_get_ex_data", {TLS_Mandatory}},
  1820. {"SSL_set_ex_data", {TLS_Mandatory}},
  1821. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1822. {"SSL_get_servername", {TLS_Mandatory}},
  1823. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1824. {"SSL_ctrl", {TLS_Mandatory}},
  1825. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1826. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1827. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1828. {NULL, {TLS_END_OF_LIST}}};
  1829. /* Similar array as ssl_sw. These functions could be located in different
  1830. * lib. */
  1831. static struct ssl_func crypto_sw[] = {{"ERR_get_error", {TLS_Mandatory}},
  1832. {"ERR_error_string", {TLS_Mandatory}},
  1833. {"CONF_modules_unload", {TLS_Mandatory}},
  1834. {"X509_free", {TLS_Mandatory}},
  1835. {"X509_get_subject_name",
  1836. {TLS_Mandatory}},
  1837. {"X509_get_issuer_name", {TLS_Mandatory}},
  1838. {"X509_NAME_oneline", {TLS_Mandatory}},
  1839. {"X509_get_serialNumber",
  1840. {TLS_Mandatory}},
  1841. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1842. {"EVP_Digest", {TLS_Mandatory}},
  1843. {"i2d_X509", {TLS_Mandatory}},
  1844. {"BN_bn2hex", {TLS_Mandatory}},
  1845. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1846. {"BN_free", {TLS_Mandatory}},
  1847. {"CRYPTO_free", {TLS_Mandatory}},
  1848. {"ERR_clear_error", {TLS_Mandatory}},
  1849. {NULL, {TLS_END_OF_LIST}}};
  1850. #else
  1851. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1852. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1853. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1854. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1855. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1856. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1857. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1858. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1859. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1860. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1861. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1862. #define SSL_CTX_use_PrivateKey_file \
  1863. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1864. #define SSL_CTX_use_certificate_file \
  1865. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1866. #define SSL_CTX_set_default_passwd_cb \
  1867. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1868. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1869. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1870. #define SSL_CTX_use_certificate_chain_file \
  1871. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1872. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1873. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1874. #define SSL_CTX_set_verify \
  1875. (*(void (*)(SSL_CTX *, \
  1876. int, \
  1877. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1878. .ptr)
  1879. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1880. #define SSL_CTX_load_verify_locations \
  1881. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1882. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1883. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1884. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1885. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1886. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1887. #define SSL_CIPHER_get_name \
  1888. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1889. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1890. #define SSL_CTX_set_session_id_context \
  1891. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1892. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1893. #define SSL_CTX_set_cipher_list \
  1894. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1895. #define SSL_CTX_set_info_callback \
  1896. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1897. .ptr)
  1898. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1899. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1900. #define SSL_CTX_callback_ctrl \
  1901. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1902. #define SSL_get_servername \
  1903. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1904. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1905. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1906. #define SSL_CTX_set_alpn_protos \
  1907. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1908. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1909. const unsigned char **out,
  1910. unsigned char *outlen,
  1911. const unsigned char *in,
  1912. unsigned int inlen,
  1913. void *arg);
  1914. #define SSL_CTX_set_alpn_select_cb \
  1915. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1916. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1917. const unsigned char **out,
  1918. unsigned int *outlen,
  1919. void *arg);
  1920. #define SSL_CTX_set_next_protos_advertised_cb \
  1921. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1922. .ptr)
  1923. #define SSL_CTX_set_options(ctx, op) \
  1924. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1925. #define SSL_CTX_clear_options(ctx, op) \
  1926. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1927. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1928. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1929. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1930. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1931. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1932. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1933. SSL_CTX_callback_ctrl(ctx, \
  1934. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1935. (void (*)(void))cb)
  1936. #define SSL_set_tlsext_host_name(ctx, arg) \
  1937. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1938. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1939. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1940. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1941. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1942. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1943. #define CRYPTO_set_locking_callback \
  1944. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1945. #define CRYPTO_set_id_callback \
  1946. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1947. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1948. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1949. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1950. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1951. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1952. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1953. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1954. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1955. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1956. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1957. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1958. #define X509_NAME_oneline \
  1959. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1960. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1961. #define i2c_ASN1_INTEGER \
  1962. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1963. #define EVP_get_digestbyname \
  1964. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1965. #define EVP_Digest \
  1966. (*(int (*)( \
  1967. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1968. crypto_sw[18] \
  1969. .ptr)
  1970. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1971. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1972. #define ASN1_INTEGER_to_BN \
  1973. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1974. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1975. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1976. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1977. #define OPENSSL_free(a) CRYPTO_free(a)
  1978. /* use here ERR_remove_state,
  1979. * while on some platforms function is not included into library due to
  1980. * deprication */
  1981. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1982. /* init_ssl_ctx() function updates this array.
  1983. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1984. * of respective functions. The macros above (like SSL_connect()) are really
  1985. * just calling these functions indirectly via the pointer. */
  1986. static struct ssl_func ssl_sw[] = {
  1987. {"SSL_free", {TLS_Mandatory}},
  1988. {"SSL_accept", {TLS_Mandatory}},
  1989. {"SSL_connect", {TLS_Mandatory}},
  1990. {"SSL_read", {TLS_Mandatory}},
  1991. {"SSL_write", {TLS_Mandatory}},
  1992. {"SSL_get_error", {TLS_Mandatory}},
  1993. {"SSL_set_fd", {TLS_Mandatory}},
  1994. {"SSL_new", {TLS_Mandatory}},
  1995. {"SSL_CTX_new", {TLS_Mandatory}},
  1996. {"SSLv23_server_method", {TLS_Mandatory}},
  1997. {"SSL_library_init", {TLS_Mandatory}},
  1998. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1999. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  2000. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  2001. {"SSL_CTX_free", {TLS_Mandatory}},
  2002. {"SSL_load_error_strings", {TLS_Mandatory}},
  2003. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  2004. {"SSLv23_client_method", {TLS_Mandatory}},
  2005. {"SSL_pending", {TLS_Mandatory}},
  2006. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  2007. {"SSL_shutdown", {TLS_Mandatory}},
  2008. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  2009. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  2010. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  2011. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  2012. {"SSL_get_version", {TLS_Mandatory}},
  2013. {"SSL_get_current_cipher", {TLS_Mandatory}},
  2014. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  2015. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  2016. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  2017. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  2018. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  2019. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  2020. {"SSL_get_ex_data", {TLS_Mandatory}},
  2021. {"SSL_set_ex_data", {TLS_Mandatory}},
  2022. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  2023. {"SSL_get_servername", {TLS_Mandatory}},
  2024. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  2025. {"SSL_ctrl", {TLS_Mandatory}},
  2026. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  2027. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  2028. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  2029. {NULL, {TLS_END_OF_LIST}}};
  2030. /* Similar array as ssl_sw. These functions could be located in different
  2031. * lib. */
  2032. static struct ssl_func crypto_sw[] = {
  2033. {"CRYPTO_num_locks", {TLS_Mandatory}},
  2034. {"CRYPTO_set_locking_callback", {TLS_Mandatory}},
  2035. {"CRYPTO_set_id_callback", {TLS_Mandatory}},
  2036. {"ERR_get_error", {TLS_Mandatory}},
  2037. {"ERR_error_string", {TLS_Mandatory}},
  2038. {"ERR_remove_state", {TLS_Mandatory}},
  2039. {"ERR_free_strings", {TLS_Mandatory}},
  2040. {"ENGINE_cleanup", {TLS_Mandatory}},
  2041. {"CONF_modules_unload", {TLS_Mandatory}},
  2042. {"CRYPTO_cleanup_all_ex_data", {TLS_Mandatory}},
  2043. {"EVP_cleanup", {TLS_Mandatory}},
  2044. {"X509_free", {TLS_Mandatory}},
  2045. {"X509_get_subject_name", {TLS_Mandatory}},
  2046. {"X509_get_issuer_name", {TLS_Mandatory}},
  2047. {"X509_NAME_oneline", {TLS_Mandatory}},
  2048. {"X509_get_serialNumber", {TLS_Mandatory}},
  2049. {"i2c_ASN1_INTEGER", {TLS_Mandatory}},
  2050. {"EVP_get_digestbyname", {TLS_Mandatory}},
  2051. {"EVP_Digest", {TLS_Mandatory}},
  2052. {"i2d_X509", {TLS_Mandatory}},
  2053. {"BN_bn2hex", {TLS_Mandatory}},
  2054. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  2055. {"BN_free", {TLS_Mandatory}},
  2056. {"CRYPTO_free", {TLS_Mandatory}},
  2057. {"ERR_clear_error", {TLS_Mandatory}},
  2058. {NULL, {TLS_END_OF_LIST}}};
  2059. #endif /* OPENSSL_API_1_1 */
  2060. #endif /* NO_SSL_DL */
  2061. #endif /* NO_SSL */
  2062. #if !defined(NO_CACHING)
  2063. static const char month_names[][4] = {"Jan",
  2064. "Feb",
  2065. "Mar",
  2066. "Apr",
  2067. "May",
  2068. "Jun",
  2069. "Jul",
  2070. "Aug",
  2071. "Sep",
  2072. "Oct",
  2073. "Nov",
  2074. "Dec"};
  2075. #endif /* !NO_CACHING */
  2076. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2077. * the union u. */
  2078. union usa {
  2079. struct sockaddr sa;
  2080. struct sockaddr_in sin;
  2081. #if defined(USE_IPV6)
  2082. struct sockaddr_in6 sin6;
  2083. #endif
  2084. };
  2085. /* Describes a string (chunk of memory). */
  2086. struct vec {
  2087. const char *ptr;
  2088. size_t len;
  2089. };
  2090. struct mg_file_stat {
  2091. /* File properties filled by mg_stat: */
  2092. uint64_t size;
  2093. time_t last_modified;
  2094. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2095. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2096. * case we need a "Content-Eencoding: gzip" header */
  2097. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2098. };
  2099. struct mg_file_in_memory {
  2100. char *p;
  2101. uint32_t pos;
  2102. char mode;
  2103. };
  2104. struct mg_file_access {
  2105. /* File properties filled by mg_fopen: */
  2106. FILE *fp;
  2107. #if defined(MG_USE_OPEN_FILE)
  2108. /* TODO (low): Remove obsolete "file in memory" implementation.
  2109. * In an "early 2017" discussion at Google groups
  2110. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2111. * we decided to get rid of this feature (after some fade-out
  2112. * phase). */
  2113. const char *membuf;
  2114. #endif
  2115. };
  2116. struct mg_file {
  2117. struct mg_file_stat stat;
  2118. struct mg_file_access access;
  2119. };
  2120. #if defined(MG_USE_OPEN_FILE)
  2121. #define STRUCT_FILE_INITIALIZER \
  2122. { \
  2123. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2124. { \
  2125. (FILE *)NULL, (const char *)NULL \
  2126. } \
  2127. }
  2128. #else
  2129. #define STRUCT_FILE_INITIALIZER \
  2130. { \
  2131. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2132. { \
  2133. (FILE *)NULL \
  2134. } \
  2135. }
  2136. #endif
  2137. /* Describes listening socket, or socket which was accept()-ed by the master
  2138. * thread and queued for future handling by the worker thread. */
  2139. struct socket {
  2140. SOCKET sock; /* Listening socket */
  2141. union usa lsa; /* Local socket address */
  2142. union usa rsa; /* Remote socket address */
  2143. unsigned char is_ssl; /* Is port SSL-ed */
  2144. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2145. * port */
  2146. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2147. };
  2148. /* Enum const for all options must be in sync with
  2149. * static struct mg_option config_options[]
  2150. * This is tested in the unit test (test/private.c)
  2151. * "Private Config Options"
  2152. */
  2153. enum {
  2154. /* Once for each server */
  2155. LISTENING_PORTS,
  2156. NUM_THREADS,
  2157. RUN_AS_USER,
  2158. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2159. * socket option typedef TCP_NODELAY. */
  2160. MAX_REQUEST_SIZE,
  2161. LINGER_TIMEOUT,
  2162. CONNECTION_QUEUE_SIZE,
  2163. LISTEN_BACKLOG_SIZE,
  2164. #if defined(__linux__)
  2165. ALLOW_SENDFILE_CALL,
  2166. #endif
  2167. #if defined(_WIN32)
  2168. CASE_SENSITIVE_FILES,
  2169. #endif
  2170. THROTTLE,
  2171. ACCESS_LOG_FILE,
  2172. ERROR_LOG_FILE,
  2173. ENABLE_KEEP_ALIVE,
  2174. REQUEST_TIMEOUT,
  2175. KEEP_ALIVE_TIMEOUT,
  2176. #if defined(USE_WEBSOCKET)
  2177. WEBSOCKET_TIMEOUT,
  2178. ENABLE_WEBSOCKET_PING_PONG,
  2179. #endif
  2180. DECODE_URL,
  2181. #if defined(USE_LUA)
  2182. LUA_BACKGROUND_SCRIPT,
  2183. LUA_BACKGROUND_SCRIPT_PARAMS,
  2184. #endif
  2185. #if defined(USE_TIMERS)
  2186. CGI_TIMEOUT,
  2187. #endif
  2188. /* Once for each domain */
  2189. DOCUMENT_ROOT,
  2190. CGI_EXTENSIONS,
  2191. CGI_ENVIRONMENT,
  2192. PUT_DELETE_PASSWORDS_FILE,
  2193. CGI_INTERPRETER,
  2194. CGI_INTERPRETER_ARGS,
  2195. PROTECT_URI,
  2196. AUTHENTICATION_DOMAIN,
  2197. ENABLE_AUTH_DOMAIN_CHECK,
  2198. SSI_EXTENSIONS,
  2199. ENABLE_DIRECTORY_LISTING,
  2200. GLOBAL_PASSWORDS_FILE,
  2201. INDEX_FILES,
  2202. ACCESS_CONTROL_LIST,
  2203. EXTRA_MIME_TYPES,
  2204. SSL_CERTIFICATE,
  2205. SSL_CERTIFICATE_CHAIN,
  2206. URL_REWRITE_PATTERN,
  2207. HIDE_FILES,
  2208. SSL_DO_VERIFY_PEER,
  2209. SSL_CA_PATH,
  2210. SSL_CA_FILE,
  2211. SSL_VERIFY_DEPTH,
  2212. SSL_DEFAULT_VERIFY_PATHS,
  2213. SSL_CIPHER_LIST,
  2214. SSL_PROTOCOL_VERSION,
  2215. SSL_SHORT_TRUST,
  2216. #if defined(USE_LUA)
  2217. LUA_PRELOAD_FILE,
  2218. LUA_SCRIPT_EXTENSIONS,
  2219. LUA_SERVER_PAGE_EXTENSIONS,
  2220. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2221. LUA_DEBUG_PARAMS,
  2222. #endif
  2223. #endif
  2224. #if defined(USE_DUKTAPE)
  2225. DUKTAPE_SCRIPT_EXTENSIONS,
  2226. #endif
  2227. #if defined(USE_WEBSOCKET)
  2228. WEBSOCKET_ROOT,
  2229. #endif
  2230. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2231. LUA_WEBSOCKET_EXTENSIONS,
  2232. #endif
  2233. ACCESS_CONTROL_ALLOW_ORIGIN,
  2234. ACCESS_CONTROL_ALLOW_METHODS,
  2235. ACCESS_CONTROL_ALLOW_HEADERS,
  2236. ERROR_PAGES,
  2237. #if !defined(NO_CACHING)
  2238. STATIC_FILE_MAX_AGE,
  2239. STATIC_FILE_CACHE_CONTROL,
  2240. #endif
  2241. #if !defined(NO_SSL)
  2242. STRICT_HTTPS_MAX_AGE,
  2243. #endif
  2244. ADDITIONAL_HEADER,
  2245. ALLOW_INDEX_SCRIPT_SUB_RES,
  2246. #if defined(DAEMONIZE)
  2247. ENABLE_DAEMONIZE,
  2248. #endif
  2249. NUM_OPTIONS
  2250. };
  2251. /* Config option name, config types, default value.
  2252. * Must be in the same order as the enum const above.
  2253. */
  2254. static const struct mg_option config_options[] = {
  2255. /* Once for each server */
  2256. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2257. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2258. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2259. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2260. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2261. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2262. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2263. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2264. #if defined(__linux__)
  2265. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2266. #endif
  2267. #if defined(_WIN32)
  2268. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2269. #endif
  2270. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2271. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2272. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2273. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2274. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2275. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2276. #if defined(USE_WEBSOCKET)
  2277. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2278. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2279. #endif
  2280. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2281. #if defined(USE_LUA)
  2282. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2283. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2284. #endif
  2285. #if defined(USE_TIMERS)
  2286. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2287. #endif
  2288. /* Once for each domain */
  2289. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2290. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2291. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2292. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2293. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2294. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2295. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2296. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2297. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2298. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2299. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2300. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2301. {"index_files",
  2302. MG_CONFIG_TYPE_STRING_LIST,
  2303. #if defined(USE_LUA)
  2304. "index.xhtml,index.html,index.htm,"
  2305. "index.lp,index.lsp,index.lua,index.cgi,"
  2306. "index.shtml,index.php"},
  2307. #else
  2308. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2309. #endif
  2310. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2311. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2312. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2313. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2314. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2315. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2316. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2317. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2318. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2319. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2320. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2321. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2322. #if defined(USE_HTTP2)
  2323. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  2324. * as a minimum in 2020 */
  2325. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  2326. #else
  2327. /* Keep the default (compatibility) */
  2328. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2329. #endif /* defined(USE_HTTP2) */
  2330. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2331. #if defined(USE_LUA)
  2332. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2333. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2334. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2335. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2336. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2337. #endif
  2338. #endif
  2339. #if defined(USE_DUKTAPE)
  2340. /* The support for duktape is still in alpha version state.
  2341. * The name of this config option might change. */
  2342. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2343. #endif
  2344. #if defined(USE_WEBSOCKET)
  2345. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2346. #endif
  2347. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2348. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2349. #endif
  2350. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2351. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2352. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2353. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2354. #if !defined(NO_CACHING)
  2355. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2356. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2357. #endif
  2358. #if !defined(NO_SSL)
  2359. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2360. #endif
  2361. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2362. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2363. #if defined(DAEMONIZE)
  2364. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2365. #endif
  2366. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2367. /* Check if the config_options and the corresponding enum have compatible
  2368. * sizes. */
  2369. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2370. == (NUM_OPTIONS + 1),
  2371. "config_options and enum not sync");
  2372. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2373. struct mg_handler_info {
  2374. /* Name/Pattern of the URI. */
  2375. char *uri;
  2376. size_t uri_len;
  2377. /* handler type */
  2378. int handler_type;
  2379. /* Handler for http/https or authorization requests. */
  2380. mg_request_handler handler;
  2381. unsigned int refcount;
  2382. int removing;
  2383. /* Handler for ws/wss (websocket) requests. */
  2384. mg_websocket_connect_handler connect_handler;
  2385. mg_websocket_ready_handler ready_handler;
  2386. mg_websocket_data_handler data_handler;
  2387. mg_websocket_close_handler close_handler;
  2388. /* accepted subprotocols for ws/wss requests. */
  2389. struct mg_websocket_subprotocols *subprotocols;
  2390. /* Handler for authorization requests */
  2391. mg_authorization_handler auth_handler;
  2392. /* User supplied argument for the handler function. */
  2393. void *cbdata;
  2394. /* next handler in a linked list */
  2395. struct mg_handler_info *next;
  2396. };
  2397. enum {
  2398. CONTEXT_INVALID,
  2399. CONTEXT_SERVER,
  2400. CONTEXT_HTTP_CLIENT,
  2401. CONTEXT_WS_CLIENT
  2402. };
  2403. struct mg_domain_context {
  2404. SSL_CTX *ssl_ctx; /* SSL context */
  2405. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2406. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2407. int64_t ssl_cert_last_mtime;
  2408. /* Server nonce */
  2409. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2410. unsigned long nonce_count; /* Used nonces, used for authentication */
  2411. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2412. /* linked list of shared lua websockets */
  2413. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2414. #endif
  2415. /* Linked list of domains */
  2416. struct mg_domain_context *next;
  2417. };
  2418. /* Stop flag can be "volatile" or require a lock */
  2419. typedef int volatile stop_flag_t;
  2420. #ifdef STOP_FLAG_NEEDS_LOCK
  2421. static int
  2422. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2423. {
  2424. int r;
  2425. mg_global_lock();
  2426. r = ((*f) == 0);
  2427. mg_global_unlock();
  2428. return r;
  2429. }
  2430. static int
  2431. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2432. {
  2433. int r;
  2434. mg_global_lock();
  2435. r = ((*f) == 2);
  2436. mg_global_unlock();
  2437. return r;
  2438. }
  2439. static void
  2440. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2441. {
  2442. mg_global_lock();
  2443. (*f) = v;
  2444. mg_global_unlock();
  2445. }
  2446. #else /* STOP_FLAG_NEEDS_LOCK */
  2447. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2448. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2449. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2450. #endif /* STOP_FLAG_NEEDS_LOCK */
  2451. struct mg_context {
  2452. /* Part 1 - Physical context:
  2453. * This holds threads, ports, timeouts, ...
  2454. * set for the entire server, independent from the
  2455. * addressed hostname.
  2456. */
  2457. /* Connection related */
  2458. int context_type; /* See CONTEXT_* above */
  2459. struct socket *listening_sockets;
  2460. struct mg_pollfd *listening_socket_fds;
  2461. unsigned int num_listening_sockets;
  2462. struct mg_connection *worker_connections; /* The connection struct, pre-
  2463. * allocated for each worker */
  2464. #if defined(USE_SERVER_STATS)
  2465. volatile ptrdiff_t active_connections;
  2466. volatile ptrdiff_t max_active_connections;
  2467. volatile ptrdiff_t total_connections;
  2468. volatile ptrdiff_t total_requests;
  2469. volatile int64_t total_data_read;
  2470. volatile int64_t total_data_written;
  2471. #endif
  2472. /* Thread related */
  2473. stop_flag_t stop_flag; /* Should we stop event loop */
  2474. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2475. pthread_t masterthreadid; /* The master thread ID */
  2476. unsigned int
  2477. cfg_worker_threads; /* The number of configured worker threads. */
  2478. pthread_t *worker_threadids; /* The worker thread IDs */
  2479. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2480. /* Connection to thread dispatching */
  2481. #if defined(ALTERNATIVE_QUEUE)
  2482. struct socket *client_socks;
  2483. void **client_wait_events;
  2484. #else
  2485. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2486. worker thread */
  2487. volatile int sq_head; /* Head of the socket queue */
  2488. volatile int sq_tail; /* Tail of the socket queue */
  2489. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2490. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2491. volatile int sq_blocked; /* Status information: sq is full */
  2492. int sq_size; /* No of elements in socket queue */
  2493. #if defined(USE_SERVER_STATS)
  2494. int sq_max_fill;
  2495. #endif /* USE_SERVER_STATS */
  2496. #endif /* ALTERNATIVE_QUEUE */
  2497. /* Memory related */
  2498. unsigned int max_request_size; /* The max request size */
  2499. #if defined(USE_SERVER_STATS)
  2500. struct mg_memory_stat ctx_memory;
  2501. #endif
  2502. /* Operating system related */
  2503. char *systemName; /* What operating system is running */
  2504. time_t start_time; /* Server start time, used for authentication
  2505. * and for diagnstics. */
  2506. #if defined(USE_TIMERS)
  2507. struct ttimers *timers;
  2508. #endif
  2509. /* Lua specific: Background operations and shared websockets */
  2510. #if defined(USE_LUA)
  2511. void *lua_background_state;
  2512. #endif
  2513. /* Server nonce */
  2514. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2515. * ssl_cert_last_mtime, nonce_count, and
  2516. * next (linked list) */
  2517. /* Server callbacks */
  2518. struct mg_callbacks callbacks; /* User-defined callback function */
  2519. void *user_data; /* User-defined data */
  2520. /* Part 2 - Logical domain:
  2521. * This holds hostname, TLS certificate, document root, ...
  2522. * set for a domain hosted at the server.
  2523. * There may be multiple domains hosted at one physical server.
  2524. * The default domain "dd" is the first element of a list of
  2525. * domains.
  2526. */
  2527. struct mg_domain_context dd; /* default domain */
  2528. };
  2529. #if defined(USE_SERVER_STATS)
  2530. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2531. static struct mg_memory_stat *
  2532. get_memory_stat(struct mg_context *ctx)
  2533. {
  2534. if (ctx) {
  2535. return &(ctx->ctx_memory);
  2536. }
  2537. return &mg_common_memory;
  2538. }
  2539. #endif
  2540. enum {
  2541. CONNECTION_TYPE_INVALID = 0,
  2542. CONNECTION_TYPE_REQUEST = 1,
  2543. CONNECTION_TYPE_RESPONSE = 2
  2544. };
  2545. enum {
  2546. PROTOCOL_TYPE_HTTP1 = 0,
  2547. PROTOCOL_TYPE_WEBSOCKET = 1,
  2548. PROTOCOL_TYPE_HTTP2 = 2
  2549. };
  2550. #if defined(USE_HTTP2)
  2551. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2552. #define HTTP2_DYN_TABLE_SIZE (256)
  2553. #endif
  2554. struct mg_http2_connection {
  2555. uint32_t stream_id;
  2556. uint32_t dyn_table_size;
  2557. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2558. };
  2559. #endif
  2560. struct mg_connection {
  2561. int connection_type; /* see CONNECTION_TYPE_* above */
  2562. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2563. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2564. fully sent */
  2565. #ifdef USE_HTTP2
  2566. struct mg_http2_connection http2;
  2567. #endif
  2568. struct mg_request_info request_info;
  2569. struct mg_response_info response_info;
  2570. struct mg_context *phys_ctx;
  2571. struct mg_domain_context *dom_ctx;
  2572. #if defined(USE_SERVER_STATS)
  2573. int conn_state; /* 0 = undef, numerical value may change in different
  2574. * versions. For the current definition, see
  2575. * mg_get_connection_info_impl */
  2576. #endif
  2577. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2578. SSL *ssl; /* SSL descriptor */
  2579. struct socket client; /* Connected client */
  2580. time_t conn_birth_time; /* Time (wall clock) when connection was
  2581. * established */
  2582. #if defined(USE_SERVER_STATS)
  2583. time_t conn_close_time; /* Time (wall clock) when connection was
  2584. * closed (or 0 if still open) */
  2585. #endif
  2586. struct timespec req_time; /* Time (since system start) when the request
  2587. * was received */
  2588. int64_t num_bytes_sent; /* Total bytes sent to client */
  2589. int64_t content_len; /* How many bytes of content can be read
  2590. * !is_chunked: Content-Length header value
  2591. * or -1 (until connection closed,
  2592. * not allowed for a request)
  2593. * is_chunked: >= 0, appended gradually
  2594. */
  2595. int64_t consumed_content; /* How many bytes of content have been read */
  2596. int is_chunked; /* Transfer-Encoding is chunked:
  2597. * 0 = not chunked,
  2598. * 1 = chunked, not yet, or some data read,
  2599. * 2 = chunked, has error,
  2600. * 3 = chunked, all data read except trailer,
  2601. * 4 = chunked, all data read
  2602. */
  2603. char *buf; /* Buffer for received data */
  2604. char *path_info; /* PATH_INFO part of the URL */
  2605. int must_close; /* 1 if connection must be closed */
  2606. int accept_gzip; /* 1 if gzip encoding is accepted */
  2607. int in_error_handler; /* 1 if in handler for user defined error
  2608. * pages */
  2609. #if defined(USE_WEBSOCKET)
  2610. int in_websocket_handling; /* 1 if in read_websocket */
  2611. #endif
  2612. int handled_requests; /* Number of requests handled by this connection
  2613. */
  2614. int buf_size; /* Buffer size */
  2615. int request_len; /* Size of the request + headers in a buffer */
  2616. int data_len; /* Total size of data in a buffer */
  2617. int status_code; /* HTTP reply status code, e.g. 200 */
  2618. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2619. * throttle */
  2620. time_t last_throttle_time; /* Last time throttled data was sent */
  2621. int last_throttle_bytes; /* Bytes sent this second */
  2622. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2623. * atomic transmissions for websockets */
  2624. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2625. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2626. #endif
  2627. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2628. * for quick access */
  2629. };
  2630. /* Directory entry */
  2631. struct de {
  2632. struct mg_connection *conn;
  2633. char *file_name;
  2634. struct mg_file_stat file;
  2635. };
  2636. #define mg_cry_internal(conn, fmt, ...) \
  2637. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2638. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2639. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2640. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2641. struct mg_context *ctx,
  2642. const char *func,
  2643. unsigned line,
  2644. const char *fmt,
  2645. ...) PRINTF_ARGS(5, 6);
  2646. #if !defined(NO_THREAD_NAME)
  2647. #if defined(_WIN32) && defined(_MSC_VER)
  2648. /* Set the thread name for debugging purposes in Visual Studio
  2649. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2650. */
  2651. #pragma pack(push, 8)
  2652. typedef struct tagTHREADNAME_INFO {
  2653. DWORD dwType; /* Must be 0x1000. */
  2654. LPCSTR szName; /* Pointer to name (in user addr space). */
  2655. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2656. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2657. } THREADNAME_INFO;
  2658. #pragma pack(pop)
  2659. #elif defined(__linux__)
  2660. #include <sys/prctl.h>
  2661. #include <sys/sendfile.h>
  2662. #if defined(ALTERNATIVE_QUEUE)
  2663. #include <sys/eventfd.h>
  2664. #endif /* ALTERNATIVE_QUEUE */
  2665. #if defined(ALTERNATIVE_QUEUE)
  2666. static void *
  2667. event_create(void)
  2668. {
  2669. int evhdl = eventfd(0, EFD_CLOEXEC);
  2670. int *ret;
  2671. if (evhdl == -1) {
  2672. /* Linux uses -1 on error, Windows NULL. */
  2673. /* However, Linux does not return 0 on success either. */
  2674. return 0;
  2675. }
  2676. ret = (int *)mg_malloc(sizeof(int));
  2677. if (ret) {
  2678. *ret = evhdl;
  2679. } else {
  2680. (void)close(evhdl);
  2681. }
  2682. return (void *)ret;
  2683. }
  2684. static int
  2685. event_wait(void *eventhdl)
  2686. {
  2687. uint64_t u;
  2688. int evhdl, s;
  2689. if (!eventhdl) {
  2690. /* error */
  2691. return 0;
  2692. }
  2693. evhdl = *(int *)eventhdl;
  2694. s = (int)read(evhdl, &u, sizeof(u));
  2695. if (s != sizeof(u)) {
  2696. /* error */
  2697. return 0;
  2698. }
  2699. (void)u; /* the value is not required */
  2700. return 1;
  2701. }
  2702. static int
  2703. event_signal(void *eventhdl)
  2704. {
  2705. uint64_t u = 1;
  2706. int evhdl, s;
  2707. if (!eventhdl) {
  2708. /* error */
  2709. return 0;
  2710. }
  2711. evhdl = *(int *)eventhdl;
  2712. s = (int)write(evhdl, &u, sizeof(u));
  2713. if (s != sizeof(u)) {
  2714. /* error */
  2715. return 0;
  2716. }
  2717. return 1;
  2718. }
  2719. static void
  2720. event_destroy(void *eventhdl)
  2721. {
  2722. int evhdl;
  2723. if (!eventhdl) {
  2724. /* error */
  2725. return;
  2726. }
  2727. evhdl = *(int *)eventhdl;
  2728. close(evhdl);
  2729. mg_free(eventhdl);
  2730. }
  2731. #endif
  2732. #endif
  2733. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2734. struct posix_event {
  2735. pthread_mutex_t mutex;
  2736. pthread_cond_t cond;
  2737. int signaled;
  2738. };
  2739. static void *
  2740. event_create(void)
  2741. {
  2742. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2743. if (ret == 0) {
  2744. /* out of memory */
  2745. return 0;
  2746. }
  2747. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2748. /* pthread mutex not available */
  2749. mg_free(ret);
  2750. return 0;
  2751. }
  2752. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2753. /* pthread cond not available */
  2754. pthread_mutex_destroy(&(ret->mutex));
  2755. mg_free(ret);
  2756. return 0;
  2757. }
  2758. ret->signaled = 0;
  2759. return (void *)ret;
  2760. }
  2761. static int
  2762. event_wait(void *eventhdl)
  2763. {
  2764. struct posix_event *ev = (struct posix_event *)eventhdl;
  2765. pthread_mutex_lock(&(ev->mutex));
  2766. while (!ev->signaled) {
  2767. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2768. }
  2769. ev->signaled = 0;
  2770. pthread_mutex_unlock(&(ev->mutex));
  2771. return 1;
  2772. }
  2773. static int
  2774. event_signal(void *eventhdl)
  2775. {
  2776. struct posix_event *ev = (struct posix_event *)eventhdl;
  2777. pthread_mutex_lock(&(ev->mutex));
  2778. pthread_cond_signal(&(ev->cond));
  2779. ev->signaled = 1;
  2780. pthread_mutex_unlock(&(ev->mutex));
  2781. return 1;
  2782. }
  2783. static void
  2784. event_destroy(void *eventhdl)
  2785. {
  2786. struct posix_event *ev = (struct posix_event *)eventhdl;
  2787. pthread_cond_destroy(&(ev->cond));
  2788. pthread_mutex_destroy(&(ev->mutex));
  2789. mg_free(ev);
  2790. }
  2791. #endif
  2792. static void
  2793. mg_set_thread_name(const char *name)
  2794. {
  2795. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2796. mg_snprintf(
  2797. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2798. #if defined(_WIN32)
  2799. #if defined(_MSC_VER)
  2800. /* Windows and Visual Studio Compiler */
  2801. __try {
  2802. THREADNAME_INFO info;
  2803. info.dwType = 0x1000;
  2804. info.szName = threadName;
  2805. info.dwThreadID = ~0U;
  2806. info.dwFlags = 0;
  2807. RaiseException(0x406D1388,
  2808. 0,
  2809. sizeof(info) / sizeof(ULONG_PTR),
  2810. (ULONG_PTR *)&info);
  2811. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2812. }
  2813. #elif defined(__MINGW32__)
  2814. /* No option known to set thread name for MinGW known */
  2815. #endif
  2816. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2817. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2818. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2819. #if defined(__MACH__)
  2820. /* OS X only current thread name can be changed */
  2821. (void)pthread_setname_np(threadName);
  2822. #else
  2823. (void)pthread_setname_np(pthread_self(), threadName);
  2824. #endif
  2825. #elif defined(__linux__)
  2826. /* On Linux we can use the prctl function.
  2827. * When building for Linux Standard Base (LSB) use
  2828. * NO_THREAD_NAME. However, thread names are a big
  2829. * help for debugging, so the stadard is to set them.
  2830. */
  2831. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2832. #endif
  2833. }
  2834. #else /* !defined(NO_THREAD_NAME) */
  2835. void
  2836. mg_set_thread_name(const char *threadName)
  2837. {
  2838. }
  2839. #endif
  2840. #if defined(MG_LEGACY_INTERFACE)
  2841. const char **
  2842. mg_get_valid_option_names(void)
  2843. {
  2844. /* This function is deprecated. Use mg_get_valid_options instead. */
  2845. static const char
  2846. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2847. int i;
  2848. for (i = 0; config_options[i].name != NULL; i++) {
  2849. data[i * 2] = config_options[i].name;
  2850. data[i * 2 + 1] = config_options[i].default_value;
  2851. }
  2852. return data;
  2853. }
  2854. #endif
  2855. const struct mg_option *
  2856. mg_get_valid_options(void)
  2857. {
  2858. return config_options;
  2859. }
  2860. /* Do not open file (used in is_file_in_memory) */
  2861. #define MG_FOPEN_MODE_NONE (0)
  2862. /* Open file for read only access */
  2863. #define MG_FOPEN_MODE_READ (1)
  2864. /* Open file for writing, create and overwrite */
  2865. #define MG_FOPEN_MODE_WRITE (2)
  2866. /* Open file for writing, create and append */
  2867. #define MG_FOPEN_MODE_APPEND (4)
  2868. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2869. * output filep and return 1, otherwise return 0 and don't modify anything.
  2870. */
  2871. static int
  2872. open_file_in_memory(const struct mg_connection *conn,
  2873. const char *path,
  2874. struct mg_file *filep,
  2875. int mode)
  2876. {
  2877. #if defined(MG_USE_OPEN_FILE)
  2878. size_t size = 0;
  2879. const char *buf = NULL;
  2880. if (!conn) {
  2881. return 0;
  2882. }
  2883. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2884. return 0;
  2885. }
  2886. if (conn->phys_ctx->callbacks.open_file) {
  2887. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2888. if (buf != NULL) {
  2889. if (filep == NULL) {
  2890. /* This is a file in memory, but we cannot store the
  2891. * properties
  2892. * now.
  2893. * Called from "is_file_in_memory" function. */
  2894. return 1;
  2895. }
  2896. /* NOTE: override filep->size only on success. Otherwise, it
  2897. * might
  2898. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2899. filep->access.membuf = buf;
  2900. filep->access.fp = NULL;
  2901. /* Size was set by the callback */
  2902. filep->stat.size = size;
  2903. /* Assume the data may change during runtime by setting
  2904. * last_modified = now */
  2905. filep->stat.last_modified = time(NULL);
  2906. filep->stat.is_directory = 0;
  2907. filep->stat.is_gzipped = 0;
  2908. }
  2909. }
  2910. return (buf != NULL);
  2911. #else
  2912. (void)conn;
  2913. (void)path;
  2914. (void)filep;
  2915. (void)mode;
  2916. return 0;
  2917. #endif
  2918. }
  2919. static int
  2920. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2921. {
  2922. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2923. }
  2924. static int
  2925. is_file_opened(const struct mg_file_access *fileacc)
  2926. {
  2927. if (!fileacc) {
  2928. return 0;
  2929. }
  2930. #if defined(MG_USE_OPEN_FILE)
  2931. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2932. #else
  2933. return (fileacc->fp != NULL);
  2934. #endif
  2935. }
  2936. #if !defined(NO_FILESYSTEMS)
  2937. static int mg_stat(const struct mg_connection *conn,
  2938. const char *path,
  2939. struct mg_file_stat *filep);
  2940. /* mg_fopen will open a file either in memory or on the disk.
  2941. * The input parameter path is a string in UTF-8 encoding.
  2942. * The input parameter mode is MG_FOPEN_MODE_*
  2943. * On success, either fp or membuf will be set in the output
  2944. * struct file. All status members will also be set.
  2945. * The function returns 1 on success, 0 on error. */
  2946. static int
  2947. mg_fopen(const struct mg_connection *conn,
  2948. const char *path,
  2949. int mode,
  2950. struct mg_file *filep)
  2951. {
  2952. int found;
  2953. if (!filep) {
  2954. return 0;
  2955. }
  2956. filep->access.fp = NULL;
  2957. #if defined(MG_USE_OPEN_FILE)
  2958. filep->access.membuf = NULL;
  2959. #endif
  2960. if (!is_file_in_memory(conn, path)) {
  2961. /* filep is initialized in mg_stat: all fields with memset to,
  2962. * some fields like size and modification date with values */
  2963. found = mg_stat(conn, path, &(filep->stat));
  2964. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2965. /* file does not exist and will not be created */
  2966. return 0;
  2967. }
  2968. #if defined(_WIN32)
  2969. {
  2970. wchar_t wbuf[W_PATH_MAX];
  2971. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2972. switch (mode) {
  2973. case MG_FOPEN_MODE_READ:
  2974. filep->access.fp = _wfopen(wbuf, L"rb");
  2975. break;
  2976. case MG_FOPEN_MODE_WRITE:
  2977. filep->access.fp = _wfopen(wbuf, L"wb");
  2978. break;
  2979. case MG_FOPEN_MODE_APPEND:
  2980. filep->access.fp = _wfopen(wbuf, L"ab");
  2981. break;
  2982. }
  2983. }
  2984. #else
  2985. /* Linux et al already use unicode. No need to convert. */
  2986. switch (mode) {
  2987. case MG_FOPEN_MODE_READ:
  2988. filep->access.fp = fopen(path, "r");
  2989. break;
  2990. case MG_FOPEN_MODE_WRITE:
  2991. filep->access.fp = fopen(path, "w");
  2992. break;
  2993. case MG_FOPEN_MODE_APPEND:
  2994. filep->access.fp = fopen(path, "a");
  2995. break;
  2996. }
  2997. #endif
  2998. if (!found) {
  2999. /* File did not exist before fopen was called.
  3000. * Maybe it has been created now. Get stat info
  3001. * like creation time now. */
  3002. found = mg_stat(conn, path, &(filep->stat));
  3003. (void)found;
  3004. }
  3005. /* file is on disk */
  3006. return (filep->access.fp != NULL);
  3007. } else {
  3008. #if defined(MG_USE_OPEN_FILE)
  3009. /* is_file_in_memory returned true */
  3010. if (open_file_in_memory(conn, path, filep, mode)) {
  3011. /* file is in memory */
  3012. return (filep->access.membuf != NULL);
  3013. }
  3014. #endif
  3015. }
  3016. /* Open failed */
  3017. return 0;
  3018. }
  3019. /* return 0 on success, just like fclose */
  3020. static int
  3021. mg_fclose(struct mg_file_access *fileacc)
  3022. {
  3023. int ret = -1;
  3024. if (fileacc != NULL) {
  3025. if (fileacc->fp != NULL) {
  3026. ret = fclose(fileacc->fp);
  3027. #if defined(MG_USE_OPEN_FILE)
  3028. } else if (fileacc->membuf != NULL) {
  3029. ret = 0;
  3030. #endif
  3031. }
  3032. /* reset all members of fileacc */
  3033. memset(fileacc, 0, sizeof(*fileacc));
  3034. }
  3035. return ret;
  3036. }
  3037. #endif /* NO_FILESYSTEMS */
  3038. static void
  3039. mg_strlcpy(register char *dst, register const char *src, size_t n)
  3040. {
  3041. for (; *src != '\0' && n > 1; n--) {
  3042. *dst++ = *src++;
  3043. }
  3044. *dst = '\0';
  3045. }
  3046. static int
  3047. lowercase(const char *s)
  3048. {
  3049. return tolower((unsigned char)*s);
  3050. }
  3051. int
  3052. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  3053. {
  3054. int diff = 0;
  3055. if (len > 0) {
  3056. do {
  3057. diff = lowercase(s1++) - lowercase(s2++);
  3058. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  3059. }
  3060. return diff;
  3061. }
  3062. int
  3063. mg_strcasecmp(const char *s1, const char *s2)
  3064. {
  3065. int diff;
  3066. do {
  3067. diff = lowercase(s1++) - lowercase(s2++);
  3068. } while (diff == 0 && s1[-1] != '\0');
  3069. return diff;
  3070. }
  3071. static char *
  3072. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3073. {
  3074. char *p;
  3075. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3076. * defined */
  3077. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3078. mg_strlcpy(p, ptr, len + 1);
  3079. }
  3080. return p;
  3081. }
  3082. static char *
  3083. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3084. {
  3085. return mg_strndup_ctx(str, strlen(str), ctx);
  3086. }
  3087. static char *
  3088. mg_strdup(const char *str)
  3089. {
  3090. return mg_strndup_ctx(str, strlen(str), NULL);
  3091. }
  3092. static const char *
  3093. mg_strcasestr(const char *big_str, const char *small_str)
  3094. {
  3095. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3096. if (big_len >= small_len) {
  3097. for (i = 0; i <= (big_len - small_len); i++) {
  3098. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3099. return big_str + i;
  3100. }
  3101. }
  3102. }
  3103. return NULL;
  3104. }
  3105. /* Return null terminated string of given maximum length.
  3106. * Report errors if length is exceeded. */
  3107. static void
  3108. mg_vsnprintf(const struct mg_connection *conn,
  3109. int *truncated,
  3110. char *buf,
  3111. size_t buflen,
  3112. const char *fmt,
  3113. va_list ap)
  3114. {
  3115. int n, ok;
  3116. if (buflen == 0) {
  3117. if (truncated) {
  3118. *truncated = 1;
  3119. }
  3120. return;
  3121. }
  3122. #if defined(__clang__)
  3123. #pragma clang diagnostic push
  3124. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3125. /* Using fmt as a non-literal is intended here, since it is mostly called
  3126. * indirectly by mg_snprintf */
  3127. #endif
  3128. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3129. ok = (n >= 0) && ((size_t)n < buflen);
  3130. #if defined(__clang__)
  3131. #pragma clang diagnostic pop
  3132. #endif
  3133. if (ok) {
  3134. if (truncated) {
  3135. *truncated = 0;
  3136. }
  3137. } else {
  3138. if (truncated) {
  3139. *truncated = 1;
  3140. }
  3141. mg_cry_internal(conn,
  3142. "truncating vsnprintf buffer: [%.*s]",
  3143. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3144. buf);
  3145. n = (int)buflen - 1;
  3146. }
  3147. buf[n] = '\0';
  3148. }
  3149. static void
  3150. mg_snprintf(const struct mg_connection *conn,
  3151. int *truncated,
  3152. char *buf,
  3153. size_t buflen,
  3154. const char *fmt,
  3155. ...)
  3156. {
  3157. va_list ap;
  3158. va_start(ap, fmt);
  3159. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3160. va_end(ap);
  3161. }
  3162. static int
  3163. get_option_index(const char *name)
  3164. {
  3165. int i;
  3166. for (i = 0; config_options[i].name != NULL; i++) {
  3167. if (strcmp(config_options[i].name, name) == 0) {
  3168. return i;
  3169. }
  3170. }
  3171. return -1;
  3172. }
  3173. const char *
  3174. mg_get_option(const struct mg_context *ctx, const char *name)
  3175. {
  3176. int i;
  3177. if ((i = get_option_index(name)) == -1) {
  3178. return NULL;
  3179. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3180. return "";
  3181. } else {
  3182. return ctx->dd.config[i];
  3183. }
  3184. }
  3185. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3186. struct mg_context *
  3187. mg_get_context(const struct mg_connection *conn)
  3188. {
  3189. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3190. }
  3191. void *
  3192. mg_get_user_data(const struct mg_context *ctx)
  3193. {
  3194. return (ctx == NULL) ? NULL : ctx->user_data;
  3195. }
  3196. void *
  3197. mg_get_user_context_data(const struct mg_connection *conn)
  3198. {
  3199. return mg_get_user_data(mg_get_context(conn));
  3200. }
  3201. void *
  3202. mg_get_thread_pointer(const struct mg_connection *conn)
  3203. {
  3204. /* both methods should return the same pointer */
  3205. if (conn) {
  3206. /* quick access, in case conn is known */
  3207. return conn->tls_user_ptr;
  3208. } else {
  3209. /* otherwise get pointer from thread local storage (TLS) */
  3210. struct mg_workerTLS *tls =
  3211. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3212. return tls->user_ptr;
  3213. }
  3214. }
  3215. void
  3216. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3217. {
  3218. if (conn != NULL) {
  3219. conn->request_info.conn_data = data;
  3220. }
  3221. }
  3222. void *
  3223. mg_get_user_connection_data(const struct mg_connection *conn)
  3224. {
  3225. if (conn != NULL) {
  3226. return conn->request_info.conn_data;
  3227. }
  3228. return NULL;
  3229. }
  3230. #if defined(MG_LEGACY_INTERFACE)
  3231. /* Deprecated: Use mg_get_server_ports instead. */
  3232. size_t
  3233. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3234. {
  3235. size_t i;
  3236. if (!ctx) {
  3237. return 0;
  3238. }
  3239. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3240. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3241. ports[i] =
  3242. #if defined(USE_IPV6)
  3243. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3244. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3245. :
  3246. #endif
  3247. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3248. }
  3249. return i;
  3250. }
  3251. #endif
  3252. int
  3253. mg_get_server_ports(const struct mg_context *ctx,
  3254. int size,
  3255. struct mg_server_port *ports)
  3256. {
  3257. int i, cnt = 0;
  3258. if (size <= 0) {
  3259. return -1;
  3260. }
  3261. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3262. if (!ctx) {
  3263. return -1;
  3264. }
  3265. if (!ctx->listening_sockets) {
  3266. return -1;
  3267. }
  3268. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3269. ports[cnt].port =
  3270. #if defined(USE_IPV6)
  3271. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3272. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3273. :
  3274. #endif
  3275. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3276. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3277. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3278. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3279. /* IPv4 */
  3280. ports[cnt].protocol = 1;
  3281. cnt++;
  3282. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3283. /* IPv6 */
  3284. ports[cnt].protocol = 3;
  3285. cnt++;
  3286. }
  3287. }
  3288. return cnt;
  3289. }
  3290. static void
  3291. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3292. {
  3293. buf[0] = '\0';
  3294. if (!usa) {
  3295. return;
  3296. }
  3297. if (usa->sa.sa_family == AF_INET) {
  3298. getnameinfo(&usa->sa,
  3299. sizeof(usa->sin),
  3300. buf,
  3301. (unsigned)len,
  3302. NULL,
  3303. 0,
  3304. NI_NUMERICHOST);
  3305. }
  3306. #if defined(USE_IPV6)
  3307. else if (usa->sa.sa_family == AF_INET6) {
  3308. getnameinfo(&usa->sa,
  3309. sizeof(usa->sin6),
  3310. buf,
  3311. (unsigned)len,
  3312. NULL,
  3313. 0,
  3314. NI_NUMERICHOST);
  3315. }
  3316. #endif
  3317. }
  3318. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3319. * included in all responses other than 100, 101, 5xx. */
  3320. static void
  3321. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3322. {
  3323. #if !defined(REENTRANT_TIME)
  3324. struct tm *tm;
  3325. tm = ((t != NULL) ? gmtime(t) : NULL);
  3326. if (tm != NULL) {
  3327. #else
  3328. struct tm _tm;
  3329. struct tm *tm = &_tm;
  3330. if (t != NULL) {
  3331. gmtime_r(t, tm);
  3332. #endif
  3333. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3334. } else {
  3335. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3336. buf[buf_len - 1] = '\0';
  3337. }
  3338. }
  3339. /* difftime for struct timespec. Return value is in seconds. */
  3340. static double
  3341. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3342. {
  3343. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3344. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3345. }
  3346. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3347. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3348. const char *func,
  3349. unsigned line,
  3350. const char *fmt,
  3351. va_list ap);
  3352. #include "external_mg_cry_internal_impl.inl"
  3353. #elif !defined(NO_FILESYSTEMS)
  3354. /* Print error message to the opened error log stream. */
  3355. static void
  3356. mg_cry_internal_impl(const struct mg_connection *conn,
  3357. const char *func,
  3358. unsigned line,
  3359. const char *fmt,
  3360. va_list ap)
  3361. {
  3362. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3363. struct mg_file fi;
  3364. time_t timestamp;
  3365. /* Unused, in the RELEASE build */
  3366. (void)func;
  3367. (void)line;
  3368. #if defined(GCC_DIAGNOSTIC)
  3369. #pragma GCC diagnostic push
  3370. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3371. #endif
  3372. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3373. #if defined(GCC_DIAGNOSTIC)
  3374. #pragma GCC diagnostic pop
  3375. #endif
  3376. buf[sizeof(buf) - 1] = 0;
  3377. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3378. if (!conn) {
  3379. puts(buf);
  3380. return;
  3381. }
  3382. /* Do not lock when getting the callback value, here and below.
  3383. * I suppose this is fine, since function cannot disappear in the
  3384. * same way string option can. */
  3385. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3386. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3387. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3388. if (mg_fopen(conn,
  3389. conn->dom_ctx->config[ERROR_LOG_FILE],
  3390. MG_FOPEN_MODE_APPEND,
  3391. &fi)
  3392. == 0) {
  3393. fi.access.fp = NULL;
  3394. }
  3395. } else {
  3396. fi.access.fp = NULL;
  3397. }
  3398. if (fi.access.fp != NULL) {
  3399. flockfile(fi.access.fp);
  3400. timestamp = time(NULL);
  3401. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3402. fprintf(fi.access.fp,
  3403. "[%010lu] [error] [client %s] ",
  3404. (unsigned long)timestamp,
  3405. src_addr);
  3406. if (conn->request_info.request_method != NULL) {
  3407. fprintf(fi.access.fp,
  3408. "%s %s: ",
  3409. conn->request_info.request_method,
  3410. conn->request_info.request_uri
  3411. ? conn->request_info.request_uri
  3412. : "");
  3413. }
  3414. fprintf(fi.access.fp, "%s", buf);
  3415. fputc('\n', fi.access.fp);
  3416. fflush(fi.access.fp);
  3417. funlockfile(fi.access.fp);
  3418. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3419. * mg_cry here anyway ;-) */
  3420. }
  3421. }
  3422. }
  3423. #else
  3424. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3425. #endif /* Externally provided function */
  3426. /* Construct fake connection structure. Used for logging, if connection
  3427. * is not applicable at the moment of logging. */
  3428. static struct mg_connection *
  3429. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3430. {
  3431. static const struct mg_connection conn_zero = {0};
  3432. *fc = conn_zero;
  3433. fc->phys_ctx = ctx;
  3434. fc->dom_ctx = &(ctx->dd);
  3435. return fc;
  3436. }
  3437. static void
  3438. mg_cry_internal_wrap(const struct mg_connection *conn,
  3439. struct mg_context *ctx,
  3440. const char *func,
  3441. unsigned line,
  3442. const char *fmt,
  3443. ...)
  3444. {
  3445. va_list ap;
  3446. va_start(ap, fmt);
  3447. if (!conn && ctx) {
  3448. struct mg_connection fc;
  3449. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3450. } else {
  3451. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3452. }
  3453. va_end(ap);
  3454. }
  3455. void
  3456. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3457. {
  3458. va_list ap;
  3459. va_start(ap, fmt);
  3460. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3461. va_end(ap);
  3462. }
  3463. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3464. const char *
  3465. mg_version(void)
  3466. {
  3467. return CIVETWEB_VERSION;
  3468. }
  3469. const struct mg_request_info *
  3470. mg_get_request_info(const struct mg_connection *conn)
  3471. {
  3472. if (!conn) {
  3473. return NULL;
  3474. }
  3475. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3476. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3477. char txt[16];
  3478. struct mg_workerTLS *tls =
  3479. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3480. sprintf(txt, "%03i", conn->response_info.status_code);
  3481. if (strlen(txt) == 3) {
  3482. memcpy(tls->txtbuf, txt, 4);
  3483. } else {
  3484. strcpy(tls->txtbuf, "ERR");
  3485. }
  3486. ((struct mg_connection *)conn)->request_info.local_uri =
  3487. ((struct mg_connection *)conn)->request_info.request_uri =
  3488. tls->txtbuf; /* use thread safe buffer */
  3489. ((struct mg_connection *)conn)->request_info.num_headers =
  3490. conn->response_info.num_headers;
  3491. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3492. conn->response_info.http_headers,
  3493. sizeof(conn->response_info.http_headers));
  3494. } else
  3495. #endif
  3496. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3497. return NULL;
  3498. }
  3499. return &conn->request_info;
  3500. }
  3501. const struct mg_response_info *
  3502. mg_get_response_info(const struct mg_connection *conn)
  3503. {
  3504. if (!conn) {
  3505. return NULL;
  3506. }
  3507. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3508. return NULL;
  3509. }
  3510. return &conn->response_info;
  3511. }
  3512. static const char *
  3513. get_proto_name(const struct mg_connection *conn)
  3514. {
  3515. #if defined(__clang__)
  3516. #pragma clang diagnostic push
  3517. #pragma clang diagnostic ignored "-Wunreachable-code"
  3518. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3519. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3520. * unreachable, but splitting into four different #ifdef clauses here is more
  3521. * complicated.
  3522. */
  3523. #endif
  3524. const struct mg_request_info *ri = &conn->request_info;
  3525. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3526. ? (ri->is_ssl ? "wss" : "ws")
  3527. : (ri->is_ssl ? "https" : "http"));
  3528. return proto;
  3529. #if defined(__clang__)
  3530. #pragma clang diagnostic pop
  3531. #endif
  3532. }
  3533. int
  3534. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3535. {
  3536. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3537. return -1;
  3538. } else {
  3539. int truncated = 0;
  3540. const struct mg_request_info *ri = &conn->request_info;
  3541. const char *proto = get_proto_name(conn);
  3542. if (ri->local_uri == NULL) {
  3543. return -1;
  3544. }
  3545. if ((ri->request_uri != NULL)
  3546. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3547. /* The request uri is different from the local uri.
  3548. * This is usually if an absolute URI, including server
  3549. * name has been provided. */
  3550. mg_snprintf(conn,
  3551. &truncated,
  3552. buf,
  3553. buflen,
  3554. "%s://%s",
  3555. proto,
  3556. ri->request_uri);
  3557. if (truncated) {
  3558. return -1;
  3559. }
  3560. return 0;
  3561. } else {
  3562. /* The common case is a relative URI, so we have to
  3563. * construct an absolute URI from server name and port */
  3564. #if defined(USE_IPV6)
  3565. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3566. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3567. : htons(conn->client.lsa.sin.sin_port);
  3568. #else
  3569. int port = htons(conn->client.lsa.sin.sin_port);
  3570. #endif
  3571. int def_port = ri->is_ssl ? 443 : 80;
  3572. int auth_domain_check_enabled =
  3573. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3574. && (!mg_strcasecmp(
  3575. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3576. const char *server_domain =
  3577. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3578. char portstr[16];
  3579. char server_ip[48];
  3580. if (port != def_port) {
  3581. sprintf(portstr, ":%u", (unsigned)port);
  3582. } else {
  3583. portstr[0] = 0;
  3584. }
  3585. if (!auth_domain_check_enabled || !server_domain) {
  3586. sockaddr_to_string(server_ip,
  3587. sizeof(server_ip),
  3588. &conn->client.lsa);
  3589. server_domain = server_ip;
  3590. }
  3591. mg_snprintf(conn,
  3592. &truncated,
  3593. buf,
  3594. buflen,
  3595. "%s://%s%s%s",
  3596. proto,
  3597. server_domain,
  3598. portstr,
  3599. ri->local_uri);
  3600. if (truncated) {
  3601. return -1;
  3602. }
  3603. return 0;
  3604. }
  3605. }
  3606. }
  3607. /* Skip the characters until one of the delimiters characters found.
  3608. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3609. * Advance pointer to buffer to the next word. Return found 0-terminated
  3610. * word.
  3611. * Delimiters can be quoted with quotechar. */
  3612. static char *
  3613. skip_quoted(char **buf,
  3614. const char *delimiters,
  3615. const char *whitespace,
  3616. char quotechar)
  3617. {
  3618. char *p, *begin_word, *end_word, *end_whitespace;
  3619. begin_word = *buf;
  3620. end_word = begin_word + strcspn(begin_word, delimiters);
  3621. /* Check for quotechar */
  3622. if (end_word > begin_word) {
  3623. p = end_word - 1;
  3624. while (*p == quotechar) {
  3625. /* While the delimiter is quoted, look for the next delimiter.
  3626. */
  3627. /* This happens, e.g., in calls from parse_auth_header,
  3628. * if the user name contains a " character. */
  3629. /* If there is anything beyond end_word, copy it. */
  3630. if (*end_word != '\0') {
  3631. size_t end_off = strcspn(end_word + 1, delimiters);
  3632. memmove(p, end_word, end_off + 1);
  3633. p += end_off; /* p must correspond to end_word - 1 */
  3634. end_word += end_off + 1;
  3635. } else {
  3636. *p = '\0';
  3637. break;
  3638. }
  3639. }
  3640. for (p++; p < end_word; p++) {
  3641. *p = '\0';
  3642. }
  3643. }
  3644. if (*end_word == '\0') {
  3645. *buf = end_word;
  3646. } else {
  3647. #if defined(GCC_DIAGNOSTIC)
  3648. /* Disable spurious conversion warning for GCC */
  3649. #pragma GCC diagnostic push
  3650. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3651. #endif /* defined(GCC_DIAGNOSTIC) */
  3652. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3653. #if defined(GCC_DIAGNOSTIC)
  3654. #pragma GCC diagnostic pop
  3655. #endif /* defined(GCC_DIAGNOSTIC) */
  3656. for (p = end_word; p < end_whitespace; p++) {
  3657. *p = '\0';
  3658. }
  3659. *buf = end_whitespace;
  3660. }
  3661. return begin_word;
  3662. }
  3663. /* Return HTTP header value, or NULL if not found. */
  3664. static const char *
  3665. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3666. {
  3667. int i;
  3668. for (i = 0; i < num_hdr; i++) {
  3669. if (!mg_strcasecmp(name, hdr[i].name)) {
  3670. return hdr[i].value;
  3671. }
  3672. }
  3673. return NULL;
  3674. }
  3675. #if defined(USE_WEBSOCKET)
  3676. /* Retrieve requested HTTP header multiple values, and return the number of
  3677. * found occurrences */
  3678. static int
  3679. get_req_headers(const struct mg_request_info *ri,
  3680. const char *name,
  3681. const char **output,
  3682. int output_max_size)
  3683. {
  3684. int i;
  3685. int cnt = 0;
  3686. if (ri) {
  3687. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3688. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3689. output[cnt++] = ri->http_headers[i].value;
  3690. }
  3691. }
  3692. }
  3693. return cnt;
  3694. }
  3695. #endif
  3696. const char *
  3697. mg_get_header(const struct mg_connection *conn, const char *name)
  3698. {
  3699. if (!conn) {
  3700. return NULL;
  3701. }
  3702. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3703. return get_header(conn->request_info.http_headers,
  3704. conn->request_info.num_headers,
  3705. name);
  3706. }
  3707. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3708. return get_header(conn->response_info.http_headers,
  3709. conn->response_info.num_headers,
  3710. name);
  3711. }
  3712. return NULL;
  3713. }
  3714. static const char *
  3715. get_http_version(const struct mg_connection *conn)
  3716. {
  3717. if (!conn) {
  3718. return NULL;
  3719. }
  3720. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3721. return conn->request_info.http_version;
  3722. }
  3723. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3724. return conn->response_info.http_version;
  3725. }
  3726. return NULL;
  3727. }
  3728. /* A helper function for traversing a comma separated list of values.
  3729. * It returns a list pointer shifted to the next value, or NULL if the end
  3730. * of the list found.
  3731. * Value is stored in val vector. If value has form "x=y", then eq_val
  3732. * vector is initialized to point to the "y" part, and val vector length
  3733. * is adjusted to point only to "x". */
  3734. static const char *
  3735. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3736. {
  3737. int end;
  3738. reparse:
  3739. if (val == NULL || list == NULL || *list == '\0') {
  3740. /* End of the list */
  3741. return NULL;
  3742. }
  3743. /* Skip over leading LWS */
  3744. while (*list == ' ' || *list == '\t')
  3745. list++;
  3746. val->ptr = list;
  3747. if ((list = strchr(val->ptr, ',')) != NULL) {
  3748. /* Comma found. Store length and shift the list ptr */
  3749. val->len = ((size_t)(list - val->ptr));
  3750. list++;
  3751. } else {
  3752. /* This value is the last one */
  3753. list = val->ptr + strlen(val->ptr);
  3754. val->len = ((size_t)(list - val->ptr));
  3755. }
  3756. /* Adjust length for trailing LWS */
  3757. end = (int)val->len - 1;
  3758. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3759. end--;
  3760. val->len = (size_t)(end) + (size_t)(1);
  3761. if (val->len == 0) {
  3762. /* Ignore any empty entries. */
  3763. goto reparse;
  3764. }
  3765. if (eq_val != NULL) {
  3766. /* Value has form "x=y", adjust pointers and lengths
  3767. * so that val points to "x", and eq_val points to "y". */
  3768. eq_val->len = 0;
  3769. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3770. if (eq_val->ptr != NULL) {
  3771. eq_val->ptr++; /* Skip over '=' character */
  3772. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3773. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3774. }
  3775. }
  3776. return list;
  3777. }
  3778. /* A helper function for checking if a comma separated list of values
  3779. * contains
  3780. * the given option (case insensitvely).
  3781. * 'header' can be NULL, in which case false is returned. */
  3782. static int
  3783. header_has_option(const char *header, const char *option)
  3784. {
  3785. struct vec opt_vec;
  3786. struct vec eq_vec;
  3787. DEBUG_ASSERT(option != NULL);
  3788. DEBUG_ASSERT(option[0] != '\0');
  3789. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3790. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3791. return 1;
  3792. }
  3793. return 0;
  3794. }
  3795. /* Perform case-insensitive match of string against pattern */
  3796. static ptrdiff_t
  3797. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3798. {
  3799. const char *or_str;
  3800. ptrdiff_t i, j, len, res;
  3801. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3802. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3803. return (res > 0) ? res
  3804. : match_prefix(or_str + 1,
  3805. (size_t)((pattern + pattern_len)
  3806. - (or_str + 1)),
  3807. str);
  3808. }
  3809. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3810. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3811. continue;
  3812. } else if (pattern[i] == '$') {
  3813. return (str[j] == '\0') ? j : -1;
  3814. } else if (pattern[i] == '*') {
  3815. i++;
  3816. if (pattern[i] == '*') {
  3817. i++;
  3818. len = (ptrdiff_t)strlen(str + j);
  3819. } else {
  3820. len = (ptrdiff_t)strcspn(str + j, "/");
  3821. }
  3822. if (i == (ptrdiff_t)pattern_len) {
  3823. return j + len;
  3824. }
  3825. do {
  3826. res = match_prefix(pattern + i,
  3827. (pattern_len - (size_t)i),
  3828. str + j + len);
  3829. } while (res == -1 && len-- > 0);
  3830. return (res == -1) ? -1 : j + res + len;
  3831. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3832. return -1;
  3833. }
  3834. }
  3835. return (ptrdiff_t)j;
  3836. }
  3837. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3838. * This function must tolerate situations when connection info is not
  3839. * set up, for example if request parsing failed. */
  3840. static int
  3841. should_keep_alive(const struct mg_connection *conn)
  3842. {
  3843. const char *http_version;
  3844. const char *header;
  3845. /* First satisfy needs of the server */
  3846. if ((conn == NULL) || conn->must_close) {
  3847. /* Close, if civetweb framework needs to close */
  3848. return 0;
  3849. }
  3850. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3851. /* Close, if keep alive is not enabled */
  3852. return 0;
  3853. }
  3854. /* Check explicit wish of the client */
  3855. header = mg_get_header(conn, "Connection");
  3856. if (header) {
  3857. /* If there is a connection header from the client, obey */
  3858. if (header_has_option(header, "keep-alive")) {
  3859. return 1;
  3860. }
  3861. return 0;
  3862. }
  3863. /* Use default of the standard */
  3864. http_version = get_http_version(conn);
  3865. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3866. /* HTTP 1.1 default is keep alive */
  3867. return 1;
  3868. }
  3869. /* HTTP 1.0 (and earlier) default is to close the connection */
  3870. return 0;
  3871. }
  3872. static int
  3873. should_decode_url(const struct mg_connection *conn)
  3874. {
  3875. if (!conn || !conn->dom_ctx) {
  3876. return 0;
  3877. }
  3878. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3879. }
  3880. static const char *
  3881. suggest_connection_header(const struct mg_connection *conn)
  3882. {
  3883. return should_keep_alive(conn) ? "keep-alive" : "close";
  3884. }
  3885. #include "response.inl"
  3886. static void
  3887. send_no_cache_header(struct mg_connection *conn)
  3888. {
  3889. /* Send all current and obsolete cache opt-out directives. */
  3890. mg_response_add_header(conn,
  3891. "Cache-Control",
  3892. "no-cache, no-store, "
  3893. "must-revalidate, private, max-age=0",
  3894. -1);
  3895. mg_response_add_header(conn, "Expires", "0", -1);
  3896. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3897. /* Obsolete, but still send it for HTTP/1.0 */
  3898. mg_response_add_header(conn, "Pragma", "no-cache", -1);
  3899. }
  3900. }
  3901. static void
  3902. send_static_cache_header(struct mg_connection *conn)
  3903. {
  3904. #if !defined(NO_CACHING)
  3905. int max_age;
  3906. char val[64];
  3907. const char *cache_control =
  3908. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3909. /* If there is a full cache-control option configured,0 use it */
  3910. if (cache_control != NULL) {
  3911. mg_response_add_header(conn, "Cache-Control", cache_control, -1);
  3912. return;
  3913. }
  3914. /* Read the server config to check how long a file may be cached.
  3915. * The configuration is in seconds. */
  3916. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3917. if (max_age <= 0) {
  3918. /* 0 means "do not cache". All values <0 are reserved
  3919. * and may be used differently in the future. */
  3920. /* If a file should not be cached, do not only send
  3921. * max-age=0, but also pragmas and Expires headers. */
  3922. send_no_cache_header(conn);
  3923. return;
  3924. }
  3925. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3926. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3927. /* See also https://www.mnot.net/cache_docs/ */
  3928. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3929. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3930. * leap
  3931. * year to 31622400 seconds. For the moment, we just send whatever has
  3932. * been configured, still the behavior for >1 year should be considered
  3933. * as undefined. */
  3934. mg_snprintf(
  3935. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3936. mg_response_add_header(conn, "Cache-Control", val, -1);
  3937. #else /* NO_CACHING */
  3938. send_no_cache_header(conn);
  3939. #endif /* !NO_CACHING */
  3940. }
  3941. static void
  3942. send_additional_header(struct mg_connection *conn)
  3943. {
  3944. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3945. #if !defined(NO_SSL)
  3946. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3947. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3948. if (max_age >= 0) {
  3949. char val[64];
  3950. mg_snprintf(conn,
  3951. NULL,
  3952. val,
  3953. sizeof(val),
  3954. "max-age=%lu",
  3955. (unsigned long)max_age);
  3956. mg_response_add_header(conn, "Strict-Transport-Security", val, -1);
  3957. }
  3958. }
  3959. #endif
  3960. if (header && header[0]) {
  3961. mg_response_add_headerlines(conn, header);
  3962. }
  3963. }
  3964. #if !defined(NO_FILESYSTEMS)
  3965. static void handle_file_based_request(struct mg_connection *conn,
  3966. const char *path,
  3967. struct mg_file *filep);
  3968. #endif /* NO_FILESYSTEMS */
  3969. const char *
  3970. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3971. {
  3972. /* See IANA HTTP status code assignment:
  3973. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3974. */
  3975. switch (response_code) {
  3976. /* RFC2616 Section 10.1 - Informational 1xx */
  3977. case 100:
  3978. return "Continue"; /* RFC2616 Section 10.1.1 */
  3979. case 101:
  3980. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3981. case 102:
  3982. return "Processing"; /* RFC2518 Section 10.1 */
  3983. /* RFC2616 Section 10.2 - Successful 2xx */
  3984. case 200:
  3985. return "OK"; /* RFC2616 Section 10.2.1 */
  3986. case 201:
  3987. return "Created"; /* RFC2616 Section 10.2.2 */
  3988. case 202:
  3989. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3990. case 203:
  3991. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3992. case 204:
  3993. return "No Content"; /* RFC2616 Section 10.2.5 */
  3994. case 205:
  3995. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3996. case 206:
  3997. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3998. case 207:
  3999. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  4000. */
  4001. case 208:
  4002. return "Already Reported"; /* RFC5842 Section 7.1 */
  4003. case 226:
  4004. return "IM used"; /* RFC3229 Section 10.4.1 */
  4005. /* RFC2616 Section 10.3 - Redirection 3xx */
  4006. case 300:
  4007. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  4008. case 301:
  4009. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  4010. case 302:
  4011. return "Found"; /* RFC2616 Section 10.3.3 */
  4012. case 303:
  4013. return "See Other"; /* RFC2616 Section 10.3.4 */
  4014. case 304:
  4015. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  4016. case 305:
  4017. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  4018. case 307:
  4019. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  4020. case 308:
  4021. return "Permanent Redirect"; /* RFC7238 Section 3 */
  4022. /* RFC2616 Section 10.4 - Client Error 4xx */
  4023. case 400:
  4024. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  4025. case 401:
  4026. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  4027. case 402:
  4028. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  4029. case 403:
  4030. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  4031. case 404:
  4032. return "Not Found"; /* RFC2616 Section 10.4.5 */
  4033. case 405:
  4034. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  4035. case 406:
  4036. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  4037. case 407:
  4038. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  4039. case 408:
  4040. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  4041. case 409:
  4042. return "Conflict"; /* RFC2616 Section 10.4.10 */
  4043. case 410:
  4044. return "Gone"; /* RFC2616 Section 10.4.11 */
  4045. case 411:
  4046. return "Length Required"; /* RFC2616 Section 10.4.12 */
  4047. case 412:
  4048. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  4049. case 413:
  4050. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  4051. case 414:
  4052. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  4053. case 415:
  4054. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  4055. case 416:
  4056. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  4057. */
  4058. case 417:
  4059. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  4060. case 421:
  4061. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  4062. case 422:
  4063. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  4064. * Section 11.2 */
  4065. case 423:
  4066. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  4067. case 424:
  4068. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  4069. * Section 11.4 */
  4070. case 426:
  4071. return "Upgrade Required"; /* RFC 2817 Section 4 */
  4072. case 428:
  4073. return "Precondition Required"; /* RFC 6585, Section 3 */
  4074. case 429:
  4075. return "Too Many Requests"; /* RFC 6585, Section 4 */
  4076. case 431:
  4077. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  4078. case 451:
  4079. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  4080. * Section 3 */
  4081. /* RFC2616 Section 10.5 - Server Error 5xx */
  4082. case 500:
  4083. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  4084. case 501:
  4085. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  4086. case 502:
  4087. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4088. case 503:
  4089. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4090. case 504:
  4091. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4092. case 505:
  4093. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4094. case 506:
  4095. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4096. case 507:
  4097. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4098. * Section 11.5 */
  4099. case 508:
  4100. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4101. case 510:
  4102. return "Not Extended"; /* RFC 2774, Section 7 */
  4103. case 511:
  4104. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4105. /* Other status codes, not shown in the IANA HTTP status code
  4106. * assignment.
  4107. * E.g., "de facto" standards due to common use, ... */
  4108. case 418:
  4109. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4110. case 419:
  4111. return "Authentication Timeout"; /* common use */
  4112. case 420:
  4113. return "Enhance Your Calm"; /* common use */
  4114. case 440:
  4115. return "Login Timeout"; /* common use */
  4116. case 509:
  4117. return "Bandwidth Limit Exceeded"; /* common use */
  4118. default:
  4119. /* This error code is unknown. This should not happen. */
  4120. if (conn) {
  4121. mg_cry_internal(conn,
  4122. "Unknown HTTP response code: %u",
  4123. response_code);
  4124. }
  4125. /* Return at least a category according to RFC 2616 Section 10. */
  4126. if (response_code >= 100 && response_code < 200) {
  4127. /* Unknown informational status code */
  4128. return "Information";
  4129. }
  4130. if (response_code >= 200 && response_code < 300) {
  4131. /* Unknown success code */
  4132. return "Success";
  4133. }
  4134. if (response_code >= 300 && response_code < 400) {
  4135. /* Unknown redirection code */
  4136. return "Redirection";
  4137. }
  4138. if (response_code >= 400 && response_code < 500) {
  4139. /* Unknown request error code */
  4140. return "Client Error";
  4141. }
  4142. if (response_code >= 500 && response_code < 600) {
  4143. /* Unknown server error code */
  4144. return "Server Error";
  4145. }
  4146. /* Response code not even within reasonable range */
  4147. return "";
  4148. }
  4149. }
  4150. static int
  4151. mg_send_http_error_impl(struct mg_connection *conn,
  4152. int status,
  4153. const char *fmt,
  4154. va_list args)
  4155. {
  4156. char errmsg_buf[MG_BUF_LEN];
  4157. va_list ap;
  4158. int has_body;
  4159. #if !defined(NO_FILESYSTEMS)
  4160. char path_buf[PATH_MAX];
  4161. int len, i, page_handler_found, scope, truncated;
  4162. const char *error_handler = NULL;
  4163. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4164. const char *error_page_file_ext, *tstr;
  4165. #endif /* NO_FILESYSTEMS */
  4166. int handled_by_callback = 0;
  4167. if ((conn == NULL) || (fmt == NULL)) {
  4168. return -2;
  4169. }
  4170. /* Set status (for log) */
  4171. conn->status_code = status;
  4172. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4173. has_body = ((status > 199) && (status != 204) && (status != 304));
  4174. /* Prepare message in buf, if required */
  4175. if (has_body
  4176. || (!conn->in_error_handler
  4177. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4178. /* Store error message in errmsg_buf */
  4179. va_copy(ap, args);
  4180. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4181. va_end(ap);
  4182. /* In a debug build, print all html errors */
  4183. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4184. }
  4185. /* If there is a http_error callback, call it.
  4186. * But don't do it recursively, if callback calls mg_send_http_error again.
  4187. */
  4188. if (!conn->in_error_handler
  4189. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4190. /* Mark in_error_handler to avoid recursion and call user callback. */
  4191. conn->in_error_handler = 1;
  4192. handled_by_callback =
  4193. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4194. == 0);
  4195. conn->in_error_handler = 0;
  4196. }
  4197. if (!handled_by_callback) {
  4198. /* Check for recursion */
  4199. if (conn->in_error_handler) {
  4200. DEBUG_TRACE(
  4201. "Recursion when handling error %u - fall back to default",
  4202. status);
  4203. #if !defined(NO_FILESYSTEMS)
  4204. } else {
  4205. /* Send user defined error pages, if defined */
  4206. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4207. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4208. page_handler_found = 0;
  4209. if (error_handler != NULL) {
  4210. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4211. switch (scope) {
  4212. case 1: /* Handler for specific error, e.g. 404 error */
  4213. mg_snprintf(conn,
  4214. &truncated,
  4215. path_buf,
  4216. sizeof(path_buf) - 32,
  4217. "%serror%03u.",
  4218. error_handler,
  4219. status);
  4220. break;
  4221. case 2: /* Handler for error group, e.g., 5xx error
  4222. * handler
  4223. * for all server errors (500-599) */
  4224. mg_snprintf(conn,
  4225. &truncated,
  4226. path_buf,
  4227. sizeof(path_buf) - 32,
  4228. "%serror%01uxx.",
  4229. error_handler,
  4230. status / 100);
  4231. break;
  4232. default: /* Handler for all errors */
  4233. mg_snprintf(conn,
  4234. &truncated,
  4235. path_buf,
  4236. sizeof(path_buf) - 32,
  4237. "%serror.",
  4238. error_handler);
  4239. break;
  4240. }
  4241. /* String truncation in buf may only occur if
  4242. * error_handler is too long. This string is
  4243. * from the config, not from a client. */
  4244. (void)truncated;
  4245. /* The following code is redundant, but it should avoid
  4246. * false positives in static source code analyzers and
  4247. * vulnerability scanners.
  4248. */
  4249. path_buf[sizeof(path_buf) - 32] = 0;
  4250. len = (int)strlen(path_buf);
  4251. if (len > (int)sizeof(path_buf) - 32) {
  4252. len = (int)sizeof(path_buf) - 32;
  4253. }
  4254. /* Start with the file extenstion from the configuration. */
  4255. tstr = strchr(error_page_file_ext, '.');
  4256. while (tstr) {
  4257. for (i = 1;
  4258. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4259. i++) {
  4260. /* buffer overrun is not possible here, since
  4261. * (i < 32) && (len < sizeof(path_buf) - 32)
  4262. * ==> (i + len) < sizeof(path_buf) */
  4263. path_buf[len + i - 1] = tstr[i];
  4264. }
  4265. /* buffer overrun is not possible here, since
  4266. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4267. * ==> (i + len) <= sizeof(path_buf) */
  4268. path_buf[len + i - 1] = 0;
  4269. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4270. DEBUG_TRACE("Check error page %s - found",
  4271. path_buf);
  4272. page_handler_found = 1;
  4273. break;
  4274. }
  4275. DEBUG_TRACE("Check error page %s - not found",
  4276. path_buf);
  4277. /* Continue with the next file extenstion from the
  4278. * configuration (if there is a next one). */
  4279. tstr = strchr(tstr + i, '.');
  4280. }
  4281. }
  4282. }
  4283. if (page_handler_found) {
  4284. conn->in_error_handler = 1;
  4285. handle_file_based_request(conn, path_buf, &error_page_file);
  4286. conn->in_error_handler = 0;
  4287. return 0;
  4288. }
  4289. #endif /* NO_FILESYSTEMS */
  4290. }
  4291. /* No custom error page. Send default error page. */
  4292. conn->must_close = 1;
  4293. mg_response_start(conn, status);
  4294. send_no_cache_header(conn);
  4295. send_additional_header(conn);
  4296. if (has_body) {
  4297. mg_response_add_header(conn,
  4298. "Content-Type",
  4299. "text/plain; charset=utf-8",
  4300. -1);
  4301. }
  4302. mg_response_send_headers(conn);
  4303. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4304. if (has_body) {
  4305. /* For other errors, send a generic error message. */
  4306. const char *status_text = mg_get_response_code_text(conn, status);
  4307. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4308. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4309. } else {
  4310. /* No body allowed. Close the connection. */
  4311. DEBUG_TRACE("Error %i", status);
  4312. }
  4313. }
  4314. return 0;
  4315. }
  4316. int
  4317. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4318. {
  4319. va_list ap;
  4320. int ret;
  4321. va_start(ap, fmt);
  4322. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4323. va_end(ap);
  4324. return ret;
  4325. }
  4326. int
  4327. mg_send_http_ok(struct mg_connection *conn,
  4328. const char *mime_type,
  4329. long long content_length)
  4330. {
  4331. if ((mime_type == NULL) || (*mime_type == 0)) {
  4332. /* No content type defined: default to text/html */
  4333. mime_type = "text/html";
  4334. }
  4335. mg_response_start(conn, 200);
  4336. send_no_cache_header(conn);
  4337. send_additional_header(conn);
  4338. mg_response_add_header(conn, "Content-Type", mime_type, -1);
  4339. if (content_length < 0) {
  4340. /* Size not known. Use chunked encoding (HTTP/1.x) */
  4341. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  4342. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  4343. mg_response_add_header(conn, "Transfer-Encoding", "chunked", -1);
  4344. }
  4345. } else {
  4346. char len[32];
  4347. int trunc = 0;
  4348. mg_snprintf(conn,
  4349. &trunc,
  4350. len,
  4351. sizeof(len),
  4352. "%" UINT64_FMT,
  4353. (uint64_t)content_length);
  4354. if (!trunc) {
  4355. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  4356. * !trunc is always true */
  4357. mg_response_add_header(conn, "Content-Length", len, -1);
  4358. }
  4359. }
  4360. mg_response_send_headers(conn);
  4361. return 0;
  4362. }
  4363. int
  4364. mg_send_http_redirect(struct mg_connection *conn,
  4365. const char *target_url,
  4366. int redirect_code)
  4367. {
  4368. /* Send a 30x redirect response.
  4369. *
  4370. * Redirect types (status codes):
  4371. *
  4372. * Status | Perm/Temp | Method | Version
  4373. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4374. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4375. * 303 | temporary | always use GET | HTTP/1.1
  4376. * 307 | temporary | always keep method | HTTP/1.1
  4377. * 308 | permanent | always keep method | HTTP/1.1
  4378. */
  4379. const char *redirect_text;
  4380. int ret;
  4381. size_t content_len = 0;
  4382. char reply[MG_BUF_LEN];
  4383. /* In case redirect_code=0, use 307. */
  4384. if (redirect_code == 0) {
  4385. redirect_code = 307;
  4386. }
  4387. /* In case redirect_code is none of the above, return error. */
  4388. if ((redirect_code != 301) && (redirect_code != 302)
  4389. && (redirect_code != 303) && (redirect_code != 307)
  4390. && (redirect_code != 308)) {
  4391. /* Parameter error */
  4392. return -2;
  4393. }
  4394. /* Get proper text for response code */
  4395. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4396. /* If target_url is not defined, redirect to "/". */
  4397. if ((target_url == NULL) || (*target_url == 0)) {
  4398. target_url = "/";
  4399. }
  4400. #if defined(MG_SEND_REDIRECT_BODY)
  4401. /* TODO: condition name? */
  4402. /* Prepare a response body with a hyperlink.
  4403. *
  4404. * According to RFC2616 (and RFC1945 before):
  4405. * Unless the request method was HEAD, the entity of the
  4406. * response SHOULD contain a short hypertext note with a hyperlink to
  4407. * the new URI(s).
  4408. *
  4409. * However, this response body is not useful in M2M communication.
  4410. * Probably the original reason in the RFC was, clients not supporting
  4411. * a 30x HTTP redirect could still show the HTML page and let the user
  4412. * press the link. Since current browsers support 30x HTTP, the additional
  4413. * HTML body does not seem to make sense anymore.
  4414. *
  4415. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4416. * but it only notes:
  4417. * The server's response payload usually contains a short
  4418. * hypertext note with a hyperlink to the new URI(s).
  4419. *
  4420. * Deactivated by default. If you need the 30x body, set the define.
  4421. */
  4422. mg_snprintf(
  4423. conn,
  4424. NULL /* ignore truncation */,
  4425. reply,
  4426. sizeof(reply),
  4427. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4428. redirect_text,
  4429. target_url,
  4430. target_url);
  4431. content_len = strlen(reply);
  4432. #else
  4433. reply[0] = 0;
  4434. #endif
  4435. /* Do not send any additional header. For all other options,
  4436. * including caching, there are suitable defaults. */
  4437. ret = mg_printf(conn,
  4438. "HTTP/1.1 %i %s\r\n"
  4439. "Location: %s\r\n"
  4440. "Content-Length: %u\r\n"
  4441. "Connection: %s\r\n\r\n",
  4442. redirect_code,
  4443. redirect_text,
  4444. target_url,
  4445. (unsigned int)content_len,
  4446. suggest_connection_header(conn));
  4447. /* Send response body */
  4448. if (ret > 0) {
  4449. /* ... unless it is a HEAD request */
  4450. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4451. ret = mg_write(conn, reply, content_len);
  4452. }
  4453. }
  4454. return (ret > 0) ? ret : -1;
  4455. }
  4456. #if defined(_WIN32)
  4457. /* Create substitutes for POSIX functions in Win32. */
  4458. #if defined(GCC_DIAGNOSTIC)
  4459. /* Show no warning in case system functions are not used. */
  4460. #pragma GCC diagnostic push
  4461. #pragma GCC diagnostic ignored "-Wunused-function"
  4462. #endif
  4463. static int
  4464. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4465. {
  4466. (void)unused;
  4467. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4468. InitializeCriticalSection(&mutex->sec);
  4469. return 0;
  4470. }
  4471. static int
  4472. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4473. {
  4474. DeleteCriticalSection(&mutex->sec);
  4475. return 0;
  4476. }
  4477. static int
  4478. pthread_mutex_lock(pthread_mutex_t *mutex)
  4479. {
  4480. EnterCriticalSection(&mutex->sec);
  4481. return 0;
  4482. }
  4483. static int
  4484. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4485. {
  4486. LeaveCriticalSection(&mutex->sec);
  4487. return 0;
  4488. }
  4489. FUNCTION_MAY_BE_UNUSED
  4490. static int
  4491. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4492. {
  4493. (void)unused;
  4494. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4495. cv->waiting_thread = NULL;
  4496. return 0;
  4497. }
  4498. FUNCTION_MAY_BE_UNUSED
  4499. static int
  4500. pthread_cond_timedwait(pthread_cond_t *cv,
  4501. pthread_mutex_t *mutex,
  4502. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4503. {
  4504. struct mg_workerTLS **ptls,
  4505. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4506. int ok;
  4507. int64_t nsnow, nswaitabs, nswaitrel;
  4508. DWORD mswaitrel;
  4509. pthread_mutex_lock(&cv->threadIdSec);
  4510. /* Add this thread to cv's waiting list */
  4511. ptls = &cv->waiting_thread;
  4512. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4513. ;
  4514. tls->next_waiting_thread = NULL;
  4515. *ptls = tls;
  4516. pthread_mutex_unlock(&cv->threadIdSec);
  4517. if (abstime) {
  4518. nsnow = mg_get_current_time_ns();
  4519. nswaitabs =
  4520. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4521. nswaitrel = nswaitabs - nsnow;
  4522. if (nswaitrel < 0) {
  4523. nswaitrel = 0;
  4524. }
  4525. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4526. } else {
  4527. mswaitrel = (DWORD)INFINITE;
  4528. }
  4529. pthread_mutex_unlock(mutex);
  4530. ok = (WAIT_OBJECT_0
  4531. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4532. if (!ok) {
  4533. ok = 1;
  4534. pthread_mutex_lock(&cv->threadIdSec);
  4535. ptls = &cv->waiting_thread;
  4536. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4537. if (*ptls == tls) {
  4538. *ptls = tls->next_waiting_thread;
  4539. ok = 0;
  4540. break;
  4541. }
  4542. }
  4543. pthread_mutex_unlock(&cv->threadIdSec);
  4544. if (ok) {
  4545. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4546. (DWORD)INFINITE);
  4547. }
  4548. }
  4549. /* This thread has been removed from cv's waiting list */
  4550. pthread_mutex_lock(mutex);
  4551. return ok ? 0 : -1;
  4552. }
  4553. FUNCTION_MAY_BE_UNUSED
  4554. static int
  4555. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4556. {
  4557. return pthread_cond_timedwait(cv, mutex, NULL);
  4558. }
  4559. FUNCTION_MAY_BE_UNUSED
  4560. static int
  4561. pthread_cond_signal(pthread_cond_t *cv)
  4562. {
  4563. HANDLE wkup = NULL;
  4564. BOOL ok = FALSE;
  4565. pthread_mutex_lock(&cv->threadIdSec);
  4566. if (cv->waiting_thread) {
  4567. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4568. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4569. ok = SetEvent(wkup);
  4570. DEBUG_ASSERT(ok);
  4571. }
  4572. pthread_mutex_unlock(&cv->threadIdSec);
  4573. return ok ? 0 : 1;
  4574. }
  4575. FUNCTION_MAY_BE_UNUSED
  4576. static int
  4577. pthread_cond_broadcast(pthread_cond_t *cv)
  4578. {
  4579. pthread_mutex_lock(&cv->threadIdSec);
  4580. while (cv->waiting_thread) {
  4581. pthread_cond_signal(cv);
  4582. }
  4583. pthread_mutex_unlock(&cv->threadIdSec);
  4584. return 0;
  4585. }
  4586. FUNCTION_MAY_BE_UNUSED
  4587. static int
  4588. pthread_cond_destroy(pthread_cond_t *cv)
  4589. {
  4590. pthread_mutex_lock(&cv->threadIdSec);
  4591. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4592. pthread_mutex_unlock(&cv->threadIdSec);
  4593. pthread_mutex_destroy(&cv->threadIdSec);
  4594. return 0;
  4595. }
  4596. #if defined(ALTERNATIVE_QUEUE)
  4597. FUNCTION_MAY_BE_UNUSED
  4598. static void *
  4599. event_create(void)
  4600. {
  4601. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4602. }
  4603. FUNCTION_MAY_BE_UNUSED
  4604. static int
  4605. event_wait(void *eventhdl)
  4606. {
  4607. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4608. return (res == WAIT_OBJECT_0);
  4609. }
  4610. FUNCTION_MAY_BE_UNUSED
  4611. static int
  4612. event_signal(void *eventhdl)
  4613. {
  4614. return (int)SetEvent((HANDLE)eventhdl);
  4615. }
  4616. FUNCTION_MAY_BE_UNUSED
  4617. static void
  4618. event_destroy(void *eventhdl)
  4619. {
  4620. CloseHandle((HANDLE)eventhdl);
  4621. }
  4622. #endif
  4623. #if defined(GCC_DIAGNOSTIC)
  4624. /* Enable unused function warning again */
  4625. #pragma GCC diagnostic pop
  4626. #endif
  4627. /* For Windows, change all slashes to backslashes in path names. */
  4628. static void
  4629. change_slashes_to_backslashes(char *path)
  4630. {
  4631. int i;
  4632. for (i = 0; path[i] != '\0'; i++) {
  4633. if (path[i] == '/') {
  4634. path[i] = '\\';
  4635. }
  4636. /* remove double backslash (check i > 0 to preserve UNC paths,
  4637. * like \\server\file.txt) */
  4638. if ((i > 0) && (path[i] == '\\')) {
  4639. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4640. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4641. }
  4642. }
  4643. }
  4644. }
  4645. static int
  4646. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4647. {
  4648. int diff;
  4649. do {
  4650. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4651. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4652. s1++;
  4653. s2++;
  4654. } while ((diff == 0) && (s1[-1] != L'\0'));
  4655. return diff;
  4656. }
  4657. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4658. * wbuf and wbuf_len is a target buffer and its length. */
  4659. static void
  4660. path_to_unicode(const struct mg_connection *conn,
  4661. const char *path,
  4662. wchar_t *wbuf,
  4663. size_t wbuf_len)
  4664. {
  4665. char buf[PATH_MAX], buf2[PATH_MAX];
  4666. wchar_t wbuf2[W_PATH_MAX + 1];
  4667. DWORD long_len, err;
  4668. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4669. mg_strlcpy(buf, path, sizeof(buf));
  4670. change_slashes_to_backslashes(buf);
  4671. /* Convert to Unicode and back. If doubly-converted string does not
  4672. * match the original, something is fishy, reject. */
  4673. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4674. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4675. WideCharToMultiByte(
  4676. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4677. if (strcmp(buf, buf2) != 0) {
  4678. wbuf[0] = L'\0';
  4679. }
  4680. /* Windows file systems are not case sensitive, but you can still use
  4681. * uppercase and lowercase letters (on all modern file systems).
  4682. * The server can check if the URI uses the same upper/lowercase
  4683. * letters an the file system, effectively making Windows servers
  4684. * case sensitive (like Linux servers are). It is still not possible
  4685. * to use two files with the same name in different cases on Windows
  4686. * (like /a and /A) - this would be possible in Linux.
  4687. * As a default, Windows is not case sensitive, but the case sensitive
  4688. * file name check can be activated by an additional configuration. */
  4689. if (conn) {
  4690. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4691. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4692. "yes")) {
  4693. /* Use case sensitive compare function */
  4694. fcompare = wcscmp;
  4695. }
  4696. }
  4697. (void)conn; /* conn is currently unused */
  4698. #if !defined(_WIN32_WCE)
  4699. /* Only accept a full file path, not a Windows short (8.3) path. */
  4700. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4701. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4702. if (long_len == 0) {
  4703. err = GetLastError();
  4704. if (err == ERROR_FILE_NOT_FOUND) {
  4705. /* File does not exist. This is not always a problem here. */
  4706. return;
  4707. }
  4708. }
  4709. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4710. /* Short name is used. */
  4711. wbuf[0] = L'\0';
  4712. }
  4713. #else
  4714. (void)long_len;
  4715. (void)wbuf2;
  4716. (void)err;
  4717. if (strchr(path, '~')) {
  4718. wbuf[0] = L'\0';
  4719. }
  4720. #endif
  4721. }
  4722. #if !defined(NO_FILESYSTEMS)
  4723. static int
  4724. mg_stat(const struct mg_connection *conn,
  4725. const char *path,
  4726. struct mg_file_stat *filep)
  4727. {
  4728. wchar_t wbuf[W_PATH_MAX];
  4729. WIN32_FILE_ATTRIBUTE_DATA info;
  4730. time_t creation_time;
  4731. size_t len;
  4732. if (!filep) {
  4733. return 0;
  4734. }
  4735. memset(filep, 0, sizeof(*filep));
  4736. if (conn && is_file_in_memory(conn, path)) {
  4737. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4738. * memset */
  4739. /* Quick fix (for 1.9.x): */
  4740. /* mg_stat must fill all fields, also for files in memory */
  4741. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4742. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4743. filep->size = tmp_file.stat.size;
  4744. filep->location = 2;
  4745. /* TODO: for 1.10: restructure how files in memory are handled */
  4746. /* The "file in memory" feature is a candidate for deletion.
  4747. * Please join the discussion at
  4748. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4749. */
  4750. filep->last_modified = time(NULL); /* TODO */
  4751. /* last_modified = now ... assumes the file may change during
  4752. * runtime,
  4753. * so every mg_fopen call may return different data */
  4754. /* last_modified = conn->phys_ctx.start_time;
  4755. * May be used it the data does not change during runtime. This
  4756. * allows
  4757. * browser caching. Since we do not know, we have to assume the file
  4758. * in memory may change. */
  4759. return 1;
  4760. }
  4761. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4762. /* Windows happily opens files with some garbage at the end of file name.
  4763. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4764. * "a.cgi", despite one would expect an error back. */
  4765. len = strlen(path);
  4766. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4767. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4768. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4769. filep->last_modified =
  4770. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4771. info.ftLastWriteTime.dwHighDateTime);
  4772. /* On Windows, the file creation time can be higher than the
  4773. * modification time, e.g. when a file is copied.
  4774. * Since the Last-Modified timestamp is used for caching
  4775. * it should be based on the most recent timestamp. */
  4776. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4777. info.ftCreationTime.dwHighDateTime);
  4778. if (creation_time > filep->last_modified) {
  4779. filep->last_modified = creation_time;
  4780. }
  4781. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4782. return 1;
  4783. }
  4784. return 0;
  4785. }
  4786. #endif
  4787. static int
  4788. mg_remove(const struct mg_connection *conn, const char *path)
  4789. {
  4790. wchar_t wbuf[W_PATH_MAX];
  4791. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4792. return DeleteFileW(wbuf) ? 0 : -1;
  4793. }
  4794. static int
  4795. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4796. {
  4797. wchar_t wbuf[W_PATH_MAX];
  4798. (void)mode;
  4799. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4800. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4801. }
  4802. /* Create substitutes for POSIX functions in Win32. */
  4803. #if defined(GCC_DIAGNOSTIC)
  4804. /* Show no warning in case system functions are not used. */
  4805. #pragma GCC diagnostic push
  4806. #pragma GCC diagnostic ignored "-Wunused-function"
  4807. #endif
  4808. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4809. FUNCTION_MAY_BE_UNUSED
  4810. static DIR *
  4811. mg_opendir(const struct mg_connection *conn, const char *name)
  4812. {
  4813. DIR *dir = NULL;
  4814. wchar_t wpath[W_PATH_MAX];
  4815. DWORD attrs;
  4816. if (name == NULL) {
  4817. SetLastError(ERROR_BAD_ARGUMENTS);
  4818. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4819. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4820. } else {
  4821. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4822. attrs = GetFileAttributesW(wpath);
  4823. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4824. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4825. (void)wcscat(wpath, L"\\*");
  4826. dir->handle = FindFirstFileW(wpath, &dir->info);
  4827. dir->result.d_name[0] = '\0';
  4828. } else {
  4829. mg_free(dir);
  4830. dir = NULL;
  4831. }
  4832. }
  4833. return dir;
  4834. }
  4835. FUNCTION_MAY_BE_UNUSED
  4836. static int
  4837. mg_closedir(DIR *dir)
  4838. {
  4839. int result = 0;
  4840. if (dir != NULL) {
  4841. if (dir->handle != INVALID_HANDLE_VALUE)
  4842. result = FindClose(dir->handle) ? 0 : -1;
  4843. mg_free(dir);
  4844. } else {
  4845. result = -1;
  4846. SetLastError(ERROR_BAD_ARGUMENTS);
  4847. }
  4848. return result;
  4849. }
  4850. FUNCTION_MAY_BE_UNUSED
  4851. static struct dirent *
  4852. mg_readdir(DIR *dir)
  4853. {
  4854. struct dirent *result = 0;
  4855. if (dir) {
  4856. if (dir->handle != INVALID_HANDLE_VALUE) {
  4857. result = &dir->result;
  4858. (void)WideCharToMultiByte(CP_UTF8,
  4859. 0,
  4860. dir->info.cFileName,
  4861. -1,
  4862. result->d_name,
  4863. sizeof(result->d_name),
  4864. NULL,
  4865. NULL);
  4866. if (!FindNextFileW(dir->handle, &dir->info)) {
  4867. (void)FindClose(dir->handle);
  4868. dir->handle = INVALID_HANDLE_VALUE;
  4869. }
  4870. } else {
  4871. SetLastError(ERROR_FILE_NOT_FOUND);
  4872. }
  4873. } else {
  4874. SetLastError(ERROR_BAD_ARGUMENTS);
  4875. }
  4876. return result;
  4877. }
  4878. #if !defined(HAVE_POLL)
  4879. #undef POLLIN
  4880. #undef POLLPRI
  4881. #undef POLLOUT
  4882. #define POLLIN (1) /* Data ready - read will not block. */
  4883. #define POLLPRI (2) /* Priority data ready. */
  4884. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4885. FUNCTION_MAY_BE_UNUSED
  4886. static int
  4887. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4888. {
  4889. struct timeval tv;
  4890. fd_set rset;
  4891. fd_set wset;
  4892. unsigned int i;
  4893. int result;
  4894. SOCKET maxfd = 0;
  4895. memset(&tv, 0, sizeof(tv));
  4896. tv.tv_sec = milliseconds / 1000;
  4897. tv.tv_usec = (milliseconds % 1000) * 1000;
  4898. FD_ZERO(&rset);
  4899. FD_ZERO(&wset);
  4900. for (i = 0; i < n; i++) {
  4901. if (pfd[i].events & POLLIN) {
  4902. FD_SET(pfd[i].fd, &rset);
  4903. }
  4904. if (pfd[i].events & POLLOUT) {
  4905. FD_SET(pfd[i].fd, &wset);
  4906. }
  4907. pfd[i].revents = 0;
  4908. if (pfd[i].fd > maxfd) {
  4909. maxfd = pfd[i].fd;
  4910. }
  4911. }
  4912. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4913. for (i = 0; i < n; i++) {
  4914. if (FD_ISSET(pfd[i].fd, &rset)) {
  4915. pfd[i].revents |= POLLIN;
  4916. }
  4917. if (FD_ISSET(pfd[i].fd, &wset)) {
  4918. pfd[i].revents |= POLLOUT;
  4919. }
  4920. }
  4921. }
  4922. /* We should subtract the time used in select from remaining
  4923. * "milliseconds", in particular if called from mg_poll with a
  4924. * timeout quantum.
  4925. * Unfortunately, the remaining time is not stored in "tv" in all
  4926. * implementations, so the result in "tv" must be considered undefined.
  4927. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4928. return result;
  4929. }
  4930. #endif /* HAVE_POLL */
  4931. #if defined(GCC_DIAGNOSTIC)
  4932. /* Enable unused function warning again */
  4933. #pragma GCC diagnostic pop
  4934. #endif
  4935. static void
  4936. set_close_on_exec(SOCKET sock,
  4937. const struct mg_connection *conn /* may be null */,
  4938. struct mg_context *ctx /* may be null */)
  4939. {
  4940. (void)conn; /* Unused. */
  4941. (void)ctx;
  4942. #if defined(_WIN32_WCE)
  4943. (void)sock;
  4944. #else
  4945. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4946. #endif
  4947. }
  4948. int
  4949. mg_start_thread(mg_thread_func_t f, void *p)
  4950. {
  4951. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4952. /* Compile-time option to control stack size, e.g.
  4953. * -DUSE_STACK_SIZE=16384
  4954. */
  4955. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4956. == ((uintptr_t)(-1L)))
  4957. ? -1
  4958. : 0);
  4959. #else
  4960. return (
  4961. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4962. ? -1
  4963. : 0);
  4964. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4965. }
  4966. /* Start a thread storing the thread context. */
  4967. static int
  4968. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4969. void *p,
  4970. pthread_t *threadidptr)
  4971. {
  4972. uintptr_t uip;
  4973. HANDLE threadhandle;
  4974. int result = -1;
  4975. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4976. threadhandle = (HANDLE)uip;
  4977. if ((uip != 0) && (threadidptr != NULL)) {
  4978. *threadidptr = threadhandle;
  4979. result = 0;
  4980. }
  4981. return result;
  4982. }
  4983. /* Wait for a thread to finish. */
  4984. static int
  4985. mg_join_thread(pthread_t threadid)
  4986. {
  4987. int result;
  4988. DWORD dwevent;
  4989. result = -1;
  4990. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4991. if (dwevent == WAIT_FAILED) {
  4992. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4993. } else {
  4994. if (dwevent == WAIT_OBJECT_0) {
  4995. CloseHandle(threadid);
  4996. result = 0;
  4997. }
  4998. }
  4999. return result;
  5000. }
  5001. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  5002. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  5003. /* Create substitutes for POSIX functions in Win32. */
  5004. #if defined(GCC_DIAGNOSTIC)
  5005. /* Show no warning in case system functions are not used. */
  5006. #pragma GCC diagnostic push
  5007. #pragma GCC diagnostic ignored "-Wunused-function"
  5008. #endif
  5009. FUNCTION_MAY_BE_UNUSED
  5010. static HANDLE
  5011. dlopen(const char *dll_name, int flags)
  5012. {
  5013. wchar_t wbuf[W_PATH_MAX];
  5014. (void)flags;
  5015. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  5016. return LoadLibraryW(wbuf);
  5017. }
  5018. FUNCTION_MAY_BE_UNUSED
  5019. static int
  5020. dlclose(void *handle)
  5021. {
  5022. int result;
  5023. if (FreeLibrary((HMODULE)handle) != 0) {
  5024. result = 0;
  5025. } else {
  5026. result = -1;
  5027. }
  5028. return result;
  5029. }
  5030. #if defined(GCC_DIAGNOSTIC)
  5031. /* Enable unused function warning again */
  5032. #pragma GCC diagnostic pop
  5033. #endif
  5034. #endif
  5035. #if !defined(NO_CGI)
  5036. #define SIGKILL (0)
  5037. static int
  5038. kill(pid_t pid, int sig_num)
  5039. {
  5040. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  5041. (void)CloseHandle((HANDLE)pid);
  5042. return 0;
  5043. }
  5044. #if !defined(WNOHANG)
  5045. #define WNOHANG (1)
  5046. #endif
  5047. static pid_t
  5048. waitpid(pid_t pid, int *status, int flags)
  5049. {
  5050. DWORD timeout = INFINITE;
  5051. DWORD waitres;
  5052. (void)status; /* Currently not used by any client here */
  5053. if ((flags | WNOHANG) == WNOHANG) {
  5054. timeout = 0;
  5055. }
  5056. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  5057. if (waitres == WAIT_OBJECT_0) {
  5058. return pid;
  5059. }
  5060. if (waitres == WAIT_TIMEOUT) {
  5061. return 0;
  5062. }
  5063. return (pid_t)-1;
  5064. }
  5065. static void
  5066. trim_trailing_whitespaces(char *s)
  5067. {
  5068. char *e = s + strlen(s);
  5069. while ((e > s) && isspace((unsigned char)e[-1])) {
  5070. *(--e) = '\0';
  5071. }
  5072. }
  5073. static pid_t
  5074. spawn_process(struct mg_connection *conn,
  5075. const char *prog,
  5076. char *envblk,
  5077. char *envp[],
  5078. int fdin[2],
  5079. int fdout[2],
  5080. int fderr[2],
  5081. const char *dir)
  5082. {
  5083. HANDLE me;
  5084. char *p, *interp;
  5085. char *interp_arg = 0;
  5086. char full_dir[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX];
  5087. int truncated;
  5088. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5089. STARTUPINFOA si;
  5090. PROCESS_INFORMATION pi = {0};
  5091. (void)envp;
  5092. memset(&si, 0, sizeof(si));
  5093. si.cb = sizeof(si);
  5094. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5095. si.wShowWindow = SW_HIDE;
  5096. me = GetCurrentProcess();
  5097. DuplicateHandle(me,
  5098. (HANDLE)_get_osfhandle(fdin[0]),
  5099. me,
  5100. &si.hStdInput,
  5101. 0,
  5102. TRUE,
  5103. DUPLICATE_SAME_ACCESS);
  5104. DuplicateHandle(me,
  5105. (HANDLE)_get_osfhandle(fdout[1]),
  5106. me,
  5107. &si.hStdOutput,
  5108. 0,
  5109. TRUE,
  5110. DUPLICATE_SAME_ACCESS);
  5111. DuplicateHandle(me,
  5112. (HANDLE)_get_osfhandle(fderr[1]),
  5113. me,
  5114. &si.hStdError,
  5115. 0,
  5116. TRUE,
  5117. DUPLICATE_SAME_ACCESS);
  5118. /* Mark handles that should not be inherited. See
  5119. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5120. */
  5121. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5122. HANDLE_FLAG_INHERIT,
  5123. 0);
  5124. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5125. HANDLE_FLAG_INHERIT,
  5126. 0);
  5127. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5128. HANDLE_FLAG_INHERIT,
  5129. 0);
  5130. /* First check, if there is a CGI interpreter configured for all CGI
  5131. * scripts. */
  5132. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5133. if (interp != NULL) {
  5134. /* If there is a configured interpreter, check for additional arguments
  5135. */
  5136. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5137. } else {
  5138. /* Otherwise, the interpreter must be stated in the first line of the
  5139. * CGI script file, after a #! (shebang) mark. */
  5140. buf[0] = buf[1] = '\0';
  5141. /* Get the full script path */
  5142. mg_snprintf(
  5143. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5144. if (truncated) {
  5145. pi.hProcess = (pid_t)-1;
  5146. goto spawn_cleanup;
  5147. }
  5148. /* Open the script file, to read the first line */
  5149. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5150. #if defined(MG_USE_OPEN_FILE)
  5151. p = (char *)file.access.membuf;
  5152. #else
  5153. p = (char *)NULL;
  5154. #endif
  5155. /* Read the first line of the script into the buffer */
  5156. mg_fgets(buf, sizeof(buf), &file, &p);
  5157. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5158. buf[sizeof(buf) - 1] = '\0';
  5159. }
  5160. if ((buf[0] == '#') && (buf[1] == '!')) {
  5161. trim_trailing_whitespaces(buf + 2);
  5162. } else {
  5163. buf[2] = '\0';
  5164. }
  5165. interp = buf + 2;
  5166. }
  5167. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5168. if (interp[0] != '\0') {
  5169. /* This is an interpreted script file. We must call the interpreter. */
  5170. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5171. mg_snprintf(conn,
  5172. &truncated,
  5173. cmdline,
  5174. sizeof(cmdline),
  5175. "\"%s\" %s \"%s\\%s\"",
  5176. interp,
  5177. interp_arg,
  5178. full_dir,
  5179. prog);
  5180. } else {
  5181. mg_snprintf(conn,
  5182. &truncated,
  5183. cmdline,
  5184. sizeof(cmdline),
  5185. "\"%s\" \"%s\\%s\"",
  5186. interp,
  5187. full_dir,
  5188. prog);
  5189. }
  5190. } else {
  5191. /* This is (probably) a compiled program. We call it directly. */
  5192. mg_snprintf(conn,
  5193. &truncated,
  5194. cmdline,
  5195. sizeof(cmdline),
  5196. "\"%s\\%s\"",
  5197. full_dir,
  5198. prog);
  5199. }
  5200. if (truncated) {
  5201. pi.hProcess = (pid_t)-1;
  5202. goto spawn_cleanup;
  5203. }
  5204. DEBUG_TRACE("Running [%s]", cmdline);
  5205. if (CreateProcessA(NULL,
  5206. cmdline,
  5207. NULL,
  5208. NULL,
  5209. TRUE,
  5210. CREATE_NEW_PROCESS_GROUP,
  5211. envblk,
  5212. NULL,
  5213. &si,
  5214. &pi)
  5215. == 0) {
  5216. mg_cry_internal(
  5217. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5218. pi.hProcess = (pid_t)-1;
  5219. /* goto spawn_cleanup; */
  5220. }
  5221. spawn_cleanup:
  5222. (void)CloseHandle(si.hStdOutput);
  5223. (void)CloseHandle(si.hStdError);
  5224. (void)CloseHandle(si.hStdInput);
  5225. if (pi.hThread != NULL) {
  5226. (void)CloseHandle(pi.hThread);
  5227. }
  5228. return (pid_t)pi.hProcess;
  5229. }
  5230. #endif /* !NO_CGI */
  5231. static int
  5232. set_blocking_mode(SOCKET sock)
  5233. {
  5234. unsigned long non_blocking = 0;
  5235. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5236. }
  5237. static int
  5238. set_non_blocking_mode(SOCKET sock)
  5239. {
  5240. unsigned long non_blocking = 1;
  5241. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5242. }
  5243. #else
  5244. #if !defined(NO_FILESYSTEMS)
  5245. static int
  5246. mg_stat(const struct mg_connection *conn,
  5247. const char *path,
  5248. struct mg_file_stat *filep)
  5249. {
  5250. struct stat st;
  5251. if (!filep) {
  5252. return 0;
  5253. }
  5254. memset(filep, 0, sizeof(*filep));
  5255. if (conn && is_file_in_memory(conn, path)) {
  5256. /* Quick fix (for 1.9.x): */
  5257. /* mg_stat must fill all fields, also for files in memory */
  5258. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5259. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5260. filep->size = tmp_file.stat.size;
  5261. filep->last_modified = time(NULL);
  5262. filep->location = 2;
  5263. /* TODO: remove legacy "files in memory" feature */
  5264. return 1;
  5265. }
  5266. if (0 == stat(path, &st)) {
  5267. filep->size = (uint64_t)(st.st_size);
  5268. filep->last_modified = st.st_mtime;
  5269. filep->is_directory = S_ISDIR(st.st_mode);
  5270. return 1;
  5271. }
  5272. return 0;
  5273. }
  5274. #endif /* NO_FILESYSTEMS */
  5275. static void
  5276. set_close_on_exec(int fd,
  5277. const struct mg_connection *conn /* may be null */,
  5278. struct mg_context *ctx /* may be null */)
  5279. {
  5280. #if defined(__ZEPHYR__)
  5281. (void)fd;
  5282. (void)conn;
  5283. (void)ctx;
  5284. #else
  5285. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5286. if (conn || ctx) {
  5287. struct mg_connection fc;
  5288. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5289. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5290. __func__,
  5291. strerror(ERRNO));
  5292. }
  5293. }
  5294. #endif
  5295. }
  5296. int
  5297. mg_start_thread(mg_thread_func_t func, void *param)
  5298. {
  5299. pthread_t thread_id;
  5300. pthread_attr_t attr;
  5301. int result;
  5302. (void)pthread_attr_init(&attr);
  5303. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5304. #if defined(__ZEPHYR__)
  5305. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5306. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5307. /* Compile-time option to control stack size,
  5308. * e.g. -DUSE_STACK_SIZE=16384 */
  5309. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5310. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5311. result = pthread_create(&thread_id, &attr, func, param);
  5312. pthread_attr_destroy(&attr);
  5313. return result;
  5314. }
  5315. /* Start a thread storing the thread context. */
  5316. static int
  5317. mg_start_thread_with_id(mg_thread_func_t func,
  5318. void *param,
  5319. pthread_t *threadidptr)
  5320. {
  5321. pthread_t thread_id;
  5322. pthread_attr_t attr;
  5323. int result;
  5324. (void)pthread_attr_init(&attr);
  5325. #if defined(__ZEPHYR__)
  5326. pthread_attr_setstack(&attr,
  5327. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5328. ZEPHYR_STACK_SIZE);
  5329. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5330. /* Compile-time option to control stack size,
  5331. * e.g. -DUSE_STACK_SIZE=16384 */
  5332. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5333. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5334. result = pthread_create(&thread_id, &attr, func, param);
  5335. pthread_attr_destroy(&attr);
  5336. if ((result == 0) && (threadidptr != NULL)) {
  5337. *threadidptr = thread_id;
  5338. }
  5339. return result;
  5340. }
  5341. /* Wait for a thread to finish. */
  5342. static int
  5343. mg_join_thread(pthread_t threadid)
  5344. {
  5345. int result;
  5346. result = pthread_join(threadid, NULL);
  5347. return result;
  5348. }
  5349. #if !defined(NO_CGI)
  5350. static pid_t
  5351. spawn_process(struct mg_connection *conn,
  5352. const char *prog,
  5353. char *envblk,
  5354. char *envp[],
  5355. int fdin[2],
  5356. int fdout[2],
  5357. int fderr[2],
  5358. const char *dir)
  5359. {
  5360. pid_t pid;
  5361. const char *interp;
  5362. (void)envblk;
  5363. if ((pid = fork()) == -1) {
  5364. /* Parent */
  5365. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5366. } else if (pid != 0) {
  5367. /* Make sure children close parent-side descriptors.
  5368. * The caller will close the child-side immediately. */
  5369. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5370. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5371. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5372. } else {
  5373. /* Child */
  5374. if (chdir(dir) != 0) {
  5375. mg_cry_internal(
  5376. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5377. } else if (dup2(fdin[0], 0) == -1) {
  5378. mg_cry_internal(conn,
  5379. "%s: dup2(%d, 0): %s",
  5380. __func__,
  5381. fdin[0],
  5382. strerror(ERRNO));
  5383. } else if (dup2(fdout[1], 1) == -1) {
  5384. mg_cry_internal(conn,
  5385. "%s: dup2(%d, 1): %s",
  5386. __func__,
  5387. fdout[1],
  5388. strerror(ERRNO));
  5389. } else if (dup2(fderr[1], 2) == -1) {
  5390. mg_cry_internal(conn,
  5391. "%s: dup2(%d, 2): %s",
  5392. __func__,
  5393. fderr[1],
  5394. strerror(ERRNO));
  5395. } else {
  5396. struct sigaction sa;
  5397. /* Keep stderr and stdout in two different pipes.
  5398. * Stdout will be sent back to the client,
  5399. * stderr should go into a server error log. */
  5400. (void)close(fdin[0]);
  5401. (void)close(fdout[1]);
  5402. (void)close(fderr[1]);
  5403. /* Close write end fdin and read end fdout and fderr */
  5404. (void)close(fdin[1]);
  5405. (void)close(fdout[0]);
  5406. (void)close(fderr[0]);
  5407. /* After exec, all signal handlers are restored to their default
  5408. * values, with one exception of SIGCHLD. According to
  5409. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5410. * will leave unchanged after exec if it was set to be ignored.
  5411. * Restore it to default action. */
  5412. memset(&sa, 0, sizeof(sa));
  5413. sa.sa_handler = SIG_DFL;
  5414. sigaction(SIGCHLD, &sa, NULL);
  5415. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5416. if (interp == NULL) {
  5417. /* no interpreter configured, call the programm directly */
  5418. (void)execle(prog, prog, NULL, envp);
  5419. mg_cry_internal(conn,
  5420. "%s: execle(%s): %s",
  5421. __func__,
  5422. prog,
  5423. strerror(ERRNO));
  5424. } else {
  5425. /* call the configured interpreter */
  5426. const char *interp_args =
  5427. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5428. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5429. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5430. } else {
  5431. (void)execle(interp, interp, prog, NULL, envp);
  5432. }
  5433. mg_cry_internal(conn,
  5434. "%s: execle(%s %s): %s",
  5435. __func__,
  5436. interp,
  5437. prog,
  5438. strerror(ERRNO));
  5439. }
  5440. }
  5441. exit(EXIT_FAILURE);
  5442. }
  5443. return pid;
  5444. }
  5445. #endif /* !NO_CGI */
  5446. static int
  5447. set_non_blocking_mode(SOCKET sock)
  5448. {
  5449. int flags = fcntl(sock, F_GETFL, 0);
  5450. if (flags < 0) {
  5451. return -1;
  5452. }
  5453. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5454. return -1;
  5455. }
  5456. return 0;
  5457. }
  5458. static int
  5459. set_blocking_mode(SOCKET sock)
  5460. {
  5461. int flags = fcntl(sock, F_GETFL, 0);
  5462. if (flags < 0) {
  5463. return -1;
  5464. }
  5465. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5466. return -1;
  5467. }
  5468. return 0;
  5469. }
  5470. #endif /* _WIN32 / else */
  5471. /* End of initial operating system specific define block. */
  5472. /* Get a random number (independent of C rand function) */
  5473. static uint64_t
  5474. get_random(void)
  5475. {
  5476. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5477. static uint64_t lcg = 0; /* Linear congruential generator */
  5478. uint64_t now = mg_get_current_time_ns();
  5479. if (lfsr == 0) {
  5480. /* lfsr will be only 0 if has not been initialized,
  5481. * so this code is called only once. */
  5482. lfsr = mg_get_current_time_ns();
  5483. lcg = mg_get_current_time_ns();
  5484. } else {
  5485. /* Get the next step of both random number generators. */
  5486. lfsr = (lfsr >> 1)
  5487. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5488. << 63);
  5489. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5490. }
  5491. /* Combining two pseudo-random number generators and a high resolution
  5492. * part
  5493. * of the current server time will make it hard (impossible?) to guess
  5494. * the
  5495. * next number. */
  5496. return (lfsr ^ lcg ^ now);
  5497. }
  5498. static int
  5499. mg_poll(struct mg_pollfd *pfd,
  5500. unsigned int n,
  5501. int milliseconds,
  5502. stop_flag_t *stop_flag)
  5503. {
  5504. /* Call poll, but only for a maximum time of a few seconds.
  5505. * This will allow to stop the server after some seconds, instead
  5506. * of having to wait for a long socket timeout. */
  5507. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5508. do {
  5509. int result;
  5510. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5511. /* Shut down signal */
  5512. return -2;
  5513. }
  5514. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5515. ms_now = milliseconds;
  5516. }
  5517. result = poll(pfd, n, ms_now);
  5518. if (result != 0) {
  5519. /* Poll returned either success (1) or error (-1).
  5520. * Forward both to the caller. */
  5521. return result;
  5522. }
  5523. /* Poll returned timeout (0). */
  5524. if (milliseconds > 0) {
  5525. milliseconds -= ms_now;
  5526. }
  5527. } while (milliseconds != 0);
  5528. /* timeout: return 0 */
  5529. return 0;
  5530. }
  5531. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5532. * descriptor.
  5533. * Return value:
  5534. * >=0 .. number of bytes successfully written
  5535. * -1 .. timeout
  5536. * -2 .. error
  5537. */
  5538. static int
  5539. push_inner(struct mg_context *ctx,
  5540. FILE *fp,
  5541. SOCKET sock,
  5542. SSL *ssl,
  5543. const char *buf,
  5544. int len,
  5545. double timeout)
  5546. {
  5547. uint64_t start = 0, now = 0, timeout_ns = 0;
  5548. int n, err;
  5549. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5550. #if defined(_WIN32)
  5551. typedef int len_t;
  5552. #else
  5553. typedef size_t len_t;
  5554. #endif
  5555. if (timeout > 0) {
  5556. now = mg_get_current_time_ns();
  5557. start = now;
  5558. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5559. }
  5560. if (ctx == NULL) {
  5561. return -2;
  5562. }
  5563. #if defined(NO_SSL)
  5564. if (ssl) {
  5565. return -2;
  5566. }
  5567. #endif
  5568. /* Try to read until it succeeds, fails, times out, or the server
  5569. * shuts down. */
  5570. for (;;) {
  5571. #if !defined(NO_SSL)
  5572. if (ssl != NULL) {
  5573. ERR_clear_error();
  5574. n = SSL_write(ssl, buf, len);
  5575. if (n <= 0) {
  5576. err = SSL_get_error(ssl, n);
  5577. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5578. err = ERRNO;
  5579. } else if ((err == SSL_ERROR_WANT_READ)
  5580. || (err == SSL_ERROR_WANT_WRITE)) {
  5581. n = 0;
  5582. } else {
  5583. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5584. ERR_clear_error();
  5585. return -2;
  5586. }
  5587. ERR_clear_error();
  5588. } else {
  5589. err = 0;
  5590. }
  5591. } else
  5592. #endif
  5593. if (fp != NULL) {
  5594. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5595. if (ferror(fp)) {
  5596. n = -1;
  5597. err = ERRNO;
  5598. } else {
  5599. err = 0;
  5600. }
  5601. } else {
  5602. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5603. err = (n < 0) ? ERRNO : 0;
  5604. #if defined(_WIN32)
  5605. if (err == WSAEWOULDBLOCK) {
  5606. err = 0;
  5607. n = 0;
  5608. }
  5609. #else
  5610. if (err == EWOULDBLOCK) {
  5611. err = 0;
  5612. n = 0;
  5613. }
  5614. #endif
  5615. if (n < 0) {
  5616. /* shutdown of the socket at client side */
  5617. return -2;
  5618. }
  5619. }
  5620. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5621. return -2;
  5622. }
  5623. if ((n > 0) || ((n == 0) && (len == 0))) {
  5624. /* some data has been read, or no data was requested */
  5625. return n;
  5626. }
  5627. if (n < 0) {
  5628. /* socket error - check errno */
  5629. DEBUG_TRACE("send() failed, error %d", err);
  5630. /* TODO (mid): error handling depending on the error code.
  5631. * These codes are different between Windows and Linux.
  5632. * Currently there is no problem with failing send calls,
  5633. * if there is a reproducible situation, it should be
  5634. * investigated in detail.
  5635. */
  5636. return -2;
  5637. }
  5638. /* Only in case n=0 (timeout), repeat calling the write function */
  5639. /* If send failed, wait before retry */
  5640. if (fp != NULL) {
  5641. /* For files, just wait a fixed time.
  5642. * Maybe it helps, maybe not. */
  5643. mg_sleep(5);
  5644. } else {
  5645. /* For sockets, wait for the socket using poll */
  5646. struct mg_pollfd pfd[1];
  5647. int pollres;
  5648. pfd[0].fd = sock;
  5649. pfd[0].events = POLLOUT;
  5650. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5651. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5652. return -2;
  5653. }
  5654. if (pollres > 0) {
  5655. continue;
  5656. }
  5657. }
  5658. if (timeout > 0) {
  5659. now = mg_get_current_time_ns();
  5660. if ((now - start) > timeout_ns) {
  5661. /* Timeout */
  5662. break;
  5663. }
  5664. }
  5665. }
  5666. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5667. used */
  5668. return -1;
  5669. }
  5670. static int
  5671. push_all(struct mg_context *ctx,
  5672. FILE *fp,
  5673. SOCKET sock,
  5674. SSL *ssl,
  5675. const char *buf,
  5676. int len)
  5677. {
  5678. double timeout = -1.0;
  5679. int n, nwritten = 0;
  5680. if (ctx == NULL) {
  5681. return -1;
  5682. }
  5683. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5684. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5685. }
  5686. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5687. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5688. if (n < 0) {
  5689. if (nwritten == 0) {
  5690. nwritten = -1; /* Propagate the error */
  5691. }
  5692. break;
  5693. } else if (n == 0) {
  5694. break; /* No more data to write */
  5695. } else {
  5696. nwritten += n;
  5697. len -= n;
  5698. }
  5699. }
  5700. return nwritten;
  5701. }
  5702. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5703. * Return value:
  5704. * >=0 .. number of bytes successfully read
  5705. * -1 .. timeout
  5706. * -2 .. error
  5707. */
  5708. static int
  5709. pull_inner(FILE *fp,
  5710. struct mg_connection *conn,
  5711. char *buf,
  5712. int len,
  5713. double timeout)
  5714. {
  5715. int nread, err = 0;
  5716. #if defined(_WIN32)
  5717. typedef int len_t;
  5718. #else
  5719. typedef size_t len_t;
  5720. #endif
  5721. /* We need an additional wait loop around this, because in some cases
  5722. * with TLSwe may get data from the socket but not from SSL_read.
  5723. * In this case we need to repeat at least once.
  5724. */
  5725. if (fp != NULL) {
  5726. #if !defined(_WIN32_WCE)
  5727. /* Use read() instead of fread(), because if we're reading from the
  5728. * CGI pipe, fread() may block until IO buffer is filled up. We
  5729. * cannot afford to block and must pass all read bytes immediately
  5730. * to the client. */
  5731. nread = (int)read(fileno(fp), buf, (size_t)len);
  5732. #else
  5733. /* WinCE does not support CGI pipes */
  5734. nread = (int)fread(buf, 1, (size_t)len, fp);
  5735. #endif
  5736. err = (nread < 0) ? ERRNO : 0;
  5737. if ((nread == 0) && (len > 0)) {
  5738. /* Should get data, but got EOL */
  5739. return -2;
  5740. }
  5741. #if !defined(NO_SSL)
  5742. } else if (conn->ssl != NULL) {
  5743. int ssl_pending;
  5744. struct mg_pollfd pfd[1];
  5745. int pollres;
  5746. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5747. /* We already know there is no more data buffered in conn->buf
  5748. * but there is more available in the SSL layer. So don't poll
  5749. * conn->client.sock yet. */
  5750. if (ssl_pending > len) {
  5751. ssl_pending = len;
  5752. }
  5753. pollres = 1;
  5754. } else {
  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. }
  5765. if (pollres > 0) {
  5766. ERR_clear_error();
  5767. nread =
  5768. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5769. if (nread <= 0) {
  5770. err = SSL_get_error(conn->ssl, nread);
  5771. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5772. err = ERRNO;
  5773. } else if ((err == SSL_ERROR_WANT_READ)
  5774. || (err == SSL_ERROR_WANT_WRITE)) {
  5775. nread = 0;
  5776. } else {
  5777. /* All errors should return -2 */
  5778. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5779. ERR_clear_error();
  5780. return -2;
  5781. }
  5782. ERR_clear_error();
  5783. } else {
  5784. err = 0;
  5785. }
  5786. } else if (pollres < 0) {
  5787. /* Error */
  5788. return -2;
  5789. } else {
  5790. /* pollres = 0 means timeout */
  5791. nread = 0;
  5792. }
  5793. #endif
  5794. } else {
  5795. struct mg_pollfd pfd[1];
  5796. int pollres;
  5797. pfd[0].fd = conn->client.sock;
  5798. pfd[0].events = POLLIN;
  5799. pollres = mg_poll(pfd,
  5800. 1,
  5801. (int)(timeout * 1000.0),
  5802. &(conn->phys_ctx->stop_flag));
  5803. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5804. return -2;
  5805. }
  5806. if (pollres > 0) {
  5807. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5808. err = (nread < 0) ? ERRNO : 0;
  5809. if (nread <= 0) {
  5810. /* shutdown of the socket at client side */
  5811. return -2;
  5812. }
  5813. } else if (pollres < 0) {
  5814. /* error callint poll */
  5815. return -2;
  5816. } else {
  5817. /* pollres = 0 means timeout */
  5818. nread = 0;
  5819. }
  5820. }
  5821. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5822. return -2;
  5823. }
  5824. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5825. /* some data has been read, or no data was requested */
  5826. return nread;
  5827. }
  5828. if (nread < 0) {
  5829. /* socket error - check errno */
  5830. #if defined(_WIN32)
  5831. if (err == WSAEWOULDBLOCK) {
  5832. /* TODO (low): check if this is still required */
  5833. /* standard case if called from close_socket_gracefully */
  5834. return -2;
  5835. } else if (err == WSAETIMEDOUT) {
  5836. /* TODO (low): check if this is still required */
  5837. /* timeout is handled by the while loop */
  5838. return 0;
  5839. } else if (err == WSAECONNABORTED) {
  5840. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5841. return -2;
  5842. } else {
  5843. DEBUG_TRACE("recv() failed, error %d", err);
  5844. return -2;
  5845. }
  5846. #else
  5847. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5848. * if the timeout is reached and if the socket was set to non-
  5849. * blocking in close_socket_gracefully, so we can not distinguish
  5850. * here. We have to wait for the timeout in both cases for now.
  5851. */
  5852. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5853. /* TODO (low): check if this is still required */
  5854. /* EAGAIN/EWOULDBLOCK:
  5855. * standard case if called from close_socket_gracefully
  5856. * => should return -1 */
  5857. /* or timeout occurred
  5858. * => the code must stay in the while loop */
  5859. /* EINTR can be generated on a socket with a timeout set even
  5860. * when SA_RESTART is effective for all relevant signals
  5861. * (see signal(7)).
  5862. * => stay in the while loop */
  5863. } else {
  5864. DEBUG_TRACE("recv() failed, error %d", err);
  5865. return -2;
  5866. }
  5867. #endif
  5868. }
  5869. /* Timeout occurred, but no data available. */
  5870. return -1;
  5871. }
  5872. static int
  5873. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5874. {
  5875. int n, nread = 0;
  5876. double timeout = -1.0;
  5877. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5878. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5879. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5880. }
  5881. if (timeout >= 0.0) {
  5882. start_time = mg_get_current_time_ns();
  5883. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5884. }
  5885. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5886. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5887. if (n == -2) {
  5888. if (nread == 0) {
  5889. nread = -1; /* Propagate the error */
  5890. }
  5891. break;
  5892. } else if (n == -1) {
  5893. /* timeout */
  5894. if (timeout >= 0.0) {
  5895. now = mg_get_current_time_ns();
  5896. if ((now - start_time) <= timeout_ns) {
  5897. continue;
  5898. }
  5899. }
  5900. break;
  5901. } else if (n == 0) {
  5902. break; /* No more data to read */
  5903. } else {
  5904. nread += n;
  5905. len -= n;
  5906. }
  5907. }
  5908. return nread;
  5909. }
  5910. static void
  5911. discard_unread_request_data(struct mg_connection *conn)
  5912. {
  5913. char buf[MG_BUF_LEN];
  5914. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5915. ;
  5916. }
  5917. static int
  5918. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5919. {
  5920. int64_t content_len, n, buffered_len, nread;
  5921. int64_t len64 =
  5922. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5923. * int, we may not read more
  5924. * bytes */
  5925. const char *body;
  5926. if (conn == NULL) {
  5927. return 0;
  5928. }
  5929. /* If Content-Length is not set for a response with body data,
  5930. * we do not know in advance how much data should be read. */
  5931. content_len = conn->content_len;
  5932. if (content_len < 0) {
  5933. /* The body data is completed when the connection is closed. */
  5934. content_len = INT64_MAX;
  5935. }
  5936. nread = 0;
  5937. if (conn->consumed_content < content_len) {
  5938. /* Adjust number of bytes to read. */
  5939. int64_t left_to_read = content_len - conn->consumed_content;
  5940. if (left_to_read < len64) {
  5941. /* Do not read more than the total content length of the
  5942. * request.
  5943. */
  5944. len64 = left_to_read;
  5945. }
  5946. /* Return buffered data */
  5947. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5948. - conn->consumed_content;
  5949. if (buffered_len > 0) {
  5950. if (len64 < buffered_len) {
  5951. buffered_len = len64;
  5952. }
  5953. body = conn->buf + conn->request_len + conn->consumed_content;
  5954. memcpy(buf, body, (size_t)buffered_len);
  5955. len64 -= buffered_len;
  5956. conn->consumed_content += buffered_len;
  5957. nread += buffered_len;
  5958. buf = (char *)buf + buffered_len;
  5959. }
  5960. /* We have returned all buffered data. Read new data from the remote
  5961. * socket.
  5962. */
  5963. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5964. conn->consumed_content += n;
  5965. nread += n;
  5966. } else {
  5967. nread = ((nread > 0) ? nread : n);
  5968. }
  5969. }
  5970. return (int)nread;
  5971. }
  5972. /* Forward declarations */
  5973. static void handle_request(struct mg_connection *);
  5974. #ifdef USE_HTTP2
  5975. #if defined(NO_SSL)
  5976. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5977. #endif
  5978. #include "mod_http2.inl"
  5979. /* Not supported with HTTP/2 */
  5980. #define HTTP1_only \
  5981. { \
  5982. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5983. http2_must_use_http1(conn); \
  5984. return; \
  5985. } \
  5986. }
  5987. #else
  5988. #define HTTP1_only
  5989. #endif
  5990. int
  5991. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5992. {
  5993. if (len > INT_MAX) {
  5994. len = INT_MAX;
  5995. }
  5996. if (conn == NULL) {
  5997. return 0;
  5998. }
  5999. if (conn->is_chunked) {
  6000. size_t all_read = 0;
  6001. while (len > 0) {
  6002. if (conn->is_chunked >= 3) {
  6003. /* No more data left to read */
  6004. return 0;
  6005. }
  6006. if (conn->is_chunked != 1) {
  6007. /* Has error */
  6008. return -1;
  6009. }
  6010. if (conn->consumed_content != conn->content_len) {
  6011. /* copy from the current chunk */
  6012. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  6013. if (read_ret < 1) {
  6014. /* read error */
  6015. conn->is_chunked = 2;
  6016. return -1;
  6017. }
  6018. all_read += (size_t)read_ret;
  6019. len -= (size_t)read_ret;
  6020. if (conn->consumed_content == conn->content_len) {
  6021. /* Add data bytes in the current chunk have been read,
  6022. * so we are expecting \r\n now. */
  6023. char x[2];
  6024. conn->content_len += 2;
  6025. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  6026. || (x[1] != '\n')) {
  6027. /* Protocol violation */
  6028. conn->is_chunked = 2;
  6029. return -1;
  6030. }
  6031. }
  6032. } else {
  6033. /* fetch a new chunk */
  6034. size_t i;
  6035. char lenbuf[64];
  6036. char *end = NULL;
  6037. unsigned long chunkSize = 0;
  6038. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  6039. conn->content_len++;
  6040. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  6041. lenbuf[i] = 0;
  6042. }
  6043. if ((i > 0) && (lenbuf[i] == '\r')
  6044. && (lenbuf[i - 1] != '\r')) {
  6045. continue;
  6046. }
  6047. if ((i > 1) && (lenbuf[i] == '\n')
  6048. && (lenbuf[i - 1] == '\r')) {
  6049. lenbuf[i + 1] = 0;
  6050. chunkSize = strtoul(lenbuf, &end, 16);
  6051. if (chunkSize == 0) {
  6052. /* regular end of content */
  6053. conn->is_chunked = 3;
  6054. }
  6055. break;
  6056. }
  6057. if (!isxdigit((unsigned char)lenbuf[i])) {
  6058. /* illegal character for chunk length */
  6059. conn->is_chunked = 2;
  6060. return -1;
  6061. }
  6062. }
  6063. if ((end == NULL) || (*end != '\r')) {
  6064. /* chunksize not set correctly */
  6065. conn->is_chunked = 2;
  6066. return -1;
  6067. }
  6068. if (chunkSize == 0) {
  6069. /* try discarding trailer for keep-alive */
  6070. conn->content_len += 2;
  6071. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  6072. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  6073. conn->is_chunked = 4;
  6074. }
  6075. break;
  6076. }
  6077. /* append a new chunk */
  6078. conn->content_len += (int64_t)chunkSize;
  6079. }
  6080. }
  6081. return (int)all_read;
  6082. }
  6083. return mg_read_inner(conn, buf, len);
  6084. }
  6085. int
  6086. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  6087. {
  6088. time_t now;
  6089. int n, total, allowed;
  6090. if (conn == NULL) {
  6091. return 0;
  6092. }
  6093. if (len > INT_MAX) {
  6094. return -1;
  6095. }
  6096. /* Mark connection as "data sent" */
  6097. conn->request_state = 10;
  6098. #ifdef USE_HTTP2
  6099. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  6100. http2_data_frame_head(conn, len, 0);
  6101. }
  6102. #endif
  6103. if (conn->throttle > 0) {
  6104. if ((now = time(NULL)) != conn->last_throttle_time) {
  6105. conn->last_throttle_time = now;
  6106. conn->last_throttle_bytes = 0;
  6107. }
  6108. allowed = conn->throttle - conn->last_throttle_bytes;
  6109. if (allowed > (int)len) {
  6110. allowed = (int)len;
  6111. }
  6112. total = push_all(conn->phys_ctx,
  6113. NULL,
  6114. conn->client.sock,
  6115. conn->ssl,
  6116. (const char *)buf,
  6117. allowed);
  6118. if (total == allowed) {
  6119. buf = (const char *)buf + total;
  6120. conn->last_throttle_bytes += total;
  6121. while ((total < (int)len)
  6122. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6123. allowed = (conn->throttle > ((int)len - total))
  6124. ? (int)len - total
  6125. : conn->throttle;
  6126. n = push_all(conn->phys_ctx,
  6127. NULL,
  6128. conn->client.sock,
  6129. conn->ssl,
  6130. (const char *)buf,
  6131. allowed);
  6132. if (n != allowed) {
  6133. break;
  6134. }
  6135. sleep(1);
  6136. conn->last_throttle_bytes = allowed;
  6137. conn->last_throttle_time = time(NULL);
  6138. buf = (const char *)buf + n;
  6139. total += n;
  6140. }
  6141. }
  6142. } else {
  6143. total = push_all(conn->phys_ctx,
  6144. NULL,
  6145. conn->client.sock,
  6146. conn->ssl,
  6147. (const char *)buf,
  6148. (int)len);
  6149. }
  6150. if (total > 0) {
  6151. conn->num_bytes_sent += total;
  6152. }
  6153. return total;
  6154. }
  6155. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6156. int
  6157. mg_send_chunk(struct mg_connection *conn,
  6158. const char *chunk,
  6159. unsigned int chunk_len)
  6160. {
  6161. char lenbuf[16];
  6162. size_t lenbuf_len;
  6163. int ret;
  6164. int t;
  6165. /* First store the length information in a text buffer. */
  6166. sprintf(lenbuf, "%x\r\n", chunk_len);
  6167. lenbuf_len = strlen(lenbuf);
  6168. /* Then send length information, chunk and terminating \r\n. */
  6169. ret = mg_write(conn, lenbuf, lenbuf_len);
  6170. if (ret != (int)lenbuf_len) {
  6171. return -1;
  6172. }
  6173. t = ret;
  6174. ret = mg_write(conn, chunk, chunk_len);
  6175. if (ret != (int)chunk_len) {
  6176. return -1;
  6177. }
  6178. t += ret;
  6179. ret = mg_write(conn, "\r\n", 2);
  6180. if (ret != 2) {
  6181. return -1;
  6182. }
  6183. t += ret;
  6184. return t;
  6185. }
  6186. #if defined(GCC_DIAGNOSTIC)
  6187. /* This block forwards format strings to printf implementations,
  6188. * so we need to disable the format-nonliteral warning. */
  6189. #pragma GCC diagnostic push
  6190. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6191. #endif
  6192. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6193. static int
  6194. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6195. {
  6196. va_list ap_copy;
  6197. size_t size = MG_BUF_LEN / 4;
  6198. int len = -1;
  6199. *buf = NULL;
  6200. while (len < 0) {
  6201. if (*buf) {
  6202. mg_free(*buf);
  6203. }
  6204. size *= 4;
  6205. *buf = (char *)mg_malloc(size);
  6206. if (!*buf) {
  6207. break;
  6208. }
  6209. va_copy(ap_copy, ap);
  6210. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6211. va_end(ap_copy);
  6212. (*buf)[size - 1] = 0;
  6213. }
  6214. return len;
  6215. }
  6216. /* Print message to buffer. If buffer is large enough to hold the message,
  6217. * return buffer. If buffer is to small, allocate large enough buffer on
  6218. * heap,
  6219. * and return allocated buffer. */
  6220. static int
  6221. alloc_vprintf(char **out_buf,
  6222. char *prealloc_buf,
  6223. size_t prealloc_size,
  6224. const char *fmt,
  6225. va_list ap)
  6226. {
  6227. va_list ap_copy;
  6228. int len;
  6229. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6230. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6231. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6232. * Therefore, we make two passes: on first pass, get required message
  6233. * length.
  6234. * On second pass, actually print the message. */
  6235. va_copy(ap_copy, ap);
  6236. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6237. va_end(ap_copy);
  6238. if (len < 0) {
  6239. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6240. * Switch to alternative code path that uses incremental
  6241. * allocations.
  6242. */
  6243. va_copy(ap_copy, ap);
  6244. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6245. va_end(ap_copy);
  6246. } else if ((size_t)(len) >= prealloc_size) {
  6247. /* The pre-allocated buffer not large enough. */
  6248. /* Allocate a new buffer. */
  6249. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6250. if (!*out_buf) {
  6251. /* Allocation failed. Return -1 as "out of memory" error. */
  6252. return -1;
  6253. }
  6254. /* Buffer allocation successful. Store the string there. */
  6255. va_copy(ap_copy, ap);
  6256. IGNORE_UNUSED_RESULT(
  6257. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6258. va_end(ap_copy);
  6259. } else {
  6260. /* The pre-allocated buffer is large enough.
  6261. * Use it to store the string and return the address. */
  6262. va_copy(ap_copy, ap);
  6263. IGNORE_UNUSED_RESULT(
  6264. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6265. va_end(ap_copy);
  6266. *out_buf = prealloc_buf;
  6267. }
  6268. return len;
  6269. }
  6270. #if defined(GCC_DIAGNOSTIC)
  6271. /* Enable format-nonliteral warning again. */
  6272. #pragma GCC diagnostic pop
  6273. #endif
  6274. static int
  6275. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6276. {
  6277. char mem[MG_BUF_LEN];
  6278. char *buf = NULL;
  6279. int len;
  6280. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6281. len = mg_write(conn, buf, (size_t)len);
  6282. }
  6283. if (buf != mem) {
  6284. mg_free(buf);
  6285. }
  6286. return len;
  6287. }
  6288. int
  6289. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6290. {
  6291. va_list ap;
  6292. int result;
  6293. va_start(ap, fmt);
  6294. result = mg_vprintf(conn, fmt, ap);
  6295. va_end(ap);
  6296. return result;
  6297. }
  6298. int
  6299. mg_url_decode(const char *src,
  6300. int src_len,
  6301. char *dst,
  6302. int dst_len,
  6303. int is_form_url_encoded)
  6304. {
  6305. int i, j, a, b;
  6306. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6307. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6308. if ((i < src_len - 2) && (src[i] == '%')
  6309. && isxdigit((unsigned char)src[i + 1])
  6310. && isxdigit((unsigned char)src[i + 2])) {
  6311. a = tolower((unsigned char)src[i + 1]);
  6312. b = tolower((unsigned char)src[i + 2]);
  6313. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6314. i += 2;
  6315. } else if (is_form_url_encoded && (src[i] == '+')) {
  6316. dst[j] = ' ';
  6317. } else {
  6318. dst[j] = src[i];
  6319. }
  6320. }
  6321. dst[j] = '\0'; /* Null-terminate the destination */
  6322. return (i >= src_len) ? j : -1;
  6323. }
  6324. /* form url decoding of an entire string */
  6325. static void
  6326. url_decode_in_place(char *buf)
  6327. {
  6328. int len = (int)strlen(buf);
  6329. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6330. }
  6331. int
  6332. mg_get_var(const char *data,
  6333. size_t data_len,
  6334. const char *name,
  6335. char *dst,
  6336. size_t dst_len)
  6337. {
  6338. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6339. }
  6340. int
  6341. mg_get_var2(const char *data,
  6342. size_t data_len,
  6343. const char *name,
  6344. char *dst,
  6345. size_t dst_len,
  6346. size_t occurrence)
  6347. {
  6348. const char *p, *e, *s;
  6349. size_t name_len;
  6350. int len;
  6351. if ((dst == NULL) || (dst_len == 0)) {
  6352. len = -2;
  6353. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6354. len = -1;
  6355. dst[0] = '\0';
  6356. } else {
  6357. name_len = strlen(name);
  6358. e = data + data_len;
  6359. len = -1;
  6360. dst[0] = '\0';
  6361. /* data is "var1=val1&var2=val2...". Find variable first */
  6362. for (p = data; p + name_len < e; p++) {
  6363. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6364. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6365. /* Point p to variable value */
  6366. p += name_len + 1;
  6367. /* Point s to the end of the value */
  6368. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6369. if (s == NULL) {
  6370. s = e;
  6371. }
  6372. DEBUG_ASSERT(s >= p);
  6373. if (s < p) {
  6374. return -3;
  6375. }
  6376. /* Decode variable into destination buffer */
  6377. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6378. /* Redirect error code from -1 to -2 (destination buffer too
  6379. * small). */
  6380. if (len == -1) {
  6381. len = -2;
  6382. }
  6383. break;
  6384. }
  6385. }
  6386. }
  6387. return len;
  6388. }
  6389. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6390. int
  6391. mg_split_form_urlencoded(char *data,
  6392. struct mg_header *form_fields,
  6393. unsigned num_form_fields)
  6394. {
  6395. char *b;
  6396. int i;
  6397. int num = 0;
  6398. if (data == NULL) {
  6399. /* parameter error */
  6400. return -1;
  6401. }
  6402. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6403. /* determine the number of expected fields */
  6404. if (data[0] == 0) {
  6405. return 0;
  6406. }
  6407. /* count number of & to return the number of key-value-pairs */
  6408. num = 1;
  6409. while (*data) {
  6410. if (*data == '&') {
  6411. num++;
  6412. }
  6413. data++;
  6414. }
  6415. return num;
  6416. }
  6417. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6418. /* parameter error */
  6419. return -1;
  6420. }
  6421. for (i = 0; i < (int)num_form_fields; i++) {
  6422. /* extract key-value pairs from input data */
  6423. while ((*data == ' ') || (*data == '\t')) {
  6424. /* skip initial spaces */
  6425. data++;
  6426. }
  6427. if (*data == 0) {
  6428. /* end of string reached */
  6429. break;
  6430. }
  6431. form_fields[num].name = data;
  6432. /* find & or = */
  6433. b = data;
  6434. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6435. b++;
  6436. }
  6437. if (*b == 0) {
  6438. /* last key without value */
  6439. form_fields[num].value = NULL;
  6440. } else if (*b == '&') {
  6441. /* mid key without value */
  6442. form_fields[num].value = NULL;
  6443. } else {
  6444. /* terminate string */
  6445. *b = 0;
  6446. /* value starts after '=' */
  6447. data = b + 1;
  6448. form_fields[num].value = data;
  6449. }
  6450. /* new field is stored */
  6451. num++;
  6452. /* find a next key */
  6453. b = strchr(data, '&');
  6454. if (b == 0) {
  6455. /* no more data */
  6456. break;
  6457. } else {
  6458. /* terminate value of last field at '&' */
  6459. *b = 0;
  6460. /* next key-value-pairs starts after '&' */
  6461. data = b + 1;
  6462. }
  6463. }
  6464. /* Decode all values */
  6465. for (i = 0; i < num; i++) {
  6466. if (form_fields[i].name) {
  6467. url_decode_in_place((char *)form_fields[i].name);
  6468. }
  6469. if (form_fields[i].value) {
  6470. url_decode_in_place((char *)form_fields[i].value);
  6471. }
  6472. }
  6473. /* return number of fields found */
  6474. return num;
  6475. }
  6476. /* HCP24: some changes to compare hole var_name */
  6477. int
  6478. mg_get_cookie(const char *cookie_header,
  6479. const char *var_name,
  6480. char *dst,
  6481. size_t dst_size)
  6482. {
  6483. const char *s, *p, *end;
  6484. int name_len, len = -1;
  6485. if ((dst == NULL) || (dst_size == 0)) {
  6486. return -2;
  6487. }
  6488. dst[0] = '\0';
  6489. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6490. return -1;
  6491. }
  6492. name_len = (int)strlen(var_name);
  6493. end = s + strlen(s);
  6494. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6495. if (s[name_len] == '=') {
  6496. /* HCP24: now check is it a substring or a full cookie name */
  6497. if ((s == cookie_header) || (s[-1] == ' ')) {
  6498. s += name_len + 1;
  6499. if ((p = strchr(s, ' ')) == NULL) {
  6500. p = end;
  6501. }
  6502. if (p[-1] == ';') {
  6503. p--;
  6504. }
  6505. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6506. s++;
  6507. p--;
  6508. }
  6509. if ((size_t)(p - s) < dst_size) {
  6510. len = (int)(p - s);
  6511. mg_strlcpy(dst, s, (size_t)len + 1);
  6512. } else {
  6513. len = -3;
  6514. }
  6515. break;
  6516. }
  6517. }
  6518. }
  6519. return len;
  6520. }
  6521. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6522. static void
  6523. base64_encode(const unsigned char *src, int src_len, char *dst)
  6524. {
  6525. static const char *b64 =
  6526. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6527. int i, j, a, b, c;
  6528. for (i = j = 0; i < src_len; i += 3) {
  6529. a = src[i];
  6530. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6531. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6532. dst[j++] = b64[a >> 2];
  6533. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6534. if (i + 1 < src_len) {
  6535. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6536. }
  6537. if (i + 2 < src_len) {
  6538. dst[j++] = b64[c & 63];
  6539. }
  6540. }
  6541. while (j % 4 != 0) {
  6542. dst[j++] = '=';
  6543. }
  6544. dst[j++] = '\0';
  6545. }
  6546. #endif
  6547. #if defined(USE_LUA)
  6548. static unsigned char
  6549. b64reverse(char letter)
  6550. {
  6551. if ((letter >= 'A') && (letter <= 'Z')) {
  6552. return letter - 'A';
  6553. }
  6554. if ((letter >= 'a') && (letter <= 'z')) {
  6555. return letter - 'a' + 26;
  6556. }
  6557. if ((letter >= '0') && (letter <= '9')) {
  6558. return letter - '0' + 52;
  6559. }
  6560. if (letter == '+') {
  6561. return 62;
  6562. }
  6563. if (letter == '/') {
  6564. return 63;
  6565. }
  6566. if (letter == '=') {
  6567. return 255; /* normal end */
  6568. }
  6569. return 254; /* error */
  6570. }
  6571. static int
  6572. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6573. {
  6574. int i;
  6575. unsigned char a, b, c, d;
  6576. *dst_len = 0;
  6577. for (i = 0; i < src_len; i += 4) {
  6578. a = b64reverse(src[i]);
  6579. if (a >= 254) {
  6580. return i;
  6581. }
  6582. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6583. if (b >= 254) {
  6584. return i + 1;
  6585. }
  6586. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6587. if (c == 254) {
  6588. return i + 2;
  6589. }
  6590. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6591. if (d == 254) {
  6592. return i + 3;
  6593. }
  6594. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6595. if (c != 255) {
  6596. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6597. if (d != 255) {
  6598. dst[(*dst_len)++] = (c << 6) + d;
  6599. }
  6600. }
  6601. }
  6602. return -1;
  6603. }
  6604. #endif
  6605. static int
  6606. is_put_or_delete_method(const struct mg_connection *conn)
  6607. {
  6608. if (conn) {
  6609. const char *s = conn->request_info.request_method;
  6610. return (s != NULL)
  6611. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6612. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6613. }
  6614. return 0;
  6615. }
  6616. #if !defined(NO_FILES)
  6617. static int
  6618. extention_matches_script(
  6619. struct mg_connection *conn, /* in: request (must be valid) */
  6620. const char *filename /* in: filename (must be valid) */
  6621. )
  6622. {
  6623. #if !defined(NO_CGI)
  6624. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6625. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6626. filename)
  6627. > 0) {
  6628. return 1;
  6629. }
  6630. #endif
  6631. #if defined(USE_LUA)
  6632. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6633. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6634. filename)
  6635. > 0) {
  6636. return 1;
  6637. }
  6638. #endif
  6639. #if defined(USE_DUKTAPE)
  6640. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6641. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6642. filename)
  6643. > 0) {
  6644. return 1;
  6645. }
  6646. #endif
  6647. /* filename and conn could be unused, if all preocessor conditions
  6648. * are false (no script language supported). */
  6649. (void)filename;
  6650. (void)conn;
  6651. return 0;
  6652. }
  6653. /* For given directory path, substitute it to valid index file.
  6654. * Return 1 if index file has been found, 0 if not found.
  6655. * If the file is found, it's stats is returned in stp. */
  6656. static int
  6657. substitute_index_file(struct mg_connection *conn,
  6658. char *path,
  6659. size_t path_len,
  6660. struct mg_file_stat *filestat)
  6661. {
  6662. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6663. struct vec filename_vec;
  6664. size_t n = strlen(path);
  6665. int found = 0;
  6666. /* The 'path' given to us points to the directory. Remove all trailing
  6667. * directory separator characters from the end of the path, and
  6668. * then append single directory separator character. */
  6669. while ((n > 0) && (path[n - 1] == '/')) {
  6670. n--;
  6671. }
  6672. path[n] = '/';
  6673. /* Traverse index files list. For each entry, append it to the given
  6674. * path and see if the file exists. If it exists, break the loop */
  6675. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6676. /* Ignore too long entries that may overflow path buffer */
  6677. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6678. continue;
  6679. }
  6680. /* Prepare full path to the index file */
  6681. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6682. /* Does it exist? */
  6683. if (mg_stat(conn, path, filestat)) {
  6684. /* Yes it does, break the loop */
  6685. found = 1;
  6686. break;
  6687. }
  6688. }
  6689. /* If no index file exists, restore directory path */
  6690. if (!found) {
  6691. path[n] = '\0';
  6692. }
  6693. return found;
  6694. }
  6695. #endif
  6696. static void
  6697. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6698. char *filename, /* out: filename */
  6699. size_t filename_buf_len, /* in: size of filename buffer */
  6700. struct mg_file_stat *filestat, /* out: file status structure */
  6701. int *is_found, /* out: file found (directly) */
  6702. int *is_script_resource, /* out: handled by a script? */
  6703. int *is_websocket_request, /* out: websocket connetion? */
  6704. int *is_put_or_delete_request /* out: put/delete a file? */
  6705. )
  6706. {
  6707. char const *accept_encoding;
  6708. #if !defined(NO_FILES)
  6709. const char *uri = conn->request_info.local_uri;
  6710. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6711. const char *rewrite;
  6712. struct vec a, b;
  6713. ptrdiff_t match_len;
  6714. char gz_path[PATH_MAX];
  6715. int truncated;
  6716. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6717. char *tmp_str;
  6718. size_t tmp_str_len, sep_pos;
  6719. int allow_substitute_script_subresources;
  6720. #endif
  6721. #else
  6722. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6723. #endif
  6724. /* Step 1: Set all initially unknown outputs to zero */
  6725. memset(filestat, 0, sizeof(*filestat));
  6726. *filename = 0;
  6727. *is_found = 0;
  6728. *is_script_resource = 0;
  6729. /* Step 2: Check if the request attempts to modify the file system */
  6730. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6731. /* Step 3: Check if it is a websocket request, and modify the document
  6732. * root if required */
  6733. #if defined(USE_WEBSOCKET)
  6734. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6735. #if !defined(NO_FILES)
  6736. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6737. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6738. }
  6739. #endif /* !NO_FILES */
  6740. #else /* USE_WEBSOCKET */
  6741. *is_websocket_request = 0;
  6742. #endif /* USE_WEBSOCKET */
  6743. /* Step 4: Check if gzip encoded response is allowed */
  6744. conn->accept_gzip = 0;
  6745. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6746. if (strstr(accept_encoding, "gzip") != NULL) {
  6747. conn->accept_gzip = 1;
  6748. }
  6749. }
  6750. #if !defined(NO_FILES)
  6751. /* Step 5: If there is no root directory, don't look for files. */
  6752. /* Note that root == NULL is a regular use case here. This occurs,
  6753. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6754. * config is not required. */
  6755. if (root == NULL) {
  6756. /* all file related outputs have already been set to 0, just return
  6757. */
  6758. return;
  6759. }
  6760. /* Step 6: Determine the local file path from the root path and the
  6761. * request uri. */
  6762. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6763. * part of the path one byte on the right. */
  6764. mg_snprintf(
  6765. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6766. if (truncated) {
  6767. goto interpret_cleanup;
  6768. }
  6769. /* Step 7: URI rewriting */
  6770. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6771. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6772. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6773. mg_snprintf(conn,
  6774. &truncated,
  6775. filename,
  6776. filename_buf_len - 1,
  6777. "%.*s%s",
  6778. (int)b.len,
  6779. b.ptr,
  6780. uri + match_len);
  6781. break;
  6782. }
  6783. }
  6784. if (truncated) {
  6785. goto interpret_cleanup;
  6786. }
  6787. /* Step 8: Check if the file exists at the server */
  6788. /* Local file path and name, corresponding to requested URI
  6789. * is now stored in "filename" variable. */
  6790. if (mg_stat(conn, filename, filestat)) {
  6791. int uri_len = (int)strlen(uri);
  6792. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6793. /* 8.1: File exists. */
  6794. *is_found = 1;
  6795. /* 8.2: Check if it is a script type. */
  6796. if (extention_matches_script(conn, filename)) {
  6797. /* The request addresses a CGI resource, Lua script or
  6798. * server-side javascript.
  6799. * The URI corresponds to the script itself (like
  6800. * /path/script.cgi), and there is no additional resource
  6801. * path (like /path/script.cgi/something).
  6802. * Requests that modify (replace or delete) a resource, like
  6803. * PUT and DELETE requests, should replace/delete the script
  6804. * file.
  6805. * Requests that read or write from/to a resource, like GET and
  6806. * POST requests, should call the script and return the
  6807. * generated response. */
  6808. *is_script_resource = (!*is_put_or_delete_request);
  6809. }
  6810. /* 8.3: If the request target is a directory, there could be
  6811. * a substitute file (index.html, index.cgi, ...). */
  6812. if (filestat->is_directory && is_uri_end_slash) {
  6813. /* Use a local copy here, since substitute_index_file will
  6814. * change the content of the file status */
  6815. struct mg_file_stat tmp_filestat;
  6816. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6817. if (substitute_index_file(
  6818. conn, filename, filename_buf_len, &tmp_filestat)) {
  6819. /* Substitute file found. Copy stat to the output, then
  6820. * check if the file is a script file */
  6821. *filestat = tmp_filestat;
  6822. if (extention_matches_script(conn, filename)) {
  6823. /* Substitute file is a script file */
  6824. *is_script_resource = 1;
  6825. } else {
  6826. /* Substitute file is a regular file */
  6827. *is_script_resource = 0;
  6828. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6829. }
  6830. }
  6831. /* If there is no substitute file, the server could return
  6832. * a directory listing in a later step */
  6833. }
  6834. return;
  6835. }
  6836. /* Step 9: Check for zipped files: */
  6837. /* If we can't find the actual file, look for the file
  6838. * with the same name but a .gz extension. If we find it,
  6839. * use that and set the gzipped flag in the file struct
  6840. * to indicate that the response need to have the content-
  6841. * encoding: gzip header.
  6842. * We can only do this if the browser declares support. */
  6843. if (conn->accept_gzip) {
  6844. mg_snprintf(
  6845. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6846. if (truncated) {
  6847. goto interpret_cleanup;
  6848. }
  6849. if (mg_stat(conn, gz_path, filestat)) {
  6850. if (filestat) {
  6851. filestat->is_gzipped = 1;
  6852. *is_found = 1;
  6853. }
  6854. /* Currently gz files can not be scripts. */
  6855. return;
  6856. }
  6857. }
  6858. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6859. /* Step 10: Script resources may handle sub-resources */
  6860. /* Support PATH_INFO for CGI scripts. */
  6861. tmp_str_len = strlen(filename);
  6862. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6863. if (!tmp_str) {
  6864. /* Out of memory */
  6865. goto interpret_cleanup;
  6866. }
  6867. memcpy(tmp_str, filename, tmp_str_len + 1);
  6868. /* Check config, if index scripts may have sub-resources */
  6869. allow_substitute_script_subresources =
  6870. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6871. "yes");
  6872. sep_pos = tmp_str_len;
  6873. while (sep_pos > 0) {
  6874. sep_pos--;
  6875. if (tmp_str[sep_pos] == '/') {
  6876. int is_script = 0, does_exist = 0;
  6877. tmp_str[sep_pos] = 0;
  6878. if (tmp_str[0]) {
  6879. is_script = extention_matches_script(conn, tmp_str);
  6880. does_exist = mg_stat(conn, tmp_str, filestat);
  6881. }
  6882. if (does_exist && is_script) {
  6883. filename[sep_pos] = 0;
  6884. memmove(filename + sep_pos + 2,
  6885. filename + sep_pos + 1,
  6886. strlen(filename + sep_pos + 1) + 1);
  6887. conn->path_info = filename + sep_pos + 1;
  6888. filename[sep_pos + 1] = '/';
  6889. *is_script_resource = 1;
  6890. *is_found = 1;
  6891. break;
  6892. }
  6893. if (allow_substitute_script_subresources) {
  6894. if (substitute_index_file(
  6895. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6896. /* some intermediate directory has an index file */
  6897. if (extention_matches_script(conn, tmp_str)) {
  6898. DEBUG_TRACE("Substitute script %s serving path %s",
  6899. tmp_str,
  6900. filename);
  6901. /* this index file is a script */
  6902. mg_snprintf(conn,
  6903. &truncated,
  6904. filename,
  6905. filename_buf_len,
  6906. "%s//%s",
  6907. tmp_str,
  6908. filename + sep_pos + 1);
  6909. if (truncated) {
  6910. mg_free(tmp_str);
  6911. goto interpret_cleanup;
  6912. }
  6913. sep_pos = strlen(tmp_str);
  6914. filename[sep_pos] = 0;
  6915. conn->path_info = filename + sep_pos + 1;
  6916. *is_script_resource = 1;
  6917. *is_found = 1;
  6918. break;
  6919. } else {
  6920. DEBUG_TRACE("Substitute file %s serving path %s",
  6921. tmp_str,
  6922. filename);
  6923. /* non-script files will not have sub-resources */
  6924. filename[sep_pos] = 0;
  6925. conn->path_info = 0;
  6926. *is_script_resource = 0;
  6927. *is_found = 0;
  6928. break;
  6929. }
  6930. }
  6931. }
  6932. tmp_str[sep_pos] = '/';
  6933. }
  6934. }
  6935. mg_free(tmp_str);
  6936. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6937. #endif /* !defined(NO_FILES) */
  6938. return;
  6939. #if !defined(NO_FILES)
  6940. /* Reset all outputs */
  6941. interpret_cleanup:
  6942. memset(filestat, 0, sizeof(*filestat));
  6943. *filename = 0;
  6944. *is_found = 0;
  6945. *is_script_resource = 0;
  6946. *is_websocket_request = 0;
  6947. *is_put_or_delete_request = 0;
  6948. #endif /* !defined(NO_FILES) */
  6949. }
  6950. /* Check whether full request is buffered. Return:
  6951. * -1 if request or response is malformed
  6952. * 0 if request or response is not yet fully buffered
  6953. * >0 actual request length, including last \r\n\r\n */
  6954. static int
  6955. get_http_header_len(const char *buf, int buflen)
  6956. {
  6957. int i;
  6958. for (i = 0; i < buflen; i++) {
  6959. /* Do an unsigned comparison in some conditions below */
  6960. const unsigned char c = (unsigned char)buf[i];
  6961. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6962. && !isprint(c)) {
  6963. /* abort scan as soon as one malformed character is found */
  6964. return -1;
  6965. }
  6966. if (i < buflen - 1) {
  6967. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6968. /* Two newline, no carriage return - not standard compliant,
  6969. * but it should be accepted */
  6970. return i + 2;
  6971. }
  6972. }
  6973. if (i < buflen - 3) {
  6974. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6975. && (buf[i + 3] == '\n')) {
  6976. /* Two \r\n - standard compliant */
  6977. return i + 4;
  6978. }
  6979. }
  6980. }
  6981. return 0;
  6982. }
  6983. #if !defined(NO_CACHING)
  6984. /* Convert month to the month number. Return -1 on error, or month number */
  6985. static int
  6986. get_month_index(const char *s)
  6987. {
  6988. size_t i;
  6989. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6990. if (!strcmp(s, month_names[i])) {
  6991. return (int)i;
  6992. }
  6993. }
  6994. return -1;
  6995. }
  6996. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6997. static time_t
  6998. parse_date_string(const char *datetime)
  6999. {
  7000. char month_str[32] = {0};
  7001. int second, minute, hour, day, month, year;
  7002. time_t result = (time_t)0;
  7003. struct tm tm;
  7004. if ((sscanf(datetime,
  7005. "%d/%3s/%d %d:%d:%d",
  7006. &day,
  7007. month_str,
  7008. &year,
  7009. &hour,
  7010. &minute,
  7011. &second)
  7012. == 6)
  7013. || (sscanf(datetime,
  7014. "%d %3s %d %d:%d:%d",
  7015. &day,
  7016. month_str,
  7017. &year,
  7018. &hour,
  7019. &minute,
  7020. &second)
  7021. == 6)
  7022. || (sscanf(datetime,
  7023. "%*3s, %d %3s %d %d:%d:%d",
  7024. &day,
  7025. month_str,
  7026. &year,
  7027. &hour,
  7028. &minute,
  7029. &second)
  7030. == 6)
  7031. || (sscanf(datetime,
  7032. "%d-%3s-%d %d:%d:%d",
  7033. &day,
  7034. month_str,
  7035. &year,
  7036. &hour,
  7037. &minute,
  7038. &second)
  7039. == 6)) {
  7040. month = get_month_index(month_str);
  7041. if ((month >= 0) && (year >= 1970)) {
  7042. memset(&tm, 0, sizeof(tm));
  7043. tm.tm_year = year - 1900;
  7044. tm.tm_mon = month;
  7045. tm.tm_mday = day;
  7046. tm.tm_hour = hour;
  7047. tm.tm_min = minute;
  7048. tm.tm_sec = second;
  7049. result = timegm(&tm);
  7050. }
  7051. }
  7052. return result;
  7053. }
  7054. #endif /* !NO_CACHING */
  7055. /* Pre-process URIs according to RFC + protect against directory disclosure
  7056. * attacks by removing '..', excessive '/' and '\' characters */
  7057. static void
  7058. remove_dot_segments(char *inout)
  7059. {
  7060. /* Windows backend protection
  7061. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7062. * in URI by slash */
  7063. char *out_end = inout;
  7064. char *in = inout;
  7065. if (!in) {
  7066. /* Param error. */
  7067. return;
  7068. }
  7069. while (*in) {
  7070. if (*in == '\\') {
  7071. *in = '/';
  7072. }
  7073. in++;
  7074. }
  7075. /* Algorithm "remove_dot_segments" from
  7076. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7077. /* Step 1:
  7078. * The input buffer is initialized.
  7079. * The output buffer is initialized to the empty string.
  7080. */
  7081. in = inout;
  7082. /* Step 2:
  7083. * While the input buffer is not empty, loop as follows:
  7084. */
  7085. /* Less than out_end of the inout buffer is used as output, so keep
  7086. * condition: out_end <= in */
  7087. while (*in) {
  7088. /* Step 2a:
  7089. * If the input buffer begins with a prefix of "../" or "./",
  7090. * then remove that prefix from the input buffer;
  7091. */
  7092. if (!strncmp(in, "../", 3)) {
  7093. in += 3;
  7094. } else if (!strncmp(in, "./", 2)) {
  7095. in += 2;
  7096. }
  7097. /* otherwise */
  7098. /* Step 2b:
  7099. * if the input buffer begins with a prefix of "/./" or "/.",
  7100. * where "." is a complete path segment, then replace that
  7101. * prefix with "/" in the input buffer;
  7102. */
  7103. else if (!strncmp(in, "/./", 3)) {
  7104. in += 2;
  7105. } else if (!strcmp(in, "/.")) {
  7106. in[1] = 0;
  7107. }
  7108. /* otherwise */
  7109. /* Step 2c:
  7110. * if the input buffer begins with a prefix of "/../" or "/..",
  7111. * where ".." is a complete path segment, then replace that
  7112. * prefix with "/" in the input buffer and remove the last
  7113. * segment and its preceding "/" (if any) from the output
  7114. * buffer;
  7115. */
  7116. else if (!strncmp(in, "/../", 4)) {
  7117. in += 3;
  7118. if (inout != out_end) {
  7119. /* remove last segment */
  7120. do {
  7121. out_end--;
  7122. } while ((inout != out_end) && (*out_end != '/'));
  7123. }
  7124. } else if (!strcmp(in, "/..")) {
  7125. in[1] = 0;
  7126. if (inout != out_end) {
  7127. /* remove last segment */
  7128. do {
  7129. out_end--;
  7130. } while ((inout != out_end) && (*out_end != '/'));
  7131. }
  7132. }
  7133. /* otherwise */
  7134. /* Step 2d:
  7135. * if the input buffer consists only of "." or "..", then remove
  7136. * that from the input buffer;
  7137. */
  7138. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7139. *in = 0;
  7140. }
  7141. /* otherwise */
  7142. /* Step 2e:
  7143. * move the first path segment in the input buffer to the end of
  7144. * the output buffer, including the initial "/" character (if
  7145. * any) and any subsequent characters up to, but not including,
  7146. * the next "/" character or the end of the input buffer.
  7147. */
  7148. else {
  7149. do {
  7150. *out_end = *in;
  7151. out_end++;
  7152. in++;
  7153. } while ((*in != 0) && (*in != '/'));
  7154. }
  7155. }
  7156. /* Step 3:
  7157. * Finally, the output buffer is returned as the result of
  7158. * remove_dot_segments.
  7159. */
  7160. /* Terminate output */
  7161. *out_end = 0;
  7162. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7163. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7164. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7165. * or "//" anymore.
  7166. */
  7167. out_end = in = inout;
  7168. while (*in) {
  7169. if (*in == '.') {
  7170. /* remove . at the end or preceding of / */
  7171. char *in_ahead = in;
  7172. do {
  7173. in_ahead++;
  7174. } while (*in_ahead == '.');
  7175. if (*in_ahead == '/') {
  7176. in = in_ahead;
  7177. if ((out_end != inout) && (out_end[-1] == '/')) {
  7178. /* remove generated // */
  7179. out_end--;
  7180. }
  7181. } else if (*in_ahead == 0) {
  7182. in = in_ahead;
  7183. } else {
  7184. do {
  7185. *out_end++ = '.';
  7186. in++;
  7187. } while (in != in_ahead);
  7188. }
  7189. } else if (*in == '/') {
  7190. /* replace // by / */
  7191. *out_end++ = '/';
  7192. do {
  7193. in++;
  7194. } while (*in == '/');
  7195. } else {
  7196. *out_end++ = *in;
  7197. in++;
  7198. }
  7199. }
  7200. *out_end = 0;
  7201. }
  7202. static const struct {
  7203. const char *extension;
  7204. size_t ext_len;
  7205. const char *mime_type;
  7206. } builtin_mime_types[] = {
  7207. /* IANA registered MIME types
  7208. * (http://www.iana.org/assignments/media-types)
  7209. * application types */
  7210. {".doc", 4, "application/msword"},
  7211. {".eps", 4, "application/postscript"},
  7212. {".exe", 4, "application/octet-stream"},
  7213. {".js", 3, "application/javascript"},
  7214. {".json", 5, "application/json"},
  7215. {".pdf", 4, "application/pdf"},
  7216. {".ps", 3, "application/postscript"},
  7217. {".rtf", 4, "application/rtf"},
  7218. {".xhtml", 6, "application/xhtml+xml"},
  7219. {".xsl", 4, "application/xml"},
  7220. {".xslt", 5, "application/xml"},
  7221. /* fonts */
  7222. {".ttf", 4, "application/font-sfnt"},
  7223. {".cff", 4, "application/font-sfnt"},
  7224. {".otf", 4, "application/font-sfnt"},
  7225. {".aat", 4, "application/font-sfnt"},
  7226. {".sil", 4, "application/font-sfnt"},
  7227. {".pfr", 4, "application/font-tdpfr"},
  7228. {".woff", 5, "application/font-woff"},
  7229. /* audio */
  7230. {".mp3", 4, "audio/mpeg"},
  7231. {".oga", 4, "audio/ogg"},
  7232. {".ogg", 4, "audio/ogg"},
  7233. /* image */
  7234. {".gif", 4, "image/gif"},
  7235. {".ief", 4, "image/ief"},
  7236. {".jpeg", 5, "image/jpeg"},
  7237. {".jpg", 4, "image/jpeg"},
  7238. {".jpm", 4, "image/jpm"},
  7239. {".jpx", 4, "image/jpx"},
  7240. {".png", 4, "image/png"},
  7241. {".svg", 4, "image/svg+xml"},
  7242. {".tif", 4, "image/tiff"},
  7243. {".tiff", 5, "image/tiff"},
  7244. /* model */
  7245. {".wrl", 4, "model/vrml"},
  7246. /* text */
  7247. {".css", 4, "text/css"},
  7248. {".csv", 4, "text/csv"},
  7249. {".htm", 4, "text/html"},
  7250. {".html", 5, "text/html"},
  7251. {".sgm", 4, "text/sgml"},
  7252. {".shtm", 5, "text/html"},
  7253. {".shtml", 6, "text/html"},
  7254. {".txt", 4, "text/plain"},
  7255. {".xml", 4, "text/xml"},
  7256. /* video */
  7257. {".mov", 4, "video/quicktime"},
  7258. {".mp4", 4, "video/mp4"},
  7259. {".mpeg", 5, "video/mpeg"},
  7260. {".mpg", 4, "video/mpeg"},
  7261. {".ogv", 4, "video/ogg"},
  7262. {".qt", 3, "video/quicktime"},
  7263. /* not registered types
  7264. * (http://reference.sitepoint.com/html/mime-types-full,
  7265. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7266. {".arj", 4, "application/x-arj-compressed"},
  7267. {".gz", 3, "application/x-gunzip"},
  7268. {".rar", 4, "application/x-arj-compressed"},
  7269. {".swf", 4, "application/x-shockwave-flash"},
  7270. {".tar", 4, "application/x-tar"},
  7271. {".tgz", 4, "application/x-tar-gz"},
  7272. {".torrent", 8, "application/x-bittorrent"},
  7273. {".ppt", 4, "application/x-mspowerpoint"},
  7274. {".xls", 4, "application/x-msexcel"},
  7275. {".zip", 4, "application/x-zip-compressed"},
  7276. {".aac",
  7277. 4,
  7278. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7279. {".aif", 4, "audio/x-aif"},
  7280. {".m3u", 4, "audio/x-mpegurl"},
  7281. {".mid", 4, "audio/x-midi"},
  7282. {".ra", 3, "audio/x-pn-realaudio"},
  7283. {".ram", 4, "audio/x-pn-realaudio"},
  7284. {".wav", 4, "audio/x-wav"},
  7285. {".bmp", 4, "image/bmp"},
  7286. {".ico", 4, "image/x-icon"},
  7287. {".pct", 4, "image/x-pct"},
  7288. {".pict", 5, "image/pict"},
  7289. {".rgb", 4, "image/x-rgb"},
  7290. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7291. {".asf", 4, "video/x-ms-asf"},
  7292. {".avi", 4, "video/x-msvideo"},
  7293. {".m4v", 4, "video/x-m4v"},
  7294. {NULL, 0, NULL}};
  7295. const char *
  7296. mg_get_builtin_mime_type(const char *path)
  7297. {
  7298. const char *ext;
  7299. size_t i, path_len;
  7300. path_len = strlen(path);
  7301. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7302. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7303. if ((path_len > builtin_mime_types[i].ext_len)
  7304. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7305. return builtin_mime_types[i].mime_type;
  7306. }
  7307. }
  7308. return "text/plain";
  7309. }
  7310. /* Look at the "path" extension and figure what mime type it has.
  7311. * Store mime type in the vector. */
  7312. static void
  7313. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7314. {
  7315. struct vec ext_vec, mime_vec;
  7316. const char *list, *ext;
  7317. size_t path_len;
  7318. path_len = strlen(path);
  7319. if ((conn == NULL) || (vec == NULL)) {
  7320. if (vec != NULL) {
  7321. memset(vec, '\0', sizeof(struct vec));
  7322. }
  7323. return;
  7324. }
  7325. /* Scan user-defined mime types first, in case user wants to
  7326. * override default mime types. */
  7327. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7328. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7329. /* ext now points to the path suffix */
  7330. ext = path + path_len - ext_vec.len;
  7331. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7332. *vec = mime_vec;
  7333. return;
  7334. }
  7335. }
  7336. vec->ptr = mg_get_builtin_mime_type(path);
  7337. vec->len = strlen(vec->ptr);
  7338. }
  7339. /* Stringify binary data. Output buffer must be twice as big as input,
  7340. * because each byte takes 2 bytes in string representation */
  7341. static void
  7342. bin2str(char *to, const unsigned char *p, size_t len)
  7343. {
  7344. static const char *hex = "0123456789abcdef";
  7345. for (; len--; p++) {
  7346. *to++ = hex[p[0] >> 4];
  7347. *to++ = hex[p[0] & 0x0f];
  7348. }
  7349. *to = '\0';
  7350. }
  7351. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7352. */
  7353. char *
  7354. mg_md5(char buf[33], ...)
  7355. {
  7356. md5_byte_t hash[16];
  7357. const char *p;
  7358. va_list ap;
  7359. md5_state_t ctx;
  7360. md5_init(&ctx);
  7361. va_start(ap, buf);
  7362. while ((p = va_arg(ap, const char *)) != NULL) {
  7363. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7364. }
  7365. va_end(ap);
  7366. md5_finish(&ctx, hash);
  7367. bin2str(buf, hash, sizeof(hash));
  7368. return buf;
  7369. }
  7370. /* Check the user's password, return 1 if OK */
  7371. static int
  7372. check_password(const char *method,
  7373. const char *ha1,
  7374. const char *uri,
  7375. const char *nonce,
  7376. const char *nc,
  7377. const char *cnonce,
  7378. const char *qop,
  7379. const char *response)
  7380. {
  7381. char ha2[32 + 1], expected_response[32 + 1];
  7382. /* Some of the parameters may be NULL */
  7383. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7384. || (qop == NULL) || (response == NULL)) {
  7385. return 0;
  7386. }
  7387. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7388. if (strlen(response) != 32) {
  7389. return 0;
  7390. }
  7391. mg_md5(ha2, method, ":", uri, NULL);
  7392. mg_md5(expected_response,
  7393. ha1,
  7394. ":",
  7395. nonce,
  7396. ":",
  7397. nc,
  7398. ":",
  7399. cnonce,
  7400. ":",
  7401. qop,
  7402. ":",
  7403. ha2,
  7404. NULL);
  7405. return mg_strcasecmp(response, expected_response) == 0;
  7406. }
  7407. #if !defined(NO_FILESYSTEMS)
  7408. /* Use the global passwords file, if specified by auth_gpass option,
  7409. * or search for .htpasswd in the requested directory. */
  7410. static void
  7411. open_auth_file(struct mg_connection *conn,
  7412. const char *path,
  7413. struct mg_file *filep)
  7414. {
  7415. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7416. char name[PATH_MAX];
  7417. const char *p, *e,
  7418. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7419. int truncated;
  7420. if (gpass != NULL) {
  7421. /* Use global passwords file */
  7422. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7423. #if defined(DEBUG)
  7424. /* Use mg_cry_internal here, since gpass has been
  7425. * configured. */
  7426. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7427. #endif
  7428. }
  7429. /* Important: using local struct mg_file to test path for
  7430. * is_directory flag. If filep is used, mg_stat() makes it
  7431. * appear as if auth file was opened.
  7432. * TODO(mid): Check if this is still required after rewriting
  7433. * mg_stat */
  7434. } else if (mg_stat(conn, path, &filep->stat)
  7435. && filep->stat.is_directory) {
  7436. mg_snprintf(conn,
  7437. &truncated,
  7438. name,
  7439. sizeof(name),
  7440. "%s/%s",
  7441. path,
  7442. PASSWORDS_FILE_NAME);
  7443. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7444. #if defined(DEBUG)
  7445. /* Don't use mg_cry_internal here, but only a trace, since
  7446. * this is a typical case. It will occur for every directory
  7447. * without a password file. */
  7448. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7449. #endif
  7450. }
  7451. } else {
  7452. /* Try to find .htpasswd in requested directory. */
  7453. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7454. if (e[0] == '/') {
  7455. break;
  7456. }
  7457. }
  7458. mg_snprintf(conn,
  7459. &truncated,
  7460. name,
  7461. sizeof(name),
  7462. "%.*s/%s",
  7463. (int)(e - p),
  7464. p,
  7465. PASSWORDS_FILE_NAME);
  7466. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7467. #if defined(DEBUG)
  7468. /* Don't use mg_cry_internal here, but only a trace, since
  7469. * this is a typical case. It will occur for every directory
  7470. * without a password file. */
  7471. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7472. #endif
  7473. }
  7474. }
  7475. }
  7476. }
  7477. #endif /* NO_FILESYSTEMS */
  7478. /* Parsed Authorization header */
  7479. struct ah {
  7480. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7481. };
  7482. /* Return 1 on success. Always initializes the ah structure. */
  7483. static int
  7484. parse_auth_header(struct mg_connection *conn,
  7485. char *buf,
  7486. size_t buf_size,
  7487. struct ah *ah)
  7488. {
  7489. char *name, *value, *s;
  7490. const char *auth_header;
  7491. uint64_t nonce;
  7492. if (!ah || !conn) {
  7493. return 0;
  7494. }
  7495. (void)memset(ah, 0, sizeof(*ah));
  7496. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7497. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7498. return 0;
  7499. }
  7500. /* Make modifiable copy of the auth header */
  7501. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7502. s = buf;
  7503. /* Parse authorization header */
  7504. for (;;) {
  7505. /* Gobble initial spaces */
  7506. while (isspace((unsigned char)*s)) {
  7507. s++;
  7508. }
  7509. name = skip_quoted(&s, "=", " ", 0);
  7510. /* Value is either quote-delimited, or ends at first comma or space.
  7511. */
  7512. if (s[0] == '\"') {
  7513. s++;
  7514. value = skip_quoted(&s, "\"", " ", '\\');
  7515. if (s[0] == ',') {
  7516. s++;
  7517. }
  7518. } else {
  7519. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7520. * uses spaces */
  7521. }
  7522. if (*name == '\0') {
  7523. break;
  7524. }
  7525. if (!strcmp(name, "username")) {
  7526. ah->user = value;
  7527. } else if (!strcmp(name, "cnonce")) {
  7528. ah->cnonce = value;
  7529. } else if (!strcmp(name, "response")) {
  7530. ah->response = value;
  7531. } else if (!strcmp(name, "uri")) {
  7532. ah->uri = value;
  7533. } else if (!strcmp(name, "qop")) {
  7534. ah->qop = value;
  7535. } else if (!strcmp(name, "nc")) {
  7536. ah->nc = value;
  7537. } else if (!strcmp(name, "nonce")) {
  7538. ah->nonce = value;
  7539. }
  7540. }
  7541. #if !defined(NO_NONCE_CHECK)
  7542. /* Read the nonce from the response. */
  7543. if (ah->nonce == NULL) {
  7544. return 0;
  7545. }
  7546. s = NULL;
  7547. nonce = strtoull(ah->nonce, &s, 10);
  7548. if ((s == NULL) || (*s != 0)) {
  7549. return 0;
  7550. }
  7551. /* Convert the nonce from the client to a number. */
  7552. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7553. /* The converted number corresponds to the time the nounce has been
  7554. * created. This should not be earlier than the server start. */
  7555. /* Server side nonce check is valuable in all situations but one:
  7556. * if the server restarts frequently, but the client should not see
  7557. * that, so the server should accept nonces from previous starts. */
  7558. /* However, the reasonable default is to not accept a nonce from a
  7559. * previous start, so if anyone changed the access rights between
  7560. * two restarts, a new login is required. */
  7561. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7562. /* nonce is from a previous start of the server and no longer valid
  7563. * (replay attack?) */
  7564. return 0;
  7565. }
  7566. /* Check if the nonce is too high, so it has not (yet) been used by the
  7567. * server. */
  7568. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7569. + conn->dom_ctx->nonce_count)) {
  7570. return 0;
  7571. }
  7572. #else
  7573. (void)nonce;
  7574. #endif
  7575. /* CGI needs it as REMOTE_USER */
  7576. if (ah->user != NULL) {
  7577. conn->request_info.remote_user =
  7578. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7579. } else {
  7580. return 0;
  7581. }
  7582. return 1;
  7583. }
  7584. static const char *
  7585. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7586. {
  7587. #if defined(MG_USE_OPEN_FILE)
  7588. const char *eof;
  7589. size_t len;
  7590. const char *memend;
  7591. #else
  7592. (void)p; /* parameter is unused */
  7593. #endif
  7594. if (!filep) {
  7595. return NULL;
  7596. }
  7597. #if defined(MG_USE_OPEN_FILE)
  7598. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7599. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7600. /* Search for \n from p till the end of stream */
  7601. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7602. if (eof != NULL) {
  7603. eof += 1; /* Include \n */
  7604. } else {
  7605. eof = memend; /* Copy remaining data */
  7606. }
  7607. len =
  7608. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7609. memcpy(buf, *p, len);
  7610. buf[len] = '\0';
  7611. *p += len;
  7612. return len ? eof : NULL;
  7613. } else /* filep->access.fp block below */
  7614. #endif
  7615. if (filep->access.fp != NULL) {
  7616. return fgets(buf, (int)size, filep->access.fp);
  7617. } else {
  7618. return NULL;
  7619. }
  7620. }
  7621. /* Define the initial recursion depth for procesesing htpasswd files that
  7622. * include other htpasswd
  7623. * (or even the same) files. It is not difficult to provide a file or files
  7624. * s.t. they force civetweb
  7625. * to infinitely recurse and then crash.
  7626. */
  7627. #define INITIAL_DEPTH 9
  7628. #if INITIAL_DEPTH <= 0
  7629. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7630. #endif
  7631. #if !defined(NO_FILESYSTEMS)
  7632. struct read_auth_file_struct {
  7633. struct mg_connection *conn;
  7634. struct ah ah;
  7635. const char *domain;
  7636. char buf[256 + 256 + 40];
  7637. const char *f_user;
  7638. const char *f_domain;
  7639. const char *f_ha1;
  7640. };
  7641. static int
  7642. read_auth_file(struct mg_file *filep,
  7643. struct read_auth_file_struct *workdata,
  7644. int depth)
  7645. {
  7646. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7647. int is_authorized = 0;
  7648. struct mg_file fp;
  7649. size_t l;
  7650. if (!filep || !workdata || (0 == depth)) {
  7651. return 0;
  7652. }
  7653. /* Loop over passwords file */
  7654. #if defined(MG_USE_OPEN_FILE)
  7655. p = (char *)filep->access.membuf;
  7656. #endif
  7657. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7658. l = strlen(workdata->buf);
  7659. while (l > 0) {
  7660. if (isspace((unsigned char)workdata->buf[l - 1])
  7661. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7662. l--;
  7663. workdata->buf[l] = 0;
  7664. } else
  7665. break;
  7666. }
  7667. if (l < 1) {
  7668. continue;
  7669. }
  7670. workdata->f_user = workdata->buf;
  7671. if (workdata->f_user[0] == ':') {
  7672. /* user names may not contain a ':' and may not be empty,
  7673. * so lines starting with ':' may be used for a special purpose
  7674. */
  7675. if (workdata->f_user[1] == '#') {
  7676. /* :# is a comment */
  7677. continue;
  7678. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7679. if (mg_fopen(workdata->conn,
  7680. workdata->f_user + 9,
  7681. MG_FOPEN_MODE_READ,
  7682. &fp)) {
  7683. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7684. (void)mg_fclose(
  7685. &fp.access); /* ignore error on read only file */
  7686. /* No need to continue processing files once we have a
  7687. * match, since nothing will reset it back
  7688. * to 0.
  7689. */
  7690. if (is_authorized) {
  7691. return is_authorized;
  7692. }
  7693. } else {
  7694. mg_cry_internal(workdata->conn,
  7695. "%s: cannot open authorization file: %s",
  7696. __func__,
  7697. workdata->buf);
  7698. }
  7699. continue;
  7700. }
  7701. /* everything is invalid for the moment (might change in the
  7702. * future) */
  7703. mg_cry_internal(workdata->conn,
  7704. "%s: syntax error in authorization file: %s",
  7705. __func__,
  7706. workdata->buf);
  7707. continue;
  7708. }
  7709. workdata->f_domain = strchr(workdata->f_user, ':');
  7710. if (workdata->f_domain == NULL) {
  7711. mg_cry_internal(workdata->conn,
  7712. "%s: syntax error in authorization file: %s",
  7713. __func__,
  7714. workdata->buf);
  7715. continue;
  7716. }
  7717. *(char *)(workdata->f_domain) = 0;
  7718. (workdata->f_domain)++;
  7719. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7720. if (workdata->f_ha1 == NULL) {
  7721. mg_cry_internal(workdata->conn,
  7722. "%s: syntax error in authorization file: %s",
  7723. __func__,
  7724. workdata->buf);
  7725. continue;
  7726. }
  7727. *(char *)(workdata->f_ha1) = 0;
  7728. (workdata->f_ha1)++;
  7729. if (!strcmp(workdata->ah.user, workdata->f_user)
  7730. && !strcmp(workdata->domain, workdata->f_domain)) {
  7731. return check_password(workdata->conn->request_info.request_method,
  7732. workdata->f_ha1,
  7733. workdata->ah.uri,
  7734. workdata->ah.nonce,
  7735. workdata->ah.nc,
  7736. workdata->ah.cnonce,
  7737. workdata->ah.qop,
  7738. workdata->ah.response);
  7739. }
  7740. }
  7741. return is_authorized;
  7742. }
  7743. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7744. static int
  7745. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7746. {
  7747. struct read_auth_file_struct workdata;
  7748. char buf[MG_BUF_LEN];
  7749. if (!conn || !conn->dom_ctx) {
  7750. return 0;
  7751. }
  7752. memset(&workdata, 0, sizeof(workdata));
  7753. workdata.conn = conn;
  7754. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7755. return 0;
  7756. }
  7757. if (realm) {
  7758. workdata.domain = realm;
  7759. } else {
  7760. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7761. }
  7762. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7763. }
  7764. /* Public function to check http digest authentication header */
  7765. int
  7766. mg_check_digest_access_authentication(struct mg_connection *conn,
  7767. const char *realm,
  7768. const char *filename)
  7769. {
  7770. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7771. int auth;
  7772. if (!conn || !filename) {
  7773. return -1;
  7774. }
  7775. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7776. return -2;
  7777. }
  7778. auth = authorize(conn, &file, realm);
  7779. mg_fclose(&file.access);
  7780. return auth;
  7781. }
  7782. #endif /* NO_FILESYSTEMS */
  7783. /* Return 1 if request is authorised, 0 otherwise. */
  7784. static int
  7785. check_authorization(struct mg_connection *conn, const char *path)
  7786. {
  7787. #if !defined(NO_FILESYSTEMS)
  7788. char fname[PATH_MAX];
  7789. struct vec uri_vec, filename_vec;
  7790. const char *list;
  7791. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7792. int authorized = 1, truncated;
  7793. if (!conn || !conn->dom_ctx) {
  7794. return 0;
  7795. }
  7796. list = conn->dom_ctx->config[PROTECT_URI];
  7797. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7798. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7799. mg_snprintf(conn,
  7800. &truncated,
  7801. fname,
  7802. sizeof(fname),
  7803. "%.*s",
  7804. (int)filename_vec.len,
  7805. filename_vec.ptr);
  7806. if (truncated
  7807. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7808. mg_cry_internal(conn,
  7809. "%s: cannot open %s: %s",
  7810. __func__,
  7811. fname,
  7812. strerror(errno));
  7813. }
  7814. break;
  7815. }
  7816. }
  7817. if (!is_file_opened(&file.access)) {
  7818. open_auth_file(conn, path, &file);
  7819. }
  7820. if (is_file_opened(&file.access)) {
  7821. authorized = authorize(conn, &file, NULL);
  7822. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7823. }
  7824. return authorized;
  7825. #else
  7826. (void)conn;
  7827. (void)path;
  7828. return 1;
  7829. #endif /* NO_FILESYSTEMS */
  7830. }
  7831. /* Internal function. Assumes conn is valid */
  7832. static void
  7833. send_authorization_request(struct mg_connection *conn, const char *realm)
  7834. {
  7835. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7836. int trunc = 0;
  7837. char buf[128];
  7838. if (!realm) {
  7839. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7840. }
  7841. mg_lock_context(conn->phys_ctx);
  7842. nonce += conn->dom_ctx->nonce_count;
  7843. ++conn->dom_ctx->nonce_count;
  7844. mg_unlock_context(conn->phys_ctx);
  7845. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7846. conn->must_close = 1;
  7847. /* Create 401 response */
  7848. mg_response_start(conn, 401);
  7849. send_no_cache_header(conn);
  7850. send_additional_header(conn);
  7851. mg_response_add_header(conn, "Content-Length", "0", -1);
  7852. /* Content for "WWW-Authenticate" header */
  7853. mg_snprintf(conn,
  7854. &trunc,
  7855. buf,
  7856. sizeof(buf),
  7857. "Digest qop=\"auth\", realm=\"%s\", "
  7858. "nonce=\"%" UINT64_FMT "\"",
  7859. realm,
  7860. nonce);
  7861. if (!trunc) {
  7862. /* !trunc should always be true */
  7863. mg_response_add_header(conn, "WWW-Authenticate", buf, -1);
  7864. }
  7865. /* Send all headers */
  7866. mg_response_send_headers(conn);
  7867. }
  7868. /* Interface function. Parameters are provided by the user, so do
  7869. * at least some basic checks.
  7870. */
  7871. int
  7872. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7873. const char *realm)
  7874. {
  7875. if (conn && conn->dom_ctx) {
  7876. send_authorization_request(conn, realm);
  7877. return 0;
  7878. }
  7879. return -1;
  7880. }
  7881. #if !defined(NO_FILES)
  7882. static int
  7883. is_authorized_for_put(struct mg_connection *conn)
  7884. {
  7885. if (conn) {
  7886. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7887. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7888. int ret = 0;
  7889. if (passfile != NULL
  7890. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7891. ret = authorize(conn, &file, NULL);
  7892. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7893. }
  7894. return ret;
  7895. }
  7896. return 0;
  7897. }
  7898. #endif
  7899. int
  7900. mg_modify_passwords_file(const char *fname,
  7901. const char *domain,
  7902. const char *user,
  7903. const char *pass)
  7904. {
  7905. int found, i;
  7906. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7907. FILE *fp, *fp2;
  7908. found = 0;
  7909. fp = fp2 = NULL;
  7910. /* Regard empty password as no password - remove user record. */
  7911. if ((pass != NULL) && (pass[0] == '\0')) {
  7912. pass = NULL;
  7913. }
  7914. /* Other arguments must not be empty */
  7915. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7916. return 0;
  7917. }
  7918. /* Using the given file format, user name and domain must not contain
  7919. * ':'
  7920. */
  7921. if (strchr(user, ':') != NULL) {
  7922. return 0;
  7923. }
  7924. if (strchr(domain, ':') != NULL) {
  7925. return 0;
  7926. }
  7927. /* Do not allow control characters like newline in user name and domain.
  7928. * Do not allow excessively long names either. */
  7929. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7930. if (iscntrl((unsigned char)user[i])) {
  7931. return 0;
  7932. }
  7933. }
  7934. if (user[i]) {
  7935. return 0;
  7936. }
  7937. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7938. if (iscntrl((unsigned char)domain[i])) {
  7939. return 0;
  7940. }
  7941. }
  7942. if (domain[i]) {
  7943. return 0;
  7944. }
  7945. /* The maximum length of the path to the password file is limited */
  7946. if ((strlen(fname) + 4) >= PATH_MAX) {
  7947. return 0;
  7948. }
  7949. /* Create a temporary file name. Length has been checked before. */
  7950. strcpy(tmp, fname);
  7951. strcat(tmp, ".tmp");
  7952. /* Create the file if does not exist */
  7953. /* Use of fopen here is OK, since fname is only ASCII */
  7954. if ((fp = fopen(fname, "a+")) != NULL) {
  7955. (void)fclose(fp);
  7956. }
  7957. /* Open the given file and temporary file */
  7958. if ((fp = fopen(fname, "r")) == NULL) {
  7959. return 0;
  7960. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7961. fclose(fp);
  7962. return 0;
  7963. }
  7964. /* Copy the stuff to temporary file */
  7965. while (fgets(line, sizeof(line), fp) != NULL) {
  7966. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7967. continue;
  7968. }
  7969. u[255] = 0;
  7970. d[255] = 0;
  7971. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7972. found++;
  7973. if (pass != NULL) {
  7974. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7975. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7976. }
  7977. } else {
  7978. fprintf(fp2, "%s", line);
  7979. }
  7980. }
  7981. /* If new user, just add it */
  7982. if (!found && (pass != NULL)) {
  7983. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7984. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7985. }
  7986. /* Close files */
  7987. fclose(fp);
  7988. fclose(fp2);
  7989. /* Put the temp file in place of real file */
  7990. IGNORE_UNUSED_RESULT(remove(fname));
  7991. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7992. return 1;
  7993. }
  7994. static int
  7995. is_valid_port(unsigned long port)
  7996. {
  7997. return (port <= 0xffff);
  7998. }
  7999. static int
  8000. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  8001. {
  8002. struct addrinfo hints, *res, *ressave;
  8003. int func_ret = 0;
  8004. int gai_ret;
  8005. memset(&hints, 0, sizeof(struct addrinfo));
  8006. hints.ai_family = af;
  8007. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8008. if (gai_ret != 0) {
  8009. /* gai_strerror could be used to convert gai_ret to a string */
  8010. /* POSIX return values: see
  8011. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8012. */
  8013. /* Windows return values: see
  8014. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8015. */
  8016. return 0;
  8017. }
  8018. ressave = res;
  8019. while (res) {
  8020. if (dstlen >= (size_t)res->ai_addrlen) {
  8021. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8022. func_ret = 1;
  8023. }
  8024. res = res->ai_next;
  8025. }
  8026. freeaddrinfo(ressave);
  8027. return func_ret;
  8028. }
  8029. static int
  8030. connect_socket(struct mg_context *ctx /* may be NULL */,
  8031. const char *host,
  8032. int port,
  8033. int use_ssl,
  8034. char *ebuf,
  8035. size_t ebuf_len,
  8036. SOCKET *sock /* output: socket, must not be NULL */,
  8037. union usa *sa /* output: socket address, must not be NULL */
  8038. )
  8039. {
  8040. int ip_ver = 0;
  8041. int conn_ret = -1;
  8042. int sockerr = 0;
  8043. *sock = INVALID_SOCKET;
  8044. memset(sa, 0, sizeof(*sa));
  8045. if (ebuf_len > 0) {
  8046. *ebuf = 0;
  8047. }
  8048. if (host == NULL) {
  8049. mg_snprintf(NULL,
  8050. NULL, /* No truncation check for ebuf */
  8051. ebuf,
  8052. ebuf_len,
  8053. "%s",
  8054. "NULL host");
  8055. return 0;
  8056. }
  8057. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8058. mg_snprintf(NULL,
  8059. NULL, /* No truncation check for ebuf */
  8060. ebuf,
  8061. ebuf_len,
  8062. "%s",
  8063. "invalid port");
  8064. return 0;
  8065. }
  8066. #if !defined(NO_SSL)
  8067. #if !defined(NO_SSL_DL)
  8068. #if defined(OPENSSL_API_1_1)
  8069. if (use_ssl && (TLS_client_method == NULL)) {
  8070. mg_snprintf(NULL,
  8071. NULL, /* No truncation check for ebuf */
  8072. ebuf,
  8073. ebuf_len,
  8074. "%s",
  8075. "SSL is not initialized");
  8076. return 0;
  8077. }
  8078. #else
  8079. if (use_ssl && (SSLv23_client_method == NULL)) {
  8080. mg_snprintf(NULL,
  8081. NULL, /* No truncation check for ebuf */
  8082. ebuf,
  8083. ebuf_len,
  8084. "%s",
  8085. "SSL is not initialized");
  8086. return 0;
  8087. }
  8088. #endif /* OPENSSL_API_1_1 */
  8089. #else
  8090. (void)use_ssl;
  8091. #endif /* NO_SSL_DL */
  8092. #else
  8093. (void)use_ssl;
  8094. #endif /* !defined(NO_SSL) */
  8095. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  8096. sa->sin.sin_family = AF_INET;
  8097. sa->sin.sin_port = htons((uint16_t)port);
  8098. ip_ver = 4;
  8099. #if defined(USE_IPV6)
  8100. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  8101. sa->sin6.sin6_family = AF_INET6;
  8102. sa->sin6.sin6_port = htons((uint16_t)port);
  8103. ip_ver = 6;
  8104. } else if (host[0] == '[') {
  8105. /* While getaddrinfo on Windows will work with [::1],
  8106. * getaddrinfo on Linux only works with ::1 (without []). */
  8107. size_t l = strlen(host + 1);
  8108. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8109. if (h) {
  8110. h[l - 1] = 0;
  8111. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  8112. sa->sin6.sin6_family = AF_INET6;
  8113. sa->sin6.sin6_port = htons((uint16_t)port);
  8114. ip_ver = 6;
  8115. }
  8116. mg_free(h);
  8117. }
  8118. #endif
  8119. }
  8120. if (ip_ver == 0) {
  8121. mg_snprintf(NULL,
  8122. NULL, /* No truncation check for ebuf */
  8123. ebuf,
  8124. ebuf_len,
  8125. "%s",
  8126. "host not found");
  8127. return 0;
  8128. }
  8129. if (ip_ver == 4) {
  8130. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8131. }
  8132. #if defined(USE_IPV6)
  8133. else if (ip_ver == 6) {
  8134. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8135. }
  8136. #endif
  8137. if (*sock == INVALID_SOCKET) {
  8138. mg_snprintf(NULL,
  8139. NULL, /* No truncation check for ebuf */
  8140. ebuf,
  8141. ebuf_len,
  8142. "socket(): %s",
  8143. strerror(ERRNO));
  8144. return 0;
  8145. }
  8146. if (0 != set_non_blocking_mode(*sock)) {
  8147. mg_snprintf(NULL,
  8148. NULL, /* No truncation check for ebuf */
  8149. ebuf,
  8150. ebuf_len,
  8151. "Cannot set socket to non-blocking: %s",
  8152. strerror(ERRNO));
  8153. closesocket(*sock);
  8154. *sock = INVALID_SOCKET;
  8155. return 0;
  8156. }
  8157. set_close_on_exec(*sock, NULL, ctx);
  8158. if (ip_ver == 4) {
  8159. /* connected with IPv4 */
  8160. conn_ret = connect(*sock,
  8161. (struct sockaddr *)((void *)&sa->sin),
  8162. sizeof(sa->sin));
  8163. }
  8164. #if defined(USE_IPV6)
  8165. else if (ip_ver == 6) {
  8166. /* connected with IPv6 */
  8167. conn_ret = connect(*sock,
  8168. (struct sockaddr *)((void *)&sa->sin6),
  8169. sizeof(sa->sin6));
  8170. }
  8171. #endif
  8172. if (conn_ret != 0) {
  8173. sockerr = ERRNO;
  8174. }
  8175. #if defined(_WIN32)
  8176. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8177. #else
  8178. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8179. #endif
  8180. /* Data for getsockopt */
  8181. void *psockerr = &sockerr;
  8182. int ret;
  8183. #if defined(_WIN32)
  8184. int len = (int)sizeof(sockerr);
  8185. #else
  8186. socklen_t len = (socklen_t)sizeof(sockerr);
  8187. #endif
  8188. /* Data for poll */
  8189. struct mg_pollfd pfd[1];
  8190. int pollres;
  8191. int ms_wait = 10000; /* 10 second timeout */
  8192. stop_flag_t nonstop;
  8193. STOP_FLAG_ASSIGN(&nonstop, 0);
  8194. /* For a non-blocking socket, the connect sequence is:
  8195. * 1) call connect (will not block)
  8196. * 2) wait until the socket is ready for writing (select or poll)
  8197. * 3) check connection state with getsockopt
  8198. */
  8199. pfd[0].fd = *sock;
  8200. pfd[0].events = POLLOUT;
  8201. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8202. if (pollres != 1) {
  8203. /* Not connected */
  8204. mg_snprintf(NULL,
  8205. NULL, /* No truncation check for ebuf */
  8206. ebuf,
  8207. ebuf_len,
  8208. "connect(%s:%d): timeout",
  8209. host,
  8210. port);
  8211. closesocket(*sock);
  8212. *sock = INVALID_SOCKET;
  8213. return 0;
  8214. }
  8215. #if defined(_WIN32)
  8216. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8217. #else
  8218. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8219. #endif
  8220. if ((ret == 0) && (sockerr == 0)) {
  8221. conn_ret = 0;
  8222. }
  8223. }
  8224. if (conn_ret != 0) {
  8225. /* Not connected */
  8226. mg_snprintf(NULL,
  8227. NULL, /* No truncation check for ebuf */
  8228. ebuf,
  8229. ebuf_len,
  8230. "connect(%s:%d): error %s",
  8231. host,
  8232. port,
  8233. strerror(sockerr));
  8234. closesocket(*sock);
  8235. *sock = INVALID_SOCKET;
  8236. return 0;
  8237. }
  8238. return 1;
  8239. }
  8240. int
  8241. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8242. {
  8243. static const char *dont_escape = "._-$,;~()";
  8244. static const char *hex = "0123456789abcdef";
  8245. char *pos = dst;
  8246. const char *end = dst + dst_len - 1;
  8247. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8248. if (isalnum((unsigned char)*src)
  8249. || (strchr(dont_escape, *src) != NULL)) {
  8250. *pos = *src;
  8251. } else if (pos + 2 < end) {
  8252. pos[0] = '%';
  8253. pos[1] = hex[(unsigned char)*src >> 4];
  8254. pos[2] = hex[(unsigned char)*src & 0xf];
  8255. pos += 2;
  8256. } else {
  8257. break;
  8258. }
  8259. }
  8260. *pos = '\0';
  8261. return (*src == '\0') ? (int)(pos - dst) : -1;
  8262. }
  8263. /* Return 0 on success, non-zero if an error occurs. */
  8264. static int
  8265. print_dir_entry(struct de *de)
  8266. {
  8267. size_t namesize, escsize, i;
  8268. char *href, *esc, *p;
  8269. char size[64], mod[64];
  8270. #if defined(REENTRANT_TIME)
  8271. struct tm _tm;
  8272. struct tm *tm = &_tm;
  8273. #else
  8274. struct tm *tm;
  8275. #endif
  8276. /* Estimate worst case size for encoding and escaping */
  8277. namesize = strlen(de->file_name) + 1;
  8278. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8279. href = (char *)mg_malloc(namesize * 3 + escsize);
  8280. if (href == NULL) {
  8281. return -1;
  8282. }
  8283. mg_url_encode(de->file_name, href, namesize * 3);
  8284. esc = NULL;
  8285. if (escsize > 0) {
  8286. /* HTML escaping needed */
  8287. esc = href + namesize * 3;
  8288. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8289. mg_strlcpy(p, de->file_name + i, 2);
  8290. if (*p == '&') {
  8291. strcpy(p, "&amp;");
  8292. } else if (*p == '<') {
  8293. strcpy(p, "&lt;");
  8294. } else if (*p == '>') {
  8295. strcpy(p, "&gt;");
  8296. }
  8297. }
  8298. }
  8299. if (de->file.is_directory) {
  8300. mg_snprintf(de->conn,
  8301. NULL, /* Buffer is big enough */
  8302. size,
  8303. sizeof(size),
  8304. "%s",
  8305. "[DIRECTORY]");
  8306. } else {
  8307. /* We use (signed) cast below because MSVC 6 compiler cannot
  8308. * convert unsigned __int64 to double. Sigh. */
  8309. if (de->file.size < 1024) {
  8310. mg_snprintf(de->conn,
  8311. NULL, /* Buffer is big enough */
  8312. size,
  8313. sizeof(size),
  8314. "%d",
  8315. (int)de->file.size);
  8316. } else if (de->file.size < 0x100000) {
  8317. mg_snprintf(de->conn,
  8318. NULL, /* Buffer is big enough */
  8319. size,
  8320. sizeof(size),
  8321. "%.1fk",
  8322. (double)de->file.size / 1024.0);
  8323. } else if (de->file.size < 0x40000000) {
  8324. mg_snprintf(de->conn,
  8325. NULL, /* Buffer is big enough */
  8326. size,
  8327. sizeof(size),
  8328. "%.1fM",
  8329. (double)de->file.size / 1048576);
  8330. } else {
  8331. mg_snprintf(de->conn,
  8332. NULL, /* Buffer is big enough */
  8333. size,
  8334. sizeof(size),
  8335. "%.1fG",
  8336. (double)de->file.size / 1073741824);
  8337. }
  8338. }
  8339. /* Note: mg_snprintf will not cause a buffer overflow above.
  8340. * So, string truncation checks are not required here. */
  8341. #if defined(REENTRANT_TIME)
  8342. localtime_r(&de->file.last_modified, tm);
  8343. #else
  8344. tm = localtime(&de->file.last_modified);
  8345. #endif
  8346. if (tm != NULL) {
  8347. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8348. } else {
  8349. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8350. mod[sizeof(mod) - 1] = '\0';
  8351. }
  8352. mg_printf(de->conn,
  8353. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8354. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8355. href,
  8356. de->file.is_directory ? "/" : "",
  8357. esc ? esc : de->file_name,
  8358. de->file.is_directory ? "/" : "",
  8359. mod,
  8360. size);
  8361. mg_free(href);
  8362. return 0;
  8363. }
  8364. /* This function is called from send_directory() and used for
  8365. * sorting directory entries by size, or name, or modification time.
  8366. * On windows, __cdecl specification is needed in case if project is built
  8367. * with __stdcall convention. qsort always requires __cdels callback. */
  8368. static int WINCDECL
  8369. compare_dir_entries(const void *p1, const void *p2)
  8370. {
  8371. if (p1 && p2) {
  8372. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8373. const char *query_string = a->conn->request_info.query_string;
  8374. int cmp_result = 0;
  8375. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8376. query_string = "n";
  8377. }
  8378. if (a->file.is_directory && !b->file.is_directory) {
  8379. return -1; /* Always put directories on top */
  8380. } else if (!a->file.is_directory && b->file.is_directory) {
  8381. return 1; /* Always put directories on top */
  8382. } else if (*query_string == 'n') {
  8383. cmp_result = strcmp(a->file_name, b->file_name);
  8384. } else if (*query_string == 's') {
  8385. cmp_result = (a->file.size == b->file.size)
  8386. ? 0
  8387. : ((a->file.size > b->file.size) ? 1 : -1);
  8388. } else if (*query_string == 'd') {
  8389. cmp_result =
  8390. (a->file.last_modified == b->file.last_modified)
  8391. ? 0
  8392. : ((a->file.last_modified > b->file.last_modified) ? 1
  8393. : -1);
  8394. }
  8395. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8396. }
  8397. return 0;
  8398. }
  8399. static int
  8400. must_hide_file(struct mg_connection *conn, const char *path)
  8401. {
  8402. if (conn && conn->dom_ctx) {
  8403. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8404. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8405. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8406. || ((pattern != NULL)
  8407. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8408. }
  8409. return 0;
  8410. }
  8411. #if !defined(NO_FILESYSTEMS)
  8412. static int
  8413. scan_directory(struct mg_connection *conn,
  8414. const char *dir,
  8415. void *data,
  8416. int (*cb)(struct de *, void *))
  8417. {
  8418. char path[PATH_MAX];
  8419. struct dirent *dp;
  8420. DIR *dirp;
  8421. struct de de;
  8422. int truncated;
  8423. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8424. return 0;
  8425. } else {
  8426. de.conn = conn;
  8427. while ((dp = mg_readdir(dirp)) != NULL) {
  8428. /* Do not show current dir and hidden files */
  8429. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8430. || must_hide_file(conn, dp->d_name)) {
  8431. continue;
  8432. }
  8433. mg_snprintf(
  8434. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8435. /* If we don't memset stat structure to zero, mtime will have
  8436. * garbage and strftime() will segfault later on in
  8437. * print_dir_entry(). memset is required only if mg_stat()
  8438. * fails. For more details, see
  8439. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8440. memset(&de.file, 0, sizeof(de.file));
  8441. if (truncated) {
  8442. /* If the path is not complete, skip processing. */
  8443. continue;
  8444. }
  8445. if (!mg_stat(conn, path, &de.file)) {
  8446. mg_cry_internal(conn,
  8447. "%s: mg_stat(%s) failed: %s",
  8448. __func__,
  8449. path,
  8450. strerror(ERRNO));
  8451. }
  8452. de.file_name = dp->d_name;
  8453. cb(&de, data);
  8454. }
  8455. (void)mg_closedir(dirp);
  8456. }
  8457. return 1;
  8458. }
  8459. #endif /* NO_FILESYSTEMS */
  8460. #if !defined(NO_FILES)
  8461. static int
  8462. remove_directory(struct mg_connection *conn, const char *dir)
  8463. {
  8464. char path[PATH_MAX];
  8465. struct dirent *dp;
  8466. DIR *dirp;
  8467. struct de de;
  8468. int truncated;
  8469. int ok = 1;
  8470. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8471. return 0;
  8472. } else {
  8473. de.conn = conn;
  8474. while ((dp = mg_readdir(dirp)) != NULL) {
  8475. /* Do not show current dir (but show hidden files as they will
  8476. * also be removed) */
  8477. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8478. continue;
  8479. }
  8480. mg_snprintf(
  8481. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8482. /* If we don't memset stat structure to zero, mtime will have
  8483. * garbage and strftime() will segfault later on in
  8484. * print_dir_entry(). memset is required only if mg_stat()
  8485. * fails. For more details, see
  8486. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8487. memset(&de.file, 0, sizeof(de.file));
  8488. if (truncated) {
  8489. /* Do not delete anything shorter */
  8490. ok = 0;
  8491. continue;
  8492. }
  8493. if (!mg_stat(conn, path, &de.file)) {
  8494. mg_cry_internal(conn,
  8495. "%s: mg_stat(%s) failed: %s",
  8496. __func__,
  8497. path,
  8498. strerror(ERRNO));
  8499. ok = 0;
  8500. }
  8501. if (de.file.is_directory) {
  8502. if (remove_directory(conn, path) == 0) {
  8503. ok = 0;
  8504. }
  8505. } else {
  8506. /* This will fail file is the file is in memory */
  8507. if (mg_remove(conn, path) == 0) {
  8508. ok = 0;
  8509. }
  8510. }
  8511. }
  8512. (void)mg_closedir(dirp);
  8513. IGNORE_UNUSED_RESULT(rmdir(dir));
  8514. }
  8515. return ok;
  8516. }
  8517. #endif
  8518. struct dir_scan_data {
  8519. struct de *entries;
  8520. unsigned int num_entries;
  8521. unsigned int arr_size;
  8522. };
  8523. /* Behaves like realloc(), but frees original pointer on failure */
  8524. static void *
  8525. realloc2(void *ptr, size_t size)
  8526. {
  8527. void *new_ptr = mg_realloc(ptr, size);
  8528. if ((new_ptr == NULL) && (size > 0)) {
  8529. mg_free(ptr);
  8530. }
  8531. return new_ptr;
  8532. }
  8533. #if !defined(NO_FILESYSTEMS)
  8534. static int
  8535. dir_scan_callback(struct de *de, void *data)
  8536. {
  8537. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8538. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8539. dsd->arr_size *= 2;
  8540. dsd->entries =
  8541. (struct de *)realloc2(dsd->entries,
  8542. dsd->arr_size * sizeof(dsd->entries[0]));
  8543. }
  8544. if (dsd->entries == NULL) {
  8545. /* TODO(lsm, low): propagate an error to the caller */
  8546. dsd->num_entries = 0;
  8547. } else {
  8548. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8549. dsd->entries[dsd->num_entries].file = de->file;
  8550. dsd->entries[dsd->num_entries].conn = de->conn;
  8551. dsd->num_entries++;
  8552. }
  8553. return 0;
  8554. }
  8555. static void
  8556. handle_directory_request(struct mg_connection *conn, const char *dir)
  8557. {
  8558. unsigned int i;
  8559. int sort_direction;
  8560. struct dir_scan_data data = {NULL, 0, 128};
  8561. char date[64], *esc, *p;
  8562. const char *title;
  8563. time_t curtime = time(NULL);
  8564. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8565. mg_send_http_error(conn,
  8566. 500,
  8567. "Error: Cannot open directory\nopendir(%s): %s",
  8568. dir,
  8569. strerror(ERRNO));
  8570. return;
  8571. }
  8572. gmt_time_string(date, sizeof(date), &curtime);
  8573. if (!conn) {
  8574. return;
  8575. }
  8576. esc = NULL;
  8577. title = conn->request_info.local_uri;
  8578. if (title[strcspn(title, "&<>")]) {
  8579. /* HTML escaping needed */
  8580. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8581. if (esc) {
  8582. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8583. mg_strlcpy(p, title + i, 2);
  8584. if (*p == '&') {
  8585. strcpy(p, "&amp;");
  8586. } else if (*p == '<') {
  8587. strcpy(p, "&lt;");
  8588. } else if (*p == '>') {
  8589. strcpy(p, "&gt;");
  8590. }
  8591. }
  8592. } else {
  8593. title = "";
  8594. }
  8595. }
  8596. sort_direction = ((conn->request_info.query_string != NULL)
  8597. && (conn->request_info.query_string[0] != '\0')
  8598. && (conn->request_info.query_string[1] == 'd'))
  8599. ? 'a'
  8600. : 'd';
  8601. conn->must_close = 1;
  8602. /* Create 200 OK response */
  8603. mg_response_start(conn, 200);
  8604. send_static_cache_header(conn);
  8605. send_additional_header(conn);
  8606. mg_response_add_header(conn,
  8607. "Content-Type",
  8608. "text/html; charset=utf-8",
  8609. -1);
  8610. /* Send all headers */
  8611. mg_response_send_headers(conn);
  8612. /* Body */
  8613. mg_printf(conn,
  8614. "<html><head><title>Index of %s</title>"
  8615. "<style>th {text-align: left;}</style></head>"
  8616. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8617. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8618. "<th><a href=\"?d%c\">Modified</a></th>"
  8619. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8620. "<tr><td colspan=\"3\"><hr></td></tr>",
  8621. esc ? esc : title,
  8622. esc ? esc : title,
  8623. sort_direction,
  8624. sort_direction,
  8625. sort_direction);
  8626. mg_free(esc);
  8627. /* Print first entry - link to a parent directory */
  8628. mg_printf(conn,
  8629. "<tr><td><a href=\"%s\">%s</a></td>"
  8630. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8631. "..",
  8632. "Parent directory",
  8633. "-",
  8634. "-");
  8635. /* Sort and print directory entries */
  8636. if (data.entries != NULL) {
  8637. qsort(data.entries,
  8638. (size_t)data.num_entries,
  8639. sizeof(data.entries[0]),
  8640. compare_dir_entries);
  8641. for (i = 0; i < data.num_entries; i++) {
  8642. print_dir_entry(&data.entries[i]);
  8643. mg_free(data.entries[i].file_name);
  8644. }
  8645. mg_free(data.entries);
  8646. }
  8647. mg_printf(conn, "%s", "</table></pre></body></html>");
  8648. conn->status_code = 200;
  8649. }
  8650. #endif /* NO_FILESYSTEMS */
  8651. /* Send len bytes from the opened file to the client. */
  8652. static void
  8653. send_file_data(struct mg_connection *conn,
  8654. struct mg_file *filep,
  8655. int64_t offset,
  8656. int64_t len)
  8657. {
  8658. char buf[MG_BUF_LEN];
  8659. int to_read, num_read, num_written;
  8660. int64_t size;
  8661. if (!filep || !conn) {
  8662. return;
  8663. }
  8664. /* Sanity check the offset */
  8665. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8666. : (int64_t)(filep->stat.size);
  8667. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8668. #if defined(MG_USE_OPEN_FILE)
  8669. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8670. /* file stored in memory */
  8671. if (len > size - offset) {
  8672. len = size - offset;
  8673. }
  8674. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8675. } else /* else block below */
  8676. #endif
  8677. if (len > 0 && filep->access.fp != NULL) {
  8678. /* file stored on disk */
  8679. #if defined(__linux__)
  8680. /* sendfile is only available for Linux */
  8681. if ((conn->ssl == 0) && (conn->throttle == 0)
  8682. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8683. "yes"))) {
  8684. off_t sf_offs = (off_t)offset;
  8685. ssize_t sf_sent;
  8686. int sf_file = fileno(filep->access.fp);
  8687. int loop_cnt = 0;
  8688. do {
  8689. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8690. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8691. size_t sf_tosend =
  8692. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8693. sf_sent =
  8694. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8695. if (sf_sent > 0) {
  8696. len -= sf_sent;
  8697. offset += sf_sent;
  8698. } else if (loop_cnt == 0) {
  8699. /* This file can not be sent using sendfile.
  8700. * This might be the case for pseudo-files in the
  8701. * /sys/ and /proc/ file system.
  8702. * Use the regular user mode copy code instead. */
  8703. break;
  8704. } else if (sf_sent == 0) {
  8705. /* No error, but 0 bytes sent. May be EOF? */
  8706. return;
  8707. }
  8708. loop_cnt++;
  8709. } while ((len > 0) && (sf_sent >= 0));
  8710. if (sf_sent > 0) {
  8711. return; /* OK */
  8712. }
  8713. /* sf_sent<0 means error, thus fall back to the classic way */
  8714. /* This is always the case, if sf_file is not a "normal" file,
  8715. * e.g., for sending data from the output of a CGI process. */
  8716. offset = (int64_t)sf_offs;
  8717. }
  8718. #endif
  8719. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8720. mg_cry_internal(conn,
  8721. "%s: fseeko() failed: %s",
  8722. __func__,
  8723. strerror(ERRNO));
  8724. mg_send_http_error(
  8725. conn,
  8726. 500,
  8727. "%s",
  8728. "Error: Unable to access file at requested position.");
  8729. } else {
  8730. while (len > 0) {
  8731. /* Calculate how much to read from the file in the buffer */
  8732. to_read = sizeof(buf);
  8733. if ((int64_t)to_read > len) {
  8734. to_read = (int)len;
  8735. }
  8736. /* Read from file, exit the loop on error */
  8737. if ((num_read =
  8738. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8739. <= 0) {
  8740. break;
  8741. }
  8742. /* Send read bytes to the client, exit the loop on error */
  8743. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8744. != num_read) {
  8745. break;
  8746. }
  8747. /* Both read and were successful, adjust counters */
  8748. len -= num_written;
  8749. }
  8750. }
  8751. }
  8752. }
  8753. static int
  8754. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8755. {
  8756. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8757. }
  8758. static void
  8759. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8760. {
  8761. if ((filestat != NULL) && (buf != NULL)) {
  8762. mg_snprintf(NULL,
  8763. NULL, /* All calls to construct_etag use 64 byte buffer */
  8764. buf,
  8765. buf_len,
  8766. "\"%lx.%" INT64_FMT "\"",
  8767. (unsigned long)filestat->last_modified,
  8768. filestat->size);
  8769. }
  8770. }
  8771. static void
  8772. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8773. {
  8774. if (filep != NULL && filep->fp != NULL) {
  8775. #if defined(_WIN32)
  8776. (void)conn; /* Unused. */
  8777. #else
  8778. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8779. mg_cry_internal(conn,
  8780. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8781. __func__,
  8782. strerror(ERRNO));
  8783. }
  8784. #endif
  8785. }
  8786. }
  8787. #if defined(USE_ZLIB)
  8788. #include "mod_zlib.inl"
  8789. #endif
  8790. #if !defined(NO_FILESYSTEMS)
  8791. static void
  8792. handle_static_file_request(struct mg_connection *conn,
  8793. const char *path,
  8794. struct mg_file *filep,
  8795. const char *mime_type,
  8796. const char *additional_headers)
  8797. {
  8798. char lm[64], etag[64];
  8799. char range[128]; /* large enough, so there will be no overflow */
  8800. const char *range_hdr;
  8801. int64_t cl, r1, r2;
  8802. struct vec mime_vec;
  8803. int n, truncated;
  8804. char gz_path[PATH_MAX];
  8805. const char *encoding = 0;
  8806. const char *origin_hdr;
  8807. const char *cors_orig_cfg;
  8808. const char *cors1, *cors2;
  8809. int is_head_request;
  8810. #if defined(USE_ZLIB)
  8811. /* Compression is allowed, unless there is a reason not to use
  8812. * compression. If the file is already compressed, too small or a
  8813. * "range" request was made, on the fly compression is not possible. */
  8814. int allow_on_the_fly_compression = 1;
  8815. #endif
  8816. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8817. return;
  8818. }
  8819. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8820. if (mime_type == NULL) {
  8821. get_mime_type(conn, path, &mime_vec);
  8822. } else {
  8823. mime_vec.ptr = mime_type;
  8824. mime_vec.len = strlen(mime_type);
  8825. }
  8826. if (filep->stat.size > INT64_MAX) {
  8827. mg_send_http_error(conn,
  8828. 500,
  8829. "Error: File size is too large to send\n%" INT64_FMT,
  8830. filep->stat.size);
  8831. return;
  8832. }
  8833. cl = (int64_t)filep->stat.size;
  8834. conn->status_code = 200;
  8835. range[0] = '\0';
  8836. #if defined(USE_ZLIB)
  8837. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8838. * it's important to rewrite the filename after resolving
  8839. * the mime type from it, to preserve the actual file's type */
  8840. if (!conn->accept_gzip) {
  8841. allow_on_the_fly_compression = 0;
  8842. }
  8843. #endif
  8844. /* Check if there is a range header */
  8845. range_hdr = mg_get_header(conn, "Range");
  8846. /* For gzipped files, add *.gz */
  8847. if (filep->stat.is_gzipped) {
  8848. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8849. if (truncated) {
  8850. mg_send_http_error(conn,
  8851. 500,
  8852. "Error: Path of zipped file too long (%s)",
  8853. path);
  8854. return;
  8855. }
  8856. path = gz_path;
  8857. encoding = "gzip";
  8858. #if defined(USE_ZLIB)
  8859. /* File is already compressed. No "on the fly" compression. */
  8860. allow_on_the_fly_compression = 0;
  8861. #endif
  8862. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8863. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8864. struct mg_file_stat file_stat;
  8865. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8866. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8867. && !file_stat.is_directory) {
  8868. file_stat.is_gzipped = 1;
  8869. filep->stat = file_stat;
  8870. cl = (int64_t)filep->stat.size;
  8871. path = gz_path;
  8872. encoding = "gzip";
  8873. #if defined(USE_ZLIB)
  8874. /* File is already compressed. No "on the fly" compression. */
  8875. allow_on_the_fly_compression = 0;
  8876. #endif
  8877. }
  8878. }
  8879. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8880. mg_send_http_error(conn,
  8881. 500,
  8882. "Error: Cannot open file\nfopen(%s): %s",
  8883. path,
  8884. strerror(ERRNO));
  8885. return;
  8886. }
  8887. fclose_on_exec(&filep->access, conn);
  8888. /* If "Range" request was made: parse header, send only selected part
  8889. * of the file. */
  8890. r1 = r2 = 0;
  8891. if ((range_hdr != NULL)
  8892. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8893. && (r2 >= 0)) {
  8894. /* actually, range requests don't play well with a pre-gzipped
  8895. * file (since the range is specified in the uncompressed space) */
  8896. if (filep->stat.is_gzipped) {
  8897. mg_send_http_error(
  8898. conn,
  8899. 416, /* 416 = Range Not Satisfiable */
  8900. "%s",
  8901. "Error: Range requests in gzipped files are not supported");
  8902. (void)mg_fclose(
  8903. &filep->access); /* ignore error on read only file */
  8904. return;
  8905. }
  8906. conn->status_code = 206;
  8907. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8908. mg_snprintf(conn,
  8909. NULL, /* range buffer is big enough */
  8910. range,
  8911. sizeof(range),
  8912. "bytes "
  8913. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8914. r1,
  8915. r1 + cl - 1,
  8916. filep->stat.size);
  8917. #if defined(USE_ZLIB)
  8918. /* Do not compress ranges. */
  8919. allow_on_the_fly_compression = 0;
  8920. #endif
  8921. }
  8922. /* Do not compress small files. Small files do not benefit from file
  8923. * compression, but there is still some overhead. */
  8924. #if defined(USE_ZLIB)
  8925. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8926. /* File is below the size limit. */
  8927. allow_on_the_fly_compression = 0;
  8928. }
  8929. #endif
  8930. /* Standard CORS header */
  8931. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8932. origin_hdr = mg_get_header(conn, "Origin");
  8933. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8934. /* Cross-origin resource sharing (CORS), see
  8935. * http://www.html5rocks.com/en/tutorials/cors/,
  8936. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8937. * -
  8938. * preflight is not supported for files. */
  8939. cors1 = "Access-Control-Allow-Origin";
  8940. cors2 = cors_orig_cfg;
  8941. } else {
  8942. cors1 = cors2 = "";
  8943. }
  8944. /* Prepare Etag, and Last-Modified headers. */
  8945. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8946. construct_etag(etag, sizeof(etag), &filep->stat);
  8947. /* Create 2xx (200, 206) response */
  8948. mg_response_start(conn, conn->status_code);
  8949. send_static_cache_header(conn);
  8950. send_additional_header(conn);
  8951. mg_response_add_header(conn,
  8952. "Content-Type",
  8953. mime_vec.ptr,
  8954. (int)mime_vec.len);
  8955. if (cors1[0] != 0) {
  8956. mg_response_add_header(conn, cors1, cors2, -1);
  8957. }
  8958. mg_response_add_header(conn, "Last-Modified", lm, -1);
  8959. mg_response_add_header(conn, "Etag", etag, -1);
  8960. #if defined(USE_ZLIB)
  8961. /* On the fly compression allowed */
  8962. if (allow_on_the_fly_compression) {
  8963. /* For on the fly compression, we don't know the content size in
  8964. * advance, so we have to use chunked encoding */
  8965. encoding = "gzip";
  8966. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8967. /* HTTP/2 is always using "chunks" (frames) */
  8968. mg_response_add_header(conn, "Transfer-Encoding", "chunked", -1);
  8969. }
  8970. } else
  8971. #endif
  8972. {
  8973. /* Without on-the-fly compression, we know the content-length
  8974. * and we can use ranges (with on-the-fly compression we cannot).
  8975. * So we send these response headers only in this case. */
  8976. char len[32];
  8977. int trunc = 0;
  8978. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8979. if (!trunc) {
  8980. mg_response_add_header(conn, "Content-Length", len, -1);
  8981. }
  8982. mg_response_add_header(conn, "Accept-Ranges", "bytes", -1);
  8983. }
  8984. if (encoding) {
  8985. mg_response_add_header(conn, "Content-Encoding", encoding, -1);
  8986. }
  8987. if (range[0] != 0) {
  8988. mg_response_add_header(conn, "Content-Range", range, -1);
  8989. }
  8990. /* The code above does not add any header starting with X- to make
  8991. * sure no one of the additional_headers is included twice */
  8992. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8993. mg_response_add_headerlines(conn, additional_headers);
  8994. }
  8995. /* Send all headers */
  8996. mg_response_send_headers(conn);
  8997. if (!is_head_request) {
  8998. #if defined(USE_ZLIB)
  8999. if (allow_on_the_fly_compression) {
  9000. /* Compress and send */
  9001. send_compressed_data(conn, filep);
  9002. } else
  9003. #endif
  9004. {
  9005. /* Send file directly */
  9006. send_file_data(conn, filep, r1, cl);
  9007. }
  9008. }
  9009. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9010. }
  9011. int
  9012. mg_send_file_body(struct mg_connection *conn, const char *path)
  9013. {
  9014. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9015. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9016. return -1;
  9017. }
  9018. fclose_on_exec(&file.access, conn);
  9019. send_file_data(conn, &file, 0, INT64_MAX);
  9020. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9021. return 0; /* >= 0 for OK */
  9022. }
  9023. #endif /* NO_FILESYSTEMS */
  9024. #if !defined(NO_CACHING)
  9025. /* Return True if we should reply 304 Not Modified. */
  9026. static int
  9027. is_not_modified(const struct mg_connection *conn,
  9028. const struct mg_file_stat *filestat)
  9029. {
  9030. char etag[64];
  9031. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9032. const char *inm = mg_get_header(conn, "If-None-Match");
  9033. construct_etag(etag, sizeof(etag), filestat);
  9034. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9035. || ((ims != NULL)
  9036. && (filestat->last_modified <= parse_date_string(ims)));
  9037. }
  9038. static void
  9039. handle_not_modified_static_file_request(struct mg_connection *conn,
  9040. struct mg_file *filep)
  9041. {
  9042. char lm[64], etag[64];
  9043. if ((conn == NULL) || (filep == NULL)) {
  9044. return;
  9045. }
  9046. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9047. construct_etag(etag, sizeof(etag), &filep->stat);
  9048. /* Create 304 "not modified" response */
  9049. mg_response_start(conn, 304);
  9050. send_static_cache_header(conn);
  9051. send_additional_header(conn);
  9052. mg_response_add_header(conn, "Last-Modified", lm, -1);
  9053. mg_response_add_header(conn, "Etag", etag, -1);
  9054. /* Send all headers */
  9055. mg_response_send_headers(conn);
  9056. }
  9057. #endif
  9058. #if !defined(NO_FILESYSTEMS)
  9059. void
  9060. mg_send_file(struct mg_connection *conn, const char *path)
  9061. {
  9062. mg_send_mime_file2(conn, path, NULL, NULL);
  9063. }
  9064. void
  9065. mg_send_mime_file(struct mg_connection *conn,
  9066. const char *path,
  9067. const char *mime_type)
  9068. {
  9069. mg_send_mime_file2(conn, path, mime_type, NULL);
  9070. }
  9071. void
  9072. mg_send_mime_file2(struct mg_connection *conn,
  9073. const char *path,
  9074. const char *mime_type,
  9075. const char *additional_headers)
  9076. {
  9077. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9078. if (!conn) {
  9079. /* No conn */
  9080. return;
  9081. }
  9082. if (mg_stat(conn, path, &file.stat)) {
  9083. #if !defined(NO_CACHING)
  9084. if (is_not_modified(conn, &file.stat)) {
  9085. /* Send 304 "Not Modified" - this must not send any body data */
  9086. handle_not_modified_static_file_request(conn, &file);
  9087. } else
  9088. #endif /* NO_CACHING */
  9089. if (file.stat.is_directory) {
  9090. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9091. "yes")) {
  9092. handle_directory_request(conn, path);
  9093. } else {
  9094. mg_send_http_error(conn,
  9095. 403,
  9096. "%s",
  9097. "Error: Directory listing denied");
  9098. }
  9099. } else {
  9100. handle_static_file_request(
  9101. conn, path, &file, mime_type, additional_headers);
  9102. }
  9103. } else {
  9104. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9105. }
  9106. }
  9107. /* For a given PUT path, create all intermediate subdirectories.
  9108. * Return 0 if the path itself is a directory.
  9109. * Return 1 if the path leads to a file.
  9110. * Return -1 for if the path is too long.
  9111. * Return -2 if path can not be created.
  9112. */
  9113. static int
  9114. put_dir(struct mg_connection *conn, const char *path)
  9115. {
  9116. char buf[PATH_MAX];
  9117. const char *s, *p;
  9118. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9119. size_t len;
  9120. int res = 1;
  9121. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9122. len = (size_t)(p - path);
  9123. if (len >= sizeof(buf)) {
  9124. /* path too long */
  9125. res = -1;
  9126. break;
  9127. }
  9128. memcpy(buf, path, len);
  9129. buf[len] = '\0';
  9130. /* Try to create intermediate directory */
  9131. DEBUG_TRACE("mkdir(%s)", buf);
  9132. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9133. /* path does not exixt and can not be created */
  9134. res = -2;
  9135. break;
  9136. }
  9137. /* Is path itself a directory? */
  9138. if (p[1] == '\0') {
  9139. res = 0;
  9140. }
  9141. }
  9142. return res;
  9143. }
  9144. static void
  9145. remove_bad_file(const struct mg_connection *conn, const char *path)
  9146. {
  9147. int r = mg_remove(conn, path);
  9148. if (r != 0) {
  9149. mg_cry_internal(conn,
  9150. "%s: Cannot remove invalid file %s",
  9151. __func__,
  9152. path);
  9153. }
  9154. }
  9155. long long
  9156. mg_store_body(struct mg_connection *conn, const char *path)
  9157. {
  9158. char buf[MG_BUF_LEN];
  9159. long long len = 0;
  9160. int ret, n;
  9161. struct mg_file fi;
  9162. if (conn->consumed_content != 0) {
  9163. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9164. return -11;
  9165. }
  9166. ret = put_dir(conn, path);
  9167. if (ret < 0) {
  9168. /* -1 for path too long,
  9169. * -2 for path can not be created. */
  9170. return ret;
  9171. }
  9172. if (ret != 1) {
  9173. /* Return 0 means, path itself is a directory. */
  9174. return 0;
  9175. }
  9176. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9177. return -12;
  9178. }
  9179. ret = mg_read(conn, buf, sizeof(buf));
  9180. while (ret > 0) {
  9181. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9182. if (n != ret) {
  9183. (void)mg_fclose(
  9184. &fi.access); /* File is bad and will be removed anyway. */
  9185. remove_bad_file(conn, path);
  9186. return -13;
  9187. }
  9188. len += ret;
  9189. ret = mg_read(conn, buf, sizeof(buf));
  9190. }
  9191. /* File is open for writing. If fclose fails, there was probably an
  9192. * error flushing the buffer to disk, so the file on disk might be
  9193. * broken. Delete it and return an error to the caller. */
  9194. if (mg_fclose(&fi.access) != 0) {
  9195. remove_bad_file(conn, path);
  9196. return -14;
  9197. }
  9198. return len;
  9199. }
  9200. #endif /* NO_FILESYSTEMS */
  9201. /* Parse a buffer:
  9202. * Forward the string pointer till the end of a word, then
  9203. * terminate it and forward till the begin of the next word.
  9204. */
  9205. static int
  9206. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9207. {
  9208. /* Forward until a space is found - use isgraph here */
  9209. /* See http://www.cplusplus.com/reference/cctype/ */
  9210. while (isgraph((unsigned char)**ppw)) {
  9211. (*ppw)++;
  9212. }
  9213. /* Check end of word */
  9214. if (eol) {
  9215. /* must be a end of line */
  9216. if ((**ppw != '\r') && (**ppw != '\n')) {
  9217. return -1;
  9218. }
  9219. } else {
  9220. /* must be a end of a word, but not a line */
  9221. if (**ppw != ' ') {
  9222. return -1;
  9223. }
  9224. }
  9225. /* Terminate and forward to the next word */
  9226. do {
  9227. **ppw = 0;
  9228. (*ppw)++;
  9229. } while (isspace((unsigned char)**ppw));
  9230. /* Check after term */
  9231. if (!eol) {
  9232. /* if it's not the end of line, there must be a next word */
  9233. if (!isgraph((unsigned char)**ppw)) {
  9234. return -1;
  9235. }
  9236. }
  9237. /* ok */
  9238. return 1;
  9239. }
  9240. /* Parse HTTP headers from the given buffer, advance buf pointer
  9241. * to the point where parsing stopped.
  9242. * All parameters must be valid pointers (not NULL).
  9243. * Return <0 on error. */
  9244. static int
  9245. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9246. {
  9247. int i;
  9248. int num_headers = 0;
  9249. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9250. char *dp = *buf;
  9251. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9252. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9253. dp++;
  9254. }
  9255. if (dp == *buf) {
  9256. /* End of headers reached. */
  9257. break;
  9258. }
  9259. if (*dp != ':') {
  9260. /* This is not a valid field. */
  9261. return -1;
  9262. }
  9263. /* End of header key (*dp == ':') */
  9264. /* Truncate here and set the key name */
  9265. *dp = 0;
  9266. hdr[i].name = *buf;
  9267. /* Skip all spaces */
  9268. do {
  9269. dp++;
  9270. } while ((*dp == ' ') || (*dp == '\t'));
  9271. /* The rest of the line is the value */
  9272. hdr[i].value = dp;
  9273. /* Find end of line */
  9274. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9275. dp++;
  9276. };
  9277. /* eliminate \r */
  9278. if (*dp == '\r') {
  9279. *dp = 0;
  9280. dp++;
  9281. if (*dp != '\n') {
  9282. /* This is not a valid line. */
  9283. return -1;
  9284. }
  9285. }
  9286. /* here *dp is either 0 or '\n' */
  9287. /* in any case, we have a new header */
  9288. num_headers = i + 1;
  9289. if (*dp) {
  9290. *dp = 0;
  9291. dp++;
  9292. *buf = dp;
  9293. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9294. /* This is the end of the header */
  9295. break;
  9296. }
  9297. } else {
  9298. *buf = dp;
  9299. break;
  9300. }
  9301. }
  9302. return num_headers;
  9303. }
  9304. struct mg_http_method_info {
  9305. const char *name;
  9306. int request_has_body;
  9307. int response_has_body;
  9308. int is_safe;
  9309. int is_idempotent;
  9310. int is_cacheable;
  9311. };
  9312. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9313. static const struct mg_http_method_info http_methods[] = {
  9314. /* HTTP (RFC 2616) */
  9315. {"GET", 0, 1, 1, 1, 1},
  9316. {"POST", 1, 1, 0, 0, 0},
  9317. {"PUT", 1, 0, 0, 1, 0},
  9318. {"DELETE", 0, 0, 0, 1, 0},
  9319. {"HEAD", 0, 0, 1, 1, 1},
  9320. {"OPTIONS", 0, 0, 1, 1, 0},
  9321. {"CONNECT", 1, 1, 0, 0, 0},
  9322. /* TRACE method (RFC 2616) is not supported for security reasons */
  9323. /* PATCH method (RFC 5789) */
  9324. {"PATCH", 1, 0, 0, 0, 0},
  9325. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9326. /* WEBDAV (RFC 2518) */
  9327. {"PROPFIND", 0, 1, 1, 1, 0},
  9328. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9329. * Some PROPFIND results MAY be cached, with care,
  9330. * as there is no cache validation mechanism for
  9331. * most properties. This method is both safe and
  9332. * idempotent (see Section 9.1 of [RFC2616]). */
  9333. {"MKCOL", 0, 0, 0, 1, 0},
  9334. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9335. * When MKCOL is invoked without a request body,
  9336. * the newly created collection SHOULD have no
  9337. * members. A MKCOL request message may contain
  9338. * a message body. The precise behavior of a MKCOL
  9339. * request when the body is present is undefined,
  9340. * ... ==> We do not support MKCOL with body data.
  9341. * This method is idempotent, but not safe (see
  9342. * Section 9.1 of [RFC2616]). Responses to this
  9343. * method MUST NOT be cached. */
  9344. /* Unsupported WEBDAV Methods: */
  9345. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9346. /* + 11 methods from RFC 3253 */
  9347. /* ORDERPATCH (RFC 3648) */
  9348. /* ACL (RFC 3744) */
  9349. /* SEARCH (RFC 5323) */
  9350. /* + MicroSoft extensions
  9351. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9352. /* REPORT method (RFC 3253) */
  9353. {"REPORT", 1, 1, 1, 1, 1},
  9354. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9355. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9356. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9357. * to be useful for REST in case a "GET request with body" is
  9358. * required. */
  9359. {NULL, 0, 0, 0, 0, 0}
  9360. /* end of list */
  9361. };
  9362. static const struct mg_http_method_info *
  9363. get_http_method_info(const char *method)
  9364. {
  9365. /* Check if the method is known to the server. The list of all known
  9366. * HTTP methods can be found here at
  9367. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9368. */
  9369. const struct mg_http_method_info *m = http_methods;
  9370. while (m->name) {
  9371. if (!strcmp(m->name, method)) {
  9372. return m;
  9373. }
  9374. m++;
  9375. }
  9376. return NULL;
  9377. }
  9378. static int
  9379. is_valid_http_method(const char *method)
  9380. {
  9381. return (get_http_method_info(method) != NULL);
  9382. }
  9383. /* Parse HTTP request, fill in mg_request_info structure.
  9384. * This function modifies the buffer by NUL-terminating
  9385. * HTTP request components, header names and header values.
  9386. * Parameters:
  9387. * buf (in/out): pointer to the HTTP header to parse and split
  9388. * len (in): length of HTTP header buffer
  9389. * re (out): parsed header as mg_request_info
  9390. * buf and ri must be valid pointers (not NULL), len>0.
  9391. * Returns <0 on error. */
  9392. static int
  9393. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9394. {
  9395. int request_length;
  9396. int init_skip = 0;
  9397. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9398. * remote_port */
  9399. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9400. NULL;
  9401. ri->num_headers = 0;
  9402. /* RFC says that all initial whitespaces should be ingored */
  9403. /* This included all leading \r and \n (isspace) */
  9404. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9405. while ((len > 0) && isspace((unsigned char)*buf)) {
  9406. buf++;
  9407. len--;
  9408. init_skip++;
  9409. }
  9410. if (len == 0) {
  9411. /* Incomplete request */
  9412. return 0;
  9413. }
  9414. /* Control characters are not allowed, including zero */
  9415. if (iscntrl((unsigned char)*buf)) {
  9416. return -1;
  9417. }
  9418. /* Find end of HTTP header */
  9419. request_length = get_http_header_len(buf, len);
  9420. if (request_length <= 0) {
  9421. return request_length;
  9422. }
  9423. buf[request_length - 1] = '\0';
  9424. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9425. return -1;
  9426. }
  9427. /* The first word has to be the HTTP method */
  9428. ri->request_method = buf;
  9429. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9430. return -1;
  9431. }
  9432. /* Check for a valid http method */
  9433. if (!is_valid_http_method(ri->request_method)) {
  9434. return -1;
  9435. }
  9436. /* The second word is the URI */
  9437. ri->request_uri = buf;
  9438. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9439. return -1;
  9440. }
  9441. /* Next would be the HTTP version */
  9442. ri->http_version = buf;
  9443. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9444. return -1;
  9445. }
  9446. /* Check for a valid HTTP version key */
  9447. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9448. /* Invalid request */
  9449. return -1;
  9450. }
  9451. ri->http_version += 5;
  9452. /* Parse all HTTP headers */
  9453. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9454. if (ri->num_headers < 0) {
  9455. /* Error while parsing headers */
  9456. return -1;
  9457. }
  9458. return request_length + init_skip;
  9459. }
  9460. static int
  9461. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9462. {
  9463. int response_length;
  9464. int init_skip = 0;
  9465. char *tmp, *tmp2;
  9466. long l;
  9467. /* Initialize elements. */
  9468. ri->http_version = ri->status_text = NULL;
  9469. ri->num_headers = ri->status_code = 0;
  9470. /* RFC says that all initial whitespaces should be ingored */
  9471. /* This included all leading \r and \n (isspace) */
  9472. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9473. while ((len > 0) && isspace((unsigned char)*buf)) {
  9474. buf++;
  9475. len--;
  9476. init_skip++;
  9477. }
  9478. if (len == 0) {
  9479. /* Incomplete request */
  9480. return 0;
  9481. }
  9482. /* Control characters are not allowed, including zero */
  9483. if (iscntrl((unsigned char)*buf)) {
  9484. return -1;
  9485. }
  9486. /* Find end of HTTP header */
  9487. response_length = get_http_header_len(buf, len);
  9488. if (response_length <= 0) {
  9489. return response_length;
  9490. }
  9491. buf[response_length - 1] = '\0';
  9492. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9493. return -1;
  9494. }
  9495. /* The first word is the HTTP version */
  9496. /* Check for a valid HTTP version key */
  9497. if (strncmp(buf, "HTTP/", 5) != 0) {
  9498. /* Invalid request */
  9499. return -1;
  9500. }
  9501. buf += 5;
  9502. if (!isgraph((unsigned char)buf[0])) {
  9503. /* Invalid request */
  9504. return -1;
  9505. }
  9506. ri->http_version = buf;
  9507. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9508. return -1;
  9509. }
  9510. /* The second word is the status as a number */
  9511. tmp = buf;
  9512. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9513. return -1;
  9514. }
  9515. l = strtol(tmp, &tmp2, 10);
  9516. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9517. /* Everything else but a 3 digit code is invalid */
  9518. return -1;
  9519. }
  9520. ri->status_code = (int)l;
  9521. /* The rest of the line is the status text */
  9522. ri->status_text = buf;
  9523. /* Find end of status text */
  9524. /* isgraph or isspace = isprint */
  9525. while (isprint((unsigned char)*buf)) {
  9526. buf++;
  9527. }
  9528. if ((*buf != '\r') && (*buf != '\n')) {
  9529. return -1;
  9530. }
  9531. /* Terminate string and forward buf to next line */
  9532. do {
  9533. *buf = 0;
  9534. buf++;
  9535. } while (isspace((unsigned char)*buf));
  9536. /* Parse all HTTP headers */
  9537. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9538. if (ri->num_headers < 0) {
  9539. /* Error while parsing headers */
  9540. return -1;
  9541. }
  9542. return response_length + init_skip;
  9543. }
  9544. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9545. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9546. * buffer (which marks the end of HTTP request). Buffer buf may already
  9547. * have some data. The length of the data is stored in nread.
  9548. * Upon every read operation, increase nread by the number of bytes read. */
  9549. static int
  9550. read_message(FILE *fp,
  9551. struct mg_connection *conn,
  9552. char *buf,
  9553. int bufsiz,
  9554. int *nread)
  9555. {
  9556. int request_len, n = 0;
  9557. struct timespec last_action_time;
  9558. double request_timeout;
  9559. if (!conn) {
  9560. return 0;
  9561. }
  9562. memset(&last_action_time, 0, sizeof(last_action_time));
  9563. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9564. /* value of request_timeout is in seconds, config in milliseconds */
  9565. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9566. } else {
  9567. request_timeout = -1.0;
  9568. }
  9569. if (conn->handled_requests > 0) {
  9570. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9571. request_timeout =
  9572. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9573. }
  9574. }
  9575. request_len = get_http_header_len(buf, *nread);
  9576. while (request_len == 0) {
  9577. /* Full request not yet received */
  9578. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9579. /* Server is to be stopped. */
  9580. return -1;
  9581. }
  9582. if (*nread >= bufsiz) {
  9583. /* Request too long */
  9584. return -2;
  9585. }
  9586. n = pull_inner(
  9587. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9588. if (n == -2) {
  9589. /* Receive error */
  9590. return -1;
  9591. }
  9592. /* update clock after every read request */
  9593. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9594. if (n > 0) {
  9595. *nread += n;
  9596. request_len = get_http_header_len(buf, *nread);
  9597. }
  9598. if ((request_len == 0) && (request_timeout >= 0)) {
  9599. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9600. > request_timeout) {
  9601. /* Timeout */
  9602. return -1;
  9603. }
  9604. }
  9605. }
  9606. return request_len;
  9607. }
  9608. #if !defined(NO_CGI) || !defined(NO_FILES)
  9609. static int
  9610. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9611. {
  9612. const char *expect;
  9613. char buf[MG_BUF_LEN];
  9614. int success = 0;
  9615. if (!conn) {
  9616. return 0;
  9617. }
  9618. expect = mg_get_header(conn, "Expect");
  9619. DEBUG_ASSERT(fp != NULL);
  9620. if (!fp) {
  9621. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9622. return 0;
  9623. }
  9624. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9625. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9626. */
  9627. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9628. } else {
  9629. if (expect != NULL) {
  9630. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9631. conn->status_code = 100;
  9632. } else {
  9633. conn->status_code = 200;
  9634. }
  9635. DEBUG_ASSERT(conn->consumed_content == 0);
  9636. if (conn->consumed_content != 0) {
  9637. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9638. return 0;
  9639. }
  9640. for (;;) {
  9641. int nread = mg_read(conn, buf, sizeof(buf));
  9642. if (nread <= 0) {
  9643. success = (nread == 0);
  9644. break;
  9645. }
  9646. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9647. break;
  9648. }
  9649. }
  9650. /* Each error code path in this function must send an error */
  9651. if (!success) {
  9652. /* NOTE: Maybe some data has already been sent. */
  9653. /* TODO (low): If some data has been sent, a correct error
  9654. * reply can no longer be sent, so just close the connection */
  9655. mg_send_http_error(conn, 500, "%s", "");
  9656. }
  9657. }
  9658. return success;
  9659. }
  9660. #endif
  9661. #if defined(USE_TIMERS)
  9662. #define TIMER_API static
  9663. #include "timer.inl"
  9664. #endif /* USE_TIMERS */
  9665. #if !defined(NO_CGI)
  9666. /* This structure helps to create an environment for the spawned CGI
  9667. * program.
  9668. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9669. * last element must be NULL.
  9670. * However, on Windows there is a requirement that all these
  9671. * VARIABLE=VALUE\0
  9672. * strings must reside in a contiguous buffer. The end of the buffer is
  9673. * marked by two '\0' characters.
  9674. * We satisfy both worlds: we create an envp array (which is vars), all
  9675. * entries are actually pointers inside buf. */
  9676. struct cgi_environment {
  9677. struct mg_connection *conn;
  9678. /* Data block */
  9679. char *buf; /* Environment buffer */
  9680. size_t buflen; /* Space available in buf */
  9681. size_t bufused; /* Space taken in buf */
  9682. /* Index block */
  9683. char **var; /* char **envp */
  9684. size_t varlen; /* Number of variables available in var */
  9685. size_t varused; /* Number of variables stored in var */
  9686. };
  9687. static void addenv(struct cgi_environment *env,
  9688. PRINTF_FORMAT_STRING(const char *fmt),
  9689. ...) PRINTF_ARGS(2, 3);
  9690. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9691. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9692. static void
  9693. addenv(struct cgi_environment *env, const char *fmt, ...)
  9694. {
  9695. size_t i, n, space;
  9696. int truncated = 0;
  9697. char *added;
  9698. va_list ap;
  9699. if ((env->varlen - env->varused) < 2) {
  9700. mg_cry_internal(env->conn,
  9701. "%s: Cannot register CGI variable [%s]",
  9702. __func__,
  9703. fmt);
  9704. return;
  9705. }
  9706. /* Calculate how much space is left in the buffer */
  9707. space = (env->buflen - env->bufused);
  9708. do {
  9709. /* Space for "\0\0" is always needed. */
  9710. if (space <= 2) {
  9711. /* Allocate new buffer */
  9712. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9713. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9714. if (!added) {
  9715. /* Out of memory */
  9716. mg_cry_internal(
  9717. env->conn,
  9718. "%s: Cannot allocate memory for CGI variable [%s]",
  9719. __func__,
  9720. fmt);
  9721. return;
  9722. }
  9723. /* Retarget pointers */
  9724. env->buf = added;
  9725. env->buflen = n;
  9726. for (i = 0, n = 0; i < env->varused; i++) {
  9727. env->var[i] = added + n;
  9728. n += strlen(added + n) + 1;
  9729. }
  9730. space = (env->buflen - env->bufused);
  9731. }
  9732. /* Make a pointer to the free space int the buffer */
  9733. added = env->buf + env->bufused;
  9734. /* Copy VARIABLE=VALUE\0 string into the free space */
  9735. va_start(ap, fmt);
  9736. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9737. va_end(ap);
  9738. /* Do not add truncated strings to the environment */
  9739. if (truncated) {
  9740. /* Reallocate the buffer */
  9741. space = 0;
  9742. }
  9743. } while (truncated);
  9744. /* Calculate number of bytes added to the environment */
  9745. n = strlen(added) + 1;
  9746. env->bufused += n;
  9747. /* Append a pointer to the added string into the envp array */
  9748. env->var[env->varused] = added;
  9749. env->varused++;
  9750. }
  9751. /* Return 0 on success, non-zero if an error occurs. */
  9752. static int
  9753. prepare_cgi_environment(struct mg_connection *conn,
  9754. const char *prog,
  9755. struct cgi_environment *env)
  9756. {
  9757. const char *s;
  9758. struct vec var_vec;
  9759. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9760. int i, truncated, uri_len;
  9761. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9762. return -1;
  9763. }
  9764. env->conn = conn;
  9765. env->buflen = CGI_ENVIRONMENT_SIZE;
  9766. env->bufused = 0;
  9767. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9768. if (env->buf == NULL) {
  9769. mg_cry_internal(conn,
  9770. "%s: Not enough memory for environmental buffer",
  9771. __func__);
  9772. return -1;
  9773. }
  9774. env->varlen = MAX_CGI_ENVIR_VARS;
  9775. env->varused = 0;
  9776. env->var =
  9777. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9778. if (env->var == NULL) {
  9779. mg_cry_internal(conn,
  9780. "%s: Not enough memory for environmental variables",
  9781. __func__);
  9782. mg_free(env->buf);
  9783. return -1;
  9784. }
  9785. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9786. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9787. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9788. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9789. /* Prepare the environment block */
  9790. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9791. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9792. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9793. #if defined(USE_IPV6)
  9794. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9795. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9796. } else
  9797. #endif
  9798. {
  9799. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9800. }
  9801. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9802. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9803. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9804. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9805. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9806. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9807. /* SCRIPT_NAME */
  9808. uri_len = (int)strlen(conn->request_info.local_uri);
  9809. if (conn->path_info == NULL) {
  9810. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9811. /* URI: /path_to_script/script.cgi */
  9812. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9813. } else {
  9814. /* URI: /path_to_script/ ... using index.cgi */
  9815. const char *index_file = strrchr(prog, '/');
  9816. if (index_file) {
  9817. addenv(env,
  9818. "SCRIPT_NAME=%s%s",
  9819. conn->request_info.local_uri,
  9820. index_file + 1);
  9821. }
  9822. }
  9823. } else {
  9824. /* URI: /path_to_script/script.cgi/path_info */
  9825. addenv(env,
  9826. "SCRIPT_NAME=%.*s",
  9827. uri_len - (int)strlen(conn->path_info),
  9828. conn->request_info.local_uri);
  9829. }
  9830. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9831. if (conn->path_info == NULL) {
  9832. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9833. } else {
  9834. addenv(env,
  9835. "PATH_TRANSLATED=%s%s",
  9836. conn->dom_ctx->config[DOCUMENT_ROOT],
  9837. conn->path_info);
  9838. }
  9839. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9840. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9841. addenv(env, "CONTENT_TYPE=%s", s);
  9842. }
  9843. if (conn->request_info.query_string != NULL) {
  9844. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9845. }
  9846. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9847. addenv(env, "CONTENT_LENGTH=%s", s);
  9848. }
  9849. if ((s = getenv("PATH")) != NULL) {
  9850. addenv(env, "PATH=%s", s);
  9851. }
  9852. if (conn->path_info != NULL) {
  9853. addenv(env, "PATH_INFO=%s", conn->path_info);
  9854. }
  9855. if (conn->status_code > 0) {
  9856. /* CGI error handler should show the status code */
  9857. addenv(env, "STATUS=%d", conn->status_code);
  9858. }
  9859. #if defined(_WIN32)
  9860. if ((s = getenv("COMSPEC")) != NULL) {
  9861. addenv(env, "COMSPEC=%s", s);
  9862. }
  9863. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9864. addenv(env, "SYSTEMROOT=%s", s);
  9865. }
  9866. if ((s = getenv("SystemDrive")) != NULL) {
  9867. addenv(env, "SystemDrive=%s", s);
  9868. }
  9869. if ((s = getenv("ProgramFiles")) != NULL) {
  9870. addenv(env, "ProgramFiles=%s", s);
  9871. }
  9872. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9873. addenv(env, "ProgramFiles(x86)=%s", s);
  9874. }
  9875. #else
  9876. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9877. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9878. }
  9879. #endif /* _WIN32 */
  9880. if ((s = getenv("PERLLIB")) != NULL) {
  9881. addenv(env, "PERLLIB=%s", s);
  9882. }
  9883. if (conn->request_info.remote_user != NULL) {
  9884. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9885. addenv(env, "%s", "AUTH_TYPE=Digest");
  9886. }
  9887. /* Add all headers as HTTP_* variables */
  9888. for (i = 0; i < conn->request_info.num_headers; i++) {
  9889. (void)mg_snprintf(conn,
  9890. &truncated,
  9891. http_var_name,
  9892. sizeof(http_var_name),
  9893. "HTTP_%s",
  9894. conn->request_info.http_headers[i].name);
  9895. if (truncated) {
  9896. mg_cry_internal(conn,
  9897. "%s: HTTP header variable too long [%s]",
  9898. __func__,
  9899. conn->request_info.http_headers[i].name);
  9900. continue;
  9901. }
  9902. /* Convert variable name into uppercase, and change - to _ */
  9903. for (p = http_var_name; *p != '\0'; p++) {
  9904. if (*p == '-') {
  9905. *p = '_';
  9906. }
  9907. *p = (char)toupper((unsigned char)*p);
  9908. }
  9909. addenv(env,
  9910. "%s=%s",
  9911. http_var_name,
  9912. conn->request_info.http_headers[i].value);
  9913. }
  9914. /* Add user-specified variables */
  9915. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9916. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9917. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9918. }
  9919. env->var[env->varused] = NULL;
  9920. env->buf[env->bufused] = '\0';
  9921. return 0;
  9922. }
  9923. /* Data for CGI process control: PID and number of references */
  9924. struct process_control_data {
  9925. pid_t pid;
  9926. ptrdiff_t references;
  9927. };
  9928. static int
  9929. abort_process(void *data)
  9930. {
  9931. /* Waitpid checks for child status and won't work for a pid that does
  9932. * not identify a child of the current process. Thus, if the pid is
  9933. * reused, we will not affect a different process. */
  9934. struct process_control_data *proc = (struct process_control_data *)data;
  9935. int status = 0;
  9936. ptrdiff_t refs;
  9937. pid_t ret_pid;
  9938. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9939. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9940. /* Stop child process */
  9941. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9942. kill(proc->pid, SIGABRT);
  9943. /* Wait until process is terminated (don't leave zombies) */
  9944. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9945. ;
  9946. } else {
  9947. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9948. }
  9949. /* Dec reference counter */
  9950. refs = mg_atomic_dec(&proc->references);
  9951. if (refs == 0) {
  9952. /* no more references - free data */
  9953. mg_free(data);
  9954. }
  9955. return 0;
  9956. }
  9957. /* Local (static) function assumes all arguments are valid. */
  9958. static void
  9959. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9960. {
  9961. char *buf;
  9962. size_t buflen;
  9963. int headers_len, data_len, i, truncated;
  9964. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9965. const char *status, *status_text, *connection_state;
  9966. char *pbuf, dir[PATH_MAX], *p;
  9967. struct mg_request_info ri;
  9968. struct cgi_environment blk;
  9969. FILE *in = NULL, *out = NULL, *err = NULL;
  9970. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9971. pid_t pid = (pid_t)-1;
  9972. struct process_control_data *proc = NULL;
  9973. #if defined(USE_TIMERS)
  9974. double cgi_timeout = -1.0;
  9975. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9976. /* Get timeout in seconds */
  9977. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9978. }
  9979. #endif
  9980. buf = NULL;
  9981. buflen = conn->phys_ctx->max_request_size;
  9982. i = prepare_cgi_environment(conn, prog, &blk);
  9983. if (i != 0) {
  9984. blk.buf = NULL;
  9985. blk.var = NULL;
  9986. goto done;
  9987. }
  9988. /* CGI must be executed in its own directory. 'dir' must point to the
  9989. * directory containing executable program, 'p' must point to the
  9990. * executable program name relative to 'dir'. */
  9991. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9992. if (truncated) {
  9993. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9994. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9995. goto done;
  9996. }
  9997. if ((p = strrchr(dir, '/')) != NULL) {
  9998. *p++ = '\0';
  9999. } else {
  10000. dir[0] = '.';
  10001. dir[1] = '\0';
  10002. p = (char *)prog;
  10003. }
  10004. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10005. status = strerror(ERRNO);
  10006. mg_cry_internal(
  10007. conn,
  10008. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10009. prog,
  10010. status);
  10011. mg_send_http_error(conn,
  10012. 500,
  10013. "Error: Cannot create CGI pipe: %s",
  10014. status);
  10015. goto done;
  10016. }
  10017. proc = (struct process_control_data *)
  10018. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10019. if (proc == NULL) {
  10020. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10021. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10022. goto done;
  10023. }
  10024. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10025. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  10026. if (pid == (pid_t)-1) {
  10027. status = strerror(ERRNO);
  10028. mg_cry_internal(
  10029. conn,
  10030. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10031. prog,
  10032. status);
  10033. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10034. mg_free(proc);
  10035. proc = NULL;
  10036. goto done;
  10037. }
  10038. /* Store data in shared process_control_data */
  10039. proc->pid = pid;
  10040. proc->references = 1;
  10041. #if defined(USE_TIMERS)
  10042. if (cgi_timeout > 0.0) {
  10043. proc->references = 2;
  10044. // Start a timer for CGI
  10045. timer_add(conn->phys_ctx,
  10046. cgi_timeout /* in seconds */,
  10047. 0.0,
  10048. 1,
  10049. abort_process,
  10050. (void *)proc);
  10051. }
  10052. #endif
  10053. /* Parent closes only one side of the pipes.
  10054. * If we don't mark them as closed, close() attempt before
  10055. * return from this function throws an exception on Windows.
  10056. * Windows does not like when closed descriptor is closed again. */
  10057. (void)close(fdin[0]);
  10058. (void)close(fdout[1]);
  10059. (void)close(fderr[1]);
  10060. fdin[0] = fdout[1] = fderr[1] = -1;
  10061. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10062. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10063. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10064. status = strerror(ERRNO);
  10065. mg_cry_internal(conn,
  10066. "Error: CGI program \"%s\": Can not open fd: %s",
  10067. prog,
  10068. status);
  10069. mg_send_http_error(conn,
  10070. 500,
  10071. "Error: CGI can not open fd\nfdopen: %s",
  10072. status);
  10073. goto done;
  10074. }
  10075. setbuf(in, NULL);
  10076. setbuf(out, NULL);
  10077. setbuf(err, NULL);
  10078. fout.access.fp = out;
  10079. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10080. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10081. conn->content_len);
  10082. /* This is a POST/PUT request, or another request with body data. */
  10083. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10084. /* Error sending the body data */
  10085. mg_cry_internal(
  10086. conn,
  10087. "Error: CGI program \"%s\": Forward body data failed",
  10088. prog);
  10089. goto done;
  10090. }
  10091. }
  10092. /* Close so child gets an EOF. */
  10093. fclose(in);
  10094. in = NULL;
  10095. fdin[1] = -1;
  10096. /* Now read CGI reply into a buffer. We need to set correct
  10097. * status code, thus we need to see all HTTP headers first.
  10098. * Do not send anything back to client, until we buffer in all
  10099. * HTTP headers. */
  10100. data_len = 0;
  10101. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10102. if (buf == NULL) {
  10103. mg_send_http_error(conn,
  10104. 500,
  10105. "Error: Not enough memory for CGI buffer (%u bytes)",
  10106. (unsigned int)buflen);
  10107. mg_cry_internal(
  10108. conn,
  10109. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10110. "bytes)",
  10111. prog,
  10112. (unsigned int)buflen);
  10113. goto done;
  10114. }
  10115. DEBUG_TRACE("CGI: %s", "wait for response");
  10116. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10117. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10118. if (headers_len <= 0) {
  10119. /* Could not parse the CGI response. Check if some error message on
  10120. * stderr. */
  10121. i = pull_all(err, conn, buf, (int)buflen);
  10122. if (i > 0) {
  10123. /* CGI program explicitly sent an error */
  10124. /* Write the error message to the internal log */
  10125. mg_cry_internal(conn,
  10126. "Error: CGI program \"%s\" sent error "
  10127. "message: [%.*s]",
  10128. prog,
  10129. i,
  10130. buf);
  10131. /* Don't send the error message back to the client */
  10132. mg_send_http_error(conn,
  10133. 500,
  10134. "Error: CGI program \"%s\" failed.",
  10135. prog);
  10136. } else {
  10137. /* CGI program did not explicitly send an error, but a broken
  10138. * respon header */
  10139. mg_cry_internal(conn,
  10140. "Error: CGI program sent malformed or too big "
  10141. "(>%u bytes) HTTP headers: [%.*s]",
  10142. (unsigned)buflen,
  10143. data_len,
  10144. buf);
  10145. mg_send_http_error(conn,
  10146. 500,
  10147. "Error: CGI program sent malformed or too big "
  10148. "(>%u bytes) HTTP headers: [%.*s]",
  10149. (unsigned)buflen,
  10150. data_len,
  10151. buf);
  10152. }
  10153. /* in both cases, abort processing CGI */
  10154. goto done;
  10155. }
  10156. pbuf = buf;
  10157. buf[headers_len - 1] = '\0';
  10158. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10159. /* Make up and send the status line */
  10160. status_text = "OK";
  10161. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10162. != NULL) {
  10163. conn->status_code = atoi(status);
  10164. status_text = status;
  10165. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10166. status_text++;
  10167. }
  10168. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10169. != NULL) {
  10170. conn->status_code = 307;
  10171. } else {
  10172. conn->status_code = 200;
  10173. }
  10174. connection_state =
  10175. get_header(ri.http_headers, ri.num_headers, "Connection");
  10176. if (!header_has_option(connection_state, "keep-alive")) {
  10177. conn->must_close = 1;
  10178. }
  10179. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10180. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10181. /* Send headers */
  10182. for (i = 0; i < ri.num_headers; i++) {
  10183. DEBUG_TRACE("CGI header: %s: %s",
  10184. ri.http_headers[i].name,
  10185. ri.http_headers[i].value);
  10186. mg_printf(conn,
  10187. "%s: %s\r\n",
  10188. ri.http_headers[i].name,
  10189. ri.http_headers[i].value);
  10190. }
  10191. mg_write(conn, "\r\n", 2);
  10192. /* Send chunk of data that may have been read after the headers */
  10193. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10194. /* Read the rest of CGI output and send to the client */
  10195. DEBUG_TRACE("CGI: %s", "forward all data");
  10196. send_file_data(conn, &fout, 0, INT64_MAX);
  10197. DEBUG_TRACE("CGI: %s", "all data sent");
  10198. done:
  10199. mg_free(blk.var);
  10200. mg_free(blk.buf);
  10201. if (pid != (pid_t)-1) {
  10202. abort_process((void *)proc);
  10203. }
  10204. if (fdin[0] != -1) {
  10205. close(fdin[0]);
  10206. }
  10207. if (fdout[1] != -1) {
  10208. close(fdout[1]);
  10209. }
  10210. if (fderr[1] != -1) {
  10211. close(fderr[1]);
  10212. }
  10213. if (in != NULL) {
  10214. fclose(in);
  10215. } else if (fdin[1] != -1) {
  10216. close(fdin[1]);
  10217. }
  10218. if (out != NULL) {
  10219. fclose(out);
  10220. } else if (fdout[0] != -1) {
  10221. close(fdout[0]);
  10222. }
  10223. if (err != NULL) {
  10224. fclose(err);
  10225. } else if (fderr[0] != -1) {
  10226. close(fderr[0]);
  10227. }
  10228. mg_free(buf);
  10229. }
  10230. #endif /* !NO_CGI */
  10231. #if !defined(NO_FILES)
  10232. static void
  10233. mkcol(struct mg_connection *conn, const char *path)
  10234. {
  10235. int rc, body_len;
  10236. struct de de;
  10237. if (conn == NULL) {
  10238. return;
  10239. }
  10240. /* TODO (mid): Check the mg_send_http_error situations in this function
  10241. */
  10242. memset(&de.file, 0, sizeof(de.file));
  10243. if (!mg_stat(conn, path, &de.file)) {
  10244. mg_cry_internal(conn,
  10245. "%s: mg_stat(%s) failed: %s",
  10246. __func__,
  10247. path,
  10248. strerror(ERRNO));
  10249. }
  10250. if (de.file.last_modified) {
  10251. /* TODO (mid): This check does not seem to make any sense ! */
  10252. /* TODO (mid): Add a webdav unit test first, before changing
  10253. * anything here. */
  10254. mg_send_http_error(
  10255. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10256. return;
  10257. }
  10258. body_len = conn->data_len - conn->request_len;
  10259. if (body_len > 0) {
  10260. mg_send_http_error(
  10261. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10262. return;
  10263. }
  10264. rc = mg_mkdir(conn, path, 0755);
  10265. if (rc == 0) {
  10266. /* Create 201 "Created" response */
  10267. mg_response_start(conn, 201);
  10268. send_static_cache_header(conn);
  10269. send_additional_header(conn);
  10270. mg_response_add_header(conn, "Content-Length", "0", -1);
  10271. /* Send all headers - there is no body */
  10272. mg_response_send_headers(conn);
  10273. } else {
  10274. if (errno == EEXIST) {
  10275. mg_send_http_error(
  10276. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10277. } else if (errno == EACCES) {
  10278. mg_send_http_error(
  10279. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10280. } else if (errno == ENOENT) {
  10281. mg_send_http_error(
  10282. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10283. } else {
  10284. mg_send_http_error(
  10285. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10286. }
  10287. }
  10288. }
  10289. static void
  10290. put_file(struct mg_connection *conn, const char *path)
  10291. {
  10292. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10293. const char *range;
  10294. int64_t r1, r2;
  10295. int rc;
  10296. if (conn == NULL) {
  10297. return;
  10298. }
  10299. if (mg_stat(conn, path, &file.stat)) {
  10300. /* File already exists */
  10301. conn->status_code = 200;
  10302. if (file.stat.is_directory) {
  10303. /* This is an already existing directory,
  10304. * so there is nothing to do for the server. */
  10305. rc = 0;
  10306. } else {
  10307. /* File exists and is not a directory. */
  10308. /* Can it be replaced? */
  10309. #if defined(MG_USE_OPEN_FILE)
  10310. if (file.access.membuf != NULL) {
  10311. /* This is an "in-memory" file, that can not be replaced */
  10312. mg_send_http_error(conn,
  10313. 405,
  10314. "Error: Put not possible\nReplacing %s "
  10315. "is not supported",
  10316. path);
  10317. return;
  10318. }
  10319. #endif
  10320. /* Check if the server may write this file */
  10321. if (access(path, W_OK) == 0) {
  10322. /* Access granted */
  10323. rc = 1;
  10324. } else {
  10325. mg_send_http_error(
  10326. conn,
  10327. 403,
  10328. "Error: Put not possible\nReplacing %s is not allowed",
  10329. path);
  10330. return;
  10331. }
  10332. }
  10333. } else {
  10334. /* File should be created */
  10335. conn->status_code = 201;
  10336. rc = put_dir(conn, path);
  10337. }
  10338. if (rc == 0) {
  10339. /* put_dir returns 0 if path is a directory */
  10340. /* Create response */
  10341. mg_response_start(conn, conn->status_code);
  10342. send_no_cache_header(conn);
  10343. send_additional_header(conn);
  10344. mg_response_add_header(conn, "Content-Length", "0", -1);
  10345. /* Send all headers - there is no body */
  10346. mg_response_send_headers(conn);
  10347. /* Request to create a directory has been fulfilled successfully.
  10348. * No need to put a file. */
  10349. return;
  10350. }
  10351. if (rc == -1) {
  10352. /* put_dir returns -1 if the path is too long */
  10353. mg_send_http_error(conn,
  10354. 414,
  10355. "Error: Path too long\nput_dir(%s): %s",
  10356. path,
  10357. strerror(ERRNO));
  10358. return;
  10359. }
  10360. if (rc == -2) {
  10361. /* put_dir returns -2 if the directory can not be created */
  10362. mg_send_http_error(conn,
  10363. 500,
  10364. "Error: Can not create directory\nput_dir(%s): %s",
  10365. path,
  10366. strerror(ERRNO));
  10367. return;
  10368. }
  10369. /* A file should be created or overwritten. */
  10370. /* Currently CivetWeb does not nead read+write access. */
  10371. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10372. || file.access.fp == NULL) {
  10373. (void)mg_fclose(&file.access);
  10374. mg_send_http_error(conn,
  10375. 500,
  10376. "Error: Can not create file\nfopen(%s): %s",
  10377. path,
  10378. strerror(ERRNO));
  10379. return;
  10380. }
  10381. fclose_on_exec(&file.access, conn);
  10382. range = mg_get_header(conn, "Content-Range");
  10383. r1 = r2 = 0;
  10384. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10385. conn->status_code = 206; /* Partial content */
  10386. fseeko(file.access.fp, r1, SEEK_SET);
  10387. }
  10388. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10389. /* forward_body_data failed.
  10390. * The error code has already been sent to the client,
  10391. * and conn->status_code is already set. */
  10392. (void)mg_fclose(&file.access);
  10393. return;
  10394. }
  10395. if (mg_fclose(&file.access) != 0) {
  10396. /* fclose failed. This might have different reasons, but a likely
  10397. * one is "no space on disk", http 507. */
  10398. conn->status_code = 507;
  10399. }
  10400. /* Create response (status_code has been set before) */
  10401. mg_response_start(conn, conn->status_code);
  10402. send_no_cache_header(conn);
  10403. send_additional_header(conn);
  10404. mg_response_add_header(conn, "Content-Length", "0", -1);
  10405. /* Send all headers - there is no body */
  10406. mg_response_send_headers(conn);
  10407. }
  10408. static void
  10409. delete_file(struct mg_connection *conn, const char *path)
  10410. {
  10411. struct de de;
  10412. memset(&de.file, 0, sizeof(de.file));
  10413. if (!mg_stat(conn, path, &de.file)) {
  10414. /* mg_stat returns 0 if the file does not exist */
  10415. mg_send_http_error(conn,
  10416. 404,
  10417. "Error: Cannot delete file\nFile %s not found",
  10418. path);
  10419. return;
  10420. }
  10421. #if 0 /* Ignore if a file in memory is inside a folder */
  10422. if (de.access.membuf != NULL) {
  10423. /* the file is cached in memory */
  10424. mg_send_http_error(
  10425. conn,
  10426. 405,
  10427. "Error: Delete not possible\nDeleting %s is not supported",
  10428. path);
  10429. return;
  10430. }
  10431. #endif
  10432. if (de.file.is_directory) {
  10433. if (remove_directory(conn, path)) {
  10434. /* Delete is successful: Return 204 without content. */
  10435. mg_send_http_error(conn, 204, "%s", "");
  10436. } else {
  10437. /* Delete is not successful: Return 500 (Server error). */
  10438. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10439. }
  10440. return;
  10441. }
  10442. /* This is an existing file (not a directory).
  10443. * Check if write permission is granted. */
  10444. if (access(path, W_OK) != 0) {
  10445. /* File is read only */
  10446. mg_send_http_error(
  10447. conn,
  10448. 403,
  10449. "Error: Delete not possible\nDeleting %s is not allowed",
  10450. path);
  10451. return;
  10452. }
  10453. /* Try to delete it. */
  10454. if (mg_remove(conn, path) == 0) {
  10455. /* Delete was successful: Return 204 without content. */
  10456. mg_response_start(conn, 204);
  10457. send_no_cache_header(conn);
  10458. send_additional_header(conn);
  10459. mg_response_add_header(conn, "Content-Length", "0", -1);
  10460. mg_response_send_headers(conn);
  10461. } else {
  10462. /* Delete not successful (file locked). */
  10463. mg_send_http_error(conn,
  10464. 423,
  10465. "Error: Cannot delete file\nremove(%s): %s",
  10466. path,
  10467. strerror(ERRNO));
  10468. }
  10469. }
  10470. #endif /* !NO_FILES */
  10471. #if !defined(NO_FILESYSTEMS)
  10472. static void
  10473. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10474. static void
  10475. do_ssi_include(struct mg_connection *conn,
  10476. const char *ssi,
  10477. char *tag,
  10478. int include_level)
  10479. {
  10480. char file_name[MG_BUF_LEN], path[512], *p;
  10481. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10482. size_t len;
  10483. int truncated = 0;
  10484. if (conn == NULL) {
  10485. return;
  10486. }
  10487. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10488. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10489. * always < MG_BUF_LEN. */
  10490. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10491. /* File name is relative to the webserver root */
  10492. file_name[511] = 0;
  10493. (void)mg_snprintf(conn,
  10494. &truncated,
  10495. path,
  10496. sizeof(path),
  10497. "%s/%s",
  10498. conn->dom_ctx->config[DOCUMENT_ROOT],
  10499. file_name);
  10500. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10501. /* File name is relative to the webserver working directory
  10502. * or it is absolute system path */
  10503. file_name[511] = 0;
  10504. (void)
  10505. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10506. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10507. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10508. /* File name is relative to the currect document */
  10509. file_name[511] = 0;
  10510. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10511. if (!truncated) {
  10512. if ((p = strrchr(path, '/')) != NULL) {
  10513. p[1] = '\0';
  10514. }
  10515. len = strlen(path);
  10516. (void)mg_snprintf(conn,
  10517. &truncated,
  10518. path + len,
  10519. sizeof(path) - len,
  10520. "%s",
  10521. file_name);
  10522. }
  10523. } else {
  10524. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10525. return;
  10526. }
  10527. if (truncated) {
  10528. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10529. return;
  10530. }
  10531. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10532. mg_cry_internal(conn,
  10533. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10534. tag,
  10535. path,
  10536. strerror(ERRNO));
  10537. } else {
  10538. fclose_on_exec(&file.access, conn);
  10539. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10540. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10541. path)
  10542. > 0) {
  10543. send_ssi_file(conn, path, &file, include_level + 1);
  10544. } else {
  10545. send_file_data(conn, &file, 0, INT64_MAX);
  10546. }
  10547. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10548. }
  10549. }
  10550. #if !defined(NO_POPEN)
  10551. static void
  10552. do_ssi_exec(struct mg_connection *conn, char *tag)
  10553. {
  10554. char cmd[1024] = "";
  10555. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10556. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10557. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10558. } else {
  10559. cmd[1023] = 0;
  10560. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10561. mg_cry_internal(conn,
  10562. "Cannot SSI #exec: [%s]: %s",
  10563. cmd,
  10564. strerror(ERRNO));
  10565. } else {
  10566. send_file_data(conn, &file, 0, INT64_MAX);
  10567. pclose(file.access.fp);
  10568. }
  10569. }
  10570. }
  10571. #endif /* !NO_POPEN */
  10572. static int
  10573. mg_fgetc(struct mg_file *filep, int offset)
  10574. {
  10575. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10576. if (filep == NULL) {
  10577. return EOF;
  10578. }
  10579. #if defined(MG_USE_OPEN_FILE)
  10580. if ((filep->access.membuf != NULL) && (offset >= 0)
  10581. && (((unsigned int)(offset)) < filep->stat.size)) {
  10582. return ((const unsigned char *)filep->access.membuf)[offset];
  10583. } else /* else block below */
  10584. #endif
  10585. if (filep->access.fp != NULL) {
  10586. return fgetc(filep->access.fp);
  10587. } else {
  10588. return EOF;
  10589. }
  10590. }
  10591. static void
  10592. send_ssi_file(struct mg_connection *conn,
  10593. const char *path,
  10594. struct mg_file *filep,
  10595. int include_level)
  10596. {
  10597. char buf[MG_BUF_LEN];
  10598. int ch, offset, len, in_tag, in_ssi_tag;
  10599. if (include_level > 10) {
  10600. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10601. return;
  10602. }
  10603. in_tag = in_ssi_tag = len = offset = 0;
  10604. /* Read file, byte by byte, and look for SSI include tags */
  10605. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10606. if (in_tag) {
  10607. /* We are in a tag, either SSI tag or html tag */
  10608. if (ch == '>') {
  10609. /* Tag is closing */
  10610. buf[len++] = '>';
  10611. if (in_ssi_tag) {
  10612. /* Handle SSI tag */
  10613. buf[len] = 0;
  10614. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10615. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10616. #if !defined(NO_POPEN)
  10617. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10618. do_ssi_exec(conn, buf + 9);
  10619. #endif /* !NO_POPEN */
  10620. } else {
  10621. mg_cry_internal(conn,
  10622. "%s: unknown SSI "
  10623. "command: \"%s\"",
  10624. path,
  10625. buf);
  10626. }
  10627. len = 0;
  10628. in_ssi_tag = in_tag = 0;
  10629. } else {
  10630. /* Not an SSI tag */
  10631. /* Flush buffer */
  10632. (void)mg_write(conn, buf, (size_t)len);
  10633. len = 0;
  10634. in_tag = 0;
  10635. }
  10636. } else {
  10637. /* Tag is still open */
  10638. buf[len++] = (char)(ch & 0xff);
  10639. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10640. /* All SSI tags start with <!--# */
  10641. in_ssi_tag = 1;
  10642. }
  10643. if ((len + 2) > (int)sizeof(buf)) {
  10644. /* Tag to long for buffer */
  10645. mg_cry_internal(conn, "%s: tag is too large", path);
  10646. return;
  10647. }
  10648. }
  10649. } else {
  10650. /* We are not in a tag yet. */
  10651. if (ch == '<') {
  10652. /* Tag is opening */
  10653. in_tag = 1;
  10654. if (len > 0) {
  10655. /* Flush current buffer.
  10656. * Buffer is filled with "len" bytes. */
  10657. (void)mg_write(conn, buf, (size_t)len);
  10658. }
  10659. /* Store the < */
  10660. len = 1;
  10661. buf[0] = '<';
  10662. } else {
  10663. /* No Tag */
  10664. /* Add data to buffer */
  10665. buf[len++] = (char)(ch & 0xff);
  10666. /* Flush if buffer is full */
  10667. if (len == (int)sizeof(buf)) {
  10668. mg_write(conn, buf, (size_t)len);
  10669. len = 0;
  10670. }
  10671. }
  10672. }
  10673. }
  10674. /* Send the rest of buffered data */
  10675. if (len > 0) {
  10676. mg_write(conn, buf, (size_t)len);
  10677. }
  10678. }
  10679. static void
  10680. handle_ssi_file_request(struct mg_connection *conn,
  10681. const char *path,
  10682. struct mg_file *filep)
  10683. {
  10684. char date[64];
  10685. time_t curtime = time(NULL);
  10686. const char *cors_orig_cfg;
  10687. const char *cors1, *cors2;
  10688. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10689. return;
  10690. }
  10691. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10692. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10693. /* Cross-origin resource sharing (CORS). */
  10694. cors1 = "Access-Control-Allow-Origin";
  10695. cors2 = cors_orig_cfg;
  10696. } else {
  10697. cors1 = cors2 = "";
  10698. }
  10699. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10700. /* File exists (precondition for calling this function),
  10701. * but can not be opened by the server. */
  10702. mg_send_http_error(conn,
  10703. 500,
  10704. "Error: Cannot read file\nfopen(%s): %s",
  10705. path,
  10706. strerror(ERRNO));
  10707. } else {
  10708. /* Set "must_close" for HTTP/1.x, since we do not know the
  10709. * content length */
  10710. conn->must_close = 1;
  10711. gmt_time_string(date, sizeof(date), &curtime);
  10712. fclose_on_exec(&filep->access, conn);
  10713. /* 200 OK response */
  10714. mg_response_start(conn, 200);
  10715. send_no_cache_header(conn);
  10716. send_additional_header(conn);
  10717. mg_response_add_header(conn, "Content-Type", "text/html", -1);
  10718. if (cors1[0]) {
  10719. mg_response_add_header(conn, cors1, cors2, -1);
  10720. }
  10721. mg_response_send_headers(conn);
  10722. /* Header sent, now send body */
  10723. send_ssi_file(conn, path, filep, 0);
  10724. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10725. }
  10726. }
  10727. #endif /* NO_FILESYSTEMS */
  10728. #if !defined(NO_FILES)
  10729. static void
  10730. send_options(struct mg_connection *conn)
  10731. {
  10732. if (!conn) {
  10733. return;
  10734. }
  10735. /* We do not set a "Cache-Control" header here, but leave the default.
  10736. * Since browsers do not send an OPTIONS request, we can not test the
  10737. * effect anyway. */
  10738. mg_response_start(conn, 200);
  10739. mg_response_add_header(conn, "Content-Type", "text/html", -1);
  10740. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10741. /* Use the same as before */
  10742. mg_response_add_header(
  10743. conn,
  10744. "Allow",
  10745. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10746. -1);
  10747. mg_response_add_header(conn, "DAV", "1", -1);
  10748. } else {
  10749. /* TODO: Check this later for HTTP/2 */
  10750. mg_response_add_header(conn, "Allow", "GET, POST", -1);
  10751. }
  10752. send_additional_header(conn);
  10753. mg_response_send_headers(conn);
  10754. }
  10755. /* Writes PROPFIND properties for a collection element */
  10756. static int
  10757. print_props(struct mg_connection *conn,
  10758. const char *uri,
  10759. const char *name,
  10760. struct mg_file_stat *filep)
  10761. {
  10762. size_t href_size, i, j;
  10763. int len;
  10764. char *href, mtime[64];
  10765. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10766. return 0;
  10767. }
  10768. /* Estimate worst case size for encoding */
  10769. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10770. href = (char *)mg_malloc(href_size);
  10771. if (href == NULL) {
  10772. return 0;
  10773. }
  10774. len = mg_url_encode(uri, href, href_size);
  10775. if (len >= 0) {
  10776. /* Append an extra string */
  10777. mg_url_encode(name, href + len, href_size - (size_t)len);
  10778. }
  10779. /* Directory separator should be preserved. */
  10780. for (i = j = 0; href[i]; j++) {
  10781. if (!strncmp(href + i, "%2f", 3)) {
  10782. href[j] = '/';
  10783. i += 3;
  10784. } else {
  10785. href[j] = href[i++];
  10786. }
  10787. }
  10788. href[j] = '\0';
  10789. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10790. mg_printf(conn,
  10791. "<d:response>"
  10792. "<d:href>%s</d:href>"
  10793. "<d:propstat>"
  10794. "<d:prop>"
  10795. "<d:resourcetype>%s</d:resourcetype>"
  10796. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10797. "<d:getlastmodified>%s</d:getlastmodified>"
  10798. "</d:prop>"
  10799. "<d:status>HTTP/1.1 200 OK</d:status>"
  10800. "</d:propstat>"
  10801. "</d:response>\n",
  10802. href,
  10803. filep->is_directory ? "<d:collection/>" : "",
  10804. filep->size,
  10805. mtime);
  10806. mg_free(href);
  10807. return 1;
  10808. }
  10809. static int
  10810. print_dav_dir_entry(struct de *de, void *data)
  10811. {
  10812. struct mg_connection *conn = (struct mg_connection *)data;
  10813. if (!de || !conn
  10814. || !print_props(
  10815. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10816. return -1;
  10817. }
  10818. return 0;
  10819. }
  10820. static void
  10821. handle_propfind(struct mg_connection *conn,
  10822. const char *path,
  10823. struct mg_file_stat *filep)
  10824. {
  10825. const char *depth = mg_get_header(conn, "Depth");
  10826. char date[64];
  10827. time_t curtime = time(NULL);
  10828. gmt_time_string(date, sizeof(date), &curtime);
  10829. if (!conn || !path || !filep || !conn->dom_ctx) {
  10830. return;
  10831. }
  10832. conn->must_close = 1;
  10833. /* return 207 "Multi-Status" */
  10834. mg_response_start(conn, 207);
  10835. send_static_cache_header(conn);
  10836. send_additional_header(conn);
  10837. mg_response_add_header(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10838. mg_response_send_headers(conn);
  10839. /* Content */
  10840. mg_printf(conn,
  10841. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10842. "<d:multistatus xmlns:d='DAV:'>\n");
  10843. /* Print properties for the requested resource itself */
  10844. print_props(conn, conn->request_info.local_uri, "", filep);
  10845. /* If it is a directory, print directory entries too if Depth is not 0
  10846. */
  10847. if (filep->is_directory
  10848. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10849. "yes")
  10850. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10851. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10852. }
  10853. mg_printf(conn, "%s\n", "</d:multistatus>");
  10854. }
  10855. #endif
  10856. void
  10857. mg_lock_connection(struct mg_connection *conn)
  10858. {
  10859. if (conn) {
  10860. (void)pthread_mutex_lock(&conn->mutex);
  10861. }
  10862. }
  10863. void
  10864. mg_unlock_connection(struct mg_connection *conn)
  10865. {
  10866. if (conn) {
  10867. (void)pthread_mutex_unlock(&conn->mutex);
  10868. }
  10869. }
  10870. void
  10871. mg_lock_context(struct mg_context *ctx)
  10872. {
  10873. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10874. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10875. }
  10876. }
  10877. void
  10878. mg_unlock_context(struct mg_context *ctx)
  10879. {
  10880. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10881. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10882. }
  10883. }
  10884. #if defined(USE_LUA)
  10885. #include "mod_lua.inl"
  10886. #endif /* USE_LUA */
  10887. #if defined(USE_DUKTAPE)
  10888. #include "mod_duktape.inl"
  10889. #endif /* USE_DUKTAPE */
  10890. #if defined(USE_WEBSOCKET)
  10891. #if !defined(NO_SSL_DL)
  10892. #define SHA_API static
  10893. #include "sha1.inl"
  10894. #endif
  10895. static int
  10896. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10897. {
  10898. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10899. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10900. SHA_CTX sha_ctx;
  10901. int truncated;
  10902. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10903. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10904. if (truncated) {
  10905. conn->must_close = 1;
  10906. return 0;
  10907. }
  10908. DEBUG_TRACE("%s", "Send websocket handshake");
  10909. SHA1_Init(&sha_ctx);
  10910. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10911. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10912. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10913. mg_printf(conn,
  10914. "HTTP/1.1 101 Switching Protocols\r\n"
  10915. "Upgrade: websocket\r\n"
  10916. "Connection: Upgrade\r\n"
  10917. "Sec-WebSocket-Accept: %s\r\n",
  10918. b64_sha);
  10919. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10920. mg_printf(conn,
  10921. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10922. conn->request_info.acceptedWebSocketSubprotocol);
  10923. } else {
  10924. mg_printf(conn, "%s", "\r\n");
  10925. }
  10926. return 1;
  10927. }
  10928. #if !defined(MG_MAX_UNANSWERED_PING)
  10929. /* Configuration of the maximum number of websocket PINGs that might
  10930. * stay unanswered before the connection is considered broken.
  10931. * Note: The name of this define may still change (until it is
  10932. * defined as a compile parameter in a documentation).
  10933. */
  10934. #define MG_MAX_UNANSWERED_PING (5)
  10935. #endif
  10936. static void
  10937. read_websocket(struct mg_connection *conn,
  10938. mg_websocket_data_handler ws_data_handler,
  10939. void *callback_data)
  10940. {
  10941. /* Pointer to the beginning of the portion of the incoming websocket
  10942. * message queue.
  10943. * The original websocket upgrade request is never removed, so the queue
  10944. * begins after it. */
  10945. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10946. int n, error, exit_by_callback;
  10947. int ret;
  10948. /* body_len is the length of the entire queue in bytes
  10949. * len is the length of the current message
  10950. * data_len is the length of the current message's data payload
  10951. * header_len is the length of the current message's header */
  10952. size_t i, len, mask_len = 0, header_len, body_len;
  10953. uint64_t data_len = 0;
  10954. /* "The masking key is a 32-bit value chosen at random by the client."
  10955. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10956. */
  10957. unsigned char mask[4];
  10958. /* data points to the place where the message is stored when passed to
  10959. * the websocket_data callback. This is either mem on the stack, or a
  10960. * dynamically allocated buffer if it is too large. */
  10961. unsigned char mem[4096];
  10962. unsigned char mop; /* mask flag and opcode */
  10963. /* Variables used for connection monitoring */
  10964. double timeout = -1.0;
  10965. int enable_ping_pong = 0;
  10966. int ping_count = 0;
  10967. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10968. enable_ping_pong =
  10969. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10970. "yes");
  10971. }
  10972. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10973. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10974. }
  10975. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10976. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10977. }
  10978. /* Enter data processing loop */
  10979. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10980. conn->request_info.remote_addr,
  10981. conn->request_info.remote_port);
  10982. conn->in_websocket_handling = 1;
  10983. mg_set_thread_name("wsock");
  10984. /* Loop continuously, reading messages from the socket, invoking the
  10985. * callback, and waiting repeatedly until an error occurs. */
  10986. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10987. && (!conn->must_close)) {
  10988. header_len = 0;
  10989. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10990. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10991. len = buf[1] & 127;
  10992. mask_len = (buf[1] & 128) ? 4 : 0;
  10993. if ((len < 126) && (body_len >= mask_len)) {
  10994. /* inline 7-bit length field */
  10995. data_len = len;
  10996. header_len = 2 + mask_len;
  10997. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10998. /* 16-bit length field */
  10999. header_len = 4 + mask_len;
  11000. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11001. } else if (body_len >= (10 + mask_len)) {
  11002. /* 64-bit length field */
  11003. uint32_t l1, l2;
  11004. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11005. memcpy(&l2, &buf[6], 4);
  11006. header_len = 10 + mask_len;
  11007. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11008. if (data_len > (uint64_t)0x7FFF0000ul) {
  11009. /* no can do */
  11010. mg_cry_internal(
  11011. conn,
  11012. "%s",
  11013. "websocket out of memory; closing connection");
  11014. break;
  11015. }
  11016. }
  11017. }
  11018. if ((header_len > 0) && (body_len >= header_len)) {
  11019. /* Allocate space to hold websocket payload */
  11020. unsigned char *data = mem;
  11021. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11022. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11023. conn->phys_ctx);
  11024. if (data == NULL) {
  11025. /* Allocation failed, exit the loop and then close the
  11026. * connection */
  11027. mg_cry_internal(
  11028. conn,
  11029. "%s",
  11030. "websocket out of memory; closing connection");
  11031. break;
  11032. }
  11033. }
  11034. /* Copy the mask before we shift the queue and destroy it */
  11035. if (mask_len > 0) {
  11036. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11037. } else {
  11038. memset(mask, 0, sizeof(mask));
  11039. }
  11040. /* Read frame payload from the first message in the queue into
  11041. * data and advance the queue by moving the memory in place. */
  11042. DEBUG_ASSERT(body_len >= header_len);
  11043. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11044. mop = buf[0]; /* current mask and opcode */
  11045. /* Overflow case */
  11046. len = body_len - header_len;
  11047. memcpy(data, buf + header_len, len);
  11048. error = 0;
  11049. while ((uint64_t)len < data_len) {
  11050. n = pull_inner(NULL,
  11051. conn,
  11052. (char *)(data + len),
  11053. (int)(data_len - len),
  11054. timeout);
  11055. if (n <= -2) {
  11056. error = 1;
  11057. break;
  11058. } else if (n > 0) {
  11059. len += (size_t)n;
  11060. } else {
  11061. /* Timeout: should retry */
  11062. /* TODO: retry condition */
  11063. }
  11064. }
  11065. if (error) {
  11066. mg_cry_internal(
  11067. conn,
  11068. "%s",
  11069. "Websocket pull failed; closing connection");
  11070. if (data != mem) {
  11071. mg_free(data);
  11072. }
  11073. break;
  11074. }
  11075. conn->data_len = conn->request_len;
  11076. } else {
  11077. mop = buf[0]; /* current mask and opcode, overwritten by
  11078. * memmove() */
  11079. /* Length of the message being read at the front of the
  11080. * queue. Cast to 31 bit is OK, since we limited
  11081. * data_len before. */
  11082. len = (size_t)data_len + header_len;
  11083. /* Copy the data payload into the data pointer for the
  11084. * callback. Cast to 31 bit is OK, since we
  11085. * limited data_len */
  11086. memcpy(data, buf + header_len, (size_t)data_len);
  11087. /* Move the queue forward len bytes */
  11088. memmove(buf, buf + len, body_len - len);
  11089. /* Mark the queue as advanced */
  11090. conn->data_len -= (int)len;
  11091. }
  11092. /* Apply mask if necessary */
  11093. if (mask_len > 0) {
  11094. for (i = 0; i < (size_t)data_len; i++) {
  11095. data[i] ^= mask[i & 3];
  11096. }
  11097. }
  11098. exit_by_callback = 0;
  11099. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11100. /* filter PONG messages */
  11101. DEBUG_TRACE("PONG from %s:%u",
  11102. conn->request_info.remote_addr,
  11103. conn->request_info.remote_port);
  11104. /* No unanwered PINGs left */
  11105. ping_count = 0;
  11106. } else if (enable_ping_pong
  11107. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11108. /* reply PING messages */
  11109. DEBUG_TRACE("Reply PING from %s:%u",
  11110. conn->request_info.remote_addr,
  11111. conn->request_info.remote_port);
  11112. ret = mg_websocket_write(conn,
  11113. MG_WEBSOCKET_OPCODE_PONG,
  11114. (char *)data,
  11115. (size_t)data_len);
  11116. if (ret <= 0) {
  11117. /* Error: send failed */
  11118. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11119. break;
  11120. }
  11121. } else {
  11122. /* Exit the loop if callback signals to exit (server side),
  11123. * or "connection close" opcode received (client side). */
  11124. if ((ws_data_handler != NULL)
  11125. && !ws_data_handler(conn,
  11126. mop,
  11127. (char *)data,
  11128. (size_t)data_len,
  11129. callback_data)) {
  11130. exit_by_callback = 1;
  11131. }
  11132. }
  11133. /* It a buffer has been allocated, free it again */
  11134. if (data != mem) {
  11135. mg_free(data);
  11136. }
  11137. if (exit_by_callback) {
  11138. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11139. conn->request_info.remote_addr,
  11140. conn->request_info.remote_port);
  11141. break;
  11142. }
  11143. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11144. /* Opcode == 8, connection close */
  11145. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11146. conn->request_info.remote_addr,
  11147. conn->request_info.remote_port);
  11148. break;
  11149. }
  11150. /* Not breaking the loop, process next websocket frame. */
  11151. } else {
  11152. /* Read from the socket into the next available location in the
  11153. * message queue. */
  11154. n = pull_inner(NULL,
  11155. conn,
  11156. conn->buf + conn->data_len,
  11157. conn->buf_size - conn->data_len,
  11158. timeout);
  11159. if (n <= -2) {
  11160. /* Error, no bytes read */
  11161. DEBUG_TRACE("PULL from %s:%u failed",
  11162. conn->request_info.remote_addr,
  11163. conn->request_info.remote_port);
  11164. break;
  11165. }
  11166. if (n > 0) {
  11167. conn->data_len += n;
  11168. /* Reset open PING count */
  11169. ping_count = 0;
  11170. } else {
  11171. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11172. && (!conn->must_close)) {
  11173. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11174. /* Stop sending PING */
  11175. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11176. "- closing connection",
  11177. ping_count,
  11178. conn->request_info.remote_addr,
  11179. conn->request_info.remote_port);
  11180. break;
  11181. }
  11182. if (enable_ping_pong) {
  11183. /* Send Websocket PING message */
  11184. DEBUG_TRACE("PING to %s:%u",
  11185. conn->request_info.remote_addr,
  11186. conn->request_info.remote_port);
  11187. ret = mg_websocket_write(conn,
  11188. MG_WEBSOCKET_OPCODE_PING,
  11189. NULL,
  11190. 0);
  11191. if (ret <= 0) {
  11192. /* Error: send failed */
  11193. DEBUG_TRACE("Send PING failed (%i)", ret);
  11194. break;
  11195. }
  11196. ping_count++;
  11197. }
  11198. }
  11199. /* Timeout: should retry */
  11200. /* TODO: get timeout def */
  11201. }
  11202. }
  11203. }
  11204. /* Leave data processing loop */
  11205. mg_set_thread_name("worker");
  11206. conn->in_websocket_handling = 0;
  11207. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11208. conn->request_info.remote_addr,
  11209. conn->request_info.remote_port);
  11210. }
  11211. static int
  11212. mg_websocket_write_exec(struct mg_connection *conn,
  11213. int opcode,
  11214. const char *data,
  11215. size_t dataLen,
  11216. uint32_t masking_key)
  11217. {
  11218. unsigned char header[14];
  11219. size_t headerLen;
  11220. int retval;
  11221. #if defined(GCC_DIAGNOSTIC)
  11222. /* Disable spurious conversion warning for GCC */
  11223. #pragma GCC diagnostic push
  11224. #pragma GCC diagnostic ignored "-Wconversion"
  11225. #endif
  11226. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11227. #if defined(GCC_DIAGNOSTIC)
  11228. #pragma GCC diagnostic pop
  11229. #endif
  11230. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11231. if (dataLen < 126) {
  11232. /* inline 7-bit length field */
  11233. header[1] = (unsigned char)dataLen;
  11234. headerLen = 2;
  11235. } else if (dataLen <= 0xFFFF) {
  11236. /* 16-bit length field */
  11237. uint16_t len = htons((uint16_t)dataLen);
  11238. header[1] = 126;
  11239. memcpy(header + 2, &len, 2);
  11240. headerLen = 4;
  11241. } else {
  11242. /* 64-bit length field */
  11243. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11244. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11245. header[1] = 127;
  11246. memcpy(header + 2, &len1, 4);
  11247. memcpy(header + 6, &len2, 4);
  11248. headerLen = 10;
  11249. }
  11250. if (masking_key) {
  11251. /* add mask */
  11252. header[1] |= 0x80;
  11253. memcpy(header + headerLen, &masking_key, 4);
  11254. headerLen += 4;
  11255. }
  11256. /* Note that POSIX/Winsock's send() is threadsafe
  11257. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11258. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11259. * push(), although that is only a problem if the packet is large or
  11260. * outgoing buffer is full). */
  11261. /* TODO: Check if this lock should be moved to user land.
  11262. * Currently the server sets this lock for websockets, but
  11263. * not for any other connection. It must be set for every
  11264. * conn read/written by more than one thread, no matter if
  11265. * it is a websocket or regular connection. */
  11266. (void)mg_lock_connection(conn);
  11267. retval = mg_write(conn, header, headerLen);
  11268. if (retval != (int)headerLen) {
  11269. /* Did not send complete header */
  11270. retval = -1;
  11271. } else {
  11272. if (dataLen > 0) {
  11273. retval = mg_write(conn, data, dataLen);
  11274. }
  11275. /* if dataLen == 0, the header length (2) is returned */
  11276. }
  11277. /* TODO: Remove this unlock as well, when lock is removed. */
  11278. mg_unlock_connection(conn);
  11279. return retval;
  11280. }
  11281. int
  11282. mg_websocket_write(struct mg_connection *conn,
  11283. int opcode,
  11284. const char *data,
  11285. size_t dataLen)
  11286. {
  11287. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11288. }
  11289. static void
  11290. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11291. {
  11292. size_t i = 0;
  11293. i = 0;
  11294. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11295. /* Convert in 32 bit words, if data is 4 byte aligned */
  11296. while (i < (in_len - 3)) {
  11297. *(uint32_t *)(void *)(out + i) =
  11298. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11299. i += 4;
  11300. }
  11301. }
  11302. if (i != in_len) {
  11303. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11304. while (i < in_len) {
  11305. *(uint8_t *)(void *)(out + i) =
  11306. *(uint8_t *)(void *)(in + i)
  11307. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11308. i++;
  11309. }
  11310. }
  11311. }
  11312. int
  11313. mg_websocket_client_write(struct mg_connection *conn,
  11314. int opcode,
  11315. const char *data,
  11316. size_t dataLen)
  11317. {
  11318. int retval = -1;
  11319. char *masked_data =
  11320. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11321. uint32_t masking_key = 0;
  11322. if (masked_data == NULL) {
  11323. /* Return -1 in an error case */
  11324. mg_cry_internal(conn,
  11325. "%s",
  11326. "Cannot allocate buffer for masked websocket response: "
  11327. "Out of memory");
  11328. return -1;
  11329. }
  11330. do {
  11331. /* Get a masking key - but not 0 */
  11332. masking_key = (uint32_t)get_random();
  11333. } while (masking_key == 0);
  11334. mask_data(data, dataLen, masking_key, masked_data);
  11335. retval = mg_websocket_write_exec(
  11336. conn, opcode, masked_data, dataLen, masking_key);
  11337. mg_free(masked_data);
  11338. return retval;
  11339. }
  11340. static void
  11341. handle_websocket_request(struct mg_connection *conn,
  11342. const char *path,
  11343. int is_callback_resource,
  11344. struct mg_websocket_subprotocols *subprotocols,
  11345. mg_websocket_connect_handler ws_connect_handler,
  11346. mg_websocket_ready_handler ws_ready_handler,
  11347. mg_websocket_data_handler ws_data_handler,
  11348. mg_websocket_close_handler ws_close_handler,
  11349. void *cbData)
  11350. {
  11351. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11352. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11353. ptrdiff_t lua_websock = 0;
  11354. #if !defined(USE_LUA)
  11355. (void)path;
  11356. #endif
  11357. /* Step 1: Check websocket protocol version. */
  11358. /* Step 1.1: Check Sec-WebSocket-Key. */
  11359. if (!websock_key) {
  11360. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11361. * requires a Sec-WebSocket-Key header.
  11362. */
  11363. /* It could be the hixie draft version
  11364. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11365. */
  11366. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11367. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11368. char key3[8];
  11369. if ((key1 != NULL) && (key2 != NULL)) {
  11370. /* This version uses 8 byte body data in a GET request */
  11371. conn->content_len = 8;
  11372. if (8 == mg_read(conn, key3, 8)) {
  11373. /* This is the hixie version */
  11374. mg_send_http_error(conn,
  11375. 426,
  11376. "%s",
  11377. "Protocol upgrade to RFC 6455 required");
  11378. return;
  11379. }
  11380. }
  11381. /* This is an unknown version */
  11382. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11383. return;
  11384. }
  11385. /* Step 1.2: Check websocket protocol version. */
  11386. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11387. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11388. /* Reject wrong versions */
  11389. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11390. return;
  11391. }
  11392. /* Step 1.3: Could check for "Host", but we do not really nead this
  11393. * value for anything, so just ignore it. */
  11394. /* Step 2: If a callback is responsible, call it. */
  11395. if (is_callback_resource) {
  11396. /* Step 2.1 check and select subprotocol */
  11397. const char *protocols[64]; // max 64 headers
  11398. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11399. "Sec-WebSocket-Protocol",
  11400. protocols,
  11401. 64);
  11402. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11403. int cnt = 0;
  11404. int idx;
  11405. unsigned long len;
  11406. const char *sep, *curSubProtocol,
  11407. *acceptedWebSocketSubprotocol = NULL;
  11408. /* look for matching subprotocol */
  11409. do {
  11410. const char *protocol = protocols[cnt];
  11411. do {
  11412. sep = strchr(protocol, ',');
  11413. curSubProtocol = protocol;
  11414. len = sep ? (unsigned long)(sep - protocol)
  11415. : (unsigned long)strlen(protocol);
  11416. while (sep && isspace((unsigned char)*++sep))
  11417. ; // ignore leading whitespaces
  11418. protocol = sep;
  11419. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11420. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11421. && (strncmp(curSubProtocol,
  11422. subprotocols->subprotocols[idx],
  11423. len)
  11424. == 0)) {
  11425. acceptedWebSocketSubprotocol =
  11426. subprotocols->subprotocols[idx];
  11427. break;
  11428. }
  11429. }
  11430. } while (sep && !acceptedWebSocketSubprotocol);
  11431. } while (++cnt < nbSubprotocolHeader
  11432. && !acceptedWebSocketSubprotocol);
  11433. conn->request_info.acceptedWebSocketSubprotocol =
  11434. acceptedWebSocketSubprotocol;
  11435. } else if (nbSubprotocolHeader > 0) {
  11436. /* keep legacy behavior */
  11437. const char *protocol = protocols[0];
  11438. /* The protocol is a comma separated list of names. */
  11439. /* The server must only return one value from this list. */
  11440. /* First check if it is a list or just a single value. */
  11441. const char *sep = strrchr(protocol, ',');
  11442. if (sep == NULL) {
  11443. /* Just a single protocol -> accept it. */
  11444. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11445. } else {
  11446. /* Multiple protocols -> accept the last one. */
  11447. /* This is just a quick fix if the client offers multiple
  11448. * protocols. The handler should have a list of accepted
  11449. * protocols on his own
  11450. * and use it to select one protocol among those the client
  11451. * has
  11452. * offered.
  11453. */
  11454. while (isspace((unsigned char)*++sep)) {
  11455. ; /* ignore leading whitespaces */
  11456. }
  11457. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11458. }
  11459. }
  11460. if ((ws_connect_handler != NULL)
  11461. && (ws_connect_handler(conn, cbData) != 0)) {
  11462. /* C callback has returned non-zero, do not proceed with
  11463. * handshake.
  11464. */
  11465. /* Note that C callbacks are no longer called when Lua is
  11466. * responsible, so C can no longer filter callbacks for Lua. */
  11467. return;
  11468. }
  11469. }
  11470. #if defined(USE_LUA)
  11471. /* Step 3: No callback. Check if Lua is responsible. */
  11472. else {
  11473. /* Step 3.1: Check if Lua is responsible. */
  11474. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11475. lua_websock = match_prefix(
  11476. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11477. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11478. path);
  11479. }
  11480. if (lua_websock) {
  11481. /* Step 3.2: Lua is responsible: call it. */
  11482. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11483. if (!conn->lua_websocket_state) {
  11484. /* Lua rejected the new client */
  11485. return;
  11486. }
  11487. }
  11488. }
  11489. #endif
  11490. /* Step 4: Check if there is a responsible websocket handler. */
  11491. if (!is_callback_resource && !lua_websock) {
  11492. /* There is no callback, and Lua is not responsible either. */
  11493. /* Reply with a 404 Not Found. We are still at a standard
  11494. * HTTP request here, before the websocket handshake, so
  11495. * we can still send standard HTTP error replies. */
  11496. mg_send_http_error(conn, 404, "%s", "Not found");
  11497. return;
  11498. }
  11499. /* Step 5: The websocket connection has been accepted */
  11500. if (!send_websocket_handshake(conn, websock_key)) {
  11501. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11502. return;
  11503. }
  11504. /* Step 6: Call the ready handler */
  11505. if (is_callback_resource) {
  11506. if (ws_ready_handler != NULL) {
  11507. ws_ready_handler(conn, cbData);
  11508. }
  11509. #if defined(USE_LUA)
  11510. } else if (lua_websock) {
  11511. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11512. /* the ready handler returned false */
  11513. return;
  11514. }
  11515. #endif
  11516. }
  11517. /* Step 7: Enter the read loop */
  11518. if (is_callback_resource) {
  11519. read_websocket(conn, ws_data_handler, cbData);
  11520. #if defined(USE_LUA)
  11521. } else if (lua_websock) {
  11522. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11523. #endif
  11524. }
  11525. /* Step 8: Call the close handler */
  11526. if (ws_close_handler) {
  11527. ws_close_handler(conn, cbData);
  11528. }
  11529. }
  11530. #endif /* !USE_WEBSOCKET */
  11531. /* Is upgrade request:
  11532. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11533. * 1 = upgrade to websocket
  11534. * 2 = upgrade to HTTP/2
  11535. * -1 = upgrade to unknown protocol
  11536. */
  11537. static int
  11538. should_switch_to_protocol(const struct mg_connection *conn)
  11539. {
  11540. const char *upgrade, *connection;
  11541. /* A websocket protocoll has the following HTTP headers:
  11542. *
  11543. * Connection: Upgrade
  11544. * Upgrade: Websocket
  11545. */
  11546. connection = mg_get_header(conn, "Connection");
  11547. if (connection == NULL) {
  11548. return PROTOCOL_TYPE_HTTP1;
  11549. }
  11550. if (!mg_strcasestr(connection, "upgrade")) {
  11551. return PROTOCOL_TYPE_HTTP1;
  11552. }
  11553. upgrade = mg_get_header(conn, "Upgrade");
  11554. if (upgrade == NULL) {
  11555. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11556. return -1;
  11557. }
  11558. /* Upgrade to ... */
  11559. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11560. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11561. * "Sec-WebSocket-Version" are also required.
  11562. * Don't check them here, since even an unsupported websocket protocol
  11563. * request still IS a websocket request (in contrast to a standard HTTP
  11564. * request). It will fail later in handle_websocket_request.
  11565. */
  11566. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11567. }
  11568. if (0 != mg_strcasestr(upgrade, "h2")) {
  11569. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11570. }
  11571. /* Upgrade to another protocol */
  11572. return -1;
  11573. }
  11574. static int
  11575. isbyte(int n)
  11576. {
  11577. return (n >= 0) && (n <= 255);
  11578. }
  11579. static int
  11580. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11581. {
  11582. int n, a, b, c, d, slash = 32, len = 0;
  11583. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11584. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11585. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11586. && (slash < 33)) {
  11587. len = n;
  11588. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11589. | (uint32_t)d;
  11590. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11591. }
  11592. return len;
  11593. }
  11594. static int
  11595. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11596. {
  11597. int throttle = 0;
  11598. struct vec vec, val;
  11599. uint32_t net, mask;
  11600. char mult;
  11601. double v;
  11602. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11603. mult = ',';
  11604. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11605. || (v < 0)
  11606. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11607. && (mult != ','))) {
  11608. continue;
  11609. }
  11610. v *= (lowercase(&mult) == 'k')
  11611. ? 1024
  11612. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11613. if (vec.len == 1 && vec.ptr[0] == '*') {
  11614. throttle = (int)v;
  11615. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11616. if ((remote_ip & mask) == net) {
  11617. throttle = (int)v;
  11618. }
  11619. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11620. throttle = (int)v;
  11621. }
  11622. }
  11623. return throttle;
  11624. }
  11625. static uint32_t
  11626. get_remote_ip(const struct mg_connection *conn)
  11627. {
  11628. if (!conn) {
  11629. return 0;
  11630. }
  11631. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11632. }
  11633. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11634. #include "handle_form.inl"
  11635. #if defined(MG_LEGACY_INTERFACE)
  11636. /* Implement the deprecated mg_upload function by calling the new
  11637. * mg_handle_form_request function. While mg_upload could only handle
  11638. * HTML forms sent as POST request in multipart/form-data format
  11639. * containing only file input elements, mg_handle_form_request can
  11640. * handle all form input elements and all standard request methods. */
  11641. struct mg_upload_user_data {
  11642. struct mg_connection *conn;
  11643. const char *destination_dir;
  11644. int num_uploaded_files;
  11645. };
  11646. /* Helper function for deprecated mg_upload. */
  11647. static int
  11648. mg_upload_field_found(const char *key,
  11649. const char *filename,
  11650. char *path,
  11651. size_t pathlen,
  11652. void *user_data)
  11653. {
  11654. int truncated = 0;
  11655. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11656. (void)key;
  11657. if (!filename) {
  11658. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11659. return FORM_FIELD_STORAGE_ABORT;
  11660. }
  11661. mg_snprintf(fud->conn,
  11662. &truncated,
  11663. path,
  11664. pathlen - 1,
  11665. "%s/%s",
  11666. fud->destination_dir,
  11667. filename);
  11668. if (truncated) {
  11669. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11670. return FORM_FIELD_STORAGE_ABORT;
  11671. }
  11672. return FORM_FIELD_STORAGE_STORE;
  11673. }
  11674. /* Helper function for deprecated mg_upload. */
  11675. static int
  11676. mg_upload_field_get(const char *key,
  11677. const char *value,
  11678. size_t value_size,
  11679. void *user_data)
  11680. {
  11681. /* Function should never be called */
  11682. (void)key;
  11683. (void)value;
  11684. (void)value_size;
  11685. (void)user_data;
  11686. return 0;
  11687. }
  11688. /* Helper function for deprecated mg_upload. */
  11689. static int
  11690. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11691. {
  11692. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11693. (void)file_size;
  11694. fud->num_uploaded_files++;
  11695. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11696. return 0;
  11697. }
  11698. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11699. int
  11700. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11701. {
  11702. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11703. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11704. mg_upload_field_get,
  11705. mg_upload_field_stored,
  11706. 0};
  11707. int ret;
  11708. fdh.user_data = (void *)&fud;
  11709. ret = mg_handle_form_request(conn, &fdh);
  11710. if (ret < 0) {
  11711. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11712. }
  11713. return fud.num_uploaded_files;
  11714. }
  11715. #endif
  11716. static int
  11717. get_first_ssl_listener_index(const struct mg_context *ctx)
  11718. {
  11719. unsigned int i;
  11720. int idx = -1;
  11721. if (ctx) {
  11722. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11723. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11724. }
  11725. }
  11726. return idx;
  11727. }
  11728. /* Return host (without port) */
  11729. /* Use mg_free to free the result */
  11730. static const char *
  11731. alloc_get_host(struct mg_connection *conn)
  11732. {
  11733. char buf[1025];
  11734. size_t buflen = sizeof(buf);
  11735. const char *host_header = get_header(conn->request_info.http_headers,
  11736. conn->request_info.num_headers,
  11737. "Host");
  11738. char *host;
  11739. if (host_header != NULL) {
  11740. char *pos;
  11741. /* Create a local copy of the "Host" header, since it might be
  11742. * modified here. */
  11743. mg_strlcpy(buf, host_header, buflen);
  11744. buf[buflen - 1] = '\0';
  11745. host = buf;
  11746. while (isspace((unsigned char)*host)) {
  11747. host++;
  11748. }
  11749. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11750. * is found. */
  11751. if (*host == '[') {
  11752. pos = strchr(host, ']');
  11753. if (!pos) {
  11754. /* Malformed hostname starts with '[', but no ']' found */
  11755. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11756. return NULL;
  11757. }
  11758. /* terminate after ']' */
  11759. pos[1] = 0;
  11760. } else {
  11761. /* Otherwise, a ':' separates hostname and port number */
  11762. pos = strchr(host, ':');
  11763. if (pos != NULL) {
  11764. *pos = '\0';
  11765. }
  11766. }
  11767. if (conn->ssl) {
  11768. /* This is a HTTPS connection, maybe we have a hostname
  11769. * from SNI (set in ssl_servername_callback). */
  11770. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11771. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11772. /* We are not using the default domain */
  11773. if (mg_strcasecmp(host, sslhost)) {
  11774. /* Mismatch between SNI domain and HTTP domain */
  11775. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11776. sslhost,
  11777. host);
  11778. return NULL;
  11779. }
  11780. }
  11781. DEBUG_TRACE("HTTPS Host: %s", host);
  11782. } else {
  11783. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11784. while (dom) {
  11785. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11786. /* Found matching domain */
  11787. DEBUG_TRACE("HTTP domain %s found",
  11788. dom->config[AUTHENTICATION_DOMAIN]);
  11789. /* TODO: Check if this is a HTTP or HTTPS domain */
  11790. conn->dom_ctx = dom;
  11791. break;
  11792. }
  11793. mg_lock_context(conn->phys_ctx);
  11794. dom = dom->next;
  11795. mg_unlock_context(conn->phys_ctx);
  11796. }
  11797. DEBUG_TRACE("HTTP Host: %s", host);
  11798. }
  11799. } else {
  11800. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11801. host = buf;
  11802. DEBUG_TRACE("IP: %s", host);
  11803. }
  11804. return mg_strdup_ctx(host, conn->phys_ctx);
  11805. }
  11806. static void
  11807. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11808. {
  11809. char target_url[MG_BUF_LEN];
  11810. int truncated = 0;
  11811. conn->must_close = 1;
  11812. /* Send host, port, uri and (if it exists) ?query_string */
  11813. if (conn->host) {
  11814. /* Use "308 Permanent Redirect" */
  11815. int redirect_code = 308;
  11816. /* Create target URL */
  11817. mg_snprintf(
  11818. conn,
  11819. &truncated,
  11820. target_url,
  11821. sizeof(target_url),
  11822. "https://%s:%d%s%s%s",
  11823. conn->host,
  11824. #if defined(USE_IPV6)
  11825. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11826. == AF_INET6)
  11827. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11828. .lsa.sin6.sin6_port)
  11829. :
  11830. #endif
  11831. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11832. .lsa.sin.sin_port),
  11833. conn->request_info.local_uri,
  11834. (conn->request_info.query_string == NULL) ? "" : "?",
  11835. (conn->request_info.query_string == NULL)
  11836. ? ""
  11837. : conn->request_info.query_string);
  11838. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11839. * is used as buffer size) */
  11840. if (truncated) {
  11841. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11842. return;
  11843. }
  11844. /* Use redirect helper function */
  11845. mg_send_http_redirect(conn, target_url, redirect_code);
  11846. }
  11847. }
  11848. static void
  11849. mg_set_handler_type(struct mg_context *phys_ctx,
  11850. struct mg_domain_context *dom_ctx,
  11851. const char *uri,
  11852. int handler_type,
  11853. int is_delete_request,
  11854. mg_request_handler handler,
  11855. struct mg_websocket_subprotocols *subprotocols,
  11856. mg_websocket_connect_handler connect_handler,
  11857. mg_websocket_ready_handler ready_handler,
  11858. mg_websocket_data_handler data_handler,
  11859. mg_websocket_close_handler close_handler,
  11860. mg_authorization_handler auth_handler,
  11861. void *cbdata)
  11862. {
  11863. struct mg_handler_info *tmp_rh, **lastref;
  11864. size_t urilen = strlen(uri);
  11865. if (handler_type == WEBSOCKET_HANDLER) {
  11866. DEBUG_ASSERT(handler == NULL);
  11867. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11868. || ready_handler != NULL || data_handler != NULL
  11869. || close_handler != NULL);
  11870. DEBUG_ASSERT(auth_handler == NULL);
  11871. if (handler != NULL) {
  11872. return;
  11873. }
  11874. if (!is_delete_request && (connect_handler == NULL)
  11875. && (ready_handler == NULL) && (data_handler == NULL)
  11876. && (close_handler == NULL)) {
  11877. return;
  11878. }
  11879. if (auth_handler != NULL) {
  11880. return;
  11881. }
  11882. } else if (handler_type == REQUEST_HANDLER) {
  11883. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11884. && data_handler == NULL && close_handler == NULL);
  11885. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11886. DEBUG_ASSERT(auth_handler == NULL);
  11887. if ((connect_handler != NULL) || (ready_handler != NULL)
  11888. || (data_handler != NULL) || (close_handler != NULL)) {
  11889. return;
  11890. }
  11891. if (!is_delete_request && (handler == NULL)) {
  11892. return;
  11893. }
  11894. if (auth_handler != NULL) {
  11895. return;
  11896. }
  11897. } else { /* AUTH_HANDLER */
  11898. DEBUG_ASSERT(handler == NULL);
  11899. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11900. && data_handler == NULL && close_handler == NULL);
  11901. DEBUG_ASSERT(auth_handler != NULL);
  11902. if (handler != NULL) {
  11903. return;
  11904. }
  11905. if ((connect_handler != NULL) || (ready_handler != NULL)
  11906. || (data_handler != NULL) || (close_handler != NULL)) {
  11907. return;
  11908. }
  11909. if (!is_delete_request && (auth_handler == NULL)) {
  11910. return;
  11911. }
  11912. }
  11913. if (!phys_ctx || !dom_ctx) {
  11914. return;
  11915. }
  11916. mg_lock_context(phys_ctx);
  11917. /* first try to find an existing handler */
  11918. do {
  11919. lastref = &(dom_ctx->handlers);
  11920. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11921. tmp_rh = tmp_rh->next) {
  11922. if (tmp_rh->handler_type == handler_type
  11923. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11924. if (!is_delete_request) {
  11925. /* update existing handler */
  11926. if (handler_type == REQUEST_HANDLER) {
  11927. /* Wait for end of use before updating */
  11928. if (tmp_rh->refcount) {
  11929. mg_unlock_context(phys_ctx);
  11930. mg_sleep(1);
  11931. mg_lock_context(phys_ctx);
  11932. /* tmp_rh might have been freed, search again. */
  11933. break;
  11934. }
  11935. /* Ok, the handler is no more use -> Update it */
  11936. tmp_rh->handler = handler;
  11937. } else if (handler_type == WEBSOCKET_HANDLER) {
  11938. tmp_rh->subprotocols = subprotocols;
  11939. tmp_rh->connect_handler = connect_handler;
  11940. tmp_rh->ready_handler = ready_handler;
  11941. tmp_rh->data_handler = data_handler;
  11942. tmp_rh->close_handler = close_handler;
  11943. } else { /* AUTH_HANDLER */
  11944. tmp_rh->auth_handler = auth_handler;
  11945. }
  11946. tmp_rh->cbdata = cbdata;
  11947. } else {
  11948. /* remove existing handler */
  11949. if (handler_type == REQUEST_HANDLER) {
  11950. /* Wait for end of use before removing */
  11951. if (tmp_rh->refcount) {
  11952. tmp_rh->removing = 1;
  11953. mg_unlock_context(phys_ctx);
  11954. mg_sleep(1);
  11955. mg_lock_context(phys_ctx);
  11956. /* tmp_rh might have been freed, search again. */
  11957. break;
  11958. }
  11959. /* Ok, the handler is no more used */
  11960. }
  11961. *lastref = tmp_rh->next;
  11962. mg_free(tmp_rh->uri);
  11963. mg_free(tmp_rh);
  11964. }
  11965. mg_unlock_context(phys_ctx);
  11966. return;
  11967. }
  11968. lastref = &(tmp_rh->next);
  11969. }
  11970. } while (tmp_rh != NULL);
  11971. if (is_delete_request) {
  11972. /* no handler to set, this was a remove request to a non-existing
  11973. * handler */
  11974. mg_unlock_context(phys_ctx);
  11975. return;
  11976. }
  11977. tmp_rh =
  11978. (struct mg_handler_info *)mg_calloc_ctx(1,
  11979. sizeof(struct mg_handler_info),
  11980. phys_ctx);
  11981. if (tmp_rh == NULL) {
  11982. mg_unlock_context(phys_ctx);
  11983. mg_cry_ctx_internal(phys_ctx,
  11984. "%s",
  11985. "Cannot create new request handler struct, OOM");
  11986. return;
  11987. }
  11988. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11989. if (!tmp_rh->uri) {
  11990. mg_unlock_context(phys_ctx);
  11991. mg_free(tmp_rh);
  11992. mg_cry_ctx_internal(phys_ctx,
  11993. "%s",
  11994. "Cannot create new request handler struct, OOM");
  11995. return;
  11996. }
  11997. tmp_rh->uri_len = urilen;
  11998. if (handler_type == REQUEST_HANDLER) {
  11999. tmp_rh->refcount = 0;
  12000. tmp_rh->removing = 0;
  12001. tmp_rh->handler = handler;
  12002. } else if (handler_type == WEBSOCKET_HANDLER) {
  12003. tmp_rh->subprotocols = subprotocols;
  12004. tmp_rh->connect_handler = connect_handler;
  12005. tmp_rh->ready_handler = ready_handler;
  12006. tmp_rh->data_handler = data_handler;
  12007. tmp_rh->close_handler = close_handler;
  12008. } else { /* AUTH_HANDLER */
  12009. tmp_rh->auth_handler = auth_handler;
  12010. }
  12011. tmp_rh->cbdata = cbdata;
  12012. tmp_rh->handler_type = handler_type;
  12013. tmp_rh->next = NULL;
  12014. *lastref = tmp_rh;
  12015. mg_unlock_context(phys_ctx);
  12016. }
  12017. void
  12018. mg_set_request_handler(struct mg_context *ctx,
  12019. const char *uri,
  12020. mg_request_handler handler,
  12021. void *cbdata)
  12022. {
  12023. mg_set_handler_type(ctx,
  12024. &(ctx->dd),
  12025. uri,
  12026. REQUEST_HANDLER,
  12027. handler == NULL,
  12028. handler,
  12029. NULL,
  12030. NULL,
  12031. NULL,
  12032. NULL,
  12033. NULL,
  12034. NULL,
  12035. cbdata);
  12036. }
  12037. void
  12038. mg_set_websocket_handler(struct mg_context *ctx,
  12039. const char *uri,
  12040. mg_websocket_connect_handler connect_handler,
  12041. mg_websocket_ready_handler ready_handler,
  12042. mg_websocket_data_handler data_handler,
  12043. mg_websocket_close_handler close_handler,
  12044. void *cbdata)
  12045. {
  12046. mg_set_websocket_handler_with_subprotocols(ctx,
  12047. uri,
  12048. NULL,
  12049. connect_handler,
  12050. ready_handler,
  12051. data_handler,
  12052. close_handler,
  12053. cbdata);
  12054. }
  12055. void
  12056. mg_set_websocket_handler_with_subprotocols(
  12057. struct mg_context *ctx,
  12058. const char *uri,
  12059. struct mg_websocket_subprotocols *subprotocols,
  12060. mg_websocket_connect_handler connect_handler,
  12061. mg_websocket_ready_handler ready_handler,
  12062. mg_websocket_data_handler data_handler,
  12063. mg_websocket_close_handler close_handler,
  12064. void *cbdata)
  12065. {
  12066. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12067. && (data_handler == NULL)
  12068. && (close_handler == NULL);
  12069. mg_set_handler_type(ctx,
  12070. &(ctx->dd),
  12071. uri,
  12072. WEBSOCKET_HANDLER,
  12073. is_delete_request,
  12074. NULL,
  12075. subprotocols,
  12076. connect_handler,
  12077. ready_handler,
  12078. data_handler,
  12079. close_handler,
  12080. NULL,
  12081. cbdata);
  12082. }
  12083. void
  12084. mg_set_auth_handler(struct mg_context *ctx,
  12085. const char *uri,
  12086. mg_authorization_handler handler,
  12087. void *cbdata)
  12088. {
  12089. mg_set_handler_type(ctx,
  12090. &(ctx->dd),
  12091. uri,
  12092. AUTH_HANDLER,
  12093. handler == NULL,
  12094. NULL,
  12095. NULL,
  12096. NULL,
  12097. NULL,
  12098. NULL,
  12099. NULL,
  12100. handler,
  12101. cbdata);
  12102. }
  12103. static int
  12104. get_request_handler(struct mg_connection *conn,
  12105. int handler_type,
  12106. mg_request_handler *handler,
  12107. struct mg_websocket_subprotocols **subprotocols,
  12108. mg_websocket_connect_handler *connect_handler,
  12109. mg_websocket_ready_handler *ready_handler,
  12110. mg_websocket_data_handler *data_handler,
  12111. mg_websocket_close_handler *close_handler,
  12112. mg_authorization_handler *auth_handler,
  12113. void **cbdata,
  12114. struct mg_handler_info **handler_info)
  12115. {
  12116. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12117. if (request_info) {
  12118. const char *uri = request_info->local_uri;
  12119. size_t urilen = strlen(uri);
  12120. struct mg_handler_info *tmp_rh;
  12121. int step, matched;
  12122. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12123. return 0;
  12124. }
  12125. mg_lock_context(conn->phys_ctx);
  12126. for (step = 0; step < 3; step++) {
  12127. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12128. tmp_rh = tmp_rh->next) {
  12129. if (tmp_rh->handler_type != handler_type) {
  12130. continue;
  12131. }
  12132. if (step == 0) {
  12133. /* first try for an exact match */
  12134. matched = (tmp_rh->uri_len == urilen)
  12135. && (strcmp(tmp_rh->uri, uri) == 0);
  12136. } else if (step == 1) {
  12137. /* next try for a partial match, we will accept
  12138. uri/something */
  12139. matched =
  12140. (tmp_rh->uri_len < urilen)
  12141. && (uri[tmp_rh->uri_len] == '/')
  12142. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12143. } else {
  12144. /* finally try for pattern match */
  12145. matched =
  12146. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12147. }
  12148. if (matched) {
  12149. if (handler_type == WEBSOCKET_HANDLER) {
  12150. *subprotocols = tmp_rh->subprotocols;
  12151. *connect_handler = tmp_rh->connect_handler;
  12152. *ready_handler = tmp_rh->ready_handler;
  12153. *data_handler = tmp_rh->data_handler;
  12154. *close_handler = tmp_rh->close_handler;
  12155. } else if (handler_type == REQUEST_HANDLER) {
  12156. if (tmp_rh->removing) {
  12157. /* Treat as none found */
  12158. step = 2;
  12159. break;
  12160. }
  12161. *handler = tmp_rh->handler;
  12162. /* Acquire handler and give it back */
  12163. tmp_rh->refcount++;
  12164. *handler_info = tmp_rh;
  12165. } else { /* AUTH_HANDLER */
  12166. *auth_handler = tmp_rh->auth_handler;
  12167. }
  12168. *cbdata = tmp_rh->cbdata;
  12169. mg_unlock_context(conn->phys_ctx);
  12170. return 1;
  12171. }
  12172. }
  12173. }
  12174. mg_unlock_context(conn->phys_ctx);
  12175. }
  12176. return 0; /* none found */
  12177. }
  12178. /* Check if the script file is in a path, allowed for script files.
  12179. * This can be used if uploading files is possible not only for the server
  12180. * admin, and the upload mechanism does not check the file extension.
  12181. */
  12182. static int
  12183. is_in_script_path(const struct mg_connection *conn, const char *path)
  12184. {
  12185. /* TODO (Feature): Add config value for allowed script path.
  12186. * Default: All allowed. */
  12187. (void)conn;
  12188. (void)path;
  12189. return 1;
  12190. }
  12191. #if defined(USE_WEBSOCKET) \
  12192. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12193. static int
  12194. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12195. void *cbdata)
  12196. {
  12197. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12198. if (pcallbacks->websocket_connect) {
  12199. return pcallbacks->websocket_connect(conn);
  12200. }
  12201. /* No handler set - assume "OK" */
  12202. return 0;
  12203. }
  12204. static void
  12205. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12206. {
  12207. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12208. if (pcallbacks->websocket_ready) {
  12209. pcallbacks->websocket_ready(conn);
  12210. }
  12211. }
  12212. static int
  12213. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12214. int bits,
  12215. char *data,
  12216. size_t len,
  12217. void *cbdata)
  12218. {
  12219. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12220. if (pcallbacks->websocket_data) {
  12221. return pcallbacks->websocket_data(conn, bits, data, len);
  12222. }
  12223. /* No handler set - assume "OK" */
  12224. return 1;
  12225. }
  12226. static void
  12227. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12228. void *cbdata)
  12229. {
  12230. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12231. if (pcallbacks->connection_close) {
  12232. pcallbacks->connection_close(conn);
  12233. }
  12234. }
  12235. #endif
  12236. /* This is the heart of the Civetweb's logic.
  12237. * This function is called when the request is read, parsed and validated,
  12238. * and Civetweb must decide what action to take: serve a file, or
  12239. * a directory, or call embedded function, etcetera. */
  12240. static void
  12241. handle_request(struct mg_connection *conn)
  12242. {
  12243. struct mg_request_info *ri = &conn->request_info;
  12244. char path[PATH_MAX];
  12245. int uri_len, ssl_index;
  12246. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12247. is_put_or_delete_request = 0, is_callback_resource = 0;
  12248. int i;
  12249. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12250. mg_request_handler callback_handler = NULL;
  12251. struct mg_handler_info *handler_info = NULL;
  12252. struct mg_websocket_subprotocols *subprotocols;
  12253. mg_websocket_connect_handler ws_connect_handler = NULL;
  12254. mg_websocket_ready_handler ws_ready_handler = NULL;
  12255. mg_websocket_data_handler ws_data_handler = NULL;
  12256. mg_websocket_close_handler ws_close_handler = NULL;
  12257. void *callback_data = NULL;
  12258. mg_authorization_handler auth_handler = NULL;
  12259. void *auth_callback_data = NULL;
  12260. int handler_type;
  12261. time_t curtime = time(NULL);
  12262. char date[64];
  12263. path[0] = 0;
  12264. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12265. conn->request_state = 0;
  12266. /* 1. get the request url */
  12267. /* 1.1. split into url and query string */
  12268. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12269. != NULL) {
  12270. *((char *)conn->request_info.query_string++) = '\0';
  12271. }
  12272. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12273. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12274. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12275. if (ssl_index >= 0) {
  12276. redirect_to_https_port(conn, ssl_index);
  12277. } else {
  12278. /* A http to https forward port has been specified,
  12279. * but no https port to forward to. */
  12280. mg_send_http_error(conn,
  12281. 503,
  12282. "%s",
  12283. "Error: SSL forward not configured properly");
  12284. mg_cry_internal(conn,
  12285. "%s",
  12286. "Can not redirect to SSL, no SSL port available");
  12287. }
  12288. return;
  12289. }
  12290. uri_len = (int)strlen(ri->local_uri);
  12291. /* 1.3. decode url (if config says so) */
  12292. if (should_decode_url(conn)) {
  12293. mg_url_decode(
  12294. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12295. }
  12296. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12297. * not possible */
  12298. remove_dot_segments((char *)ri->local_uri);
  12299. /* step 1. completed, the url is known now */
  12300. uri_len = (int)strlen(ri->local_uri);
  12301. DEBUG_TRACE("URL: %s", ri->local_uri);
  12302. /* 2. if this ip has limited speed, set it for this connection */
  12303. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12304. get_remote_ip(conn),
  12305. ri->local_uri);
  12306. /* 3. call a "handle everything" callback, if registered */
  12307. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12308. /* Note that since V1.7 the "begin_request" function is called
  12309. * before an authorization check. If an authorization check is
  12310. * required, use a request_handler instead. */
  12311. i = conn->phys_ctx->callbacks.begin_request(conn);
  12312. if (i > 0) {
  12313. /* callback already processed the request. Store the
  12314. return value as a status code for the access log. */
  12315. conn->status_code = i;
  12316. if (!conn->must_close) {
  12317. discard_unread_request_data(conn);
  12318. }
  12319. return;
  12320. } else if (i == 0) {
  12321. /* civetweb should process the request */
  12322. } else {
  12323. /* unspecified - may change with the next version */
  12324. return;
  12325. }
  12326. }
  12327. /* request not yet handled by a handler or redirect, so the request
  12328. * is processed here */
  12329. /* 4. Check for CORS preflight requests and handle them (if configured).
  12330. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12331. */
  12332. if (!strcmp(ri->request_method, "OPTIONS")) {
  12333. /* Send a response to CORS preflights only if
  12334. * access_control_allow_methods is not NULL and not an empty string.
  12335. * In this case, scripts can still handle CORS. */
  12336. const char *cors_meth_cfg =
  12337. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12338. const char *cors_orig_cfg =
  12339. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12340. const char *cors_origin =
  12341. get_header(ri->http_headers, ri->num_headers, "Origin");
  12342. const char *cors_acrm = get_header(ri->http_headers,
  12343. ri->num_headers,
  12344. "Access-Control-Request-Method");
  12345. /* Todo: check if cors_origin is in cors_orig_cfg.
  12346. * Or, let the client check this. */
  12347. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12348. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12349. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12350. /* This is a valid CORS preflight, and the server is configured
  12351. * to
  12352. * handle it automatically. */
  12353. const char *cors_acrh =
  12354. get_header(ri->http_headers,
  12355. ri->num_headers,
  12356. "Access-Control-Request-Headers");
  12357. gmt_time_string(date, sizeof(date), &curtime);
  12358. mg_printf(conn,
  12359. "HTTP/1.1 200 OK\r\n"
  12360. "Date: %s\r\n"
  12361. "Access-Control-Allow-Origin: %s\r\n"
  12362. "Access-Control-Allow-Methods: %s\r\n"
  12363. "Content-Length: 0\r\n"
  12364. "Connection: %s\r\n",
  12365. date,
  12366. cors_orig_cfg,
  12367. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12368. suggest_connection_header(conn));
  12369. if (cors_acrh != NULL) {
  12370. /* CORS request is asking for additional headers */
  12371. const char *cors_hdr_cfg =
  12372. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12373. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12374. /* Allow only if access_control_allow_headers is
  12375. * not NULL and not an empty string. If this
  12376. * configuration is set to *, allow everything.
  12377. * Otherwise this configuration must be a list
  12378. * of allowed HTTP header names. */
  12379. mg_printf(conn,
  12380. "Access-Control-Allow-Headers: %s\r\n",
  12381. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12382. : cors_hdr_cfg));
  12383. }
  12384. }
  12385. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12386. mg_printf(conn, "\r\n");
  12387. return;
  12388. }
  12389. }
  12390. /* 5. interpret the url to find out how the request must be handled
  12391. */
  12392. /* 5.1. first test, if the request targets the regular http(s)://
  12393. * protocol namespace or the websocket ws(s):// protocol namespace.
  12394. */
  12395. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12396. #if defined(USE_WEBSOCKET)
  12397. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12398. #else
  12399. handler_type = REQUEST_HANDLER;
  12400. #endif /* defined(USE_WEBSOCKET) */
  12401. if (is_websocket_request) {
  12402. HTTP1_only;
  12403. }
  12404. /* 5.2. check if the request will be handled by a callback */
  12405. if (get_request_handler(conn,
  12406. handler_type,
  12407. &callback_handler,
  12408. &subprotocols,
  12409. &ws_connect_handler,
  12410. &ws_ready_handler,
  12411. &ws_data_handler,
  12412. &ws_close_handler,
  12413. NULL,
  12414. &callback_data,
  12415. &handler_info)) {
  12416. /* 5.2.1. A callback will handle this request. All requests
  12417. * handled
  12418. * by a callback have to be considered as requests to a script
  12419. * resource. */
  12420. is_callback_resource = 1;
  12421. is_script_resource = 1;
  12422. is_put_or_delete_request = is_put_or_delete_method(conn);
  12423. } else {
  12424. no_callback_resource:
  12425. /* 5.2.2. No callback is responsible for this request. The URI
  12426. * addresses a file based resource (static content or Lua/cgi
  12427. * scripts in the file system). */
  12428. is_callback_resource = 0;
  12429. interpret_uri(conn,
  12430. path,
  12431. sizeof(path),
  12432. &file.stat,
  12433. &is_found,
  12434. &is_script_resource,
  12435. &is_websocket_request,
  12436. &is_put_or_delete_request);
  12437. }
  12438. /* 6. authorization check */
  12439. /* 6.1. a custom authorization handler is installed */
  12440. if (get_request_handler(conn,
  12441. AUTH_HANDLER,
  12442. NULL,
  12443. NULL,
  12444. NULL,
  12445. NULL,
  12446. NULL,
  12447. NULL,
  12448. &auth_handler,
  12449. &auth_callback_data,
  12450. NULL)) {
  12451. if (!auth_handler(conn, auth_callback_data)) {
  12452. return;
  12453. }
  12454. } else if (is_put_or_delete_request && !is_script_resource
  12455. && !is_callback_resource) {
  12456. HTTP1_only;
  12457. /* 6.2. this request is a PUT/DELETE to a real file */
  12458. /* 6.2.1. thus, the server must have real files */
  12459. #if defined(NO_FILES)
  12460. if (1) {
  12461. #else
  12462. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12463. #endif
  12464. /* This server does not have any real files, thus the
  12465. * PUT/DELETE methods are not valid. */
  12466. mg_send_http_error(conn,
  12467. 405,
  12468. "%s method not allowed",
  12469. conn->request_info.request_method);
  12470. return;
  12471. }
  12472. #if !defined(NO_FILES)
  12473. /* 6.2.2. Check if put authorization for static files is
  12474. * available.
  12475. */
  12476. if (!is_authorized_for_put(conn)) {
  12477. send_authorization_request(conn, NULL);
  12478. return;
  12479. }
  12480. #endif
  12481. } else {
  12482. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12483. * or it is a PUT or DELETE request to a resource that does not
  12484. * correspond to a file. Check authorization. */
  12485. if (!check_authorization(conn, path)) {
  12486. send_authorization_request(conn, NULL);
  12487. return;
  12488. }
  12489. }
  12490. /* request is authorized or does not need authorization */
  12491. /* 7. check if there are request handlers for this uri */
  12492. if (is_callback_resource) {
  12493. HTTP1_only;
  12494. if (!is_websocket_request) {
  12495. i = callback_handler(conn, callback_data);
  12496. /* Callback handler will not be used anymore. Release it */
  12497. mg_lock_context(conn->phys_ctx);
  12498. handler_info->refcount--;
  12499. mg_unlock_context(conn->phys_ctx);
  12500. if (i > 0) {
  12501. /* Do nothing, callback has served the request. Store
  12502. * then return value as status code for the log and discard
  12503. * all data from the client not used by the callback. */
  12504. conn->status_code = i;
  12505. if (!conn->must_close) {
  12506. discard_unread_request_data(conn);
  12507. }
  12508. } else {
  12509. /* The handler did NOT handle the request. */
  12510. /* Some proper reactions would be:
  12511. * a) close the connections without sending anything
  12512. * b) send a 404 not found
  12513. * c) try if there is a file matching the URI
  12514. * It would be possible to do a, b or c in the callback
  12515. * implementation, and return 1 - we cannot do anything
  12516. * here, that is not possible in the callback.
  12517. *
  12518. * TODO: What would be the best reaction here?
  12519. * (Note: The reaction may change, if there is a better
  12520. *idea.)
  12521. */
  12522. /* For the moment, use option c: We look for a proper file,
  12523. * but since a file request is not always a script resource,
  12524. * the authorization check might be different. */
  12525. interpret_uri(conn,
  12526. path,
  12527. sizeof(path),
  12528. &file.stat,
  12529. &is_found,
  12530. &is_script_resource,
  12531. &is_websocket_request,
  12532. &is_put_or_delete_request);
  12533. callback_handler = NULL;
  12534. /* Here we are at a dead end:
  12535. * According to URI matching, a callback should be
  12536. * responsible for handling the request,
  12537. * we called it, but the callback declared itself
  12538. * not responsible.
  12539. * We use a goto here, to get out of this dead end,
  12540. * and continue with the default handling.
  12541. * A goto here is simpler and better to understand
  12542. * than some curious loop. */
  12543. goto no_callback_resource;
  12544. }
  12545. } else {
  12546. #if defined(USE_WEBSOCKET)
  12547. handle_websocket_request(conn,
  12548. path,
  12549. is_callback_resource,
  12550. subprotocols,
  12551. ws_connect_handler,
  12552. ws_ready_handler,
  12553. ws_data_handler,
  12554. ws_close_handler,
  12555. callback_data);
  12556. #endif
  12557. }
  12558. return;
  12559. }
  12560. /* 8. handle websocket requests */
  12561. #if defined(USE_WEBSOCKET)
  12562. if (is_websocket_request) {
  12563. HTTP1_only;
  12564. if (is_script_resource) {
  12565. if (is_in_script_path(conn, path)) {
  12566. /* Websocket Lua script */
  12567. handle_websocket_request(conn,
  12568. path,
  12569. 0 /* Lua Script */,
  12570. NULL,
  12571. NULL,
  12572. NULL,
  12573. NULL,
  12574. NULL,
  12575. conn->phys_ctx->user_data);
  12576. } else {
  12577. /* Script was in an illegal path */
  12578. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12579. }
  12580. } else {
  12581. #if defined(MG_LEGACY_INTERFACE)
  12582. handle_websocket_request(
  12583. conn,
  12584. path,
  12585. !is_script_resource /* could be deprecated global callback
  12586. */
  12587. ,
  12588. NULL,
  12589. deprecated_websocket_connect_wrapper,
  12590. deprecated_websocket_ready_wrapper,
  12591. deprecated_websocket_data_wrapper,
  12592. NULL,
  12593. conn->phys_ctx->callbacks);
  12594. #else
  12595. mg_send_http_error(conn, 404, "%s", "Not found");
  12596. #endif
  12597. }
  12598. return;
  12599. } else
  12600. #endif
  12601. #if defined(NO_FILES)
  12602. /* 9a. In case the server uses only callbacks, this uri is
  12603. * unknown.
  12604. * Then, all request handling ends here. */
  12605. mg_send_http_error(conn, 404, "%s", "Not Found");
  12606. #else
  12607. /* 9b. This request is either for a static file or resource handled
  12608. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12609. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12610. mg_send_http_error(conn, 404, "%s", "Not Found");
  12611. return;
  12612. }
  12613. /* 10. Request is handled by a script */
  12614. if (is_script_resource) {
  12615. HTTP1_only;
  12616. handle_file_based_request(conn, path, &file);
  12617. return;
  12618. }
  12619. /* 11. Handle put/delete/mkcol requests */
  12620. if (is_put_or_delete_request) {
  12621. HTTP1_only;
  12622. /* 11.1. PUT method */
  12623. if (!strcmp(ri->request_method, "PUT")) {
  12624. put_file(conn, path);
  12625. return;
  12626. }
  12627. /* 11.2. DELETE method */
  12628. if (!strcmp(ri->request_method, "DELETE")) {
  12629. delete_file(conn, path);
  12630. return;
  12631. }
  12632. /* 11.3. MKCOL method */
  12633. if (!strcmp(ri->request_method, "MKCOL")) {
  12634. mkcol(conn, path);
  12635. return;
  12636. }
  12637. /* 11.4. PATCH method
  12638. * This method is not supported for static resources,
  12639. * only for scripts (Lua, CGI) and callbacks. */
  12640. mg_send_http_error(conn,
  12641. 405,
  12642. "%s method not allowed",
  12643. conn->request_info.request_method);
  12644. return;
  12645. }
  12646. /* 11. File does not exist, or it was configured that it should be
  12647. * hidden */
  12648. if (!is_found || (must_hide_file(conn, path))) {
  12649. mg_send_http_error(conn, 404, "%s", "Not found");
  12650. return;
  12651. }
  12652. /* 12. Directory uris should end with a slash */
  12653. if (file.stat.is_directory && (uri_len > 0)
  12654. && (ri->local_uri[uri_len - 1] != '/')) {
  12655. size_t len = strlen(ri->request_uri);
  12656. char *new_path = mg_malloc_ctx(len + 2, conn->phys_ctx);
  12657. if (!new_path) {
  12658. mg_send_http_error(conn, 500, "out or memory");
  12659. } else {
  12660. memcpy(new_path, ri->request_uri, len);
  12661. new_path[len] = '/';
  12662. new_path[len + 1] = 0;
  12663. mg_send_http_redirect(conn, new_path, 301);
  12664. }
  12665. return;
  12666. }
  12667. /* 13. Handle other methods than GET/HEAD */
  12668. /* 13.1. Handle PROPFIND */
  12669. if (!strcmp(ri->request_method, "PROPFIND")) {
  12670. handle_propfind(conn, path, &file.stat);
  12671. return;
  12672. }
  12673. /* 13.2. Handle OPTIONS for files */
  12674. if (!strcmp(ri->request_method, "OPTIONS")) {
  12675. /* This standard handler is only used for real files.
  12676. * Scripts should support the OPTIONS method themselves, to allow a
  12677. * maximum flexibility.
  12678. * Lua and CGI scripts may fully support CORS this way (including
  12679. * preflights). */
  12680. send_options(conn);
  12681. return;
  12682. }
  12683. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12684. if ((0 != strcmp(ri->request_method, "GET"))
  12685. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12686. mg_send_http_error(conn,
  12687. 405,
  12688. "%s method not allowed",
  12689. conn->request_info.request_method);
  12690. return;
  12691. }
  12692. /* 14. directories */
  12693. if (file.stat.is_directory) {
  12694. /* Substitute files have already been handled above. */
  12695. /* Here we can either generate and send a directory listing,
  12696. * or send an "access denied" error. */
  12697. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12698. "yes")) {
  12699. handle_directory_request(conn, path);
  12700. } else {
  12701. mg_send_http_error(conn,
  12702. 403,
  12703. "%s",
  12704. "Error: Directory listing denied");
  12705. }
  12706. return;
  12707. }
  12708. /* 15. SSI files */
  12709. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12710. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12711. path)
  12712. > 0) {
  12713. if (is_in_script_path(conn, path)) {
  12714. handle_ssi_file_request(conn, path, &file);
  12715. } else {
  12716. /* Script was in an illegal path */
  12717. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12718. }
  12719. return;
  12720. }
  12721. /* 16. Static file - maybe cached */
  12722. #if !defined(NO_CACHING)
  12723. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12724. /* Send 304 "Not Modified" - this must not send any body data */
  12725. handle_not_modified_static_file_request(conn, &file);
  12726. return;
  12727. }
  12728. #endif /* !NO_CACHING */
  12729. /* 17. Static file - not cached */
  12730. handle_static_file_request(conn, path, &file, NULL, NULL);
  12731. #endif /* !defined(NO_FILES) */
  12732. }
  12733. #if !defined(NO_FILESYSTEMS)
  12734. static void
  12735. handle_file_based_request(struct mg_connection *conn,
  12736. const char *path,
  12737. struct mg_file *file)
  12738. {
  12739. if (!conn || !conn->dom_ctx) {
  12740. return;
  12741. }
  12742. if (0) {
  12743. #if defined(USE_LUA)
  12744. } else if (match_prefix(
  12745. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12746. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12747. path)
  12748. > 0) {
  12749. if (is_in_script_path(conn, path)) {
  12750. /* Lua server page: an SSI like page containing mostly plain
  12751. * html code plus some tags with server generated contents. */
  12752. handle_lsp_request(conn, path, file, NULL);
  12753. } else {
  12754. /* Script was in an illegal path */
  12755. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12756. }
  12757. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12758. strlen(
  12759. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12760. path)
  12761. > 0) {
  12762. if (is_in_script_path(conn, path)) {
  12763. /* Lua in-server module script: a CGI like script used to
  12764. * generate
  12765. * the
  12766. * entire reply. */
  12767. mg_exec_lua_script(conn, path, NULL);
  12768. } else {
  12769. /* Script was in an illegal path */
  12770. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12771. }
  12772. #endif
  12773. #if defined(USE_DUKTAPE)
  12774. } else if (match_prefix(
  12775. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12776. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12777. path)
  12778. > 0) {
  12779. if (is_in_script_path(conn, path)) {
  12780. /* Call duktape to generate the page */
  12781. mg_exec_duktape_script(conn, path);
  12782. } else {
  12783. /* Script was in an illegal path */
  12784. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12785. }
  12786. #endif
  12787. #if !defined(NO_CGI)
  12788. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12789. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12790. path)
  12791. > 0) {
  12792. if (is_in_script_path(conn, path)) {
  12793. /* CGI scripts may support all HTTP methods */
  12794. handle_cgi_request(conn, path);
  12795. } else {
  12796. /* Script was in an illegal path */
  12797. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12798. }
  12799. #endif /* !NO_CGI */
  12800. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12801. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12802. path)
  12803. > 0) {
  12804. if (is_in_script_path(conn, path)) {
  12805. handle_ssi_file_request(conn, path, file);
  12806. } else {
  12807. /* Script was in an illegal path */
  12808. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12809. }
  12810. #if !defined(NO_CACHING)
  12811. } else if ((!conn->in_error_handler)
  12812. && is_not_modified(conn, &file->stat)) {
  12813. /* Send 304 "Not Modified" - this must not send any body data */
  12814. handle_not_modified_static_file_request(conn, file);
  12815. #endif /* !NO_CACHING */
  12816. } else {
  12817. handle_static_file_request(conn, path, file, NULL, NULL);
  12818. }
  12819. }
  12820. #endif /* NO_FILESYSTEMS */
  12821. static void
  12822. close_all_listening_sockets(struct mg_context *ctx)
  12823. {
  12824. unsigned int i;
  12825. if (!ctx) {
  12826. return;
  12827. }
  12828. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12829. closesocket(ctx->listening_sockets[i].sock);
  12830. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12831. }
  12832. mg_free(ctx->listening_sockets);
  12833. ctx->listening_sockets = NULL;
  12834. mg_free(ctx->listening_socket_fds);
  12835. ctx->listening_socket_fds = NULL;
  12836. }
  12837. /* Valid listening port specification is: [ip_address:]port[s]
  12838. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12839. * Examples for IPv6: [::]:80, [::1]:80,
  12840. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12841. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12842. * In order to bind to both, IPv4 and IPv6, you can either add
  12843. * both ports using 8080,[::]:8080, or the short form +8080.
  12844. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12845. * one only accepting IPv4 the other only IPv6. +8080 creates
  12846. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12847. * environment, they might work differently, or might not work
  12848. * at all - it must be tested what options work best in the
  12849. * relevant network environment.
  12850. */
  12851. static int
  12852. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12853. {
  12854. unsigned int a, b, c, d;
  12855. unsigned port;
  12856. unsigned long portUL;
  12857. int ch, len;
  12858. const char *cb;
  12859. char *endptr;
  12860. #if defined(USE_IPV6)
  12861. char buf[100] = {0};
  12862. #endif
  12863. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12864. * Also, all-zeroes in the socket address means binding to all addresses
  12865. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12866. memset(so, 0, sizeof(*so));
  12867. so->lsa.sin.sin_family = AF_INET;
  12868. *ip_version = 0;
  12869. /* Initialize port and len as invalid. */
  12870. port = 0;
  12871. len = 0;
  12872. /* Test for different ways to format this string */
  12873. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12874. == 5) {
  12875. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12876. so->lsa.sin.sin_addr.s_addr =
  12877. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12878. so->lsa.sin.sin_port = htons((uint16_t)port);
  12879. *ip_version = 4;
  12880. #if defined(USE_IPV6)
  12881. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12882. && mg_inet_pton(
  12883. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12884. /* IPv6 address, examples: see above */
  12885. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12886. */
  12887. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12888. *ip_version = 6;
  12889. #endif
  12890. } else if ((vec->ptr[0] == '+')
  12891. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12892. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12893. /* Add 1 to len for the + character we skipped before */
  12894. len++;
  12895. #if defined(USE_IPV6)
  12896. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12897. so->lsa.sin6.sin6_family = AF_INET6;
  12898. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12899. *ip_version = 4 + 6;
  12900. #else
  12901. /* Bind to IPv4 only, since IPv6 is not built in. */
  12902. so->lsa.sin.sin_port = htons((uint16_t)port);
  12903. *ip_version = 4;
  12904. #endif
  12905. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12906. && (vec->ptr != endptr)) {
  12907. len = (int)(endptr - vec->ptr);
  12908. port = (uint16_t)portUL;
  12909. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12910. so->lsa.sin.sin_port = htons((uint16_t)port);
  12911. *ip_version = 4;
  12912. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12913. /* String could be a hostname. This check algotithm
  12914. * will only work for RFC 952 compliant hostnames,
  12915. * starting with a letter, containing only letters,
  12916. * digits and hyphen ('-'). Newer specs may allow
  12917. * more, but this is not guaranteed here, since it
  12918. * may interfere with rules for port option lists. */
  12919. /* According to RFC 1035, hostnames are restricted to 255 characters
  12920. * in total (63 between two dots). */
  12921. char hostname[256];
  12922. size_t hostnlen = (size_t)(cb - vec->ptr);
  12923. if (hostnlen >= sizeof(hostname)) {
  12924. /* This would be invalid in any case */
  12925. *ip_version = 0;
  12926. return 0;
  12927. }
  12928. memcpy(hostname, vec->ptr, hostnlen);
  12929. hostname[hostnlen] = 0;
  12930. if (mg_inet_pton(
  12931. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12932. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12933. *ip_version = 4;
  12934. so->lsa.sin.sin_family = AF_INET;
  12935. so->lsa.sin.sin_port = htons((uint16_t)port);
  12936. len += (int)(hostnlen + 1);
  12937. } else {
  12938. port = 0;
  12939. len = 0;
  12940. }
  12941. #if defined(USE_IPV6)
  12942. } else if (mg_inet_pton(AF_INET6,
  12943. hostname,
  12944. &so->lsa.sin6,
  12945. sizeof(so->lsa.sin6))) {
  12946. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12947. *ip_version = 6;
  12948. so->lsa.sin6.sin6_family = AF_INET6;
  12949. so->lsa.sin.sin_port = htons((uint16_t)port);
  12950. len += (int)(hostnlen + 1);
  12951. } else {
  12952. port = 0;
  12953. len = 0;
  12954. }
  12955. #endif
  12956. }
  12957. } else {
  12958. /* Parsing failure. */
  12959. }
  12960. /* sscanf and the option splitting code ensure the following condition
  12961. */
  12962. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12963. *ip_version = 0;
  12964. return 0;
  12965. }
  12966. ch = vec->ptr[len]; /* Next character after the port number */
  12967. so->is_ssl = (ch == 's');
  12968. so->ssl_redir = (ch == 'r');
  12969. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12970. if (is_valid_port(port)
  12971. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12972. return 1;
  12973. }
  12974. /* Reset ip_version to 0 if there is an error */
  12975. *ip_version = 0;
  12976. return 0;
  12977. }
  12978. /* Is there any SSL port in use? */
  12979. static int
  12980. is_ssl_port_used(const char *ports)
  12981. {
  12982. if (ports) {
  12983. /* There are several different allowed syntax variants:
  12984. * - "80" for a single port using every network interface
  12985. * - "localhost:80" for a single port using only localhost
  12986. * - "80,localhost:8080" for two ports, one bound to localhost
  12987. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12988. * to IPv4 localhost, one to IPv6 localhost
  12989. * - "+80" use port 80 for IPv4 and IPv6
  12990. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12991. * for both: IPv4 and IPv4
  12992. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12993. * additionally port 8080 bound to localhost connections
  12994. *
  12995. * If we just look for 's' anywhere in the string, "localhost:80"
  12996. * will be detected as SSL (false positive).
  12997. * Looking for 's' after a digit may cause false positives in
  12998. * "my24service:8080".
  12999. * Looking from 's' backward if there are only ':' and numbers
  13000. * before will not work for "24service:8080" (non SSL, port 8080)
  13001. * or "24s" (SSL, port 24).
  13002. *
  13003. * Remark: Initially hostnames were not allowed to start with a
  13004. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13005. * Section 2.1).
  13006. *
  13007. * To get this correct, the entire string must be parsed as a whole,
  13008. * reading it as a list element for element and parsing with an
  13009. * algorithm equivalent to parse_port_string.
  13010. *
  13011. * In fact, we use local interface names here, not arbitrary
  13012. * hostnames, so in most cases the only name will be "localhost".
  13013. *
  13014. * So, for now, we use this simple algorithm, that may still return
  13015. * a false positive in bizarre cases.
  13016. */
  13017. int i;
  13018. int portslen = (int)strlen(ports);
  13019. char prevIsNumber = 0;
  13020. for (i = 0; i < portslen; i++) {
  13021. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13022. return 1;
  13023. }
  13024. if (ports[i] >= '0' && ports[i] <= '9') {
  13025. prevIsNumber = 1;
  13026. } else {
  13027. prevIsNumber = 0;
  13028. }
  13029. }
  13030. }
  13031. return 0;
  13032. }
  13033. static int
  13034. set_ports_option(struct mg_context *phys_ctx)
  13035. {
  13036. const char *list;
  13037. int on = 1;
  13038. #if defined(USE_IPV6)
  13039. int off = 0;
  13040. #endif
  13041. struct vec vec;
  13042. struct socket so, *ptr;
  13043. struct mg_pollfd *pfd;
  13044. union usa usa;
  13045. socklen_t len;
  13046. int ip_version;
  13047. int portsTotal = 0;
  13048. int portsOk = 0;
  13049. const char *opt_txt;
  13050. long opt_listen_backlog;
  13051. if (!phys_ctx) {
  13052. return 0;
  13053. }
  13054. memset(&so, 0, sizeof(so));
  13055. memset(&usa, 0, sizeof(usa));
  13056. len = sizeof(usa);
  13057. list = phys_ctx->dd.config[LISTENING_PORTS];
  13058. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13059. portsTotal++;
  13060. if (!parse_port_string(&vec, &so, &ip_version)) {
  13061. mg_cry_ctx_internal(
  13062. phys_ctx,
  13063. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13064. (int)vec.len,
  13065. vec.ptr,
  13066. portsTotal,
  13067. "[IP_ADDRESS:]PORT[s|r]");
  13068. continue;
  13069. }
  13070. #if !defined(NO_SSL)
  13071. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13072. mg_cry_ctx_internal(phys_ctx,
  13073. "Cannot add SSL socket (entry %i)",
  13074. portsTotal);
  13075. continue;
  13076. }
  13077. #endif
  13078. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  13079. == INVALID_SOCKET) {
  13080. mg_cry_ctx_internal(phys_ctx,
  13081. "cannot create socket (entry %i)",
  13082. portsTotal);
  13083. continue;
  13084. }
  13085. #if defined(_WIN32)
  13086. /* Windows SO_REUSEADDR lets many procs binds to a
  13087. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13088. * if someone already has the socket -- DTL */
  13089. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13090. * Windows might need a few seconds before
  13091. * the same port can be used again in the
  13092. * same process, so a short Sleep may be
  13093. * required between mg_stop and mg_start.
  13094. */
  13095. if (setsockopt(so.sock,
  13096. SOL_SOCKET,
  13097. SO_EXCLUSIVEADDRUSE,
  13098. (SOCK_OPT_TYPE)&on,
  13099. sizeof(on))
  13100. != 0) {
  13101. /* Set reuse option, but don't abort on errors. */
  13102. mg_cry_ctx_internal(
  13103. phys_ctx,
  13104. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13105. portsTotal);
  13106. }
  13107. #else
  13108. if (setsockopt(so.sock,
  13109. SOL_SOCKET,
  13110. SO_REUSEADDR,
  13111. (SOCK_OPT_TYPE)&on,
  13112. sizeof(on))
  13113. != 0) {
  13114. /* Set reuse option, but don't abort on errors. */
  13115. mg_cry_ctx_internal(
  13116. phys_ctx,
  13117. "cannot set socket option SO_REUSEADDR (entry %i)",
  13118. portsTotal);
  13119. }
  13120. #endif
  13121. if (ip_version > 4) {
  13122. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13123. #if defined(USE_IPV6)
  13124. if (ip_version > 6) {
  13125. if (so.lsa.sa.sa_family == AF_INET6
  13126. && setsockopt(so.sock,
  13127. IPPROTO_IPV6,
  13128. IPV6_V6ONLY,
  13129. (void *)&off,
  13130. sizeof(off))
  13131. != 0) {
  13132. /* Set IPv6 only option, but don't abort on errors. */
  13133. mg_cry_ctx_internal(phys_ctx,
  13134. "cannot set socket option "
  13135. "IPV6_V6ONLY=off (entry %i)",
  13136. portsTotal);
  13137. }
  13138. } else {
  13139. if (so.lsa.sa.sa_family == AF_INET6
  13140. && setsockopt(so.sock,
  13141. IPPROTO_IPV6,
  13142. IPV6_V6ONLY,
  13143. (void *)&on,
  13144. sizeof(on))
  13145. != 0) {
  13146. /* Set IPv6 only option, but don't abort on errors. */
  13147. mg_cry_ctx_internal(phys_ctx,
  13148. "cannot set socket option "
  13149. "IPV6_V6ONLY=on (entry %i)",
  13150. portsTotal);
  13151. }
  13152. }
  13153. #else
  13154. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13155. closesocket(so.sock);
  13156. so.sock = INVALID_SOCKET;
  13157. continue;
  13158. #endif
  13159. }
  13160. if (so.lsa.sa.sa_family == AF_INET) {
  13161. len = sizeof(so.lsa.sin);
  13162. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13163. mg_cry_ctx_internal(phys_ctx,
  13164. "cannot bind to %.*s: %d (%s)",
  13165. (int)vec.len,
  13166. vec.ptr,
  13167. (int)ERRNO,
  13168. strerror(errno));
  13169. closesocket(so.sock);
  13170. so.sock = INVALID_SOCKET;
  13171. continue;
  13172. }
  13173. }
  13174. #if defined(USE_IPV6)
  13175. else if (so.lsa.sa.sa_family == AF_INET6) {
  13176. len = sizeof(so.lsa.sin6);
  13177. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13178. mg_cry_ctx_internal(phys_ctx,
  13179. "cannot bind to IPv6 %.*s: %d (%s)",
  13180. (int)vec.len,
  13181. vec.ptr,
  13182. (int)ERRNO,
  13183. strerror(errno));
  13184. closesocket(so.sock);
  13185. so.sock = INVALID_SOCKET;
  13186. continue;
  13187. }
  13188. }
  13189. #endif
  13190. else {
  13191. mg_cry_ctx_internal(
  13192. phys_ctx,
  13193. "cannot bind: address family not supported (entry %i)",
  13194. portsTotal);
  13195. closesocket(so.sock);
  13196. so.sock = INVALID_SOCKET;
  13197. continue;
  13198. }
  13199. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13200. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13201. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13202. mg_cry_ctx_internal(phys_ctx,
  13203. "%s value \"%s\" is invalid",
  13204. config_options[LISTEN_BACKLOG_SIZE].name,
  13205. opt_txt);
  13206. closesocket(so.sock);
  13207. so.sock = INVALID_SOCKET;
  13208. continue;
  13209. }
  13210. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13211. mg_cry_ctx_internal(phys_ctx,
  13212. "cannot listen to %.*s: %d (%s)",
  13213. (int)vec.len,
  13214. vec.ptr,
  13215. (int)ERRNO,
  13216. strerror(errno));
  13217. closesocket(so.sock);
  13218. so.sock = INVALID_SOCKET;
  13219. continue;
  13220. }
  13221. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13222. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13223. int err = (int)ERRNO;
  13224. mg_cry_ctx_internal(phys_ctx,
  13225. "call to getsockname failed %.*s: %d (%s)",
  13226. (int)vec.len,
  13227. vec.ptr,
  13228. err,
  13229. strerror(errno));
  13230. closesocket(so.sock);
  13231. so.sock = INVALID_SOCKET;
  13232. continue;
  13233. }
  13234. /* Update lsa port in case of random free ports */
  13235. #if defined(USE_IPV6)
  13236. if (so.lsa.sa.sa_family == AF_INET6) {
  13237. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13238. } else
  13239. #endif
  13240. {
  13241. so.lsa.sin.sin_port = usa.sin.sin_port;
  13242. }
  13243. if ((ptr = (struct socket *)
  13244. mg_realloc_ctx(phys_ctx->listening_sockets,
  13245. (phys_ctx->num_listening_sockets + 1)
  13246. * sizeof(phys_ctx->listening_sockets[0]),
  13247. phys_ctx))
  13248. == NULL) {
  13249. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13250. closesocket(so.sock);
  13251. so.sock = INVALID_SOCKET;
  13252. continue;
  13253. }
  13254. if ((pfd = (struct mg_pollfd *)
  13255. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13256. (phys_ctx->num_listening_sockets + 1)
  13257. * sizeof(phys_ctx->listening_socket_fds[0]),
  13258. phys_ctx))
  13259. == NULL) {
  13260. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13261. closesocket(so.sock);
  13262. so.sock = INVALID_SOCKET;
  13263. mg_free(ptr);
  13264. continue;
  13265. }
  13266. set_close_on_exec(so.sock, NULL, phys_ctx);
  13267. phys_ctx->listening_sockets = ptr;
  13268. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13269. phys_ctx->listening_socket_fds = pfd;
  13270. phys_ctx->num_listening_sockets++;
  13271. portsOk++;
  13272. }
  13273. if (portsOk != portsTotal) {
  13274. close_all_listening_sockets(phys_ctx);
  13275. portsOk = 0;
  13276. }
  13277. return portsOk;
  13278. }
  13279. static const char *
  13280. header_val(const struct mg_connection *conn, const char *header)
  13281. {
  13282. const char *header_value;
  13283. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13284. return "-";
  13285. } else {
  13286. return header_value;
  13287. }
  13288. }
  13289. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13290. static void log_access(const struct mg_connection *conn);
  13291. #include "external_log_access.inl"
  13292. #elif !defined(NO_FILESYSTEMS)
  13293. static void
  13294. log_access(const struct mg_connection *conn)
  13295. {
  13296. const struct mg_request_info *ri;
  13297. struct mg_file fi;
  13298. char date[64], src_addr[IP_ADDR_STR_LEN];
  13299. struct tm *tm;
  13300. const char *referer;
  13301. const char *user_agent;
  13302. char buf[4096];
  13303. if (!conn || !conn->dom_ctx) {
  13304. return;
  13305. }
  13306. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13307. if (mg_fopen(conn,
  13308. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13309. MG_FOPEN_MODE_APPEND,
  13310. &fi)
  13311. == 0) {
  13312. fi.access.fp = NULL;
  13313. }
  13314. } else {
  13315. fi.access.fp = NULL;
  13316. }
  13317. /* Log is written to a file and/or a callback. If both are not set,
  13318. * executing the rest of the function is pointless. */
  13319. if ((fi.access.fp == NULL)
  13320. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13321. return;
  13322. }
  13323. tm = localtime(&conn->conn_birth_time);
  13324. if (tm != NULL) {
  13325. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13326. } else {
  13327. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13328. date[sizeof(date) - 1] = '\0';
  13329. }
  13330. ri = &conn->request_info;
  13331. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13332. referer = header_val(conn, "Referer");
  13333. user_agent = header_val(conn, "User-Agent");
  13334. mg_snprintf(conn,
  13335. NULL, /* Ignore truncation in access log */
  13336. buf,
  13337. sizeof(buf),
  13338. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13339. src_addr,
  13340. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13341. date,
  13342. ri->request_method ? ri->request_method : "-",
  13343. ri->request_uri ? ri->request_uri : "-",
  13344. ri->query_string ? "?" : "",
  13345. ri->query_string ? ri->query_string : "",
  13346. ri->http_version,
  13347. conn->status_code,
  13348. conn->num_bytes_sent,
  13349. referer,
  13350. user_agent);
  13351. if (conn->phys_ctx->callbacks.log_access) {
  13352. conn->phys_ctx->callbacks.log_access(conn, buf);
  13353. }
  13354. if (fi.access.fp) {
  13355. int ok = 1;
  13356. flockfile(fi.access.fp);
  13357. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13358. ok = 0;
  13359. }
  13360. if (fflush(fi.access.fp) != 0) {
  13361. ok = 0;
  13362. }
  13363. funlockfile(fi.access.fp);
  13364. if (mg_fclose(&fi.access) != 0) {
  13365. ok = 0;
  13366. }
  13367. if (!ok) {
  13368. mg_cry_internal(conn,
  13369. "Error writing log file %s",
  13370. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13371. }
  13372. }
  13373. }
  13374. #else
  13375. #error Must either enable filesystems or provide a custom log_access implementation
  13376. #endif /* Externally provided function */
  13377. /* Verify given socket address against the ACL.
  13378. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13379. */
  13380. static int
  13381. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13382. {
  13383. int allowed, flag;
  13384. uint32_t net, mask;
  13385. struct vec vec;
  13386. if (phys_ctx) {
  13387. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13388. /* If any ACL is set, deny by default */
  13389. allowed = (list == NULL) ? '+' : '-';
  13390. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13391. flag = vec.ptr[0];
  13392. if ((flag != '+' && flag != '-')
  13393. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13394. mg_cry_ctx_internal(phys_ctx,
  13395. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13396. __func__);
  13397. return -1;
  13398. }
  13399. if (net == (remote_ip & mask)) {
  13400. allowed = flag;
  13401. }
  13402. }
  13403. return allowed == '+';
  13404. }
  13405. return -1;
  13406. }
  13407. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13408. static int
  13409. set_uid_option(struct mg_context *phys_ctx)
  13410. {
  13411. int success = 0;
  13412. if (phys_ctx) {
  13413. /* We are currently running as curr_uid. */
  13414. const uid_t curr_uid = getuid();
  13415. /* If set, we want to run as run_as_user. */
  13416. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13417. const struct passwd *to_pw = NULL;
  13418. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13419. /* run_as_user does not exist on the system. We can't proceed
  13420. * further. */
  13421. mg_cry_ctx_internal(phys_ctx,
  13422. "%s: unknown user [%s]",
  13423. __func__,
  13424. run_as_user);
  13425. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13426. /* There was either no request to change user, or we're already
  13427. * running as run_as_user. Nothing else to do.
  13428. */
  13429. success = 1;
  13430. } else {
  13431. /* Valid change request. */
  13432. if (setgid(to_pw->pw_gid) == -1) {
  13433. mg_cry_ctx_internal(phys_ctx,
  13434. "%s: setgid(%s): %s",
  13435. __func__,
  13436. run_as_user,
  13437. strerror(errno));
  13438. } else if (setgroups(0, NULL) == -1) {
  13439. mg_cry_ctx_internal(phys_ctx,
  13440. "%s: setgroups(): %s",
  13441. __func__,
  13442. strerror(errno));
  13443. } else if (setuid(to_pw->pw_uid) == -1) {
  13444. mg_cry_ctx_internal(phys_ctx,
  13445. "%s: setuid(%s): %s",
  13446. __func__,
  13447. run_as_user,
  13448. strerror(errno));
  13449. } else {
  13450. success = 1;
  13451. }
  13452. }
  13453. }
  13454. return success;
  13455. }
  13456. #endif /* !_WIN32 */
  13457. static void
  13458. tls_dtor(void *key)
  13459. {
  13460. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13461. /* key == pthread_getspecific(sTlsKey); */
  13462. if (tls) {
  13463. if (tls->is_master == 2) {
  13464. tls->is_master = -3; /* Mark memory as dead */
  13465. mg_free(tls);
  13466. }
  13467. }
  13468. pthread_setspecific(sTlsKey, NULL);
  13469. }
  13470. #if !defined(NO_SSL)
  13471. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13472. struct mg_domain_context *dom_ctx,
  13473. const char *pem,
  13474. const char *chain);
  13475. static const char *ssl_error(void);
  13476. static int
  13477. refresh_trust(struct mg_connection *conn)
  13478. {
  13479. struct stat cert_buf;
  13480. int64_t t = 0;
  13481. const char *pem;
  13482. const char *chain;
  13483. int should_verify_peer;
  13484. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13485. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13486. * refresh_trust still can not work. */
  13487. return 0;
  13488. }
  13489. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13490. if (chain == NULL) {
  13491. /* pem is not NULL here */
  13492. chain = pem;
  13493. }
  13494. if (*chain == 0) {
  13495. chain = NULL;
  13496. }
  13497. if (stat(pem, &cert_buf) != -1) {
  13498. t = (int64_t)cert_buf.st_mtime;
  13499. }
  13500. mg_lock_context(conn->phys_ctx);
  13501. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13502. conn->dom_ctx->ssl_cert_last_mtime = t;
  13503. should_verify_peer = 0;
  13504. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13505. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13506. == 0) {
  13507. should_verify_peer = 1;
  13508. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13509. "optional")
  13510. == 0) {
  13511. should_verify_peer = 1;
  13512. }
  13513. }
  13514. if (should_verify_peer) {
  13515. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13516. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13517. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13518. ca_file,
  13519. ca_path)
  13520. != 1) {
  13521. mg_unlock_context(conn->phys_ctx);
  13522. mg_cry_ctx_internal(
  13523. conn->phys_ctx,
  13524. "SSL_CTX_load_verify_locations error: %s "
  13525. "ssl_verify_peer requires setting "
  13526. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13527. "present in "
  13528. "the .conf file?",
  13529. ssl_error());
  13530. return 0;
  13531. }
  13532. }
  13533. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13534. mg_unlock_context(conn->phys_ctx);
  13535. return 0;
  13536. }
  13537. }
  13538. mg_unlock_context(conn->phys_ctx);
  13539. return 1;
  13540. }
  13541. #if defined(OPENSSL_API_1_1)
  13542. #else
  13543. static pthread_mutex_t *ssl_mutexes;
  13544. #endif /* OPENSSL_API_1_1 */
  13545. static int
  13546. sslize(struct mg_connection *conn,
  13547. int (*func)(SSL *),
  13548. const struct mg_client_options *client_options)
  13549. {
  13550. int ret, err;
  13551. int short_trust;
  13552. unsigned timeout = 1024;
  13553. unsigned i;
  13554. if (!conn) {
  13555. return 0;
  13556. }
  13557. short_trust =
  13558. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13559. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13560. if (short_trust) {
  13561. int trust_ret = refresh_trust(conn);
  13562. if (!trust_ret) {
  13563. return trust_ret;
  13564. }
  13565. }
  13566. mg_lock_context(conn->phys_ctx);
  13567. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13568. mg_unlock_context(conn->phys_ctx);
  13569. if (conn->ssl == NULL) {
  13570. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13571. OPENSSL_REMOVE_THREAD_STATE();
  13572. return 0;
  13573. }
  13574. SSL_set_app_data(conn->ssl, (char *)conn);
  13575. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13576. if (ret != 1) {
  13577. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13578. SSL_free(conn->ssl);
  13579. conn->ssl = NULL;
  13580. OPENSSL_REMOVE_THREAD_STATE();
  13581. return 0;
  13582. }
  13583. if (client_options) {
  13584. if (client_options->host_name) {
  13585. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13586. }
  13587. }
  13588. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13589. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13590. /* NOTE: The loop below acts as a back-off, so we can end
  13591. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13592. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13593. if (to >= 0) {
  13594. timeout = (unsigned)to;
  13595. }
  13596. }
  13597. /* SSL functions may fail and require to be called again:
  13598. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13599. * Here "func" could be SSL_connect or SSL_accept. */
  13600. for (i = 0; i <= timeout; i += 50) {
  13601. ERR_clear_error();
  13602. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13603. ret = func(conn->ssl);
  13604. if (ret != 1) {
  13605. err = SSL_get_error(conn->ssl, ret);
  13606. if ((err == SSL_ERROR_WANT_CONNECT)
  13607. || (err == SSL_ERROR_WANT_ACCEPT)
  13608. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13609. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13610. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13611. /* Don't wait if the server is going to be stopped. */
  13612. break;
  13613. }
  13614. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13615. /* Simply retry the function call. */
  13616. mg_sleep(50);
  13617. } else {
  13618. /* Need to retry the function call "later".
  13619. * See https://linux.die.net/man/3/ssl_get_error
  13620. * This is typical for non-blocking sockets. */
  13621. struct mg_pollfd pfd;
  13622. int pollres;
  13623. pfd.fd = conn->client.sock;
  13624. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13625. || (err == SSL_ERROR_WANT_WRITE))
  13626. ? POLLOUT
  13627. : POLLIN;
  13628. pollres =
  13629. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13630. if (pollres < 0) {
  13631. /* Break if error occured (-1)
  13632. * or server shutdown (-2) */
  13633. break;
  13634. }
  13635. }
  13636. } else if (err == SSL_ERROR_SYSCALL) {
  13637. /* This is an IO error. Look at errno. */
  13638. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13639. break;
  13640. } else {
  13641. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13642. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13643. break;
  13644. }
  13645. } else {
  13646. /* success */
  13647. break;
  13648. }
  13649. }
  13650. ERR_clear_error();
  13651. if (ret != 1) {
  13652. SSL_free(conn->ssl);
  13653. conn->ssl = NULL;
  13654. OPENSSL_REMOVE_THREAD_STATE();
  13655. return 0;
  13656. }
  13657. return 1;
  13658. }
  13659. /* Return OpenSSL error message (from CRYPTO lib) */
  13660. static const char *
  13661. ssl_error(void)
  13662. {
  13663. unsigned long err;
  13664. err = ERR_get_error();
  13665. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13666. }
  13667. static int
  13668. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13669. {
  13670. int i;
  13671. const char hexdigit[] = "0123456789abcdef";
  13672. if ((memlen <= 0) || (buflen <= 0)) {
  13673. return 0;
  13674. }
  13675. if (buflen < (3 * memlen)) {
  13676. return 0;
  13677. }
  13678. for (i = 0; i < memlen; i++) {
  13679. if (i > 0) {
  13680. buf[3 * i - 1] = ' ';
  13681. }
  13682. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13683. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13684. }
  13685. buf[3 * memlen - 1] = 0;
  13686. return 1;
  13687. }
  13688. static int
  13689. ssl_get_client_cert_info(const struct mg_connection *conn,
  13690. struct mg_client_cert *client_cert)
  13691. {
  13692. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13693. if (cert) {
  13694. char str_buf[1024];
  13695. unsigned char buf[256];
  13696. char *str_serial = NULL;
  13697. unsigned int ulen;
  13698. int ilen;
  13699. unsigned char *tmp_buf;
  13700. unsigned char *tmp_p;
  13701. /* Handle to algorithm used for fingerprint */
  13702. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13703. /* Get Subject and issuer */
  13704. X509_NAME *subj = X509_get_subject_name(cert);
  13705. X509_NAME *iss = X509_get_issuer_name(cert);
  13706. /* Get serial number */
  13707. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13708. /* Translate serial number to a hex string */
  13709. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13710. if (serial_bn) {
  13711. str_serial = BN_bn2hex(serial_bn);
  13712. BN_free(serial_bn);
  13713. }
  13714. client_cert->serial =
  13715. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13716. /* Translate subject and issuer to a string */
  13717. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13718. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13719. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13720. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13721. /* Calculate SHA1 fingerprint and store as a hex string */
  13722. ulen = 0;
  13723. /* ASN1_digest is deprecated. Do the calculation manually,
  13724. * using EVP_Digest. */
  13725. ilen = i2d_X509(cert, NULL);
  13726. tmp_buf = (ilen > 0)
  13727. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13728. conn->phys_ctx)
  13729. : NULL;
  13730. if (tmp_buf) {
  13731. tmp_p = tmp_buf;
  13732. (void)i2d_X509(cert, &tmp_p);
  13733. if (!EVP_Digest(
  13734. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13735. ulen = 0;
  13736. }
  13737. mg_free(tmp_buf);
  13738. }
  13739. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13740. *str_buf = 0;
  13741. }
  13742. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13743. client_cert->peer_cert = (void *)cert;
  13744. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13745. * see https://linux.die.net/man/3/bn_bn2hex */
  13746. OPENSSL_free(str_serial);
  13747. return 1;
  13748. }
  13749. return 0;
  13750. }
  13751. #if defined(OPENSSL_API_1_1)
  13752. #else
  13753. static void
  13754. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13755. {
  13756. (void)line;
  13757. (void)file;
  13758. if (mode & 1) {
  13759. /* 1 is CRYPTO_LOCK */
  13760. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13761. } else {
  13762. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13763. }
  13764. }
  13765. #endif /* OPENSSL_API_1_1 */
  13766. #if !defined(NO_SSL_DL)
  13767. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13768. static void *
  13769. load_tls_dll(char *ebuf,
  13770. size_t ebuf_len,
  13771. const char *dll_name,
  13772. struct ssl_func *sw)
  13773. {
  13774. union {
  13775. void *p;
  13776. void (*fp)(void);
  13777. } u;
  13778. void *dll_handle;
  13779. struct ssl_func *fp;
  13780. int ok;
  13781. int truncated = 0;
  13782. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13783. mg_snprintf(NULL,
  13784. NULL, /* No truncation check for ebuf */
  13785. ebuf,
  13786. ebuf_len,
  13787. "%s: cannot load %s",
  13788. __func__,
  13789. dll_name);
  13790. return NULL;
  13791. }
  13792. ok = 1;
  13793. for (fp = sw; fp->name != NULL; fp++) {
  13794. enum ssl_func_category req = fp->required;
  13795. #if defined(_WIN32)
  13796. /* GetProcAddress() returns pointer to function */
  13797. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13798. #else
  13799. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13800. * pointers to function pointers. We need to use a union to make a
  13801. * cast. */
  13802. u.p = dlsym(dll_handle, fp->name);
  13803. #endif /* _WIN32 */
  13804. /* Set pointer (might be NULL) */
  13805. fp->ptr = u.fp;
  13806. if (u.fp == NULL) {
  13807. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13808. tls_feature_missing[req]++;
  13809. if (req == TLS_Mandatory) {
  13810. /* Mandatory function is missing */
  13811. if (ok) {
  13812. /* This is the first missing function.
  13813. * Create a new error message. */
  13814. mg_snprintf(NULL,
  13815. &truncated,
  13816. ebuf,
  13817. ebuf_len,
  13818. "%s: %s: cannot find %s",
  13819. __func__,
  13820. dll_name,
  13821. fp->name);
  13822. ok = 0;
  13823. } else {
  13824. /* This is yet anothermissing function.
  13825. * Append existing error message. */
  13826. size_t cur_len = strlen(ebuf);
  13827. if (!truncated) {
  13828. mg_snprintf(NULL,
  13829. &truncated,
  13830. ebuf + cur_len,
  13831. ebuf_len - cur_len - 3,
  13832. ", %s",
  13833. fp->name);
  13834. if (truncated) {
  13835. /* If truncated, add "..." */
  13836. strcat(ebuf, "...");
  13837. }
  13838. }
  13839. }
  13840. }
  13841. }
  13842. }
  13843. if (!ok) {
  13844. (void)dlclose(dll_handle);
  13845. return NULL;
  13846. }
  13847. return dll_handle;
  13848. }
  13849. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13850. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13851. #endif /* NO_SSL_DL */
  13852. #if defined(SSL_ALREADY_INITIALIZED)
  13853. static volatile ptrdiff_t cryptolib_users =
  13854. 1; /* Reference counter for crypto library. */
  13855. #else
  13856. static volatile ptrdiff_t cryptolib_users =
  13857. 0; /* Reference counter for crypto library. */
  13858. #endif
  13859. static int
  13860. initialize_ssl(char *ebuf, size_t ebuf_len)
  13861. {
  13862. #if defined(OPENSSL_API_1_1)
  13863. if (ebuf_len > 0) {
  13864. ebuf[0] = 0;
  13865. }
  13866. #if !defined(NO_SSL_DL)
  13867. if (!cryptolib_dll_handle) {
  13868. cryptolib_dll_handle =
  13869. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13870. if (!cryptolib_dll_handle) {
  13871. mg_snprintf(NULL,
  13872. NULL, /* No truncation check for ebuf */
  13873. ebuf,
  13874. ebuf_len,
  13875. "%s: error loading library %s",
  13876. __func__,
  13877. CRYPTO_LIB);
  13878. DEBUG_TRACE("%s", ebuf);
  13879. return 0;
  13880. }
  13881. }
  13882. #endif /* NO_SSL_DL */
  13883. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13884. return 1;
  13885. }
  13886. #else /* not OPENSSL_API_1_1 */
  13887. int i, num_locks;
  13888. size_t size;
  13889. if (ebuf_len > 0) {
  13890. ebuf[0] = 0;
  13891. }
  13892. #if !defined(NO_SSL_DL)
  13893. if (!cryptolib_dll_handle) {
  13894. cryptolib_dll_handle =
  13895. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13896. if (!cryptolib_dll_handle) {
  13897. mg_snprintf(NULL,
  13898. NULL, /* No truncation check for ebuf */
  13899. ebuf,
  13900. ebuf_len,
  13901. "%s: error loading library %s",
  13902. __func__,
  13903. CRYPTO_LIB);
  13904. DEBUG_TRACE("%s", ebuf);
  13905. return 0;
  13906. }
  13907. }
  13908. #endif /* NO_SSL_DL */
  13909. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13910. return 1;
  13911. }
  13912. /* Initialize locking callbacks, needed for thread safety.
  13913. * http://www.openssl.org/support/faq.html#PROG1
  13914. */
  13915. num_locks = CRYPTO_num_locks();
  13916. if (num_locks < 0) {
  13917. num_locks = 0;
  13918. }
  13919. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13920. /* allocate mutex array, if required */
  13921. if (num_locks == 0) {
  13922. /* No mutex array required */
  13923. ssl_mutexes = NULL;
  13924. } else {
  13925. /* Mutex array required - allocate it */
  13926. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13927. /* Check OOM */
  13928. if (ssl_mutexes == NULL) {
  13929. mg_snprintf(NULL,
  13930. NULL, /* No truncation check for ebuf */
  13931. ebuf,
  13932. ebuf_len,
  13933. "%s: cannot allocate mutexes: %s",
  13934. __func__,
  13935. ssl_error());
  13936. DEBUG_TRACE("%s", ebuf);
  13937. return 0;
  13938. }
  13939. /* initialize mutex array */
  13940. for (i = 0; i < num_locks; i++) {
  13941. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13942. mg_snprintf(NULL,
  13943. NULL, /* No truncation check for ebuf */
  13944. ebuf,
  13945. ebuf_len,
  13946. "%s: error initializing mutex %i of %i",
  13947. __func__,
  13948. i,
  13949. num_locks);
  13950. DEBUG_TRACE("%s", ebuf);
  13951. mg_free(ssl_mutexes);
  13952. return 0;
  13953. }
  13954. }
  13955. }
  13956. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13957. CRYPTO_set_id_callback(&mg_current_thread_id);
  13958. #endif /* OPENSSL_API_1_1 */
  13959. #if !defined(NO_SSL_DL)
  13960. if (!ssllib_dll_handle) {
  13961. ssllib_dll_handle = load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13962. if (!ssllib_dll_handle) {
  13963. #if !defined(OPENSSL_API_1_1)
  13964. mg_free(ssl_mutexes);
  13965. #endif
  13966. DEBUG_TRACE("%s", ebuf);
  13967. return 0;
  13968. }
  13969. }
  13970. #endif /* NO_SSL_DL */
  13971. #if defined(OPENSSL_API_1_1)
  13972. /* Initialize SSL library */
  13973. OPENSSL_init_ssl(0, NULL);
  13974. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13975. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13976. NULL);
  13977. #else
  13978. /* Initialize SSL library */
  13979. SSL_library_init();
  13980. SSL_load_error_strings();
  13981. #endif
  13982. return 1;
  13983. }
  13984. static int
  13985. ssl_use_pem_file(struct mg_context *phys_ctx,
  13986. struct mg_domain_context *dom_ctx,
  13987. const char *pem,
  13988. const char *chain)
  13989. {
  13990. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13991. mg_cry_ctx_internal(phys_ctx,
  13992. "%s: cannot open certificate file %s: %s",
  13993. __func__,
  13994. pem,
  13995. ssl_error());
  13996. return 0;
  13997. }
  13998. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13999. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14000. mg_cry_ctx_internal(phys_ctx,
  14001. "%s: cannot open private key file %s: %s",
  14002. __func__,
  14003. pem,
  14004. ssl_error());
  14005. return 0;
  14006. }
  14007. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14008. mg_cry_ctx_internal(phys_ctx,
  14009. "%s: certificate and private key do not match: %s",
  14010. __func__,
  14011. pem);
  14012. return 0;
  14013. }
  14014. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14015. * chain files that contain private keys and certificates in
  14016. * SSL_CTX_use_certificate_chain_file.
  14017. * The CivetWeb-Server used pem-Files that contained both information.
  14018. * In order to make wolfSSL work, it is split in two files.
  14019. * One file that contains key and certificate used by the server and
  14020. * an optional chain file for the ssl stack.
  14021. */
  14022. if (chain) {
  14023. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14024. mg_cry_ctx_internal(phys_ctx,
  14025. "%s: cannot use certificate chain file %s: %s",
  14026. __func__,
  14027. chain,
  14028. ssl_error());
  14029. return 0;
  14030. }
  14031. }
  14032. return 1;
  14033. }
  14034. #if defined(OPENSSL_API_1_1)
  14035. static unsigned long
  14036. ssl_get_protocol(int version_id)
  14037. {
  14038. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14039. if (version_id > 0)
  14040. ret |= SSL_OP_NO_SSLv2;
  14041. if (version_id > 1)
  14042. ret |= SSL_OP_NO_SSLv3;
  14043. if (version_id > 2)
  14044. ret |= SSL_OP_NO_TLSv1;
  14045. if (version_id > 3)
  14046. ret |= SSL_OP_NO_TLSv1_1;
  14047. if (version_id > 4)
  14048. ret |= SSL_OP_NO_TLSv1_2;
  14049. #if defined(SSL_OP_NO_TLSv1_3)
  14050. if (version_id > 5)
  14051. ret |= SSL_OP_NO_TLSv1_3;
  14052. #endif
  14053. return ret;
  14054. }
  14055. #else
  14056. static long
  14057. ssl_get_protocol(int version_id)
  14058. {
  14059. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14060. if (version_id > 0)
  14061. ret |= SSL_OP_NO_SSLv2;
  14062. if (version_id > 1)
  14063. ret |= SSL_OP_NO_SSLv3;
  14064. if (version_id > 2)
  14065. ret |= SSL_OP_NO_TLSv1;
  14066. if (version_id > 3)
  14067. ret |= SSL_OP_NO_TLSv1_1;
  14068. if (version_id > 4)
  14069. ret |= SSL_OP_NO_TLSv1_2;
  14070. #if defined(SSL_OP_NO_TLSv1_3)
  14071. if (version_id > 5)
  14072. ret |= SSL_OP_NO_TLSv1_3;
  14073. #endif
  14074. return (long)ret;
  14075. }
  14076. #endif /* OPENSSL_API_1_1 */
  14077. /* SSL callback documentation:
  14078. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14079. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14080. * https://linux.die.net/man/3/ssl_set_info_callback */
  14081. /* Note: There is no "const" for the first argument in the documentation
  14082. * examples, however some (maybe most, but not all) headers of OpenSSL
  14083. * versions / OpenSSL compatibility layers have it. Having a different
  14084. * definition will cause a warning in C and an error in C++. Use "const SSL
  14085. * *", while automatical conversion from "SSL *" works for all compilers,
  14086. * but not other way around */
  14087. static void
  14088. ssl_info_callback(const SSL *ssl, int what, int ret)
  14089. {
  14090. (void)ret;
  14091. if (what & SSL_CB_HANDSHAKE_START) {
  14092. SSL_get_app_data(ssl);
  14093. }
  14094. if (what & SSL_CB_HANDSHAKE_DONE) {
  14095. /* TODO: check for openSSL 1.1 */
  14096. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14097. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14098. }
  14099. }
  14100. static int
  14101. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14102. {
  14103. #if defined(GCC_DIAGNOSTIC)
  14104. #pragma GCC diagnostic push
  14105. #pragma GCC diagnostic ignored "-Wcast-align"
  14106. #endif /* defined(GCC_DIAGNOSTIC) */
  14107. /* We used an aligned pointer in SSL_set_app_data */
  14108. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14109. #if defined(GCC_DIAGNOSTIC)
  14110. #pragma GCC diagnostic pop
  14111. #endif /* defined(GCC_DIAGNOSTIC) */
  14112. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14113. (void)ad;
  14114. (void)arg;
  14115. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14116. DEBUG_ASSERT(0);
  14117. return SSL_TLSEXT_ERR_NOACK;
  14118. }
  14119. conn->dom_ctx = &(conn->phys_ctx->dd);
  14120. /* Old clients (Win XP) will not support SNI. Then, there
  14121. * is no server name available in the request - we can
  14122. * only work with the default certificate.
  14123. * Multiple HTTPS hosts on one IP+port are only possible
  14124. * with a certificate containing all alternative names.
  14125. */
  14126. if ((servername == NULL) || (*servername == 0)) {
  14127. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14128. mg_lock_context(conn->phys_ctx);
  14129. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14130. mg_unlock_context(conn->phys_ctx);
  14131. return SSL_TLSEXT_ERR_NOACK;
  14132. }
  14133. DEBUG_TRACE("TLS connection to host %s", servername);
  14134. while (conn->dom_ctx) {
  14135. if (!mg_strcasecmp(servername,
  14136. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14137. /* Found matching domain */
  14138. DEBUG_TRACE("TLS domain %s found",
  14139. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14140. break;
  14141. }
  14142. mg_lock_context(conn->phys_ctx);
  14143. conn->dom_ctx = conn->dom_ctx->next;
  14144. mg_unlock_context(conn->phys_ctx);
  14145. }
  14146. if (conn->dom_ctx == NULL) {
  14147. /* Default domain */
  14148. DEBUG_TRACE("TLS default domain %s used",
  14149. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14150. conn->dom_ctx = &(conn->phys_ctx->dd);
  14151. }
  14152. mg_lock_context(conn->phys_ctx);
  14153. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14154. mg_unlock_context(conn->phys_ctx);
  14155. return SSL_TLSEXT_ERR_OK;
  14156. }
  14157. #if defined(USE_HTTP2)
  14158. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14159. static const char *alpn_proto_order[] = {alpn_proto_list,
  14160. alpn_proto_list + 3,
  14161. alpn_proto_list + 3 + 8,
  14162. NULL};
  14163. #else
  14164. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14165. static const char *alpn_proto_order[] = {alpn_proto_list,
  14166. alpn_proto_list + 8,
  14167. NULL};
  14168. #endif
  14169. static int
  14170. alpn_select_cb(SSL *ssl,
  14171. const unsigned char **out,
  14172. unsigned char *outlen,
  14173. const unsigned char *in,
  14174. unsigned int inlen,
  14175. void *arg)
  14176. {
  14177. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14178. unsigned int i, j;
  14179. struct mg_workerTLS *tls =
  14180. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14181. (void)ssl;
  14182. (void)dom_ctx;
  14183. if (tls == NULL) {
  14184. /* Need to store protocol in Thread Local Storage */
  14185. /* If there is no Thread Local Storage, don't use ALPN */
  14186. return SSL_TLSEXT_ERR_NOACK;
  14187. }
  14188. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14189. /* check all accepted protocols in this order */
  14190. const char *alpn_proto = alpn_proto_order[j];
  14191. /* search input for matching protocol */
  14192. for (i = 0; i < inlen; i++) {
  14193. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14194. *out = in + i + 1;
  14195. *outlen = in[i];
  14196. tls->alpn_proto = alpn_proto;
  14197. return SSL_TLSEXT_ERR_OK;
  14198. }
  14199. }
  14200. }
  14201. /* Nothing found */
  14202. return SSL_TLSEXT_ERR_NOACK;
  14203. }
  14204. static int
  14205. next_protos_advertised_cb(SSL *ssl,
  14206. const unsigned char **data,
  14207. unsigned int *len,
  14208. void *arg)
  14209. {
  14210. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14211. *data = (const unsigned char *)alpn_proto_list;
  14212. *len = (unsigned int)strlen((const char *)data);
  14213. (void)ssl;
  14214. (void)dom_ctx;
  14215. return SSL_TLSEXT_ERR_OK;
  14216. }
  14217. static int
  14218. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14219. {
  14220. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14221. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14222. (const unsigned char *)alpn_proto_list,
  14223. alpn_len);
  14224. if (ret != 0) {
  14225. mg_cry_ctx_internal(phys_ctx,
  14226. "SSL_CTX_set_alpn_protos error: %s",
  14227. ssl_error());
  14228. }
  14229. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14230. alpn_select_cb,
  14231. (void *)dom_ctx);
  14232. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14233. next_protos_advertised_cb,
  14234. (void *)dom_ctx);
  14235. return ret;
  14236. }
  14237. /* Setup SSL CTX as required by CivetWeb */
  14238. static int
  14239. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14240. struct mg_domain_context *dom_ctx,
  14241. const char *pem,
  14242. const char *chain)
  14243. {
  14244. int callback_ret;
  14245. int should_verify_peer;
  14246. int peer_certificate_optional;
  14247. const char *ca_path;
  14248. const char *ca_file;
  14249. int use_default_verify_paths;
  14250. int verify_depth;
  14251. struct timespec now_mt;
  14252. md5_byte_t ssl_context_id[16];
  14253. md5_state_t md5state;
  14254. int protocol_ver;
  14255. #if defined(OPENSSL_API_1_1)
  14256. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14257. mg_cry_ctx_internal(phys_ctx,
  14258. "SSL_CTX_new (server) error: %s",
  14259. ssl_error());
  14260. return 0;
  14261. }
  14262. #else
  14263. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14264. mg_cry_ctx_internal(phys_ctx,
  14265. "SSL_CTX_new (server) error: %s",
  14266. ssl_error());
  14267. return 0;
  14268. }
  14269. #endif /* OPENSSL_API_1_1 */
  14270. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14271. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14272. | SSL_OP_NO_TLSv1_1);
  14273. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14274. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14275. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14276. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14277. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14278. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14279. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14280. #if defined(SSL_OP_NO_RENEGOTIATION)
  14281. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14282. #endif
  14283. #if !defined(NO_SSL_DL)
  14284. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14285. #endif /* NO_SSL_DL */
  14286. /* In SSL documentation examples callback defined without const
  14287. * specifier 'void (*)(SSL *, int, int)' See:
  14288. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14289. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14290. * But in the source code const SSL is used:
  14291. * 'void (*)(const SSL *, int, int)' See:
  14292. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14293. * Problem about wrong documentation described, but not resolved:
  14294. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14295. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14296. * But when compiled with modern C++ compiler, correct const should be
  14297. * provided
  14298. */
  14299. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14300. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14301. ssl_servername_callback);
  14302. /* If a callback has been specified, call it. */
  14303. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14304. ? 0
  14305. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14306. phys_ctx->user_data));
  14307. /* If callback returns 0, civetweb sets up the SSL certificate.
  14308. * If it returns 1, civetweb assumes the calback already did this.
  14309. * If it returns -1, initializing ssl fails. */
  14310. if (callback_ret < 0) {
  14311. mg_cry_ctx_internal(phys_ctx,
  14312. "SSL callback returned error: %i",
  14313. callback_ret);
  14314. return 0;
  14315. }
  14316. if (callback_ret > 0) {
  14317. /* Callback did everything. */
  14318. return 1;
  14319. }
  14320. /* If a domain callback has been specified, call it. */
  14321. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14322. ? 0
  14323. : (phys_ctx->callbacks.init_ssl_domain(
  14324. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14325. dom_ctx->ssl_ctx,
  14326. phys_ctx->user_data));
  14327. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14328. * If it returns 1, civetweb assumes the calback already did this.
  14329. * If it returns -1, initializing ssl fails. */
  14330. if (callback_ret < 0) {
  14331. mg_cry_ctx_internal(phys_ctx,
  14332. "Domain SSL callback returned error: %i",
  14333. callback_ret);
  14334. return 0;
  14335. }
  14336. if (callback_ret > 0) {
  14337. /* Domain callback did everything. */
  14338. return 1;
  14339. }
  14340. /* Use some combination of start time, domain and port as a SSL
  14341. * context ID. This should be unique on the current machine. */
  14342. md5_init(&md5state);
  14343. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14344. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14345. md5_append(&md5state,
  14346. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14347. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14348. md5_append(&md5state,
  14349. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14350. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14351. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14352. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14353. md5_finish(&md5state, ssl_context_id);
  14354. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14355. (unsigned char *)ssl_context_id,
  14356. sizeof(ssl_context_id));
  14357. if (pem != NULL) {
  14358. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14359. return 0;
  14360. }
  14361. }
  14362. /* Should we support client certificates? */
  14363. /* Default is "no". */
  14364. should_verify_peer = 0;
  14365. peer_certificate_optional = 0;
  14366. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14367. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14368. /* Yes, they are mandatory */
  14369. should_verify_peer = 1;
  14370. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14371. "optional")
  14372. == 0) {
  14373. /* Yes, they are optional */
  14374. should_verify_peer = 1;
  14375. peer_certificate_optional = 1;
  14376. }
  14377. }
  14378. use_default_verify_paths =
  14379. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14380. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14381. == 0);
  14382. if (should_verify_peer) {
  14383. ca_path = dom_ctx->config[SSL_CA_PATH];
  14384. ca_file = dom_ctx->config[SSL_CA_FILE];
  14385. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14386. != 1) {
  14387. mg_cry_ctx_internal(phys_ctx,
  14388. "SSL_CTX_load_verify_locations error: %s "
  14389. "ssl_verify_peer requires setting "
  14390. "either ssl_ca_path or ssl_ca_file. "
  14391. "Is any of them present in the "
  14392. ".conf file?",
  14393. ssl_error());
  14394. return 0;
  14395. }
  14396. if (peer_certificate_optional) {
  14397. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14398. } else {
  14399. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14400. SSL_VERIFY_PEER
  14401. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14402. NULL);
  14403. }
  14404. if (use_default_verify_paths
  14405. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14406. mg_cry_ctx_internal(phys_ctx,
  14407. "SSL_CTX_set_default_verify_paths error: %s",
  14408. ssl_error());
  14409. return 0;
  14410. }
  14411. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14412. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14413. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14414. }
  14415. }
  14416. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14417. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14418. dom_ctx->config[SSL_CIPHER_LIST])
  14419. != 1) {
  14420. mg_cry_ctx_internal(phys_ctx,
  14421. "SSL_CTX_set_cipher_list error: %s",
  14422. ssl_error());
  14423. }
  14424. }
  14425. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14426. #if !defined(NO_SSL_DL)
  14427. if (!tls_feature_missing[TLS_ALPN])
  14428. #endif
  14429. {
  14430. init_alpn(phys_ctx, dom_ctx);
  14431. }
  14432. return 1;
  14433. }
  14434. /* Check if SSL is required.
  14435. * If so, dynamically load SSL library
  14436. * and set up ctx->ssl_ctx pointer. */
  14437. static int
  14438. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14439. {
  14440. void *ssl_ctx = 0;
  14441. int callback_ret;
  14442. const char *pem;
  14443. const char *chain;
  14444. char ebuf[128];
  14445. if (!phys_ctx) {
  14446. return 0;
  14447. }
  14448. if (!dom_ctx) {
  14449. dom_ctx = &(phys_ctx->dd);
  14450. }
  14451. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14452. /* No SSL port is set. No need to setup SSL. */
  14453. return 1;
  14454. }
  14455. /* Check for external SSL_CTX */
  14456. callback_ret =
  14457. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14458. ? 0
  14459. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14460. phys_ctx->user_data));
  14461. if (callback_ret < 0) {
  14462. mg_cry_ctx_internal(phys_ctx,
  14463. "external_ssl_ctx callback returned error: %i",
  14464. callback_ret);
  14465. return 0;
  14466. } else if (callback_ret > 0) {
  14467. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14468. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14469. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14470. return 0;
  14471. }
  14472. return 1;
  14473. }
  14474. /* Check for external domain SSL_CTX */
  14475. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14476. ? 0
  14477. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14478. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14479. &ssl_ctx,
  14480. phys_ctx->user_data));
  14481. if (callback_ret < 0) {
  14482. mg_cry_ctx_internal(
  14483. phys_ctx,
  14484. "external_ssl_ctx_domain callback returned error: %i",
  14485. callback_ret);
  14486. return 0;
  14487. } else if (callback_ret > 0) {
  14488. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14489. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14490. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14491. return 0;
  14492. }
  14493. return 1;
  14494. }
  14495. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14496. * 0, CivetWeb should continue initializing SSL */
  14497. /* If PEM file is not specified and the init_ssl callbacks
  14498. * are not specified, setup will fail. */
  14499. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14500. && (phys_ctx->callbacks.init_ssl == NULL)
  14501. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14502. /* No certificate and no init_ssl callbacks:
  14503. * Essential data to set up TLS is missing.
  14504. */
  14505. mg_cry_ctx_internal(phys_ctx,
  14506. "Initializing SSL failed: -%s is not set",
  14507. config_options[SSL_CERTIFICATE].name);
  14508. return 0;
  14509. }
  14510. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14511. if (chain == NULL) {
  14512. chain = pem;
  14513. }
  14514. if ((chain != NULL) && (*chain == 0)) {
  14515. chain = NULL;
  14516. }
  14517. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14518. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14519. return 0;
  14520. }
  14521. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14522. }
  14523. static void
  14524. uninitialize_ssl(void)
  14525. {
  14526. #if defined(OPENSSL_API_1_1)
  14527. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14528. /* Shutdown according to
  14529. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14530. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14531. */
  14532. CONF_modules_unload(1);
  14533. #else
  14534. int i;
  14535. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14536. /* Shutdown according to
  14537. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14538. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14539. */
  14540. CRYPTO_set_locking_callback(NULL);
  14541. CRYPTO_set_id_callback(NULL);
  14542. ENGINE_cleanup();
  14543. CONF_modules_unload(1);
  14544. ERR_free_strings();
  14545. EVP_cleanup();
  14546. CRYPTO_cleanup_all_ex_data();
  14547. OPENSSL_REMOVE_THREAD_STATE();
  14548. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14549. pthread_mutex_destroy(&ssl_mutexes[i]);
  14550. }
  14551. mg_free(ssl_mutexes);
  14552. ssl_mutexes = NULL;
  14553. #endif /* OPENSSL_API_1_1 */
  14554. }
  14555. }
  14556. #endif /* !NO_SSL */
  14557. #if !defined(NO_FILESYSTEMS)
  14558. static int
  14559. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14560. {
  14561. if (phys_ctx) {
  14562. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14563. const char *path;
  14564. struct mg_connection fc;
  14565. if (!dom_ctx) {
  14566. dom_ctx = &(phys_ctx->dd);
  14567. }
  14568. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14569. if ((path != NULL)
  14570. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14571. mg_cry_ctx_internal(phys_ctx,
  14572. "Cannot open %s: %s",
  14573. path,
  14574. strerror(ERRNO));
  14575. return 0;
  14576. }
  14577. return 1;
  14578. }
  14579. return 0;
  14580. }
  14581. #endif /* NO_FILESYSTEMS */
  14582. static int
  14583. set_acl_option(struct mg_context *phys_ctx)
  14584. {
  14585. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14586. }
  14587. static void
  14588. reset_per_request_attributes(struct mg_connection *conn)
  14589. {
  14590. if (!conn) {
  14591. return;
  14592. }
  14593. conn->connection_type =
  14594. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14595. conn->num_bytes_sent = conn->consumed_content = 0;
  14596. conn->path_info = NULL;
  14597. conn->status_code = -1;
  14598. conn->content_len = -1;
  14599. conn->is_chunked = 0;
  14600. conn->must_close = 0;
  14601. conn->request_len = 0;
  14602. conn->throttle = 0;
  14603. conn->accept_gzip = 0;
  14604. conn->response_info.content_length = conn->request_info.content_length = -1;
  14605. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14606. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14607. conn->response_info.status_text = NULL;
  14608. conn->response_info.status_code = 0;
  14609. conn->request_info.remote_user = NULL;
  14610. conn->request_info.request_method = NULL;
  14611. conn->request_info.request_uri = NULL;
  14612. conn->request_info.local_uri = NULL;
  14613. #if defined(MG_LEGACY_INTERFACE)
  14614. /* Legacy before split into local_uri and request_uri */
  14615. conn->request_info.uri = NULL;
  14616. #endif
  14617. }
  14618. static int
  14619. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14620. {
  14621. if (setsockopt(sock,
  14622. IPPROTO_TCP,
  14623. TCP_NODELAY,
  14624. (SOCK_OPT_TYPE)&nodelay_on,
  14625. sizeof(nodelay_on))
  14626. != 0) {
  14627. /* Error */
  14628. return 1;
  14629. }
  14630. /* OK */
  14631. return 0;
  14632. }
  14633. #if !defined(__ZEPHYR__)
  14634. static void
  14635. close_socket_gracefully(struct mg_connection *conn)
  14636. {
  14637. #if defined(_WIN32)
  14638. char buf[MG_BUF_LEN];
  14639. int n;
  14640. #endif
  14641. struct linger linger;
  14642. int error_code = 0;
  14643. int linger_timeout = -2;
  14644. socklen_t opt_len = sizeof(error_code);
  14645. if (!conn) {
  14646. return;
  14647. }
  14648. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14649. * "Note that enabling a nonzero timeout on a nonblocking socket
  14650. * is not recommended.", so set it to blocking now */
  14651. set_blocking_mode(conn->client.sock);
  14652. /* Send FIN to the client */
  14653. shutdown(conn->client.sock, SHUTDOWN_WR);
  14654. #if defined(_WIN32)
  14655. /* Read and discard pending incoming data. If we do not do that and
  14656. * close
  14657. * the socket, the data in the send buffer may be discarded. This
  14658. * behaviour is seen on Windows, when client keeps sending data
  14659. * when server decides to close the connection; then when client
  14660. * does recv() it gets no data back. */
  14661. do {
  14662. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14663. } while (n > 0);
  14664. #endif
  14665. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14666. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14667. }
  14668. /* Set linger option according to configuration */
  14669. if (linger_timeout >= 0) {
  14670. /* Set linger option to avoid socket hanging out after close. This
  14671. * prevent ephemeral port exhaust problem under high QPS. */
  14672. linger.l_onoff = 1;
  14673. #if defined(_MSC_VER)
  14674. #pragma warning(push)
  14675. #pragma warning(disable : 4244)
  14676. #endif
  14677. #if defined(GCC_DIAGNOSTIC)
  14678. #pragma GCC diagnostic push
  14679. #pragma GCC diagnostic ignored "-Wconversion"
  14680. #endif
  14681. /* Data type of linger structure elements may differ,
  14682. * so we don't know what cast we need here.
  14683. * Disable type conversion warnings. */
  14684. linger.l_linger = (linger_timeout + 999) / 1000;
  14685. #if defined(GCC_DIAGNOSTIC)
  14686. #pragma GCC diagnostic pop
  14687. #endif
  14688. #if defined(_MSC_VER)
  14689. #pragma warning(pop)
  14690. #endif
  14691. } else {
  14692. linger.l_onoff = 0;
  14693. linger.l_linger = 0;
  14694. }
  14695. if (linger_timeout < -1) {
  14696. /* Default: don't configure any linger */
  14697. } else if (getsockopt(conn->client.sock,
  14698. SOL_SOCKET,
  14699. SO_ERROR,
  14700. #if defined(_WIN32) /* WinSock uses different data type here */
  14701. (char *)&error_code,
  14702. #else
  14703. &error_code,
  14704. #endif
  14705. &opt_len)
  14706. != 0) {
  14707. /* Cannot determine if socket is already closed. This should
  14708. * not occur and never did in a test. Log an error message
  14709. * and continue. */
  14710. mg_cry_internal(conn,
  14711. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14712. __func__,
  14713. strerror(ERRNO));
  14714. #if defined(_WIN32)
  14715. } else if (error_code == WSAECONNRESET) {
  14716. #else
  14717. } else if (error_code == ECONNRESET) {
  14718. #endif
  14719. /* Socket already closed by client/peer, close socket without linger
  14720. */
  14721. } else {
  14722. /* Set linger timeout */
  14723. if (setsockopt(conn->client.sock,
  14724. SOL_SOCKET,
  14725. SO_LINGER,
  14726. (char *)&linger,
  14727. sizeof(linger))
  14728. != 0) {
  14729. mg_cry_internal(
  14730. conn,
  14731. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14732. __func__,
  14733. linger.l_onoff,
  14734. linger.l_linger,
  14735. strerror(ERRNO));
  14736. }
  14737. }
  14738. /* Now we know that our FIN is ACK-ed, safe to close */
  14739. closesocket(conn->client.sock);
  14740. conn->client.sock = INVALID_SOCKET;
  14741. }
  14742. #endif
  14743. static void
  14744. close_connection(struct mg_connection *conn)
  14745. {
  14746. #if defined(USE_SERVER_STATS)
  14747. conn->conn_state = 6; /* to close */
  14748. #endif
  14749. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14750. if (conn->lua_websocket_state) {
  14751. lua_websocket_close(conn, conn->lua_websocket_state);
  14752. conn->lua_websocket_state = NULL;
  14753. }
  14754. #endif
  14755. mg_lock_connection(conn);
  14756. /* Set close flag, so keep-alive loops will stop */
  14757. conn->must_close = 1;
  14758. /* call the connection_close callback if assigned */
  14759. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14760. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14761. conn->phys_ctx->callbacks.connection_close(conn);
  14762. }
  14763. }
  14764. /* Reset user data, after close callback is called.
  14765. * Do not reuse it. If the user needs a destructor,
  14766. * it must be done in the connection_close callback. */
  14767. mg_set_user_connection_data(conn, NULL);
  14768. #if defined(USE_SERVER_STATS)
  14769. conn->conn_state = 7; /* closing */
  14770. #endif
  14771. #if !defined(NO_SSL)
  14772. if (conn->ssl != NULL) {
  14773. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14774. */
  14775. SSL_shutdown(conn->ssl);
  14776. SSL_free(conn->ssl);
  14777. OPENSSL_REMOVE_THREAD_STATE();
  14778. conn->ssl = NULL;
  14779. }
  14780. #endif
  14781. if (conn->client.sock != INVALID_SOCKET) {
  14782. #if defined(__ZEPHYR__)
  14783. closesocket(conn->client.sock);
  14784. #else
  14785. close_socket_gracefully(conn);
  14786. #endif
  14787. conn->client.sock = INVALID_SOCKET;
  14788. }
  14789. if (conn->host) {
  14790. mg_free((void *)conn->host);
  14791. conn->host = NULL;
  14792. }
  14793. mg_unlock_connection(conn);
  14794. #if defined(USE_SERVER_STATS)
  14795. conn->conn_state = 8; /* closed */
  14796. #endif
  14797. }
  14798. void
  14799. mg_close_connection(struct mg_connection *conn)
  14800. {
  14801. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14802. return;
  14803. }
  14804. #if defined(USE_WEBSOCKET)
  14805. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14806. if (conn->in_websocket_handling) {
  14807. /* Set close flag, so the server thread can exit. */
  14808. conn->must_close = 1;
  14809. return;
  14810. }
  14811. }
  14812. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14813. unsigned int i;
  14814. /* client context: loops must end */
  14815. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14816. conn->must_close = 1;
  14817. /* We need to get the client thread out of the select/recv call
  14818. * here. */
  14819. /* Since we use a sleep quantum of some seconds to check for recv
  14820. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14821. /* join worker thread */
  14822. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14823. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14824. }
  14825. }
  14826. #endif /* defined(USE_WEBSOCKET) */
  14827. close_connection(conn);
  14828. #if !defined(NO_SSL)
  14829. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14830. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14831. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14832. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14833. }
  14834. #endif
  14835. #if defined(USE_WEBSOCKET)
  14836. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14837. mg_free(conn->phys_ctx->worker_threadids);
  14838. (void)pthread_mutex_destroy(&conn->mutex);
  14839. mg_free(conn);
  14840. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14841. (void)pthread_mutex_destroy(&conn->mutex);
  14842. mg_free(conn);
  14843. }
  14844. #else
  14845. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14846. (void)pthread_mutex_destroy(&conn->mutex);
  14847. mg_free(conn);
  14848. }
  14849. #endif /* defined(USE_WEBSOCKET) */
  14850. }
  14851. static struct mg_connection *
  14852. mg_connect_client_impl(const struct mg_client_options *client_options,
  14853. int use_ssl,
  14854. char *ebuf,
  14855. size_t ebuf_len)
  14856. {
  14857. struct mg_connection *conn = NULL;
  14858. SOCKET sock;
  14859. union usa sa;
  14860. struct sockaddr *psa;
  14861. socklen_t len;
  14862. unsigned max_req_size =
  14863. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14864. /* Size of structures, aligned to 8 bytes */
  14865. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14866. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14867. conn =
  14868. (struct mg_connection *)mg_calloc(1,
  14869. conn_size + ctx_size + max_req_size);
  14870. if (conn == NULL) {
  14871. mg_snprintf(NULL,
  14872. NULL, /* No truncation check for ebuf */
  14873. ebuf,
  14874. ebuf_len,
  14875. "calloc(): %s",
  14876. strerror(ERRNO));
  14877. return NULL;
  14878. }
  14879. #if defined(GCC_DIAGNOSTIC)
  14880. #pragma GCC diagnostic push
  14881. #pragma GCC diagnostic ignored "-Wcast-align"
  14882. #endif /* defined(GCC_DIAGNOSTIC) */
  14883. /* conn_size is aligned to 8 bytes */
  14884. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14885. #if defined(GCC_DIAGNOSTIC)
  14886. #pragma GCC diagnostic pop
  14887. #endif /* defined(GCC_DIAGNOSTIC) */
  14888. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14889. conn->buf_size = (int)max_req_size;
  14890. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14891. conn->dom_ctx = &(conn->phys_ctx->dd);
  14892. if (!connect_socket(conn->phys_ctx,
  14893. client_options->host,
  14894. client_options->port,
  14895. use_ssl,
  14896. ebuf,
  14897. ebuf_len,
  14898. &sock,
  14899. &sa)) {
  14900. /* ebuf is set by connect_socket,
  14901. * free all memory and return NULL; */
  14902. mg_free(conn);
  14903. return NULL;
  14904. }
  14905. #if !defined(NO_SSL)
  14906. #if defined(OPENSSL_API_1_1)
  14907. if (use_ssl
  14908. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14909. == NULL) {
  14910. mg_snprintf(NULL,
  14911. NULL, /* No truncation check for ebuf */
  14912. ebuf,
  14913. ebuf_len,
  14914. "SSL_CTX_new error: %s",
  14915. ssl_error());
  14916. closesocket(sock);
  14917. mg_free(conn);
  14918. return NULL;
  14919. }
  14920. #else
  14921. if (use_ssl
  14922. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14923. == NULL) {
  14924. mg_snprintf(NULL,
  14925. NULL, /* No truncation check for ebuf */
  14926. ebuf,
  14927. ebuf_len,
  14928. "SSL_CTX_new error: %s",
  14929. ssl_error());
  14930. closesocket(sock);
  14931. mg_free(conn);
  14932. return NULL;
  14933. }
  14934. #endif /* OPENSSL_API_1_1 */
  14935. #endif /* NO_SSL */
  14936. #if defined(USE_IPV6)
  14937. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14938. : sizeof(conn->client.rsa.sin6);
  14939. psa = (sa.sa.sa_family == AF_INET)
  14940. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14941. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14942. #else
  14943. len = sizeof(conn->client.rsa.sin);
  14944. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14945. #endif
  14946. conn->client.sock = sock;
  14947. conn->client.lsa = sa;
  14948. if (getsockname(sock, psa, &len) != 0) {
  14949. mg_cry_internal(conn,
  14950. "%s: getsockname() failed: %s",
  14951. __func__,
  14952. strerror(ERRNO));
  14953. }
  14954. conn->client.is_ssl = use_ssl ? 1 : 0;
  14955. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14956. mg_snprintf(NULL,
  14957. NULL, /* No truncation check for ebuf */
  14958. ebuf,
  14959. ebuf_len,
  14960. "Can not create mutex");
  14961. #if !defined(NO_SSL)
  14962. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14963. #endif
  14964. closesocket(sock);
  14965. mg_free(conn);
  14966. return NULL;
  14967. }
  14968. #if !defined(NO_SSL)
  14969. if (use_ssl) {
  14970. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14971. * SSL_CTX_set_verify call is needed to switch off server
  14972. * certificate checking, which is off by default in OpenSSL and
  14973. * on in yaSSL. */
  14974. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14975. * SSL_VERIFY_PEER, verify_ssl_server); */
  14976. if (client_options->client_cert) {
  14977. if (!ssl_use_pem_file(conn->phys_ctx,
  14978. conn->dom_ctx,
  14979. client_options->client_cert,
  14980. NULL)) {
  14981. mg_snprintf(NULL,
  14982. NULL, /* No truncation check for ebuf */
  14983. ebuf,
  14984. ebuf_len,
  14985. "Can not use SSL client certificate");
  14986. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14987. closesocket(sock);
  14988. mg_free(conn);
  14989. return NULL;
  14990. }
  14991. }
  14992. if (client_options->server_cert) {
  14993. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14994. client_options->server_cert,
  14995. NULL)
  14996. != 1) {
  14997. mg_cry_internal(conn,
  14998. "SSL_CTX_load_verify_locations error: %s ",
  14999. ssl_error());
  15000. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15001. closesocket(sock);
  15002. mg_free(conn);
  15003. return NULL;
  15004. }
  15005. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15006. } else {
  15007. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15008. }
  15009. if (!sslize(conn, SSL_connect, client_options)) {
  15010. mg_snprintf(NULL,
  15011. NULL, /* No truncation check for ebuf */
  15012. ebuf,
  15013. ebuf_len,
  15014. "SSL connection error");
  15015. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15016. closesocket(sock);
  15017. mg_free(conn);
  15018. return NULL;
  15019. }
  15020. }
  15021. #endif
  15022. return conn;
  15023. }
  15024. CIVETWEB_API struct mg_connection *
  15025. mg_connect_client_secure(const struct mg_client_options *client_options,
  15026. char *error_buffer,
  15027. size_t error_buffer_size)
  15028. {
  15029. return mg_connect_client_impl(client_options,
  15030. 1,
  15031. error_buffer,
  15032. error_buffer_size);
  15033. }
  15034. struct mg_connection *
  15035. mg_connect_client(const char *host,
  15036. int port,
  15037. int use_ssl,
  15038. char *error_buffer,
  15039. size_t error_buffer_size)
  15040. {
  15041. struct mg_client_options opts;
  15042. memset(&opts, 0, sizeof(opts));
  15043. opts.host = host;
  15044. opts.port = port;
  15045. return mg_connect_client_impl(&opts,
  15046. use_ssl,
  15047. error_buffer,
  15048. error_buffer_size);
  15049. }
  15050. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15051. struct mg_connection *
  15052. mg_connect_client2(const char *host,
  15053. const char *protocol,
  15054. int port,
  15055. const char *path,
  15056. struct mg_init_data *init,
  15057. struct mg_error_data *error)
  15058. {
  15059. int is_ssl, is_ws;
  15060. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15061. if (error != NULL) {
  15062. error->code = 0;
  15063. if (error->text_buffer_size > 0) {
  15064. *error->text = 0;
  15065. }
  15066. }
  15067. if ((host == NULL) || (protocol == NULL)) {
  15068. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15069. mg_snprintf(NULL,
  15070. NULL, /* No truncation check for error buffers */
  15071. error->text,
  15072. error->text_buffer_size,
  15073. "%s",
  15074. "Invalid parameters");
  15075. }
  15076. return NULL;
  15077. }
  15078. /* check all known protocolls */
  15079. if (!mg_strcasecmp(protocol, "http")) {
  15080. is_ssl = 0;
  15081. is_ws = 0;
  15082. } else if (!mg_strcasecmp(protocol, "https")) {
  15083. is_ssl = 1;
  15084. is_ws = 0;
  15085. #if defined(USE_WEBSOCKET)
  15086. } else if (!mg_strcasecmp(protocol, "ws")) {
  15087. is_ssl = 0;
  15088. is_ws = 1;
  15089. } else if (!mg_strcasecmp(protocol, "wss")) {
  15090. is_ssl = 1;
  15091. is_ws = 1;
  15092. #endif
  15093. } else {
  15094. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15095. mg_snprintf(NULL,
  15096. NULL, /* No truncation check for error buffers */
  15097. error->text,
  15098. error->text_buffer_size,
  15099. "Protocol %s not supported",
  15100. protocol);
  15101. }
  15102. return NULL;
  15103. }
  15104. /* TODO: The current implementation here just calls the old
  15105. * implementations, without using any new options. This is just a first
  15106. * step to test the new interfaces. */
  15107. #if defined(USE_WEBSOCKET)
  15108. if (is_ws) {
  15109. /* TODO: implement all options */
  15110. return mg_connect_websocket_client(
  15111. host,
  15112. port,
  15113. is_ssl,
  15114. ((error != NULL) ? error->text : NULL),
  15115. ((error != NULL) ? error->text_buffer_size : 0),
  15116. (path ? path : ""),
  15117. NULL /* TODO: origin */,
  15118. deprecated_websocket_data_wrapper,
  15119. deprecated_websocket_close_wrapper,
  15120. (void *)init->callbacks);
  15121. }
  15122. #endif
  15123. /* TODO: all additional options */
  15124. struct mg_client_options opts;
  15125. memset(&opts, 0, sizeof(opts));
  15126. opts.host = host;
  15127. opts.port = port;
  15128. return mg_connect_client_impl(&opts,
  15129. is_ssl,
  15130. ((error != NULL) ? error->text : NULL),
  15131. ((error != NULL) ? error->text_buffer_size
  15132. : 0));
  15133. }
  15134. #endif
  15135. static const struct {
  15136. const char *proto;
  15137. size_t proto_len;
  15138. unsigned default_port;
  15139. } abs_uri_protocols[] = {{"http://", 7, 80},
  15140. {"https://", 8, 443},
  15141. {"ws://", 5, 80},
  15142. {"wss://", 6, 443},
  15143. {NULL, 0, 0}};
  15144. /* Check if the uri is valid.
  15145. * return 0 for invalid uri,
  15146. * return 1 for *,
  15147. * return 2 for relative uri,
  15148. * return 3 for absolute uri without port,
  15149. * return 4 for absolute uri with port */
  15150. static int
  15151. get_uri_type(const char *uri)
  15152. {
  15153. int i;
  15154. const char *hostend, *portbegin;
  15155. char *portend;
  15156. unsigned long port;
  15157. /* According to the HTTP standard
  15158. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15159. * URI can be an asterisk (*) or should start with slash (relative uri),
  15160. * or it should start with the protocol (absolute uri). */
  15161. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15162. /* asterisk */
  15163. return 1;
  15164. }
  15165. /* Valid URIs according to RFC 3986
  15166. * (https://www.ietf.org/rfc/rfc3986.txt)
  15167. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15168. * and unreserved characters A-Z a-z 0-9 and -._~
  15169. * and % encoded symbols.
  15170. */
  15171. for (i = 0; uri[i] != 0; i++) {
  15172. if (uri[i] < 33) {
  15173. /* control characters and spaces are invalid */
  15174. return 0;
  15175. }
  15176. if (uri[i] > 126) {
  15177. /* non-ascii characters must be % encoded */
  15178. return 0;
  15179. } else {
  15180. switch (uri[i]) {
  15181. case '"': /* 34 */
  15182. case '<': /* 60 */
  15183. case '>': /* 62 */
  15184. case '\\': /* 92 */
  15185. case '^': /* 94 */
  15186. case '`': /* 96 */
  15187. case '{': /* 123 */
  15188. case '|': /* 124 */
  15189. case '}': /* 125 */
  15190. return 0;
  15191. default:
  15192. /* character is ok */
  15193. break;
  15194. }
  15195. }
  15196. }
  15197. /* A relative uri starts with a / character */
  15198. if (uri[0] == '/') {
  15199. /* relative uri */
  15200. return 2;
  15201. }
  15202. /* It could be an absolute uri: */
  15203. /* This function only checks if the uri is valid, not if it is
  15204. * addressing the current server. So civetweb can also be used
  15205. * as a proxy server. */
  15206. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15207. if (mg_strncasecmp(uri,
  15208. abs_uri_protocols[i].proto,
  15209. abs_uri_protocols[i].proto_len)
  15210. == 0) {
  15211. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15212. if (!hostend) {
  15213. return 0;
  15214. }
  15215. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15216. if (!portbegin) {
  15217. return 3;
  15218. }
  15219. port = strtoul(portbegin + 1, &portend, 10);
  15220. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15221. return 0;
  15222. }
  15223. return 4;
  15224. }
  15225. }
  15226. return 0;
  15227. }
  15228. /* Return NULL or the relative uri at the current server */
  15229. static const char *
  15230. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15231. {
  15232. const char *server_domain;
  15233. size_t server_domain_len;
  15234. size_t request_domain_len = 0;
  15235. unsigned long port = 0;
  15236. int i, auth_domain_check_enabled;
  15237. const char *hostbegin = NULL;
  15238. const char *hostend = NULL;
  15239. const char *portbegin;
  15240. char *portend;
  15241. auth_domain_check_enabled =
  15242. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15243. /* DNS is case insensitive, so use case insensitive string compare here
  15244. */
  15245. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15246. if (mg_strncasecmp(uri,
  15247. abs_uri_protocols[i].proto,
  15248. abs_uri_protocols[i].proto_len)
  15249. == 0) {
  15250. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15251. hostend = strchr(hostbegin, '/');
  15252. if (!hostend) {
  15253. return 0;
  15254. }
  15255. portbegin = strchr(hostbegin, ':');
  15256. if ((!portbegin) || (portbegin > hostend)) {
  15257. port = abs_uri_protocols[i].default_port;
  15258. request_domain_len = (size_t)(hostend - hostbegin);
  15259. } else {
  15260. port = strtoul(portbegin + 1, &portend, 10);
  15261. if ((portend != hostend) || (port <= 0)
  15262. || !is_valid_port(port)) {
  15263. return 0;
  15264. }
  15265. request_domain_len = (size_t)(portbegin - hostbegin);
  15266. }
  15267. /* protocol found, port set */
  15268. break;
  15269. }
  15270. }
  15271. if (!port) {
  15272. /* port remains 0 if the protocol is not found */
  15273. return 0;
  15274. }
  15275. /* Check if the request is directed to a different server. */
  15276. /* First check if the port is the same (IPv4 and IPv6). */
  15277. #if defined(USE_IPV6)
  15278. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  15279. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  15280. /* Request is directed to a different port */
  15281. return 0;
  15282. }
  15283. } else
  15284. #endif
  15285. {
  15286. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  15287. /* Request is directed to a different port */
  15288. return 0;
  15289. }
  15290. }
  15291. /* Finally check if the server corresponds to the authentication
  15292. * domain of the server (the server domain).
  15293. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15294. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15295. * but do not allow substrings (like
  15296. * http://notmydomain.com/path/file.ext
  15297. * or http://mydomain.com.fake/path/file.ext).
  15298. */
  15299. if (auth_domain_check_enabled) {
  15300. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15301. server_domain_len = strlen(server_domain);
  15302. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15303. return 0;
  15304. }
  15305. if ((request_domain_len == server_domain_len)
  15306. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15307. /* Request is directed to this server - full name match. */
  15308. } else {
  15309. if (request_domain_len < (server_domain_len + 2)) {
  15310. /* Request is directed to another server: The server name
  15311. * is longer than the request name.
  15312. * Drop this case here to avoid overflows in the
  15313. * following checks. */
  15314. return 0;
  15315. }
  15316. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15317. /* Request is directed to another server: It could be a
  15318. * substring
  15319. * like notmyserver.com */
  15320. return 0;
  15321. }
  15322. if (0
  15323. != memcmp(server_domain,
  15324. hostbegin + request_domain_len - server_domain_len,
  15325. server_domain_len)) {
  15326. /* Request is directed to another server:
  15327. * The server name is different. */
  15328. return 0;
  15329. }
  15330. }
  15331. }
  15332. return hostend;
  15333. }
  15334. static int
  15335. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15336. {
  15337. if (ebuf_len > 0) {
  15338. ebuf[0] = '\0';
  15339. }
  15340. *err = 0;
  15341. reset_per_request_attributes(conn);
  15342. if (!conn) {
  15343. mg_snprintf(conn,
  15344. NULL, /* No truncation check for ebuf */
  15345. ebuf,
  15346. ebuf_len,
  15347. "%s",
  15348. "Internal error");
  15349. *err = 500;
  15350. return 0;
  15351. }
  15352. /* Set the time the request was received. This value should be used for
  15353. * timeouts. */
  15354. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15355. conn->request_len =
  15356. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15357. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15358. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15359. mg_snprintf(conn,
  15360. NULL, /* No truncation check for ebuf */
  15361. ebuf,
  15362. ebuf_len,
  15363. "%s",
  15364. "Invalid message size");
  15365. *err = 500;
  15366. return 0;
  15367. }
  15368. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15369. mg_snprintf(conn,
  15370. NULL, /* No truncation check for ebuf */
  15371. ebuf,
  15372. ebuf_len,
  15373. "%s",
  15374. "Message too large");
  15375. *err = 413;
  15376. return 0;
  15377. }
  15378. if (conn->request_len <= 0) {
  15379. if (conn->data_len > 0) {
  15380. mg_snprintf(conn,
  15381. NULL, /* No truncation check for ebuf */
  15382. ebuf,
  15383. ebuf_len,
  15384. "%s",
  15385. "Malformed message");
  15386. *err = 400;
  15387. } else {
  15388. /* Server did not recv anything -> just close the connection */
  15389. conn->must_close = 1;
  15390. mg_snprintf(conn,
  15391. NULL, /* No truncation check for ebuf */
  15392. ebuf,
  15393. ebuf_len,
  15394. "%s",
  15395. "No data received");
  15396. *err = 0;
  15397. }
  15398. return 0;
  15399. }
  15400. return 1;
  15401. }
  15402. static int
  15403. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15404. {
  15405. const char *cl;
  15406. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15407. return 0;
  15408. }
  15409. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15410. <= 0) {
  15411. mg_snprintf(conn,
  15412. NULL, /* No truncation check for ebuf */
  15413. ebuf,
  15414. ebuf_len,
  15415. "%s",
  15416. "Bad request");
  15417. *err = 400;
  15418. return 0;
  15419. }
  15420. /* Message is a valid request */
  15421. /* Is there a "host" ? */
  15422. if (conn->host != NULL) {
  15423. mg_free((void *)conn->host);
  15424. }
  15425. conn->host = alloc_get_host(conn);
  15426. if (!conn->host) {
  15427. mg_snprintf(conn,
  15428. NULL, /* No truncation check for ebuf */
  15429. ebuf,
  15430. ebuf_len,
  15431. "%s",
  15432. "Bad request: Host mismatch");
  15433. *err = 400;
  15434. return 0;
  15435. }
  15436. if (((cl = get_header(conn->request_info.http_headers,
  15437. conn->request_info.num_headers,
  15438. "Transfer-Encoding"))
  15439. != NULL)
  15440. && mg_strcasecmp(cl, "identity")) {
  15441. if (mg_strcasecmp(cl, "chunked")) {
  15442. mg_snprintf(conn,
  15443. NULL, /* No truncation check for ebuf */
  15444. ebuf,
  15445. ebuf_len,
  15446. "%s",
  15447. "Bad request");
  15448. *err = 400;
  15449. return 0;
  15450. }
  15451. conn->is_chunked = 1;
  15452. conn->content_len = 0; /* not yet read */
  15453. } else if ((cl = get_header(conn->request_info.http_headers,
  15454. conn->request_info.num_headers,
  15455. "Content-Length"))
  15456. != NULL) {
  15457. /* Request has content length set */
  15458. char *endptr = NULL;
  15459. conn->content_len = strtoll(cl, &endptr, 10);
  15460. if ((endptr == cl) || (conn->content_len < 0)) {
  15461. mg_snprintf(conn,
  15462. NULL, /* No truncation check for ebuf */
  15463. ebuf,
  15464. ebuf_len,
  15465. "%s",
  15466. "Bad request");
  15467. *err = 411;
  15468. return 0;
  15469. }
  15470. /* Publish the content length back to the request info. */
  15471. conn->request_info.content_length = conn->content_len;
  15472. } else {
  15473. /* There is no exception, see RFC7230. */
  15474. conn->content_len = 0;
  15475. }
  15476. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15477. return 1;
  15478. }
  15479. /* conn is assumed to be valid in this internal function */
  15480. static int
  15481. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15482. {
  15483. const char *cl;
  15484. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15485. return 0;
  15486. }
  15487. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15488. <= 0) {
  15489. mg_snprintf(conn,
  15490. NULL, /* No truncation check for ebuf */
  15491. ebuf,
  15492. ebuf_len,
  15493. "%s",
  15494. "Bad response");
  15495. *err = 400;
  15496. return 0;
  15497. }
  15498. /* Message is a valid response */
  15499. if (((cl = get_header(conn->response_info.http_headers,
  15500. conn->response_info.num_headers,
  15501. "Transfer-Encoding"))
  15502. != NULL)
  15503. && mg_strcasecmp(cl, "identity")) {
  15504. if (mg_strcasecmp(cl, "chunked")) {
  15505. mg_snprintf(conn,
  15506. NULL, /* No truncation check for ebuf */
  15507. ebuf,
  15508. ebuf_len,
  15509. "%s",
  15510. "Bad request");
  15511. *err = 400;
  15512. return 0;
  15513. }
  15514. conn->is_chunked = 1;
  15515. conn->content_len = 0; /* not yet read */
  15516. } else if ((cl = get_header(conn->response_info.http_headers,
  15517. conn->response_info.num_headers,
  15518. "Content-Length"))
  15519. != NULL) {
  15520. char *endptr = NULL;
  15521. conn->content_len = strtoll(cl, &endptr, 10);
  15522. if ((endptr == cl) || (conn->content_len < 0)) {
  15523. mg_snprintf(conn,
  15524. NULL, /* No truncation check for ebuf */
  15525. ebuf,
  15526. ebuf_len,
  15527. "%s",
  15528. "Bad request");
  15529. *err = 411;
  15530. return 0;
  15531. }
  15532. /* Publish the content length back to the response info. */
  15533. conn->response_info.content_length = conn->content_len;
  15534. /* TODO: check if it is still used in response_info */
  15535. conn->request_info.content_length = conn->content_len;
  15536. /* TODO: we should also consider HEAD method */
  15537. if (conn->response_info.status_code == 304) {
  15538. conn->content_len = 0;
  15539. }
  15540. } else {
  15541. /* TODO: we should also consider HEAD method */
  15542. if (((conn->response_info.status_code >= 100)
  15543. && (conn->response_info.status_code <= 199))
  15544. || (conn->response_info.status_code == 204)
  15545. || (conn->response_info.status_code == 304)) {
  15546. conn->content_len = 0;
  15547. } else {
  15548. conn->content_len = -1; /* unknown content length */
  15549. }
  15550. }
  15551. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15552. return 1;
  15553. }
  15554. int
  15555. mg_get_response(struct mg_connection *conn,
  15556. char *ebuf,
  15557. size_t ebuf_len,
  15558. int timeout)
  15559. {
  15560. int err, ret;
  15561. char txt[32]; /* will not overflow */
  15562. char *save_timeout;
  15563. char *new_timeout;
  15564. if (ebuf_len > 0) {
  15565. ebuf[0] = '\0';
  15566. }
  15567. if (!conn) {
  15568. mg_snprintf(conn,
  15569. NULL, /* No truncation check for ebuf */
  15570. ebuf,
  15571. ebuf_len,
  15572. "%s",
  15573. "Parameter error");
  15574. return -1;
  15575. }
  15576. /* Reset the previous responses */
  15577. conn->data_len = 0;
  15578. /* Implementation of API function for HTTP clients */
  15579. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15580. if (timeout >= 0) {
  15581. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15582. new_timeout = txt;
  15583. } else {
  15584. new_timeout = NULL;
  15585. }
  15586. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15587. ret = get_response(conn, ebuf, ebuf_len, &err);
  15588. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15589. #if defined(MG_LEGACY_INTERFACE)
  15590. /* TODO: 1) uri is deprecated;
  15591. * 2) here, ri.uri is the http response code */
  15592. conn->request_info.uri = conn->request_info.request_uri;
  15593. #endif
  15594. conn->request_info.local_uri = conn->request_info.request_uri;
  15595. /* TODO (mid): Define proper return values - maybe return length?
  15596. * For the first test use <0 for error and >0 for OK */
  15597. return (ret == 0) ? -1 : +1;
  15598. }
  15599. struct mg_connection *
  15600. mg_download(const char *host,
  15601. int port,
  15602. int use_ssl,
  15603. char *ebuf,
  15604. size_t ebuf_len,
  15605. const char *fmt,
  15606. ...)
  15607. {
  15608. struct mg_connection *conn;
  15609. va_list ap;
  15610. int i;
  15611. int reqerr;
  15612. if (ebuf_len > 0) {
  15613. ebuf[0] = '\0';
  15614. }
  15615. va_start(ap, fmt);
  15616. /* open a connection */
  15617. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15618. if (conn != NULL) {
  15619. i = mg_vprintf(conn, fmt, ap);
  15620. if (i <= 0) {
  15621. mg_snprintf(conn,
  15622. NULL, /* No truncation check for ebuf */
  15623. ebuf,
  15624. ebuf_len,
  15625. "%s",
  15626. "Error sending request");
  15627. } else {
  15628. /* make sure the buffer is clear */
  15629. conn->data_len = 0;
  15630. get_response(conn, ebuf, ebuf_len, &reqerr);
  15631. #if defined(MG_LEGACY_INTERFACE)
  15632. /* TODO: 1) uri is deprecated;
  15633. * 2) here, ri.uri is the http response code */
  15634. conn->request_info.uri = conn->request_info.request_uri;
  15635. #endif
  15636. conn->request_info.local_uri = conn->request_info.request_uri;
  15637. }
  15638. }
  15639. /* if an error occurred, close the connection */
  15640. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15641. mg_close_connection(conn);
  15642. conn = NULL;
  15643. }
  15644. va_end(ap);
  15645. return conn;
  15646. }
  15647. struct websocket_client_thread_data {
  15648. struct mg_connection *conn;
  15649. mg_websocket_data_handler data_handler;
  15650. mg_websocket_close_handler close_handler;
  15651. void *callback_data;
  15652. };
  15653. #if defined(USE_WEBSOCKET)
  15654. #if defined(_WIN32)
  15655. static unsigned __stdcall websocket_client_thread(void *data)
  15656. #else
  15657. static void *
  15658. websocket_client_thread(void *data)
  15659. #endif
  15660. {
  15661. struct websocket_client_thread_data *cdata =
  15662. (struct websocket_client_thread_data *)data;
  15663. void *user_thread_ptr = NULL;
  15664. #if !defined(_WIN32)
  15665. struct sigaction sa;
  15666. /* Ignore SIGPIPE */
  15667. memset(&sa, 0, sizeof(sa));
  15668. sa.sa_handler = SIG_IGN;
  15669. sigaction(SIGPIPE, &sa, NULL);
  15670. #endif
  15671. mg_set_thread_name("ws-clnt");
  15672. if (cdata->conn->phys_ctx) {
  15673. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15674. /* 3 indicates a websocket client thread */
  15675. /* TODO: check if conn->phys_ctx can be set */
  15676. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15677. cdata->conn->phys_ctx, 3);
  15678. }
  15679. }
  15680. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15681. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15682. if (cdata->close_handler != NULL) {
  15683. cdata->close_handler(cdata->conn, cdata->callback_data);
  15684. }
  15685. /* The websocket_client context has only this thread. If it runs out,
  15686. set the stop_flag to 2 (= "stopped"). */
  15687. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15688. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15689. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15690. 3,
  15691. user_thread_ptr);
  15692. }
  15693. mg_free((void *)cdata);
  15694. #if defined(_WIN32)
  15695. return 0;
  15696. #else
  15697. return NULL;
  15698. #endif
  15699. }
  15700. #endif
  15701. static struct mg_connection *
  15702. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15703. int use_ssl,
  15704. char *error_buffer,
  15705. size_t error_buffer_size,
  15706. const char *path,
  15707. const char *origin,
  15708. mg_websocket_data_handler data_func,
  15709. mg_websocket_close_handler close_func,
  15710. void *user_data)
  15711. {
  15712. struct mg_connection *conn = NULL;
  15713. #if defined(USE_WEBSOCKET)
  15714. struct websocket_client_thread_data *thread_data;
  15715. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15716. const char *handshake_req;
  15717. int port = client_options->port;
  15718. const char *host = client_options->host;
  15719. int i;
  15720. if (origin != NULL) {
  15721. handshake_req = "GET %s HTTP/1.1\r\n"
  15722. "Host: %s\r\n"
  15723. "Upgrade: websocket\r\n"
  15724. "Connection: Upgrade\r\n"
  15725. "Sec-WebSocket-Key: %s\r\n"
  15726. "Sec-WebSocket-Version: 13\r\n"
  15727. "Origin: %s\r\n"
  15728. "\r\n";
  15729. } else {
  15730. handshake_req = "GET %s HTTP/1.1\r\n"
  15731. "Host: %s\r\n"
  15732. "Upgrade: websocket\r\n"
  15733. "Connection: Upgrade\r\n"
  15734. "Sec-WebSocket-Key: %s\r\n"
  15735. "Sec-WebSocket-Version: 13\r\n"
  15736. "\r\n";
  15737. }
  15738. #if defined(__clang__)
  15739. #pragma clang diagnostic push
  15740. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15741. #endif
  15742. /* Establish the client connection and request upgrade */
  15743. conn =
  15744. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15745. if (conn == NULL) {
  15746. /* error_buffer already filled */
  15747. return NULL;
  15748. }
  15749. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15750. if (i <= 0) {
  15751. mg_snprintf(conn,
  15752. NULL, /* No truncation check for ebuf */
  15753. error_buffer,
  15754. error_buffer_size,
  15755. "%s",
  15756. "Error sending request");
  15757. mg_close_connection(conn);
  15758. return NULL;
  15759. }
  15760. conn->data_len = 0;
  15761. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15762. mg_close_connection(conn);
  15763. return NULL;
  15764. }
  15765. conn->request_info.local_uri = conn->request_info.request_uri;
  15766. #if defined(__clang__)
  15767. #pragma clang diagnostic pop
  15768. #endif
  15769. /* Connection object will be null if something goes wrong */
  15770. if (conn == NULL) {
  15771. if (!*error_buffer) {
  15772. /* There should be already an error message */
  15773. mg_snprintf(conn,
  15774. NULL, /* No truncation check for ebuf */
  15775. error_buffer,
  15776. error_buffer_size,
  15777. "Unexpected error");
  15778. }
  15779. return NULL;
  15780. }
  15781. if (conn->response_info.status_code != 101) {
  15782. /* We sent an "upgrade" request. For a correct websocket
  15783. * protocol handshake, we expect a "101 Continue" response.
  15784. * Otherwise it is a protocol violation. Maybe the HTTP
  15785. * Server does not know websockets. */
  15786. if (!*error_buffer) {
  15787. /* set an error, if not yet set */
  15788. mg_snprintf(conn,
  15789. NULL, /* No truncation check for ebuf */
  15790. error_buffer,
  15791. error_buffer_size,
  15792. "Unexpected server reply");
  15793. }
  15794. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15795. mg_close_connection(conn);
  15796. return NULL;
  15797. }
  15798. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15799. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15800. if (!thread_data) {
  15801. DEBUG_TRACE("%s\r\n", "Out of memory");
  15802. mg_close_connection(conn);
  15803. return NULL;
  15804. }
  15805. thread_data->conn = conn;
  15806. thread_data->data_handler = data_func;
  15807. thread_data->close_handler = close_func;
  15808. thread_data->callback_data = user_data;
  15809. conn->phys_ctx->worker_threadids =
  15810. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15811. if (!conn->phys_ctx->worker_threadids) {
  15812. DEBUG_TRACE("%s\r\n", "Out of memory");
  15813. mg_free(thread_data);
  15814. mg_close_connection(conn);
  15815. return NULL;
  15816. }
  15817. /* Now upgrade to ws/wss client context */
  15818. conn->phys_ctx->user_data = user_data;
  15819. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15820. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15821. /* Start a thread to read the websocket client connection
  15822. * This thread will automatically stop when mg_disconnect is
  15823. * called on the client connection */
  15824. if (mg_start_thread_with_id(websocket_client_thread,
  15825. thread_data,
  15826. conn->phys_ctx->worker_threadids)
  15827. != 0) {
  15828. conn->phys_ctx->cfg_worker_threads = 0;
  15829. mg_free(thread_data);
  15830. mg_close_connection(conn);
  15831. conn = NULL;
  15832. DEBUG_TRACE("%s",
  15833. "Websocket client connect thread could not be started\r\n");
  15834. }
  15835. #else
  15836. /* Appease "unused parameter" warnings */
  15837. (void)client_options;
  15838. (void)use_ssl;
  15839. (void)error_buffer;
  15840. (void)error_buffer_size;
  15841. (void)path;
  15842. (void)origin;
  15843. (void)user_data;
  15844. (void)data_func;
  15845. (void)close_func;
  15846. #endif
  15847. return conn;
  15848. }
  15849. struct mg_connection *
  15850. mg_connect_websocket_client(const char *host,
  15851. int port,
  15852. int use_ssl,
  15853. char *error_buffer,
  15854. size_t error_buffer_size,
  15855. const char *path,
  15856. const char *origin,
  15857. mg_websocket_data_handler data_func,
  15858. mg_websocket_close_handler close_func,
  15859. void *user_data)
  15860. {
  15861. struct mg_client_options client_options;
  15862. memset(&client_options, 0, sizeof(client_options));
  15863. client_options.host = host;
  15864. client_options.port = port;
  15865. return mg_connect_websocket_client_impl(&client_options,
  15866. use_ssl,
  15867. error_buffer,
  15868. error_buffer_size,
  15869. path,
  15870. origin,
  15871. data_func,
  15872. close_func,
  15873. user_data);
  15874. }
  15875. struct mg_connection *
  15876. mg_connect_websocket_client_secure(
  15877. const struct mg_client_options *client_options,
  15878. char *error_buffer,
  15879. size_t error_buffer_size,
  15880. const char *path,
  15881. const char *origin,
  15882. mg_websocket_data_handler data_func,
  15883. mg_websocket_close_handler close_func,
  15884. void *user_data)
  15885. {
  15886. if (!client_options) {
  15887. return NULL;
  15888. }
  15889. return mg_connect_websocket_client_impl(client_options,
  15890. 1,
  15891. error_buffer,
  15892. error_buffer_size,
  15893. path,
  15894. origin,
  15895. data_func,
  15896. close_func,
  15897. user_data);
  15898. }
  15899. /* Prepare connection data structure */
  15900. static void
  15901. init_connection(struct mg_connection *conn)
  15902. {
  15903. /* Is keep alive allowed by the server */
  15904. int keep_alive_enabled =
  15905. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15906. if (!keep_alive_enabled) {
  15907. conn->must_close = 1;
  15908. }
  15909. /* Important: on new connection, reset the receiving buffer. Credit
  15910. * goes to crule42. */
  15911. conn->data_len = 0;
  15912. conn->handled_requests = 0;
  15913. mg_set_user_connection_data(conn, NULL);
  15914. #if defined(USE_SERVER_STATS)
  15915. conn->conn_state = 2; /* init */
  15916. #endif
  15917. /* call the init_connection callback if assigned */
  15918. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15919. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15920. void *conn_data = NULL;
  15921. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15922. mg_set_user_connection_data(conn, conn_data);
  15923. }
  15924. }
  15925. }
  15926. /* Process a connection - may handle multiple requests
  15927. * using the same connection.
  15928. * Must be called with a valid connection (conn and
  15929. * conn->phys_ctx must be valid).
  15930. */
  15931. static void
  15932. process_new_connection(struct mg_connection *conn)
  15933. {
  15934. struct mg_request_info *ri = &conn->request_info;
  15935. int keep_alive, discard_len;
  15936. char ebuf[100];
  15937. const char *hostend;
  15938. int reqerr, uri_type;
  15939. #if defined(USE_SERVER_STATS)
  15940. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15941. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15942. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  15943. #endif
  15944. init_connection(conn);
  15945. DEBUG_TRACE("Start processing connection from %s",
  15946. conn->request_info.remote_addr);
  15947. /* Loop over multiple requests sent using the same connection
  15948. * (while "keep alive"). */
  15949. do {
  15950. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15951. conn->handled_requests + 1);
  15952. #if defined(USE_SERVER_STATS)
  15953. conn->conn_state = 3; /* ready */
  15954. #endif
  15955. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15956. /* The request sent by the client could not be understood by
  15957. * the server, or it was incomplete or a timeout. Send an
  15958. * error message and close the connection. */
  15959. if (reqerr > 0) {
  15960. DEBUG_ASSERT(ebuf[0] != '\0');
  15961. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15962. }
  15963. } else if (strcmp(ri->http_version, "1.0")
  15964. && strcmp(ri->http_version, "1.1")) {
  15965. /* HTTP/2 is not allowed here */
  15966. mg_snprintf(conn,
  15967. NULL, /* No truncation check for ebuf */
  15968. ebuf,
  15969. sizeof(ebuf),
  15970. "Bad HTTP version: [%s]",
  15971. ri->http_version);
  15972. mg_send_http_error(conn, 505, "%s", ebuf);
  15973. }
  15974. if (ebuf[0] == '\0') {
  15975. uri_type = get_uri_type(conn->request_info.request_uri);
  15976. switch (uri_type) {
  15977. case 1:
  15978. /* Asterisk */
  15979. conn->request_info.local_uri = 0;
  15980. /* TODO: Deal with '*'. */
  15981. break;
  15982. case 2:
  15983. /* relative uri */
  15984. conn->request_info.local_uri = conn->request_info.request_uri;
  15985. break;
  15986. case 3:
  15987. case 4:
  15988. /* absolute uri (with/without port) */
  15989. hostend = get_rel_url_at_current_server(
  15990. conn->request_info.request_uri, conn);
  15991. if (hostend) {
  15992. conn->request_info.local_uri = hostend;
  15993. } else {
  15994. conn->request_info.local_uri = NULL;
  15995. }
  15996. break;
  15997. default:
  15998. mg_snprintf(conn,
  15999. NULL, /* No truncation check for ebuf */
  16000. ebuf,
  16001. sizeof(ebuf),
  16002. "Invalid URI");
  16003. mg_send_http_error(conn, 400, "%s", ebuf);
  16004. conn->request_info.local_uri = NULL;
  16005. break;
  16006. }
  16007. #if defined(MG_LEGACY_INTERFACE)
  16008. /* Legacy before split into local_uri and request_uri */
  16009. conn->request_info.uri = conn->request_info.local_uri;
  16010. #endif
  16011. }
  16012. if (ebuf[0] != '\0') {
  16013. conn->protocol_type = -1;
  16014. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  16015. /* HTTP/1 allows protocol upgrade */
  16016. conn->protocol_type = should_switch_to_protocol(conn);
  16017. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16018. /* This will occur, if a HTTP/1.1 request should be upgraded
  16019. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16020. * Since most (all?) major browsers only support HTTP/2 using
  16021. * ALPN, this is hard to test and very low priority.
  16022. * Deactivate it (at least for now).
  16023. */
  16024. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16025. }
  16026. }
  16027. DEBUG_TRACE("http: %s, error: %s",
  16028. (ri->http_version ? ri->http_version : "none"),
  16029. (ebuf[0] ? ebuf : "none"));
  16030. if (ebuf[0] == '\0') {
  16031. if (conn->request_info.local_uri) {
  16032. /* handle request to local server */
  16033. #if defined(USE_SERVER_STATS)
  16034. conn->conn_state = 4; /* processing */
  16035. #endif
  16036. handle_request(conn);
  16037. #if defined(USE_SERVER_STATS)
  16038. conn->conn_state = 5; /* processed */
  16039. mg_atomic_add64(&(conn->phys_ctx->total_data_read),
  16040. conn->consumed_content);
  16041. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  16042. conn->num_bytes_sent);
  16043. #endif
  16044. DEBUG_TRACE("%s", "handle_request done");
  16045. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16046. conn->phys_ctx->callbacks.end_request(conn,
  16047. conn->status_code);
  16048. DEBUG_TRACE("%s", "end_request callback done");
  16049. }
  16050. log_access(conn);
  16051. /* Response complete. Free header buffer */
  16052. free_buffered_response_header_list(conn);
  16053. } else {
  16054. /* TODO: handle non-local request (PROXY) */
  16055. conn->must_close = 1;
  16056. }
  16057. } else {
  16058. conn->must_close = 1;
  16059. }
  16060. if (ri->remote_user != NULL) {
  16061. mg_free((void *)ri->remote_user);
  16062. /* Important! When having connections with and without auth
  16063. * would cause double free and then crash */
  16064. ri->remote_user = NULL;
  16065. }
  16066. /* NOTE(lsm): order is important here. should_keep_alive() call
  16067. * is using parsed request, which will be invalid after
  16068. * memmove's below.
  16069. * Therefore, memorize should_keep_alive() result now for later
  16070. * use in loop exit condition. */
  16071. /* Enable it only if this request is completely discardable. */
  16072. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16073. && should_keep_alive(conn) && (conn->content_len >= 0)
  16074. && (conn->request_len > 0)
  16075. && ((conn->is_chunked == 4)
  16076. || (!conn->is_chunked
  16077. && ((conn->consumed_content == conn->content_len)
  16078. || ((conn->request_len + conn->content_len)
  16079. <= conn->data_len))))
  16080. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16081. if (keep_alive) {
  16082. /* Discard all buffered data for this request */
  16083. discard_len =
  16084. ((conn->request_len + conn->content_len) < conn->data_len)
  16085. ? (int)(conn->request_len + conn->content_len)
  16086. : conn->data_len;
  16087. conn->data_len -= discard_len;
  16088. if (conn->data_len > 0) {
  16089. DEBUG_TRACE("discard_len = %d", discard_len);
  16090. memmove(conn->buf,
  16091. conn->buf + discard_len,
  16092. (size_t)conn->data_len);
  16093. }
  16094. }
  16095. DEBUG_ASSERT(conn->data_len >= 0);
  16096. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16097. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16098. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16099. (long int)conn->data_len,
  16100. (long int)conn->buf_size);
  16101. break;
  16102. }
  16103. conn->handled_requests++;
  16104. } while (keep_alive);
  16105. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16106. conn->request_info.remote_addr,
  16107. difftime(time(NULL), conn->conn_birth_time));
  16108. close_connection(conn);
  16109. #if defined(USE_SERVER_STATS)
  16110. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16111. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16112. #endif
  16113. }
  16114. #if defined(ALTERNATIVE_QUEUE)
  16115. static void
  16116. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16117. {
  16118. unsigned int i;
  16119. while (!ctx->stop_flag) {
  16120. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16121. /* find a free worker slot and signal it */
  16122. if (ctx->client_socks[i].in_use == 2) {
  16123. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16124. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16125. ctx->client_socks[i] = *sp;
  16126. ctx->client_socks[i].in_use = 1;
  16127. /* socket has been moved to the consumer */
  16128. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16129. (void)event_signal(ctx->client_wait_events[i]);
  16130. return;
  16131. }
  16132. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16133. }
  16134. }
  16135. /* queue is full */
  16136. mg_sleep(1);
  16137. }
  16138. /* must consume */
  16139. set_blocking_mode(sp->sock);
  16140. closesocket(sp->sock);
  16141. }
  16142. static int
  16143. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16144. {
  16145. DEBUG_TRACE("%s", "going idle");
  16146. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16147. ctx->client_socks[thread_index].in_use = 2;
  16148. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16149. event_wait(ctx->client_wait_events[thread_index]);
  16150. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16151. *sp = ctx->client_socks[thread_index];
  16152. if (ctx->stop_flag) {
  16153. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16154. if (sp->in_use == 1) {
  16155. /* must consume */
  16156. set_blocking_mode(sp->sock);
  16157. closesocket(sp->sock);
  16158. }
  16159. return 0;
  16160. }
  16161. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16162. if (sp->in_use == 1) {
  16163. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16164. return 1;
  16165. }
  16166. /* must not reach here */
  16167. DEBUG_ASSERT(0);
  16168. return 0;
  16169. }
  16170. #else /* ALTERNATIVE_QUEUE */
  16171. /* Worker threads take accepted socket from the queue */
  16172. static int
  16173. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16174. {
  16175. (void)thread_index;
  16176. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16177. DEBUG_TRACE("%s", "going idle");
  16178. /* If the queue is empty, wait. We're idle at this point. */
  16179. while ((ctx->sq_head == ctx->sq_tail)
  16180. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16181. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16182. }
  16183. /* If we're stopping, sq_head may be equal to sq_tail. */
  16184. if (ctx->sq_head > ctx->sq_tail) {
  16185. /* Copy socket from the queue and increment tail */
  16186. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16187. ctx->sq_tail++;
  16188. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16189. /* Wrap pointers if needed */
  16190. while (ctx->sq_tail > ctx->sq_size) {
  16191. ctx->sq_tail -= ctx->sq_size;
  16192. ctx->sq_head -= ctx->sq_size;
  16193. }
  16194. }
  16195. (void)pthread_cond_signal(&ctx->sq_empty);
  16196. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16197. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16198. }
  16199. /* Master thread adds accepted socket to a queue */
  16200. static void
  16201. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16202. {
  16203. int queue_filled;
  16204. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16205. queue_filled = ctx->sq_head - ctx->sq_tail;
  16206. /* If the queue is full, wait */
  16207. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16208. && (queue_filled >= ctx->sq_size)) {
  16209. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16210. #if defined(USE_SERVER_STATS)
  16211. if (queue_filled > ctx->sq_max_fill) {
  16212. ctx->sq_max_fill = queue_filled;
  16213. }
  16214. #endif
  16215. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16216. ctx->sq_blocked = 0; /* Not blocked now */
  16217. queue_filled = ctx->sq_head - ctx->sq_tail;
  16218. }
  16219. if (queue_filled < ctx->sq_size) {
  16220. /* Copy socket to the queue and increment head */
  16221. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16222. ctx->sq_head++;
  16223. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16224. }
  16225. queue_filled = ctx->sq_head - ctx->sq_tail;
  16226. #if defined(USE_SERVER_STATS)
  16227. if (queue_filled > ctx->sq_max_fill) {
  16228. ctx->sq_max_fill = queue_filled;
  16229. }
  16230. #endif
  16231. (void)pthread_cond_signal(&ctx->sq_full);
  16232. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16233. }
  16234. #endif /* ALTERNATIVE_QUEUE */
  16235. static void
  16236. worker_thread_run(struct mg_connection *conn)
  16237. {
  16238. struct mg_context *ctx = conn->phys_ctx;
  16239. int thread_index;
  16240. struct mg_workerTLS tls;
  16241. #if defined(MG_LEGACY_INTERFACE)
  16242. uint32_t addr;
  16243. #endif
  16244. mg_set_thread_name("worker");
  16245. tls.is_master = 0;
  16246. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16247. #if defined(_WIN32)
  16248. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16249. #endif
  16250. /* Initialize thread local storage before calling any callback */
  16251. pthread_setspecific(sTlsKey, &tls);
  16252. /* Check if there is a user callback */
  16253. if (ctx->callbacks.init_thread) {
  16254. /* call init_thread for a worker thread (type 1), and store the
  16255. * return value */
  16256. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16257. } else {
  16258. /* No callback: set user pointer to NULL */
  16259. tls.user_ptr = NULL;
  16260. }
  16261. /* Connection structure has been pre-allocated */
  16262. thread_index = (int)(conn - ctx->worker_connections);
  16263. if ((thread_index < 0)
  16264. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16265. mg_cry_ctx_internal(ctx,
  16266. "Internal error: Invalid worker index %i",
  16267. thread_index);
  16268. return;
  16269. }
  16270. /* Request buffers are not pre-allocated. They are private to the
  16271. * request and do not contain any state information that might be
  16272. * of interest to anyone observing a server status. */
  16273. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16274. if (conn->buf == NULL) {
  16275. mg_cry_ctx_internal(
  16276. ctx,
  16277. "Out of memory: Cannot allocate buffer for worker %i",
  16278. thread_index);
  16279. return;
  16280. }
  16281. conn->buf_size = (int)ctx->max_request_size;
  16282. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16283. conn->host = NULL; /* until we have more information. */
  16284. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16285. conn->request_info.user_data = ctx->user_data;
  16286. /* Allocate a mutex for this connection to allow communication both
  16287. * within the request handler and from elsewhere in the application
  16288. */
  16289. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16290. mg_free(conn->buf);
  16291. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16292. return;
  16293. }
  16294. #if defined(USE_SERVER_STATS)
  16295. conn->conn_state = 1; /* not consumed */
  16296. #endif
  16297. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16298. * signal sq_empty condvar to wake up the master waiting in
  16299. * produce_socket() */
  16300. while (consume_socket(ctx, &conn->client, thread_index)) {
  16301. /* New connections must start with new protocol negotiation */
  16302. tls.alpn_proto = NULL;
  16303. #if defined(USE_SERVER_STATS)
  16304. conn->conn_close_time = 0;
  16305. #endif
  16306. conn->conn_birth_time = time(NULL);
  16307. /* Fill in IP, port info early so even if SSL setup below fails,
  16308. * error handler would have the corresponding info.
  16309. * Thanks to Johannes Winkelmann for the patch.
  16310. */
  16311. #if defined(USE_IPV6)
  16312. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  16313. conn->request_info.remote_port =
  16314. ntohs(conn->client.rsa.sin6.sin6_port);
  16315. } else
  16316. #endif
  16317. {
  16318. conn->request_info.remote_port =
  16319. ntohs(conn->client.rsa.sin.sin_port);
  16320. }
  16321. sockaddr_to_string(conn->request_info.remote_addr,
  16322. sizeof(conn->request_info.remote_addr),
  16323. &conn->client.rsa);
  16324. DEBUG_TRACE("Start processing connection from %s",
  16325. conn->request_info.remote_addr);
  16326. conn->request_info.is_ssl = conn->client.is_ssl;
  16327. if (conn->client.is_ssl) {
  16328. #if !defined(NO_SSL)
  16329. /* HTTPS connection */
  16330. if (sslize(conn, SSL_accept, NULL)) {
  16331. /* conn->dom_ctx is set in get_request */
  16332. /* Get SSL client certificate information (if set) */
  16333. struct mg_client_cert client_cert;
  16334. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16335. conn->request_info.client_cert = &client_cert;
  16336. }
  16337. /* process HTTPS connection */
  16338. #if defined(USE_HTTP2)
  16339. if ((tls.alpn_proto != NULL)
  16340. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16341. /* process HTTPS/2 connection */
  16342. init_connection(conn);
  16343. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16344. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16345. conn->content_len = -1;
  16346. conn->is_chunked = 0;
  16347. process_new_http2_connection(conn);
  16348. } else
  16349. #endif
  16350. {
  16351. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16352. process_new_connection(conn);
  16353. }
  16354. /* Free client certificate info */
  16355. if (conn->request_info.client_cert) {
  16356. mg_free((void *)(conn->request_info.client_cert->subject));
  16357. mg_free((void *)(conn->request_info.client_cert->issuer));
  16358. mg_free((void *)(conn->request_info.client_cert->serial));
  16359. mg_free((void *)(conn->request_info.client_cert->finger));
  16360. /* Free certificate memory */
  16361. X509_free(
  16362. (X509 *)conn->request_info.client_cert->peer_cert);
  16363. conn->request_info.client_cert->peer_cert = 0;
  16364. conn->request_info.client_cert->subject = 0;
  16365. conn->request_info.client_cert->issuer = 0;
  16366. conn->request_info.client_cert->serial = 0;
  16367. conn->request_info.client_cert->finger = 0;
  16368. conn->request_info.client_cert = 0;
  16369. }
  16370. } else {
  16371. /* make sure the connection is cleaned up on SSL failure */
  16372. close_connection(conn);
  16373. }
  16374. #endif
  16375. } else {
  16376. /* process HTTP connection */
  16377. process_new_connection(conn);
  16378. }
  16379. DEBUG_TRACE("%s", "Connection closed");
  16380. #if defined(USE_SERVER_STATS)
  16381. conn->conn_close_time = time(NULL);
  16382. #endif
  16383. }
  16384. /* Call exit thread user callback */
  16385. if (ctx->callbacks.exit_thread) {
  16386. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16387. }
  16388. /* delete thread local storage objects */
  16389. pthread_setspecific(sTlsKey, NULL);
  16390. #if defined(_WIN32)
  16391. CloseHandle(tls.pthread_cond_helper_mutex);
  16392. #endif
  16393. pthread_mutex_destroy(&conn->mutex);
  16394. /* Free the request buffer. */
  16395. conn->buf_size = 0;
  16396. mg_free(conn->buf);
  16397. conn->buf = NULL;
  16398. #if defined(USE_SERVER_STATS)
  16399. conn->conn_state = 9; /* done */
  16400. #endif
  16401. DEBUG_TRACE("%s", "exiting");
  16402. }
  16403. /* Threads have different return types on Windows and Unix. */
  16404. #if defined(_WIN32)
  16405. static unsigned __stdcall worker_thread(void *thread_func_param)
  16406. {
  16407. worker_thread_run((struct mg_connection *)thread_func_param);
  16408. return 0;
  16409. }
  16410. #else
  16411. static void *
  16412. worker_thread(void *thread_func_param)
  16413. {
  16414. #if !defined(__ZEPHYR__)
  16415. struct sigaction sa;
  16416. /* Ignore SIGPIPE */
  16417. memset(&sa, 0, sizeof(sa));
  16418. sa.sa_handler = SIG_IGN;
  16419. sigaction(SIGPIPE, &sa, NULL);
  16420. #endif
  16421. worker_thread_run((struct mg_connection *)thread_func_param);
  16422. return NULL;
  16423. }
  16424. #endif /* _WIN32 */
  16425. /* This is an internal function, thus all arguments are expected to be
  16426. * valid - a NULL check is not required. */
  16427. static void
  16428. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16429. {
  16430. struct socket so;
  16431. char src_addr[IP_ADDR_STR_LEN];
  16432. socklen_t len = sizeof(so.rsa);
  16433. #if !defined(__ZEPHYR__)
  16434. int on = 1;
  16435. #endif
  16436. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16437. == INVALID_SOCKET) {
  16438. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16439. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16440. mg_cry_ctx_internal(ctx,
  16441. "%s: %s is not allowed to connect",
  16442. __func__,
  16443. src_addr);
  16444. closesocket(so.sock);
  16445. } else {
  16446. /* Put so socket structure into the queue */
  16447. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16448. set_close_on_exec(so.sock, NULL, ctx);
  16449. so.is_ssl = listener->is_ssl;
  16450. so.ssl_redir = listener->ssl_redir;
  16451. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16452. mg_cry_ctx_internal(ctx,
  16453. "%s: getsockname() failed: %s",
  16454. __func__,
  16455. strerror(ERRNO));
  16456. }
  16457. #if !defined(__ZEPHYR__)
  16458. /* Set TCP keep-alive. This is needed because if HTTP-level
  16459. * keep-alive
  16460. * is enabled, and client resets the connection, server won't get
  16461. * TCP FIN or RST and will keep the connection open forever. With
  16462. * TCP keep-alive, next keep-alive handshake will figure out that
  16463. * the client is down and will close the server end.
  16464. * Thanks to Igor Klopov who suggested the patch. */
  16465. if (setsockopt(so.sock,
  16466. SOL_SOCKET,
  16467. SO_KEEPALIVE,
  16468. (SOCK_OPT_TYPE)&on,
  16469. sizeof(on))
  16470. != 0) {
  16471. mg_cry_ctx_internal(
  16472. ctx,
  16473. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16474. __func__,
  16475. strerror(ERRNO));
  16476. }
  16477. #endif
  16478. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16479. * to effectively fill up the underlying IP packet payload and
  16480. * reduce the overhead of sending lots of small buffers. However
  16481. * this hurts the server's throughput (ie. operations per second)
  16482. * when HTTP 1.1 persistent connections are used and the responses
  16483. * are relatively small (eg. less than 1400 bytes).
  16484. */
  16485. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16486. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16487. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16488. mg_cry_ctx_internal(
  16489. ctx,
  16490. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16491. __func__,
  16492. strerror(ERRNO));
  16493. }
  16494. }
  16495. /* The "non blocking" property should already be
  16496. * inherited from the parent socket. Set it for
  16497. * non-compliant socket implementations. */
  16498. set_non_blocking_mode(so.sock);
  16499. so.in_use = 0;
  16500. produce_socket(ctx, &so);
  16501. }
  16502. }
  16503. static void
  16504. master_thread_run(struct mg_context *ctx)
  16505. {
  16506. struct mg_workerTLS tls;
  16507. struct mg_pollfd *pfd;
  16508. unsigned int i;
  16509. unsigned int workerthreadcount;
  16510. if (!ctx) {
  16511. return;
  16512. }
  16513. mg_set_thread_name("master");
  16514. /* Increase priority of the master thread */
  16515. #if defined(_WIN32)
  16516. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16517. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16518. int min_prio = sched_get_priority_min(SCHED_RR);
  16519. int max_prio = sched_get_priority_max(SCHED_RR);
  16520. if ((min_prio >= 0) && (max_prio >= 0)
  16521. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16522. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16523. struct sched_param sched_param = {0};
  16524. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16525. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16526. }
  16527. #endif
  16528. /* Initialize thread local storage */
  16529. #if defined(_WIN32)
  16530. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16531. #endif
  16532. tls.is_master = 1;
  16533. pthread_setspecific(sTlsKey, &tls);
  16534. if (ctx->callbacks.init_thread) {
  16535. /* Callback for the master thread (type 0) */
  16536. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16537. } else {
  16538. tls.user_ptr = NULL;
  16539. }
  16540. /* Server starts *now* */
  16541. ctx->start_time = time(NULL);
  16542. /* Start the server */
  16543. pfd = ctx->listening_socket_fds;
  16544. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16545. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16546. pfd[i].fd = ctx->listening_sockets[i].sock;
  16547. pfd[i].events = POLLIN;
  16548. }
  16549. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16550. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16551. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16552. * successful poll, and POLLIN is defined as
  16553. * (POLLRDNORM | POLLRDBAND)
  16554. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16555. * pfd[i].revents == POLLIN. */
  16556. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16557. && (pfd[i].revents & POLLIN)) {
  16558. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16559. }
  16560. }
  16561. }
  16562. }
  16563. /* Here stop_flag is 1 - Initiate shutdown. */
  16564. DEBUG_TRACE("%s", "stopping workers");
  16565. /* Stop signal received: somebody called mg_stop. Quit. */
  16566. close_all_listening_sockets(ctx);
  16567. /* Wakeup workers that are waiting for connections to handle. */
  16568. #if defined(ALTERNATIVE_QUEUE)
  16569. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16570. event_signal(ctx->client_wait_events[i]);
  16571. }
  16572. #else
  16573. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16574. pthread_cond_broadcast(&ctx->sq_full);
  16575. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16576. #endif
  16577. /* Join all worker threads to avoid leaking threads. */
  16578. workerthreadcount = ctx->cfg_worker_threads;
  16579. for (i = 0; i < workerthreadcount; i++) {
  16580. if (ctx->worker_threadids[i] != 0) {
  16581. mg_join_thread(ctx->worker_threadids[i]);
  16582. }
  16583. }
  16584. #if defined(USE_LUA)
  16585. /* Free Lua state of lua background task */
  16586. if (ctx->lua_background_state) {
  16587. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16588. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16589. if (lua_istable(lstate, -1)) {
  16590. reg_boolean(lstate, "shutdown", 1);
  16591. lua_pop(lstate, 1);
  16592. mg_sleep(2);
  16593. }
  16594. lua_close(lstate);
  16595. ctx->lua_background_state = 0;
  16596. }
  16597. #endif
  16598. DEBUG_TRACE("%s", "exiting");
  16599. /* call exit thread callback */
  16600. if (ctx->callbacks.exit_thread) {
  16601. /* Callback for the master thread (type 0) */
  16602. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16603. }
  16604. #if defined(_WIN32)
  16605. CloseHandle(tls.pthread_cond_helper_mutex);
  16606. #endif
  16607. pthread_setspecific(sTlsKey, NULL);
  16608. /* Signal mg_stop() that we're done.
  16609. * WARNING: This must be the very last thing this
  16610. * thread does, as ctx becomes invalid after this line. */
  16611. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16612. }
  16613. /* Threads have different return types on Windows and Unix. */
  16614. #if defined(_WIN32)
  16615. static unsigned __stdcall master_thread(void *thread_func_param)
  16616. {
  16617. master_thread_run((struct mg_context *)thread_func_param);
  16618. return 0;
  16619. }
  16620. #else
  16621. static void *
  16622. master_thread(void *thread_func_param)
  16623. {
  16624. #if !defined(__ZEPHYR__)
  16625. struct sigaction sa;
  16626. /* Ignore SIGPIPE */
  16627. memset(&sa, 0, sizeof(sa));
  16628. sa.sa_handler = SIG_IGN;
  16629. sigaction(SIGPIPE, &sa, NULL);
  16630. #endif
  16631. master_thread_run((struct mg_context *)thread_func_param);
  16632. return NULL;
  16633. }
  16634. #endif /* _WIN32 */
  16635. static void
  16636. free_context(struct mg_context *ctx)
  16637. {
  16638. int i;
  16639. struct mg_handler_info *tmp_rh;
  16640. if (ctx == NULL) {
  16641. return;
  16642. }
  16643. if (ctx->callbacks.exit_context) {
  16644. ctx->callbacks.exit_context(ctx);
  16645. }
  16646. /* All threads exited, no sync is needed. Destroy thread mutex and
  16647. * condvars
  16648. */
  16649. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16650. #if defined(ALTERNATIVE_QUEUE)
  16651. mg_free(ctx->client_socks);
  16652. if (ctx->client_wait_events != NULL) {
  16653. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16654. event_destroy(ctx->client_wait_events[i]);
  16655. }
  16656. mg_free(ctx->client_wait_events);
  16657. }
  16658. #else
  16659. (void)pthread_cond_destroy(&ctx->sq_empty);
  16660. (void)pthread_cond_destroy(&ctx->sq_full);
  16661. mg_free(ctx->squeue);
  16662. #endif
  16663. /* Destroy other context global data structures mutex */
  16664. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16665. #if defined(USE_TIMERS)
  16666. timers_exit(ctx);
  16667. #endif
  16668. /* Deallocate config parameters */
  16669. for (i = 0; i < NUM_OPTIONS; i++) {
  16670. if (ctx->dd.config[i] != NULL) {
  16671. #if defined(_MSC_VER)
  16672. #pragma warning(suppress : 6001)
  16673. #endif
  16674. mg_free(ctx->dd.config[i]);
  16675. }
  16676. }
  16677. /* Deallocate request handlers */
  16678. while (ctx->dd.handlers) {
  16679. tmp_rh = ctx->dd.handlers;
  16680. ctx->dd.handlers = tmp_rh->next;
  16681. mg_free(tmp_rh->uri);
  16682. mg_free(tmp_rh);
  16683. }
  16684. #if !defined(NO_SSL)
  16685. /* Deallocate SSL context */
  16686. if (ctx->dd.ssl_ctx != NULL) {
  16687. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16688. int callback_ret =
  16689. (ctx->callbacks.external_ssl_ctx == NULL)
  16690. ? 0
  16691. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16692. if (callback_ret == 0) {
  16693. SSL_CTX_free(ctx->dd.ssl_ctx);
  16694. }
  16695. /* else: ignore error and ommit SSL_CTX_free in case
  16696. * callback_ret is 1 */
  16697. }
  16698. #endif /* !NO_SSL */
  16699. /* Deallocate worker thread ID array */
  16700. mg_free(ctx->worker_threadids);
  16701. /* Deallocate worker thread ID array */
  16702. mg_free(ctx->worker_connections);
  16703. /* deallocate system name string */
  16704. mg_free(ctx->systemName);
  16705. /* Deallocate context itself */
  16706. mg_free(ctx);
  16707. }
  16708. void
  16709. mg_stop(struct mg_context *ctx)
  16710. {
  16711. pthread_t mt;
  16712. if (!ctx) {
  16713. return;
  16714. }
  16715. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16716. * two threads is not allowed. */
  16717. mt = ctx->masterthreadid;
  16718. if (mt == 0) {
  16719. return;
  16720. }
  16721. ctx->masterthreadid = 0;
  16722. /* Set stop flag, so all threads know they have to exit. */
  16723. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16724. /* Wait until everything has stopped. */
  16725. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16726. (void)mg_sleep(10);
  16727. }
  16728. mg_join_thread(mt);
  16729. free_context(ctx);
  16730. #if defined(_WIN32)
  16731. (void)WSACleanup();
  16732. #endif /* _WIN32 */
  16733. }
  16734. static void
  16735. get_system_name(char **sysName)
  16736. {
  16737. #if defined(_WIN32)
  16738. #if defined(_WIN32_WCE)
  16739. *sysName = mg_strdup("WinCE");
  16740. #else
  16741. char name[128];
  16742. DWORD dwVersion = 0;
  16743. DWORD dwMajorVersion = 0;
  16744. DWORD dwMinorVersion = 0;
  16745. DWORD dwBuild = 0;
  16746. BOOL wowRet, isWoW = FALSE;
  16747. #if defined(_MSC_VER)
  16748. #pragma warning(push)
  16749. /* GetVersion was declared deprecated */
  16750. #pragma warning(disable : 4996)
  16751. #endif
  16752. dwVersion = GetVersion();
  16753. #if defined(_MSC_VER)
  16754. #pragma warning(pop)
  16755. #endif
  16756. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16757. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16758. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16759. (void)dwBuild;
  16760. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16761. sprintf(name,
  16762. "Windows %u.%u%s",
  16763. (unsigned)dwMajorVersion,
  16764. (unsigned)dwMinorVersion,
  16765. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16766. *sysName = mg_strdup(name);
  16767. #endif
  16768. #elif defined(__ZEPHYR__)
  16769. *sysName = mg_strdup("Zephyr OS");
  16770. #else
  16771. struct utsname name;
  16772. memset(&name, 0, sizeof(name));
  16773. uname(&name);
  16774. *sysName = mg_strdup(name.sysname);
  16775. #endif
  16776. }
  16777. static void
  16778. legacy_init(const char **options)
  16779. {
  16780. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16781. if (options) {
  16782. const char **run_options = options;
  16783. const char *optname = config_options[LISTENING_PORTS].name;
  16784. /* Try to find the "listening_ports" option */
  16785. while (*run_options) {
  16786. if (!strcmp(*run_options, optname)) {
  16787. ports_option = run_options[1];
  16788. }
  16789. run_options += 2;
  16790. }
  16791. }
  16792. if (is_ssl_port_used(ports_option)) {
  16793. /* Initialize with SSL support */
  16794. mg_init_library(MG_FEATURES_TLS);
  16795. } else {
  16796. /* Initialize without SSL support */
  16797. mg_init_library(MG_FEATURES_DEFAULT);
  16798. }
  16799. }
  16800. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16801. static
  16802. #endif
  16803. struct mg_context *
  16804. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16805. {
  16806. struct mg_context *ctx;
  16807. const char *name, *value, *default_value;
  16808. int idx, ok, workerthreadcount;
  16809. unsigned int i;
  16810. int itmp;
  16811. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16812. const char **options =
  16813. ((init != NULL) ? (init->configuration_options) : (NULL));
  16814. struct mg_workerTLS tls;
  16815. #if defined(_WIN32)
  16816. WSADATA data;
  16817. WSAStartup(MAKEWORD(2, 2), &data);
  16818. #endif /* _WIN32 */
  16819. if (error != NULL) {
  16820. error->code = 0;
  16821. if (error->text_buffer_size > 0) {
  16822. *error->text = 0;
  16823. }
  16824. }
  16825. if (mg_init_library_called == 0) {
  16826. /* Legacy INIT, if mg_start is called without mg_init_library.
  16827. * Note: This will cause a memory leak when unloading the library.
  16828. */
  16829. legacy_init(options);
  16830. }
  16831. /* Allocate context and initialize reasonable general case defaults. */
  16832. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16833. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16834. mg_snprintf(NULL,
  16835. NULL, /* No truncation check for error buffers */
  16836. error->text,
  16837. error->text_buffer_size,
  16838. "%s",
  16839. "Out of memory");
  16840. }
  16841. return NULL;
  16842. }
  16843. /* Random number generator will initialize at the first call */
  16844. ctx->dd.auth_nonce_mask =
  16845. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16846. /* Save started thread index to reuse in other external API calls
  16847. * For the sake of thread synchronization all non-civetweb threads
  16848. * can be considered as single external thread */
  16849. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16850. tls.is_master = -1; /* Thread calling mg_start */
  16851. tls.thread_idx = ctx->starter_thread_idx;
  16852. #if defined(_WIN32)
  16853. tls.pthread_cond_helper_mutex = NULL;
  16854. #endif
  16855. pthread_setspecific(sTlsKey, &tls);
  16856. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16857. #if !defined(ALTERNATIVE_QUEUE)
  16858. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16859. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16860. ctx->sq_blocked = 0;
  16861. #endif
  16862. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16863. if (!ok) {
  16864. const char *err_msg =
  16865. "Cannot initialize thread synchronization objects";
  16866. /* Fatal error - abort start. However, this situation should never
  16867. * occur in practice. */
  16868. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16869. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16870. mg_snprintf(NULL,
  16871. NULL, /* No truncation check for error buffers */
  16872. error->text,
  16873. error->text_buffer_size,
  16874. "%s",
  16875. err_msg);
  16876. }
  16877. mg_free(ctx);
  16878. pthread_setspecific(sTlsKey, NULL);
  16879. return NULL;
  16880. }
  16881. if ((init != NULL) && (init->callbacks != NULL)) {
  16882. /* Set all callbacks except exit_context. */
  16883. ctx->callbacks = *init->callbacks;
  16884. exit_callback = init->callbacks->exit_context;
  16885. /* The exit callback is activated once the context is successfully
  16886. * created. It should not be called, if an incomplete context object
  16887. * is deleted during a failed initialization. */
  16888. ctx->callbacks.exit_context = 0;
  16889. }
  16890. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16891. ctx->dd.handlers = NULL;
  16892. ctx->dd.next = NULL;
  16893. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16894. ctx->dd.shared_lua_websockets = NULL;
  16895. #endif
  16896. /* Store options */
  16897. while (options && (name = *options++) != NULL) {
  16898. if ((idx = get_option_index(name)) == -1) {
  16899. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16900. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16901. mg_snprintf(NULL,
  16902. NULL, /* No truncation check for error buffers */
  16903. error->text,
  16904. error->text_buffer_size,
  16905. "Invalid configuration option: %s",
  16906. name);
  16907. }
  16908. free_context(ctx);
  16909. pthread_setspecific(sTlsKey, NULL);
  16910. return NULL;
  16911. } else if ((value = *options++) == NULL) {
  16912. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16913. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16914. mg_snprintf(NULL,
  16915. NULL, /* No truncation check for error buffers */
  16916. error->text,
  16917. error->text_buffer_size,
  16918. "Invalid configuration option value: %s",
  16919. name);
  16920. }
  16921. free_context(ctx);
  16922. pthread_setspecific(sTlsKey, NULL);
  16923. return NULL;
  16924. }
  16925. if (ctx->dd.config[idx] != NULL) {
  16926. /* A duplicate configuration option is not an error - the last
  16927. * option value will be used. */
  16928. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16929. mg_free(ctx->dd.config[idx]);
  16930. }
  16931. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16932. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16933. }
  16934. /* Set default value if needed */
  16935. for (i = 0; config_options[i].name != NULL; i++) {
  16936. default_value = config_options[i].default_value;
  16937. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16938. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16939. }
  16940. }
  16941. /* Request size option */
  16942. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16943. if (itmp < 1024) {
  16944. mg_cry_ctx_internal(ctx,
  16945. "%s too small",
  16946. config_options[MAX_REQUEST_SIZE].name);
  16947. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16948. mg_snprintf(NULL,
  16949. NULL, /* No truncation check for error buffers */
  16950. error->text,
  16951. error->text_buffer_size,
  16952. "Invalid configuration option value: %s",
  16953. config_options[MAX_REQUEST_SIZE].name);
  16954. }
  16955. free_context(ctx);
  16956. pthread_setspecific(sTlsKey, NULL);
  16957. return NULL;
  16958. }
  16959. ctx->max_request_size = (unsigned)itmp;
  16960. /* Queue length */
  16961. #if !defined(ALTERNATIVE_QUEUE)
  16962. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16963. if (itmp < 1) {
  16964. mg_cry_ctx_internal(ctx,
  16965. "%s too small",
  16966. config_options[CONNECTION_QUEUE_SIZE].name);
  16967. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16968. mg_snprintf(NULL,
  16969. NULL, /* No truncation check for error buffers */
  16970. error->text,
  16971. error->text_buffer_size,
  16972. "Invalid configuration option value: %s",
  16973. config_options[CONNECTION_QUEUE_SIZE].name);
  16974. }
  16975. free_context(ctx);
  16976. pthread_setspecific(sTlsKey, NULL);
  16977. return NULL;
  16978. }
  16979. ctx->squeue =
  16980. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16981. if (ctx->squeue == NULL) {
  16982. mg_cry_ctx_internal(ctx,
  16983. "Out of memory: Cannot allocate %s",
  16984. config_options[CONNECTION_QUEUE_SIZE].name);
  16985. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16986. mg_snprintf(NULL,
  16987. NULL, /* No truncation check for error buffers */
  16988. error->text,
  16989. error->text_buffer_size,
  16990. "Out of memory: Cannot allocate %s",
  16991. config_options[CONNECTION_QUEUE_SIZE].name);
  16992. }
  16993. free_context(ctx);
  16994. pthread_setspecific(sTlsKey, NULL);
  16995. return NULL;
  16996. }
  16997. ctx->sq_size = itmp;
  16998. #endif
  16999. /* Worker thread count option */
  17000. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17001. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17002. if (workerthreadcount <= 0) {
  17003. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17004. } else {
  17005. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17006. }
  17007. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17008. mg_snprintf(NULL,
  17009. NULL, /* No truncation check for error buffers */
  17010. error->text,
  17011. error->text_buffer_size,
  17012. "Invalid configuration option value: %s",
  17013. config_options[NUM_THREADS].name);
  17014. }
  17015. free_context(ctx);
  17016. pthread_setspecific(sTlsKey, NULL);
  17017. return NULL;
  17018. }
  17019. /* Document root */
  17020. #if defined(NO_FILES)
  17021. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17022. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17023. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17024. mg_snprintf(NULL,
  17025. NULL, /* No truncation check for error buffers */
  17026. error->text,
  17027. error->text_buffer_size,
  17028. "Invalid configuration option value: %s",
  17029. config_options[DOCUMENT_ROOT].name);
  17030. }
  17031. free_context(ctx);
  17032. pthread_setspecific(sTlsKey, NULL);
  17033. return NULL;
  17034. }
  17035. #endif
  17036. get_system_name(&ctx->systemName);
  17037. #if defined(USE_LUA)
  17038. /* If a Lua background script has been configured, start it. */
  17039. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17040. char ebuf[256];
  17041. struct vec opt_vec;
  17042. struct vec eq_vec;
  17043. const char *sparams;
  17044. lua_State *state = mg_prepare_lua_context_script(
  17045. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17046. if (!state) {
  17047. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  17048. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17049. mg_snprintf(NULL,
  17050. NULL, /* No truncation check for error buffers */
  17051. error->text,
  17052. error->text_buffer_size,
  17053. "Error in script %s: %s",
  17054. config_options[DOCUMENT_ROOT].name,
  17055. ebuf);
  17056. }
  17057. free_context(ctx);
  17058. pthread_setspecific(sTlsKey, NULL);
  17059. return NULL;
  17060. }
  17061. ctx->lua_background_state = (void *)state;
  17062. lua_newtable(state);
  17063. reg_boolean(state, "shutdown", 0);
  17064. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17065. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17066. reg_llstring(
  17067. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17068. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17069. break;
  17070. }
  17071. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17072. } else {
  17073. ctx->lua_background_state = 0;
  17074. }
  17075. #endif
  17076. /* Step by step initialization of ctx - depending on build options */
  17077. #if !defined(NO_FILESYSTEMS)
  17078. if (!set_gpass_option(ctx, NULL)) {
  17079. const char *err_msg = "Invalid global password file";
  17080. /* Fatal error - abort start. */
  17081. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17082. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17083. mg_snprintf(NULL,
  17084. NULL, /* No truncation check for error buffers */
  17085. error->text,
  17086. error->text_buffer_size,
  17087. "%s",
  17088. err_msg);
  17089. }
  17090. free_context(ctx);
  17091. pthread_setspecific(sTlsKey, NULL);
  17092. return NULL;
  17093. }
  17094. #endif
  17095. #if !defined(NO_SSL)
  17096. if (!init_ssl_ctx(ctx, NULL)) {
  17097. const char *err_msg = "Error initializing SSL context";
  17098. /* Fatal error - abort start. */
  17099. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17100. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17101. mg_snprintf(NULL,
  17102. NULL, /* No truncation check for error buffers */
  17103. error->text,
  17104. error->text_buffer_size,
  17105. "%s",
  17106. err_msg);
  17107. }
  17108. free_context(ctx);
  17109. pthread_setspecific(sTlsKey, NULL);
  17110. return NULL;
  17111. }
  17112. #endif
  17113. if (!set_ports_option(ctx)) {
  17114. const char *err_msg = "Failed to setup server ports";
  17115. /* Fatal error - abort start. */
  17116. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17117. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17118. mg_snprintf(NULL,
  17119. NULL, /* No truncation check for error buffers */
  17120. error->text,
  17121. error->text_buffer_size,
  17122. "%s",
  17123. err_msg);
  17124. }
  17125. free_context(ctx);
  17126. pthread_setspecific(sTlsKey, NULL);
  17127. return NULL;
  17128. }
  17129. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17130. if (!set_uid_option(ctx)) {
  17131. const char *err_msg = "Failed to run as configured user";
  17132. /* Fatal error - abort start. */
  17133. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17134. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17135. mg_snprintf(NULL,
  17136. NULL, /* No truncation check for error buffers */
  17137. error->text,
  17138. error->text_buffer_size,
  17139. "%s",
  17140. err_msg);
  17141. }
  17142. free_context(ctx);
  17143. pthread_setspecific(sTlsKey, NULL);
  17144. return NULL;
  17145. }
  17146. #endif
  17147. if (!set_acl_option(ctx)) {
  17148. const char *err_msg = "Failed to setup access control list";
  17149. /* Fatal error - abort start. */
  17150. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17151. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17152. mg_snprintf(NULL,
  17153. NULL, /* No truncation check for error buffers */
  17154. error->text,
  17155. error->text_buffer_size,
  17156. "%s",
  17157. err_msg);
  17158. }
  17159. free_context(ctx);
  17160. pthread_setspecific(sTlsKey, NULL);
  17161. return NULL;
  17162. }
  17163. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17164. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17165. sizeof(pthread_t),
  17166. ctx);
  17167. if (ctx->worker_threadids == NULL) {
  17168. const char *err_msg = "Not enough memory for worker thread ID array";
  17169. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17170. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17171. mg_snprintf(NULL,
  17172. NULL, /* No truncation check for error buffers */
  17173. error->text,
  17174. error->text_buffer_size,
  17175. "%s",
  17176. err_msg);
  17177. }
  17178. free_context(ctx);
  17179. pthread_setspecific(sTlsKey, NULL);
  17180. return NULL;
  17181. }
  17182. ctx->worker_connections =
  17183. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17184. sizeof(struct mg_connection),
  17185. ctx);
  17186. if (ctx->worker_connections == NULL) {
  17187. const char *err_msg =
  17188. "Not enough memory for worker thread connection array";
  17189. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17190. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17191. mg_snprintf(NULL,
  17192. NULL, /* No truncation check for error buffers */
  17193. error->text,
  17194. error->text_buffer_size,
  17195. "%s",
  17196. err_msg);
  17197. }
  17198. free_context(ctx);
  17199. pthread_setspecific(sTlsKey, NULL);
  17200. return NULL;
  17201. }
  17202. #if defined(ALTERNATIVE_QUEUE)
  17203. ctx->client_wait_events =
  17204. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17205. sizeof(ctx->client_wait_events[0]),
  17206. ctx);
  17207. if (ctx->client_wait_events == NULL) {
  17208. const char *err_msg = "Not enough memory for worker event array";
  17209. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17210. mg_free(ctx->worker_threadids);
  17211. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17212. mg_snprintf(NULL,
  17213. NULL, /* No truncation check for error buffers */
  17214. error->text,
  17215. error->text_buffer_size,
  17216. "%s",
  17217. err_msg);
  17218. }
  17219. free_context(ctx);
  17220. pthread_setspecific(sTlsKey, NULL);
  17221. return NULL;
  17222. }
  17223. ctx->client_socks =
  17224. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17225. sizeof(ctx->client_socks[0]),
  17226. ctx);
  17227. if (ctx->client_socks == NULL) {
  17228. const char *err_msg = "Not enough memory for worker socket array";
  17229. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17230. mg_free(ctx->client_wait_events);
  17231. mg_free(ctx->worker_threadids);
  17232. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17233. mg_snprintf(NULL,
  17234. NULL, /* No truncation check for error buffers */
  17235. error->text,
  17236. error->text_buffer_size,
  17237. "%s",
  17238. err_msg);
  17239. }
  17240. free_context(ctx);
  17241. pthread_setspecific(sTlsKey, NULL);
  17242. return NULL;
  17243. }
  17244. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17245. ctx->client_wait_events[i] = event_create();
  17246. if (ctx->client_wait_events[i] == 0) {
  17247. const char *err_msg = "Error creating worker event %i";
  17248. mg_cry_ctx_internal(ctx, err_msg, i);
  17249. while (i > 0) {
  17250. i--;
  17251. event_destroy(ctx->client_wait_events[i]);
  17252. }
  17253. mg_free(ctx->client_socks);
  17254. mg_free(ctx->client_wait_events);
  17255. mg_free(ctx->worker_threadids);
  17256. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17257. mg_snprintf(NULL,
  17258. NULL, /* No truncation check for error buffers */
  17259. error->text,
  17260. error->text_buffer_size,
  17261. err_msg,
  17262. i);
  17263. }
  17264. free_context(ctx);
  17265. pthread_setspecific(sTlsKey, NULL);
  17266. return NULL;
  17267. }
  17268. }
  17269. #endif
  17270. #if defined(USE_TIMERS)
  17271. if (timers_init(ctx) != 0) {
  17272. const char *err_msg = "Error creating timers";
  17273. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17274. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17275. mg_snprintf(NULL,
  17276. NULL, /* No truncation check for error buffers */
  17277. error->text,
  17278. error->text_buffer_size,
  17279. "%s",
  17280. err_msg);
  17281. }
  17282. free_context(ctx);
  17283. pthread_setspecific(sTlsKey, NULL);
  17284. return NULL;
  17285. }
  17286. #endif
  17287. /* Context has been created - init user libraries */
  17288. if (ctx->callbacks.init_context) {
  17289. ctx->callbacks.init_context(ctx);
  17290. }
  17291. /* From now, the context is successfully created.
  17292. * When it is destroyed, the exit callback should be called. */
  17293. ctx->callbacks.exit_context = exit_callback;
  17294. ctx->context_type = CONTEXT_SERVER; /* server context */
  17295. /* Start worker threads */
  17296. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17297. /* worker_thread sets up the other fields */
  17298. ctx->worker_connections[i].phys_ctx = ctx;
  17299. if (mg_start_thread_with_id(worker_thread,
  17300. &ctx->worker_connections[i],
  17301. &ctx->worker_threadids[i])
  17302. != 0) {
  17303. long error_no = (long)ERRNO;
  17304. /* thread was not created */
  17305. if (i > 0) {
  17306. /* If the second, third, ... thread cannot be created, set a
  17307. * warning, but keep running. */
  17308. mg_cry_ctx_internal(ctx,
  17309. "Cannot start worker thread %i: error %ld",
  17310. i + 1,
  17311. error_no);
  17312. /* If the server initialization should stop here, all
  17313. * threads that have already been created must be stopped
  17314. * first, before any free_context(ctx) call.
  17315. */
  17316. } else {
  17317. /* If the first worker thread cannot be created, stop
  17318. * initialization and free the entire server context. */
  17319. mg_cry_ctx_internal(ctx,
  17320. "Cannot create threads: error %ld",
  17321. error_no);
  17322. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17323. mg_snprintf(
  17324. NULL,
  17325. NULL, /* No truncation check for error buffers */
  17326. error->text,
  17327. error->text_buffer_size,
  17328. "Cannot create first worker thread: error %ld",
  17329. error_no);
  17330. }
  17331. free_context(ctx);
  17332. pthread_setspecific(sTlsKey, NULL);
  17333. return NULL;
  17334. }
  17335. break;
  17336. }
  17337. }
  17338. /* Start master (listening) thread */
  17339. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17340. pthread_setspecific(sTlsKey, NULL);
  17341. return ctx;
  17342. }
  17343. struct mg_context *
  17344. mg_start(const struct mg_callbacks *callbacks,
  17345. void *user_data,
  17346. const char **options)
  17347. {
  17348. struct mg_init_data init = {0};
  17349. init.callbacks = callbacks;
  17350. init.user_data = user_data;
  17351. init.configuration_options = options;
  17352. return mg_start2(&init, NULL);
  17353. }
  17354. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17355. /* Add an additional domain to an already running web server. */
  17356. int
  17357. mg_start_domain2(struct mg_context *ctx,
  17358. const char **options,
  17359. struct mg_error_data *error)
  17360. {
  17361. const char *name;
  17362. const char *value;
  17363. const char *default_value;
  17364. struct mg_domain_context *new_dom;
  17365. struct mg_domain_context *dom;
  17366. int idx, i;
  17367. if (error != NULL) {
  17368. error->code = 0;
  17369. if (error->text_buffer_size > 0) {
  17370. *error->text = 0;
  17371. }
  17372. }
  17373. if ((ctx == NULL) || (options == NULL)) {
  17374. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17375. mg_snprintf(NULL,
  17376. NULL, /* No truncation check for error buffers */
  17377. error->text,
  17378. error->text_buffer_size,
  17379. "%s",
  17380. "Invalid parameters");
  17381. }
  17382. return -1;
  17383. }
  17384. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17385. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17386. mg_snprintf(NULL,
  17387. NULL, /* No truncation check for error buffers */
  17388. error->text,
  17389. error->text_buffer_size,
  17390. "%s",
  17391. "Server already stopped");
  17392. }
  17393. return -1;
  17394. }
  17395. new_dom = (struct mg_domain_context *)
  17396. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17397. if (!new_dom) {
  17398. /* Out of memory */
  17399. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17400. mg_snprintf(NULL,
  17401. NULL, /* No truncation check for error buffers */
  17402. error->text,
  17403. error->text_buffer_size,
  17404. "%s",
  17405. "Out or memory");
  17406. }
  17407. return -6;
  17408. }
  17409. /* Store options - TODO: unite duplicate code */
  17410. while (options && (name = *options++) != NULL) {
  17411. if ((idx = get_option_index(name)) == -1) {
  17412. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17413. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17414. mg_snprintf(NULL,
  17415. NULL, /* No truncation check for error buffers */
  17416. error->text,
  17417. error->text_buffer_size,
  17418. "Invalid option: %s",
  17419. name);
  17420. }
  17421. mg_free(new_dom);
  17422. return -2;
  17423. } else if ((value = *options++) == NULL) {
  17424. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17425. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17426. mg_snprintf(NULL,
  17427. NULL, /* No truncation check for error buffers */
  17428. error->text,
  17429. error->text_buffer_size,
  17430. "Invalid option value: %s",
  17431. name);
  17432. }
  17433. mg_free(new_dom);
  17434. return -2;
  17435. }
  17436. if (new_dom->config[idx] != NULL) {
  17437. /* Duplicate option: Later values overwrite earlier ones. */
  17438. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17439. mg_free(new_dom->config[idx]);
  17440. }
  17441. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17442. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17443. }
  17444. /* Authentication domain is mandatory */
  17445. /* TODO: Maybe use a new option hostname? */
  17446. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17447. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  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. "Mandatory option %s missing",
  17454. config_options[AUTHENTICATION_DOMAIN].name);
  17455. }
  17456. mg_free(new_dom);
  17457. return -4;
  17458. }
  17459. /* Set default value if needed. Take the config value from
  17460. * ctx as a default value. */
  17461. for (i = 0; config_options[i].name != NULL; i++) {
  17462. default_value = ctx->dd.config[i];
  17463. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17464. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17465. }
  17466. }
  17467. new_dom->handlers = NULL;
  17468. new_dom->next = NULL;
  17469. new_dom->nonce_count = 0;
  17470. new_dom->auth_nonce_mask =
  17471. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17472. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17473. new_dom->shared_lua_websockets = NULL;
  17474. #endif
  17475. if (!init_ssl_ctx(ctx, new_dom)) {
  17476. /* Init SSL failed */
  17477. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17478. mg_snprintf(NULL,
  17479. NULL, /* No truncation check for error buffers */
  17480. error->text,
  17481. error->text_buffer_size,
  17482. "%s",
  17483. "Initializing SSL context failed");
  17484. }
  17485. mg_free(new_dom);
  17486. return -3;
  17487. }
  17488. /* Add element to linked list. */
  17489. mg_lock_context(ctx);
  17490. idx = 0;
  17491. dom = &(ctx->dd);
  17492. for (;;) {
  17493. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17494. dom->config[AUTHENTICATION_DOMAIN])) {
  17495. /* Domain collision */
  17496. mg_cry_ctx_internal(ctx,
  17497. "domain %s already in use",
  17498. new_dom->config[AUTHENTICATION_DOMAIN]);
  17499. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17500. mg_snprintf(NULL,
  17501. NULL, /* No truncation check for error buffers */
  17502. error->text,
  17503. error->text_buffer_size,
  17504. "Domain %s specified by %s is already in use",
  17505. new_dom->config[AUTHENTICATION_DOMAIN],
  17506. config_options[AUTHENTICATION_DOMAIN].name);
  17507. }
  17508. mg_free(new_dom);
  17509. mg_unlock_context(ctx);
  17510. return -5;
  17511. }
  17512. /* Count number of domains */
  17513. idx++;
  17514. if (dom->next == NULL) {
  17515. dom->next = new_dom;
  17516. break;
  17517. }
  17518. dom = dom->next;
  17519. }
  17520. mg_unlock_context(ctx);
  17521. /* Return domain number */
  17522. return idx;
  17523. }
  17524. int
  17525. mg_start_domain(struct mg_context *ctx, const char **options)
  17526. {
  17527. return mg_start_domain2(ctx, options, NULL);
  17528. }
  17529. #endif
  17530. /* Feature check API function */
  17531. unsigned
  17532. mg_check_feature(unsigned feature)
  17533. {
  17534. static const unsigned feature_set = 0
  17535. /* Set bits for available features according to API documentation.
  17536. * This bit mask is created at compile time, according to the active
  17537. * preprocessor defines. It is a single const value at runtime. */
  17538. #if !defined(NO_FILES)
  17539. | MG_FEATURES_FILES
  17540. #endif
  17541. #if !defined(NO_SSL)
  17542. | MG_FEATURES_SSL
  17543. #endif
  17544. #if !defined(NO_CGI)
  17545. | MG_FEATURES_CGI
  17546. #endif
  17547. #if defined(USE_IPV6)
  17548. | MG_FEATURES_IPV6
  17549. #endif
  17550. #if defined(USE_WEBSOCKET)
  17551. | MG_FEATURES_WEBSOCKET
  17552. #endif
  17553. #if defined(USE_LUA)
  17554. | MG_FEATURES_LUA
  17555. #endif
  17556. #if defined(USE_DUKTAPE)
  17557. | MG_FEATURES_SSJS
  17558. #endif
  17559. #if !defined(NO_CACHING)
  17560. | MG_FEATURES_CACHE
  17561. #endif
  17562. #if defined(USE_SERVER_STATS)
  17563. | MG_FEATURES_STATS
  17564. #endif
  17565. #if defined(USE_ZLIB)
  17566. | MG_FEATURES_COMPRESSION
  17567. #endif
  17568. /* Set some extra bits not defined in the API documentation.
  17569. * These bits may change without further notice. */
  17570. #if defined(MG_LEGACY_INTERFACE)
  17571. | 0x00008000u
  17572. #endif
  17573. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17574. | 0x00004000u
  17575. #endif
  17576. #if defined(MEMORY_DEBUGGING)
  17577. | 0x00001000u
  17578. #endif
  17579. #if defined(USE_TIMERS)
  17580. | 0x00020000u
  17581. #endif
  17582. #if !defined(NO_NONCE_CHECK)
  17583. | 0x00040000u
  17584. #endif
  17585. #if !defined(NO_POPEN)
  17586. | 0x00080000u
  17587. #endif
  17588. ;
  17589. return (feature & feature_set);
  17590. }
  17591. static size_t
  17592. mg_str_append(char **dst, char *end, const char *src)
  17593. {
  17594. size_t len = strlen(src);
  17595. if (*dst != end) {
  17596. /* Append src if enough space, or close dst. */
  17597. if ((size_t)(end - *dst) > len) {
  17598. strcpy(*dst, src);
  17599. *dst += len;
  17600. } else {
  17601. *dst = end;
  17602. }
  17603. }
  17604. return len;
  17605. }
  17606. /* Get system information. It can be printed or stored by the caller.
  17607. * Return the size of available information. */
  17608. int
  17609. mg_get_system_info(char *buffer, int buflen)
  17610. {
  17611. char *end, *append_eoobj = NULL, block[256];
  17612. size_t system_info_length = 0;
  17613. #if defined(_WIN32)
  17614. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17615. #else
  17616. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17617. #endif
  17618. if ((buffer == NULL) || (buflen < 1)) {
  17619. buflen = 0;
  17620. end = buffer;
  17621. } else {
  17622. *buffer = 0;
  17623. end = buffer + buflen;
  17624. }
  17625. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17626. /* has enough space to append eoobj */
  17627. append_eoobj = buffer;
  17628. if (end) {
  17629. end -= sizeof(eoobj) - 1;
  17630. }
  17631. }
  17632. system_info_length += mg_str_append(&buffer, end, "{");
  17633. /* Server version */
  17634. {
  17635. const char *version = mg_version();
  17636. mg_snprintf(NULL,
  17637. NULL,
  17638. block,
  17639. sizeof(block),
  17640. "%s\"version\" : \"%s\"",
  17641. eol,
  17642. version);
  17643. system_info_length += mg_str_append(&buffer, end, block);
  17644. }
  17645. /* System info */
  17646. {
  17647. #if defined(_WIN32)
  17648. DWORD dwVersion = 0;
  17649. DWORD dwMajorVersion = 0;
  17650. DWORD dwMinorVersion = 0;
  17651. SYSTEM_INFO si;
  17652. GetSystemInfo(&si);
  17653. #if defined(_MSC_VER)
  17654. #pragma warning(push)
  17655. /* GetVersion was declared deprecated */
  17656. #pragma warning(disable : 4996)
  17657. #endif
  17658. dwVersion = GetVersion();
  17659. #if defined(_MSC_VER)
  17660. #pragma warning(pop)
  17661. #endif
  17662. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17663. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17664. mg_snprintf(NULL,
  17665. NULL,
  17666. block,
  17667. sizeof(block),
  17668. ",%s\"os\" : \"Windows %u.%u\"",
  17669. eol,
  17670. (unsigned)dwMajorVersion,
  17671. (unsigned)dwMinorVersion);
  17672. system_info_length += mg_str_append(&buffer, end, block);
  17673. mg_snprintf(NULL,
  17674. NULL,
  17675. block,
  17676. sizeof(block),
  17677. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17678. eol,
  17679. (unsigned)si.wProcessorArchitecture,
  17680. (unsigned)si.dwNumberOfProcessors,
  17681. (unsigned)si.dwActiveProcessorMask);
  17682. system_info_length += mg_str_append(&buffer, end, block);
  17683. #elif defined(__ZEPHYR__)
  17684. mg_snprintf(NULL,
  17685. NULL,
  17686. block,
  17687. sizeof(block),
  17688. ",%s\"os\" : \"%s %s\"",
  17689. eol,
  17690. "Zephyr OS",
  17691. ZEPHYR_VERSION);
  17692. system_info_length += mg_str_append(&buffer, end, block);
  17693. #else
  17694. struct utsname name;
  17695. memset(&name, 0, sizeof(name));
  17696. uname(&name);
  17697. mg_snprintf(NULL,
  17698. NULL,
  17699. block,
  17700. sizeof(block),
  17701. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17702. eol,
  17703. name.sysname,
  17704. name.version,
  17705. name.release,
  17706. name.machine);
  17707. system_info_length += mg_str_append(&buffer, end, block);
  17708. #endif
  17709. }
  17710. /* Features */
  17711. {
  17712. mg_snprintf(NULL,
  17713. NULL,
  17714. block,
  17715. sizeof(block),
  17716. ",%s\"features\" : %lu"
  17717. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17718. eol,
  17719. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17720. eol,
  17721. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17722. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17723. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17724. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17725. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17726. : "",
  17727. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17728. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17729. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17730. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17731. system_info_length += mg_str_append(&buffer, end, block);
  17732. #if defined(USE_LUA)
  17733. mg_snprintf(NULL,
  17734. NULL,
  17735. block,
  17736. sizeof(block),
  17737. ",%s\"lua_version\" : \"%u (%s)\"",
  17738. eol,
  17739. (unsigned)LUA_VERSION_NUM,
  17740. LUA_RELEASE);
  17741. system_info_length += mg_str_append(&buffer, end, block);
  17742. #endif
  17743. #if defined(USE_DUKTAPE)
  17744. mg_snprintf(NULL,
  17745. NULL,
  17746. block,
  17747. sizeof(block),
  17748. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17749. eol,
  17750. (unsigned)DUK_VERSION / 10000,
  17751. ((unsigned)DUK_VERSION / 100) % 100,
  17752. (unsigned)DUK_VERSION % 100);
  17753. system_info_length += mg_str_append(&buffer, end, block);
  17754. #endif
  17755. }
  17756. /* Build date */
  17757. {
  17758. #if defined(GCC_DIAGNOSTIC)
  17759. #if GCC_VERSION >= 40900
  17760. #pragma GCC diagnostic push
  17761. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17762. #pragma GCC diagnostic ignored "-Wdate-time"
  17763. #endif
  17764. #endif
  17765. mg_snprintf(NULL,
  17766. NULL,
  17767. block,
  17768. sizeof(block),
  17769. ",%s\"build\" : \"%s\"",
  17770. eol,
  17771. __DATE__);
  17772. #if defined(GCC_DIAGNOSTIC)
  17773. #if GCC_VERSION >= 40900
  17774. #pragma GCC diagnostic pop
  17775. #endif
  17776. #endif
  17777. system_info_length += mg_str_append(&buffer, end, block);
  17778. }
  17779. /* Compiler information */
  17780. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17781. {
  17782. #if defined(_MSC_VER)
  17783. mg_snprintf(NULL,
  17784. NULL,
  17785. block,
  17786. sizeof(block),
  17787. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17788. eol,
  17789. (unsigned)_MSC_VER,
  17790. (unsigned)_MSC_FULL_VER);
  17791. system_info_length += mg_str_append(&buffer, end, block);
  17792. #elif defined(__MINGW64__)
  17793. mg_snprintf(NULL,
  17794. NULL,
  17795. block,
  17796. sizeof(block),
  17797. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17798. eol,
  17799. (unsigned)__MINGW64_VERSION_MAJOR,
  17800. (unsigned)__MINGW64_VERSION_MINOR);
  17801. system_info_length += mg_str_append(&buffer, end, block);
  17802. mg_snprintf(NULL,
  17803. NULL,
  17804. block,
  17805. sizeof(block),
  17806. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17807. eol,
  17808. (unsigned)__MINGW32_MAJOR_VERSION,
  17809. (unsigned)__MINGW32_MINOR_VERSION);
  17810. system_info_length += mg_str_append(&buffer, end, block);
  17811. #elif defined(__MINGW32__)
  17812. mg_snprintf(NULL,
  17813. NULL,
  17814. block,
  17815. sizeof(block),
  17816. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17817. eol,
  17818. (unsigned)__MINGW32_MAJOR_VERSION,
  17819. (unsigned)__MINGW32_MINOR_VERSION);
  17820. system_info_length += mg_str_append(&buffer, end, block);
  17821. #elif defined(__clang__)
  17822. mg_snprintf(NULL,
  17823. NULL,
  17824. block,
  17825. sizeof(block),
  17826. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17827. eol,
  17828. __clang_major__,
  17829. __clang_minor__,
  17830. __clang_patchlevel__,
  17831. __clang_version__);
  17832. system_info_length += mg_str_append(&buffer, end, block);
  17833. #elif defined(__GNUC__)
  17834. mg_snprintf(NULL,
  17835. NULL,
  17836. block,
  17837. sizeof(block),
  17838. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17839. eol,
  17840. (unsigned)__GNUC__,
  17841. (unsigned)__GNUC_MINOR__,
  17842. (unsigned)__GNUC_PATCHLEVEL__);
  17843. system_info_length += mg_str_append(&buffer, end, block);
  17844. #elif defined(__INTEL_COMPILER)
  17845. mg_snprintf(NULL,
  17846. NULL,
  17847. block,
  17848. sizeof(block),
  17849. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17850. eol,
  17851. (unsigned)__INTEL_COMPILER);
  17852. system_info_length += mg_str_append(&buffer, end, block);
  17853. #elif defined(__BORLANDC__)
  17854. mg_snprintf(NULL,
  17855. NULL,
  17856. block,
  17857. sizeof(block),
  17858. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17859. eol,
  17860. (unsigned)__BORLANDC__);
  17861. system_info_length += mg_str_append(&buffer, end, block);
  17862. #elif defined(__SUNPRO_C)
  17863. mg_snprintf(NULL,
  17864. NULL,
  17865. block,
  17866. sizeof(block),
  17867. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17868. eol,
  17869. (unsigned)__SUNPRO_C);
  17870. system_info_length += mg_str_append(&buffer, end, block);
  17871. #else
  17872. mg_snprintf(NULL,
  17873. NULL,
  17874. block,
  17875. sizeof(block),
  17876. ",%s\"compiler\" : \"other\"",
  17877. eol);
  17878. system_info_length += mg_str_append(&buffer, end, block);
  17879. #endif
  17880. }
  17881. /* Determine 32/64 bit data mode.
  17882. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17883. {
  17884. mg_snprintf(NULL,
  17885. NULL,
  17886. block,
  17887. sizeof(block),
  17888. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17889. "char:%u/%u, "
  17890. "ptr:%u, size:%u, time:%u\"",
  17891. eol,
  17892. (unsigned)sizeof(short),
  17893. (unsigned)sizeof(int),
  17894. (unsigned)sizeof(long),
  17895. (unsigned)sizeof(long long),
  17896. (unsigned)sizeof(float),
  17897. (unsigned)sizeof(double),
  17898. (unsigned)sizeof(long double),
  17899. (unsigned)sizeof(char),
  17900. (unsigned)sizeof(wchar_t),
  17901. (unsigned)sizeof(void *),
  17902. (unsigned)sizeof(size_t),
  17903. (unsigned)sizeof(time_t));
  17904. system_info_length += mg_str_append(&buffer, end, block);
  17905. }
  17906. /* Terminate string */
  17907. if (append_eoobj) {
  17908. strcat(append_eoobj, eoobj);
  17909. }
  17910. system_info_length += sizeof(eoobj) - 1;
  17911. return (int)system_info_length;
  17912. }
  17913. /* Get context information. It can be printed or stored by the caller.
  17914. * Return the size of available information. */
  17915. int
  17916. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17917. {
  17918. #if defined(USE_SERVER_STATS)
  17919. char *end, *append_eoobj = NULL, block[256];
  17920. size_t context_info_length = 0;
  17921. #if defined(_WIN32)
  17922. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17923. #else
  17924. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17925. #endif
  17926. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17927. if ((buffer == NULL) || (buflen < 1)) {
  17928. buflen = 0;
  17929. end = buffer;
  17930. } else {
  17931. *buffer = 0;
  17932. end = buffer + buflen;
  17933. }
  17934. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17935. /* has enough space to append eoobj */
  17936. append_eoobj = buffer;
  17937. end -= sizeof(eoobj) - 1;
  17938. }
  17939. context_info_length += mg_str_append(&buffer, end, "{");
  17940. if (ms) { /* <-- should be always true */
  17941. /* Memory information */
  17942. int blockCount = (int)ms->blockCount;
  17943. int64_t totalMemUsed = ms->totalMemUsed;
  17944. int64_t maxMemUsed = ms->maxMemUsed;
  17945. if (totalMemUsed > maxMemUsed) {
  17946. maxMemUsed = totalMemUsed;
  17947. }
  17948. mg_snprintf(NULL,
  17949. NULL,
  17950. block,
  17951. sizeof(block),
  17952. "%s\"memory\" : {%s"
  17953. "\"blocks\" : %i,%s"
  17954. "\"used\" : %" INT64_FMT ",%s"
  17955. "\"maxUsed\" : %" INT64_FMT "%s"
  17956. "}",
  17957. eol,
  17958. eol,
  17959. blockCount,
  17960. eol,
  17961. totalMemUsed,
  17962. eol,
  17963. maxMemUsed,
  17964. eol);
  17965. context_info_length += mg_str_append(&buffer, end, block);
  17966. }
  17967. if (ctx) {
  17968. /* Declare all variables at begin of the block, to comply
  17969. * with old C standards. */
  17970. char start_time_str[64] = {0};
  17971. char now_str[64] = {0};
  17972. time_t start_time = ctx->start_time;
  17973. time_t now = time(NULL);
  17974. int64_t total_data_read, total_data_written;
  17975. int active_connections = (int)ctx->active_connections;
  17976. int max_active_connections = (int)ctx->max_active_connections;
  17977. int total_connections = (int)ctx->total_connections;
  17978. if (active_connections > max_active_connections) {
  17979. max_active_connections = active_connections;
  17980. }
  17981. if (active_connections > total_connections) {
  17982. total_connections = active_connections;
  17983. }
  17984. /* Connections information */
  17985. mg_snprintf(NULL,
  17986. NULL,
  17987. block,
  17988. sizeof(block),
  17989. ",%s\"connections\" : {%s"
  17990. "\"active\" : %i,%s"
  17991. "\"maxActive\" : %i,%s"
  17992. "\"total\" : %i%s"
  17993. "}",
  17994. eol,
  17995. eol,
  17996. active_connections,
  17997. eol,
  17998. max_active_connections,
  17999. eol,
  18000. total_connections,
  18001. eol);
  18002. context_info_length += mg_str_append(&buffer, end, block);
  18003. /* Queue information */
  18004. #if !defined(ALTERNATIVE_QUEUE)
  18005. mg_snprintf(NULL,
  18006. NULL,
  18007. block,
  18008. sizeof(block),
  18009. ",%s\"queue\" : {%s"
  18010. "\"length\" : %i,%s"
  18011. "\"filled\" : %i,%s"
  18012. "\"maxFilled\" : %i,%s"
  18013. "\"full\" : %s%s"
  18014. "}",
  18015. eol,
  18016. eol,
  18017. ctx->sq_size,
  18018. eol,
  18019. ctx->sq_head - ctx->sq_tail,
  18020. eol,
  18021. ctx->sq_max_fill,
  18022. eol,
  18023. (ctx->sq_blocked ? "true" : "false"),
  18024. eol);
  18025. context_info_length += mg_str_append(&buffer, end, block);
  18026. #endif
  18027. /* Requests information */
  18028. mg_snprintf(NULL,
  18029. NULL,
  18030. block,
  18031. sizeof(block),
  18032. ",%s\"requests\" : {%s"
  18033. "\"total\" : %i%s"
  18034. "}",
  18035. eol,
  18036. eol,
  18037. ctx->total_requests,
  18038. eol);
  18039. context_info_length += mg_str_append(&buffer, end, block);
  18040. /* Data information */
  18041. total_data_read =
  18042. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18043. total_data_written =
  18044. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18045. mg_snprintf(NULL,
  18046. NULL,
  18047. block,
  18048. sizeof(block),
  18049. ",%s\"data\" : {%s"
  18050. "\"read\" : %" INT64_FMT ",%s"
  18051. "\"written\" : %" INT64_FMT "%s"
  18052. "}",
  18053. eol,
  18054. eol,
  18055. total_data_read,
  18056. eol,
  18057. total_data_written,
  18058. eol);
  18059. context_info_length += mg_str_append(&buffer, end, block);
  18060. /* Execution time information */
  18061. gmt_time_string(start_time_str,
  18062. sizeof(start_time_str) - 1,
  18063. &start_time);
  18064. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18065. mg_snprintf(NULL,
  18066. NULL,
  18067. block,
  18068. sizeof(block),
  18069. ",%s\"time\" : {%s"
  18070. "\"uptime\" : %.0f,%s"
  18071. "\"start\" : \"%s\",%s"
  18072. "\"now\" : \"%s\"%s"
  18073. "}",
  18074. eol,
  18075. eol,
  18076. difftime(now, start_time),
  18077. eol,
  18078. start_time_str,
  18079. eol,
  18080. now_str,
  18081. eol);
  18082. context_info_length += mg_str_append(&buffer, end, block);
  18083. }
  18084. /* Terminate string */
  18085. if (append_eoobj) {
  18086. strcat(append_eoobj, eoobj);
  18087. }
  18088. context_info_length += sizeof(eoobj) - 1;
  18089. return (int)context_info_length;
  18090. #else
  18091. (void)ctx;
  18092. if ((buffer != NULL) && (buflen > 0)) {
  18093. *buffer = 0;
  18094. }
  18095. return 0;
  18096. #endif
  18097. }
  18098. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18099. /* Get connection information. It can be printed or stored by the caller.
  18100. * Return the size of available information. */
  18101. int
  18102. mg_get_connection_info(const struct mg_context *ctx,
  18103. int idx,
  18104. char *buffer,
  18105. int buflen)
  18106. {
  18107. const struct mg_connection *conn;
  18108. const struct mg_request_info *ri;
  18109. char *end, *append_eoobj = NULL, block[256];
  18110. size_t connection_info_length = 0;
  18111. int state = 0;
  18112. const char *state_str = "unknown";
  18113. #if defined(_WIN32)
  18114. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18115. #else
  18116. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18117. #endif
  18118. if ((buffer == NULL) || (buflen < 1)) {
  18119. buflen = 0;
  18120. end = buffer;
  18121. } else {
  18122. *buffer = 0;
  18123. end = buffer + buflen;
  18124. }
  18125. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18126. /* has enough space to append eoobj */
  18127. append_eoobj = buffer;
  18128. end -= sizeof(eoobj) - 1;
  18129. }
  18130. if ((ctx == NULL) || (idx < 0)) {
  18131. /* Parameter error */
  18132. return 0;
  18133. }
  18134. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18135. /* Out of range */
  18136. return 0;
  18137. }
  18138. /* Take connection [idx]. This connection is not locked in
  18139. * any way, so some other thread might use it. */
  18140. conn = (ctx->worker_connections) + idx;
  18141. /* Initialize output string */
  18142. connection_info_length += mg_str_append(&buffer, end, "{");
  18143. /* Init variables */
  18144. ri = &(conn->request_info);
  18145. #if defined(USE_SERVER_STATS)
  18146. state = conn->conn_state;
  18147. /* State as string */
  18148. switch (state) {
  18149. case 0:
  18150. state_str = "undefined";
  18151. break;
  18152. case 1:
  18153. state_str = "not used";
  18154. break;
  18155. case 2:
  18156. state_str = "init";
  18157. break;
  18158. case 3:
  18159. state_str = "ready";
  18160. break;
  18161. case 4:
  18162. state_str = "processing";
  18163. break;
  18164. case 5:
  18165. state_str = "processed";
  18166. break;
  18167. case 6:
  18168. state_str = "to close";
  18169. break;
  18170. case 7:
  18171. state_str = "closing";
  18172. break;
  18173. case 8:
  18174. state_str = "closed";
  18175. break;
  18176. case 9:
  18177. state_str = "done";
  18178. break;
  18179. }
  18180. #endif
  18181. /* Connection info */
  18182. if ((state >= 3) && (state < 9)) {
  18183. mg_snprintf(NULL,
  18184. NULL,
  18185. block,
  18186. sizeof(block),
  18187. "%s\"connection\" : {%s"
  18188. "\"remote\" : {%s"
  18189. "\"protocol\" : \"%s\",%s"
  18190. "\"addr\" : \"%s\",%s"
  18191. "\"port\" : %u%s"
  18192. "},%s"
  18193. "\"handled_requests\" : %u%s"
  18194. "}",
  18195. eol,
  18196. eol,
  18197. eol,
  18198. get_proto_name(conn),
  18199. eol,
  18200. ri->remote_addr,
  18201. eol,
  18202. ri->remote_port,
  18203. eol,
  18204. eol,
  18205. conn->handled_requests,
  18206. eol);
  18207. connection_info_length += mg_str_append(&buffer, end, block);
  18208. }
  18209. /* Request info */
  18210. if ((state >= 4) && (state < 6)) {
  18211. mg_snprintf(NULL,
  18212. NULL,
  18213. block,
  18214. sizeof(block),
  18215. "%s%s\"request_info\" : {%s"
  18216. "\"method\" : \"%s\",%s"
  18217. "\"uri\" : \"%s\",%s"
  18218. "\"query\" : %s%s%s%s"
  18219. "}",
  18220. (connection_info_length > 1 ? "," : ""),
  18221. eol,
  18222. eol,
  18223. ri->request_method,
  18224. eol,
  18225. ri->request_uri,
  18226. eol,
  18227. ri->query_string ? "\"" : "",
  18228. ri->query_string ? ri->query_string : "null",
  18229. ri->query_string ? "\"" : "",
  18230. eol);
  18231. connection_info_length += mg_str_append(&buffer, end, block);
  18232. }
  18233. /* Execution time information */
  18234. if ((state >= 2) && (state < 9)) {
  18235. char start_time_str[64] = {0};
  18236. char close_time_str[64] = {0};
  18237. time_t start_time = conn->conn_birth_time;
  18238. time_t close_time = conn->conn_close_time;
  18239. double time_diff;
  18240. gmt_time_string(start_time_str,
  18241. sizeof(start_time_str) - 1,
  18242. &start_time);
  18243. if (close_time != 0) {
  18244. time_diff = difftime(close_time, start_time);
  18245. gmt_time_string(close_time_str,
  18246. sizeof(close_time_str) - 1,
  18247. &close_time);
  18248. } else {
  18249. time_t now = time(NULL);
  18250. time_diff = difftime(now, start_time);
  18251. close_time_str[0] = 0; /* or use "now" ? */
  18252. }
  18253. mg_snprintf(NULL,
  18254. NULL,
  18255. block,
  18256. sizeof(block),
  18257. "%s%s\"time\" : {%s"
  18258. "\"uptime\" : %.0f,%s"
  18259. "\"start\" : \"%s\",%s"
  18260. "\"closed\" : \"%s\"%s"
  18261. "}",
  18262. (connection_info_length > 1 ? "," : ""),
  18263. eol,
  18264. eol,
  18265. time_diff,
  18266. eol,
  18267. start_time_str,
  18268. eol,
  18269. close_time_str,
  18270. eol);
  18271. connection_info_length += mg_str_append(&buffer, end, block);
  18272. }
  18273. /* Remote user name */
  18274. if ((ri->remote_user) && (state < 9)) {
  18275. mg_snprintf(NULL,
  18276. NULL,
  18277. block,
  18278. sizeof(block),
  18279. "%s%s\"user\" : {%s"
  18280. "\"name\" : \"%s\",%s"
  18281. "}",
  18282. (connection_info_length > 1 ? "," : ""),
  18283. eol,
  18284. eol,
  18285. ri->remote_user,
  18286. eol);
  18287. connection_info_length += mg_str_append(&buffer, end, block);
  18288. }
  18289. /* Data block */
  18290. if (state >= 3) {
  18291. mg_snprintf(NULL,
  18292. NULL,
  18293. block,
  18294. sizeof(block),
  18295. "%s%s\"data\" : {%s"
  18296. "\"read\" : %" INT64_FMT ",%s"
  18297. "\"written\" : %" INT64_FMT "%s"
  18298. "}",
  18299. (connection_info_length > 1 ? "," : ""),
  18300. eol,
  18301. eol,
  18302. conn->consumed_content,
  18303. eol,
  18304. conn->num_bytes_sent,
  18305. eol);
  18306. connection_info_length += mg_str_append(&buffer, end, block);
  18307. }
  18308. /* State */
  18309. mg_snprintf(NULL,
  18310. NULL,
  18311. block,
  18312. sizeof(block),
  18313. "%s%s\"state\" : \"%s\"",
  18314. (connection_info_length > 1 ? "," : ""),
  18315. eol,
  18316. state_str);
  18317. connection_info_length += mg_str_append(&buffer, end, block);
  18318. /* Terminate string */
  18319. if (append_eoobj) {
  18320. strcat(append_eoobj, eoobj);
  18321. }
  18322. connection_info_length += sizeof(eoobj) - 1;
  18323. return (int)connection_info_length;
  18324. }
  18325. #endif
  18326. /* Initialize this library. This function does not need to be thread safe.
  18327. */
  18328. unsigned
  18329. mg_init_library(unsigned features)
  18330. {
  18331. #if !defined(NO_SSL)
  18332. char ebuf[128];
  18333. #endif
  18334. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18335. unsigned features_inited = features_to_init;
  18336. if (mg_init_library_called <= 0) {
  18337. /* Not initialized yet */
  18338. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18339. return 0;
  18340. }
  18341. }
  18342. mg_global_lock();
  18343. if (mg_init_library_called <= 0) {
  18344. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  18345. /* Fatal error - abort start. However, this situation should
  18346. * never occur in practice. */
  18347. mg_global_unlock();
  18348. return 0;
  18349. }
  18350. #if defined(_WIN32)
  18351. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18352. #else
  18353. pthread_mutexattr_init(&pthread_mutex_attr);
  18354. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  18355. #endif
  18356. #if defined(USE_LUA)
  18357. lua_init_optional_libraries();
  18358. #endif
  18359. }
  18360. mg_global_unlock();
  18361. #if !defined(NO_SSL)
  18362. if (features_to_init & MG_FEATURES_SSL) {
  18363. if (!mg_ssl_initialized) {
  18364. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18365. mg_ssl_initialized = 1;
  18366. } else {
  18367. (void)ebuf;
  18368. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18369. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18370. }
  18371. } else {
  18372. /* ssl already initialized */
  18373. }
  18374. }
  18375. #endif
  18376. /* Start WinSock for Windows */
  18377. mg_global_lock();
  18378. if (mg_init_library_called <= 0) {
  18379. #if defined(_WIN32)
  18380. WSADATA data;
  18381. WSAStartup(MAKEWORD(2, 2), &data);
  18382. #endif /* _WIN32 */
  18383. mg_init_library_called = 1;
  18384. } else {
  18385. mg_init_library_called++;
  18386. }
  18387. mg_global_unlock();
  18388. return features_inited;
  18389. }
  18390. /* Un-initialize this library. */
  18391. unsigned
  18392. mg_exit_library(void)
  18393. {
  18394. if (mg_init_library_called <= 0) {
  18395. return 0;
  18396. }
  18397. mg_global_lock();
  18398. mg_init_library_called--;
  18399. if (mg_init_library_called == 0) {
  18400. #if defined(_WIN32)
  18401. (void)WSACleanup();
  18402. #endif /* _WIN32 */
  18403. #if !defined(NO_SSL)
  18404. if (mg_ssl_initialized) {
  18405. uninitialize_ssl();
  18406. mg_ssl_initialized = 0;
  18407. }
  18408. #endif
  18409. #if defined(_WIN32)
  18410. (void)pthread_mutex_destroy(&global_log_file_lock);
  18411. #else
  18412. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18413. #endif
  18414. (void)pthread_key_delete(sTlsKey);
  18415. #if defined(USE_LUA)
  18416. lua_exit_optional_libraries();
  18417. #endif
  18418. mg_global_unlock();
  18419. (void)pthread_mutex_destroy(&global_lock_mutex);
  18420. return 1;
  18421. }
  18422. mg_global_unlock();
  18423. return 1;
  18424. }
  18425. /* End of civetweb.c */