civetweb.c 527 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845
  1. /* Copyright (c) 2013-2018 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(_LARGEFILE_SOURCE)
  59. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  60. #endif
  61. #if !defined(_FILE_OFFSET_BITS)
  62. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  63. #endif
  64. #if !defined(__STDC_FORMAT_MACROS)
  65. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  66. #endif
  67. #if !defined(__STDC_LIMIT_MACROS)
  68. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  69. #endif
  70. #if !defined(_DARWIN_UNLIMITED_SELECT)
  71. #define _DARWIN_UNLIMITED_SELECT
  72. #endif
  73. #if defined(__sun)
  74. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  75. #define __inline inline /* not recognized on older compiler versions */
  76. #endif
  77. #endif
  78. #if defined(__clang__)
  79. /* Enable reserved-id-macro warning again. */
  80. #pragma GCC diagnostic pop
  81. #endif
  82. #if defined(USE_LUA)
  83. #define USE_TIMERS
  84. #endif
  85. #if defined(_MSC_VER)
  86. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  87. #pragma warning(disable : 4306)
  88. /* conditional expression is constant: introduced by FD_SET(..) */
  89. #pragma warning(disable : 4127)
  90. /* non-constant aggregate initializer: issued due to missing C99 support */
  91. #pragma warning(disable : 4204)
  92. /* padding added after data member */
  93. #pragma warning(disable : 4820)
  94. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  95. #pragma warning(disable : 4668)
  96. /* no function prototype given: converting '()' to '(void)' */
  97. #pragma warning(disable : 4255)
  98. /* function has been selected for automatic inline expansion */
  99. #pragma warning(disable : 4711)
  100. #endif
  101. /* This code uses static_assert to check some conditions.
  102. * Unfortunately some compilers still do not support it, so we have a
  103. * replacement function here. */
  104. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  105. #define mg_static_assert _Static_assert
  106. #elif defined(__cplusplus) && __cplusplus >= 201103L
  107. #define mg_static_assert static_assert
  108. #else
  109. char static_assert_replacement[1];
  110. #define mg_static_assert(cond, txt) \
  111. extern char static_assert_replacement[(cond) ? 1 : -1]
  112. #endif
  113. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  114. "int data type size check");
  115. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  116. "pointer data type size check");
  117. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  118. /* Alternative queue is well tested and should be the new default */
  119. #if defined(NO_ALTERNATIVE_QUEUE)
  120. #if defined(ALTERNATIVE_QUEUE)
  121. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  122. #endif
  123. #else
  124. #define ALTERNATIVE_QUEUE
  125. #endif
  126. /* DTL -- including winsock2.h works better if lean and mean */
  127. #if !defined(WIN32_LEAN_AND_MEAN)
  128. #define WIN32_LEAN_AND_MEAN
  129. #endif
  130. #if defined(__SYMBIAN32__)
  131. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  132. * Symbian is no longer maintained since 2014-01-01.
  133. * Recent versions of CivetWeb are no longer tested for Symbian.
  134. * It makes no sense, to support an abandoned operating system.
  135. */
  136. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  137. #define NO_SSL /* SSL is not supported */
  138. #define NO_CGI /* CGI is not supported */
  139. #define PATH_MAX FILENAME_MAX
  140. #endif /* __SYMBIAN32__ */
  141. #if !defined(CIVETWEB_HEADER_INCLUDED)
  142. /* Include the header file here, so the CivetWeb interface is defined for the
  143. * entire implementation, including the following forward definitions. */
  144. #include "civetweb.h"
  145. #endif
  146. #if !defined(DEBUG_TRACE)
  147. #if defined(DEBUG)
  148. static void DEBUG_TRACE_FUNC(const char *func,
  149. unsigned line,
  150. PRINTF_FORMAT_STRING(const char *fmt),
  151. ...) PRINTF_ARGS(3, 4);
  152. #define DEBUG_TRACE(fmt, ...) \
  153. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  154. #define NEED_DEBUG_TRACE_FUNC
  155. #else
  156. #define DEBUG_TRACE(fmt, ...) \
  157. do { \
  158. } while (0)
  159. #endif /* DEBUG */
  160. #endif /* DEBUG_TRACE */
  161. #if !defined(DEBUG_ASSERT)
  162. #if defined(DEBUG)
  163. #define DEBUG_ASSERT(cond) \
  164. do { \
  165. if (!(cond)) { \
  166. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  167. exit(2); /* Exit with error */ \
  168. } \
  169. } while (0)
  170. #else
  171. #define DEBUG_ASSERT(cond)
  172. #endif /* DEBUG */
  173. #endif
  174. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  175. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  176. __attribute__((no_instrument_function));
  177. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  178. __attribute__((no_instrument_function));
  179. void
  180. __cyg_profile_func_enter(void *this_fn, void *call_site)
  181. {
  182. if ((void *)this_fn != (void *)printf) {
  183. printf("E %p %p\n", this_fn, call_site);
  184. }
  185. }
  186. void
  187. __cyg_profile_func_exit(void *this_fn, void *call_site)
  188. {
  189. if ((void *)this_fn != (void *)printf) {
  190. printf("X %p %p\n", this_fn, call_site);
  191. }
  192. }
  193. #endif
  194. #if !defined(IGNORE_UNUSED_RESULT)
  195. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  196. #endif
  197. #if defined(__GNUC__) || defined(__MINGW32__)
  198. /* GCC unused function attribute seems fundamentally broken.
  199. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  200. * OR UNUSED" for individual functions failed.
  201. * Either the compiler creates an "unused-function" warning if a
  202. * function is not marked with __attribute__((unused)).
  203. * On the other hand, if the function is marked with this attribute,
  204. * but is used, the compiler raises a completely idiotic
  205. * "used-but-marked-unused" warning - and
  206. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  207. * raises error: unknown option after "#pragma GCC diagnostic".
  208. * Disable this warning completely, until the GCC guys sober up
  209. * again.
  210. */
  211. #pragma GCC diagnostic ignored "-Wunused-function"
  212. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  213. #else
  214. #define FUNCTION_MAY_BE_UNUSED
  215. #endif
  216. /* Some ANSI #includes are not available on Windows CE */
  217. #if !defined(_WIN32_WCE)
  218. #include <errno.h>
  219. #include <fcntl.h>
  220. #include <signal.h>
  221. #include <sys/stat.h>
  222. #include <sys/types.h>
  223. #endif /* !_WIN32_WCE */
  224. #if defined(__clang__)
  225. /* When using -Weverything, clang does not accept it's own headers
  226. * in a release build configuration. Disable what is too much in
  227. * -Weverything. */
  228. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  229. #endif
  230. #if defined(__GNUC__) || defined(__MINGW32__)
  231. /* Who on earth came to the conclusion, using __DATE__ should rise
  232. * an "expansion of date or time macro is not reproducible"
  233. * warning. That's exactly what was intended by using this macro.
  234. * Just disable this nonsense warning. */
  235. /* And disabling them does not work either:
  236. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  237. * #pragma clang diagnostic ignored "-Wdate-time"
  238. * So we just have to disable ALL warnings for some lines
  239. * of code.
  240. * This seems to be a known GCC bug, not resolved since 2012:
  241. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  242. */
  243. #endif
  244. #if defined(__MACH__) /* Apple OSX section */
  245. #if defined(__clang__)
  246. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  247. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  248. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  249. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  250. #endif
  251. #endif
  252. #define CLOCK_MONOTONIC (1)
  253. #define CLOCK_REALTIME (2)
  254. #include <mach/clock.h>
  255. #include <mach/mach.h>
  256. #include <mach/mach_time.h>
  257. #include <sys/errno.h>
  258. #include <sys/time.h>
  259. /* clock_gettime is not implemented on OSX prior to 10.12 */
  260. static int
  261. _civet_clock_gettime(int clk_id, struct timespec *t)
  262. {
  263. memset(t, 0, sizeof(*t));
  264. if (clk_id == CLOCK_REALTIME) {
  265. struct timeval now;
  266. int rv = gettimeofday(&now, NULL);
  267. if (rv) {
  268. return rv;
  269. }
  270. t->tv_sec = now.tv_sec;
  271. t->tv_nsec = now.tv_usec * 1000;
  272. return 0;
  273. } else if (clk_id == CLOCK_MONOTONIC) {
  274. static uint64_t clock_start_time = 0;
  275. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  276. uint64_t now = mach_absolute_time();
  277. if (clock_start_time == 0) {
  278. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  279. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  280. /* appease "unused variable" warning for release builds */
  281. (void)mach_status;
  282. clock_start_time = now;
  283. }
  284. now = (uint64_t)((double)(now - clock_start_time)
  285. * (double)timebase_ifo.numer
  286. / (double)timebase_ifo.denom);
  287. t->tv_sec = now / 1000000000;
  288. t->tv_nsec = now % 1000000000;
  289. return 0;
  290. }
  291. return -1; /* EINVAL - Clock ID is unknown */
  292. }
  293. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  294. #if defined(__CLOCK_AVAILABILITY)
  295. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  296. * declared but it may be NULL at runtime. So we need to check before using
  297. * it. */
  298. static int
  299. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  300. {
  301. if (clock_gettime) {
  302. return clock_gettime(clk_id, t);
  303. }
  304. return _civet_clock_gettime(clk_id, t);
  305. }
  306. #define clock_gettime _civet_safe_clock_gettime
  307. #else
  308. #define clock_gettime _civet_clock_gettime
  309. #endif
  310. #endif
  311. #include <ctype.h>
  312. #include <limits.h>
  313. #include <stdarg.h>
  314. #include <stddef.h>
  315. #include <stdint.h>
  316. #include <stdio.h>
  317. #include <stdlib.h>
  318. #include <string.h>
  319. #include <time.h>
  320. /********************************************************************/
  321. /* CivetWeb configuration defines */
  322. /********************************************************************/
  323. /* Maximum number of threads that can be configured.
  324. * The number of threads actually created depends on the "num_threads"
  325. * configuration parameter, but this is the upper limit. */
  326. #if !defined(MAX_WORKER_THREADS)
  327. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  328. #endif
  329. /* Timeout interval for select/poll calls.
  330. * The timeouts depend on "*_timeout_ms" configuration values, but long
  331. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  332. * This reduces the time required to stop the server. */
  333. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  334. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  335. #endif
  336. /* Do not try to compress files smaller than this limit. */
  337. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  338. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  339. #endif
  340. #if !defined(PASSWORDS_FILE_NAME)
  341. #define PASSWORDS_FILE_NAME ".htpasswd"
  342. #endif
  343. /* Initial buffer size for all CGI environment variables. In case there is
  344. * not enough space, another block is allocated. */
  345. #if !defined(CGI_ENVIRONMENT_SIZE)
  346. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  347. #endif
  348. /* Maximum number of environment variables. */
  349. #if !defined(MAX_CGI_ENVIR_VARS)
  350. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  351. #endif
  352. /* General purpose buffer size. */
  353. #if !defined(MG_BUF_LEN) /* in bytes */
  354. #define MG_BUF_LEN (1024 * 8)
  355. #endif
  356. /* Size of the accepted socket queue (in case the old queue implementation
  357. * is used). */
  358. #if !defined(MGSQLEN)
  359. #define MGSQLEN (20) /* count */
  360. #endif
  361. /********************************************************************/
  362. /* Helper makros */
  363. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  364. /* Standard defines */
  365. #if !defined(INT64_MAX)
  366. #define INT64_MAX (9223372036854775807)
  367. #endif
  368. #define SHUTDOWN_RD (0)
  369. #define SHUTDOWN_WR (1)
  370. #define SHUTDOWN_BOTH (2)
  371. mg_static_assert(MAX_WORKER_THREADS >= 1,
  372. "worker threads must be a positive number");
  373. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  374. "size_t data type size check");
  375. #if defined(_WIN32) /* WINDOWS include block */
  376. #include <windows.h>
  377. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  378. #include <ws2tcpip.h>
  379. typedef const char *SOCK_OPT_TYPE;
  380. #if !defined(PATH_MAX)
  381. #define W_PATH_MAX (MAX_PATH)
  382. /* at most three UTF-8 chars per wchar_t */
  383. #define PATH_MAX (W_PATH_MAX * 3)
  384. #else
  385. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  386. #endif
  387. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  388. #if !defined(_IN_PORT_T)
  389. #if !defined(in_port_t)
  390. #define in_port_t u_short
  391. #endif
  392. #endif
  393. #if !defined(_WIN32_WCE)
  394. #include <direct.h>
  395. #include <io.h>
  396. #include <process.h>
  397. #else /* _WIN32_WCE */
  398. #define NO_CGI /* WinCE has no pipes */
  399. #define NO_POPEN /* WinCE has no popen */
  400. typedef long off_t;
  401. #define errno ((int)(GetLastError()))
  402. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  403. #endif /* _WIN32_WCE */
  404. #define MAKEUQUAD(lo, hi) \
  405. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  406. #define RATE_DIFF (10000000) /* 100 nsecs */
  407. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  408. #define SYS2UNIX_TIME(lo, hi) \
  409. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  410. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  411. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  412. * Also use _strtoui64 on modern M$ compilers */
  413. #if defined(_MSC_VER)
  414. #if (_MSC_VER < 1300)
  415. #define STRX(x) #x
  416. #define STR(x) STRX(x)
  417. #define __func__ __FILE__ ":" STR(__LINE__)
  418. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  419. #define strtoll(x, y, z) (_atoi64(x))
  420. #else
  421. #define __func__ __FUNCTION__
  422. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  423. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  424. #endif
  425. #endif /* _MSC_VER */
  426. #define ERRNO ((int)(GetLastError()))
  427. #define NO_SOCKLEN_T
  428. #if defined(_WIN64) || defined(__MINGW64__)
  429. #if !defined(SSL_LIB)
  430. #define SSL_LIB "ssleay64.dll"
  431. #endif
  432. #if !defined(CRYPTO_LIB)
  433. #define CRYPTO_LIB "libeay64.dll"
  434. #endif
  435. #else
  436. #if !defined(SSL_LIB)
  437. #define SSL_LIB "ssleay32.dll"
  438. #endif
  439. #if !defined(CRYPTO_LIB)
  440. #define CRYPTO_LIB "libeay32.dll"
  441. #endif
  442. #endif
  443. #define O_NONBLOCK (0)
  444. #if !defined(W_OK)
  445. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  446. #endif
  447. #if !defined(EWOULDBLOCK)
  448. #define EWOULDBLOCK WSAEWOULDBLOCK
  449. #endif /* !EWOULDBLOCK */
  450. #define _POSIX_
  451. #define INT64_FMT "I64d"
  452. #define UINT64_FMT "I64u"
  453. #define WINCDECL __cdecl
  454. #define vsnprintf_impl _vsnprintf
  455. #define access _access
  456. #define mg_sleep(x) (Sleep(x))
  457. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  458. #if !defined(popen)
  459. #define popen(x, y) (_popen(x, y))
  460. #endif
  461. #if !defined(pclose)
  462. #define pclose(x) (_pclose(x))
  463. #endif
  464. #define close(x) (_close(x))
  465. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  466. #define RTLD_LAZY (0)
  467. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  468. #define fdopen(x, y) (_fdopen((x), (y)))
  469. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  470. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  471. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  472. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  473. #define sleep(x) (Sleep((x)*1000))
  474. #define rmdir(x) (_rmdir(x))
  475. #if defined(_WIN64) || !defined(__MINGW32__)
  476. /* Only MinGW 32 bit is missing this function */
  477. #define timegm(x) (_mkgmtime(x))
  478. #else
  479. time_t timegm(struct tm *tm);
  480. #define NEED_TIMEGM
  481. #endif
  482. #if !defined(fileno)
  483. #define fileno(x) (_fileno(x))
  484. #endif /* !fileno MINGW #defines fileno */
  485. typedef HANDLE pthread_mutex_t;
  486. typedef DWORD pthread_key_t;
  487. typedef HANDLE pthread_t;
  488. typedef struct {
  489. CRITICAL_SECTION threadIdSec;
  490. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  491. } pthread_cond_t;
  492. #if !defined(__clockid_t_defined)
  493. typedef DWORD clockid_t;
  494. #endif
  495. #if !defined(CLOCK_MONOTONIC)
  496. #define CLOCK_MONOTONIC (1)
  497. #endif
  498. #if !defined(CLOCK_REALTIME)
  499. #define CLOCK_REALTIME (2)
  500. #endif
  501. #if !defined(CLOCK_THREAD)
  502. #define CLOCK_THREAD (3)
  503. #endif
  504. #if !defined(CLOCK_PROCESS)
  505. #define CLOCK_PROCESS (4)
  506. #endif
  507. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  508. #define _TIMESPEC_DEFINED
  509. #endif
  510. #if !defined(_TIMESPEC_DEFINED)
  511. struct timespec {
  512. time_t tv_sec; /* seconds */
  513. long tv_nsec; /* nanoseconds */
  514. };
  515. #endif
  516. #if !defined(WIN_PTHREADS_TIME_H)
  517. #define MUST_IMPLEMENT_CLOCK_GETTIME
  518. #endif
  519. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  520. #define clock_gettime mg_clock_gettime
  521. static int
  522. clock_gettime(clockid_t clk_id, struct timespec *tp)
  523. {
  524. FILETIME ft;
  525. ULARGE_INTEGER li, li2;
  526. BOOL ok = FALSE;
  527. double d;
  528. static double perfcnt_per_sec = 0.0;
  529. static BOOL initialized = FALSE;
  530. if (!initialized) {
  531. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  532. perfcnt_per_sec = 1.0 / li.QuadPart;
  533. initialized = TRUE;
  534. }
  535. if (tp) {
  536. memset(tp, 0, sizeof(*tp));
  537. if (clk_id == CLOCK_REALTIME) {
  538. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  539. GetSystemTimeAsFileTime(&ft);
  540. li.LowPart = ft.dwLowDateTime;
  541. li.HighPart = ft.dwHighDateTime;
  542. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  543. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  544. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  545. ok = TRUE;
  546. /* END: CLOCK_REALTIME */
  547. } else if (clk_id == CLOCK_MONOTONIC) {
  548. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  549. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  550. d = li.QuadPart * perfcnt_per_sec;
  551. tp->tv_sec = (time_t)d;
  552. d -= (double)tp->tv_sec;
  553. tp->tv_nsec = (long)(d * 1.0E9);
  554. ok = TRUE;
  555. /* END: CLOCK_MONOTONIC */
  556. } else if (clk_id == CLOCK_THREAD) {
  557. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  558. FILETIME t_create, t_exit, t_kernel, t_user;
  559. if (GetThreadTimes(GetCurrentThread(),
  560. &t_create,
  561. &t_exit,
  562. &t_kernel,
  563. &t_user)) {
  564. li.LowPart = t_user.dwLowDateTime;
  565. li.HighPart = t_user.dwHighDateTime;
  566. li2.LowPart = t_kernel.dwLowDateTime;
  567. li2.HighPart = t_kernel.dwHighDateTime;
  568. li.QuadPart += li2.QuadPart;
  569. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  570. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  571. ok = TRUE;
  572. }
  573. /* END: CLOCK_THREAD */
  574. } else if (clk_id == CLOCK_PROCESS) {
  575. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  576. FILETIME t_create, t_exit, t_kernel, t_user;
  577. if (GetProcessTimes(GetCurrentProcess(),
  578. &t_create,
  579. &t_exit,
  580. &t_kernel,
  581. &t_user)) {
  582. li.LowPart = t_user.dwLowDateTime;
  583. li.HighPart = t_user.dwHighDateTime;
  584. li2.LowPart = t_kernel.dwLowDateTime;
  585. li2.HighPart = t_kernel.dwHighDateTime;
  586. li.QuadPart += li2.QuadPart;
  587. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  588. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  589. ok = TRUE;
  590. }
  591. /* END: CLOCK_PROCESS */
  592. } else {
  593. /* BEGIN: unknown clock */
  594. /* ok = FALSE; already set by init */
  595. /* END: unknown clock */
  596. }
  597. }
  598. return ok ? 0 : -1;
  599. }
  600. #endif
  601. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  602. static int pthread_mutex_lock(pthread_mutex_t *);
  603. static int pthread_mutex_unlock(pthread_mutex_t *);
  604. static void path_to_unicode(const struct mg_connection *conn,
  605. const char *path,
  606. wchar_t *wbuf,
  607. size_t wbuf_len);
  608. /* All file operations need to be rewritten to solve #246. */
  609. struct mg_file;
  610. static const char *
  611. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  612. /* POSIX dirent interface */
  613. struct dirent {
  614. char d_name[PATH_MAX];
  615. };
  616. typedef struct DIR {
  617. HANDLE handle;
  618. WIN32_FIND_DATAW info;
  619. struct dirent result;
  620. } DIR;
  621. #if defined(_WIN32)
  622. #if !defined(HAVE_POLL)
  623. struct pollfd {
  624. SOCKET fd;
  625. short events;
  626. short revents;
  627. };
  628. #endif
  629. #endif
  630. /* Mark required libraries */
  631. #if defined(_MSC_VER)
  632. #pragma comment(lib, "Ws2_32.lib")
  633. #endif
  634. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  635. #include <arpa/inet.h>
  636. #include <inttypes.h>
  637. #include <netdb.h>
  638. #include <netinet/in.h>
  639. #include <netinet/tcp.h>
  640. #include <stdint.h>
  641. #include <sys/poll.h>
  642. #include <sys/socket.h>
  643. #include <sys/time.h>
  644. #include <sys/utsname.h>
  645. #include <sys/wait.h>
  646. typedef const void *SOCK_OPT_TYPE;
  647. #if defined(ANDROID)
  648. typedef unsigned short int in_port_t;
  649. #endif
  650. #include <dirent.h>
  651. #include <grp.h>
  652. #include <pwd.h>
  653. #include <unistd.h>
  654. #define vsnprintf_impl vsnprintf
  655. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  656. #include <dlfcn.h>
  657. #endif
  658. #include <pthread.h>
  659. #if defined(__MACH__)
  660. #define SSL_LIB "libssl.dylib"
  661. #define CRYPTO_LIB "libcrypto.dylib"
  662. #else
  663. #if !defined(SSL_LIB)
  664. #define SSL_LIB "libssl.so"
  665. #endif
  666. #if !defined(CRYPTO_LIB)
  667. #define CRYPTO_LIB "libcrypto.so"
  668. #endif
  669. #endif
  670. #if !defined(O_BINARY)
  671. #define O_BINARY (0)
  672. #endif /* O_BINARY */
  673. #define closesocket(a) (close(a))
  674. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  675. #define mg_remove(conn, x) (remove(x))
  676. #define mg_sleep(x) (usleep((x)*1000))
  677. #define mg_opendir(conn, x) (opendir(x))
  678. #define mg_closedir(x) (closedir(x))
  679. #define mg_readdir(x) (readdir(x))
  680. #define ERRNO (errno)
  681. #define INVALID_SOCKET (-1)
  682. #define INT64_FMT PRId64
  683. #define UINT64_FMT PRIu64
  684. typedef int SOCKET;
  685. #define WINCDECL
  686. #if defined(__hpux)
  687. /* HPUX 11 does not have monotonic, fall back to realtime */
  688. #if !defined(CLOCK_MONOTONIC)
  689. #define CLOCK_MONOTONIC CLOCK_REALTIME
  690. #endif
  691. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  692. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  693. * the prototypes use int* rather than socklen_t* which matches the
  694. * actual library expectation. When called with the wrong size arg
  695. * accept() returns a zero client inet addr and check_acl() always
  696. * fails. Since socklen_t is widely used below, just force replace
  697. * their typedef with int. - DTL
  698. */
  699. #define socklen_t int
  700. #endif /* hpux */
  701. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  702. /* Maximum queue length for pending connections. This value is passed as
  703. * parameter to the "listen" socket call. */
  704. #if !defined(SOMAXCONN)
  705. /* This symbol may be defined in winsock2.h so this must after that include */
  706. #define SOMAXCONN (100) /* in pending connections (count) */
  707. #endif
  708. /* In case our C library is missing "timegm", provide an implementation */
  709. #if defined(NEED_TIMEGM)
  710. static inline int
  711. is_leap(int y)
  712. {
  713. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  714. }
  715. static inline int
  716. count_leap(int y)
  717. {
  718. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  719. }
  720. time_t
  721. timegm(struct tm *tm)
  722. {
  723. static const unsigned short ydays[] = {
  724. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  725. int year = tm->tm_year + 1900;
  726. int mon = tm->tm_mon;
  727. int mday = tm->tm_mday - 1;
  728. int hour = tm->tm_hour;
  729. int min = tm->tm_min;
  730. int sec = tm->tm_sec;
  731. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  732. || (mday >= ydays[mon + 1] - ydays[mon]
  733. + (mon == 1 && is_leap(year) ? 1 : 0))
  734. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  735. return -1;
  736. time_t res = year - 1970;
  737. res *= 365;
  738. res += mday;
  739. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  740. res += count_leap(year);
  741. res *= 24;
  742. res += hour;
  743. res *= 60;
  744. res += min;
  745. res *= 60;
  746. res += sec;
  747. return res;
  748. }
  749. #endif /* NEED_TIMEGM */
  750. /* va_copy should always be a macro, C99 and C++11 - DTL */
  751. #if !defined(va_copy)
  752. #define va_copy(x, y) ((x) = (y))
  753. #endif
  754. #if defined(_WIN32)
  755. /* Create substitutes for POSIX functions in Win32. */
  756. #if defined(GCC_DIAGNOSTIC)
  757. /* Show no warning in case system functions are not used. */
  758. #pragma GCC diagnostic push
  759. #pragma GCC diagnostic ignored "-Wunused-function"
  760. #endif
  761. static CRITICAL_SECTION global_log_file_lock;
  762. FUNCTION_MAY_BE_UNUSED
  763. static DWORD
  764. pthread_self(void)
  765. {
  766. return GetCurrentThreadId();
  767. }
  768. FUNCTION_MAY_BE_UNUSED
  769. static int
  770. pthread_key_create(
  771. pthread_key_t *key,
  772. void (*_ignored)(void *) /* destructor not supported for Windows */
  773. )
  774. {
  775. (void)_ignored;
  776. if ((key != 0)) {
  777. *key = TlsAlloc();
  778. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  779. }
  780. return -2;
  781. }
  782. FUNCTION_MAY_BE_UNUSED
  783. static int
  784. pthread_key_delete(pthread_key_t key)
  785. {
  786. return TlsFree(key) ? 0 : 1;
  787. }
  788. FUNCTION_MAY_BE_UNUSED
  789. static int
  790. pthread_setspecific(pthread_key_t key, void *value)
  791. {
  792. return TlsSetValue(key, value) ? 0 : 1;
  793. }
  794. FUNCTION_MAY_BE_UNUSED
  795. static void *
  796. pthread_getspecific(pthread_key_t key)
  797. {
  798. return TlsGetValue(key);
  799. }
  800. #if defined(GCC_DIAGNOSTIC)
  801. /* Enable unused function warning again */
  802. #pragma GCC diagnostic pop
  803. #endif
  804. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  805. #else
  806. static pthread_mutexattr_t pthread_mutex_attr;
  807. #endif /* _WIN32 */
  808. #if defined(_WIN32_WCE)
  809. /* Create substitutes for POSIX functions in Win32. */
  810. #if defined(GCC_DIAGNOSTIC)
  811. /* Show no warning in case system functions are not used. */
  812. #pragma GCC diagnostic push
  813. #pragma GCC diagnostic ignored "-Wunused-function"
  814. #endif
  815. FUNCTION_MAY_BE_UNUSED
  816. static time_t
  817. time(time_t *ptime)
  818. {
  819. time_t t;
  820. SYSTEMTIME st;
  821. FILETIME ft;
  822. GetSystemTime(&st);
  823. SystemTimeToFileTime(&st, &ft);
  824. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  825. if (ptime != NULL) {
  826. *ptime = t;
  827. }
  828. return t;
  829. }
  830. FUNCTION_MAY_BE_UNUSED
  831. static struct tm *
  832. localtime_s(const time_t *ptime, struct tm *ptm)
  833. {
  834. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  835. FILETIME ft, lft;
  836. SYSTEMTIME st;
  837. TIME_ZONE_INFORMATION tzinfo;
  838. if (ptm == NULL) {
  839. return NULL;
  840. }
  841. *(int64_t *)&ft = t;
  842. FileTimeToLocalFileTime(&ft, &lft);
  843. FileTimeToSystemTime(&lft, &st);
  844. ptm->tm_year = st.wYear - 1900;
  845. ptm->tm_mon = st.wMonth - 1;
  846. ptm->tm_wday = st.wDayOfWeek;
  847. ptm->tm_mday = st.wDay;
  848. ptm->tm_hour = st.wHour;
  849. ptm->tm_min = st.wMinute;
  850. ptm->tm_sec = st.wSecond;
  851. ptm->tm_yday = 0; /* hope nobody uses this */
  852. ptm->tm_isdst =
  853. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  854. return ptm;
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static struct tm *
  858. gmtime_s(const time_t *ptime, struct tm *ptm)
  859. {
  860. /* FIXME(lsm): fix this. */
  861. return localtime_s(ptime, ptm);
  862. }
  863. static int mg_atomic_inc(volatile int *addr);
  864. static struct tm tm_array[MAX_WORKER_THREADS];
  865. static int tm_index = 0;
  866. FUNCTION_MAY_BE_UNUSED
  867. static struct tm *
  868. localtime(const time_t *ptime)
  869. {
  870. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  871. return localtime_s(ptime, tm_array + i);
  872. }
  873. FUNCTION_MAY_BE_UNUSED
  874. static struct tm *
  875. gmtime(const time_t *ptime)
  876. {
  877. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  878. return gmtime_s(ptime, tm_array + i);
  879. }
  880. FUNCTION_MAY_BE_UNUSED
  881. static size_t
  882. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  883. {
  884. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  885. * for WinCE"); */
  886. return 0;
  887. }
  888. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  889. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  890. #define remove(f) mg_remove(NULL, f)
  891. FUNCTION_MAY_BE_UNUSED
  892. static int
  893. rename(const char *a, const char *b)
  894. {
  895. wchar_t wa[W_PATH_MAX];
  896. wchar_t wb[W_PATH_MAX];
  897. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  898. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  899. return MoveFileW(wa, wb) ? 0 : -1;
  900. }
  901. struct stat {
  902. int64_t st_size;
  903. time_t st_mtime;
  904. };
  905. FUNCTION_MAY_BE_UNUSED
  906. static int
  907. stat(const char *name, struct stat *st)
  908. {
  909. wchar_t wbuf[W_PATH_MAX];
  910. WIN32_FILE_ATTRIBUTE_DATA attr;
  911. time_t creation_time, write_time;
  912. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  913. memset(&attr, 0, sizeof(attr));
  914. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  915. st->st_size =
  916. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  917. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  918. attr.ftLastWriteTime.dwHighDateTime);
  919. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  920. attr.ftCreationTime.dwHighDateTime);
  921. if (creation_time > write_time) {
  922. st->st_mtime = creation_time;
  923. } else {
  924. st->st_mtime = write_time;
  925. }
  926. return 0;
  927. }
  928. #define access(x, a) 1 /* not required anyway */
  929. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  930. /* Values from errno.h in Windows SDK (Visual Studio). */
  931. #define EEXIST 17
  932. #define EACCES 13
  933. #define ENOENT 2
  934. #if defined(GCC_DIAGNOSTIC)
  935. /* Enable unused function warning again */
  936. #pragma GCC diagnostic pop
  937. #endif
  938. #endif /* defined(_WIN32_WCE) */
  939. #if defined(GCC_DIAGNOSTIC)
  940. /* Show no warning in case system functions are not used. */
  941. #pragma GCC diagnostic push
  942. #pragma GCC diagnostic ignored "-Wunused-function"
  943. #endif /* defined(GCC_DIAGNOSTIC) */
  944. #if defined(__clang__)
  945. /* Show no warning in case system functions are not used. */
  946. #pragma clang diagnostic push
  947. #pragma clang diagnostic ignored "-Wunused-function"
  948. #endif
  949. static pthread_mutex_t global_lock_mutex;
  950. #if defined(_WIN32)
  951. /* Forward declaration for Windows */
  952. FUNCTION_MAY_BE_UNUSED
  953. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  954. FUNCTION_MAY_BE_UNUSED
  955. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  956. #endif
  957. FUNCTION_MAY_BE_UNUSED
  958. static void
  959. mg_global_lock(void)
  960. {
  961. (void)pthread_mutex_lock(&global_lock_mutex);
  962. }
  963. FUNCTION_MAY_BE_UNUSED
  964. static void
  965. mg_global_unlock(void)
  966. {
  967. (void)pthread_mutex_unlock(&global_lock_mutex);
  968. }
  969. FUNCTION_MAY_BE_UNUSED
  970. static int
  971. mg_atomic_inc(volatile int *addr)
  972. {
  973. int ret;
  974. #if defined(_WIN32) && !defined(NO_ATOMICS)
  975. /* Depending on the SDK, this function uses either
  976. * (volatile unsigned int *) or (volatile LONG *),
  977. * so whatever you use, the other SDK is likely to raise a warning. */
  978. ret = InterlockedIncrement((volatile long *)addr);
  979. #elif defined(__GNUC__) \
  980. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  981. && !defined(NO_ATOMICS)
  982. ret = __sync_add_and_fetch(addr, 1);
  983. #else
  984. mg_global_lock();
  985. ret = (++(*addr));
  986. mg_global_unlock();
  987. #endif
  988. return ret;
  989. }
  990. FUNCTION_MAY_BE_UNUSED
  991. static int
  992. mg_atomic_dec(volatile int *addr)
  993. {
  994. int ret;
  995. #if defined(_WIN32) && !defined(NO_ATOMICS)
  996. /* Depending on the SDK, this function uses either
  997. * (volatile unsigned int *) or (volatile LONG *),
  998. * so whatever you use, the other SDK is likely to raise a warning. */
  999. ret = InterlockedDecrement((volatile long *)addr);
  1000. #elif defined(__GNUC__) \
  1001. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1002. && !defined(NO_ATOMICS)
  1003. ret = __sync_sub_and_fetch(addr, 1);
  1004. #else
  1005. mg_global_lock();
  1006. ret = (--(*addr));
  1007. mg_global_unlock();
  1008. #endif
  1009. return ret;
  1010. }
  1011. #if defined(USE_SERVER_STATS)
  1012. static int64_t
  1013. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1014. {
  1015. int64_t ret;
  1016. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1017. ret = InterlockedAdd64(addr, value);
  1018. #elif defined(__GNUC__) \
  1019. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1020. && !defined(NO_ATOMICS)
  1021. ret = __sync_add_and_fetch(addr, value);
  1022. #else
  1023. mg_global_lock();
  1024. *addr += value;
  1025. ret = (*addr);
  1026. mg_global_unlock();
  1027. #endif
  1028. return ret;
  1029. }
  1030. #endif
  1031. #if defined(GCC_DIAGNOSTIC)
  1032. /* Show no warning in case system functions are not used. */
  1033. #pragma GCC diagnostic pop
  1034. #endif /* defined(GCC_DIAGNOSTIC) */
  1035. #if defined(__clang__)
  1036. /* Show no warning in case system functions are not used. */
  1037. #pragma clang diagnostic pop
  1038. #endif
  1039. #if defined(USE_SERVER_STATS)
  1040. struct mg_memory_stat {
  1041. volatile int64_t totalMemUsed;
  1042. volatile int64_t maxMemUsed;
  1043. volatile int blockCount;
  1044. };
  1045. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1046. static void *
  1047. mg_malloc_ex(size_t size,
  1048. struct mg_context *ctx,
  1049. const char *file,
  1050. unsigned line)
  1051. {
  1052. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1053. void *memory = 0;
  1054. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1055. #if defined(MEMORY_DEBUGGING)
  1056. char mallocStr[256];
  1057. #else
  1058. (void)file;
  1059. (void)line;
  1060. #endif
  1061. if (data) {
  1062. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1063. if (mmem > mstat->maxMemUsed) {
  1064. /* could use atomic compare exchange, but this
  1065. * seems overkill for statistics data */
  1066. mstat->maxMemUsed = mmem;
  1067. }
  1068. mg_atomic_inc(&mstat->blockCount);
  1069. ((uintptr_t *)data)[0] = size;
  1070. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1071. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1072. }
  1073. #if defined(MEMORY_DEBUGGING)
  1074. sprintf(mallocStr,
  1075. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1076. memory,
  1077. (unsigned long)size,
  1078. (unsigned long)mstat->totalMemUsed,
  1079. (unsigned long)mstat->blockCount,
  1080. file,
  1081. line);
  1082. #if defined(_WIN32)
  1083. OutputDebugStringA(mallocStr);
  1084. #else
  1085. DEBUG_TRACE("%s", mallocStr);
  1086. #endif
  1087. #endif
  1088. return memory;
  1089. }
  1090. static void *
  1091. mg_calloc_ex(size_t count,
  1092. size_t size,
  1093. struct mg_context *ctx,
  1094. const char *file,
  1095. unsigned line)
  1096. {
  1097. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1098. if (data) {
  1099. memset(data, 0, size * count);
  1100. }
  1101. return data;
  1102. }
  1103. static void
  1104. mg_free_ex(void *memory, const char *file, unsigned line)
  1105. {
  1106. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1107. #if defined(MEMORY_DEBUGGING)
  1108. char mallocStr[256];
  1109. #else
  1110. (void)file;
  1111. (void)line;
  1112. #endif
  1113. if (memory) {
  1114. uintptr_t size = ((uintptr_t *)data)[0];
  1115. struct mg_memory_stat *mstat =
  1116. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1117. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1118. mg_atomic_dec(&mstat->blockCount);
  1119. #if defined(MEMORY_DEBUGGING)
  1120. sprintf(mallocStr,
  1121. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1122. memory,
  1123. (unsigned long)size,
  1124. (unsigned long)mstat->totalMemUsed,
  1125. (unsigned long)mstat->blockCount,
  1126. file,
  1127. line);
  1128. #if defined(_WIN32)
  1129. OutputDebugStringA(mallocStr);
  1130. #else
  1131. DEBUG_TRACE("%s", mallocStr);
  1132. #endif
  1133. #endif
  1134. free(data);
  1135. }
  1136. }
  1137. static void *
  1138. mg_realloc_ex(void *memory,
  1139. size_t newsize,
  1140. struct mg_context *ctx,
  1141. const char *file,
  1142. unsigned line)
  1143. {
  1144. void *data;
  1145. void *_realloc;
  1146. uintptr_t oldsize;
  1147. #if defined(MEMORY_DEBUGGING)
  1148. char mallocStr[256];
  1149. #else
  1150. (void)file;
  1151. (void)line;
  1152. #endif
  1153. if (newsize) {
  1154. if (memory) {
  1155. /* Reallocate existing block */
  1156. struct mg_memory_stat *mstat;
  1157. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1158. oldsize = ((uintptr_t *)data)[0];
  1159. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1160. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1161. if (_realloc) {
  1162. data = _realloc;
  1163. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1164. #if defined(MEMORY_DEBUGGING)
  1165. sprintf(mallocStr,
  1166. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1167. memory,
  1168. (unsigned long)oldsize,
  1169. (unsigned long)mstat->totalMemUsed,
  1170. (unsigned long)mstat->blockCount,
  1171. file,
  1172. line);
  1173. #if defined(_WIN32)
  1174. OutputDebugStringA(mallocStr);
  1175. #else
  1176. DEBUG_TRACE("%s", mallocStr);
  1177. #endif
  1178. #endif
  1179. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1180. #if defined(MEMORY_DEBUGGING)
  1181. sprintf(mallocStr,
  1182. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1183. memory,
  1184. (unsigned long)newsize,
  1185. (unsigned long)mstat->totalMemUsed,
  1186. (unsigned long)mstat->blockCount,
  1187. file,
  1188. line);
  1189. #if defined(_WIN32)
  1190. OutputDebugStringA(mallocStr);
  1191. #else
  1192. DEBUG_TRACE("%s", mallocStr);
  1193. #endif
  1194. #endif
  1195. *(uintptr_t *)data = newsize;
  1196. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1197. } else {
  1198. #if defined(MEMORY_DEBUGGING)
  1199. #if defined(_WIN32)
  1200. OutputDebugStringA("MEM: realloc failed\n");
  1201. #else
  1202. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1203. #endif
  1204. #endif
  1205. return _realloc;
  1206. }
  1207. } else {
  1208. /* Allocate new block */
  1209. data = mg_malloc_ex(newsize, ctx, file, line);
  1210. }
  1211. } else {
  1212. /* Free existing block */
  1213. data = 0;
  1214. mg_free_ex(memory, file, line);
  1215. }
  1216. return data;
  1217. }
  1218. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1219. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1220. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1221. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1222. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1223. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1224. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1225. #else /* USE_SERVER_STATS */
  1226. static __inline void *
  1227. mg_malloc(size_t a)
  1228. {
  1229. return malloc(a);
  1230. }
  1231. static __inline void *
  1232. mg_calloc(size_t a, size_t b)
  1233. {
  1234. return calloc(a, b);
  1235. }
  1236. static __inline void *
  1237. mg_realloc(void *a, size_t b)
  1238. {
  1239. return realloc(a, b);
  1240. }
  1241. static __inline void
  1242. mg_free(void *a)
  1243. {
  1244. free(a);
  1245. }
  1246. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1247. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1248. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1249. #define mg_free_ctx(a, c) mg_free(a)
  1250. #endif /* USE_SERVER_STATS */
  1251. static void mg_vsnprintf(const struct mg_connection *conn,
  1252. int *truncated,
  1253. char *buf,
  1254. size_t buflen,
  1255. const char *fmt,
  1256. va_list ap);
  1257. static void mg_snprintf(const struct mg_connection *conn,
  1258. int *truncated,
  1259. char *buf,
  1260. size_t buflen,
  1261. PRINTF_FORMAT_STRING(const char *fmt),
  1262. ...) PRINTF_ARGS(5, 6);
  1263. /* This following lines are just meant as a reminder to use the mg-functions
  1264. * for memory management */
  1265. #if defined(malloc)
  1266. #undef malloc
  1267. #endif
  1268. #if defined(calloc)
  1269. #undef calloc
  1270. #endif
  1271. #if defined(realloc)
  1272. #undef realloc
  1273. #endif
  1274. #if defined(free)
  1275. #undef free
  1276. #endif
  1277. #if defined(snprintf)
  1278. #undef snprintf
  1279. #endif
  1280. #if defined(vsnprintf)
  1281. #undef vsnprintf
  1282. #endif
  1283. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1284. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1285. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1286. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1287. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1288. #if defined(_WIN32)
  1289. /* vsnprintf must not be used in any system,
  1290. * but this define only works well for Windows. */
  1291. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1292. #endif
  1293. /* mg_init_library counter */
  1294. static int mg_init_library_called = 0;
  1295. #if !defined(NO_SSL)
  1296. static int mg_ssl_initialized = 0;
  1297. #endif
  1298. static pthread_key_t sTlsKey; /* Thread local storage index */
  1299. static int thread_idx_max = 0;
  1300. #if defined(MG_LEGACY_INTERFACE)
  1301. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1302. #endif
  1303. struct mg_workerTLS {
  1304. int is_master;
  1305. unsigned long thread_idx;
  1306. #if defined(_WIN32)
  1307. HANDLE pthread_cond_helper_mutex;
  1308. struct mg_workerTLS *next_waiting_thread;
  1309. #endif
  1310. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1311. char txtbuf[4];
  1312. #endif
  1313. };
  1314. #if defined(GCC_DIAGNOSTIC)
  1315. /* Show no warning in case system functions are not used. */
  1316. #pragma GCC diagnostic push
  1317. #pragma GCC diagnostic ignored "-Wunused-function"
  1318. #endif /* defined(GCC_DIAGNOSTIC) */
  1319. #if defined(__clang__)
  1320. /* Show no warning in case system functions are not used. */
  1321. #pragma clang diagnostic push
  1322. #pragma clang diagnostic ignored "-Wunused-function"
  1323. #endif
  1324. /* Get a unique thread ID as unsigned long, independent from the data type
  1325. * of thread IDs defined by the operating system API.
  1326. * If two calls to mg_current_thread_id return the same value, they calls
  1327. * are done from the same thread. If they return different values, they are
  1328. * done from different threads. (Provided this function is used in the same
  1329. * process context and threads are not repeatedly created and deleted, but
  1330. * CivetWeb does not do that).
  1331. * This function must match the signature required for SSL id callbacks:
  1332. * CRYPTO_set_id_callback
  1333. */
  1334. FUNCTION_MAY_BE_UNUSED
  1335. static unsigned long
  1336. mg_current_thread_id(void)
  1337. {
  1338. #if defined(_WIN32)
  1339. return GetCurrentThreadId();
  1340. #else
  1341. #if defined(__clang__)
  1342. #pragma clang diagnostic push
  1343. #pragma clang diagnostic ignored "-Wunreachable-code"
  1344. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1345. * or not, so one of the two conditions will be unreachable by construction.
  1346. * Unfortunately the C standard does not define a way to check this at
  1347. * compile time, since the #if preprocessor conditions can not use the sizeof
  1348. * operator as an argument. */
  1349. #endif
  1350. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1351. /* This is the problematic case for CRYPTO_set_id_callback:
  1352. * The OS pthread_t can not be cast to unsigned long. */
  1353. struct mg_workerTLS *tls =
  1354. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1355. if (tls == NULL) {
  1356. /* SSL called from an unknown thread: Create some thread index.
  1357. */
  1358. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1359. tls->is_master = -2; /* -2 means "3rd party thread" */
  1360. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1361. pthread_setspecific(sTlsKey, tls);
  1362. }
  1363. return tls->thread_idx;
  1364. } else {
  1365. /* pthread_t may be any data type, so a simple cast to unsigned long
  1366. * can rise a warning/error, depending on the platform.
  1367. * Here memcpy is used as an anything-to-anything cast. */
  1368. unsigned long ret = 0;
  1369. pthread_t t = pthread_self();
  1370. memcpy(&ret, &t, sizeof(pthread_t));
  1371. return ret;
  1372. }
  1373. #if defined(__clang__)
  1374. #pragma clang diagnostic pop
  1375. #endif
  1376. #endif
  1377. }
  1378. FUNCTION_MAY_BE_UNUSED
  1379. static uint64_t
  1380. mg_get_current_time_ns(void)
  1381. {
  1382. struct timespec tsnow;
  1383. clock_gettime(CLOCK_REALTIME, &tsnow);
  1384. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1385. }
  1386. #if defined(GCC_DIAGNOSTIC)
  1387. /* Show no warning in case system functions are not used. */
  1388. #pragma GCC diagnostic pop
  1389. #endif /* defined(GCC_DIAGNOSTIC) */
  1390. #if defined(__clang__)
  1391. /* Show no warning in case system functions are not used. */
  1392. #pragma clang diagnostic pop
  1393. #endif
  1394. #if defined(NEED_DEBUG_TRACE_FUNC)
  1395. static void
  1396. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1397. {
  1398. va_list args;
  1399. uint64_t nsnow;
  1400. static uint64_t nslast;
  1401. struct timespec tsnow;
  1402. /* Get some operating system independent thread id */
  1403. unsigned long thread_id = mg_current_thread_id();
  1404. clock_gettime(CLOCK_REALTIME, &tsnow);
  1405. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1406. + ((uint64_t)tsnow.tv_nsec);
  1407. if (!nslast) {
  1408. nslast = nsnow;
  1409. }
  1410. flockfile(stdout);
  1411. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1412. (unsigned long)tsnow.tv_sec,
  1413. (unsigned long)tsnow.tv_nsec,
  1414. nsnow - nslast,
  1415. thread_id,
  1416. func,
  1417. line);
  1418. va_start(args, fmt);
  1419. vprintf(fmt, args);
  1420. va_end(args);
  1421. putchar('\n');
  1422. fflush(stdout);
  1423. funlockfile(stdout);
  1424. nslast = nsnow;
  1425. }
  1426. #endif /* NEED_DEBUG_TRACE_FUNC */
  1427. #define MD5_STATIC static
  1428. #include "md5.inl"
  1429. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1430. #if defined(NO_SOCKLEN_T)
  1431. typedef int socklen_t;
  1432. #endif /* NO_SOCKLEN_T */
  1433. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1434. #if !defined(MSG_NOSIGNAL)
  1435. #define MSG_NOSIGNAL (0)
  1436. #endif
  1437. #if defined(NO_SSL)
  1438. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1439. typedef struct SSL_CTX SSL_CTX;
  1440. #else
  1441. #if defined(NO_SSL_DL)
  1442. #include <openssl/bn.h>
  1443. #include <openssl/conf.h>
  1444. #include <openssl/crypto.h>
  1445. #include <openssl/dh.h>
  1446. #include <openssl/engine.h>
  1447. #include <openssl/err.h>
  1448. #include <openssl/opensslv.h>
  1449. #include <openssl/pem.h>
  1450. #include <openssl/ssl.h>
  1451. #include <openssl/x509.h>
  1452. #if defined(WOLFSSL_VERSION)
  1453. /* Additional defines for WolfSSL, see
  1454. * https://github.com/civetweb/civetweb/issues/583 */
  1455. #include "wolfssl_extras.inl"
  1456. #endif
  1457. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1458. /* If OpenSSL headers are included, automatically select the API version */
  1459. #if !defined(OPENSSL_API_1_1)
  1460. #define OPENSSL_API_1_1
  1461. #endif
  1462. #endif
  1463. #else
  1464. /* SSL loaded dynamically from DLL.
  1465. * I put the prototypes here to be independent from OpenSSL source
  1466. * installation. */
  1467. typedef struct ssl_st SSL;
  1468. typedef struct ssl_method_st SSL_METHOD;
  1469. typedef struct ssl_ctx_st SSL_CTX;
  1470. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1471. typedef struct x509_name X509_NAME;
  1472. typedef struct asn1_integer ASN1_INTEGER;
  1473. typedef struct bignum BIGNUM;
  1474. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1475. typedef struct evp_md EVP_MD;
  1476. typedef struct x509 X509;
  1477. #define SSL_CTRL_OPTIONS (32)
  1478. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1479. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1480. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1481. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1482. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1483. #define SSL_VERIFY_NONE (0)
  1484. #define SSL_VERIFY_PEER (1)
  1485. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1486. #define SSL_VERIFY_CLIENT_ONCE (4)
  1487. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1488. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1489. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1490. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1491. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1492. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1493. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1494. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1495. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1496. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1497. #define SSL_CB_HANDSHAKE_START (0x10)
  1498. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1499. #define SSL_ERROR_NONE (0)
  1500. #define SSL_ERROR_SSL (1)
  1501. #define SSL_ERROR_WANT_READ (2)
  1502. #define SSL_ERROR_WANT_WRITE (3)
  1503. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1504. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1505. #define SSL_ERROR_ZERO_RETURN (6)
  1506. #define SSL_ERROR_WANT_CONNECT (7)
  1507. #define SSL_ERROR_WANT_ACCEPT (8)
  1508. #define TLSEXT_TYPE_server_name (0)
  1509. #define TLSEXT_NAMETYPE_host_name (0)
  1510. #define SSL_TLSEXT_ERR_OK (0)
  1511. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1512. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1513. #define SSL_TLSEXT_ERR_NOACK (3)
  1514. struct ssl_func {
  1515. const char *name; /* SSL function name */
  1516. void (*ptr)(void); /* Function pointer */
  1517. };
  1518. #if defined(OPENSSL_API_1_1)
  1519. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1520. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1521. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1522. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1523. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1524. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1525. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1526. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1527. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1528. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1529. #define OPENSSL_init_ssl \
  1530. (*(int (*)(uint64_t opts, \
  1531. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1532. .ptr)
  1533. #define SSL_CTX_use_PrivateKey_file \
  1534. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1535. #define SSL_CTX_use_certificate_file \
  1536. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1537. #define SSL_CTX_set_default_passwd_cb \
  1538. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1539. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1540. #define SSL_CTX_use_certificate_chain_file \
  1541. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1542. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1543. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1544. #define SSL_CTX_set_verify \
  1545. (*(void (*)(SSL_CTX *, \
  1546. int, \
  1547. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1548. .ptr)
  1549. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1550. #define SSL_CTX_load_verify_locations \
  1551. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1552. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1553. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1554. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1555. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1556. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1557. #define SSL_CIPHER_get_name \
  1558. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1559. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1560. #define SSL_CTX_set_session_id_context \
  1561. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1562. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1563. #define SSL_CTX_set_cipher_list \
  1564. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1565. #define SSL_CTX_set_options \
  1566. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1567. #define SSL_CTX_set_info_callback \
  1568. (*(void (*)(SSL_CTX * ctx, void (*callback)(SSL * s, int, int))) \
  1569. ssl_sw[32] \
  1570. .ptr)
  1571. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1572. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1573. #define SSL_CTX_callback_ctrl \
  1574. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1575. #define SSL_get_servername \
  1576. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1577. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1578. #define SSL_CTX_clear_options(ctx, op) \
  1579. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1580. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1581. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1582. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1583. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1584. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1585. SSL_CTX_callback_ctrl(ctx, \
  1586. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1587. (void (*)(void))cb)
  1588. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1589. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1590. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1591. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1592. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1593. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1594. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1595. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1596. // deprecated in OpenSLL 1.1.0 and should not be used, keep for a simplicity
  1597. #define ERR_remove_thread_state (*(void (*)(const void *))crypto_sw[2].ptr)
  1598. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1599. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1600. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1601. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[6].ptr)
  1602. #define X509_NAME_oneline \
  1603. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1604. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[8].ptr)
  1605. #define EVP_get_digestbyname \
  1606. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1607. #define EVP_Digest \
  1608. (*(int (*)( \
  1609. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1610. crypto_sw[10] \
  1611. .ptr)
  1612. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1613. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1614. #define ASN1_INTEGER_to_BN \
  1615. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[13].ptr)
  1616. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1617. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1618. #define OPENSSL_free(a) CRYPTO_free(a)
  1619. /* init_ssl_ctx() function updates this array.
  1620. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1621. * of respective functions. The macros above (like SSL_connect()) are really
  1622. * just calling these functions indirectly via the pointer. */
  1623. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1624. {"SSL_accept", NULL},
  1625. {"SSL_connect", NULL},
  1626. {"SSL_read", NULL},
  1627. {"SSL_write", NULL},
  1628. {"SSL_get_error", NULL},
  1629. {"SSL_set_fd", NULL},
  1630. {"SSL_new", NULL},
  1631. {"SSL_CTX_new", NULL},
  1632. {"TLS_server_method", NULL},
  1633. {"OPENSSL_init_ssl", NULL},
  1634. {"SSL_CTX_use_PrivateKey_file", NULL},
  1635. {"SSL_CTX_use_certificate_file", NULL},
  1636. {"SSL_CTX_set_default_passwd_cb", NULL},
  1637. {"SSL_CTX_free", NULL},
  1638. {"SSL_CTX_use_certificate_chain_file", NULL},
  1639. {"TLS_client_method", NULL},
  1640. {"SSL_pending", NULL},
  1641. {"SSL_CTX_set_verify", NULL},
  1642. {"SSL_shutdown", NULL},
  1643. {"SSL_CTX_load_verify_locations", NULL},
  1644. {"SSL_CTX_set_default_verify_paths", NULL},
  1645. {"SSL_CTX_set_verify_depth", NULL},
  1646. {"SSL_get_peer_certificate", NULL},
  1647. {"SSL_get_version", NULL},
  1648. {"SSL_get_current_cipher", NULL},
  1649. {"SSL_CIPHER_get_name", NULL},
  1650. {"SSL_CTX_check_private_key", NULL},
  1651. {"SSL_CTX_set_session_id_context", NULL},
  1652. {"SSL_CTX_ctrl", NULL},
  1653. {"SSL_CTX_set_cipher_list", NULL},
  1654. {"SSL_CTX_set_options", NULL},
  1655. {"SSL_CTX_set_info_callback", NULL},
  1656. {"SSL_get_ex_data", NULL},
  1657. {"SSL_set_ex_data", NULL},
  1658. {"SSL_CTX_callback_ctrl", NULL},
  1659. {"SSL_get_servername", NULL},
  1660. {"SSL_set_SSL_CTX", NULL},
  1661. {NULL, NULL}};
  1662. /* Similar array as ssl_sw. These functions could be located in different
  1663. * lib. */
  1664. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1665. {"ERR_error_string", NULL},
  1666. {"ERR_remove_thread_state", NULL},
  1667. {"CONF_modules_unload", NULL},
  1668. {"X509_free", NULL},
  1669. {"X509_get_subject_name", NULL},
  1670. {"X509_get_issuer_name", NULL},
  1671. {"X509_NAME_oneline", NULL},
  1672. {"X509_get_serialNumber", NULL},
  1673. {"EVP_get_digestbyname", NULL},
  1674. {"EVP_Digest", NULL},
  1675. {"i2d_X509", NULL},
  1676. {"BN_bn2hex", NULL},
  1677. {"ASN1_INTEGER_to_BN", NULL},
  1678. {"BN_free", NULL},
  1679. {"CRYPTO_free", NULL},
  1680. {NULL, NULL}};
  1681. #else
  1682. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1683. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1684. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1685. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1686. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1687. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1688. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1689. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1690. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1691. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1692. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1693. #define SSL_CTX_use_PrivateKey_file \
  1694. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1695. #define SSL_CTX_use_certificate_file \
  1696. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1697. #define SSL_CTX_set_default_passwd_cb \
  1698. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1699. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1700. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1701. #define SSL_CTX_use_certificate_chain_file \
  1702. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1703. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1704. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1705. #define SSL_CTX_set_verify \
  1706. (*(void (*)(SSL_CTX *, \
  1707. int, \
  1708. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1709. .ptr)
  1710. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1711. #define SSL_CTX_load_verify_locations \
  1712. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1713. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1714. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1715. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1716. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1717. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1718. #define SSL_CIPHER_get_name \
  1719. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1720. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1721. #define SSL_CTX_set_session_id_context \
  1722. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1723. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1724. #define SSL_CTX_set_cipher_list \
  1725. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1726. #define SSL_CTX_set_info_callback \
  1727. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int))) ssl_sw[32].ptr)
  1728. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1729. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1730. #define SSL_CTX_callback_ctrl \
  1731. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1732. #define SSL_get_servername \
  1733. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1734. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1735. #define SSL_CTX_set_options(ctx, op) \
  1736. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1737. #define SSL_CTX_clear_options(ctx, op) \
  1738. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1739. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1740. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1741. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1742. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1743. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1744. SSL_CTX_callback_ctrl(ctx, \
  1745. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1746. (void (*)(void))cb)
  1747. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1748. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1749. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1750. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1751. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1752. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1753. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1754. #define CRYPTO_set_locking_callback \
  1755. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1756. #define CRYPTO_set_id_callback \
  1757. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1758. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1759. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1760. #define ERR_remove_thread_state (*(void (*)(const void *))crypto_sw[5].ptr)
  1761. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1762. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1763. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1764. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1765. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1766. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1767. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1768. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1769. #define X509_NAME_oneline \
  1770. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1771. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1772. #define i2c_ASN1_INTEGER \
  1773. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1774. #define EVP_get_digestbyname \
  1775. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1776. #define EVP_Digest \
  1777. (*(int (*)( \
  1778. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1779. crypto_sw[18] \
  1780. .ptr)
  1781. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1782. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1783. #define ASN1_INTEGER_to_BN \
  1784. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1785. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1786. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1787. #define OPENSSL_free(a) CRYPTO_free(a)
  1788. /* init_ssl_ctx() function updates this array.
  1789. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1790. * of respective functions. The macros above (like SSL_connect()) are really
  1791. * just calling these functions indirectly via the pointer. */
  1792. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1793. {"SSL_accept", NULL},
  1794. {"SSL_connect", NULL},
  1795. {"SSL_read", NULL},
  1796. {"SSL_write", NULL},
  1797. {"SSL_get_error", NULL},
  1798. {"SSL_set_fd", NULL},
  1799. {"SSL_new", NULL},
  1800. {"SSL_CTX_new", NULL},
  1801. {"SSLv23_server_method", NULL},
  1802. {"SSL_library_init", NULL},
  1803. {"SSL_CTX_use_PrivateKey_file", NULL},
  1804. {"SSL_CTX_use_certificate_file", NULL},
  1805. {"SSL_CTX_set_default_passwd_cb", NULL},
  1806. {"SSL_CTX_free", NULL},
  1807. {"SSL_load_error_strings", NULL},
  1808. {"SSL_CTX_use_certificate_chain_file", NULL},
  1809. {"SSLv23_client_method", NULL},
  1810. {"SSL_pending", NULL},
  1811. {"SSL_CTX_set_verify", NULL},
  1812. {"SSL_shutdown", NULL},
  1813. {"SSL_CTX_load_verify_locations", NULL},
  1814. {"SSL_CTX_set_default_verify_paths", NULL},
  1815. {"SSL_CTX_set_verify_depth", NULL},
  1816. {"SSL_get_peer_certificate", NULL},
  1817. {"SSL_get_version", NULL},
  1818. {"SSL_get_current_cipher", NULL},
  1819. {"SSL_CIPHER_get_name", NULL},
  1820. {"SSL_CTX_check_private_key", NULL},
  1821. {"SSL_CTX_set_session_id_context", NULL},
  1822. {"SSL_CTX_ctrl", NULL},
  1823. {"SSL_CTX_set_cipher_list", NULL},
  1824. {"SSL_CTX_set_info_callback", NULL},
  1825. {"SSL_get_ex_data", NULL},
  1826. {"SSL_set_ex_data", NULL},
  1827. {"SSL_CTX_callback_ctrl", NULL},
  1828. {"SSL_get_servername", NULL},
  1829. {"SSL_set_SSL_CTX", NULL},
  1830. {NULL, NULL}};
  1831. /* Similar array as ssl_sw. These functions could be located in different
  1832. * lib. */
  1833. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1834. {"CRYPTO_set_locking_callback", NULL},
  1835. {"CRYPTO_set_id_callback", NULL},
  1836. {"ERR_get_error", NULL},
  1837. {"ERR_error_string", NULL},
  1838. {"ERR_remove_thread_state", NULL},
  1839. {"ERR_free_strings", NULL},
  1840. {"ENGINE_cleanup", NULL},
  1841. {"CONF_modules_unload", NULL},
  1842. {"CRYPTO_cleanup_all_ex_data", NULL},
  1843. {"EVP_cleanup", NULL},
  1844. {"X509_free", NULL},
  1845. {"X509_get_subject_name", NULL},
  1846. {"X509_get_issuer_name", NULL},
  1847. {"X509_NAME_oneline", NULL},
  1848. {"X509_get_serialNumber", NULL},
  1849. {"i2c_ASN1_INTEGER", NULL},
  1850. {"EVP_get_digestbyname", NULL},
  1851. {"EVP_Digest", NULL},
  1852. {"i2d_X509", NULL},
  1853. {"BN_bn2hex", NULL},
  1854. {"ASN1_INTEGER_to_BN", NULL},
  1855. {"BN_free", NULL},
  1856. {"CRYPTO_free", NULL},
  1857. {NULL, NULL}};
  1858. #endif /* OPENSSL_API_1_1 */
  1859. #endif /* NO_SSL_DL */
  1860. #endif /* NO_SSL */
  1861. #if !defined(NO_CACHING)
  1862. static const char *month_names[] = {"Jan",
  1863. "Feb",
  1864. "Mar",
  1865. "Apr",
  1866. "May",
  1867. "Jun",
  1868. "Jul",
  1869. "Aug",
  1870. "Sep",
  1871. "Oct",
  1872. "Nov",
  1873. "Dec"};
  1874. #endif /* !NO_CACHING */
  1875. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1876. * the
  1877. * union u. */
  1878. union usa {
  1879. struct sockaddr sa;
  1880. struct sockaddr_in sin;
  1881. #if defined(USE_IPV6)
  1882. struct sockaddr_in6 sin6;
  1883. #endif
  1884. };
  1885. /* Describes a string (chunk of memory). */
  1886. struct vec {
  1887. const char *ptr;
  1888. size_t len;
  1889. };
  1890. struct mg_file_stat {
  1891. /* File properties filled by mg_stat: */
  1892. uint64_t size;
  1893. time_t last_modified;
  1894. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1895. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1896. * case we need a "Content-Eencoding: gzip" header */
  1897. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1898. };
  1899. struct mg_file_in_memory {
  1900. char *p;
  1901. uint32_t pos;
  1902. char mode;
  1903. };
  1904. struct mg_file_access {
  1905. /* File properties filled by mg_fopen: */
  1906. FILE *fp;
  1907. #if defined(MG_USE_OPEN_FILE)
  1908. /* TODO (low): Remove obsolete "file in memory" implementation.
  1909. * In an "early 2017" discussion at Google groups
  1910. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1911. * we decided to get rid of this feature (after some fade-out
  1912. * phase). */
  1913. const char *membuf;
  1914. #endif
  1915. };
  1916. struct mg_file {
  1917. struct mg_file_stat stat;
  1918. struct mg_file_access access;
  1919. };
  1920. #if defined(MG_USE_OPEN_FILE)
  1921. #define STRUCT_FILE_INITIALIZER \
  1922. { \
  1923. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1924. { \
  1925. (FILE *)NULL, (const char *)NULL \
  1926. } \
  1927. }
  1928. #else
  1929. #define STRUCT_FILE_INITIALIZER \
  1930. { \
  1931. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1932. { \
  1933. (FILE *)NULL \
  1934. } \
  1935. }
  1936. #endif
  1937. /* Describes listening socket, or socket which was accept()-ed by the master
  1938. * thread and queued for future handling by the worker thread. */
  1939. struct socket {
  1940. SOCKET sock; /* Listening socket */
  1941. union usa lsa; /* Local socket address */
  1942. union usa rsa; /* Remote socket address */
  1943. unsigned char is_ssl; /* Is port SSL-ed */
  1944. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1945. * port */
  1946. unsigned char in_use; /* Is valid */
  1947. };
  1948. /* Enum const for all options must be in sync with
  1949. * static struct mg_option config_options[]
  1950. * This is tested in the unit test (test/private.c)
  1951. * "Private Config Options"
  1952. */
  1953. enum {
  1954. /* Once for each server */
  1955. LISTENING_PORTS,
  1956. NUM_THREADS,
  1957. RUN_AS_USER,
  1958. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1959. * socket option typedef TCP_NODELAY. */
  1960. MAX_REQUEST_SIZE,
  1961. LINGER_TIMEOUT,
  1962. #if defined(__linux__)
  1963. ALLOW_SENDFILE_CALL,
  1964. #endif
  1965. #if defined(_WIN32)
  1966. CASE_SENSITIVE_FILES,
  1967. #endif
  1968. THROTTLE,
  1969. ACCESS_LOG_FILE,
  1970. ERROR_LOG_FILE,
  1971. ENABLE_KEEP_ALIVE,
  1972. REQUEST_TIMEOUT,
  1973. KEEP_ALIVE_TIMEOUT,
  1974. #if defined(USE_WEBSOCKET)
  1975. WEBSOCKET_TIMEOUT,
  1976. ENABLE_WEBSOCKET_PING_PONG,
  1977. #endif
  1978. DECODE_URL,
  1979. #if defined(USE_LUA)
  1980. LUA_BACKGROUND_SCRIPT,
  1981. LUA_BACKGROUND_SCRIPT_PARAMS,
  1982. #endif
  1983. #if defined(USE_TIMERS)
  1984. CGI_TIMEOUT,
  1985. #endif
  1986. /* Once for each domain */
  1987. DOCUMENT_ROOT,
  1988. CGI_EXTENSIONS,
  1989. CGI_ENVIRONMENT,
  1990. PUT_DELETE_PASSWORDS_FILE,
  1991. CGI_INTERPRETER,
  1992. PROTECT_URI,
  1993. AUTHENTICATION_DOMAIN,
  1994. ENABLE_AUTH_DOMAIN_CHECK,
  1995. SSI_EXTENSIONS,
  1996. ENABLE_DIRECTORY_LISTING,
  1997. GLOBAL_PASSWORDS_FILE,
  1998. INDEX_FILES,
  1999. ACCESS_CONTROL_LIST,
  2000. EXTRA_MIME_TYPES,
  2001. SSL_CERTIFICATE,
  2002. SSL_CERTIFICATE_CHAIN,
  2003. URL_REWRITE_PATTERN,
  2004. HIDE_FILES,
  2005. SSL_DO_VERIFY_PEER,
  2006. SSL_CA_PATH,
  2007. SSL_CA_FILE,
  2008. SSL_VERIFY_DEPTH,
  2009. SSL_DEFAULT_VERIFY_PATHS,
  2010. SSL_CIPHER_LIST,
  2011. SSL_PROTOCOL_VERSION,
  2012. SSL_SHORT_TRUST,
  2013. #if defined(USE_LUA)
  2014. LUA_PRELOAD_FILE,
  2015. LUA_SCRIPT_EXTENSIONS,
  2016. LUA_SERVER_PAGE_EXTENSIONS,
  2017. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2018. LUA_DEBUG_PARAMS,
  2019. #endif
  2020. #endif
  2021. #if defined(USE_DUKTAPE)
  2022. DUKTAPE_SCRIPT_EXTENSIONS,
  2023. #endif
  2024. #if defined(USE_WEBSOCKET)
  2025. WEBSOCKET_ROOT,
  2026. #endif
  2027. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2028. LUA_WEBSOCKET_EXTENSIONS,
  2029. #endif
  2030. ACCESS_CONTROL_ALLOW_ORIGIN,
  2031. ACCESS_CONTROL_ALLOW_METHODS,
  2032. ACCESS_CONTROL_ALLOW_HEADERS,
  2033. ERROR_PAGES,
  2034. #if !defined(NO_CACHING)
  2035. STATIC_FILE_MAX_AGE,
  2036. #endif
  2037. #if !defined(NO_SSL)
  2038. STRICT_HTTPS_MAX_AGE,
  2039. #endif
  2040. ADDITIONAL_HEADER,
  2041. ALLOW_INDEX_SCRIPT_SUB_RES,
  2042. NUM_OPTIONS
  2043. };
  2044. /* Config option name, config types, default value.
  2045. * Must be in the same order as the enum const above.
  2046. */
  2047. static const struct mg_option config_options[] = {
  2048. /* Once for each server */
  2049. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2050. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2051. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2052. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2053. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2054. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2055. #if defined(__linux__)
  2056. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2057. #endif
  2058. #if defined(_WIN32)
  2059. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2060. #endif
  2061. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2062. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2063. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2064. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2065. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2066. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2067. #if defined(USE_WEBSOCKET)
  2068. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2069. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2070. #endif
  2071. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2072. #if defined(USE_LUA)
  2073. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2074. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2075. #endif
  2076. #if defined(USE_TIMERS)
  2077. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2078. #endif
  2079. /* Once for each domain */
  2080. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2081. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2082. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2083. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2084. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2085. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2086. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2087. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2088. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2089. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2090. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2091. {"index_files",
  2092. MG_CONFIG_TYPE_STRING_LIST,
  2093. #if defined(USE_LUA)
  2094. "index.xhtml,index.html,index.htm,"
  2095. "index.lp,index.lsp,index.lua,index.cgi,"
  2096. "index.shtml,index.php"},
  2097. #else
  2098. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2099. #endif
  2100. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2101. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2102. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2103. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2104. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2105. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2106. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2107. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2108. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2109. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2110. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2111. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2112. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2113. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2114. #if defined(USE_LUA)
  2115. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2116. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2117. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2118. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2119. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2120. #endif
  2121. #endif
  2122. #if defined(USE_DUKTAPE)
  2123. /* The support for duktape is still in alpha version state.
  2124. * The name of this config option might change. */
  2125. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2126. #endif
  2127. #if defined(USE_WEBSOCKET)
  2128. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2129. #endif
  2130. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2131. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2132. #endif
  2133. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2134. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2135. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2136. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2137. #if !defined(NO_CACHING)
  2138. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2139. #endif
  2140. #if !defined(NO_SSL)
  2141. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2142. #endif
  2143. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2144. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2145. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2146. /* Check if the config_options and the corresponding enum have compatible
  2147. * sizes. */
  2148. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2149. == (NUM_OPTIONS + 1),
  2150. "config_options and enum not sync");
  2151. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2152. struct mg_handler_info {
  2153. /* Name/Pattern of the URI. */
  2154. char *uri;
  2155. size_t uri_len;
  2156. /* handler type */
  2157. int handler_type;
  2158. /* Handler for http/https or authorization requests. */
  2159. mg_request_handler handler;
  2160. unsigned int refcount;
  2161. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2162. pthread_cond_t
  2163. refcount_cond; /* Signaled when handler refcount is decremented */
  2164. /* Handler for ws/wss (websocket) requests. */
  2165. mg_websocket_connect_handler connect_handler;
  2166. mg_websocket_ready_handler ready_handler;
  2167. mg_websocket_data_handler data_handler;
  2168. mg_websocket_close_handler close_handler;
  2169. /* accepted subprotocols for ws/wss requests. */
  2170. struct mg_websocket_subprotocols *subprotocols;
  2171. /* Handler for authorization requests */
  2172. mg_authorization_handler auth_handler;
  2173. /* User supplied argument for the handler function. */
  2174. void *cbdata;
  2175. /* next handler in a linked list */
  2176. struct mg_handler_info *next;
  2177. };
  2178. enum {
  2179. CONTEXT_INVALID,
  2180. CONTEXT_SERVER,
  2181. CONTEXT_HTTP_CLIENT,
  2182. CONTEXT_WS_CLIENT
  2183. };
  2184. struct mg_domain_context {
  2185. SSL_CTX *ssl_ctx; /* SSL context */
  2186. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2187. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2188. /* Server nonce */
  2189. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2190. unsigned long nonce_count; /* Used nonces, used for authentication */
  2191. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2192. /* linked list of shared lua websockets */
  2193. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2194. #endif
  2195. /* Linked list of domains */
  2196. struct mg_domain_context *next;
  2197. };
  2198. struct mg_context {
  2199. /* Part 1 - Physical context:
  2200. * This holds threads, ports, timeouts, ...
  2201. * set for the entire server, independent from the
  2202. * addressed hostname.
  2203. */
  2204. /* Connection related */
  2205. int context_type; /* See CONTEXT_* above */
  2206. struct socket *listening_sockets;
  2207. struct pollfd *listening_socket_fds;
  2208. unsigned int num_listening_sockets;
  2209. struct mg_connection *worker_connections; /* The connection struct, pre-
  2210. * allocated for each worker */
  2211. #if defined(USE_SERVER_STATS)
  2212. int active_connections;
  2213. int max_connections;
  2214. int64_t total_connections;
  2215. int64_t total_requests;
  2216. int64_t total_data_read;
  2217. int64_t total_data_written;
  2218. #endif
  2219. /* Thread related */
  2220. volatile int stop_flag; /* Should we stop event loop */
  2221. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2222. pthread_t masterthreadid; /* The master thread ID */
  2223. unsigned int
  2224. cfg_worker_threads; /* The number of configured worker threads. */
  2225. pthread_t *worker_threadids; /* The worker thread IDs */
  2226. /* Connection to thread dispatching */
  2227. #if defined(ALTERNATIVE_QUEUE)
  2228. struct socket *client_socks;
  2229. void **client_wait_events;
  2230. #else
  2231. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2232. volatile int sq_head; /* Head of the socket queue */
  2233. volatile int sq_tail; /* Tail of the socket queue */
  2234. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2235. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2236. #endif
  2237. /* Memory related */
  2238. unsigned int max_request_size; /* The max request size */
  2239. #if defined(USE_SERVER_STATS)
  2240. struct mg_memory_stat ctx_memory;
  2241. #endif
  2242. /* Operating system related */
  2243. char *systemName; /* What operating system is running */
  2244. time_t start_time; /* Server start time, used for authentication
  2245. * and for diagnstics. */
  2246. #if defined(USE_TIMERS)
  2247. struct ttimers *timers;
  2248. #endif
  2249. /* Lua specific: Background operations and shared websockets */
  2250. #if defined(USE_LUA)
  2251. void *lua_background_state;
  2252. #endif
  2253. /* Server nonce */
  2254. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2255. /* Server callbacks */
  2256. struct mg_callbacks callbacks; /* User-defined callback function */
  2257. void *user_data; /* User-defined data */
  2258. /* Part 2 - Logical domain:
  2259. * This holds hostname, TLS certificate, document root, ...
  2260. * set for a domain hosted at the server.
  2261. * There may be multiple domains hosted at one physical server.
  2262. * The default domain "dd" is the first element of a list of
  2263. * domains.
  2264. */
  2265. struct mg_domain_context dd; /* default domain */
  2266. };
  2267. #if defined(USE_SERVER_STATS)
  2268. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2269. static struct mg_memory_stat *
  2270. get_memory_stat(struct mg_context *ctx)
  2271. {
  2272. if (ctx) {
  2273. return &(ctx->ctx_memory);
  2274. }
  2275. return &mg_common_memory;
  2276. }
  2277. #endif
  2278. enum {
  2279. CONNECTION_TYPE_INVALID,
  2280. CONNECTION_TYPE_REQUEST,
  2281. CONNECTION_TYPE_RESPONSE
  2282. };
  2283. struct mg_connection {
  2284. int connection_type; /* see CONNECTION_TYPE_* above */
  2285. struct mg_request_info request_info;
  2286. struct mg_response_info response_info;
  2287. struct mg_context *phys_ctx;
  2288. struct mg_domain_context *dom_ctx;
  2289. #if defined(USE_SERVER_STATS)
  2290. int conn_state; /* 0 = undef, numerical value may change in different
  2291. * versions. For the current definition, see
  2292. * mg_get_connection_info_impl */
  2293. #endif
  2294. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2295. SSL *ssl; /* SSL descriptor */
  2296. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2297. struct socket client; /* Connected client */
  2298. time_t conn_birth_time; /* Time (wall clock) when connection was
  2299. * established */
  2300. struct timespec req_time; /* Time (since system start) when the request
  2301. * was received */
  2302. int64_t num_bytes_sent; /* Total bytes sent to client */
  2303. int64_t content_len; /* Content-Length header value */
  2304. int64_t consumed_content; /* How many bytes of content have been read */
  2305. int is_chunked; /* Transfer-Encoding is chunked:
  2306. * 0 = not chunked,
  2307. * 1 = chunked, do data read yet,
  2308. * 2 = chunked, some data read,
  2309. * 3 = chunked, all data read
  2310. */
  2311. size_t chunk_remainder; /* Unread data from the last chunk */
  2312. char *buf; /* Buffer for received data */
  2313. char *path_info; /* PATH_INFO part of the URL */
  2314. int must_close; /* 1 if connection must be closed */
  2315. int accept_gzip; /* 1 if gzip encoding is accepted */
  2316. int in_error_handler; /* 1 if in handler for user defined error
  2317. * pages */
  2318. #if defined(USE_WEBSOCKET)
  2319. int in_websocket_handling; /* 1 if in read_websocket */
  2320. #endif
  2321. int handled_requests; /* Number of requests handled by this connection
  2322. */
  2323. int buf_size; /* Buffer size */
  2324. int request_len; /* Size of the request + headers in a buffer */
  2325. int data_len; /* Total size of data in a buffer */
  2326. int status_code; /* HTTP reply status code, e.g. 200 */
  2327. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2328. * throttle */
  2329. time_t last_throttle_time; /* Last time throttled data was sent */
  2330. int64_t last_throttle_bytes; /* Bytes sent this second */
  2331. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2332. * atomic transmissions for websockets */
  2333. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2334. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2335. #endif
  2336. int thread_index; /* Thread index within ctx */
  2337. };
  2338. /* Directory entry */
  2339. struct de {
  2340. struct mg_connection *conn;
  2341. char *file_name;
  2342. struct mg_file_stat file;
  2343. };
  2344. #if defined(USE_WEBSOCKET)
  2345. static int is_websocket_protocol(const struct mg_connection *conn);
  2346. #else
  2347. #define is_websocket_protocol(conn) (0)
  2348. #endif
  2349. #define mg_cry_internal(conn, fmt, ...) \
  2350. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2351. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2352. const char *func,
  2353. unsigned line,
  2354. const char *fmt,
  2355. ...) PRINTF_ARGS(4, 5);
  2356. #if !defined(NO_THREAD_NAME)
  2357. #if defined(_WIN32) && defined(_MSC_VER)
  2358. /* Set the thread name for debugging purposes in Visual Studio
  2359. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2360. */
  2361. #pragma pack(push, 8)
  2362. typedef struct tagTHREADNAME_INFO {
  2363. DWORD dwType; /* Must be 0x1000. */
  2364. LPCSTR szName; /* Pointer to name (in user addr space). */
  2365. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2366. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2367. } THREADNAME_INFO;
  2368. #pragma pack(pop)
  2369. #elif defined(__linux__)
  2370. #include <sys/prctl.h>
  2371. #include <sys/sendfile.h>
  2372. #if defined(ALTERNATIVE_QUEUE)
  2373. #include <sys/eventfd.h>
  2374. #endif /* ALTERNATIVE_QUEUE */
  2375. #if defined(ALTERNATIVE_QUEUE)
  2376. static void *
  2377. event_create(void)
  2378. {
  2379. int evhdl = eventfd(0, EFD_CLOEXEC);
  2380. int *ret;
  2381. if (evhdl == -1) {
  2382. /* Linux uses -1 on error, Windows NULL. */
  2383. /* However, Linux does not return 0 on success either. */
  2384. return 0;
  2385. }
  2386. ret = (int *)mg_malloc(sizeof(int));
  2387. if (ret) {
  2388. *ret = evhdl;
  2389. } else {
  2390. (void)close(evhdl);
  2391. }
  2392. return (void *)ret;
  2393. }
  2394. static int
  2395. event_wait(void *eventhdl)
  2396. {
  2397. uint64_t u;
  2398. int evhdl, s;
  2399. if (!eventhdl) {
  2400. /* error */
  2401. return 0;
  2402. }
  2403. evhdl = *(int *)eventhdl;
  2404. s = (int)read(evhdl, &u, sizeof(u));
  2405. if (s != sizeof(u)) {
  2406. /* error */
  2407. return 0;
  2408. }
  2409. (void)u; /* the value is not required */
  2410. return 1;
  2411. }
  2412. static int
  2413. event_signal(void *eventhdl)
  2414. {
  2415. uint64_t u = 1;
  2416. int evhdl, s;
  2417. if (!eventhdl) {
  2418. /* error */
  2419. return 0;
  2420. }
  2421. evhdl = *(int *)eventhdl;
  2422. s = (int)write(evhdl, &u, sizeof(u));
  2423. if (s != sizeof(u)) {
  2424. /* error */
  2425. return 0;
  2426. }
  2427. return 1;
  2428. }
  2429. static void
  2430. event_destroy(void *eventhdl)
  2431. {
  2432. int evhdl;
  2433. if (!eventhdl) {
  2434. /* error */
  2435. return;
  2436. }
  2437. evhdl = *(int *)eventhdl;
  2438. close(evhdl);
  2439. mg_free(eventhdl);
  2440. }
  2441. #endif
  2442. #endif
  2443. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2444. struct posix_event {
  2445. pthread_mutex_t mutex;
  2446. pthread_cond_t cond;
  2447. };
  2448. static void *
  2449. event_create(void)
  2450. {
  2451. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2452. if (ret == 0) {
  2453. /* out of memory */
  2454. return 0;
  2455. }
  2456. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2457. /* pthread mutex not available */
  2458. mg_free(ret);
  2459. return 0;
  2460. }
  2461. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2462. /* pthread cond not available */
  2463. pthread_mutex_destroy(&(ret->mutex));
  2464. mg_free(ret);
  2465. return 0;
  2466. }
  2467. return (void *)ret;
  2468. }
  2469. static int
  2470. event_wait(void *eventhdl)
  2471. {
  2472. struct posix_event *ev = (struct posix_event *)eventhdl;
  2473. pthread_mutex_lock(&(ev->mutex));
  2474. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2475. pthread_mutex_unlock(&(ev->mutex));
  2476. return 1;
  2477. }
  2478. static int
  2479. event_signal(void *eventhdl)
  2480. {
  2481. struct posix_event *ev = (struct posix_event *)eventhdl;
  2482. pthread_mutex_lock(&(ev->mutex));
  2483. pthread_cond_signal(&(ev->cond));
  2484. pthread_mutex_unlock(&(ev->mutex));
  2485. return 1;
  2486. }
  2487. static void
  2488. event_destroy(void *eventhdl)
  2489. {
  2490. struct posix_event *ev = (struct posix_event *)eventhdl;
  2491. pthread_cond_destroy(&(ev->cond));
  2492. pthread_mutex_destroy(&(ev->mutex));
  2493. mg_free(ev);
  2494. }
  2495. #endif
  2496. static void
  2497. mg_set_thread_name(const char *name)
  2498. {
  2499. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2500. mg_snprintf(
  2501. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2502. #if defined(_WIN32)
  2503. #if defined(_MSC_VER)
  2504. /* Windows and Visual Studio Compiler */
  2505. __try {
  2506. THREADNAME_INFO info;
  2507. info.dwType = 0x1000;
  2508. info.szName = threadName;
  2509. info.dwThreadID = ~0U;
  2510. info.dwFlags = 0;
  2511. RaiseException(0x406D1388,
  2512. 0,
  2513. sizeof(info) / sizeof(ULONG_PTR),
  2514. (ULONG_PTR *)&info);
  2515. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2516. }
  2517. #elif defined(__MINGW32__)
  2518. /* No option known to set thread name for MinGW */
  2519. #endif
  2520. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2521. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2522. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2523. #if defined(__MACH__)
  2524. /* OS X only current thread name can be changed */
  2525. (void)pthread_setname_np(threadName);
  2526. #else
  2527. (void)pthread_setname_np(pthread_self(), threadName);
  2528. #endif
  2529. #elif defined(__linux__)
  2530. /* on linux we can use the old prctl function */
  2531. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2532. #endif
  2533. }
  2534. #else /* !defined(NO_THREAD_NAME) */
  2535. void
  2536. mg_set_thread_name(const char *threadName)
  2537. {
  2538. }
  2539. #endif
  2540. #if defined(MG_LEGACY_INTERFACE)
  2541. const char **
  2542. mg_get_valid_option_names(void)
  2543. {
  2544. /* This function is deprecated. Use mg_get_valid_options instead. */
  2545. static const char
  2546. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2547. int i;
  2548. for (i = 0; config_options[i].name != NULL; i++) {
  2549. data[i * 2] = config_options[i].name;
  2550. data[i * 2 + 1] = config_options[i].default_value;
  2551. }
  2552. return data;
  2553. }
  2554. #endif
  2555. const struct mg_option *
  2556. mg_get_valid_options(void)
  2557. {
  2558. return config_options;
  2559. }
  2560. /* Do not open file (used in is_file_in_memory) */
  2561. #define MG_FOPEN_MODE_NONE (0)
  2562. /* Open file for read only access */
  2563. #define MG_FOPEN_MODE_READ (1)
  2564. /* Open file for writing, create and overwrite */
  2565. #define MG_FOPEN_MODE_WRITE (2)
  2566. /* Open file for writing, create and append */
  2567. #define MG_FOPEN_MODE_APPEND (4)
  2568. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2569. * output filep and return 1, otherwise return 0 and don't modify anything.
  2570. */
  2571. static int
  2572. open_file_in_memory(const struct mg_connection *conn,
  2573. const char *path,
  2574. struct mg_file *filep,
  2575. int mode)
  2576. {
  2577. #if defined(MG_USE_OPEN_FILE)
  2578. size_t size = 0;
  2579. const char *buf = NULL;
  2580. if (!conn) {
  2581. return 0;
  2582. }
  2583. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2584. return 0;
  2585. }
  2586. if (conn->phys_ctx->callbacks.open_file) {
  2587. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2588. if (buf != NULL) {
  2589. if (filep == NULL) {
  2590. /* This is a file in memory, but we cannot store the
  2591. * properties
  2592. * now.
  2593. * Called from "is_file_in_memory" function. */
  2594. return 1;
  2595. }
  2596. /* NOTE: override filep->size only on success. Otherwise, it
  2597. * might
  2598. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2599. filep->access.membuf = buf;
  2600. filep->access.fp = NULL;
  2601. /* Size was set by the callback */
  2602. filep->stat.size = size;
  2603. /* Assume the data may change during runtime by setting
  2604. * last_modified = now */
  2605. filep->stat.last_modified = time(NULL);
  2606. filep->stat.is_directory = 0;
  2607. filep->stat.is_gzipped = 0;
  2608. }
  2609. }
  2610. return (buf != NULL);
  2611. #else
  2612. (void)conn;
  2613. (void)path;
  2614. (void)filep;
  2615. (void)mode;
  2616. return 0;
  2617. #endif
  2618. }
  2619. static int
  2620. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2621. {
  2622. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2623. }
  2624. static int
  2625. is_file_opened(const struct mg_file_access *fileacc)
  2626. {
  2627. if (!fileacc) {
  2628. return 0;
  2629. }
  2630. #if defined(MG_USE_OPEN_FILE)
  2631. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2632. #else
  2633. return (fileacc->fp != NULL);
  2634. #endif
  2635. }
  2636. static int mg_stat(const struct mg_connection *conn,
  2637. const char *path,
  2638. struct mg_file_stat *filep);
  2639. /* mg_fopen will open a file either in memory or on the disk.
  2640. * The input parameter path is a string in UTF-8 encoding.
  2641. * The input parameter mode is MG_FOPEN_MODE_*
  2642. * On success, either fp or membuf will be set in the output
  2643. * struct file. All status members will also be set.
  2644. * The function returns 1 on success, 0 on error. */
  2645. static int
  2646. mg_fopen(const struct mg_connection *conn,
  2647. const char *path,
  2648. int mode,
  2649. struct mg_file *filep)
  2650. {
  2651. int found;
  2652. if (!filep) {
  2653. return 0;
  2654. }
  2655. filep->access.fp = NULL;
  2656. #if defined(MG_USE_OPEN_FILE)
  2657. filep->access.membuf = NULL;
  2658. #endif
  2659. if (!is_file_in_memory(conn, path)) {
  2660. /* filep is initialized in mg_stat: all fields with memset to,
  2661. * some fields like size and modification date with values */
  2662. found = mg_stat(conn, path, &(filep->stat));
  2663. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2664. /* file does not exist and will not be created */
  2665. return 0;
  2666. }
  2667. #if defined(_WIN32)
  2668. {
  2669. wchar_t wbuf[W_PATH_MAX];
  2670. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2671. switch (mode) {
  2672. case MG_FOPEN_MODE_READ:
  2673. filep->access.fp = _wfopen(wbuf, L"rb");
  2674. break;
  2675. case MG_FOPEN_MODE_WRITE:
  2676. filep->access.fp = _wfopen(wbuf, L"wb");
  2677. break;
  2678. case MG_FOPEN_MODE_APPEND:
  2679. filep->access.fp = _wfopen(wbuf, L"ab");
  2680. break;
  2681. }
  2682. }
  2683. #else
  2684. /* Linux et al already use unicode. No need to convert. */
  2685. switch (mode) {
  2686. case MG_FOPEN_MODE_READ:
  2687. filep->access.fp = fopen(path, "r");
  2688. break;
  2689. case MG_FOPEN_MODE_WRITE:
  2690. filep->access.fp = fopen(path, "w");
  2691. break;
  2692. case MG_FOPEN_MODE_APPEND:
  2693. filep->access.fp = fopen(path, "a");
  2694. break;
  2695. }
  2696. #endif
  2697. if (!found) {
  2698. /* File did not exist before fopen was called.
  2699. * Maybe it has been created now. Get stat info
  2700. * like creation time now. */
  2701. found = mg_stat(conn, path, &(filep->stat));
  2702. (void)found;
  2703. }
  2704. /* file is on disk */
  2705. return (filep->access.fp != NULL);
  2706. } else {
  2707. #if defined(MG_USE_OPEN_FILE)
  2708. /* is_file_in_memory returned true */
  2709. if (open_file_in_memory(conn, path, filep, mode)) {
  2710. /* file is in memory */
  2711. return (filep->access.membuf != NULL);
  2712. }
  2713. #endif
  2714. }
  2715. /* Open failed */
  2716. return 0;
  2717. }
  2718. /* return 0 on success, just like fclose */
  2719. static int
  2720. mg_fclose(struct mg_file_access *fileacc)
  2721. {
  2722. int ret = -1;
  2723. if (fileacc != NULL) {
  2724. if (fileacc->fp != NULL) {
  2725. ret = fclose(fileacc->fp);
  2726. #if defined(MG_USE_OPEN_FILE)
  2727. } else if (fileacc->membuf != NULL) {
  2728. ret = 0;
  2729. #endif
  2730. }
  2731. /* reset all members of fileacc */
  2732. memset(fileacc, 0, sizeof(*fileacc));
  2733. }
  2734. return ret;
  2735. }
  2736. static void
  2737. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2738. {
  2739. for (; *src != '\0' && n > 1; n--) {
  2740. *dst++ = *src++;
  2741. }
  2742. *dst = '\0';
  2743. }
  2744. static int
  2745. lowercase(const char *s)
  2746. {
  2747. return tolower(*(const unsigned char *)s);
  2748. }
  2749. int
  2750. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2751. {
  2752. int diff = 0;
  2753. if (len > 0) {
  2754. do {
  2755. diff = lowercase(s1++) - lowercase(s2++);
  2756. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2757. }
  2758. return diff;
  2759. }
  2760. int
  2761. mg_strcasecmp(const char *s1, const char *s2)
  2762. {
  2763. int diff;
  2764. do {
  2765. diff = lowercase(s1++) - lowercase(s2++);
  2766. } while (diff == 0 && s1[-1] != '\0');
  2767. return diff;
  2768. }
  2769. static char *
  2770. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2771. {
  2772. char *p;
  2773. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2774. * defined */
  2775. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2776. mg_strlcpy(p, ptr, len + 1);
  2777. }
  2778. return p;
  2779. }
  2780. static char *
  2781. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2782. {
  2783. return mg_strndup_ctx(str, strlen(str), ctx);
  2784. }
  2785. static char *
  2786. mg_strdup(const char *str)
  2787. {
  2788. return mg_strndup_ctx(str, strlen(str), NULL);
  2789. }
  2790. static const char *
  2791. mg_strcasestr(const char *big_str, const char *small_str)
  2792. {
  2793. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2794. if (big_len >= small_len) {
  2795. for (i = 0; i <= (big_len - small_len); i++) {
  2796. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2797. return big_str + i;
  2798. }
  2799. }
  2800. }
  2801. return NULL;
  2802. }
  2803. /* Return null terminated string of given maximum length.
  2804. * Report errors if length is exceeded. */
  2805. static void
  2806. mg_vsnprintf(const struct mg_connection *conn,
  2807. int *truncated,
  2808. char *buf,
  2809. size_t buflen,
  2810. const char *fmt,
  2811. va_list ap)
  2812. {
  2813. int n, ok;
  2814. if (buflen == 0) {
  2815. if (truncated) {
  2816. *truncated = 1;
  2817. }
  2818. return;
  2819. }
  2820. #if defined(__clang__)
  2821. #pragma clang diagnostic push
  2822. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2823. /* Using fmt as a non-literal is intended here, since it is mostly called
  2824. * indirectly by mg_snprintf */
  2825. #endif
  2826. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2827. ok = (n >= 0) && ((size_t)n < buflen);
  2828. #if defined(__clang__)
  2829. #pragma clang diagnostic pop
  2830. #endif
  2831. if (ok) {
  2832. if (truncated) {
  2833. *truncated = 0;
  2834. }
  2835. } else {
  2836. if (truncated) {
  2837. *truncated = 1;
  2838. }
  2839. mg_cry_internal(conn,
  2840. "truncating vsnprintf buffer: [%.*s]",
  2841. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2842. buf);
  2843. n = (int)buflen - 1;
  2844. }
  2845. buf[n] = '\0';
  2846. }
  2847. static void
  2848. mg_snprintf(const struct mg_connection *conn,
  2849. int *truncated,
  2850. char *buf,
  2851. size_t buflen,
  2852. const char *fmt,
  2853. ...)
  2854. {
  2855. va_list ap;
  2856. va_start(ap, fmt);
  2857. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2858. va_end(ap);
  2859. }
  2860. static int
  2861. get_option_index(const char *name)
  2862. {
  2863. int i;
  2864. for (i = 0; config_options[i].name != NULL; i++) {
  2865. if (strcmp(config_options[i].name, name) == 0) {
  2866. return i;
  2867. }
  2868. }
  2869. return -1;
  2870. }
  2871. const char *
  2872. mg_get_option(const struct mg_context *ctx, const char *name)
  2873. {
  2874. int i;
  2875. if ((i = get_option_index(name)) == -1) {
  2876. return NULL;
  2877. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2878. return "";
  2879. } else {
  2880. return ctx->dd.config[i];
  2881. }
  2882. }
  2883. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2884. struct mg_context *
  2885. mg_get_context(const struct mg_connection *conn)
  2886. {
  2887. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2888. }
  2889. void *
  2890. mg_get_user_data(const struct mg_context *ctx)
  2891. {
  2892. return (ctx == NULL) ? NULL : ctx->user_data;
  2893. }
  2894. void
  2895. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2896. {
  2897. if (conn != NULL) {
  2898. conn->request_info.conn_data = data;
  2899. }
  2900. }
  2901. void *
  2902. mg_get_user_connection_data(const struct mg_connection *conn)
  2903. {
  2904. if (conn != NULL) {
  2905. return conn->request_info.conn_data;
  2906. }
  2907. return NULL;
  2908. }
  2909. #if defined(MG_LEGACY_INTERFACE)
  2910. /* Deprecated: Use mg_get_server_ports instead. */
  2911. size_t
  2912. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2913. {
  2914. size_t i;
  2915. if (!ctx) {
  2916. return 0;
  2917. }
  2918. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2919. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2920. ports[i] =
  2921. #if defined(USE_IPV6)
  2922. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2923. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2924. :
  2925. #endif
  2926. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2927. }
  2928. return i;
  2929. }
  2930. #endif
  2931. int
  2932. mg_get_server_ports(const struct mg_context *ctx,
  2933. int size,
  2934. struct mg_server_ports *ports)
  2935. {
  2936. int i, cnt = 0;
  2937. if (size <= 0) {
  2938. return -1;
  2939. }
  2940. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2941. if (!ctx) {
  2942. return -1;
  2943. }
  2944. if (!ctx->listening_sockets) {
  2945. return -1;
  2946. }
  2947. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2948. ports[cnt].port =
  2949. #if defined(USE_IPV6)
  2950. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2951. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2952. :
  2953. #endif
  2954. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2955. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2956. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2957. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2958. /* IPv4 */
  2959. ports[cnt].protocol = 1;
  2960. cnt++;
  2961. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2962. /* IPv6 */
  2963. ports[cnt].protocol = 3;
  2964. cnt++;
  2965. }
  2966. }
  2967. return cnt;
  2968. }
  2969. static void
  2970. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2971. {
  2972. buf[0] = '\0';
  2973. if (!usa) {
  2974. return;
  2975. }
  2976. if (usa->sa.sa_family == AF_INET) {
  2977. getnameinfo(&usa->sa,
  2978. sizeof(usa->sin),
  2979. buf,
  2980. (unsigned)len,
  2981. NULL,
  2982. 0,
  2983. NI_NUMERICHOST);
  2984. }
  2985. #if defined(USE_IPV6)
  2986. else if (usa->sa.sa_family == AF_INET6) {
  2987. getnameinfo(&usa->sa,
  2988. sizeof(usa->sin6),
  2989. buf,
  2990. (unsigned)len,
  2991. NULL,
  2992. 0,
  2993. NI_NUMERICHOST);
  2994. }
  2995. #endif
  2996. }
  2997. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2998. * included in all responses other than 100, 101, 5xx. */
  2999. static void
  3000. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3001. {
  3002. #if !defined(REENTRANT_TIME)
  3003. struct tm *tm;
  3004. tm = ((t != NULL) ? gmtime(t) : NULL);
  3005. if (tm != NULL) {
  3006. #else
  3007. struct tm _tm;
  3008. struct tm *tm = &_tm;
  3009. if (t != NULL) {
  3010. gmtime_r(t, tm);
  3011. #endif
  3012. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3013. } else {
  3014. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3015. buf[buf_len - 1] = '\0';
  3016. }
  3017. }
  3018. /* difftime for struct timespec. Return value is in seconds. */
  3019. static double
  3020. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3021. {
  3022. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3023. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3024. }
  3025. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3026. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3027. const char *func,
  3028. unsigned line,
  3029. const char *fmt,
  3030. va_list ap);
  3031. #include "external_mg_cry_internal_impl.inl"
  3032. #else
  3033. /* Print error message to the opened error log stream. */
  3034. static void
  3035. mg_cry_internal_impl(const struct mg_connection *conn,
  3036. const char *func,
  3037. unsigned line,
  3038. const char *fmt,
  3039. va_list ap)
  3040. {
  3041. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3042. struct mg_file fi;
  3043. time_t timestamp;
  3044. /* Unused, in the RELEASE build */
  3045. (void)func;
  3046. (void)line;
  3047. #if defined(GCC_DIAGNOSTIC)
  3048. #pragma GCC diagnostic push
  3049. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3050. #endif
  3051. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3052. #if defined(GCC_DIAGNOSTIC)
  3053. #pragma GCC diagnostic pop
  3054. #endif
  3055. buf[sizeof(buf) - 1] = 0;
  3056. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3057. if (!conn) {
  3058. puts(buf);
  3059. return;
  3060. }
  3061. /* Do not lock when getting the callback value, here and below.
  3062. * I suppose this is fine, since function cannot disappear in the
  3063. * same way string option can. */
  3064. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3065. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3066. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3067. if (mg_fopen(conn,
  3068. conn->dom_ctx->config[ERROR_LOG_FILE],
  3069. MG_FOPEN_MODE_APPEND,
  3070. &fi)
  3071. == 0) {
  3072. fi.access.fp = NULL;
  3073. }
  3074. } else {
  3075. fi.access.fp = NULL;
  3076. }
  3077. if (fi.access.fp != NULL) {
  3078. flockfile(fi.access.fp);
  3079. timestamp = time(NULL);
  3080. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3081. fprintf(fi.access.fp,
  3082. "[%010lu] [error] [client %s] ",
  3083. (unsigned long)timestamp,
  3084. src_addr);
  3085. if (conn->request_info.request_method != NULL) {
  3086. fprintf(fi.access.fp,
  3087. "%s %s: ",
  3088. conn->request_info.request_method,
  3089. conn->request_info.request_uri
  3090. ? conn->request_info.request_uri
  3091. : "");
  3092. }
  3093. fprintf(fi.access.fp, "%s", buf);
  3094. fputc('\n', fi.access.fp);
  3095. fflush(fi.access.fp);
  3096. funlockfile(fi.access.fp);
  3097. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3098. * mg_cry here anyway ;-) */
  3099. }
  3100. }
  3101. }
  3102. #endif /* Externally provided function */
  3103. static void
  3104. mg_cry_internal_wrap(const struct mg_connection *conn,
  3105. const char *func,
  3106. unsigned line,
  3107. const char *fmt,
  3108. ...)
  3109. {
  3110. va_list ap;
  3111. va_start(ap, fmt);
  3112. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3113. va_end(ap);
  3114. }
  3115. void
  3116. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3117. {
  3118. va_list ap;
  3119. va_start(ap, fmt);
  3120. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3121. va_end(ap);
  3122. }
  3123. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3124. /* Return fake connection structure. Used for logging, if connection
  3125. * is not applicable at the moment of logging. */
  3126. static struct mg_connection *
  3127. fc(struct mg_context *ctx)
  3128. {
  3129. static struct mg_connection fake_connection;
  3130. fake_connection.phys_ctx = ctx;
  3131. fake_connection.dom_ctx = &(ctx->dd);
  3132. return &fake_connection;
  3133. }
  3134. const char *
  3135. mg_version(void)
  3136. {
  3137. return CIVETWEB_VERSION;
  3138. }
  3139. const struct mg_request_info *
  3140. mg_get_request_info(const struct mg_connection *conn)
  3141. {
  3142. if (!conn) {
  3143. return NULL;
  3144. }
  3145. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3146. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3147. char txt[16];
  3148. struct mg_workerTLS *tls =
  3149. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3150. sprintf(txt, "%03i", conn->response_info.status_code);
  3151. if (strlen(txt) == 3) {
  3152. memcpy(tls->txtbuf, txt, 4);
  3153. } else {
  3154. strcpy(tls->txtbuf, "ERR");
  3155. }
  3156. ((struct mg_connection *)conn)->request_info.local_uri =
  3157. ((struct mg_connection *)conn)->request_info.request_uri =
  3158. tls->txtbuf; /* use thread safe buffer */
  3159. ((struct mg_connection *)conn)->request_info.num_headers =
  3160. conn->response_info.num_headers;
  3161. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3162. conn->response_info.http_headers,
  3163. sizeof(conn->response_info.http_headers));
  3164. } else
  3165. #endif
  3166. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3167. return NULL;
  3168. }
  3169. return &conn->request_info;
  3170. }
  3171. const struct mg_response_info *
  3172. mg_get_response_info(const struct mg_connection *conn)
  3173. {
  3174. if (!conn) {
  3175. return NULL;
  3176. }
  3177. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3178. return NULL;
  3179. }
  3180. return &conn->response_info;
  3181. }
  3182. static const char *
  3183. get_proto_name(const struct mg_connection *conn)
  3184. {
  3185. #if defined(__clang__)
  3186. #pragma clang diagnostic push
  3187. #pragma clang diagnostic ignored "-Wunreachable-code"
  3188. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3189. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3190. * unreachable, but splitting into four different #ifdef clauses here is more
  3191. * complicated.
  3192. */
  3193. #endif
  3194. const struct mg_request_info *ri = &conn->request_info;
  3195. const char *proto =
  3196. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3197. : (ri->is_ssl ? "https" : "http"));
  3198. return proto;
  3199. #if defined(__clang__)
  3200. #pragma clang diagnostic pop
  3201. #endif
  3202. }
  3203. int
  3204. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3205. {
  3206. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3207. return -1;
  3208. } else {
  3209. int truncated = 0;
  3210. const struct mg_request_info *ri = &conn->request_info;
  3211. const char *proto = get_proto_name(conn);
  3212. if (ri->local_uri == NULL) {
  3213. return -1;
  3214. }
  3215. if ((ri->request_uri != NULL)
  3216. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3217. /* The request uri is different from the local uri.
  3218. * This is usually if an absolute URI, including server
  3219. * name has been provided. */
  3220. mg_snprintf(conn,
  3221. &truncated,
  3222. buf,
  3223. buflen,
  3224. "%s://%s",
  3225. proto,
  3226. ri->request_uri);
  3227. if (truncated) {
  3228. return -1;
  3229. }
  3230. return 0;
  3231. } else {
  3232. /* The common case is a relative URI, so we have to
  3233. * construct an absolute URI from server name and port */
  3234. #if defined(USE_IPV6)
  3235. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3236. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3237. : htons(conn->client.lsa.sin.sin_port);
  3238. #else
  3239. int port = htons(conn->client.lsa.sin.sin_port);
  3240. #endif
  3241. int def_port = ri->is_ssl ? 443 : 80;
  3242. int auth_domain_check_enabled =
  3243. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3244. && (!mg_strcasecmp(
  3245. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3246. const char *server_domain =
  3247. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3248. char portstr[16];
  3249. char server_ip[48];
  3250. if (port != def_port) {
  3251. sprintf(portstr, ":%u", (unsigned)port);
  3252. } else {
  3253. portstr[0] = 0;
  3254. }
  3255. if (!auth_domain_check_enabled || !server_domain) {
  3256. sockaddr_to_string(server_ip,
  3257. sizeof(server_ip),
  3258. &conn->client.lsa);
  3259. server_domain = server_ip;
  3260. }
  3261. mg_snprintf(conn,
  3262. &truncated,
  3263. buf,
  3264. buflen,
  3265. "%s://%s%s%s",
  3266. proto,
  3267. server_domain,
  3268. portstr,
  3269. ri->local_uri);
  3270. if (truncated) {
  3271. return -1;
  3272. }
  3273. return 0;
  3274. }
  3275. }
  3276. }
  3277. /* Skip the characters until one of the delimiters characters found.
  3278. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3279. * Advance pointer to buffer to the next word. Return found 0-terminated
  3280. * word.
  3281. * Delimiters can be quoted with quotechar. */
  3282. static char *
  3283. skip_quoted(char **buf,
  3284. const char *delimiters,
  3285. const char *whitespace,
  3286. char quotechar)
  3287. {
  3288. char *p, *begin_word, *end_word, *end_whitespace;
  3289. begin_word = *buf;
  3290. end_word = begin_word + strcspn(begin_word, delimiters);
  3291. /* Check for quotechar */
  3292. if (end_word > begin_word) {
  3293. p = end_word - 1;
  3294. while (*p == quotechar) {
  3295. /* While the delimiter is quoted, look for the next delimiter.
  3296. */
  3297. /* This happens, e.g., in calls from parse_auth_header,
  3298. * if the user name contains a " character. */
  3299. /* If there is anything beyond end_word, copy it. */
  3300. if (*end_word != '\0') {
  3301. size_t end_off = strcspn(end_word + 1, delimiters);
  3302. memmove(p, end_word, end_off + 1);
  3303. p += end_off; /* p must correspond to end_word - 1 */
  3304. end_word += end_off + 1;
  3305. } else {
  3306. *p = '\0';
  3307. break;
  3308. }
  3309. }
  3310. for (p++; p < end_word; p++) {
  3311. *p = '\0';
  3312. }
  3313. }
  3314. if (*end_word == '\0') {
  3315. *buf = end_word;
  3316. } else {
  3317. #if defined(GCC_DIAGNOSTIC)
  3318. /* Disable spurious conversion warning for GCC */
  3319. #pragma GCC diagnostic push
  3320. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3321. #endif /* defined(GCC_DIAGNOSTIC) */
  3322. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3323. #if defined(GCC_DIAGNOSTIC)
  3324. #pragma GCC diagnostic pop
  3325. #endif /* defined(GCC_DIAGNOSTIC) */
  3326. for (p = end_word; p < end_whitespace; p++) {
  3327. *p = '\0';
  3328. }
  3329. *buf = end_whitespace;
  3330. }
  3331. return begin_word;
  3332. }
  3333. /* Return HTTP header value, or NULL if not found. */
  3334. static const char *
  3335. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3336. {
  3337. int i;
  3338. for (i = 0; i < num_hdr; i++) {
  3339. if (!mg_strcasecmp(name, hdr[i].name)) {
  3340. return hdr[i].value;
  3341. }
  3342. }
  3343. return NULL;
  3344. }
  3345. #if defined(USE_WEBSOCKET)
  3346. /* Retrieve requested HTTP header multiple values, and return the number of
  3347. * found occurrences */
  3348. static int
  3349. get_req_headers(const struct mg_request_info *ri,
  3350. const char *name,
  3351. const char **output,
  3352. int output_max_size)
  3353. {
  3354. int i;
  3355. int cnt = 0;
  3356. if (ri) {
  3357. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3358. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3359. output[cnt++] = ri->http_headers[i].value;
  3360. }
  3361. }
  3362. }
  3363. return cnt;
  3364. }
  3365. #endif
  3366. const char *
  3367. mg_get_header(const struct mg_connection *conn, const char *name)
  3368. {
  3369. if (!conn) {
  3370. return NULL;
  3371. }
  3372. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3373. return get_header(conn->request_info.http_headers,
  3374. conn->request_info.num_headers,
  3375. name);
  3376. }
  3377. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3378. return get_header(conn->response_info.http_headers,
  3379. conn->response_info.num_headers,
  3380. name);
  3381. }
  3382. return NULL;
  3383. }
  3384. static const char *
  3385. get_http_version(const struct mg_connection *conn)
  3386. {
  3387. if (!conn) {
  3388. return NULL;
  3389. }
  3390. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3391. return conn->request_info.http_version;
  3392. }
  3393. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3394. return conn->response_info.http_version;
  3395. }
  3396. return NULL;
  3397. }
  3398. /* A helper function for traversing a comma separated list of values.
  3399. * It returns a list pointer shifted to the next value, or NULL if the end
  3400. * of the list found.
  3401. * Value is stored in val vector. If value has form "x=y", then eq_val
  3402. * vector is initialized to point to the "y" part, and val vector length
  3403. * is adjusted to point only to "x". */
  3404. static const char *
  3405. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3406. {
  3407. int end;
  3408. reparse:
  3409. if (val == NULL || list == NULL || *list == '\0') {
  3410. /* End of the list */
  3411. return NULL;
  3412. }
  3413. /* Skip over leading LWS */
  3414. while (*list == ' ' || *list == '\t')
  3415. list++;
  3416. val->ptr = list;
  3417. if ((list = strchr(val->ptr, ',')) != NULL) {
  3418. /* Comma found. Store length and shift the list ptr */
  3419. val->len = ((size_t)(list - val->ptr));
  3420. list++;
  3421. } else {
  3422. /* This value is the last one */
  3423. list = val->ptr + strlen(val->ptr);
  3424. val->len = ((size_t)(list - val->ptr));
  3425. }
  3426. /* Adjust length for trailing LWS */
  3427. end = (int)val->len - 1;
  3428. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3429. end--;
  3430. val->len = (size_t)(end + 1);
  3431. if (val->len == 0) {
  3432. /* Ignore any empty entries. */
  3433. goto reparse;
  3434. }
  3435. if (eq_val != NULL) {
  3436. /* Value has form "x=y", adjust pointers and lengths
  3437. * so that val points to "x", and eq_val points to "y". */
  3438. eq_val->len = 0;
  3439. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3440. if (eq_val->ptr != NULL) {
  3441. eq_val->ptr++; /* Skip over '=' character */
  3442. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3443. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3444. }
  3445. }
  3446. return list;
  3447. }
  3448. /* A helper function for checking if a comma separated list of values
  3449. * contains
  3450. * the given option (case insensitvely).
  3451. * 'header' can be NULL, in which case false is returned. */
  3452. static int
  3453. header_has_option(const char *header, const char *option)
  3454. {
  3455. struct vec opt_vec;
  3456. struct vec eq_vec;
  3457. DEBUG_ASSERT(option != NULL);
  3458. DEBUG_ASSERT(option[0] != '\0');
  3459. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3460. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3461. return 1;
  3462. }
  3463. return 0;
  3464. }
  3465. /* Perform case-insensitive match of string against pattern */
  3466. static ptrdiff_t
  3467. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3468. {
  3469. const char *or_str;
  3470. ptrdiff_t i, j, len, res;
  3471. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3472. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3473. return (res > 0) ? res
  3474. : match_prefix(or_str + 1,
  3475. (size_t)((pattern + pattern_len)
  3476. - (or_str + 1)),
  3477. str);
  3478. }
  3479. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3480. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3481. continue;
  3482. } else if (pattern[i] == '$') {
  3483. return (str[j] == '\0') ? j : -1;
  3484. } else if (pattern[i] == '*') {
  3485. i++;
  3486. if (pattern[i] == '*') {
  3487. i++;
  3488. len = strlen(str + j);
  3489. } else {
  3490. len = strcspn(str + j, "/");
  3491. }
  3492. if (i == (ptrdiff_t)pattern_len) {
  3493. return j + len;
  3494. }
  3495. do {
  3496. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3497. } while (res == -1 && len-- > 0);
  3498. return (res == -1) ? -1 : j + res + len;
  3499. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3500. return -1;
  3501. }
  3502. }
  3503. return (ptrdiff_t)j;
  3504. }
  3505. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3506. * This function must tolerate situations when connection info is not
  3507. * set up, for example if request parsing failed. */
  3508. static int
  3509. should_keep_alive(const struct mg_connection *conn)
  3510. {
  3511. const char *http_version;
  3512. const char *header;
  3513. /* First satisfy needs of the server */
  3514. if ((conn == NULL) || conn->must_close) {
  3515. /* Close, if civetweb framework needs to close */
  3516. return 0;
  3517. }
  3518. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3519. /* Close, if keep alive is not enabled */
  3520. return 0;
  3521. }
  3522. /* Check explicit wish of the client */
  3523. header = mg_get_header(conn, "Connection");
  3524. if (header) {
  3525. /* If there is a connection header from the client, obey */
  3526. if (header_has_option(header, "keep-alive")) {
  3527. return 1;
  3528. }
  3529. return 0;
  3530. }
  3531. /* Use default of the standard */
  3532. http_version = get_http_version(conn);
  3533. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3534. /* HTTP 1.1 default is keep alive */
  3535. return 1;
  3536. }
  3537. /* HTTP 1.0 (and earlier) default is to close the connection */
  3538. return 0;
  3539. }
  3540. static int
  3541. should_decode_url(const struct mg_connection *conn)
  3542. {
  3543. if (!conn || !conn->dom_ctx) {
  3544. return 0;
  3545. }
  3546. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3547. }
  3548. static const char *
  3549. suggest_connection_header(const struct mg_connection *conn)
  3550. {
  3551. return should_keep_alive(conn) ? "keep-alive" : "close";
  3552. }
  3553. static int
  3554. send_no_cache_header(struct mg_connection *conn)
  3555. {
  3556. /* Send all current and obsolete cache opt-out directives. */
  3557. return mg_printf(conn,
  3558. "Cache-Control: no-cache, no-store, "
  3559. "must-revalidate, private, max-age=0\r\n"
  3560. "Pragma: no-cache\r\n"
  3561. "Expires: 0\r\n");
  3562. }
  3563. static int
  3564. send_static_cache_header(struct mg_connection *conn)
  3565. {
  3566. #if !defined(NO_CACHING)
  3567. /* Read the server config to check how long a file may be cached.
  3568. * The configuration is in seconds. */
  3569. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3570. if (max_age <= 0) {
  3571. /* 0 means "do not cache". All values <0 are reserved
  3572. * and may be used differently in the future. */
  3573. /* If a file should not be cached, do not only send
  3574. * max-age=0, but also pragmas and Expires headers. */
  3575. return send_no_cache_header(conn);
  3576. }
  3577. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3578. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3579. /* See also https://www.mnot.net/cache_docs/ */
  3580. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3581. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3582. * leap
  3583. * year to 31622400 seconds. For the moment, we just send whatever has
  3584. * been configured, still the behavior for >1 year should be considered
  3585. * as undefined. */
  3586. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3587. #else /* NO_CACHING */
  3588. return send_no_cache_header(conn);
  3589. #endif /* !NO_CACHING */
  3590. }
  3591. static int
  3592. send_additional_header(struct mg_connection *conn)
  3593. {
  3594. int i = 0;
  3595. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3596. #if !defined(NO_SSL)
  3597. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3598. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3599. if (max_age >= 0) {
  3600. i += mg_printf(conn,
  3601. "Strict-Transport-Security: max-age=%u\r\n",
  3602. (unsigned)max_age);
  3603. }
  3604. }
  3605. #endif
  3606. if (header && header[0]) {
  3607. i += mg_printf(conn, "%s\r\n", header);
  3608. }
  3609. return i;
  3610. }
  3611. static void handle_file_based_request(struct mg_connection *conn,
  3612. const char *path,
  3613. struct mg_file *filep);
  3614. const char *
  3615. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3616. {
  3617. /* See IANA HTTP status code assignment:
  3618. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3619. */
  3620. switch (response_code) {
  3621. /* RFC2616 Section 10.1 - Informational 1xx */
  3622. case 100:
  3623. return "Continue"; /* RFC2616 Section 10.1.1 */
  3624. case 101:
  3625. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3626. case 102:
  3627. return "Processing"; /* RFC2518 Section 10.1 */
  3628. /* RFC2616 Section 10.2 - Successful 2xx */
  3629. case 200:
  3630. return "OK"; /* RFC2616 Section 10.2.1 */
  3631. case 201:
  3632. return "Created"; /* RFC2616 Section 10.2.2 */
  3633. case 202:
  3634. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3635. case 203:
  3636. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3637. case 204:
  3638. return "No Content"; /* RFC2616 Section 10.2.5 */
  3639. case 205:
  3640. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3641. case 206:
  3642. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3643. case 207:
  3644. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3645. */
  3646. case 208:
  3647. return "Already Reported"; /* RFC5842 Section 7.1 */
  3648. case 226:
  3649. return "IM used"; /* RFC3229 Section 10.4.1 */
  3650. /* RFC2616 Section 10.3 - Redirection 3xx */
  3651. case 300:
  3652. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3653. case 301:
  3654. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3655. case 302:
  3656. return "Found"; /* RFC2616 Section 10.3.3 */
  3657. case 303:
  3658. return "See Other"; /* RFC2616 Section 10.3.4 */
  3659. case 304:
  3660. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3661. case 305:
  3662. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3663. case 307:
  3664. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3665. case 308:
  3666. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3667. /* RFC2616 Section 10.4 - Client Error 4xx */
  3668. case 400:
  3669. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3670. case 401:
  3671. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3672. case 402:
  3673. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3674. case 403:
  3675. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3676. case 404:
  3677. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3678. case 405:
  3679. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3680. case 406:
  3681. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3682. case 407:
  3683. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3684. case 408:
  3685. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3686. case 409:
  3687. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3688. case 410:
  3689. return "Gone"; /* RFC2616 Section 10.4.11 */
  3690. case 411:
  3691. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3692. case 412:
  3693. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3694. case 413:
  3695. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3696. case 414:
  3697. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3698. case 415:
  3699. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3700. case 416:
  3701. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3702. */
  3703. case 417:
  3704. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3705. case 421:
  3706. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3707. case 422:
  3708. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3709. * Section 11.2 */
  3710. case 423:
  3711. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3712. case 424:
  3713. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3714. * Section 11.4 */
  3715. case 426:
  3716. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3717. case 428:
  3718. return "Precondition Required"; /* RFC 6585, Section 3 */
  3719. case 429:
  3720. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3721. case 431:
  3722. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3723. case 451:
  3724. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3725. * Section 3 */
  3726. /* RFC2616 Section 10.5 - Server Error 5xx */
  3727. case 500:
  3728. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3729. case 501:
  3730. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3731. case 502:
  3732. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3733. case 503:
  3734. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3735. case 504:
  3736. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3737. case 505:
  3738. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3739. case 506:
  3740. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3741. case 507:
  3742. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3743. * Section 11.5 */
  3744. case 508:
  3745. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3746. case 510:
  3747. return "Not Extended"; /* RFC 2774, Section 7 */
  3748. case 511:
  3749. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3750. /* Other status codes, not shown in the IANA HTTP status code
  3751. * assignment.
  3752. * E.g., "de facto" standards due to common use, ... */
  3753. case 418:
  3754. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3755. case 419:
  3756. return "Authentication Timeout"; /* common use */
  3757. case 420:
  3758. return "Enhance Your Calm"; /* common use */
  3759. case 440:
  3760. return "Login Timeout"; /* common use */
  3761. case 509:
  3762. return "Bandwidth Limit Exceeded"; /* common use */
  3763. default:
  3764. /* This error code is unknown. This should not happen. */
  3765. if (conn) {
  3766. mg_cry_internal(conn,
  3767. "Unknown HTTP response code: %u",
  3768. response_code);
  3769. }
  3770. /* Return at least a category according to RFC 2616 Section 10. */
  3771. if (response_code >= 100 && response_code < 200) {
  3772. /* Unknown informational status code */
  3773. return "Information";
  3774. }
  3775. if (response_code >= 200 && response_code < 300) {
  3776. /* Unknown success code */
  3777. return "Success";
  3778. }
  3779. if (response_code >= 300 && response_code < 400) {
  3780. /* Unknown redirection code */
  3781. return "Redirection";
  3782. }
  3783. if (response_code >= 400 && response_code < 500) {
  3784. /* Unknown request error code */
  3785. return "Client Error";
  3786. }
  3787. if (response_code >= 500 && response_code < 600) {
  3788. /* Unknown server error code */
  3789. return "Server Error";
  3790. }
  3791. /* Response code not even within reasonable range */
  3792. return "";
  3793. }
  3794. }
  3795. static int
  3796. mg_send_http_error_impl(struct mg_connection *conn,
  3797. int status,
  3798. const char *fmt,
  3799. va_list args)
  3800. {
  3801. char errmsg_buf[MG_BUF_LEN];
  3802. char path_buf[PATH_MAX];
  3803. va_list ap;
  3804. int len, i, page_handler_found, scope, truncated, has_body;
  3805. char date[64];
  3806. time_t curtime = time(NULL);
  3807. const char *error_handler = NULL;
  3808. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3809. const char *error_page_file_ext, *tstr;
  3810. int handled_by_callback = 0;
  3811. const char *status_text = mg_get_response_code_text(conn, status);
  3812. if ((conn == NULL) || (fmt == NULL)) {
  3813. return -2;
  3814. }
  3815. /* Set status (for log) */
  3816. conn->status_code = status;
  3817. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3818. has_body = ((status > 199) && (status != 204) && (status != 304));
  3819. /* Prepare message in buf, if required */
  3820. if (has_body
  3821. || (!conn->in_error_handler
  3822. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3823. /* Store error message in errmsg_buf */
  3824. va_copy(ap, args);
  3825. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3826. va_end(ap);
  3827. /* In a debug build, print all html errors */
  3828. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3829. }
  3830. /* If there is a http_error callback, call it.
  3831. * But don't do it recursively, if callback calls mg_send_http_error again.
  3832. */
  3833. if (!conn->in_error_handler
  3834. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3835. /* Mark in_error_handler to avoid recursion and call user callback. */
  3836. conn->in_error_handler = 1;
  3837. handled_by_callback =
  3838. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3839. == 0);
  3840. conn->in_error_handler = 0;
  3841. }
  3842. if (!handled_by_callback) {
  3843. /* Check for recursion */
  3844. if (conn->in_error_handler) {
  3845. DEBUG_TRACE(
  3846. "Recursion when handling error %u - fall back to default",
  3847. status);
  3848. } else {
  3849. /* Send user defined error pages, if defined */
  3850. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3851. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3852. page_handler_found = 0;
  3853. if (error_handler != NULL) {
  3854. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3855. switch (scope) {
  3856. case 1: /* Handler for specific error, e.g. 404 error */
  3857. mg_snprintf(conn,
  3858. &truncated,
  3859. path_buf,
  3860. sizeof(path_buf) - 32,
  3861. "%serror%03u.",
  3862. error_handler,
  3863. status);
  3864. break;
  3865. case 2: /* Handler for error group, e.g., 5xx error
  3866. * handler
  3867. * for all server errors (500-599) */
  3868. mg_snprintf(conn,
  3869. &truncated,
  3870. path_buf,
  3871. sizeof(path_buf) - 32,
  3872. "%serror%01uxx.",
  3873. error_handler,
  3874. status / 100);
  3875. break;
  3876. default: /* Handler for all errors */
  3877. mg_snprintf(conn,
  3878. &truncated,
  3879. path_buf,
  3880. sizeof(path_buf) - 32,
  3881. "%serror.",
  3882. error_handler);
  3883. break;
  3884. }
  3885. /* String truncation in buf may only occur if
  3886. * error_handler is too long. This string is
  3887. * from the config, not from a client. */
  3888. (void)truncated;
  3889. len = (int)strlen(path_buf);
  3890. tstr = strchr(error_page_file_ext, '.');
  3891. while (tstr) {
  3892. for (i = 1;
  3893. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3894. i++) {
  3895. /* buffer overrun is not possible here, since
  3896. * (i < 32) && (len < sizeof(path_buf) - 32)
  3897. * ==> (i + len) < sizeof(path_buf) */
  3898. path_buf[len + i - 1] = tstr[i];
  3899. }
  3900. /* buffer overrun is not possible here, since
  3901. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3902. * ==> (i + len) <= sizeof(path_buf) */
  3903. path_buf[len + i - 1] = 0;
  3904. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3905. DEBUG_TRACE("Check error page %s - found",
  3906. path_buf);
  3907. page_handler_found = 1;
  3908. break;
  3909. }
  3910. DEBUG_TRACE("Check error page %s - not found",
  3911. path_buf);
  3912. tstr = strchr(tstr + i, '.');
  3913. }
  3914. }
  3915. }
  3916. if (page_handler_found) {
  3917. conn->in_error_handler = 1;
  3918. handle_file_based_request(conn, path_buf, &error_page_file);
  3919. conn->in_error_handler = 0;
  3920. return 0;
  3921. }
  3922. }
  3923. /* No custom error page. Send default error page. */
  3924. gmt_time_string(date, sizeof(date), &curtime);
  3925. conn->must_close = 1;
  3926. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3927. send_no_cache_header(conn);
  3928. send_additional_header(conn);
  3929. if (has_body) {
  3930. mg_printf(conn,
  3931. "%s",
  3932. "Content-Type: text/plain; charset=utf-8\r\n");
  3933. }
  3934. mg_printf(conn,
  3935. "Date: %s\r\n"
  3936. "Connection: close\r\n\r\n",
  3937. date);
  3938. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3939. if (has_body) {
  3940. /* For other errors, send a generic error message. */
  3941. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3942. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3943. } else {
  3944. /* No body allowed. Close the connection. */
  3945. DEBUG_TRACE("Error %i", status);
  3946. }
  3947. }
  3948. return 0;
  3949. }
  3950. int
  3951. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3952. {
  3953. va_list ap;
  3954. int ret;
  3955. va_start(ap, fmt);
  3956. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3957. va_end(ap);
  3958. return ret;
  3959. }
  3960. int
  3961. mg_send_http_ok(struct mg_connection *conn,
  3962. const char *mime_type,
  3963. long long content_length)
  3964. {
  3965. char date[64];
  3966. time_t curtime = time(NULL);
  3967. if ((mime_type == NULL) || (*mime_type == 0)) {
  3968. /* Parameter error */
  3969. return -2;
  3970. }
  3971. gmt_time_string(date, sizeof(date), &curtime);
  3972. mg_printf(conn,
  3973. "HTTP/1.1 200 OK\r\n"
  3974. "Content-Type: %s\r\n"
  3975. "Date: %s\r\n"
  3976. "Connection: %s\r\n",
  3977. mime_type,
  3978. date,
  3979. suggest_connection_header(conn));
  3980. send_no_cache_header(conn);
  3981. send_additional_header(conn);
  3982. if (content_length < 0) {
  3983. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  3984. } else {
  3985. mg_printf(conn,
  3986. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  3987. (uint64_t)content_length);
  3988. }
  3989. return 0;
  3990. }
  3991. int
  3992. mg_send_http_redirect(struct mg_connection *conn,
  3993. const char *target_url,
  3994. int redirect_code)
  3995. {
  3996. /* Send a 30x redirect response.
  3997. *
  3998. * Redirect types (status codes):
  3999. *
  4000. * Status | Perm/Temp | Method | Version
  4001. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4002. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4003. * 303 | temporary | always use GET | HTTP/1.1
  4004. * 307 | temporary | always keep method | HTTP/1.1
  4005. * 308 | permanent | always keep method | HTTP/1.1
  4006. */
  4007. const char *redirect_text;
  4008. int ret;
  4009. size_t content_len = 0;
  4010. char reply[MG_BUF_LEN];
  4011. /* In case redirect_code=0, use 307. */
  4012. if (redirect_code == 0) {
  4013. redirect_code = 307;
  4014. }
  4015. /* In case redirect_code is none of the above, return error. */
  4016. if ((redirect_code != 301) && (redirect_code != 302)
  4017. && (redirect_code != 303) && (redirect_code != 307)
  4018. && (redirect_code != 308)) {
  4019. /* Parameter error */
  4020. return -2;
  4021. }
  4022. /* Get proper text for response code */
  4023. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4024. /* If target_url is not defined, redirect to "/". */
  4025. if ((target_url == NULL) || (*target_url == 0)) {
  4026. target_url = "/";
  4027. }
  4028. #if defined(MG_SEND_REDIRECT_BODY)
  4029. /* TODO: condition name? */
  4030. /* Prepare a response body with a hyperlink.
  4031. *
  4032. * According to RFC2616 (and RFC1945 before):
  4033. * Unless the request method was HEAD, the entity of the
  4034. * response SHOULD contain a short hypertext note with a hyperlink to
  4035. * the new URI(s).
  4036. *
  4037. * However, this response body is not useful in M2M communication.
  4038. * Probably the original reason in the RFC was, clients not supporting
  4039. * a 30x HTTP redirect could still show the HTML page and let the user
  4040. * press the link. Since current browsers support 30x HTTP, the additional
  4041. * HTML body does not seem to make sense anymore.
  4042. *
  4043. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4044. * but it only notes:
  4045. * The server's response payload usually contains a short
  4046. * hypertext note with a hyperlink to the new URI(s).
  4047. *
  4048. * Deactivated by default. If you need the 30x body, set the define.
  4049. */
  4050. mg_snprintf(
  4051. conn,
  4052. NULL /* ignore truncation */,
  4053. reply,
  4054. sizeof(reply),
  4055. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4056. redirect_text,
  4057. target_url,
  4058. target_url);
  4059. content_len = strlen(reply);
  4060. #else
  4061. reply[0] = 0;
  4062. #endif
  4063. /* Do not send any additional header. For all other options,
  4064. * including caching, there are suitable defaults. */
  4065. ret = mg_printf(conn,
  4066. "HTTP/1.1 %i %s\r\n"
  4067. "Location: %s\r\n"
  4068. "Content-Length: %u\r\n"
  4069. "Connection: %s\r\n\r\n",
  4070. redirect_code,
  4071. redirect_text,
  4072. target_url,
  4073. (unsigned int)content_len,
  4074. suggest_connection_header(conn));
  4075. /* Send response body */
  4076. if (ret > 0) {
  4077. /* ... unless it is a HEAD request */
  4078. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4079. ret = mg_write(conn, reply, content_len);
  4080. }
  4081. }
  4082. return (ret > 0) ? ret : -1;
  4083. }
  4084. #if defined(_WIN32)
  4085. /* Create substitutes for POSIX functions in Win32. */
  4086. #if defined(GCC_DIAGNOSTIC)
  4087. /* Show no warning in case system functions are not used. */
  4088. #pragma GCC diagnostic push
  4089. #pragma GCC diagnostic ignored "-Wunused-function"
  4090. #endif
  4091. FUNCTION_MAY_BE_UNUSED
  4092. static int
  4093. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4094. {
  4095. (void)unused;
  4096. *mutex = CreateMutex(NULL, FALSE, NULL);
  4097. return (*mutex == NULL) ? -1 : 0;
  4098. }
  4099. FUNCTION_MAY_BE_UNUSED
  4100. static int
  4101. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4102. {
  4103. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  4104. }
  4105. FUNCTION_MAY_BE_UNUSED
  4106. static int
  4107. pthread_mutex_lock(pthread_mutex_t *mutex)
  4108. {
  4109. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  4110. : -1;
  4111. }
  4112. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  4113. FUNCTION_MAY_BE_UNUSED
  4114. static int
  4115. pthread_mutex_trylock(pthread_mutex_t *mutex)
  4116. {
  4117. switch (WaitForSingleObject(*mutex, 0)) {
  4118. case WAIT_OBJECT_0:
  4119. return 0;
  4120. case WAIT_TIMEOUT:
  4121. return -2; /* EBUSY */
  4122. }
  4123. return -1;
  4124. }
  4125. #endif
  4126. FUNCTION_MAY_BE_UNUSED
  4127. static int
  4128. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4129. {
  4130. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  4131. }
  4132. FUNCTION_MAY_BE_UNUSED
  4133. static int
  4134. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4135. {
  4136. (void)unused;
  4137. InitializeCriticalSection(&cv->threadIdSec);
  4138. cv->waiting_thread = NULL;
  4139. return 0;
  4140. }
  4141. FUNCTION_MAY_BE_UNUSED
  4142. static int
  4143. pthread_cond_timedwait(pthread_cond_t *cv,
  4144. pthread_mutex_t *mutex,
  4145. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4146. {
  4147. struct mg_workerTLS **ptls,
  4148. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4149. int ok;
  4150. int64_t nsnow, nswaitabs, nswaitrel;
  4151. DWORD mswaitrel;
  4152. EnterCriticalSection(&cv->threadIdSec);
  4153. /* Add this thread to cv's waiting list */
  4154. ptls = &cv->waiting_thread;
  4155. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4156. ;
  4157. tls->next_waiting_thread = NULL;
  4158. *ptls = tls;
  4159. LeaveCriticalSection(&cv->threadIdSec);
  4160. if (abstime) {
  4161. nsnow = mg_get_current_time_ns();
  4162. nswaitabs =
  4163. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4164. nswaitrel = nswaitabs - nsnow;
  4165. if (nswaitrel < 0) {
  4166. nswaitrel = 0;
  4167. }
  4168. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4169. } else {
  4170. mswaitrel = (DWORD)INFINITE;
  4171. }
  4172. pthread_mutex_unlock(mutex);
  4173. ok = (WAIT_OBJECT_0
  4174. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4175. if (!ok) {
  4176. ok = 1;
  4177. EnterCriticalSection(&cv->threadIdSec);
  4178. ptls = &cv->waiting_thread;
  4179. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4180. if (*ptls == tls) {
  4181. *ptls = tls->next_waiting_thread;
  4182. ok = 0;
  4183. break;
  4184. }
  4185. }
  4186. LeaveCriticalSection(&cv->threadIdSec);
  4187. if (ok) {
  4188. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4189. (DWORD)INFINITE);
  4190. }
  4191. }
  4192. /* This thread has been removed from cv's waiting list */
  4193. pthread_mutex_lock(mutex);
  4194. return ok ? 0 : -1;
  4195. }
  4196. FUNCTION_MAY_BE_UNUSED
  4197. static int
  4198. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4199. {
  4200. return pthread_cond_timedwait(cv, mutex, NULL);
  4201. }
  4202. FUNCTION_MAY_BE_UNUSED
  4203. static int
  4204. pthread_cond_signal(pthread_cond_t *cv)
  4205. {
  4206. HANDLE wkup = NULL;
  4207. BOOL ok = FALSE;
  4208. EnterCriticalSection(&cv->threadIdSec);
  4209. if (cv->waiting_thread) {
  4210. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4211. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4212. ok = SetEvent(wkup);
  4213. DEBUG_ASSERT(ok);
  4214. }
  4215. LeaveCriticalSection(&cv->threadIdSec);
  4216. return ok ? 0 : 1;
  4217. }
  4218. FUNCTION_MAY_BE_UNUSED
  4219. static int
  4220. pthread_cond_broadcast(pthread_cond_t *cv)
  4221. {
  4222. EnterCriticalSection(&cv->threadIdSec);
  4223. while (cv->waiting_thread) {
  4224. pthread_cond_signal(cv);
  4225. }
  4226. LeaveCriticalSection(&cv->threadIdSec);
  4227. return 0;
  4228. }
  4229. FUNCTION_MAY_BE_UNUSED
  4230. static int
  4231. pthread_cond_destroy(pthread_cond_t *cv)
  4232. {
  4233. EnterCriticalSection(&cv->threadIdSec);
  4234. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4235. LeaveCriticalSection(&cv->threadIdSec);
  4236. DeleteCriticalSection(&cv->threadIdSec);
  4237. return 0;
  4238. }
  4239. #if defined(ALTERNATIVE_QUEUE)
  4240. FUNCTION_MAY_BE_UNUSED
  4241. static void *
  4242. event_create(void)
  4243. {
  4244. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4245. }
  4246. FUNCTION_MAY_BE_UNUSED
  4247. static int
  4248. event_wait(void *eventhdl)
  4249. {
  4250. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4251. return (res == WAIT_OBJECT_0);
  4252. }
  4253. FUNCTION_MAY_BE_UNUSED
  4254. static int
  4255. event_signal(void *eventhdl)
  4256. {
  4257. return (int)SetEvent((HANDLE)eventhdl);
  4258. }
  4259. FUNCTION_MAY_BE_UNUSED
  4260. static void
  4261. event_destroy(void *eventhdl)
  4262. {
  4263. CloseHandle((HANDLE)eventhdl);
  4264. }
  4265. #endif
  4266. #if defined(GCC_DIAGNOSTIC)
  4267. /* Enable unused function warning again */
  4268. #pragma GCC diagnostic pop
  4269. #endif
  4270. /* For Windows, change all slashes to backslashes in path names. */
  4271. static void
  4272. change_slashes_to_backslashes(char *path)
  4273. {
  4274. int i;
  4275. for (i = 0; path[i] != '\0'; i++) {
  4276. if (path[i] == '/') {
  4277. path[i] = '\\';
  4278. }
  4279. /* remove double backslash (check i > 0 to preserve UNC paths,
  4280. * like \\server\file.txt) */
  4281. if ((path[i] == '\\') && (i > 0)) {
  4282. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4283. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4284. }
  4285. }
  4286. }
  4287. }
  4288. static int
  4289. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4290. {
  4291. int diff;
  4292. do {
  4293. diff = tolower(*s1) - tolower(*s2);
  4294. s1++;
  4295. s2++;
  4296. } while ((diff == 0) && (s1[-1] != '\0'));
  4297. return diff;
  4298. }
  4299. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4300. * wbuf and wbuf_len is a target buffer and its length. */
  4301. static void
  4302. path_to_unicode(const struct mg_connection *conn,
  4303. const char *path,
  4304. wchar_t *wbuf,
  4305. size_t wbuf_len)
  4306. {
  4307. char buf[PATH_MAX], buf2[PATH_MAX];
  4308. wchar_t wbuf2[W_PATH_MAX + 1];
  4309. DWORD long_len, err;
  4310. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4311. mg_strlcpy(buf, path, sizeof(buf));
  4312. change_slashes_to_backslashes(buf);
  4313. /* Convert to Unicode and back. If doubly-converted string does not
  4314. * match the original, something is fishy, reject. */
  4315. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4316. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4317. WideCharToMultiByte(
  4318. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4319. if (strcmp(buf, buf2) != 0) {
  4320. wbuf[0] = L'\0';
  4321. }
  4322. /* Windows file systems are not case sensitive, but you can still use
  4323. * uppercase and lowercase letters (on all modern file systems).
  4324. * The server can check if the URI uses the same upper/lowercase
  4325. * letters an the file system, effectively making Windows servers
  4326. * case sensitive (like Linux servers are). It is still not possible
  4327. * to use two files with the same name in different cases on Windows
  4328. * (like /a and /A) - this would be possible in Linux.
  4329. * As a default, Windows is not case sensitive, but the case sensitive
  4330. * file name check can be activated by an additional configuration. */
  4331. if (conn) {
  4332. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4333. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4334. "yes")) {
  4335. /* Use case sensitive compare function */
  4336. fcompare = wcscmp;
  4337. }
  4338. }
  4339. (void)conn; /* conn is currently unused */
  4340. #if !defined(_WIN32_WCE)
  4341. /* Only accept a full file path, not a Windows short (8.3) path. */
  4342. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4343. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4344. if (long_len == 0) {
  4345. err = GetLastError();
  4346. if (err == ERROR_FILE_NOT_FOUND) {
  4347. /* File does not exist. This is not always a problem here. */
  4348. return;
  4349. }
  4350. }
  4351. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4352. /* Short name is used. */
  4353. wbuf[0] = L'\0';
  4354. }
  4355. #else
  4356. (void)long_len;
  4357. (void)wbuf2;
  4358. (void)err;
  4359. if (strchr(path, '~')) {
  4360. wbuf[0] = L'\0';
  4361. }
  4362. #endif
  4363. }
  4364. /* Windows happily opens files with some garbage at the end of file name.
  4365. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4366. * "a.cgi", despite one would expect an error back.
  4367. * This function returns non-0 if path ends with some garbage. */
  4368. static int
  4369. path_cannot_disclose_cgi(const char *path)
  4370. {
  4371. static const char *allowed_last_characters = "_-";
  4372. int last = path[strlen(path) - 1];
  4373. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4374. }
  4375. static int
  4376. mg_stat(const struct mg_connection *conn,
  4377. const char *path,
  4378. struct mg_file_stat *filep)
  4379. {
  4380. wchar_t wbuf[W_PATH_MAX];
  4381. WIN32_FILE_ATTRIBUTE_DATA info;
  4382. time_t creation_time;
  4383. if (!filep) {
  4384. return 0;
  4385. }
  4386. memset(filep, 0, sizeof(*filep));
  4387. if (conn && is_file_in_memory(conn, path)) {
  4388. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4389. * memset */
  4390. /* Quick fix (for 1.9.x): */
  4391. /* mg_stat must fill all fields, also for files in memory */
  4392. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4393. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4394. filep->size = tmp_file.stat.size;
  4395. filep->location = 2;
  4396. /* TODO: for 1.10: restructure how files in memory are handled */
  4397. /* The "file in memory" feature is a candidate for deletion.
  4398. * Please join the discussion at
  4399. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4400. */
  4401. filep->last_modified = time(NULL); /* TODO */
  4402. /* last_modified = now ... assumes the file may change during
  4403. * runtime,
  4404. * so every mg_fopen call may return different data */
  4405. /* last_modified = conn->phys_ctx.start_time;
  4406. * May be used it the data does not change during runtime. This
  4407. * allows
  4408. * browser caching. Since we do not know, we have to assume the file
  4409. * in memory may change. */
  4410. return 1;
  4411. }
  4412. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4413. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4414. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4415. filep->last_modified =
  4416. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4417. info.ftLastWriteTime.dwHighDateTime);
  4418. /* On Windows, the file creation time can be higher than the
  4419. * modification time, e.g. when a file is copied.
  4420. * Since the Last-Modified timestamp is used for caching
  4421. * it should be based on the most recent timestamp. */
  4422. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4423. info.ftCreationTime.dwHighDateTime);
  4424. if (creation_time > filep->last_modified) {
  4425. filep->last_modified = creation_time;
  4426. }
  4427. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4428. /* If file name is fishy, reset the file structure and return
  4429. * error.
  4430. * Note it is important to reset, not just return the error, cause
  4431. * functions like is_file_opened() check the struct. */
  4432. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4433. memset(filep, 0, sizeof(*filep));
  4434. return 0;
  4435. }
  4436. return 1;
  4437. }
  4438. return 0;
  4439. }
  4440. static int
  4441. mg_remove(const struct mg_connection *conn, const char *path)
  4442. {
  4443. wchar_t wbuf[W_PATH_MAX];
  4444. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4445. return DeleteFileW(wbuf) ? 0 : -1;
  4446. }
  4447. static int
  4448. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4449. {
  4450. wchar_t wbuf[W_PATH_MAX];
  4451. (void)mode;
  4452. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4453. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4454. }
  4455. /* Create substitutes for POSIX functions in Win32. */
  4456. #if defined(GCC_DIAGNOSTIC)
  4457. /* Show no warning in case system functions are not used. */
  4458. #pragma GCC diagnostic push
  4459. #pragma GCC diagnostic ignored "-Wunused-function"
  4460. #endif
  4461. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4462. FUNCTION_MAY_BE_UNUSED
  4463. static DIR *
  4464. mg_opendir(const struct mg_connection *conn, const char *name)
  4465. {
  4466. DIR *dir = NULL;
  4467. wchar_t wpath[W_PATH_MAX];
  4468. DWORD attrs;
  4469. if (name == NULL) {
  4470. SetLastError(ERROR_BAD_ARGUMENTS);
  4471. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4472. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4473. } else {
  4474. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4475. attrs = GetFileAttributesW(wpath);
  4476. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4477. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4478. (void)wcscat(wpath, L"\\*");
  4479. dir->handle = FindFirstFileW(wpath, &dir->info);
  4480. dir->result.d_name[0] = '\0';
  4481. } else {
  4482. mg_free(dir);
  4483. dir = NULL;
  4484. }
  4485. }
  4486. return dir;
  4487. }
  4488. FUNCTION_MAY_BE_UNUSED
  4489. static int
  4490. mg_closedir(DIR *dir)
  4491. {
  4492. int result = 0;
  4493. if (dir != NULL) {
  4494. if (dir->handle != INVALID_HANDLE_VALUE)
  4495. result = FindClose(dir->handle) ? 0 : -1;
  4496. mg_free(dir);
  4497. } else {
  4498. result = -1;
  4499. SetLastError(ERROR_BAD_ARGUMENTS);
  4500. }
  4501. return result;
  4502. }
  4503. FUNCTION_MAY_BE_UNUSED
  4504. static struct dirent *
  4505. mg_readdir(DIR *dir)
  4506. {
  4507. struct dirent *result = 0;
  4508. if (dir) {
  4509. if (dir->handle != INVALID_HANDLE_VALUE) {
  4510. result = &dir->result;
  4511. (void)WideCharToMultiByte(CP_UTF8,
  4512. 0,
  4513. dir->info.cFileName,
  4514. -1,
  4515. result->d_name,
  4516. sizeof(result->d_name),
  4517. NULL,
  4518. NULL);
  4519. if (!FindNextFileW(dir->handle, &dir->info)) {
  4520. (void)FindClose(dir->handle);
  4521. dir->handle = INVALID_HANDLE_VALUE;
  4522. }
  4523. } else {
  4524. SetLastError(ERROR_FILE_NOT_FOUND);
  4525. }
  4526. } else {
  4527. SetLastError(ERROR_BAD_ARGUMENTS);
  4528. }
  4529. return result;
  4530. }
  4531. #if !defined(HAVE_POLL)
  4532. #define POLLIN (1) /* Data ready - read will not block. */
  4533. #define POLLPRI (2) /* Priority data ready. */
  4534. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4535. FUNCTION_MAY_BE_UNUSED
  4536. static int
  4537. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4538. {
  4539. struct timeval tv;
  4540. fd_set rset;
  4541. fd_set wset;
  4542. unsigned int i;
  4543. int result;
  4544. SOCKET maxfd = 0;
  4545. memset(&tv, 0, sizeof(tv));
  4546. tv.tv_sec = milliseconds / 1000;
  4547. tv.tv_usec = (milliseconds % 1000) * 1000;
  4548. FD_ZERO(&rset);
  4549. FD_ZERO(&wset);
  4550. for (i = 0; i < n; i++) {
  4551. if (pfd[i].events & POLLIN) {
  4552. FD_SET((SOCKET)pfd[i].fd, &rset);
  4553. } else if (pfd[i].events & POLLOUT) {
  4554. FD_SET((SOCKET)pfd[i].fd, &wset);
  4555. }
  4556. pfd[i].revents = 0;
  4557. if (pfd[i].fd > maxfd) {
  4558. maxfd = pfd[i].fd;
  4559. }
  4560. }
  4561. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4562. for (i = 0; i < n; i++) {
  4563. if (FD_ISSET(pfd[i].fd, &rset)) {
  4564. pfd[i].revents |= POLLIN;
  4565. }
  4566. if (FD_ISSET(pfd[i].fd, &wset)) {
  4567. pfd[i].revents |= POLLOUT;
  4568. }
  4569. }
  4570. }
  4571. /* We should subtract the time used in select from remaining
  4572. * "milliseconds", in particular if called from mg_poll with a
  4573. * timeout quantum.
  4574. * Unfortunately, the remaining time is not stored in "tv" in all
  4575. * implementations, so the result in "tv" must be considered undefined.
  4576. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4577. return result;
  4578. }
  4579. #endif /* HAVE_POLL */
  4580. #if defined(GCC_DIAGNOSTIC)
  4581. /* Enable unused function warning again */
  4582. #pragma GCC diagnostic pop
  4583. #endif
  4584. static void
  4585. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4586. {
  4587. (void)conn; /* Unused. */
  4588. #if defined(_WIN32_WCE)
  4589. (void)sock;
  4590. #else
  4591. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4592. #endif
  4593. }
  4594. int
  4595. mg_start_thread(mg_thread_func_t f, void *p)
  4596. {
  4597. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4598. /* Compile-time option to control stack size, e.g.
  4599. * -DUSE_STACK_SIZE=16384
  4600. */
  4601. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4602. == ((uintptr_t)(-1L)))
  4603. ? -1
  4604. : 0);
  4605. #else
  4606. return (
  4607. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4608. ? -1
  4609. : 0);
  4610. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4611. }
  4612. /* Start a thread storing the thread context. */
  4613. static int
  4614. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4615. void *p,
  4616. pthread_t *threadidptr)
  4617. {
  4618. uintptr_t uip;
  4619. HANDLE threadhandle;
  4620. int result = -1;
  4621. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4622. threadhandle = (HANDLE)uip;
  4623. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4624. *threadidptr = threadhandle;
  4625. result = 0;
  4626. }
  4627. return result;
  4628. }
  4629. /* Wait for a thread to finish. */
  4630. static int
  4631. mg_join_thread(pthread_t threadid)
  4632. {
  4633. int result;
  4634. DWORD dwevent;
  4635. result = -1;
  4636. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4637. if (dwevent == WAIT_FAILED) {
  4638. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4639. } else {
  4640. if (dwevent == WAIT_OBJECT_0) {
  4641. CloseHandle(threadid);
  4642. result = 0;
  4643. }
  4644. }
  4645. return result;
  4646. }
  4647. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4648. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4649. /* Create substitutes for POSIX functions in Win32. */
  4650. #if defined(GCC_DIAGNOSTIC)
  4651. /* Show no warning in case system functions are not used. */
  4652. #pragma GCC diagnostic push
  4653. #pragma GCC diagnostic ignored "-Wunused-function"
  4654. #endif
  4655. FUNCTION_MAY_BE_UNUSED
  4656. static HANDLE
  4657. dlopen(const char *dll_name, int flags)
  4658. {
  4659. wchar_t wbuf[W_PATH_MAX];
  4660. (void)flags;
  4661. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4662. return LoadLibraryW(wbuf);
  4663. }
  4664. FUNCTION_MAY_BE_UNUSED
  4665. static int
  4666. dlclose(void *handle)
  4667. {
  4668. int result;
  4669. if (FreeLibrary((HMODULE)handle) != 0) {
  4670. result = 0;
  4671. } else {
  4672. result = -1;
  4673. }
  4674. return result;
  4675. }
  4676. #if defined(GCC_DIAGNOSTIC)
  4677. /* Enable unused function warning again */
  4678. #pragma GCC diagnostic pop
  4679. #endif
  4680. #endif
  4681. #if !defined(NO_CGI)
  4682. #define SIGKILL (0)
  4683. static int
  4684. kill(pid_t pid, int sig_num)
  4685. {
  4686. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4687. (void)CloseHandle((HANDLE)pid);
  4688. return 0;
  4689. }
  4690. #if !defined(WNOHANG)
  4691. #define WNOHANG (1)
  4692. #endif
  4693. static pid_t
  4694. waitpid(pid_t pid, int *status, int flags)
  4695. {
  4696. DWORD timeout = INFINITE;
  4697. DWORD waitres;
  4698. (void)status; /* Currently not used by any client here */
  4699. if ((flags | WNOHANG) == WNOHANG) {
  4700. timeout = 0;
  4701. }
  4702. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4703. if (waitres == WAIT_OBJECT_0) {
  4704. return pid;
  4705. }
  4706. if (waitres == WAIT_TIMEOUT) {
  4707. return 0;
  4708. }
  4709. return (pid_t)-1;
  4710. }
  4711. static void
  4712. trim_trailing_whitespaces(char *s)
  4713. {
  4714. char *e = s + strlen(s) - 1;
  4715. while ((e > s) && isspace(*(unsigned char *)e)) {
  4716. *e-- = '\0';
  4717. }
  4718. }
  4719. static pid_t
  4720. spawn_process(struct mg_connection *conn,
  4721. const char *prog,
  4722. char *envblk,
  4723. char *envp[],
  4724. int fdin[2],
  4725. int fdout[2],
  4726. int fderr[2],
  4727. const char *dir)
  4728. {
  4729. HANDLE me;
  4730. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4731. cmdline[PATH_MAX], buf[PATH_MAX];
  4732. int truncated;
  4733. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4734. STARTUPINFOA si;
  4735. PROCESS_INFORMATION pi = {0};
  4736. (void)envp;
  4737. memset(&si, 0, sizeof(si));
  4738. si.cb = sizeof(si);
  4739. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4740. si.wShowWindow = SW_HIDE;
  4741. me = GetCurrentProcess();
  4742. DuplicateHandle(me,
  4743. (HANDLE)_get_osfhandle(fdin[0]),
  4744. me,
  4745. &si.hStdInput,
  4746. 0,
  4747. TRUE,
  4748. DUPLICATE_SAME_ACCESS);
  4749. DuplicateHandle(me,
  4750. (HANDLE)_get_osfhandle(fdout[1]),
  4751. me,
  4752. &si.hStdOutput,
  4753. 0,
  4754. TRUE,
  4755. DUPLICATE_SAME_ACCESS);
  4756. DuplicateHandle(me,
  4757. (HANDLE)_get_osfhandle(fderr[1]),
  4758. me,
  4759. &si.hStdError,
  4760. 0,
  4761. TRUE,
  4762. DUPLICATE_SAME_ACCESS);
  4763. /* Mark handles that should not be inherited. See
  4764. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4765. */
  4766. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4767. HANDLE_FLAG_INHERIT,
  4768. 0);
  4769. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4770. HANDLE_FLAG_INHERIT,
  4771. 0);
  4772. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4773. HANDLE_FLAG_INHERIT,
  4774. 0);
  4775. /* If CGI file is a script, try to read the interpreter line */
  4776. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4777. if (interp == NULL) {
  4778. buf[0] = buf[1] = '\0';
  4779. /* Read the first line of the script into the buffer */
  4780. mg_snprintf(
  4781. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4782. if (truncated) {
  4783. pi.hProcess = (pid_t)-1;
  4784. goto spawn_cleanup;
  4785. }
  4786. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4787. #if defined(MG_USE_OPEN_FILE)
  4788. p = (char *)file.access.membuf;
  4789. #else
  4790. p = (char *)NULL;
  4791. #endif
  4792. mg_fgets(buf, sizeof(buf), &file, &p);
  4793. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4794. buf[sizeof(buf) - 1] = '\0';
  4795. }
  4796. if ((buf[0] == '#') && (buf[1] == '!')) {
  4797. trim_trailing_whitespaces(buf + 2);
  4798. } else {
  4799. buf[2] = '\0';
  4800. }
  4801. interp = buf + 2;
  4802. }
  4803. if (interp[0] != '\0') {
  4804. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4805. interp = full_interp;
  4806. }
  4807. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4808. if (interp[0] != '\0') {
  4809. mg_snprintf(conn,
  4810. &truncated,
  4811. cmdline,
  4812. sizeof(cmdline),
  4813. "\"%s\" \"%s\\%s\"",
  4814. interp,
  4815. full_dir,
  4816. prog);
  4817. } else {
  4818. mg_snprintf(conn,
  4819. &truncated,
  4820. cmdline,
  4821. sizeof(cmdline),
  4822. "\"%s\\%s\"",
  4823. full_dir,
  4824. prog);
  4825. }
  4826. if (truncated) {
  4827. pi.hProcess = (pid_t)-1;
  4828. goto spawn_cleanup;
  4829. }
  4830. DEBUG_TRACE("Running [%s]", cmdline);
  4831. if (CreateProcessA(NULL,
  4832. cmdline,
  4833. NULL,
  4834. NULL,
  4835. TRUE,
  4836. CREATE_NEW_PROCESS_GROUP,
  4837. envblk,
  4838. NULL,
  4839. &si,
  4840. &pi)
  4841. == 0) {
  4842. mg_cry_internal(
  4843. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4844. pi.hProcess = (pid_t)-1;
  4845. /* goto spawn_cleanup; */
  4846. }
  4847. spawn_cleanup:
  4848. (void)CloseHandle(si.hStdOutput);
  4849. (void)CloseHandle(si.hStdError);
  4850. (void)CloseHandle(si.hStdInput);
  4851. if (pi.hThread != NULL) {
  4852. (void)CloseHandle(pi.hThread);
  4853. }
  4854. return (pid_t)pi.hProcess;
  4855. }
  4856. #endif /* !NO_CGI */
  4857. static int
  4858. set_blocking_mode(SOCKET sock)
  4859. {
  4860. unsigned long non_blocking = 0;
  4861. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4862. }
  4863. static int
  4864. set_non_blocking_mode(SOCKET sock)
  4865. {
  4866. unsigned long non_blocking = 1;
  4867. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4868. }
  4869. #else
  4870. static int
  4871. mg_stat(const struct mg_connection *conn,
  4872. const char *path,
  4873. struct mg_file_stat *filep)
  4874. {
  4875. struct stat st;
  4876. if (!filep) {
  4877. return 0;
  4878. }
  4879. memset(filep, 0, sizeof(*filep));
  4880. if (conn && is_file_in_memory(conn, path)) {
  4881. /* Quick fix (for 1.9.x): */
  4882. /* mg_stat must fill all fields, also for files in memory */
  4883. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4884. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4885. filep->size = tmp_file.stat.size;
  4886. filep->last_modified = time(NULL);
  4887. filep->location = 2;
  4888. /* TODO: remove legacy "files in memory" feature */
  4889. return 1;
  4890. }
  4891. if (0 == stat(path, &st)) {
  4892. filep->size = (uint64_t)(st.st_size);
  4893. filep->last_modified = st.st_mtime;
  4894. filep->is_directory = S_ISDIR(st.st_mode);
  4895. return 1;
  4896. }
  4897. return 0;
  4898. }
  4899. static void
  4900. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4901. {
  4902. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4903. if (conn) {
  4904. mg_cry_internal(conn,
  4905. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4906. __func__,
  4907. strerror(ERRNO));
  4908. }
  4909. }
  4910. }
  4911. int
  4912. mg_start_thread(mg_thread_func_t func, void *param)
  4913. {
  4914. pthread_t thread_id;
  4915. pthread_attr_t attr;
  4916. int result;
  4917. (void)pthread_attr_init(&attr);
  4918. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4919. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4920. /* Compile-time option to control stack size,
  4921. * e.g. -DUSE_STACK_SIZE=16384 */
  4922. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4923. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4924. result = pthread_create(&thread_id, &attr, func, param);
  4925. pthread_attr_destroy(&attr);
  4926. return result;
  4927. }
  4928. /* Start a thread storing the thread context. */
  4929. static int
  4930. mg_start_thread_with_id(mg_thread_func_t func,
  4931. void *param,
  4932. pthread_t *threadidptr)
  4933. {
  4934. pthread_t thread_id;
  4935. pthread_attr_t attr;
  4936. int result;
  4937. (void)pthread_attr_init(&attr);
  4938. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4939. /* Compile-time option to control stack size,
  4940. * e.g. -DUSE_STACK_SIZE=16384 */
  4941. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4942. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4943. result = pthread_create(&thread_id, &attr, func, param);
  4944. pthread_attr_destroy(&attr);
  4945. if ((result == 0) && (threadidptr != NULL)) {
  4946. *threadidptr = thread_id;
  4947. }
  4948. return result;
  4949. }
  4950. /* Wait for a thread to finish. */
  4951. static int
  4952. mg_join_thread(pthread_t threadid)
  4953. {
  4954. int result;
  4955. result = pthread_join(threadid, NULL);
  4956. return result;
  4957. }
  4958. #if !defined(NO_CGI)
  4959. static pid_t
  4960. spawn_process(struct mg_connection *conn,
  4961. const char *prog,
  4962. char *envblk,
  4963. char *envp[],
  4964. int fdin[2],
  4965. int fdout[2],
  4966. int fderr[2],
  4967. const char *dir)
  4968. {
  4969. pid_t pid;
  4970. const char *interp;
  4971. (void)envblk;
  4972. if (conn == NULL) {
  4973. return 0;
  4974. }
  4975. if ((pid = fork()) == -1) {
  4976. /* Parent */
  4977. mg_send_http_error(conn,
  4978. 500,
  4979. "Error: Creating CGI process\nfork(): %s",
  4980. strerror(ERRNO));
  4981. } else if (pid == 0) {
  4982. /* Child */
  4983. if (chdir(dir) != 0) {
  4984. mg_cry_internal(
  4985. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4986. } else if (dup2(fdin[0], 0) == -1) {
  4987. mg_cry_internal(conn,
  4988. "%s: dup2(%d, 0): %s",
  4989. __func__,
  4990. fdin[0],
  4991. strerror(ERRNO));
  4992. } else if (dup2(fdout[1], 1) == -1) {
  4993. mg_cry_internal(conn,
  4994. "%s: dup2(%d, 1): %s",
  4995. __func__,
  4996. fdout[1],
  4997. strerror(ERRNO));
  4998. } else if (dup2(fderr[1], 2) == -1) {
  4999. mg_cry_internal(conn,
  5000. "%s: dup2(%d, 2): %s",
  5001. __func__,
  5002. fderr[1],
  5003. strerror(ERRNO));
  5004. } else {
  5005. /* Keep stderr and stdout in two different pipes.
  5006. * Stdout will be sent back to the client,
  5007. * stderr should go into a server error log. */
  5008. (void)close(fdin[0]);
  5009. (void)close(fdout[1]);
  5010. (void)close(fderr[1]);
  5011. /* Close write end fdin and read end fdout and fderr */
  5012. (void)close(fdin[1]);
  5013. (void)close(fdout[0]);
  5014. (void)close(fderr[0]);
  5015. /* After exec, all signal handlers are restored to their default
  5016. * values, with one exception of SIGCHLD. According to
  5017. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5018. * will leave unchanged after exec if it was set to be ignored.
  5019. * Restore it to default action. */
  5020. signal(SIGCHLD, SIG_DFL);
  5021. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5022. if (interp == NULL) {
  5023. (void)execle(prog, prog, NULL, envp);
  5024. mg_cry_internal(conn,
  5025. "%s: execle(%s): %s",
  5026. __func__,
  5027. prog,
  5028. strerror(ERRNO));
  5029. } else {
  5030. (void)execle(interp, interp, prog, NULL, envp);
  5031. mg_cry_internal(conn,
  5032. "%s: execle(%s %s): %s",
  5033. __func__,
  5034. interp,
  5035. prog,
  5036. strerror(ERRNO));
  5037. }
  5038. }
  5039. exit(EXIT_FAILURE);
  5040. }
  5041. return pid;
  5042. }
  5043. #endif /* !NO_CGI */
  5044. static int
  5045. set_non_blocking_mode(SOCKET sock)
  5046. {
  5047. int flags = fcntl(sock, F_GETFL, 0);
  5048. if (flags < 0) {
  5049. return -1;
  5050. }
  5051. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5052. return -1;
  5053. }
  5054. return 0;
  5055. }
  5056. static int
  5057. set_blocking_mode(SOCKET sock)
  5058. {
  5059. int flags = fcntl(sock, F_GETFL, 0);
  5060. if (flags < 0) {
  5061. return -1;
  5062. }
  5063. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5064. return -1;
  5065. }
  5066. return 0;
  5067. }
  5068. #endif /* _WIN32 / else */
  5069. /* End of initial operating system specific define block. */
  5070. /* Get a random number (independent of C rand function) */
  5071. static uint64_t
  5072. get_random(void)
  5073. {
  5074. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5075. static uint64_t lcg = 0; /* Linear congruential generator */
  5076. uint64_t now = mg_get_current_time_ns();
  5077. if (lfsr == 0) {
  5078. /* lfsr will be only 0 if has not been initialized,
  5079. * so this code is called only once. */
  5080. lfsr = mg_get_current_time_ns();
  5081. lcg = mg_get_current_time_ns();
  5082. } else {
  5083. /* Get the next step of both random number generators. */
  5084. lfsr = (lfsr >> 1)
  5085. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5086. << 63);
  5087. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5088. }
  5089. /* Combining two pseudo-random number generators and a high resolution
  5090. * part
  5091. * of the current server time will make it hard (impossible?) to guess
  5092. * the
  5093. * next number. */
  5094. return (lfsr ^ lcg ^ now);
  5095. }
  5096. static int
  5097. mg_poll(struct pollfd *pfd,
  5098. unsigned int n,
  5099. int milliseconds,
  5100. volatile int *stop_server)
  5101. {
  5102. /* Call poll, but only for a maximum time of a few seconds.
  5103. * This will allow to stop the server after some seconds, instead
  5104. * of having to wait for a long socket timeout. */
  5105. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5106. do {
  5107. int result;
  5108. if (*stop_server) {
  5109. /* Shut down signal */
  5110. return -2;
  5111. }
  5112. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5113. ms_now = milliseconds;
  5114. }
  5115. result = poll(pfd, n, ms_now);
  5116. if (result != 0) {
  5117. /* Poll returned either success (1) or error (-1).
  5118. * Forward both to the caller. */
  5119. return result;
  5120. }
  5121. /* Poll returned timeout (0). */
  5122. if (milliseconds > 0) {
  5123. milliseconds -= ms_now;
  5124. }
  5125. } while (milliseconds != 0);
  5126. /* timeout: return 0 */
  5127. return 0;
  5128. }
  5129. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5130. * descriptor.
  5131. * Return value:
  5132. * >=0 .. number of bytes successfully written
  5133. * -1 .. timeout
  5134. * -2 .. error
  5135. */
  5136. static int
  5137. push_inner(struct mg_context *ctx,
  5138. FILE *fp,
  5139. SOCKET sock,
  5140. SSL *ssl,
  5141. const char *buf,
  5142. int len,
  5143. double timeout)
  5144. {
  5145. uint64_t start = 0, now = 0, timeout_ns = 0;
  5146. int n, err;
  5147. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5148. #if defined(_WIN32)
  5149. typedef int len_t;
  5150. #else
  5151. typedef size_t len_t;
  5152. #endif
  5153. if (timeout > 0) {
  5154. now = mg_get_current_time_ns();
  5155. start = now;
  5156. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5157. }
  5158. if (ctx == NULL) {
  5159. return -2;
  5160. }
  5161. #if defined(NO_SSL)
  5162. if (ssl) {
  5163. return -2;
  5164. }
  5165. #endif
  5166. /* Try to read until it succeeds, fails, times out, or the server
  5167. * shuts down. */
  5168. for (;;) {
  5169. #if !defined(NO_SSL)
  5170. if (ssl != NULL) {
  5171. n = SSL_write(ssl, buf, len);
  5172. if (n <= 0) {
  5173. err = SSL_get_error(ssl, n);
  5174. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5175. err = ERRNO;
  5176. } else if ((err == SSL_ERROR_WANT_READ)
  5177. || (err == SSL_ERROR_WANT_WRITE)) {
  5178. n = 0;
  5179. } else {
  5180. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5181. return -2;
  5182. }
  5183. } else {
  5184. err = 0;
  5185. }
  5186. } else
  5187. #endif
  5188. if (fp != NULL) {
  5189. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5190. if (ferror(fp)) {
  5191. n = -1;
  5192. err = ERRNO;
  5193. } else {
  5194. err = 0;
  5195. }
  5196. } else {
  5197. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5198. err = (n < 0) ? ERRNO : 0;
  5199. #if defined(_WIN32)
  5200. if (err == WSAEWOULDBLOCK) {
  5201. err = 0;
  5202. n = 0;
  5203. }
  5204. #else
  5205. if (err == EWOULDBLOCK) {
  5206. err = 0;
  5207. n = 0;
  5208. }
  5209. #endif
  5210. if (n < 0) {
  5211. /* shutdown of the socket at client side */
  5212. return -2;
  5213. }
  5214. }
  5215. if (ctx->stop_flag) {
  5216. return -2;
  5217. }
  5218. if ((n > 0) || ((n == 0) && (len == 0))) {
  5219. /* some data has been read, or no data was requested */
  5220. return n;
  5221. }
  5222. if (n < 0) {
  5223. /* socket error - check errno */
  5224. DEBUG_TRACE("send() failed, error %d", err);
  5225. /* TODO (mid): error handling depending on the error code.
  5226. * These codes are different between Windows and Linux.
  5227. * Currently there is no problem with failing send calls,
  5228. * if there is a reproducible situation, it should be
  5229. * investigated in detail.
  5230. */
  5231. return -2;
  5232. }
  5233. /* Only in case n=0 (timeout), repeat calling the write function */
  5234. /* If send failed, wait before retry */
  5235. if (fp != NULL) {
  5236. /* For files, just wait a fixed time.
  5237. * Maybe it helps, maybe not. */
  5238. mg_sleep(5);
  5239. } else {
  5240. /* For sockets, wait for the socket using poll */
  5241. struct pollfd pfd[1];
  5242. int pollres;
  5243. pfd[0].fd = sock;
  5244. pfd[0].events = POLLOUT;
  5245. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5246. if (ctx->stop_flag) {
  5247. return -2;
  5248. }
  5249. if (pollres > 0) {
  5250. continue;
  5251. }
  5252. }
  5253. if (timeout > 0) {
  5254. now = mg_get_current_time_ns();
  5255. if ((now - start) > timeout_ns) {
  5256. /* Timeout */
  5257. break;
  5258. }
  5259. }
  5260. }
  5261. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5262. used */
  5263. return -1;
  5264. }
  5265. static int64_t
  5266. push_all(struct mg_context *ctx,
  5267. FILE *fp,
  5268. SOCKET sock,
  5269. SSL *ssl,
  5270. const char *buf,
  5271. int64_t len)
  5272. {
  5273. double timeout = -1.0;
  5274. int64_t n, nwritten = 0;
  5275. if (ctx == NULL) {
  5276. return -1;
  5277. }
  5278. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5279. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5280. }
  5281. while ((len > 0) && (ctx->stop_flag == 0)) {
  5282. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  5283. if (n < 0) {
  5284. if (nwritten == 0) {
  5285. nwritten = n; /* Propagate the error */
  5286. }
  5287. break;
  5288. } else if (n == 0) {
  5289. break; /* No more data to write */
  5290. } else {
  5291. nwritten += n;
  5292. len -= n;
  5293. }
  5294. }
  5295. return nwritten;
  5296. }
  5297. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5298. * Return value:
  5299. * >=0 .. number of bytes successfully read
  5300. * -1 .. timeout
  5301. * -2 .. error
  5302. */
  5303. static int
  5304. pull_inner(FILE *fp,
  5305. struct mg_connection *conn,
  5306. char *buf,
  5307. int len,
  5308. double timeout)
  5309. {
  5310. int nread, err = 0;
  5311. #if defined(_WIN32)
  5312. typedef int len_t;
  5313. #else
  5314. typedef size_t len_t;
  5315. #endif
  5316. #if !defined(NO_SSL)
  5317. int ssl_pending;
  5318. #endif
  5319. /* We need an additional wait loop around this, because in some cases
  5320. * with TLSwe may get data from the socket but not from SSL_read.
  5321. * In this case we need to repeat at least once.
  5322. */
  5323. if (fp != NULL) {
  5324. #if !defined(_WIN32_WCE)
  5325. /* Use read() instead of fread(), because if we're reading from the
  5326. * CGI pipe, fread() may block until IO buffer is filled up. We
  5327. * cannot afford to block and must pass all read bytes immediately
  5328. * to the client. */
  5329. nread = (int)read(fileno(fp), buf, (size_t)len);
  5330. #else
  5331. /* WinCE does not support CGI pipes */
  5332. nread = (int)fread(buf, 1, (size_t)len, fp);
  5333. #endif
  5334. err = (nread < 0) ? ERRNO : 0;
  5335. if ((nread == 0) && (len > 0)) {
  5336. /* Should get data, but got EOL */
  5337. return -2;
  5338. }
  5339. #if !defined(NO_SSL)
  5340. } else if ((conn->ssl != NULL)
  5341. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5342. /* We already know there is no more data buffered in conn->buf
  5343. * but there is more available in the SSL layer. So don't poll
  5344. * conn->client.sock yet. */
  5345. if (ssl_pending > len) {
  5346. ssl_pending = len;
  5347. }
  5348. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5349. if (nread <= 0) {
  5350. err = SSL_get_error(conn->ssl, nread);
  5351. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5352. err = ERRNO;
  5353. } else if ((err == SSL_ERROR_WANT_READ)
  5354. || (err == SSL_ERROR_WANT_WRITE)) {
  5355. nread = 0;
  5356. } else {
  5357. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5358. return -1;
  5359. }
  5360. } else {
  5361. err = 0;
  5362. }
  5363. } else if (conn->ssl != NULL) {
  5364. struct pollfd pfd[1];
  5365. int pollres;
  5366. pfd[0].fd = conn->client.sock;
  5367. pfd[0].events = POLLIN;
  5368. pollres = mg_poll(pfd,
  5369. 1,
  5370. (int)(timeout * 1000.0),
  5371. &(conn->phys_ctx->stop_flag));
  5372. if (conn->phys_ctx->stop_flag) {
  5373. return -2;
  5374. }
  5375. if (pollres > 0) {
  5376. nread = SSL_read(conn->ssl, buf, len);
  5377. if (nread <= 0) {
  5378. err = SSL_get_error(conn->ssl, nread);
  5379. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5380. err = ERRNO;
  5381. } else if ((err == SSL_ERROR_WANT_READ)
  5382. || (err == SSL_ERROR_WANT_WRITE)) {
  5383. nread = 0;
  5384. } else {
  5385. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5386. return -2;
  5387. }
  5388. } else {
  5389. err = 0;
  5390. }
  5391. } else if (pollres < 0) {
  5392. /* Error */
  5393. return -2;
  5394. } else {
  5395. /* pollres = 0 means timeout */
  5396. nread = 0;
  5397. }
  5398. #endif
  5399. } else {
  5400. struct pollfd pfd[1];
  5401. int pollres;
  5402. pfd[0].fd = conn->client.sock;
  5403. pfd[0].events = POLLIN;
  5404. pollres = mg_poll(pfd,
  5405. 1,
  5406. (int)(timeout * 1000.0),
  5407. &(conn->phys_ctx->stop_flag));
  5408. if (conn->phys_ctx->stop_flag) {
  5409. return -2;
  5410. }
  5411. if (pollres > 0) {
  5412. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5413. err = (nread < 0) ? ERRNO : 0;
  5414. if (nread <= 0) {
  5415. /* shutdown of the socket at client side */
  5416. return -2;
  5417. }
  5418. } else if (pollres < 0) {
  5419. /* error callint poll */
  5420. return -2;
  5421. } else {
  5422. /* pollres = 0 means timeout */
  5423. nread = 0;
  5424. }
  5425. }
  5426. if (conn->phys_ctx->stop_flag) {
  5427. return -2;
  5428. }
  5429. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5430. /* some data has been read, or no data was requested */
  5431. return nread;
  5432. }
  5433. if (nread < 0) {
  5434. /* socket error - check errno */
  5435. #if defined(_WIN32)
  5436. if (err == WSAEWOULDBLOCK) {
  5437. /* TODO (low): check if this is still required */
  5438. /* standard case if called from close_socket_gracefully */
  5439. return -2;
  5440. } else if (err == WSAETIMEDOUT) {
  5441. /* TODO (low): check if this is still required */
  5442. /* timeout is handled by the while loop */
  5443. return 0;
  5444. } else if (err == WSAECONNABORTED) {
  5445. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5446. return -2;
  5447. } else {
  5448. DEBUG_TRACE("recv() failed, error %d", err);
  5449. return -2;
  5450. }
  5451. #else
  5452. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5453. * if the timeout is reached and if the socket was set to non-
  5454. * blocking in close_socket_gracefully, so we can not distinguish
  5455. * here. We have to wait for the timeout in both cases for now.
  5456. */
  5457. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5458. /* TODO (low): check if this is still required */
  5459. /* EAGAIN/EWOULDBLOCK:
  5460. * standard case if called from close_socket_gracefully
  5461. * => should return -1 */
  5462. /* or timeout occurred
  5463. * => the code must stay in the while loop */
  5464. /* EINTR can be generated on a socket with a timeout set even
  5465. * when SA_RESTART is effective for all relevant signals
  5466. * (see signal(7)).
  5467. * => stay in the while loop */
  5468. } else {
  5469. DEBUG_TRACE("recv() failed, error %d", err);
  5470. return -2;
  5471. }
  5472. #endif
  5473. }
  5474. /* Timeout occurred, but no data available. */
  5475. return -1;
  5476. }
  5477. static int
  5478. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5479. {
  5480. int n, nread = 0;
  5481. double timeout = -1.0;
  5482. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5483. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5484. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5485. }
  5486. if (timeout >= 0.0) {
  5487. start_time = mg_get_current_time_ns();
  5488. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5489. }
  5490. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5491. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5492. if (n == -2) {
  5493. if (nread == 0) {
  5494. nread = -1; /* Propagate the error */
  5495. }
  5496. break;
  5497. } else if (n == -1) {
  5498. /* timeout */
  5499. if (timeout >= 0.0) {
  5500. now = mg_get_current_time_ns();
  5501. if ((now - start_time) <= timeout_ns) {
  5502. continue;
  5503. }
  5504. }
  5505. break;
  5506. } else if (n == 0) {
  5507. break; /* No more data to read */
  5508. } else {
  5509. conn->consumed_content += n;
  5510. nread += n;
  5511. len -= n;
  5512. }
  5513. }
  5514. return nread;
  5515. }
  5516. static void
  5517. discard_unread_request_data(struct mg_connection *conn)
  5518. {
  5519. char buf[MG_BUF_LEN];
  5520. size_t to_read;
  5521. int nread;
  5522. if (conn == NULL) {
  5523. return;
  5524. }
  5525. to_read = sizeof(buf);
  5526. if (conn->is_chunked) {
  5527. /* Chunked encoding: 3=chunk read completely
  5528. * completely */
  5529. while (conn->is_chunked != 3) {
  5530. nread = mg_read(conn, buf, to_read);
  5531. if (nread <= 0) {
  5532. break;
  5533. }
  5534. }
  5535. } else {
  5536. /* Not chunked: content length is known */
  5537. while (conn->consumed_content < conn->content_len) {
  5538. if (to_read
  5539. > (size_t)(conn->content_len - conn->consumed_content)) {
  5540. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5541. }
  5542. nread = mg_read(conn, buf, to_read);
  5543. if (nread <= 0) {
  5544. break;
  5545. }
  5546. }
  5547. }
  5548. }
  5549. static int
  5550. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5551. {
  5552. int64_t n, buffered_len, nread;
  5553. int64_t len64 =
  5554. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5555. * int, we may not read more
  5556. * bytes */
  5557. const char *body;
  5558. if (conn == NULL) {
  5559. return 0;
  5560. }
  5561. /* If Content-Length is not set for a request with body data
  5562. * (e.g., a PUT or POST request), we do not know in advance
  5563. * how much data should be read. */
  5564. if (conn->consumed_content == 0) {
  5565. if (conn->is_chunked == 1) {
  5566. conn->content_len = len64;
  5567. conn->is_chunked = 2;
  5568. } else if (conn->content_len == -1) {
  5569. /* The body data is completed when the connection
  5570. * is closed. */
  5571. conn->content_len = INT64_MAX;
  5572. conn->must_close = 1;
  5573. }
  5574. }
  5575. nread = 0;
  5576. if (conn->consumed_content < conn->content_len) {
  5577. /* Adjust number of bytes to read. */
  5578. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5579. if (left_to_read < len64) {
  5580. /* Do not read more than the total content length of the
  5581. * request.
  5582. */
  5583. len64 = left_to_read;
  5584. }
  5585. /* Return buffered data */
  5586. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5587. - conn->consumed_content;
  5588. if (buffered_len > 0) {
  5589. if (len64 < buffered_len) {
  5590. buffered_len = len64;
  5591. }
  5592. body = conn->buf + conn->request_len + conn->consumed_content;
  5593. memcpy(buf, body, (size_t)buffered_len);
  5594. len64 -= buffered_len;
  5595. conn->consumed_content += buffered_len;
  5596. nread += buffered_len;
  5597. buf = (char *)buf + buffered_len;
  5598. }
  5599. /* We have returned all buffered data. Read new data from the remote
  5600. * socket.
  5601. */
  5602. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5603. nread += n;
  5604. } else {
  5605. nread = ((nread > 0) ? nread : n);
  5606. }
  5607. }
  5608. return (int)nread;
  5609. }
  5610. static char
  5611. mg_getc(struct mg_connection *conn)
  5612. {
  5613. char c;
  5614. if (conn == NULL) {
  5615. return 0;
  5616. }
  5617. if (mg_read_inner(conn, &c, 1) <= 0) {
  5618. return (char)0;
  5619. }
  5620. return c;
  5621. }
  5622. int
  5623. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5624. {
  5625. if (len > INT_MAX) {
  5626. len = INT_MAX;
  5627. }
  5628. if (conn == NULL) {
  5629. return 0;
  5630. }
  5631. if (conn->is_chunked) {
  5632. size_t all_read = 0;
  5633. while (len > 0) {
  5634. if (conn->is_chunked == 3) {
  5635. /* No more data left to read */
  5636. return 0;
  5637. }
  5638. if (conn->chunk_remainder) {
  5639. /* copy from the remainder of the last received chunk */
  5640. long read_ret;
  5641. size_t read_now =
  5642. ((conn->chunk_remainder > len) ? (len)
  5643. : (conn->chunk_remainder));
  5644. conn->content_len += (int)read_now;
  5645. read_ret =
  5646. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5647. if (read_ret < 1) {
  5648. /* read error */
  5649. return -1;
  5650. }
  5651. all_read += (size_t)read_ret;
  5652. conn->chunk_remainder -= (size_t)read_ret;
  5653. len -= (size_t)read_ret;
  5654. if (conn->chunk_remainder == 0) {
  5655. /* Add data bytes in the current chunk have been read,
  5656. * so we are expecting \r\n now. */
  5657. char x1, x2;
  5658. conn->content_len += 2;
  5659. x1 = mg_getc(conn);
  5660. x2 = mg_getc(conn);
  5661. if ((x1 != '\r') || (x2 != '\n')) {
  5662. /* Protocol violation */
  5663. return -1;
  5664. }
  5665. }
  5666. } else {
  5667. /* fetch a new chunk */
  5668. int i = 0;
  5669. char lenbuf[64];
  5670. char *end = 0;
  5671. unsigned long chunkSize = 0;
  5672. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5673. conn->content_len++;
  5674. lenbuf[i] = mg_getc(conn);
  5675. if ((i > 0) && (lenbuf[i] == '\r')
  5676. && (lenbuf[i - 1] != '\r')) {
  5677. continue;
  5678. }
  5679. if ((i > 1) && (lenbuf[i] == '\n')
  5680. && (lenbuf[i - 1] == '\r')) {
  5681. lenbuf[i + 1] = 0;
  5682. chunkSize = strtoul(lenbuf, &end, 16);
  5683. if (chunkSize == 0) {
  5684. /* regular end of content */
  5685. conn->is_chunked = 3;
  5686. }
  5687. break;
  5688. }
  5689. if (!isxdigit(lenbuf[i])) {
  5690. /* illegal character for chunk length */
  5691. return -1;
  5692. }
  5693. }
  5694. if ((end == NULL) || (*end != '\r')) {
  5695. /* chunksize not set correctly */
  5696. return -1;
  5697. }
  5698. if (chunkSize == 0) {
  5699. break;
  5700. }
  5701. conn->chunk_remainder = chunkSize;
  5702. }
  5703. }
  5704. return (int)all_read;
  5705. }
  5706. return mg_read_inner(conn, buf, len);
  5707. }
  5708. int
  5709. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5710. {
  5711. time_t now;
  5712. int64_t n, total, allowed;
  5713. if (conn == NULL) {
  5714. return 0;
  5715. }
  5716. if (conn->throttle > 0) {
  5717. if ((now = time(NULL)) != conn->last_throttle_time) {
  5718. conn->last_throttle_time = now;
  5719. conn->last_throttle_bytes = 0;
  5720. }
  5721. allowed = conn->throttle - conn->last_throttle_bytes;
  5722. if (allowed > (int64_t)len) {
  5723. allowed = (int64_t)len;
  5724. }
  5725. if ((total = push_all(conn->phys_ctx,
  5726. NULL,
  5727. conn->client.sock,
  5728. conn->ssl,
  5729. (const char *)buf,
  5730. (int64_t)allowed))
  5731. == allowed) {
  5732. buf = (const char *)buf + total;
  5733. conn->last_throttle_bytes += total;
  5734. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5735. allowed = (conn->throttle > ((int64_t)len - total))
  5736. ? (int64_t)len - total
  5737. : conn->throttle;
  5738. if ((n = push_all(conn->phys_ctx,
  5739. NULL,
  5740. conn->client.sock,
  5741. conn->ssl,
  5742. (const char *)buf,
  5743. (int64_t)allowed))
  5744. != allowed) {
  5745. break;
  5746. }
  5747. sleep(1);
  5748. conn->last_throttle_bytes = allowed;
  5749. conn->last_throttle_time = time(NULL);
  5750. buf = (const char *)buf + n;
  5751. total += n;
  5752. }
  5753. }
  5754. } else {
  5755. total = push_all(conn->phys_ctx,
  5756. NULL,
  5757. conn->client.sock,
  5758. conn->ssl,
  5759. (const char *)buf,
  5760. (int64_t)len);
  5761. }
  5762. if (total > 0) {
  5763. conn->num_bytes_sent += total;
  5764. }
  5765. return (int)total;
  5766. }
  5767. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5768. int
  5769. mg_send_chunk(struct mg_connection *conn,
  5770. const char *chunk,
  5771. unsigned int chunk_len)
  5772. {
  5773. char lenbuf[16];
  5774. size_t lenbuf_len;
  5775. int ret;
  5776. int t;
  5777. /* First store the length information in a text buffer. */
  5778. sprintf(lenbuf, "%x\r\n", chunk_len);
  5779. lenbuf_len = strlen(lenbuf);
  5780. /* Then send length information, chunk and terminating \r\n. */
  5781. ret = mg_write(conn, lenbuf, lenbuf_len);
  5782. if (ret != (int)lenbuf_len) {
  5783. return -1;
  5784. }
  5785. t = ret;
  5786. ret = mg_write(conn, chunk, chunk_len);
  5787. if (ret != (int)chunk_len) {
  5788. return -1;
  5789. }
  5790. t += ret;
  5791. ret = mg_write(conn, "\r\n", 2);
  5792. if (ret != 2) {
  5793. return -1;
  5794. }
  5795. t += ret;
  5796. return t;
  5797. }
  5798. #if defined(GCC_DIAGNOSTIC)
  5799. /* This block forwards format strings to printf implementations,
  5800. * so we need to disable the format-nonliteral warning. */
  5801. #pragma GCC diagnostic push
  5802. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5803. #endif
  5804. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5805. static int
  5806. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5807. {
  5808. va_list ap_copy;
  5809. size_t size = MG_BUF_LEN / 4;
  5810. int len = -1;
  5811. *buf = NULL;
  5812. while (len < 0) {
  5813. if (*buf) {
  5814. mg_free(*buf);
  5815. }
  5816. size *= 4;
  5817. *buf = (char *)mg_malloc(size);
  5818. if (!*buf) {
  5819. break;
  5820. }
  5821. va_copy(ap_copy, ap);
  5822. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5823. va_end(ap_copy);
  5824. (*buf)[size - 1] = 0;
  5825. }
  5826. return len;
  5827. }
  5828. /* Print message to buffer. If buffer is large enough to hold the message,
  5829. * return buffer. If buffer is to small, allocate large enough buffer on
  5830. * heap,
  5831. * and return allocated buffer. */
  5832. static int
  5833. alloc_vprintf(char **out_buf,
  5834. char *prealloc_buf,
  5835. size_t prealloc_size,
  5836. const char *fmt,
  5837. va_list ap)
  5838. {
  5839. va_list ap_copy;
  5840. int len;
  5841. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5842. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5843. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5844. * Therefore, we make two passes: on first pass, get required message
  5845. * length.
  5846. * On second pass, actually print the message. */
  5847. va_copy(ap_copy, ap);
  5848. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5849. va_end(ap_copy);
  5850. if (len < 0) {
  5851. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5852. * Switch to alternative code path that uses incremental
  5853. * allocations.
  5854. */
  5855. va_copy(ap_copy, ap);
  5856. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5857. va_end(ap_copy);
  5858. } else if ((size_t)(len) >= prealloc_size) {
  5859. /* The pre-allocated buffer not large enough. */
  5860. /* Allocate a new buffer. */
  5861. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5862. if (!*out_buf) {
  5863. /* Allocation failed. Return -1 as "out of memory" error. */
  5864. return -1;
  5865. }
  5866. /* Buffer allocation successful. Store the string there. */
  5867. va_copy(ap_copy, ap);
  5868. IGNORE_UNUSED_RESULT(
  5869. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5870. va_end(ap_copy);
  5871. } else {
  5872. /* The pre-allocated buffer is large enough.
  5873. * Use it to store the string and return the address. */
  5874. va_copy(ap_copy, ap);
  5875. IGNORE_UNUSED_RESULT(
  5876. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5877. va_end(ap_copy);
  5878. *out_buf = prealloc_buf;
  5879. }
  5880. return len;
  5881. }
  5882. #if defined(GCC_DIAGNOSTIC)
  5883. /* Enable format-nonliteral warning again. */
  5884. #pragma GCC diagnostic pop
  5885. #endif
  5886. static int
  5887. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5888. {
  5889. char mem[MG_BUF_LEN];
  5890. char *buf = NULL;
  5891. int len;
  5892. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5893. len = mg_write(conn, buf, (size_t)len);
  5894. }
  5895. if ((buf != mem) && (buf != NULL)) {
  5896. mg_free(buf);
  5897. }
  5898. return len;
  5899. }
  5900. int
  5901. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5902. {
  5903. va_list ap;
  5904. int result;
  5905. va_start(ap, fmt);
  5906. result = mg_vprintf(conn, fmt, ap);
  5907. va_end(ap);
  5908. return result;
  5909. }
  5910. int
  5911. mg_url_decode(const char *src,
  5912. int src_len,
  5913. char *dst,
  5914. int dst_len,
  5915. int is_form_url_encoded)
  5916. {
  5917. int i, j, a, b;
  5918. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5919. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5920. if ((i < src_len - 2) && (src[i] == '%')
  5921. && isxdigit(*(const unsigned char *)(src + i + 1))
  5922. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5923. a = tolower(*(const unsigned char *)(src + i + 1));
  5924. b = tolower(*(const unsigned char *)(src + i + 2));
  5925. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5926. i += 2;
  5927. } else if (is_form_url_encoded && (src[i] == '+')) {
  5928. dst[j] = ' ';
  5929. } else {
  5930. dst[j] = src[i];
  5931. }
  5932. }
  5933. dst[j] = '\0'; /* Null-terminate the destination */
  5934. return (i >= src_len) ? j : -1;
  5935. }
  5936. int
  5937. mg_get_var(const char *data,
  5938. size_t data_len,
  5939. const char *name,
  5940. char *dst,
  5941. size_t dst_len)
  5942. {
  5943. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5944. }
  5945. int
  5946. mg_get_var2(const char *data,
  5947. size_t data_len,
  5948. const char *name,
  5949. char *dst,
  5950. size_t dst_len,
  5951. size_t occurrence)
  5952. {
  5953. const char *p, *e, *s;
  5954. size_t name_len;
  5955. int len;
  5956. if ((dst == NULL) || (dst_len == 0)) {
  5957. len = -2;
  5958. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5959. len = -1;
  5960. dst[0] = '\0';
  5961. } else {
  5962. name_len = strlen(name);
  5963. e = data + data_len;
  5964. len = -1;
  5965. dst[0] = '\0';
  5966. /* data is "var1=val1&var2=val2...". Find variable first */
  5967. for (p = data; p + name_len < e; p++) {
  5968. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5969. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5970. /* Point p to variable value */
  5971. p += name_len + 1;
  5972. /* Point s to the end of the value */
  5973. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5974. if (s == NULL) {
  5975. s = e;
  5976. }
  5977. DEBUG_ASSERT(s >= p);
  5978. if (s < p) {
  5979. return -3;
  5980. }
  5981. /* Decode variable into destination buffer */
  5982. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5983. /* Redirect error code from -1 to -2 (destination buffer too
  5984. * small). */
  5985. if (len == -1) {
  5986. len = -2;
  5987. }
  5988. break;
  5989. }
  5990. }
  5991. }
  5992. return len;
  5993. }
  5994. /* HCP24: some changes to compare hole var_name */
  5995. int
  5996. mg_get_cookie(const char *cookie_header,
  5997. const char *var_name,
  5998. char *dst,
  5999. size_t dst_size)
  6000. {
  6001. const char *s, *p, *end;
  6002. int name_len, len = -1;
  6003. if ((dst == NULL) || (dst_size == 0)) {
  6004. return -2;
  6005. }
  6006. dst[0] = '\0';
  6007. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6008. return -1;
  6009. }
  6010. name_len = (int)strlen(var_name);
  6011. end = s + strlen(s);
  6012. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6013. if (s[name_len] == '=') {
  6014. /* HCP24: now check is it a substring or a full cookie name */
  6015. if ((s == cookie_header) || (s[-1] == ' ')) {
  6016. s += name_len + 1;
  6017. if ((p = strchr(s, ' ')) == NULL) {
  6018. p = end;
  6019. }
  6020. if (p[-1] == ';') {
  6021. p--;
  6022. }
  6023. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6024. s++;
  6025. p--;
  6026. }
  6027. if ((size_t)(p - s) < dst_size) {
  6028. len = (int)(p - s);
  6029. mg_strlcpy(dst, s, (size_t)len + 1);
  6030. } else {
  6031. len = -3;
  6032. }
  6033. break;
  6034. }
  6035. }
  6036. }
  6037. return len;
  6038. }
  6039. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6040. static void
  6041. base64_encode(const unsigned char *src, int src_len, char *dst)
  6042. {
  6043. static const char *b64 =
  6044. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6045. int i, j, a, b, c;
  6046. for (i = j = 0; i < src_len; i += 3) {
  6047. a = src[i];
  6048. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6049. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6050. dst[j++] = b64[a >> 2];
  6051. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6052. if (i + 1 < src_len) {
  6053. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6054. }
  6055. if (i + 2 < src_len) {
  6056. dst[j++] = b64[c & 63];
  6057. }
  6058. }
  6059. while (j % 4 != 0) {
  6060. dst[j++] = '=';
  6061. }
  6062. dst[j++] = '\0';
  6063. }
  6064. #endif
  6065. #if defined(USE_LUA)
  6066. static unsigned char
  6067. b64reverse(char letter)
  6068. {
  6069. if ((letter >= 'A') && (letter <= 'Z')) {
  6070. return letter - 'A';
  6071. }
  6072. if ((letter >= 'a') && (letter <= 'z')) {
  6073. return letter - 'a' + 26;
  6074. }
  6075. if ((letter >= '0') && (letter <= '9')) {
  6076. return letter - '0' + 52;
  6077. }
  6078. if (letter == '+') {
  6079. return 62;
  6080. }
  6081. if (letter == '/') {
  6082. return 63;
  6083. }
  6084. if (letter == '=') {
  6085. return 255; /* normal end */
  6086. }
  6087. return 254; /* error */
  6088. }
  6089. static int
  6090. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6091. {
  6092. int i;
  6093. unsigned char a, b, c, d;
  6094. *dst_len = 0;
  6095. for (i = 0; i < src_len; i += 4) {
  6096. a = b64reverse(src[i]);
  6097. if (a >= 254) {
  6098. return i;
  6099. }
  6100. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6101. if (b >= 254) {
  6102. return i + 1;
  6103. }
  6104. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6105. if (c == 254) {
  6106. return i + 2;
  6107. }
  6108. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6109. if (d == 254) {
  6110. return i + 3;
  6111. }
  6112. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6113. if (c != 255) {
  6114. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6115. if (d != 255) {
  6116. dst[(*dst_len)++] = (c << 6) + d;
  6117. }
  6118. }
  6119. }
  6120. return -1;
  6121. }
  6122. #endif
  6123. static int
  6124. is_put_or_delete_method(const struct mg_connection *conn)
  6125. {
  6126. if (conn) {
  6127. const char *s = conn->request_info.request_method;
  6128. return (s != NULL)
  6129. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6130. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6131. }
  6132. return 0;
  6133. }
  6134. #if !defined(NO_FILES)
  6135. static int
  6136. extention_matches_script(
  6137. struct mg_connection *conn, /* in: request (must be valid) */
  6138. const char *filename /* in: filename (must be valid) */
  6139. )
  6140. {
  6141. #if !defined(NO_CGI)
  6142. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6143. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6144. filename)
  6145. > 0) {
  6146. return 1;
  6147. }
  6148. #endif
  6149. #if defined(USE_LUA)
  6150. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6151. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6152. filename)
  6153. > 0) {
  6154. return 1;
  6155. }
  6156. #endif
  6157. #if defined(USE_DUKTAPE)
  6158. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6159. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6160. filename)
  6161. > 0) {
  6162. return 1;
  6163. }
  6164. #endif
  6165. /* filename and conn could be unused, if all preocessor conditions
  6166. * are false (no script language supported). */
  6167. (void)filename;
  6168. (void)conn;
  6169. return 0;
  6170. }
  6171. /* For given directory path, substitute it to valid index file.
  6172. * Return 1 if index file has been found, 0 if not found.
  6173. * If the file is found, it's stats is returned in stp. */
  6174. static int
  6175. substitute_index_file(struct mg_connection *conn,
  6176. char *path,
  6177. size_t path_len,
  6178. struct mg_file_stat *filestat)
  6179. {
  6180. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6181. struct vec filename_vec;
  6182. size_t n = strlen(path);
  6183. int found = 0;
  6184. /* The 'path' given to us points to the directory. Remove all trailing
  6185. * directory separator characters from the end of the path, and
  6186. * then append single directory separator character. */
  6187. while ((n > 0) && (path[n - 1] == '/')) {
  6188. n--;
  6189. }
  6190. path[n] = '/';
  6191. /* Traverse index files list. For each entry, append it to the given
  6192. * path and see if the file exists. If it exists, break the loop */
  6193. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6194. /* Ignore too long entries that may overflow path buffer */
  6195. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6196. continue;
  6197. }
  6198. /* Prepare full path to the index file */
  6199. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6200. /* Does it exist? */
  6201. if (mg_stat(conn, path, filestat)) {
  6202. /* Yes it does, break the loop */
  6203. found = 1;
  6204. break;
  6205. }
  6206. }
  6207. /* If no index file exists, restore directory path */
  6208. if (!found) {
  6209. path[n] = '\0';
  6210. }
  6211. return found;
  6212. }
  6213. #endif
  6214. static void
  6215. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6216. char *filename, /* out: filename */
  6217. size_t filename_buf_len, /* in: size of filename buffer */
  6218. struct mg_file_stat *filestat, /* out: file status structure */
  6219. int *is_found, /* out: file found (directly) */
  6220. int *is_script_resource, /* out: handled by a script? */
  6221. int *is_websocket_request, /* out: websocket connetion? */
  6222. int *is_put_or_delete_request /* out: put/delete a file? */
  6223. )
  6224. {
  6225. char const *accept_encoding;
  6226. #if !defined(NO_FILES)
  6227. const char *uri = conn->request_info.local_uri;
  6228. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6229. const char *rewrite;
  6230. struct vec a, b;
  6231. ptrdiff_t match_len;
  6232. char gz_path[PATH_MAX];
  6233. int truncated;
  6234. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6235. char *tmp_str;
  6236. size_t tmp_str_len, sep_pos;
  6237. int allow_substitute_script_subresources;
  6238. #endif
  6239. #else
  6240. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6241. #endif
  6242. /* Step 1: Set all initially unknown outputs to zero */
  6243. memset(filestat, 0, sizeof(*filestat));
  6244. *filename = 0;
  6245. *is_found = 0;
  6246. *is_script_resource = 0;
  6247. /* Step 2: Check if the request attempts to modify the file system */
  6248. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6249. /* Step 3: Check if it is a websocket request, and modify the document
  6250. * root if required */
  6251. #if defined(USE_WEBSOCKET)
  6252. *is_websocket_request = is_websocket_protocol(conn);
  6253. #if !defined(NO_FILES)
  6254. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6255. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6256. }
  6257. #endif /* !NO_FILES */
  6258. #else /* USE_WEBSOCKET */
  6259. *is_websocket_request = 0;
  6260. #endif /* USE_WEBSOCKET */
  6261. /* Step 4: Check if gzip encoded response is allowed */
  6262. conn->accept_gzip = 0;
  6263. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6264. if (strstr(accept_encoding, "gzip") != NULL) {
  6265. conn->accept_gzip = 1;
  6266. }
  6267. }
  6268. #if !defined(NO_FILES)
  6269. /* Step 5: If there is no root directory, don't look for files. */
  6270. /* Note that root == NULL is a regular use case here. This occurs,
  6271. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6272. * config is not required. */
  6273. if (root == NULL) {
  6274. /* all file related outputs have already been set to 0, just return
  6275. */
  6276. return;
  6277. }
  6278. /* Step 6: Determine the local file path from the root path and the
  6279. * request uri. */
  6280. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6281. * part of the path one byte on the right. */
  6282. mg_snprintf(
  6283. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6284. if (truncated) {
  6285. goto interpret_cleanup;
  6286. }
  6287. /* Step 7: URI rewriting */
  6288. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6289. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6290. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6291. mg_snprintf(conn,
  6292. &truncated,
  6293. filename,
  6294. filename_buf_len - 1,
  6295. "%.*s%s",
  6296. (int)b.len,
  6297. b.ptr,
  6298. uri + match_len);
  6299. break;
  6300. }
  6301. }
  6302. if (truncated) {
  6303. goto interpret_cleanup;
  6304. }
  6305. /* Step 8: Check if the file exists at the server */
  6306. /* Local file path and name, corresponding to requested URI
  6307. * is now stored in "filename" variable. */
  6308. if (mg_stat(conn, filename, filestat)) {
  6309. int uri_len = (int)strlen(uri);
  6310. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6311. /* 8.1: File exists. */
  6312. *is_found = 1;
  6313. /* 8.2: Check if it is a script type. */
  6314. if (extention_matches_script(conn, filename)) {
  6315. /* The request addresses a CGI resource, Lua script or
  6316. * server-side javascript.
  6317. * The URI corresponds to the script itself (like
  6318. * /path/script.cgi), and there is no additional resource
  6319. * path (like /path/script.cgi/something).
  6320. * Requests that modify (replace or delete) a resource, like
  6321. * PUT and DELETE requests, should replace/delete the script
  6322. * file.
  6323. * Requests that read or write from/to a resource, like GET and
  6324. * POST requests, should call the script and return the
  6325. * generated response. */
  6326. *is_script_resource = (!*is_put_or_delete_request);
  6327. }
  6328. /* 8.3: If the request target is a directory, there could be
  6329. * a substitute file (index.html, index.cgi, ...). */
  6330. if (filestat->is_directory && is_uri_end_slash) {
  6331. /* Use a local copy here, since substitute_index_file will
  6332. * change the content of the file status */
  6333. struct mg_file_stat tmp_filestat;
  6334. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6335. if (substitute_index_file(
  6336. conn, filename, filename_buf_len, &tmp_filestat)) {
  6337. /* Substitute file found. Copy stat to the output, then
  6338. * check if the file is a script file */
  6339. *filestat = tmp_filestat;
  6340. if (extention_matches_script(conn, filename)) {
  6341. /* Substitute file is a script file */
  6342. *is_script_resource = 1;
  6343. } else {
  6344. /* Substitute file is a regular file */
  6345. *is_script_resource = 0;
  6346. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6347. }
  6348. }
  6349. /* If there is no substitute file, the server could return
  6350. * a directory listing in a later step */
  6351. }
  6352. return;
  6353. }
  6354. /* Step 9: Check for zipped files: */
  6355. /* If we can't find the actual file, look for the file
  6356. * with the same name but a .gz extension. If we find it,
  6357. * use that and set the gzipped flag in the file struct
  6358. * to indicate that the response need to have the content-
  6359. * encoding: gzip header.
  6360. * We can only do this if the browser declares support. */
  6361. if (conn->accept_gzip) {
  6362. mg_snprintf(
  6363. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6364. if (truncated) {
  6365. goto interpret_cleanup;
  6366. }
  6367. if (mg_stat(conn, gz_path, filestat)) {
  6368. if (filestat) {
  6369. filestat->is_gzipped = 1;
  6370. *is_found = 1;
  6371. }
  6372. /* Currently gz files can not be scripts. */
  6373. return;
  6374. }
  6375. }
  6376. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6377. /* Step 10: Script resources may handle sub-resources */
  6378. /* Support PATH_INFO for CGI scripts. */
  6379. tmp_str_len = strlen(filename);
  6380. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6381. if (!tmp_str) {
  6382. /* Out of memory */
  6383. goto interpret_cleanup;
  6384. }
  6385. memcpy(tmp_str, filename, tmp_str_len + 1);
  6386. /* Check config, if index scripts may have sub-resources */
  6387. allow_substitute_script_subresources =
  6388. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6389. "yes");
  6390. sep_pos = tmp_str_len;
  6391. while (sep_pos > 0) {
  6392. sep_pos--;
  6393. if (tmp_str[sep_pos] == '/') {
  6394. int is_script = 0, does_exist = 0;
  6395. tmp_str[sep_pos] = 0;
  6396. if (tmp_str[0]) {
  6397. is_script = extention_matches_script(conn, tmp_str);
  6398. does_exist = mg_stat(conn, tmp_str, filestat);
  6399. }
  6400. if (does_exist && is_script) {
  6401. filename[sep_pos] = 0;
  6402. memmove(filename + sep_pos + 2,
  6403. filename + sep_pos + 1,
  6404. strlen(filename + sep_pos + 1) + 1);
  6405. conn->path_info = filename + sep_pos + 1;
  6406. filename[sep_pos + 1] = '/';
  6407. *is_script_resource = 1;
  6408. *is_found = 1;
  6409. break;
  6410. }
  6411. if (allow_substitute_script_subresources) {
  6412. if (substitute_index_file(
  6413. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6414. /* some intermediate directory has an index file */
  6415. if (extention_matches_script(conn, tmp_str)) {
  6416. char *tmp_str2;
  6417. DEBUG_TRACE("Substitute script %s serving path %s",
  6418. tmp_str,
  6419. filename);
  6420. /* this index file is a script */
  6421. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6422. conn->phys_ctx);
  6423. mg_snprintf(conn,
  6424. &truncated,
  6425. filename,
  6426. filename_buf_len,
  6427. "%s//%s",
  6428. tmp_str,
  6429. tmp_str2);
  6430. mg_free(tmp_str2);
  6431. if (truncated) {
  6432. mg_free(tmp_str);
  6433. goto interpret_cleanup;
  6434. }
  6435. sep_pos = strlen(tmp_str);
  6436. filename[sep_pos] = 0;
  6437. conn->path_info = filename + sep_pos + 1;
  6438. *is_script_resource = 1;
  6439. *is_found = 1;
  6440. break;
  6441. } else {
  6442. DEBUG_TRACE("Substitute file %s serving path %s",
  6443. tmp_str,
  6444. filename);
  6445. /* non-script files will not have sub-resources */
  6446. filename[sep_pos] = 0;
  6447. conn->path_info = 0;
  6448. *is_script_resource = 0;
  6449. *is_found = 0;
  6450. break;
  6451. }
  6452. }
  6453. }
  6454. tmp_str[sep_pos] = '/';
  6455. }
  6456. }
  6457. mg_free(tmp_str);
  6458. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6459. #endif /* !defined(NO_FILES) */
  6460. return;
  6461. #if !defined(NO_FILES)
  6462. /* Reset all outputs */
  6463. interpret_cleanup:
  6464. memset(filestat, 0, sizeof(*filestat));
  6465. *filename = 0;
  6466. *is_found = 0;
  6467. *is_script_resource = 0;
  6468. *is_websocket_request = 0;
  6469. *is_put_or_delete_request = 0;
  6470. #endif /* !defined(NO_FILES) */
  6471. }
  6472. /* Check whether full request is buffered. Return:
  6473. * -1 if request or response is malformed
  6474. * 0 if request or response is not yet fully buffered
  6475. * >0 actual request length, including last \r\n\r\n */
  6476. static int
  6477. get_http_header_len(const char *buf, int buflen)
  6478. {
  6479. int i;
  6480. for (i = 0; i < buflen; i++) {
  6481. /* Do an unsigned comparison in some conditions below */
  6482. const unsigned char c = ((const unsigned char *)buf)[i];
  6483. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6484. && !isprint(c)) {
  6485. /* abort scan as soon as one malformed character is found */
  6486. return -1;
  6487. }
  6488. if (i < buflen - 1) {
  6489. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6490. /* Two newline, no carriage return - not standard compliant,
  6491. * but
  6492. * it
  6493. * should be accepted */
  6494. return i + 2;
  6495. }
  6496. }
  6497. if (i < buflen - 3) {
  6498. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6499. && (buf[i + 3] == '\n')) {
  6500. /* Two \r\n - standard compliant */
  6501. return i + 4;
  6502. }
  6503. }
  6504. }
  6505. return 0;
  6506. }
  6507. #if !defined(NO_CACHING)
  6508. /* Convert month to the month number. Return -1 on error, or month number */
  6509. static int
  6510. get_month_index(const char *s)
  6511. {
  6512. size_t i;
  6513. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6514. if (!strcmp(s, month_names[i])) {
  6515. return (int)i;
  6516. }
  6517. }
  6518. return -1;
  6519. }
  6520. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6521. static time_t
  6522. parse_date_string(const char *datetime)
  6523. {
  6524. char month_str[32] = {0};
  6525. int second, minute, hour, day, month, year;
  6526. time_t result = (time_t)0;
  6527. struct tm tm;
  6528. if ((sscanf(datetime,
  6529. "%d/%3s/%d %d:%d:%d",
  6530. &day,
  6531. month_str,
  6532. &year,
  6533. &hour,
  6534. &minute,
  6535. &second)
  6536. == 6)
  6537. || (sscanf(datetime,
  6538. "%d %3s %d %d:%d:%d",
  6539. &day,
  6540. month_str,
  6541. &year,
  6542. &hour,
  6543. &minute,
  6544. &second)
  6545. == 6)
  6546. || (sscanf(datetime,
  6547. "%*3s, %d %3s %d %d:%d:%d",
  6548. &day,
  6549. month_str,
  6550. &year,
  6551. &hour,
  6552. &minute,
  6553. &second)
  6554. == 6)
  6555. || (sscanf(datetime,
  6556. "%d-%3s-%d %d:%d:%d",
  6557. &day,
  6558. month_str,
  6559. &year,
  6560. &hour,
  6561. &minute,
  6562. &second)
  6563. == 6)) {
  6564. month = get_month_index(month_str);
  6565. if ((month >= 0) && (year >= 1970)) {
  6566. memset(&tm, 0, sizeof(tm));
  6567. tm.tm_year = year - 1900;
  6568. tm.tm_mon = month;
  6569. tm.tm_mday = day;
  6570. tm.tm_hour = hour;
  6571. tm.tm_min = minute;
  6572. tm.tm_sec = second;
  6573. result = timegm(&tm);
  6574. }
  6575. }
  6576. return result;
  6577. }
  6578. #endif /* !NO_CACHING */
  6579. /* Protect against directory disclosure attack by removing '..',
  6580. * excessive '/' and '\' characters */
  6581. static void
  6582. remove_double_dots_and_double_slashes(char *s)
  6583. {
  6584. char *p = s;
  6585. while ((s[0] == '.') && (s[1] == '.')) {
  6586. s++;
  6587. }
  6588. while (*s != '\0') {
  6589. *p++ = *s++;
  6590. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6591. /* Skip all following slashes, backslashes and double-dots */
  6592. while (s[0] != '\0') {
  6593. if ((s[0] == '/') || (s[0] == '\\')) {
  6594. s++;
  6595. } else if ((s[0] == '.') && (s[1] == '.')) {
  6596. s += 2;
  6597. } else {
  6598. break;
  6599. }
  6600. }
  6601. }
  6602. }
  6603. *p = '\0';
  6604. }
  6605. static const struct {
  6606. const char *extension;
  6607. size_t ext_len;
  6608. const char *mime_type;
  6609. } builtin_mime_types[] = {
  6610. /* IANA registered MIME types
  6611. * (http://www.iana.org/assignments/media-types)
  6612. * application types */
  6613. {".doc", 4, "application/msword"},
  6614. {".eps", 4, "application/postscript"},
  6615. {".exe", 4, "application/octet-stream"},
  6616. {".js", 3, "application/javascript"},
  6617. {".json", 5, "application/json"},
  6618. {".pdf", 4, "application/pdf"},
  6619. {".ps", 3, "application/postscript"},
  6620. {".rtf", 4, "application/rtf"},
  6621. {".xhtml", 6, "application/xhtml+xml"},
  6622. {".xsl", 4, "application/xml"},
  6623. {".xslt", 5, "application/xml"},
  6624. /* fonts */
  6625. {".ttf", 4, "application/font-sfnt"},
  6626. {".cff", 4, "application/font-sfnt"},
  6627. {".otf", 4, "application/font-sfnt"},
  6628. {".aat", 4, "application/font-sfnt"},
  6629. {".sil", 4, "application/font-sfnt"},
  6630. {".pfr", 4, "application/font-tdpfr"},
  6631. {".woff", 5, "application/font-woff"},
  6632. /* audio */
  6633. {".mp3", 4, "audio/mpeg"},
  6634. {".oga", 4, "audio/ogg"},
  6635. {".ogg", 4, "audio/ogg"},
  6636. /* image */
  6637. {".gif", 4, "image/gif"},
  6638. {".ief", 4, "image/ief"},
  6639. {".jpeg", 5, "image/jpeg"},
  6640. {".jpg", 4, "image/jpeg"},
  6641. {".jpm", 4, "image/jpm"},
  6642. {".jpx", 4, "image/jpx"},
  6643. {".png", 4, "image/png"},
  6644. {".svg", 4, "image/svg+xml"},
  6645. {".tif", 4, "image/tiff"},
  6646. {".tiff", 5, "image/tiff"},
  6647. /* model */
  6648. {".wrl", 4, "model/vrml"},
  6649. /* text */
  6650. {".css", 4, "text/css"},
  6651. {".csv", 4, "text/csv"},
  6652. {".htm", 4, "text/html"},
  6653. {".html", 5, "text/html"},
  6654. {".sgm", 4, "text/sgml"},
  6655. {".shtm", 5, "text/html"},
  6656. {".shtml", 6, "text/html"},
  6657. {".txt", 4, "text/plain"},
  6658. {".xml", 4, "text/xml"},
  6659. /* video */
  6660. {".mov", 4, "video/quicktime"},
  6661. {".mp4", 4, "video/mp4"},
  6662. {".mpeg", 5, "video/mpeg"},
  6663. {".mpg", 4, "video/mpeg"},
  6664. {".ogv", 4, "video/ogg"},
  6665. {".qt", 3, "video/quicktime"},
  6666. /* not registered types
  6667. * (http://reference.sitepoint.com/html/mime-types-full,
  6668. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6669. {".arj", 4, "application/x-arj-compressed"},
  6670. {".gz", 3, "application/x-gunzip"},
  6671. {".rar", 4, "application/x-arj-compressed"},
  6672. {".swf", 4, "application/x-shockwave-flash"},
  6673. {".tar", 4, "application/x-tar"},
  6674. {".tgz", 4, "application/x-tar-gz"},
  6675. {".torrent", 8, "application/x-bittorrent"},
  6676. {".ppt", 4, "application/x-mspowerpoint"},
  6677. {".xls", 4, "application/x-msexcel"},
  6678. {".zip", 4, "application/x-zip-compressed"},
  6679. {".aac",
  6680. 4,
  6681. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6682. {".aif", 4, "audio/x-aif"},
  6683. {".m3u", 4, "audio/x-mpegurl"},
  6684. {".mid", 4, "audio/x-midi"},
  6685. {".ra", 3, "audio/x-pn-realaudio"},
  6686. {".ram", 4, "audio/x-pn-realaudio"},
  6687. {".wav", 4, "audio/x-wav"},
  6688. {".bmp", 4, "image/bmp"},
  6689. {".ico", 4, "image/x-icon"},
  6690. {".pct", 4, "image/x-pct"},
  6691. {".pict", 5, "image/pict"},
  6692. {".rgb", 4, "image/x-rgb"},
  6693. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6694. {".asf", 4, "video/x-ms-asf"},
  6695. {".avi", 4, "video/x-msvideo"},
  6696. {".m4v", 4, "video/x-m4v"},
  6697. {NULL, 0, NULL}};
  6698. const char *
  6699. mg_get_builtin_mime_type(const char *path)
  6700. {
  6701. const char *ext;
  6702. size_t i, path_len;
  6703. path_len = strlen(path);
  6704. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6705. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6706. if ((path_len > builtin_mime_types[i].ext_len)
  6707. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6708. return builtin_mime_types[i].mime_type;
  6709. }
  6710. }
  6711. return "text/plain";
  6712. }
  6713. /* Look at the "path" extension and figure what mime type it has.
  6714. * Store mime type in the vector. */
  6715. static void
  6716. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6717. {
  6718. struct vec ext_vec, mime_vec;
  6719. const char *list, *ext;
  6720. size_t path_len;
  6721. path_len = strlen(path);
  6722. if ((conn == NULL) || (vec == NULL)) {
  6723. if (vec != NULL) {
  6724. memset(vec, '\0', sizeof(struct vec));
  6725. }
  6726. return;
  6727. }
  6728. /* Scan user-defined mime types first, in case user wants to
  6729. * override default mime types. */
  6730. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6731. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6732. /* ext now points to the path suffix */
  6733. ext = path + path_len - ext_vec.len;
  6734. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6735. *vec = mime_vec;
  6736. return;
  6737. }
  6738. }
  6739. vec->ptr = mg_get_builtin_mime_type(path);
  6740. vec->len = strlen(vec->ptr);
  6741. }
  6742. /* Stringify binary data. Output buffer must be twice as big as input,
  6743. * because each byte takes 2 bytes in string representation */
  6744. static void
  6745. bin2str(char *to, const unsigned char *p, size_t len)
  6746. {
  6747. static const char *hex = "0123456789abcdef";
  6748. for (; len--; p++) {
  6749. *to++ = hex[p[0] >> 4];
  6750. *to++ = hex[p[0] & 0x0f];
  6751. }
  6752. *to = '\0';
  6753. }
  6754. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6755. */
  6756. char *
  6757. mg_md5(char buf[33], ...)
  6758. {
  6759. md5_byte_t hash[16];
  6760. const char *p;
  6761. va_list ap;
  6762. md5_state_t ctx;
  6763. md5_init(&ctx);
  6764. va_start(ap, buf);
  6765. while ((p = va_arg(ap, const char *)) != NULL) {
  6766. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6767. }
  6768. va_end(ap);
  6769. md5_finish(&ctx, hash);
  6770. bin2str(buf, hash, sizeof(hash));
  6771. return buf;
  6772. }
  6773. /* Check the user's password, return 1 if OK */
  6774. static int
  6775. check_password(const char *method,
  6776. const char *ha1,
  6777. const char *uri,
  6778. const char *nonce,
  6779. const char *nc,
  6780. const char *cnonce,
  6781. const char *qop,
  6782. const char *response)
  6783. {
  6784. char ha2[32 + 1], expected_response[32 + 1];
  6785. /* Some of the parameters may be NULL */
  6786. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6787. || (qop == NULL) || (response == NULL)) {
  6788. return 0;
  6789. }
  6790. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6791. if (strlen(response) != 32) {
  6792. return 0;
  6793. }
  6794. mg_md5(ha2, method, ":", uri, NULL);
  6795. mg_md5(expected_response,
  6796. ha1,
  6797. ":",
  6798. nonce,
  6799. ":",
  6800. nc,
  6801. ":",
  6802. cnonce,
  6803. ":",
  6804. qop,
  6805. ":",
  6806. ha2,
  6807. NULL);
  6808. return mg_strcasecmp(response, expected_response) == 0;
  6809. }
  6810. /* Use the global passwords file, if specified by auth_gpass option,
  6811. * or search for .htpasswd in the requested directory. */
  6812. static void
  6813. open_auth_file(struct mg_connection *conn,
  6814. const char *path,
  6815. struct mg_file *filep)
  6816. {
  6817. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6818. char name[PATH_MAX];
  6819. const char *p, *e,
  6820. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6821. int truncated;
  6822. if (gpass != NULL) {
  6823. /* Use global passwords file */
  6824. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6825. #if defined(DEBUG)
  6826. /* Use mg_cry_internal here, since gpass has been configured. */
  6827. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6828. #endif
  6829. }
  6830. /* Important: using local struct mg_file to test path for
  6831. * is_directory flag. If filep is used, mg_stat() makes it
  6832. * appear as if auth file was opened.
  6833. * TODO(mid): Check if this is still required after rewriting
  6834. * mg_stat */
  6835. } else if (mg_stat(conn, path, &filep->stat)
  6836. && filep->stat.is_directory) {
  6837. mg_snprintf(conn,
  6838. &truncated,
  6839. name,
  6840. sizeof(name),
  6841. "%s/%s",
  6842. path,
  6843. PASSWORDS_FILE_NAME);
  6844. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6845. #if defined(DEBUG)
  6846. /* Don't use mg_cry_internal here, but only a trace, since this
  6847. * is
  6848. * a typical case. It will occur for every directory
  6849. * without a password file. */
  6850. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6851. #endif
  6852. }
  6853. } else {
  6854. /* Try to find .htpasswd in requested directory. */
  6855. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6856. if (e[0] == '/') {
  6857. break;
  6858. }
  6859. }
  6860. mg_snprintf(conn,
  6861. &truncated,
  6862. name,
  6863. sizeof(name),
  6864. "%.*s/%s",
  6865. (int)(e - p),
  6866. p,
  6867. PASSWORDS_FILE_NAME);
  6868. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6869. #if defined(DEBUG)
  6870. /* Don't use mg_cry_internal here, but only a trace, since this
  6871. * is
  6872. * a typical case. It will occur for every directory
  6873. * without a password file. */
  6874. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6875. #endif
  6876. }
  6877. }
  6878. }
  6879. }
  6880. /* Parsed Authorization header */
  6881. struct ah {
  6882. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6883. };
  6884. /* Return 1 on success. Always initializes the ah structure. */
  6885. static int
  6886. parse_auth_header(struct mg_connection *conn,
  6887. char *buf,
  6888. size_t buf_size,
  6889. struct ah *ah)
  6890. {
  6891. char *name, *value, *s;
  6892. const char *auth_header;
  6893. uint64_t nonce;
  6894. if (!ah || !conn) {
  6895. return 0;
  6896. }
  6897. (void)memset(ah, 0, sizeof(*ah));
  6898. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6899. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6900. return 0;
  6901. }
  6902. /* Make modifiable copy of the auth header */
  6903. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6904. s = buf;
  6905. /* Parse authorization header */
  6906. for (;;) {
  6907. /* Gobble initial spaces */
  6908. while (isspace(*(unsigned char *)s)) {
  6909. s++;
  6910. }
  6911. name = skip_quoted(&s, "=", " ", 0);
  6912. /* Value is either quote-delimited, or ends at first comma or space.
  6913. */
  6914. if (s[0] == '\"') {
  6915. s++;
  6916. value = skip_quoted(&s, "\"", " ", '\\');
  6917. if (s[0] == ',') {
  6918. s++;
  6919. }
  6920. } else {
  6921. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6922. * spaces */
  6923. }
  6924. if (*name == '\0') {
  6925. break;
  6926. }
  6927. if (!strcmp(name, "username")) {
  6928. ah->user = value;
  6929. } else if (!strcmp(name, "cnonce")) {
  6930. ah->cnonce = value;
  6931. } else if (!strcmp(name, "response")) {
  6932. ah->response = value;
  6933. } else if (!strcmp(name, "uri")) {
  6934. ah->uri = value;
  6935. } else if (!strcmp(name, "qop")) {
  6936. ah->qop = value;
  6937. } else if (!strcmp(name, "nc")) {
  6938. ah->nc = value;
  6939. } else if (!strcmp(name, "nonce")) {
  6940. ah->nonce = value;
  6941. }
  6942. }
  6943. #if !defined(NO_NONCE_CHECK)
  6944. /* Read the nonce from the response. */
  6945. if (ah->nonce == NULL) {
  6946. return 0;
  6947. }
  6948. s = NULL;
  6949. nonce = strtoull(ah->nonce, &s, 10);
  6950. if ((s == NULL) || (*s != 0)) {
  6951. return 0;
  6952. }
  6953. /* Convert the nonce from the client to a number. */
  6954. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6955. /* The converted number corresponds to the time the nounce has been
  6956. * created. This should not be earlier than the server start. */
  6957. /* Server side nonce check is valuable in all situations but one:
  6958. * if the server restarts frequently, but the client should not see
  6959. * that, so the server should accept nonces from previous starts. */
  6960. /* However, the reasonable default is to not accept a nonce from a
  6961. * previous start, so if anyone changed the access rights between
  6962. * two restarts, a new login is required. */
  6963. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6964. /* nonce is from a previous start of the server and no longer valid
  6965. * (replay attack?) */
  6966. return 0;
  6967. }
  6968. /* Check if the nonce is too high, so it has not (yet) been used by the
  6969. * server. */
  6970. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6971. + conn->dom_ctx->nonce_count)) {
  6972. return 0;
  6973. }
  6974. #else
  6975. (void)nonce;
  6976. #endif
  6977. /* CGI needs it as REMOTE_USER */
  6978. if (ah->user != NULL) {
  6979. conn->request_info.remote_user =
  6980. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6981. } else {
  6982. return 0;
  6983. }
  6984. return 1;
  6985. }
  6986. static const char *
  6987. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6988. {
  6989. #if defined(MG_USE_OPEN_FILE)
  6990. const char *eof;
  6991. size_t len;
  6992. const char *memend;
  6993. #else
  6994. (void)p; /* parameter is unused */
  6995. #endif
  6996. if (!filep) {
  6997. return NULL;
  6998. }
  6999. #if defined(MG_USE_OPEN_FILE)
  7000. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7001. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7002. /* Search for \n from p till the end of stream */
  7003. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7004. if (eof != NULL) {
  7005. eof += 1; /* Include \n */
  7006. } else {
  7007. eof = memend; /* Copy remaining data */
  7008. }
  7009. len =
  7010. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7011. memcpy(buf, *p, len);
  7012. buf[len] = '\0';
  7013. *p += len;
  7014. return len ? eof : NULL;
  7015. } else /* filep->access.fp block below */
  7016. #endif
  7017. if (filep->access.fp != NULL) {
  7018. return fgets(buf, (int)size, filep->access.fp);
  7019. } else {
  7020. return NULL;
  7021. }
  7022. }
  7023. /* Define the initial recursion depth for procesesing htpasswd files that
  7024. * include other htpasswd
  7025. * (or even the same) files. It is not difficult to provide a file or files
  7026. * s.t. they force civetweb
  7027. * to infinitely recurse and then crash.
  7028. */
  7029. #define INITIAL_DEPTH 9
  7030. #if INITIAL_DEPTH <= 0
  7031. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7032. #endif
  7033. struct read_auth_file_struct {
  7034. struct mg_connection *conn;
  7035. struct ah ah;
  7036. const char *domain;
  7037. char buf[256 + 256 + 40];
  7038. const char *f_user;
  7039. const char *f_domain;
  7040. const char *f_ha1;
  7041. };
  7042. static int
  7043. read_auth_file(struct mg_file *filep,
  7044. struct read_auth_file_struct *workdata,
  7045. int depth)
  7046. {
  7047. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7048. int is_authorized = 0;
  7049. struct mg_file fp;
  7050. size_t l;
  7051. if (!filep || !workdata || (0 == depth)) {
  7052. return 0;
  7053. }
  7054. /* Loop over passwords file */
  7055. #if defined(MG_USE_OPEN_FILE)
  7056. p = (char *)filep->access.membuf;
  7057. #endif
  7058. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7059. l = strlen(workdata->buf);
  7060. while (l > 0) {
  7061. if (isspace(workdata->buf[l - 1])
  7062. || iscntrl(workdata->buf[l - 1])) {
  7063. l--;
  7064. workdata->buf[l] = 0;
  7065. } else
  7066. break;
  7067. }
  7068. if (l < 1) {
  7069. continue;
  7070. }
  7071. workdata->f_user = workdata->buf;
  7072. if (workdata->f_user[0] == ':') {
  7073. /* user names may not contain a ':' and may not be empty,
  7074. * so lines starting with ':' may be used for a special purpose
  7075. */
  7076. if (workdata->f_user[1] == '#') {
  7077. /* :# is a comment */
  7078. continue;
  7079. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7080. if (mg_fopen(workdata->conn,
  7081. workdata->f_user + 9,
  7082. MG_FOPEN_MODE_READ,
  7083. &fp)) {
  7084. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7085. (void)mg_fclose(
  7086. &fp.access); /* ignore error on read only file */
  7087. /* No need to continue processing files once we have a
  7088. * match, since nothing will reset it back
  7089. * to 0.
  7090. */
  7091. if (is_authorized) {
  7092. return is_authorized;
  7093. }
  7094. } else {
  7095. mg_cry_internal(workdata->conn,
  7096. "%s: cannot open authorization file: %s",
  7097. __func__,
  7098. workdata->buf);
  7099. }
  7100. continue;
  7101. }
  7102. /* everything is invalid for the moment (might change in the
  7103. * future) */
  7104. mg_cry_internal(workdata->conn,
  7105. "%s: syntax error in authorization file: %s",
  7106. __func__,
  7107. workdata->buf);
  7108. continue;
  7109. }
  7110. workdata->f_domain = strchr(workdata->f_user, ':');
  7111. if (workdata->f_domain == NULL) {
  7112. mg_cry_internal(workdata->conn,
  7113. "%s: syntax error in authorization file: %s",
  7114. __func__,
  7115. workdata->buf);
  7116. continue;
  7117. }
  7118. *(char *)(workdata->f_domain) = 0;
  7119. (workdata->f_domain)++;
  7120. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7121. if (workdata->f_ha1 == NULL) {
  7122. mg_cry_internal(workdata->conn,
  7123. "%s: syntax error in authorization file: %s",
  7124. __func__,
  7125. workdata->buf);
  7126. continue;
  7127. }
  7128. *(char *)(workdata->f_ha1) = 0;
  7129. (workdata->f_ha1)++;
  7130. if (!strcmp(workdata->ah.user, workdata->f_user)
  7131. && !strcmp(workdata->domain, workdata->f_domain)) {
  7132. return check_password(workdata->conn->request_info.request_method,
  7133. workdata->f_ha1,
  7134. workdata->ah.uri,
  7135. workdata->ah.nonce,
  7136. workdata->ah.nc,
  7137. workdata->ah.cnonce,
  7138. workdata->ah.qop,
  7139. workdata->ah.response);
  7140. }
  7141. }
  7142. return is_authorized;
  7143. }
  7144. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7145. static int
  7146. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7147. {
  7148. struct read_auth_file_struct workdata;
  7149. char buf[MG_BUF_LEN];
  7150. if (!conn || !conn->dom_ctx) {
  7151. return 0;
  7152. }
  7153. memset(&workdata, 0, sizeof(workdata));
  7154. workdata.conn = conn;
  7155. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7156. return 0;
  7157. }
  7158. if (realm) {
  7159. workdata.domain = realm;
  7160. } else {
  7161. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7162. }
  7163. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7164. }
  7165. /* Public function to check http digest authentication header */
  7166. int
  7167. mg_check_digest_access_authentication(struct mg_connection *conn,
  7168. const char *realm,
  7169. const char *filename)
  7170. {
  7171. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7172. int auth;
  7173. if (!conn || !filename) {
  7174. return -1;
  7175. }
  7176. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7177. return -2;
  7178. }
  7179. auth = authorize(conn, &file, realm);
  7180. mg_fclose(&file.access);
  7181. return auth;
  7182. }
  7183. /* Return 1 if request is authorised, 0 otherwise. */
  7184. static int
  7185. check_authorization(struct mg_connection *conn, const char *path)
  7186. {
  7187. char fname[PATH_MAX];
  7188. struct vec uri_vec, filename_vec;
  7189. const char *list;
  7190. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7191. int authorized = 1, truncated;
  7192. if (!conn || !conn->dom_ctx) {
  7193. return 0;
  7194. }
  7195. list = conn->dom_ctx->config[PROTECT_URI];
  7196. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7197. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7198. mg_snprintf(conn,
  7199. &truncated,
  7200. fname,
  7201. sizeof(fname),
  7202. "%.*s",
  7203. (int)filename_vec.len,
  7204. filename_vec.ptr);
  7205. if (truncated
  7206. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7207. mg_cry_internal(conn,
  7208. "%s: cannot open %s: %s",
  7209. __func__,
  7210. fname,
  7211. strerror(errno));
  7212. }
  7213. break;
  7214. }
  7215. }
  7216. if (!is_file_opened(&file.access)) {
  7217. open_auth_file(conn, path, &file);
  7218. }
  7219. if (is_file_opened(&file.access)) {
  7220. authorized = authorize(conn, &file, NULL);
  7221. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7222. }
  7223. return authorized;
  7224. }
  7225. /* Internal function. Assumes conn is valid */
  7226. static void
  7227. send_authorization_request(struct mg_connection *conn, const char *realm)
  7228. {
  7229. char date[64];
  7230. time_t curtime = time(NULL);
  7231. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7232. if (!realm) {
  7233. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7234. }
  7235. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7236. nonce += conn->dom_ctx->nonce_count;
  7237. ++conn->dom_ctx->nonce_count;
  7238. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7239. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7240. conn->status_code = 401;
  7241. conn->must_close = 1;
  7242. gmt_time_string(date, sizeof(date), &curtime);
  7243. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7244. send_no_cache_header(conn);
  7245. send_additional_header(conn);
  7246. mg_printf(conn,
  7247. "Date: %s\r\n"
  7248. "Connection: %s\r\n"
  7249. "Content-Length: 0\r\n"
  7250. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7251. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7252. date,
  7253. suggest_connection_header(conn),
  7254. realm,
  7255. nonce);
  7256. }
  7257. /* Interface function. Parameters are provided by the user, so do
  7258. * at least some basic checks.
  7259. */
  7260. int
  7261. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7262. const char *realm)
  7263. {
  7264. if (conn && conn->dom_ctx) {
  7265. send_authorization_request(conn, realm);
  7266. return 0;
  7267. }
  7268. return -1;
  7269. }
  7270. #if !defined(NO_FILES)
  7271. static int
  7272. is_authorized_for_put(struct mg_connection *conn)
  7273. {
  7274. if (conn) {
  7275. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7276. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7277. int ret = 0;
  7278. if (passfile != NULL
  7279. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7280. ret = authorize(conn, &file, NULL);
  7281. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7282. }
  7283. return ret;
  7284. }
  7285. return 0;
  7286. }
  7287. #endif
  7288. int
  7289. mg_modify_passwords_file(const char *fname,
  7290. const char *domain,
  7291. const char *user,
  7292. const char *pass)
  7293. {
  7294. int found, i;
  7295. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7296. FILE *fp, *fp2;
  7297. found = 0;
  7298. fp = fp2 = NULL;
  7299. /* Regard empty password as no password - remove user record. */
  7300. if ((pass != NULL) && (pass[0] == '\0')) {
  7301. pass = NULL;
  7302. }
  7303. /* Other arguments must not be empty */
  7304. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7305. return 0;
  7306. }
  7307. /* Using the given file format, user name and domain must not contain
  7308. * ':'
  7309. */
  7310. if (strchr(user, ':') != NULL) {
  7311. return 0;
  7312. }
  7313. if (strchr(domain, ':') != NULL) {
  7314. return 0;
  7315. }
  7316. /* Do not allow control characters like newline in user name and domain.
  7317. * Do not allow excessively long names either. */
  7318. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7319. if (iscntrl(user[i])) {
  7320. return 0;
  7321. }
  7322. }
  7323. if (user[i]) {
  7324. return 0;
  7325. }
  7326. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7327. if (iscntrl(domain[i])) {
  7328. return 0;
  7329. }
  7330. }
  7331. if (domain[i]) {
  7332. return 0;
  7333. }
  7334. /* The maximum length of the path to the password file is limited */
  7335. if ((strlen(fname) + 4) >= PATH_MAX) {
  7336. return 0;
  7337. }
  7338. /* Create a temporary file name. Length has been checked before. */
  7339. strcpy(tmp, fname);
  7340. strcat(tmp, ".tmp");
  7341. /* Create the file if does not exist */
  7342. /* Use of fopen here is OK, since fname is only ASCII */
  7343. if ((fp = fopen(fname, "a+")) != NULL) {
  7344. (void)fclose(fp);
  7345. }
  7346. /* Open the given file and temporary file */
  7347. if ((fp = fopen(fname, "r")) == NULL) {
  7348. return 0;
  7349. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7350. fclose(fp);
  7351. return 0;
  7352. }
  7353. /* Copy the stuff to temporary file */
  7354. while (fgets(line, sizeof(line), fp) != NULL) {
  7355. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7356. continue;
  7357. }
  7358. u[255] = 0;
  7359. d[255] = 0;
  7360. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7361. found++;
  7362. if (pass != NULL) {
  7363. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7364. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7365. }
  7366. } else {
  7367. fprintf(fp2, "%s", line);
  7368. }
  7369. }
  7370. /* If new user, just add it */
  7371. if (!found && (pass != NULL)) {
  7372. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7373. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7374. }
  7375. /* Close files */
  7376. fclose(fp);
  7377. fclose(fp2);
  7378. /* Put the temp file in place of real file */
  7379. IGNORE_UNUSED_RESULT(remove(fname));
  7380. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7381. return 1;
  7382. }
  7383. static int
  7384. is_valid_port(unsigned long port)
  7385. {
  7386. return (port <= 0xffff);
  7387. }
  7388. static int
  7389. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7390. {
  7391. struct addrinfo hints, *res, *ressave;
  7392. int func_ret = 0;
  7393. int gai_ret;
  7394. memset(&hints, 0, sizeof(struct addrinfo));
  7395. hints.ai_family = af;
  7396. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7397. if (gai_ret != 0) {
  7398. /* gai_strerror could be used to convert gai_ret to a string */
  7399. /* POSIX return values: see
  7400. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7401. */
  7402. /* Windows return values: see
  7403. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7404. */
  7405. return 0;
  7406. }
  7407. ressave = res;
  7408. while (res) {
  7409. if (dstlen >= (size_t)res->ai_addrlen) {
  7410. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7411. func_ret = 1;
  7412. }
  7413. res = res->ai_next;
  7414. }
  7415. freeaddrinfo(ressave);
  7416. return func_ret;
  7417. }
  7418. static int
  7419. connect_socket(struct mg_context *ctx /* may be NULL */,
  7420. const char *host,
  7421. int port,
  7422. int use_ssl,
  7423. char *ebuf,
  7424. size_t ebuf_len,
  7425. SOCKET *sock /* output: socket, must not be NULL */,
  7426. union usa *sa /* output: socket address, must not be NULL */
  7427. )
  7428. {
  7429. int ip_ver = 0;
  7430. int conn_ret = -1;
  7431. int ret;
  7432. *sock = INVALID_SOCKET;
  7433. memset(sa, 0, sizeof(*sa));
  7434. if (ebuf_len > 0) {
  7435. *ebuf = 0;
  7436. }
  7437. if (host == NULL) {
  7438. mg_snprintf(NULL,
  7439. NULL, /* No truncation check for ebuf */
  7440. ebuf,
  7441. ebuf_len,
  7442. "%s",
  7443. "NULL host");
  7444. return 0;
  7445. }
  7446. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7447. mg_snprintf(NULL,
  7448. NULL, /* No truncation check for ebuf */
  7449. ebuf,
  7450. ebuf_len,
  7451. "%s",
  7452. "invalid port");
  7453. return 0;
  7454. }
  7455. #if !defined(NO_SSL)
  7456. #if !defined(NO_SSL_DL)
  7457. #if defined(OPENSSL_API_1_1)
  7458. if (use_ssl && (TLS_client_method == NULL)) {
  7459. mg_snprintf(NULL,
  7460. NULL, /* No truncation check for ebuf */
  7461. ebuf,
  7462. ebuf_len,
  7463. "%s",
  7464. "SSL is not initialized");
  7465. return 0;
  7466. }
  7467. #else
  7468. if (use_ssl && (SSLv23_client_method == NULL)) {
  7469. mg_snprintf(NULL,
  7470. NULL, /* No truncation check for ebuf */
  7471. ebuf,
  7472. ebuf_len,
  7473. "%s",
  7474. "SSL is not initialized");
  7475. return 0;
  7476. }
  7477. #endif /* OPENSSL_API_1_1 */
  7478. #else
  7479. (void)use_ssl;
  7480. #endif /* NO_SSL_DL */
  7481. #else
  7482. (void)use_ssl;
  7483. #endif /* !defined(NO_SSL) */
  7484. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7485. sa->sin.sin_family = AF_INET;
  7486. sa->sin.sin_port = htons((uint16_t)port);
  7487. ip_ver = 4;
  7488. #if defined(USE_IPV6)
  7489. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7490. sa->sin6.sin6_family = AF_INET6;
  7491. sa->sin6.sin6_port = htons((uint16_t)port);
  7492. ip_ver = 6;
  7493. } else if (host[0] == '[') {
  7494. /* While getaddrinfo on Windows will work with [::1],
  7495. * getaddrinfo on Linux only works with ::1 (without []). */
  7496. size_t l = strlen(host + 1);
  7497. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7498. if (h) {
  7499. h[l - 1] = 0;
  7500. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7501. sa->sin6.sin6_family = AF_INET6;
  7502. sa->sin6.sin6_port = htons((uint16_t)port);
  7503. ip_ver = 6;
  7504. }
  7505. mg_free(h);
  7506. }
  7507. #endif
  7508. }
  7509. if (ip_ver == 0) {
  7510. mg_snprintf(NULL,
  7511. NULL, /* No truncation check for ebuf */
  7512. ebuf,
  7513. ebuf_len,
  7514. "%s",
  7515. "host not found");
  7516. return 0;
  7517. }
  7518. if (ip_ver == 4) {
  7519. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7520. }
  7521. #if defined(USE_IPV6)
  7522. else if (ip_ver == 6) {
  7523. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7524. }
  7525. #endif
  7526. if (*sock == INVALID_SOCKET) {
  7527. mg_snprintf(NULL,
  7528. NULL, /* No truncation check for ebuf */
  7529. ebuf,
  7530. ebuf_len,
  7531. "socket(): %s",
  7532. strerror(ERRNO));
  7533. return 0;
  7534. }
  7535. if (0 != set_non_blocking_mode(*sock)) {
  7536. mg_snprintf(NULL,
  7537. NULL, /* No truncation check for ebuf */
  7538. ebuf,
  7539. ebuf_len,
  7540. "Cannot set socket to non-blocking: %s",
  7541. strerror(ERRNO));
  7542. closesocket(*sock);
  7543. *sock = INVALID_SOCKET;
  7544. return 0;
  7545. }
  7546. set_close_on_exec(*sock, fc(ctx));
  7547. if (ip_ver == 4) {
  7548. /* connected with IPv4 */
  7549. conn_ret = connect(*sock,
  7550. (struct sockaddr *)((void *)&sa->sin),
  7551. sizeof(sa->sin));
  7552. }
  7553. #if defined(USE_IPV6)
  7554. else if (ip_ver == 6) {
  7555. /* connected with IPv6 */
  7556. conn_ret = connect(*sock,
  7557. (struct sockaddr *)((void *)&sa->sin6),
  7558. sizeof(sa->sin6));
  7559. }
  7560. #endif
  7561. #if defined(_WIN32)
  7562. if (conn_ret != 0) {
  7563. DWORD err = WSAGetLastError(); /* could return WSAEWOULDBLOCK */
  7564. conn_ret = (int)err;
  7565. #if !defined(EINPROGRESS)
  7566. #define EINPROGRESS (WSAEWOULDBLOCK) /* Winsock equivalent */
  7567. #endif /* if !defined(EINPROGRESS) */
  7568. }
  7569. #endif
  7570. if ((conn_ret != 0) && (conn_ret != EINPROGRESS)) {
  7571. /* Data for getsockopt */
  7572. int sockerr = -1;
  7573. void *psockerr = &sockerr;
  7574. #if defined(_WIN32)
  7575. int len = (int)sizeof(sockerr);
  7576. #else
  7577. socklen_t len = (socklen_t)sizeof(sockerr);
  7578. #endif
  7579. /* Data for poll */
  7580. struct pollfd pfd[1];
  7581. int pollres;
  7582. int ms_wait = 10000; /* 10 second timeout */
  7583. /* For a non-blocking socket, the connect sequence is:
  7584. * 1) call connect (will not block)
  7585. * 2) wait until the socket is ready for writing (select or poll)
  7586. * 3) check connection state with getsockopt
  7587. */
  7588. pfd[0].fd = *sock;
  7589. pfd[0].events = POLLOUT;
  7590. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  7591. if (pollres != 1) {
  7592. /* Not connected */
  7593. mg_snprintf(NULL,
  7594. NULL, /* No truncation check for ebuf */
  7595. ebuf,
  7596. ebuf_len,
  7597. "connect(%s:%d): timeout",
  7598. host,
  7599. port);
  7600. closesocket(*sock);
  7601. *sock = INVALID_SOCKET;
  7602. return 0;
  7603. }
  7604. #if defined(_WIN32)
  7605. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7606. #else
  7607. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7608. #endif
  7609. if ((ret != 0) || (sockerr != 0)) {
  7610. /* Not connected */
  7611. mg_snprintf(NULL,
  7612. NULL, /* No truncation check for ebuf */
  7613. ebuf,
  7614. ebuf_len,
  7615. "connect(%s:%d): error %s",
  7616. host,
  7617. port,
  7618. strerror(sockerr));
  7619. closesocket(*sock);
  7620. *sock = INVALID_SOCKET;
  7621. return 0;
  7622. }
  7623. }
  7624. return 1;
  7625. }
  7626. int
  7627. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7628. {
  7629. static const char *dont_escape = "._-$,;~()";
  7630. static const char *hex = "0123456789abcdef";
  7631. char *pos = dst;
  7632. const char *end = dst + dst_len - 1;
  7633. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7634. if (isalnum(*(const unsigned char *)src)
  7635. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7636. *pos = *src;
  7637. } else if (pos + 2 < end) {
  7638. pos[0] = '%';
  7639. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7640. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7641. pos += 2;
  7642. } else {
  7643. break;
  7644. }
  7645. }
  7646. *pos = '\0';
  7647. return (*src == '\0') ? (int)(pos - dst) : -1;
  7648. }
  7649. /* Return 0 on success, non-zero if an error occurs. */
  7650. static int
  7651. print_dir_entry(struct de *de)
  7652. {
  7653. size_t hrefsize;
  7654. char *href;
  7655. char size[64], mod[64];
  7656. #if defined(REENTRANT_TIME)
  7657. struct tm _tm;
  7658. struct tm *tm = &_tm;
  7659. #else
  7660. struct tm *tm;
  7661. #endif
  7662. hrefsize = PATH_MAX * 3; /* worst case */
  7663. href = (char *)mg_malloc(hrefsize);
  7664. if (href == NULL) {
  7665. return -1;
  7666. }
  7667. if (de->file.is_directory) {
  7668. mg_snprintf(de->conn,
  7669. NULL, /* Buffer is big enough */
  7670. size,
  7671. sizeof(size),
  7672. "%s",
  7673. "[DIRECTORY]");
  7674. } else {
  7675. /* We use (signed) cast below because MSVC 6 compiler cannot
  7676. * convert unsigned __int64 to double. Sigh. */
  7677. if (de->file.size < 1024) {
  7678. mg_snprintf(de->conn,
  7679. NULL, /* Buffer is big enough */
  7680. size,
  7681. sizeof(size),
  7682. "%d",
  7683. (int)de->file.size);
  7684. } else if (de->file.size < 0x100000) {
  7685. mg_snprintf(de->conn,
  7686. NULL, /* Buffer is big enough */
  7687. size,
  7688. sizeof(size),
  7689. "%.1fk",
  7690. (double)de->file.size / 1024.0);
  7691. } else if (de->file.size < 0x40000000) {
  7692. mg_snprintf(de->conn,
  7693. NULL, /* Buffer is big enough */
  7694. size,
  7695. sizeof(size),
  7696. "%.1fM",
  7697. (double)de->file.size / 1048576);
  7698. } else {
  7699. mg_snprintf(de->conn,
  7700. NULL, /* Buffer is big enough */
  7701. size,
  7702. sizeof(size),
  7703. "%.1fG",
  7704. (double)de->file.size / 1073741824);
  7705. }
  7706. }
  7707. /* Note: mg_snprintf will not cause a buffer overflow above.
  7708. * So, string truncation checks are not required here. */
  7709. #if defined(REENTRANT_TIME)
  7710. localtime_r(&de->file.last_modified, tm);
  7711. #else
  7712. tm = localtime(&de->file.last_modified);
  7713. #endif
  7714. if (tm != NULL) {
  7715. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7716. } else {
  7717. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7718. mod[sizeof(mod) - 1] = '\0';
  7719. }
  7720. mg_url_encode(de->file_name, href, hrefsize);
  7721. mg_printf(de->conn,
  7722. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7723. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7724. de->conn->request_info.local_uri,
  7725. href,
  7726. de->file.is_directory ? "/" : "",
  7727. de->file_name,
  7728. de->file.is_directory ? "/" : "",
  7729. mod,
  7730. size);
  7731. mg_free(href);
  7732. return 0;
  7733. }
  7734. /* This function is called from send_directory() and used for
  7735. * sorting directory entries by size, or name, or modification time.
  7736. * On windows, __cdecl specification is needed in case if project is built
  7737. * with __stdcall convention. qsort always requires __cdels callback. */
  7738. static int WINCDECL
  7739. compare_dir_entries(const void *p1, const void *p2)
  7740. {
  7741. if (p1 && p2) {
  7742. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7743. const char *query_string = a->conn->request_info.query_string;
  7744. int cmp_result = 0;
  7745. if (query_string == NULL) {
  7746. query_string = "na";
  7747. }
  7748. if (a->file.is_directory && !b->file.is_directory) {
  7749. return -1; /* Always put directories on top */
  7750. } else if (!a->file.is_directory && b->file.is_directory) {
  7751. return 1; /* Always put directories on top */
  7752. } else if (*query_string == 'n') {
  7753. cmp_result = strcmp(a->file_name, b->file_name);
  7754. } else if (*query_string == 's') {
  7755. cmp_result = (a->file.size == b->file.size)
  7756. ? 0
  7757. : ((a->file.size > b->file.size) ? 1 : -1);
  7758. } else if (*query_string == 'd') {
  7759. cmp_result =
  7760. (a->file.last_modified == b->file.last_modified)
  7761. ? 0
  7762. : ((a->file.last_modified > b->file.last_modified) ? 1
  7763. : -1);
  7764. }
  7765. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7766. }
  7767. return 0;
  7768. }
  7769. static int
  7770. must_hide_file(struct mg_connection *conn, const char *path)
  7771. {
  7772. if (conn && conn->dom_ctx) {
  7773. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7774. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7775. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7776. || ((pattern != NULL)
  7777. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7778. }
  7779. return 0;
  7780. }
  7781. static int
  7782. scan_directory(struct mg_connection *conn,
  7783. const char *dir,
  7784. void *data,
  7785. int (*cb)(struct de *, void *))
  7786. {
  7787. char path[PATH_MAX];
  7788. struct dirent *dp;
  7789. DIR *dirp;
  7790. struct de de;
  7791. int truncated;
  7792. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7793. return 0;
  7794. } else {
  7795. de.conn = conn;
  7796. while ((dp = mg_readdir(dirp)) != NULL) {
  7797. /* Do not show current dir and hidden files */
  7798. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7799. || must_hide_file(conn, dp->d_name)) {
  7800. continue;
  7801. }
  7802. mg_snprintf(
  7803. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7804. /* If we don't memset stat structure to zero, mtime will have
  7805. * garbage and strftime() will segfault later on in
  7806. * print_dir_entry(). memset is required only if mg_stat()
  7807. * fails. For more details, see
  7808. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7809. memset(&de.file, 0, sizeof(de.file));
  7810. if (truncated) {
  7811. /* If the path is not complete, skip processing. */
  7812. continue;
  7813. }
  7814. if (!mg_stat(conn, path, &de.file)) {
  7815. mg_cry_internal(conn,
  7816. "%s: mg_stat(%s) failed: %s",
  7817. __func__,
  7818. path,
  7819. strerror(ERRNO));
  7820. }
  7821. de.file_name = dp->d_name;
  7822. cb(&de, data);
  7823. }
  7824. (void)mg_closedir(dirp);
  7825. }
  7826. return 1;
  7827. }
  7828. #if !defined(NO_FILES)
  7829. static int
  7830. remove_directory(struct mg_connection *conn, const char *dir)
  7831. {
  7832. char path[PATH_MAX];
  7833. struct dirent *dp;
  7834. DIR *dirp;
  7835. struct de de;
  7836. int truncated;
  7837. int ok = 1;
  7838. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7839. return 0;
  7840. } else {
  7841. de.conn = conn;
  7842. while ((dp = mg_readdir(dirp)) != NULL) {
  7843. /* Do not show current dir (but show hidden files as they will
  7844. * also be removed) */
  7845. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7846. continue;
  7847. }
  7848. mg_snprintf(
  7849. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7850. /* If we don't memset stat structure to zero, mtime will have
  7851. * garbage and strftime() will segfault later on in
  7852. * print_dir_entry(). memset is required only if mg_stat()
  7853. * fails. For more details, see
  7854. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7855. memset(&de.file, 0, sizeof(de.file));
  7856. if (truncated) {
  7857. /* Do not delete anything shorter */
  7858. ok = 0;
  7859. continue;
  7860. }
  7861. if (!mg_stat(conn, path, &de.file)) {
  7862. mg_cry_internal(conn,
  7863. "%s: mg_stat(%s) failed: %s",
  7864. __func__,
  7865. path,
  7866. strerror(ERRNO));
  7867. ok = 0;
  7868. }
  7869. if (de.file.is_directory) {
  7870. if (remove_directory(conn, path) == 0) {
  7871. ok = 0;
  7872. }
  7873. } else {
  7874. /* This will fail file is the file is in memory */
  7875. if (mg_remove(conn, path) == 0) {
  7876. ok = 0;
  7877. }
  7878. }
  7879. }
  7880. (void)mg_closedir(dirp);
  7881. IGNORE_UNUSED_RESULT(rmdir(dir));
  7882. }
  7883. return ok;
  7884. }
  7885. #endif
  7886. struct dir_scan_data {
  7887. struct de *entries;
  7888. unsigned int num_entries;
  7889. unsigned int arr_size;
  7890. };
  7891. /* Behaves like realloc(), but frees original pointer on failure */
  7892. static void *
  7893. realloc2(void *ptr, size_t size)
  7894. {
  7895. void *new_ptr = mg_realloc(ptr, size);
  7896. if (new_ptr == NULL) {
  7897. mg_free(ptr);
  7898. }
  7899. return new_ptr;
  7900. }
  7901. static int
  7902. dir_scan_callback(struct de *de, void *data)
  7903. {
  7904. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7905. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7906. dsd->arr_size *= 2;
  7907. dsd->entries =
  7908. (struct de *)realloc2(dsd->entries,
  7909. dsd->arr_size * sizeof(dsd->entries[0]));
  7910. }
  7911. if (dsd->entries == NULL) {
  7912. /* TODO(lsm, low): propagate an error to the caller */
  7913. dsd->num_entries = 0;
  7914. } else {
  7915. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7916. dsd->entries[dsd->num_entries].file = de->file;
  7917. dsd->entries[dsd->num_entries].conn = de->conn;
  7918. dsd->num_entries++;
  7919. }
  7920. return 0;
  7921. }
  7922. static void
  7923. handle_directory_request(struct mg_connection *conn, const char *dir)
  7924. {
  7925. unsigned int i;
  7926. int sort_direction;
  7927. struct dir_scan_data data = {NULL, 0, 128};
  7928. char date[64];
  7929. time_t curtime = time(NULL);
  7930. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7931. mg_send_http_error(conn,
  7932. 500,
  7933. "Error: Cannot open directory\nopendir(%s): %s",
  7934. dir,
  7935. strerror(ERRNO));
  7936. return;
  7937. }
  7938. gmt_time_string(date, sizeof(date), &curtime);
  7939. if (!conn) {
  7940. return;
  7941. }
  7942. sort_direction = ((conn->request_info.query_string != NULL)
  7943. && (conn->request_info.query_string[1] == 'd'))
  7944. ? 'a'
  7945. : 'd';
  7946. conn->must_close = 1;
  7947. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7948. send_static_cache_header(conn);
  7949. send_additional_header(conn);
  7950. mg_printf(conn,
  7951. "Date: %s\r\n"
  7952. "Connection: close\r\n"
  7953. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7954. date);
  7955. mg_printf(conn,
  7956. "<html><head><title>Index of %s</title>"
  7957. "<style>th {text-align: left;}</style></head>"
  7958. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7959. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7960. "<th><a href=\"?d%c\">Modified</a></th>"
  7961. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7962. "<tr><td colspan=\"3\"><hr></td></tr>",
  7963. conn->request_info.local_uri,
  7964. conn->request_info.local_uri,
  7965. sort_direction,
  7966. sort_direction,
  7967. sort_direction);
  7968. /* Print first entry - link to a parent directory */
  7969. mg_printf(conn,
  7970. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7971. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7972. conn->request_info.local_uri,
  7973. "..",
  7974. "Parent directory",
  7975. "-",
  7976. "-");
  7977. /* Sort and print directory entries */
  7978. if (data.entries != NULL) {
  7979. qsort(data.entries,
  7980. (size_t)data.num_entries,
  7981. sizeof(data.entries[0]),
  7982. compare_dir_entries);
  7983. for (i = 0; i < data.num_entries; i++) {
  7984. print_dir_entry(&data.entries[i]);
  7985. mg_free(data.entries[i].file_name);
  7986. }
  7987. mg_free(data.entries);
  7988. }
  7989. mg_printf(conn, "%s", "</table></body></html>");
  7990. conn->status_code = 200;
  7991. }
  7992. /* Send len bytes from the opened file to the client. */
  7993. static void
  7994. send_file_data(struct mg_connection *conn,
  7995. struct mg_file *filep,
  7996. int64_t offset,
  7997. int64_t len)
  7998. {
  7999. char buf[MG_BUF_LEN];
  8000. int to_read, num_read, num_written;
  8001. int64_t size;
  8002. if (!filep || !conn) {
  8003. return;
  8004. }
  8005. /* Sanity check the offset */
  8006. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8007. : (int64_t)(filep->stat.size);
  8008. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8009. #if defined(MG_USE_OPEN_FILE)
  8010. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8011. /* file stored in memory */
  8012. if (len > size - offset) {
  8013. len = size - offset;
  8014. }
  8015. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8016. } else /* else block below */
  8017. #endif
  8018. if (len > 0 && filep->access.fp != NULL) {
  8019. /* file stored on disk */
  8020. #if defined(__linux__)
  8021. /* sendfile is only available for Linux */
  8022. if ((conn->ssl == 0) && (conn->throttle == 0)
  8023. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8024. "yes"))) {
  8025. off_t sf_offs = (off_t)offset;
  8026. ssize_t sf_sent;
  8027. int sf_file = fileno(filep->access.fp);
  8028. int loop_cnt = 0;
  8029. do {
  8030. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8031. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8032. size_t sf_tosend =
  8033. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8034. sf_sent =
  8035. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8036. if (sf_sent > 0) {
  8037. len -= sf_sent;
  8038. offset += sf_sent;
  8039. } else if (loop_cnt == 0) {
  8040. /* This file can not be sent using sendfile.
  8041. * This might be the case for pseudo-files in the
  8042. * /sys/ and /proc/ file system.
  8043. * Use the regular user mode copy code instead. */
  8044. break;
  8045. } else if (sf_sent == 0) {
  8046. /* No error, but 0 bytes sent. May be EOF? */
  8047. return;
  8048. }
  8049. loop_cnt++;
  8050. } while ((len > 0) && (sf_sent >= 0));
  8051. if (sf_sent > 0) {
  8052. return; /* OK */
  8053. }
  8054. /* sf_sent<0 means error, thus fall back to the classic way */
  8055. /* This is always the case, if sf_file is not a "normal" file,
  8056. * e.g., for sending data from the output of a CGI process. */
  8057. offset = (int64_t)sf_offs;
  8058. }
  8059. #endif
  8060. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8061. mg_cry_internal(conn,
  8062. "%s: fseeko() failed: %s",
  8063. __func__,
  8064. strerror(ERRNO));
  8065. mg_send_http_error(
  8066. conn,
  8067. 500,
  8068. "%s",
  8069. "Error: Unable to access file at requested position.");
  8070. } else {
  8071. while (len > 0) {
  8072. /* Calculate how much to read from the file in the buffer */
  8073. to_read = sizeof(buf);
  8074. if ((int64_t)to_read > len) {
  8075. to_read = (int)len;
  8076. }
  8077. /* Read from file, exit the loop on error */
  8078. if ((num_read =
  8079. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8080. <= 0) {
  8081. break;
  8082. }
  8083. /* Send read bytes to the client, exit the loop on error */
  8084. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8085. != num_read) {
  8086. break;
  8087. }
  8088. /* Both read and were successful, adjust counters */
  8089. len -= num_written;
  8090. }
  8091. }
  8092. }
  8093. }
  8094. static int
  8095. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8096. {
  8097. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8098. }
  8099. static void
  8100. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8101. {
  8102. if ((filestat != NULL) && (buf != NULL)) {
  8103. mg_snprintf(NULL,
  8104. NULL, /* All calls to construct_etag use 64 byte buffer */
  8105. buf,
  8106. buf_len,
  8107. "\"%lx.%" INT64_FMT "\"",
  8108. (unsigned long)filestat->last_modified,
  8109. filestat->size);
  8110. }
  8111. }
  8112. static void
  8113. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8114. {
  8115. if (filep != NULL && filep->fp != NULL) {
  8116. #if defined(_WIN32)
  8117. (void)conn; /* Unused. */
  8118. #else
  8119. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8120. mg_cry_internal(conn,
  8121. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8122. __func__,
  8123. strerror(ERRNO));
  8124. }
  8125. #endif
  8126. }
  8127. }
  8128. #if defined(USE_ZLIB)
  8129. #include "mod_zlib.inl"
  8130. #endif
  8131. static void
  8132. handle_static_file_request(struct mg_connection *conn,
  8133. const char *path,
  8134. struct mg_file *filep,
  8135. const char *mime_type,
  8136. const char *additional_headers)
  8137. {
  8138. char date[64], lm[64], etag[64];
  8139. char range[128]; /* large enough, so there will be no overflow */
  8140. const char *msg = "OK", *hdr;
  8141. time_t curtime = time(NULL);
  8142. int64_t cl, r1, r2;
  8143. struct vec mime_vec;
  8144. int n, truncated;
  8145. char gz_path[PATH_MAX];
  8146. const char *encoding = "";
  8147. const char *cors1, *cors2, *cors3;
  8148. int is_head_request;
  8149. #if defined(USE_ZLIB)
  8150. /* Compression is allowed, unless there is a reason not to use compression.
  8151. * If the file is already compressed, too small or a "range" request was
  8152. * made, on the fly compression is not possible. */
  8153. int allow_on_the_fly_compression = 1;
  8154. #endif
  8155. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8156. return;
  8157. }
  8158. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8159. if (mime_type == NULL) {
  8160. get_mime_type(conn, path, &mime_vec);
  8161. } else {
  8162. mime_vec.ptr = mime_type;
  8163. mime_vec.len = strlen(mime_type);
  8164. }
  8165. if (filep->stat.size > INT64_MAX) {
  8166. mg_send_http_error(conn,
  8167. 500,
  8168. "Error: File size is too large to send\n%" INT64_FMT,
  8169. filep->stat.size);
  8170. return;
  8171. }
  8172. cl = (int64_t)filep->stat.size;
  8173. conn->status_code = 200;
  8174. range[0] = '\0';
  8175. #if defined(USE_ZLIB)
  8176. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8177. * it's important to rewrite the filename after resolving
  8178. * the mime type from it, to preserve the actual file's type */
  8179. if (!conn->accept_gzip) {
  8180. allow_on_the_fly_compression = 0;
  8181. }
  8182. #endif
  8183. if (filep->stat.is_gzipped) {
  8184. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8185. if (truncated) {
  8186. mg_send_http_error(conn,
  8187. 500,
  8188. "Error: Path of zipped file too long (%s)",
  8189. path);
  8190. return;
  8191. }
  8192. path = gz_path;
  8193. encoding = "Content-Encoding: gzip\r\n";
  8194. #if defined(USE_ZLIB)
  8195. /* File is already compressed. No "on the fly" compression. */
  8196. allow_on_the_fly_compression = 0;
  8197. #endif
  8198. }
  8199. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8200. mg_send_http_error(conn,
  8201. 500,
  8202. "Error: Cannot open file\nfopen(%s): %s",
  8203. path,
  8204. strerror(ERRNO));
  8205. return;
  8206. }
  8207. fclose_on_exec(&filep->access, conn);
  8208. /* If "Range" request was made: parse header, send only selected part
  8209. * of the file. */
  8210. r1 = r2 = 0;
  8211. hdr = mg_get_header(conn, "Range");
  8212. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  8213. && (r1 >= 0) && (r2 >= 0)) {
  8214. /* actually, range requests don't play well with a pre-gzipped
  8215. * file (since the range is specified in the uncompressed space) */
  8216. if (filep->stat.is_gzipped) {
  8217. mg_send_http_error(
  8218. conn,
  8219. 416, /* 416 = Range Not Satisfiable */
  8220. "%s",
  8221. "Error: Range requests in gzipped files are not supported");
  8222. (void)mg_fclose(
  8223. &filep->access); /* ignore error on read only file */
  8224. return;
  8225. }
  8226. conn->status_code = 206;
  8227. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8228. mg_snprintf(conn,
  8229. NULL, /* range buffer is big enough */
  8230. range,
  8231. sizeof(range),
  8232. "Content-Range: bytes "
  8233. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8234. r1,
  8235. r1 + cl - 1,
  8236. filep->stat.size);
  8237. msg = "Partial Content";
  8238. #if defined(USE_ZLIB)
  8239. /* Do not compress ranges. */
  8240. allow_on_the_fly_compression = 0;
  8241. #endif
  8242. }
  8243. /* Do not compress small files. Small files do not benefit from file
  8244. * compression, but there is still some overhead. */
  8245. #if defined(USE_ZLIB)
  8246. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8247. /* File is below the size limit. */
  8248. allow_on_the_fly_compression = 0;
  8249. }
  8250. #endif
  8251. /* Standard CORS header */
  8252. hdr = mg_get_header(conn, "Origin");
  8253. if (hdr) {
  8254. /* Cross-origin resource sharing (CORS), see
  8255. * http://www.html5rocks.com/en/tutorials/cors/,
  8256. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8257. * -
  8258. * preflight is not supported for files. */
  8259. cors1 = "Access-Control-Allow-Origin: ";
  8260. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8261. cors3 = "\r\n";
  8262. } else {
  8263. cors1 = cors2 = cors3 = "";
  8264. }
  8265. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8266. * according to
  8267. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8268. gmt_time_string(date, sizeof(date), &curtime);
  8269. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8270. construct_etag(etag, sizeof(etag), &filep->stat);
  8271. /* Send header */
  8272. (void)mg_printf(conn,
  8273. "HTTP/1.1 %d %s\r\n"
  8274. "%s%s%s" /* CORS */
  8275. "Date: %s\r\n"
  8276. "Last-Modified: %s\r\n"
  8277. "Etag: %s\r\n"
  8278. "Content-Type: %.*s\r\n"
  8279. "Connection: %s\r\n",
  8280. conn->status_code,
  8281. msg,
  8282. cors1,
  8283. cors2,
  8284. cors3,
  8285. date,
  8286. lm,
  8287. etag,
  8288. (int)mime_vec.len,
  8289. mime_vec.ptr,
  8290. suggest_connection_header(conn));
  8291. send_static_cache_header(conn);
  8292. send_additional_header(conn);
  8293. #if defined(USE_ZLIB)
  8294. /* On the fly compression allowed */
  8295. if (allow_on_the_fly_compression) {
  8296. /* For on the fly compression, we don't know the content size in
  8297. * advance, so we have to use chunked encoding */
  8298. (void)mg_printf(conn,
  8299. "Content-Encoding: gzip\r\n"
  8300. "Transfer-Encoding: chunked\r\n");
  8301. } else
  8302. #endif
  8303. {
  8304. /* Without on-the-fly compression, we know the content-length
  8305. * and we can use ranges (with on-the-fly compression we cannot).
  8306. * So we send these response headers only in this case. */
  8307. (void)mg_printf(conn,
  8308. "Content-Length: %" INT64_FMT "\r\n"
  8309. "Accept-Ranges: bytes\r\n"
  8310. "%s" /* range */
  8311. "%s" /* encoding */,
  8312. cl,
  8313. range,
  8314. encoding);
  8315. }
  8316. /* The previous code must not add any header starting with X- to make
  8317. * sure no one of the additional_headers is included twice */
  8318. if (additional_headers != NULL) {
  8319. (void)mg_printf(conn,
  8320. "%.*s\r\n\r\n",
  8321. (int)strlen(additional_headers),
  8322. additional_headers);
  8323. } else {
  8324. (void)mg_printf(conn, "\r\n");
  8325. }
  8326. if (!is_head_request) {
  8327. #if defined(USE_ZLIB)
  8328. if (allow_on_the_fly_compression) {
  8329. /* Compress and send */
  8330. send_compressed_data(conn, filep);
  8331. } else
  8332. #endif
  8333. {
  8334. /* Send file directly */
  8335. send_file_data(conn, filep, r1, cl);
  8336. }
  8337. }
  8338. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8339. }
  8340. int
  8341. mg_send_file_body(struct mg_connection *conn, const char *path)
  8342. {
  8343. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8344. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8345. return -1;
  8346. }
  8347. fclose_on_exec(&file.access, conn);
  8348. send_file_data(conn, &file, 0, INT64_MAX);
  8349. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8350. return 0; /* >= 0 for OK */
  8351. }
  8352. #if !defined(NO_CACHING)
  8353. /* Return True if we should reply 304 Not Modified. */
  8354. static int
  8355. is_not_modified(const struct mg_connection *conn,
  8356. const struct mg_file_stat *filestat)
  8357. {
  8358. char etag[64];
  8359. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8360. const char *inm = mg_get_header(conn, "If-None-Match");
  8361. construct_etag(etag, sizeof(etag), filestat);
  8362. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8363. || ((ims != NULL)
  8364. && (filestat->last_modified <= parse_date_string(ims)));
  8365. }
  8366. static void
  8367. handle_not_modified_static_file_request(struct mg_connection *conn,
  8368. struct mg_file *filep)
  8369. {
  8370. char date[64], lm[64], etag[64];
  8371. time_t curtime = time(NULL);
  8372. if ((conn == NULL) || (filep == NULL)) {
  8373. return;
  8374. }
  8375. conn->status_code = 304;
  8376. gmt_time_string(date, sizeof(date), &curtime);
  8377. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8378. construct_etag(etag, sizeof(etag), &filep->stat);
  8379. (void)mg_printf(conn,
  8380. "HTTP/1.1 %d %s\r\n"
  8381. "Date: %s\r\n",
  8382. conn->status_code,
  8383. mg_get_response_code_text(conn, conn->status_code),
  8384. date);
  8385. send_static_cache_header(conn);
  8386. send_additional_header(conn);
  8387. (void)mg_printf(conn,
  8388. "Last-Modified: %s\r\n"
  8389. "Etag: %s\r\n"
  8390. "Connection: %s\r\n"
  8391. "\r\n",
  8392. lm,
  8393. etag,
  8394. suggest_connection_header(conn));
  8395. }
  8396. #endif
  8397. void
  8398. mg_send_file(struct mg_connection *conn, const char *path)
  8399. {
  8400. mg_send_mime_file2(conn, path, NULL, NULL);
  8401. }
  8402. void
  8403. mg_send_mime_file(struct mg_connection *conn,
  8404. const char *path,
  8405. const char *mime_type)
  8406. {
  8407. mg_send_mime_file2(conn, path, mime_type, NULL);
  8408. }
  8409. void
  8410. mg_send_mime_file2(struct mg_connection *conn,
  8411. const char *path,
  8412. const char *mime_type,
  8413. const char *additional_headers)
  8414. {
  8415. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8416. if (!conn) {
  8417. /* No conn */
  8418. return;
  8419. }
  8420. if (mg_stat(conn, path, &file.stat)) {
  8421. #if !defined(NO_CACHING)
  8422. if (is_not_modified(conn, &file.stat)) {
  8423. /* Send 304 "Not Modified" - this must not send any body data */
  8424. handle_not_modified_static_file_request(conn, &file);
  8425. } else
  8426. #endif /* NO_CACHING */
  8427. if (file.stat.is_directory) {
  8428. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8429. "yes")) {
  8430. handle_directory_request(conn, path);
  8431. } else {
  8432. mg_send_http_error(conn,
  8433. 403,
  8434. "%s",
  8435. "Error: Directory listing denied");
  8436. }
  8437. } else {
  8438. handle_static_file_request(
  8439. conn, path, &file, mime_type, additional_headers);
  8440. }
  8441. } else {
  8442. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8443. }
  8444. }
  8445. /* For a given PUT path, create all intermediate subdirectories.
  8446. * Return 0 if the path itself is a directory.
  8447. * Return 1 if the path leads to a file.
  8448. * Return -1 for if the path is too long.
  8449. * Return -2 if path can not be created.
  8450. */
  8451. static int
  8452. put_dir(struct mg_connection *conn, const char *path)
  8453. {
  8454. char buf[PATH_MAX];
  8455. const char *s, *p;
  8456. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8457. size_t len;
  8458. int res = 1;
  8459. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8460. len = (size_t)(p - path);
  8461. if (len >= sizeof(buf)) {
  8462. /* path too long */
  8463. res = -1;
  8464. break;
  8465. }
  8466. memcpy(buf, path, len);
  8467. buf[len] = '\0';
  8468. /* Try to create intermediate directory */
  8469. DEBUG_TRACE("mkdir(%s)", buf);
  8470. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8471. /* path does not exixt and can not be created */
  8472. res = -2;
  8473. break;
  8474. }
  8475. /* Is path itself a directory? */
  8476. if (p[1] == '\0') {
  8477. res = 0;
  8478. }
  8479. }
  8480. return res;
  8481. }
  8482. static void
  8483. remove_bad_file(const struct mg_connection *conn, const char *path)
  8484. {
  8485. int r = mg_remove(conn, path);
  8486. if (r != 0) {
  8487. mg_cry_internal(conn,
  8488. "%s: Cannot remove invalid file %s",
  8489. __func__,
  8490. path);
  8491. }
  8492. }
  8493. long long
  8494. mg_store_body(struct mg_connection *conn, const char *path)
  8495. {
  8496. char buf[MG_BUF_LEN];
  8497. long long len = 0;
  8498. int ret, n;
  8499. struct mg_file fi;
  8500. if (conn->consumed_content != 0) {
  8501. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8502. return -11;
  8503. }
  8504. ret = put_dir(conn, path);
  8505. if (ret < 0) {
  8506. /* -1 for path too long,
  8507. * -2 for path can not be created. */
  8508. return ret;
  8509. }
  8510. if (ret != 1) {
  8511. /* Return 0 means, path itself is a directory. */
  8512. return 0;
  8513. }
  8514. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8515. return -12;
  8516. }
  8517. ret = mg_read(conn, buf, sizeof(buf));
  8518. while (ret > 0) {
  8519. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8520. if (n != ret) {
  8521. (void)mg_fclose(
  8522. &fi.access); /* File is bad and will be removed anyway. */
  8523. remove_bad_file(conn, path);
  8524. return -13;
  8525. }
  8526. len += ret;
  8527. ret = mg_read(conn, buf, sizeof(buf));
  8528. }
  8529. /* File is open for writing. If fclose fails, there was probably an
  8530. * error flushing the buffer to disk, so the file on disk might be
  8531. * broken. Delete it and return an error to the caller. */
  8532. if (mg_fclose(&fi.access) != 0) {
  8533. remove_bad_file(conn, path);
  8534. return -14;
  8535. }
  8536. return len;
  8537. }
  8538. /* Parse a buffer:
  8539. * Forward the string pointer till the end of a word, then
  8540. * terminate it and forward till the begin of the next word.
  8541. */
  8542. static int
  8543. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8544. {
  8545. /* Forward until a space is found - use isgraph here */
  8546. /* See http://www.cplusplus.com/reference/cctype/ */
  8547. while (isgraph(**ppw)) {
  8548. (*ppw)++;
  8549. }
  8550. /* Check end of word */
  8551. if (eol) {
  8552. /* must be a end of line */
  8553. if ((**ppw != '\r') && (**ppw != '\n')) {
  8554. return -1;
  8555. }
  8556. } else {
  8557. /* must be a end of a word, but not a line */
  8558. if (**ppw != ' ') {
  8559. return -1;
  8560. }
  8561. }
  8562. /* Terminate and forward to the next word */
  8563. do {
  8564. **ppw = 0;
  8565. (*ppw)++;
  8566. } while ((**ppw) && isspace(**ppw));
  8567. /* Check after term */
  8568. if (!eol) {
  8569. /* if it's not the end of line, there must be a next word */
  8570. if (!isgraph(**ppw)) {
  8571. return -1;
  8572. }
  8573. }
  8574. /* ok */
  8575. return 1;
  8576. }
  8577. /* Parse HTTP headers from the given buffer, advance buf pointer
  8578. * to the point where parsing stopped.
  8579. * All parameters must be valid pointers (not NULL).
  8580. * Return <0 on error. */
  8581. static int
  8582. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8583. {
  8584. int i;
  8585. int num_headers = 0;
  8586. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8587. char *dp = *buf;
  8588. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8589. dp++;
  8590. }
  8591. if (dp == *buf) {
  8592. /* End of headers reached. */
  8593. break;
  8594. }
  8595. if (*dp != ':') {
  8596. /* This is not a valid field. */
  8597. return -1;
  8598. }
  8599. /* End of header key (*dp == ':') */
  8600. /* Truncate here and set the key name */
  8601. *dp = 0;
  8602. hdr[i].name = *buf;
  8603. do {
  8604. dp++;
  8605. } while (*dp == ' ');
  8606. /* The rest of the line is the value */
  8607. hdr[i].value = dp;
  8608. *buf = dp + strcspn(dp, "\r\n");
  8609. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8610. *buf = NULL;
  8611. }
  8612. num_headers = i + 1;
  8613. if (*buf) {
  8614. (*buf)[0] = 0;
  8615. (*buf)[1] = 0;
  8616. *buf += 2;
  8617. } else {
  8618. *buf = dp;
  8619. break;
  8620. }
  8621. if ((*buf)[0] == '\r') {
  8622. /* This is the end of the header */
  8623. break;
  8624. }
  8625. }
  8626. return num_headers;
  8627. }
  8628. struct mg_http_method_info {
  8629. const char *name;
  8630. int request_has_body;
  8631. int response_has_body;
  8632. int is_safe;
  8633. int is_idempotent;
  8634. int is_cacheable;
  8635. };
  8636. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8637. static struct mg_http_method_info http_methods[] = {
  8638. /* HTTP (RFC 2616) */
  8639. {"GET", 0, 1, 1, 1, 1},
  8640. {"POST", 1, 1, 0, 0, 0},
  8641. {"PUT", 1, 0, 0, 1, 0},
  8642. {"DELETE", 0, 0, 0, 1, 0},
  8643. {"HEAD", 0, 0, 1, 1, 1},
  8644. {"OPTIONS", 0, 0, 1, 1, 0},
  8645. {"CONNECT", 1, 1, 0, 0, 0},
  8646. /* TRACE method (RFC 2616) is not supported for security reasons */
  8647. /* PATCH method (RFC 5789) */
  8648. {"PATCH", 1, 0, 0, 0, 0},
  8649. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8650. /* WEBDAV (RFC 2518) */
  8651. {"PROPFIND", 0, 1, 1, 1, 0},
  8652. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8653. * Some PROPFIND results MAY be cached, with care,
  8654. * as there is no cache validation mechanism for
  8655. * most properties. This method is both safe and
  8656. * idempotent (see Section 9.1 of [RFC2616]). */
  8657. {"MKCOL", 0, 0, 0, 1, 0},
  8658. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8659. * When MKCOL is invoked without a request body,
  8660. * the newly created collection SHOULD have no
  8661. * members. A MKCOL request message may contain
  8662. * a message body. The precise behavior of a MKCOL
  8663. * request when the body is present is undefined,
  8664. * ... ==> We do not support MKCOL with body data.
  8665. * This method is idempotent, but not safe (see
  8666. * Section 9.1 of [RFC2616]). Responses to this
  8667. * method MUST NOT be cached. */
  8668. /* Unsupported WEBDAV Methods: */
  8669. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8670. /* + 11 methods from RFC 3253 */
  8671. /* ORDERPATCH (RFC 3648) */
  8672. /* ACL (RFC 3744) */
  8673. /* SEARCH (RFC 5323) */
  8674. /* + MicroSoft extensions
  8675. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8676. /* REPORT method (RFC 3253) */
  8677. {"REPORT", 1, 1, 1, 1, 1},
  8678. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8679. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8680. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8681. * to be useful for REST in case a "GET request with body" is
  8682. * required. */
  8683. {NULL, 0, 0, 0, 0, 0}
  8684. /* end of list */
  8685. };
  8686. static const struct mg_http_method_info *
  8687. get_http_method_info(const char *method)
  8688. {
  8689. /* Check if the method is known to the server. The list of all known
  8690. * HTTP methods can be found here at
  8691. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8692. */
  8693. const struct mg_http_method_info *m = http_methods;
  8694. while (m->name) {
  8695. if (!strcmp(m->name, method)) {
  8696. return m;
  8697. }
  8698. m++;
  8699. }
  8700. return NULL;
  8701. }
  8702. static int
  8703. is_valid_http_method(const char *method)
  8704. {
  8705. return (get_http_method_info(method) != NULL);
  8706. }
  8707. /* Parse HTTP request, fill in mg_request_info structure.
  8708. * This function modifies the buffer by NUL-terminating
  8709. * HTTP request components, header names and header values.
  8710. * Parameters:
  8711. * buf (in/out): pointer to the HTTP header to parse and split
  8712. * len (in): length of HTTP header buffer
  8713. * re (out): parsed header as mg_request_info
  8714. * buf and ri must be valid pointers (not NULL), len>0.
  8715. * Returns <0 on error. */
  8716. static int
  8717. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8718. {
  8719. int request_length;
  8720. int init_skip = 0;
  8721. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8722. * remote_port */
  8723. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8724. NULL;
  8725. ri->num_headers = 0;
  8726. /* RFC says that all initial whitespaces should be ingored */
  8727. /* This included all leading \r and \n (isspace) */
  8728. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8729. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8730. buf++;
  8731. len--;
  8732. init_skip++;
  8733. }
  8734. if (len == 0) {
  8735. /* Incomplete request */
  8736. return 0;
  8737. }
  8738. /* Control characters are not allowed, including zero */
  8739. if (iscntrl(*(unsigned char *)buf)) {
  8740. return -1;
  8741. }
  8742. /* Find end of HTTP header */
  8743. request_length = get_http_header_len(buf, len);
  8744. if (request_length <= 0) {
  8745. return request_length;
  8746. }
  8747. buf[request_length - 1] = '\0';
  8748. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8749. return -1;
  8750. }
  8751. /* The first word has to be the HTTP method */
  8752. ri->request_method = buf;
  8753. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8754. return -1;
  8755. }
  8756. /* Check for a valid http method */
  8757. if (!is_valid_http_method(ri->request_method)) {
  8758. return -1;
  8759. }
  8760. /* The second word is the URI */
  8761. ri->request_uri = buf;
  8762. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8763. return -1;
  8764. }
  8765. /* Next would be the HTTP version */
  8766. ri->http_version = buf;
  8767. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8768. return -1;
  8769. }
  8770. /* Check for a valid HTTP version key */
  8771. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8772. /* Invalid request */
  8773. return -1;
  8774. }
  8775. ri->http_version += 5;
  8776. /* Parse all HTTP headers */
  8777. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8778. if (ri->num_headers < 0) {
  8779. /* Error while parsing headers */
  8780. return -1;
  8781. }
  8782. return request_length + init_skip;
  8783. }
  8784. static int
  8785. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8786. {
  8787. int response_length;
  8788. int init_skip = 0;
  8789. char *tmp, *tmp2;
  8790. long l;
  8791. /* Initialize elements. */
  8792. ri->http_version = ri->status_text = NULL;
  8793. ri->num_headers = ri->status_code = 0;
  8794. /* RFC says that all initial whitespaces should be ingored */
  8795. /* This included all leading \r and \n (isspace) */
  8796. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8797. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8798. buf++;
  8799. len--;
  8800. init_skip++;
  8801. }
  8802. if (len == 0) {
  8803. /* Incomplete request */
  8804. return 0;
  8805. }
  8806. /* Control characters are not allowed, including zero */
  8807. if (iscntrl(*(unsigned char *)buf)) {
  8808. return -1;
  8809. }
  8810. /* Find end of HTTP header */
  8811. response_length = get_http_header_len(buf, len);
  8812. if (response_length <= 0) {
  8813. return response_length;
  8814. }
  8815. buf[response_length - 1] = '\0';
  8816. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8817. return -1;
  8818. }
  8819. /* The first word is the HTTP version */
  8820. /* Check for a valid HTTP version key */
  8821. if (strncmp(buf, "HTTP/", 5) != 0) {
  8822. /* Invalid request */
  8823. return -1;
  8824. }
  8825. buf += 5;
  8826. if (!isgraph(buf[0])) {
  8827. /* Invalid request */
  8828. return -1;
  8829. }
  8830. ri->http_version = buf;
  8831. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8832. return -1;
  8833. }
  8834. /* The second word is the status as a number */
  8835. tmp = buf;
  8836. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8837. return -1;
  8838. }
  8839. l = strtol(tmp, &tmp2, 10);
  8840. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8841. /* Everything else but a 3 digit code is invalid */
  8842. return -1;
  8843. }
  8844. ri->status_code = (int)l;
  8845. /* The rest of the line is the status text */
  8846. ri->status_text = buf;
  8847. /* Find end of status text */
  8848. /* isgraph or isspace = isprint */
  8849. while (isprint(*buf)) {
  8850. buf++;
  8851. }
  8852. if ((*buf != '\r') && (*buf != '\n')) {
  8853. return -1;
  8854. }
  8855. /* Terminate string and forward buf to next line */
  8856. do {
  8857. *buf = 0;
  8858. buf++;
  8859. } while ((*buf) && isspace(*buf));
  8860. /* Parse all HTTP headers */
  8861. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8862. if (ri->num_headers < 0) {
  8863. /* Error while parsing headers */
  8864. return -1;
  8865. }
  8866. return response_length + init_skip;
  8867. }
  8868. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8869. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8870. * buffer (which marks the end of HTTP request). Buffer buf may already
  8871. * have some data. The length of the data is stored in nread.
  8872. * Upon every read operation, increase nread by the number of bytes read. */
  8873. static int
  8874. read_message(FILE *fp,
  8875. struct mg_connection *conn,
  8876. char *buf,
  8877. int bufsiz,
  8878. int *nread)
  8879. {
  8880. int request_len, n = 0;
  8881. struct timespec last_action_time;
  8882. double request_timeout;
  8883. if (!conn) {
  8884. return 0;
  8885. }
  8886. memset(&last_action_time, 0, sizeof(last_action_time));
  8887. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8888. /* value of request_timeout is in seconds, config in milliseconds */
  8889. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8890. } else {
  8891. request_timeout = -1.0;
  8892. }
  8893. if (conn->handled_requests > 0) {
  8894. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8895. request_timeout =
  8896. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8897. }
  8898. }
  8899. request_len = get_http_header_len(buf, *nread);
  8900. /* first time reading from this connection */
  8901. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8902. while (request_len == 0) {
  8903. /* Full request not yet received */
  8904. if (conn->phys_ctx->stop_flag != 0) {
  8905. /* Server is to be stopped. */
  8906. return -1;
  8907. }
  8908. if (*nread >= bufsiz) {
  8909. /* Request too long */
  8910. return -2;
  8911. }
  8912. n = pull_inner(
  8913. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8914. if (n == -2) {
  8915. /* Receive error */
  8916. return -1;
  8917. }
  8918. if (n > 0) {
  8919. *nread += n;
  8920. request_len = get_http_header_len(buf, *nread);
  8921. } else {
  8922. request_len = 0;
  8923. }
  8924. if ((request_len == 0) && (request_timeout >= 0)) {
  8925. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8926. > request_timeout) {
  8927. /* Timeout */
  8928. return -1;
  8929. }
  8930. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8931. }
  8932. }
  8933. return request_len;
  8934. }
  8935. #if !defined(NO_CGI) || !defined(NO_FILES)
  8936. static int
  8937. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8938. {
  8939. const char *expect, *body;
  8940. char buf[MG_BUF_LEN];
  8941. int to_read, nread, success = 0;
  8942. int64_t buffered_len;
  8943. double timeout = -1.0;
  8944. if (!conn) {
  8945. return 0;
  8946. }
  8947. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8948. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8949. }
  8950. expect = mg_get_header(conn, "Expect");
  8951. DEBUG_ASSERT(fp != NULL);
  8952. if (!fp) {
  8953. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8954. return 0;
  8955. }
  8956. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8957. /* Content length is not specified by the client. */
  8958. mg_send_http_error(conn,
  8959. 411,
  8960. "%s",
  8961. "Error: Client did not specify content length");
  8962. } else if ((expect != NULL)
  8963. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8964. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8965. */
  8966. mg_send_http_error(conn,
  8967. 417,
  8968. "Error: Can not fulfill expectation %s",
  8969. expect);
  8970. } else {
  8971. if (expect != NULL) {
  8972. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8973. conn->status_code = 100;
  8974. } else {
  8975. conn->status_code = 200;
  8976. }
  8977. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8978. - conn->consumed_content;
  8979. DEBUG_ASSERT(buffered_len >= 0);
  8980. DEBUG_ASSERT(conn->consumed_content == 0);
  8981. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8982. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8983. return 0;
  8984. }
  8985. if (buffered_len > 0) {
  8986. if ((int64_t)buffered_len > conn->content_len) {
  8987. buffered_len = (int)conn->content_len;
  8988. }
  8989. body = conn->buf + conn->request_len + conn->consumed_content;
  8990. push_all(
  8991. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8992. conn->consumed_content += buffered_len;
  8993. }
  8994. nread = 0;
  8995. while (conn->consumed_content < conn->content_len) {
  8996. to_read = sizeof(buf);
  8997. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8998. to_read = (int)(conn->content_len - conn->consumed_content);
  8999. }
  9000. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  9001. if (nread == -2) {
  9002. /* error */
  9003. break;
  9004. }
  9005. if (nread > 0) {
  9006. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  9007. != nread) {
  9008. break;
  9009. }
  9010. }
  9011. conn->consumed_content += nread;
  9012. }
  9013. if (conn->consumed_content == conn->content_len) {
  9014. success = (nread >= 0);
  9015. }
  9016. /* Each error code path in this function must send an error */
  9017. if (!success) {
  9018. /* NOTE: Maybe some data has already been sent. */
  9019. /* TODO (low): If some data has been sent, a correct error
  9020. * reply can no longer be sent, so just close the connection */
  9021. mg_send_http_error(conn, 500, "%s", "");
  9022. }
  9023. }
  9024. return success;
  9025. }
  9026. #endif
  9027. #if defined(USE_TIMERS)
  9028. #define TIMER_API static
  9029. #include "timer.inl"
  9030. #endif /* USE_TIMERS */
  9031. #if !defined(NO_CGI)
  9032. /* This structure helps to create an environment for the spawned CGI
  9033. * program.
  9034. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9035. * last element must be NULL.
  9036. * However, on Windows there is a requirement that all these
  9037. * VARIABLE=VALUE\0
  9038. * strings must reside in a contiguous buffer. The end of the buffer is
  9039. * marked by two '\0' characters.
  9040. * We satisfy both worlds: we create an envp array (which is vars), all
  9041. * entries are actually pointers inside buf. */
  9042. struct cgi_environment {
  9043. struct mg_connection *conn;
  9044. /* Data block */
  9045. char *buf; /* Environment buffer */
  9046. size_t buflen; /* Space available in buf */
  9047. size_t bufused; /* Space taken in buf */
  9048. /* Index block */
  9049. char **var; /* char **envp */
  9050. size_t varlen; /* Number of variables available in var */
  9051. size_t varused; /* Number of variables stored in var */
  9052. };
  9053. static void addenv(struct cgi_environment *env,
  9054. PRINTF_FORMAT_STRING(const char *fmt),
  9055. ...) PRINTF_ARGS(2, 3);
  9056. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9057. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9058. static void
  9059. addenv(struct cgi_environment *env, const char *fmt, ...)
  9060. {
  9061. size_t n, space;
  9062. int truncated = 0;
  9063. char *added;
  9064. va_list ap;
  9065. /* Calculate how much space is left in the buffer */
  9066. space = (env->buflen - env->bufused);
  9067. /* Calculate an estimate for the required space */
  9068. n = strlen(fmt) + 2 + 128;
  9069. do {
  9070. if (space <= n) {
  9071. /* Allocate new buffer */
  9072. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9073. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9074. if (!added) {
  9075. /* Out of memory */
  9076. mg_cry_internal(
  9077. env->conn,
  9078. "%s: Cannot allocate memory for CGI variable [%s]",
  9079. __func__,
  9080. fmt);
  9081. return;
  9082. }
  9083. env->buf = added;
  9084. env->buflen = n;
  9085. space = (env->buflen - env->bufused);
  9086. }
  9087. /* Make a pointer to the free space int the buffer */
  9088. added = env->buf + env->bufused;
  9089. /* Copy VARIABLE=VALUE\0 string into the free space */
  9090. va_start(ap, fmt);
  9091. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  9092. va_end(ap);
  9093. /* Do not add truncated strings to the environment */
  9094. if (truncated) {
  9095. /* Reallocate the buffer */
  9096. space = 0;
  9097. n = 1;
  9098. }
  9099. } while (truncated);
  9100. /* Calculate number of bytes added to the environment */
  9101. n = strlen(added) + 1;
  9102. env->bufused += n;
  9103. /* Now update the variable index */
  9104. space = (env->varlen - env->varused);
  9105. if (space < 2) {
  9106. mg_cry_internal(env->conn,
  9107. "%s: Cannot register CGI variable [%s]",
  9108. __func__,
  9109. fmt);
  9110. return;
  9111. }
  9112. /* Append a pointer to the added string into the envp array */
  9113. env->var[env->varused] = added;
  9114. env->varused++;
  9115. }
  9116. /* Return 0 on success, non-zero if an error occurs. */
  9117. static int
  9118. prepare_cgi_environment(struct mg_connection *conn,
  9119. const char *prog,
  9120. struct cgi_environment *env)
  9121. {
  9122. const char *s;
  9123. struct vec var_vec;
  9124. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9125. int i, truncated, uri_len;
  9126. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9127. return -1;
  9128. }
  9129. env->conn = conn;
  9130. env->buflen = CGI_ENVIRONMENT_SIZE;
  9131. env->bufused = 0;
  9132. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9133. if (env->buf == NULL) {
  9134. mg_cry_internal(conn,
  9135. "%s: Not enough memory for environmental buffer",
  9136. __func__);
  9137. return -1;
  9138. }
  9139. env->varlen = MAX_CGI_ENVIR_VARS;
  9140. env->varused = 0;
  9141. env->var =
  9142. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  9143. if (env->var == NULL) {
  9144. mg_cry_internal(conn,
  9145. "%s: Not enough memory for environmental variables",
  9146. __func__);
  9147. mg_free(env->buf);
  9148. return -1;
  9149. }
  9150. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9151. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9152. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9153. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9154. /* Prepare the environment block */
  9155. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9156. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9157. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9158. #if defined(USE_IPV6)
  9159. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9160. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9161. } else
  9162. #endif
  9163. {
  9164. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9165. }
  9166. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9167. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9168. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9169. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9170. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9171. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9172. /* SCRIPT_NAME */
  9173. uri_len = (int)strlen(conn->request_info.local_uri);
  9174. if (conn->path_info == NULL) {
  9175. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9176. /* URI: /path_to_script/script.cgi */
  9177. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9178. } else {
  9179. /* URI: /path_to_script/ ... using index.cgi */
  9180. const char *index_file = strrchr(prog, '/');
  9181. if (index_file) {
  9182. addenv(env,
  9183. "SCRIPT_NAME=%s%s",
  9184. conn->request_info.local_uri,
  9185. index_file + 1);
  9186. }
  9187. }
  9188. } else {
  9189. /* URI: /path_to_script/script.cgi/path_info */
  9190. addenv(env,
  9191. "SCRIPT_NAME=%.*s",
  9192. uri_len - (int)strlen(conn->path_info),
  9193. conn->request_info.local_uri);
  9194. }
  9195. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9196. if (conn->path_info == NULL) {
  9197. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9198. } else {
  9199. addenv(env,
  9200. "PATH_TRANSLATED=%s%s",
  9201. conn->dom_ctx->config[DOCUMENT_ROOT],
  9202. conn->path_info);
  9203. }
  9204. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9205. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9206. addenv(env, "CONTENT_TYPE=%s", s);
  9207. }
  9208. if (conn->request_info.query_string != NULL) {
  9209. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9210. }
  9211. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9212. addenv(env, "CONTENT_LENGTH=%s", s);
  9213. }
  9214. if ((s = getenv("PATH")) != NULL) {
  9215. addenv(env, "PATH=%s", s);
  9216. }
  9217. if (conn->path_info != NULL) {
  9218. addenv(env, "PATH_INFO=%s", conn->path_info);
  9219. }
  9220. if (conn->status_code > 0) {
  9221. /* CGI error handler should show the status code */
  9222. addenv(env, "STATUS=%d", conn->status_code);
  9223. }
  9224. #if defined(_WIN32)
  9225. if ((s = getenv("COMSPEC")) != NULL) {
  9226. addenv(env, "COMSPEC=%s", s);
  9227. }
  9228. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9229. addenv(env, "SYSTEMROOT=%s", s);
  9230. }
  9231. if ((s = getenv("SystemDrive")) != NULL) {
  9232. addenv(env, "SystemDrive=%s", s);
  9233. }
  9234. if ((s = getenv("ProgramFiles")) != NULL) {
  9235. addenv(env, "ProgramFiles=%s", s);
  9236. }
  9237. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9238. addenv(env, "ProgramFiles(x86)=%s", s);
  9239. }
  9240. #else
  9241. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9242. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9243. }
  9244. #endif /* _WIN32 */
  9245. if ((s = getenv("PERLLIB")) != NULL) {
  9246. addenv(env, "PERLLIB=%s", s);
  9247. }
  9248. if (conn->request_info.remote_user != NULL) {
  9249. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9250. addenv(env, "%s", "AUTH_TYPE=Digest");
  9251. }
  9252. /* Add all headers as HTTP_* variables */
  9253. for (i = 0; i < conn->request_info.num_headers; i++) {
  9254. (void)mg_snprintf(conn,
  9255. &truncated,
  9256. http_var_name,
  9257. sizeof(http_var_name),
  9258. "HTTP_%s",
  9259. conn->request_info.http_headers[i].name);
  9260. if (truncated) {
  9261. mg_cry_internal(conn,
  9262. "%s: HTTP header variable too long [%s]",
  9263. __func__,
  9264. conn->request_info.http_headers[i].name);
  9265. continue;
  9266. }
  9267. /* Convert variable name into uppercase, and change - to _ */
  9268. for (p = http_var_name; *p != '\0'; p++) {
  9269. if (*p == '-') {
  9270. *p = '_';
  9271. }
  9272. *p = (char)toupper(*(unsigned char *)p);
  9273. }
  9274. addenv(env,
  9275. "%s=%s",
  9276. http_var_name,
  9277. conn->request_info.http_headers[i].value);
  9278. }
  9279. /* Add user-specified variables */
  9280. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9281. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9282. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9283. }
  9284. env->var[env->varused] = NULL;
  9285. env->buf[env->bufused] = '\0';
  9286. return 0;
  9287. }
  9288. /* Data for CGI process control: PID and number of references */
  9289. struct process_control_data {
  9290. pid_t pid;
  9291. int references;
  9292. };
  9293. static int
  9294. abort_process(void *data)
  9295. {
  9296. /* Waitpid checks for child status and won't work for a pid that does not
  9297. * identify a child of the current process. Thus, if the pid is reused,
  9298. * we will not affect a different process. */
  9299. struct process_control_data *proc = (struct process_control_data *)data;
  9300. int status = 0;
  9301. int refs;
  9302. pid_t ret_pid;
  9303. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9304. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9305. /* Stop child process */
  9306. DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
  9307. kill(proc->pid, SIGABRT);
  9308. /* Wait until process is terminated (don't leave zombies) */
  9309. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9310. ;
  9311. } else {
  9312. DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
  9313. }
  9314. /* Dec reference counter */
  9315. refs = mg_atomic_dec(&proc->references);
  9316. if (refs == 0) {
  9317. /* no more references - free data */
  9318. mg_free(data);
  9319. }
  9320. return 0;
  9321. }
  9322. static void
  9323. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9324. {
  9325. char *buf;
  9326. size_t buflen;
  9327. int headers_len, data_len, i, truncated;
  9328. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9329. const char *status, *status_text, *connection_state;
  9330. char *pbuf, dir[PATH_MAX], *p;
  9331. struct mg_request_info ri;
  9332. struct cgi_environment blk;
  9333. FILE *in = NULL, *out = NULL, *err = NULL;
  9334. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9335. pid_t pid = (pid_t)-1;
  9336. struct process_control_data *proc = NULL;
  9337. #if defined(USE_TIMERS)
  9338. double cgi_timeout = -1.0;
  9339. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9340. /* Get timeout in seconds */
  9341. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9342. }
  9343. #endif
  9344. if (conn == NULL) {
  9345. return;
  9346. }
  9347. buf = NULL;
  9348. buflen = conn->phys_ctx->max_request_size;
  9349. i = prepare_cgi_environment(conn, prog, &blk);
  9350. if (i != 0) {
  9351. blk.buf = NULL;
  9352. blk.var = NULL;
  9353. goto done;
  9354. }
  9355. /* CGI must be executed in its own directory. 'dir' must point to the
  9356. * directory containing executable program, 'p' must point to the
  9357. * executable program name relative to 'dir'. */
  9358. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9359. if (truncated) {
  9360. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9361. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9362. goto done;
  9363. }
  9364. if ((p = strrchr(dir, '/')) != NULL) {
  9365. *p++ = '\0';
  9366. } else {
  9367. dir[0] = '.';
  9368. dir[1] = '\0';
  9369. p = (char *)prog;
  9370. }
  9371. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9372. status = strerror(ERRNO);
  9373. mg_cry_internal(
  9374. conn,
  9375. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9376. prog,
  9377. status);
  9378. mg_send_http_error(conn,
  9379. 500,
  9380. "Error: Cannot create CGI pipe: %s",
  9381. status);
  9382. goto done;
  9383. }
  9384. proc = (struct process_control_data *)
  9385. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9386. if (proc == NULL) {
  9387. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9388. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9389. goto done;
  9390. }
  9391. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9392. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9393. if (pid == (pid_t)-1) {
  9394. status = strerror(ERRNO);
  9395. mg_cry_internal(
  9396. conn,
  9397. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9398. prog,
  9399. status);
  9400. mg_send_http_error(conn,
  9401. 500,
  9402. "Error: Cannot spawn CGI process [%s]: %s",
  9403. prog,
  9404. status);
  9405. mg_free(proc);
  9406. proc = NULL;
  9407. goto done;
  9408. }
  9409. /* Store data in shared process_control_data */
  9410. proc->pid = pid;
  9411. proc->references = 1;
  9412. #if defined(USE_TIMERS)
  9413. if (cgi_timeout > 0.0) {
  9414. proc->references = 2;
  9415. // Start a timer for CGI
  9416. timer_add(conn->phys_ctx,
  9417. cgi_timeout /* in seconds */,
  9418. 0.0,
  9419. 1,
  9420. abort_process,
  9421. (void *)proc);
  9422. }
  9423. #endif
  9424. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  9425. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9426. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9427. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9428. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9429. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9430. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9431. /* Parent closes only one side of the pipes.
  9432. * If we don't mark them as closed, close() attempt before
  9433. * return from this function throws an exception on Windows.
  9434. * Windows does not like when closed descriptor is closed again. */
  9435. (void)close(fdin[0]);
  9436. (void)close(fdout[1]);
  9437. (void)close(fderr[1]);
  9438. fdin[0] = fdout[1] = fderr[1] = -1;
  9439. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9440. status = strerror(ERRNO);
  9441. mg_cry_internal(conn,
  9442. "Error: CGI program \"%s\": Can not open stdin: %s",
  9443. prog,
  9444. status);
  9445. mg_send_http_error(conn,
  9446. 500,
  9447. "Error: CGI can not open fdin\nfopen: %s",
  9448. status);
  9449. goto done;
  9450. }
  9451. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9452. status = strerror(ERRNO);
  9453. mg_cry_internal(conn,
  9454. "Error: CGI program \"%s\": Can not open stdout: %s",
  9455. prog,
  9456. status);
  9457. mg_send_http_error(conn,
  9458. 500,
  9459. "Error: CGI can not open fdout\nfopen: %s",
  9460. status);
  9461. goto done;
  9462. }
  9463. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9464. status = strerror(ERRNO);
  9465. mg_cry_internal(conn,
  9466. "Error: CGI program \"%s\": Can not open stderr: %s",
  9467. prog,
  9468. status);
  9469. mg_send_http_error(conn,
  9470. 500,
  9471. "Error: CGI can not open fderr\nfopen: %s",
  9472. status);
  9473. goto done;
  9474. }
  9475. setbuf(in, NULL);
  9476. setbuf(out, NULL);
  9477. setbuf(err, NULL);
  9478. fout.access.fp = out;
  9479. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9480. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9481. (signed long long)conn->request_info.content_length);
  9482. /* This is a POST/PUT request, or another request with body data. */
  9483. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9484. /* Error sending the body data */
  9485. mg_cry_internal(
  9486. conn,
  9487. "Error: CGI program \"%s\": Forward body data failed",
  9488. prog);
  9489. goto done;
  9490. }
  9491. }
  9492. /* Close so child gets an EOF. */
  9493. fclose(in);
  9494. in = NULL;
  9495. fdin[1] = -1;
  9496. /* Now read CGI reply into a buffer. We need to set correct
  9497. * status code, thus we need to see all HTTP headers first.
  9498. * Do not send anything back to client, until we buffer in all
  9499. * HTTP headers. */
  9500. data_len = 0;
  9501. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9502. if (buf == NULL) {
  9503. mg_send_http_error(conn,
  9504. 500,
  9505. "Error: Not enough memory for CGI buffer (%u bytes)",
  9506. (unsigned int)buflen);
  9507. mg_cry_internal(
  9508. conn,
  9509. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9510. "bytes)",
  9511. prog,
  9512. (unsigned int)buflen);
  9513. goto done;
  9514. }
  9515. DEBUG_TRACE("CGI: %s", "wait for response");
  9516. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9517. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9518. if (headers_len <= 0) {
  9519. /* Could not parse the CGI response. Check if some error message on
  9520. * stderr. */
  9521. i = pull_all(err, conn, buf, (int)buflen);
  9522. if (i > 0) {
  9523. /* CGI program explicitly sent an error */
  9524. /* Write the error message to the internal log */
  9525. mg_cry_internal(conn,
  9526. "Error: CGI program \"%s\" sent error "
  9527. "message: [%.*s]",
  9528. prog,
  9529. i,
  9530. buf);
  9531. /* Don't send the error message back to the client */
  9532. mg_send_http_error(conn,
  9533. 500,
  9534. "Error: CGI program \"%s\" failed.",
  9535. prog);
  9536. } else {
  9537. /* CGI program did not explicitly send an error, but a broken
  9538. * respon header */
  9539. mg_cry_internal(conn,
  9540. "Error: CGI program sent malformed or too big "
  9541. "(>%u bytes) HTTP headers: [%.*s]",
  9542. (unsigned)buflen,
  9543. data_len,
  9544. buf);
  9545. mg_send_http_error(conn,
  9546. 500,
  9547. "Error: CGI program sent malformed or too big "
  9548. "(>%u bytes) HTTP headers: [%.*s]",
  9549. (unsigned)buflen,
  9550. data_len,
  9551. buf);
  9552. }
  9553. /* in both cases, abort processing CGI */
  9554. goto done;
  9555. }
  9556. pbuf = buf;
  9557. buf[headers_len - 1] = '\0';
  9558. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9559. /* Make up and send the status line */
  9560. status_text = "OK";
  9561. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9562. != NULL) {
  9563. conn->status_code = atoi(status);
  9564. status_text = status;
  9565. while (isdigit(*(const unsigned char *)status_text)
  9566. || *status_text == ' ') {
  9567. status_text++;
  9568. }
  9569. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9570. != NULL) {
  9571. conn->status_code = 307;
  9572. } else {
  9573. conn->status_code = 200;
  9574. }
  9575. connection_state =
  9576. get_header(ri.http_headers, ri.num_headers, "Connection");
  9577. if (!header_has_option(connection_state, "keep-alive")) {
  9578. conn->must_close = 1;
  9579. }
  9580. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9581. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9582. /* Send headers */
  9583. for (i = 0; i < ri.num_headers; i++) {
  9584. mg_printf(conn,
  9585. "%s: %s\r\n",
  9586. ri.http_headers[i].name,
  9587. ri.http_headers[i].value);
  9588. }
  9589. mg_write(conn, "\r\n", 2);
  9590. /* Send chunk of data that may have been read after the headers */
  9591. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9592. /* Read the rest of CGI output and send to the client */
  9593. DEBUG_TRACE("CGI: %s", "forward all data");
  9594. send_file_data(conn, &fout, 0, INT64_MAX);
  9595. DEBUG_TRACE("CGI: %s", "all data sent");
  9596. done:
  9597. mg_free(blk.var);
  9598. mg_free(blk.buf);
  9599. if (pid != (pid_t)-1) {
  9600. abort_process((void *)proc);
  9601. }
  9602. if (fdin[0] != -1) {
  9603. close(fdin[0]);
  9604. }
  9605. if (fdout[1] != -1) {
  9606. close(fdout[1]);
  9607. }
  9608. if (in != NULL) {
  9609. fclose(in);
  9610. } else if (fdin[1] != -1) {
  9611. close(fdin[1]);
  9612. }
  9613. if (out != NULL) {
  9614. fclose(out);
  9615. } else if (fdout[0] != -1) {
  9616. close(fdout[0]);
  9617. }
  9618. if (err != NULL) {
  9619. fclose(err);
  9620. } else if (fderr[0] != -1) {
  9621. close(fderr[0]);
  9622. }
  9623. if (buf != NULL) {
  9624. mg_free(buf);
  9625. }
  9626. }
  9627. #endif /* !NO_CGI */
  9628. #if !defined(NO_FILES)
  9629. static void
  9630. mkcol(struct mg_connection *conn, const char *path)
  9631. {
  9632. int rc, body_len;
  9633. struct de de;
  9634. char date[64];
  9635. time_t curtime = time(NULL);
  9636. if (conn == NULL) {
  9637. return;
  9638. }
  9639. /* TODO (mid): Check the mg_send_http_error situations in this function
  9640. */
  9641. memset(&de.file, 0, sizeof(de.file));
  9642. if (!mg_stat(conn, path, &de.file)) {
  9643. mg_cry_internal(conn,
  9644. "%s: mg_stat(%s) failed: %s",
  9645. __func__,
  9646. path,
  9647. strerror(ERRNO));
  9648. }
  9649. if (de.file.last_modified) {
  9650. /* TODO (mid): This check does not seem to make any sense ! */
  9651. /* TODO (mid): Add a webdav unit test first, before changing
  9652. * anything here. */
  9653. mg_send_http_error(
  9654. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9655. return;
  9656. }
  9657. body_len = conn->data_len - conn->request_len;
  9658. if (body_len > 0) {
  9659. mg_send_http_error(
  9660. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9661. return;
  9662. }
  9663. rc = mg_mkdir(conn, path, 0755);
  9664. if (rc == 0) {
  9665. conn->status_code = 201;
  9666. gmt_time_string(date, sizeof(date), &curtime);
  9667. mg_printf(conn,
  9668. "HTTP/1.1 %d Created\r\n"
  9669. "Date: %s\r\n",
  9670. conn->status_code,
  9671. date);
  9672. send_static_cache_header(conn);
  9673. send_additional_header(conn);
  9674. mg_printf(conn,
  9675. "Content-Length: 0\r\n"
  9676. "Connection: %s\r\n\r\n",
  9677. suggest_connection_header(conn));
  9678. } else {
  9679. if (errno == EEXIST) {
  9680. mg_send_http_error(
  9681. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9682. } else if (errno == EACCES) {
  9683. mg_send_http_error(
  9684. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9685. } else if (errno == ENOENT) {
  9686. mg_send_http_error(
  9687. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9688. } else {
  9689. mg_send_http_error(
  9690. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9691. }
  9692. }
  9693. }
  9694. static void
  9695. put_file(struct mg_connection *conn, const char *path)
  9696. {
  9697. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9698. const char *range;
  9699. int64_t r1, r2;
  9700. int rc;
  9701. char date[64];
  9702. time_t curtime = time(NULL);
  9703. if (conn == NULL) {
  9704. return;
  9705. }
  9706. if (mg_stat(conn, path, &file.stat)) {
  9707. /* File already exists */
  9708. conn->status_code = 200;
  9709. if (file.stat.is_directory) {
  9710. /* This is an already existing directory,
  9711. * so there is nothing to do for the server. */
  9712. rc = 0;
  9713. } else {
  9714. /* File exists and is not a directory. */
  9715. /* Can it be replaced? */
  9716. #if defined(MG_USE_OPEN_FILE)
  9717. if (file.access.membuf != NULL) {
  9718. /* This is an "in-memory" file, that can not be replaced */
  9719. mg_send_http_error(conn,
  9720. 405,
  9721. "Error: Put not possible\nReplacing %s "
  9722. "is not supported",
  9723. path);
  9724. return;
  9725. }
  9726. #endif
  9727. /* Check if the server may write this file */
  9728. if (access(path, W_OK) == 0) {
  9729. /* Access granted */
  9730. conn->status_code = 200;
  9731. rc = 1;
  9732. } else {
  9733. mg_send_http_error(
  9734. conn,
  9735. 403,
  9736. "Error: Put not possible\nReplacing %s is not allowed",
  9737. path);
  9738. return;
  9739. }
  9740. }
  9741. } else {
  9742. /* File should be created */
  9743. conn->status_code = 201;
  9744. rc = put_dir(conn, path);
  9745. }
  9746. if (rc == 0) {
  9747. /* put_dir returns 0 if path is a directory */
  9748. gmt_time_string(date, sizeof(date), &curtime);
  9749. mg_printf(conn,
  9750. "HTTP/1.1 %d %s\r\n",
  9751. conn->status_code,
  9752. mg_get_response_code_text(NULL, conn->status_code));
  9753. send_no_cache_header(conn);
  9754. send_additional_header(conn);
  9755. mg_printf(conn,
  9756. "Date: %s\r\n"
  9757. "Content-Length: 0\r\n"
  9758. "Connection: %s\r\n\r\n",
  9759. date,
  9760. suggest_connection_header(conn));
  9761. /* Request to create a directory has been fulfilled successfully.
  9762. * No need to put a file. */
  9763. return;
  9764. }
  9765. if (rc == -1) {
  9766. /* put_dir returns -1 if the path is too long */
  9767. mg_send_http_error(conn,
  9768. 414,
  9769. "Error: Path too long\nput_dir(%s): %s",
  9770. path,
  9771. strerror(ERRNO));
  9772. return;
  9773. }
  9774. if (rc == -2) {
  9775. /* put_dir returns -2 if the directory can not be created */
  9776. mg_send_http_error(conn,
  9777. 500,
  9778. "Error: Can not create directory\nput_dir(%s): %s",
  9779. path,
  9780. strerror(ERRNO));
  9781. return;
  9782. }
  9783. /* A file should be created or overwritten. */
  9784. /* Currently CivetWeb does not nead read+write access. */
  9785. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9786. || file.access.fp == NULL) {
  9787. (void)mg_fclose(&file.access);
  9788. mg_send_http_error(conn,
  9789. 500,
  9790. "Error: Can not create file\nfopen(%s): %s",
  9791. path,
  9792. strerror(ERRNO));
  9793. return;
  9794. }
  9795. fclose_on_exec(&file.access, conn);
  9796. range = mg_get_header(conn, "Content-Range");
  9797. r1 = r2 = 0;
  9798. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9799. conn->status_code = 206; /* Partial content */
  9800. fseeko(file.access.fp, r1, SEEK_SET);
  9801. }
  9802. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9803. /* forward_body_data failed.
  9804. * The error code has already been sent to the client,
  9805. * and conn->status_code is already set. */
  9806. (void)mg_fclose(&file.access);
  9807. return;
  9808. }
  9809. if (mg_fclose(&file.access) != 0) {
  9810. /* fclose failed. This might have different reasons, but a likely
  9811. * one is "no space on disk", http 507. */
  9812. conn->status_code = 507;
  9813. }
  9814. gmt_time_string(date, sizeof(date), &curtime);
  9815. mg_printf(conn,
  9816. "HTTP/1.1 %d %s\r\n",
  9817. conn->status_code,
  9818. mg_get_response_code_text(NULL, conn->status_code));
  9819. send_no_cache_header(conn);
  9820. send_additional_header(conn);
  9821. mg_printf(conn,
  9822. "Date: %s\r\n"
  9823. "Content-Length: 0\r\n"
  9824. "Connection: %s\r\n\r\n",
  9825. date,
  9826. suggest_connection_header(conn));
  9827. }
  9828. static void
  9829. delete_file(struct mg_connection *conn, const char *path)
  9830. {
  9831. struct de de;
  9832. memset(&de.file, 0, sizeof(de.file));
  9833. if (!mg_stat(conn, path, &de.file)) {
  9834. /* mg_stat returns 0 if the file does not exist */
  9835. mg_send_http_error(conn,
  9836. 404,
  9837. "Error: Cannot delete file\nFile %s not found",
  9838. path);
  9839. return;
  9840. }
  9841. #if 0 /* Ignore if a file in memory is inside a folder */
  9842. if (de.access.membuf != NULL) {
  9843. /* the file is cached in memory */
  9844. mg_send_http_error(
  9845. conn,
  9846. 405,
  9847. "Error: Delete not possible\nDeleting %s is not supported",
  9848. path);
  9849. return;
  9850. }
  9851. #endif
  9852. if (de.file.is_directory) {
  9853. if (remove_directory(conn, path)) {
  9854. /* Delete is successful: Return 204 without content. */
  9855. mg_send_http_error(conn, 204, "%s", "");
  9856. } else {
  9857. /* Delete is not successful: Return 500 (Server error). */
  9858. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9859. }
  9860. return;
  9861. }
  9862. /* This is an existing file (not a directory).
  9863. * Check if write permission is granted. */
  9864. if (access(path, W_OK) != 0) {
  9865. /* File is read only */
  9866. mg_send_http_error(
  9867. conn,
  9868. 403,
  9869. "Error: Delete not possible\nDeleting %s is not allowed",
  9870. path);
  9871. return;
  9872. }
  9873. /* Try to delete it. */
  9874. if (mg_remove(conn, path) == 0) {
  9875. /* Delete was successful: Return 204 without content. */
  9876. mg_send_http_error(conn, 204, "%s", "");
  9877. } else {
  9878. /* Delete not successful (file locked). */
  9879. mg_send_http_error(conn,
  9880. 423,
  9881. "Error: Cannot delete file\nremove(%s): %s",
  9882. path,
  9883. strerror(ERRNO));
  9884. }
  9885. }
  9886. #endif /* !NO_FILES */
  9887. static void
  9888. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9889. static void
  9890. do_ssi_include(struct mg_connection *conn,
  9891. const char *ssi,
  9892. char *tag,
  9893. int include_level)
  9894. {
  9895. char file_name[MG_BUF_LEN], path[512], *p;
  9896. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9897. size_t len;
  9898. int truncated = 0;
  9899. if (conn == NULL) {
  9900. return;
  9901. }
  9902. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9903. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9904. * always < MG_BUF_LEN. */
  9905. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9906. /* File name is relative to the webserver root */
  9907. file_name[511] = 0;
  9908. (void)mg_snprintf(conn,
  9909. &truncated,
  9910. path,
  9911. sizeof(path),
  9912. "%s/%s",
  9913. conn->dom_ctx->config[DOCUMENT_ROOT],
  9914. file_name);
  9915. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9916. /* File name is relative to the webserver working directory
  9917. * or it is absolute system path */
  9918. file_name[511] = 0;
  9919. (void)
  9920. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9921. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9922. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9923. /* File name is relative to the currect document */
  9924. file_name[511] = 0;
  9925. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9926. if (!truncated) {
  9927. if ((p = strrchr(path, '/')) != NULL) {
  9928. p[1] = '\0';
  9929. }
  9930. len = strlen(path);
  9931. (void)mg_snprintf(conn,
  9932. &truncated,
  9933. path + len,
  9934. sizeof(path) - len,
  9935. "%s",
  9936. file_name);
  9937. }
  9938. } else {
  9939. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9940. return;
  9941. }
  9942. if (truncated) {
  9943. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9944. return;
  9945. }
  9946. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9947. mg_cry_internal(conn,
  9948. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9949. tag,
  9950. path,
  9951. strerror(ERRNO));
  9952. } else {
  9953. fclose_on_exec(&file.access, conn);
  9954. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9955. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9956. path)
  9957. > 0) {
  9958. send_ssi_file(conn, path, &file, include_level + 1);
  9959. } else {
  9960. send_file_data(conn, &file, 0, INT64_MAX);
  9961. }
  9962. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9963. }
  9964. }
  9965. #if !defined(NO_POPEN)
  9966. static void
  9967. do_ssi_exec(struct mg_connection *conn, char *tag)
  9968. {
  9969. char cmd[1024] = "";
  9970. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9971. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9972. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9973. } else {
  9974. cmd[1023] = 0;
  9975. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9976. mg_cry_internal(conn,
  9977. "Cannot SSI #exec: [%s]: %s",
  9978. cmd,
  9979. strerror(ERRNO));
  9980. } else {
  9981. send_file_data(conn, &file, 0, INT64_MAX);
  9982. pclose(file.access.fp);
  9983. }
  9984. }
  9985. }
  9986. #endif /* !NO_POPEN */
  9987. static int
  9988. mg_fgetc(struct mg_file *filep, int offset)
  9989. {
  9990. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  9991. if (filep == NULL) {
  9992. return EOF;
  9993. }
  9994. #if defined(MG_USE_OPEN_FILE)
  9995. if ((filep->access.membuf != NULL) && (offset >= 0)
  9996. && (((unsigned int)(offset)) < filep->stat.size)) {
  9997. return ((const unsigned char *)filep->access.membuf)[offset];
  9998. } else /* else block below */
  9999. #endif
  10000. if (filep->access.fp != NULL) {
  10001. return fgetc(filep->access.fp);
  10002. } else {
  10003. return EOF;
  10004. }
  10005. }
  10006. static void
  10007. send_ssi_file(struct mg_connection *conn,
  10008. const char *path,
  10009. struct mg_file *filep,
  10010. int include_level)
  10011. {
  10012. char buf[MG_BUF_LEN];
  10013. int ch, offset, len, in_tag, in_ssi_tag;
  10014. if (include_level > 10) {
  10015. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10016. return;
  10017. }
  10018. in_tag = in_ssi_tag = len = offset = 0;
  10019. /* Read file, byte by byte, and look for SSI include tags */
  10020. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10021. if (in_tag) {
  10022. /* We are in a tag, either SSI tag or html tag */
  10023. if (ch == '>') {
  10024. /* Tag is closing */
  10025. buf[len++] = '>';
  10026. if (in_ssi_tag) {
  10027. /* Handle SSI tag */
  10028. buf[len] = 0;
  10029. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10030. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10031. #if !defined(NO_POPEN)
  10032. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10033. do_ssi_exec(conn, buf + 9);
  10034. #endif /* !NO_POPEN */
  10035. } else {
  10036. mg_cry_internal(conn,
  10037. "%s: unknown SSI "
  10038. "command: \"%s\"",
  10039. path,
  10040. buf);
  10041. }
  10042. len = 0;
  10043. in_ssi_tag = in_tag = 0;
  10044. } else {
  10045. /* Not an SSI tag */
  10046. /* Flush buffer */
  10047. (void)mg_write(conn, buf, (size_t)len);
  10048. len = 0;
  10049. in_tag = 0;
  10050. }
  10051. } else {
  10052. /* Tag is still open */
  10053. buf[len++] = (char)(ch & 0xff);
  10054. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10055. /* All SSI tags start with <!--# */
  10056. in_ssi_tag = 1;
  10057. }
  10058. if ((len + 2) > (int)sizeof(buf)) {
  10059. /* Tag to long for buffer */
  10060. mg_cry_internal(conn, "%s: tag is too large", path);
  10061. return;
  10062. }
  10063. }
  10064. } else {
  10065. /* We are not in a tag yet. */
  10066. if (ch == '<') {
  10067. /* Tag is opening */
  10068. in_tag = 1;
  10069. if (len > 0) {
  10070. /* Flush current buffer.
  10071. * Buffer is filled with "len" bytes. */
  10072. (void)mg_write(conn, buf, (size_t)len);
  10073. }
  10074. /* Store the < */
  10075. len = 1;
  10076. buf[0] = '<';
  10077. } else {
  10078. /* No Tag */
  10079. /* Add data to buffer */
  10080. buf[len++] = (char)(ch & 0xff);
  10081. /* Flush if buffer is full */
  10082. if (len == (int)sizeof(buf)) {
  10083. mg_write(conn, buf, (size_t)len);
  10084. len = 0;
  10085. }
  10086. }
  10087. }
  10088. }
  10089. /* Send the rest of buffered data */
  10090. if (len > 0) {
  10091. mg_write(conn, buf, (size_t)len);
  10092. }
  10093. }
  10094. static void
  10095. handle_ssi_file_request(struct mg_connection *conn,
  10096. const char *path,
  10097. struct mg_file *filep)
  10098. {
  10099. char date[64];
  10100. time_t curtime = time(NULL);
  10101. const char *cors1, *cors2, *cors3;
  10102. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10103. return;
  10104. }
  10105. if (mg_get_header(conn, "Origin")) {
  10106. /* Cross-origin resource sharing (CORS). */
  10107. cors1 = "Access-Control-Allow-Origin: ";
  10108. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10109. cors3 = "\r\n";
  10110. } else {
  10111. cors1 = cors2 = cors3 = "";
  10112. }
  10113. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10114. /* File exists (precondition for calling this function),
  10115. * but can not be opened by the server. */
  10116. mg_send_http_error(conn,
  10117. 500,
  10118. "Error: Cannot read file\nfopen(%s): %s",
  10119. path,
  10120. strerror(ERRNO));
  10121. } else {
  10122. conn->must_close = 1;
  10123. gmt_time_string(date, sizeof(date), &curtime);
  10124. fclose_on_exec(&filep->access, conn);
  10125. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10126. send_no_cache_header(conn);
  10127. send_additional_header(conn);
  10128. mg_printf(conn,
  10129. "%s%s%s"
  10130. "Date: %s\r\n"
  10131. "Content-Type: text/html\r\n"
  10132. "Connection: %s\r\n\r\n",
  10133. cors1,
  10134. cors2,
  10135. cors3,
  10136. date,
  10137. suggest_connection_header(conn));
  10138. send_ssi_file(conn, path, filep, 0);
  10139. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10140. }
  10141. }
  10142. #if !defined(NO_FILES)
  10143. static void
  10144. send_options(struct mg_connection *conn)
  10145. {
  10146. char date[64];
  10147. time_t curtime = time(NULL);
  10148. if (!conn) {
  10149. return;
  10150. }
  10151. conn->status_code = 200;
  10152. conn->must_close = 1;
  10153. gmt_time_string(date, sizeof(date), &curtime);
  10154. /* We do not set a "Cache-Control" header here, but leave the default.
  10155. * Since browsers do not send an OPTIONS request, we can not test the
  10156. * effect anyway. */
  10157. mg_printf(conn,
  10158. "HTTP/1.1 200 OK\r\n"
  10159. "Date: %s\r\n"
  10160. "Connection: %s\r\n"
  10161. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10162. "PROPFIND, MKCOL\r\n"
  10163. "DAV: 1\r\n",
  10164. date,
  10165. suggest_connection_header(conn));
  10166. send_additional_header(conn);
  10167. mg_printf(conn, "\r\n");
  10168. }
  10169. /* Writes PROPFIND properties for a collection element */
  10170. static void
  10171. print_props(struct mg_connection *conn,
  10172. const char *uri,
  10173. struct mg_file_stat *filep)
  10174. {
  10175. char mtime[64];
  10176. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  10177. return;
  10178. }
  10179. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10180. mg_printf(conn,
  10181. "<d:response>"
  10182. "<d:href>%s</d:href>"
  10183. "<d:propstat>"
  10184. "<d:prop>"
  10185. "<d:resourcetype>%s</d:resourcetype>"
  10186. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10187. "<d:getlastmodified>%s</d:getlastmodified>"
  10188. "</d:prop>"
  10189. "<d:status>HTTP/1.1 200 OK</d:status>"
  10190. "</d:propstat>"
  10191. "</d:response>\n",
  10192. uri,
  10193. filep->is_directory ? "<d:collection/>" : "",
  10194. filep->size,
  10195. mtime);
  10196. }
  10197. static int
  10198. print_dav_dir_entry(struct de *de, void *data)
  10199. {
  10200. char href[PATH_MAX];
  10201. int truncated;
  10202. struct mg_connection *conn = (struct mg_connection *)data;
  10203. if (!de || !conn) {
  10204. return -1;
  10205. }
  10206. mg_snprintf(conn,
  10207. &truncated,
  10208. href,
  10209. sizeof(href),
  10210. "%s%s",
  10211. conn->request_info.local_uri,
  10212. de->file_name);
  10213. if (!truncated) {
  10214. size_t href_encoded_size;
  10215. char *href_encoded;
  10216. href_encoded_size = PATH_MAX * 3; /* worst case */
  10217. href_encoded = (char *)mg_malloc(href_encoded_size);
  10218. if (href_encoded == NULL) {
  10219. return -1;
  10220. }
  10221. mg_url_encode(href, href_encoded, href_encoded_size);
  10222. print_props(conn, href_encoded, &de->file);
  10223. mg_free(href_encoded);
  10224. }
  10225. return 0;
  10226. }
  10227. static void
  10228. handle_propfind(struct mg_connection *conn,
  10229. const char *path,
  10230. struct mg_file_stat *filep)
  10231. {
  10232. const char *depth = mg_get_header(conn, "Depth");
  10233. char date[64];
  10234. time_t curtime = time(NULL);
  10235. gmt_time_string(date, sizeof(date), &curtime);
  10236. if (!conn || !path || !filep || !conn->dom_ctx) {
  10237. return;
  10238. }
  10239. conn->must_close = 1;
  10240. conn->status_code = 207;
  10241. mg_printf(conn,
  10242. "HTTP/1.1 207 Multi-Status\r\n"
  10243. "Date: %s\r\n",
  10244. date);
  10245. send_static_cache_header(conn);
  10246. send_additional_header(conn);
  10247. mg_printf(conn,
  10248. "Connection: %s\r\n"
  10249. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10250. suggest_connection_header(conn));
  10251. mg_printf(conn,
  10252. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10253. "<d:multistatus xmlns:d='DAV:'>\n");
  10254. /* Print properties for the requested resource itself */
  10255. print_props(conn, conn->request_info.local_uri, filep);
  10256. /* If it is a directory, print directory entries too if Depth is not 0
  10257. */
  10258. if (filep->is_directory
  10259. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10260. "yes")
  10261. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10262. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10263. }
  10264. mg_printf(conn, "%s\n", "</d:multistatus>");
  10265. }
  10266. #endif
  10267. void
  10268. mg_lock_connection(struct mg_connection *conn)
  10269. {
  10270. if (conn) {
  10271. (void)pthread_mutex_lock(&conn->mutex);
  10272. }
  10273. }
  10274. void
  10275. mg_unlock_connection(struct mg_connection *conn)
  10276. {
  10277. if (conn) {
  10278. (void)pthread_mutex_unlock(&conn->mutex);
  10279. }
  10280. }
  10281. void
  10282. mg_lock_context(struct mg_context *ctx)
  10283. {
  10284. if (ctx) {
  10285. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10286. }
  10287. }
  10288. void
  10289. mg_unlock_context(struct mg_context *ctx)
  10290. {
  10291. if (ctx) {
  10292. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10293. }
  10294. }
  10295. #if defined(USE_LUA)
  10296. #include "mod_lua.inl"
  10297. #endif /* USE_LUA */
  10298. #if defined(USE_DUKTAPE)
  10299. #include "mod_duktape.inl"
  10300. #endif /* USE_DUKTAPE */
  10301. #if defined(USE_WEBSOCKET)
  10302. #if !defined(NO_SSL_DL)
  10303. #define SHA_API static
  10304. #include "sha1.inl"
  10305. #endif
  10306. static int
  10307. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10308. {
  10309. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10310. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10311. SHA_CTX sha_ctx;
  10312. int truncated;
  10313. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10314. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10315. if (truncated) {
  10316. conn->must_close = 1;
  10317. return 0;
  10318. }
  10319. DEBUG_TRACE("%s", "Send websocket handshake");
  10320. SHA1_Init(&sha_ctx);
  10321. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10322. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10323. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10324. mg_printf(conn,
  10325. "HTTP/1.1 101 Switching Protocols\r\n"
  10326. "Upgrade: websocket\r\n"
  10327. "Connection: Upgrade\r\n"
  10328. "Sec-WebSocket-Accept: %s\r\n",
  10329. b64_sha);
  10330. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10331. mg_printf(conn,
  10332. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10333. conn->request_info.acceptedWebSocketSubprotocol);
  10334. } else {
  10335. mg_printf(conn, "%s", "\r\n");
  10336. }
  10337. return 1;
  10338. }
  10339. #if !defined(MG_MAX_UNANSWERED_PING)
  10340. /* Configuration of the maximum number of websocket PINGs that might
  10341. * stay unanswered before the connection is considered broken.
  10342. * Note: The name of this define may still change (until it is
  10343. * defined as a compile parameter in a documentation).
  10344. */
  10345. #define MG_MAX_UNANSWERED_PING (5)
  10346. #endif
  10347. static void
  10348. read_websocket(struct mg_connection *conn,
  10349. mg_websocket_data_handler ws_data_handler,
  10350. void *callback_data)
  10351. {
  10352. /* Pointer to the beginning of the portion of the incoming websocket
  10353. * message queue.
  10354. * The original websocket upgrade request is never removed, so the queue
  10355. * begins after it. */
  10356. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10357. int n, error, exit_by_callback;
  10358. int ret;
  10359. /* body_len is the length of the entire queue in bytes
  10360. * len is the length of the current message
  10361. * data_len is the length of the current message's data payload
  10362. * header_len is the length of the current message's header */
  10363. size_t i, len, mask_len = 0, header_len, body_len;
  10364. uint64_t data_len = 0;
  10365. /* "The masking key is a 32-bit value chosen at random by the client."
  10366. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10367. */
  10368. unsigned char mask[4];
  10369. /* data points to the place where the message is stored when passed to
  10370. * the websocket_data callback. This is either mem on the stack, or a
  10371. * dynamically allocated buffer if it is too large. */
  10372. unsigned char mem[4096];
  10373. unsigned char mop; /* mask flag and opcode */
  10374. /* Variables used for connection monitoring */
  10375. double timeout = -1.0;
  10376. int enable_ping_pong = 0;
  10377. int ping_count = 0;
  10378. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10379. enable_ping_pong =
  10380. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10381. "yes");
  10382. }
  10383. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10384. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10385. }
  10386. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10387. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10388. }
  10389. /* Enter data processing loop */
  10390. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10391. conn->request_info.remote_addr,
  10392. conn->request_info.remote_port);
  10393. conn->in_websocket_handling = 1;
  10394. mg_set_thread_name("wsock");
  10395. /* Loop continuously, reading messages from the socket, invoking the
  10396. * callback, and waiting repeatedly until an error occurs. */
  10397. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10398. header_len = 0;
  10399. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10400. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10401. len = buf[1] & 127;
  10402. mask_len = (buf[1] & 128) ? 4 : 0;
  10403. if ((len < 126) && (body_len >= mask_len)) {
  10404. /* inline 7-bit length field */
  10405. data_len = len;
  10406. header_len = 2 + mask_len;
  10407. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10408. /* 16-bit length field */
  10409. header_len = 4 + mask_len;
  10410. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10411. } else if (body_len >= (10 + mask_len)) {
  10412. /* 64-bit length field */
  10413. uint32_t l1, l2;
  10414. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10415. memcpy(&l2, &buf[6], 4);
  10416. header_len = 10 + mask_len;
  10417. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10418. if (data_len > (uint64_t)0x7FFF0000ul) {
  10419. /* no can do */
  10420. mg_cry_internal(
  10421. conn,
  10422. "%s",
  10423. "websocket out of memory; closing connection");
  10424. break;
  10425. }
  10426. }
  10427. }
  10428. if ((header_len > 0) && (body_len >= header_len)) {
  10429. /* Allocate space to hold websocket payload */
  10430. unsigned char *data = mem;
  10431. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10432. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10433. conn->phys_ctx);
  10434. if (data == NULL) {
  10435. /* Allocation failed, exit the loop and then close the
  10436. * connection */
  10437. mg_cry_internal(
  10438. conn,
  10439. "%s",
  10440. "websocket out of memory; closing connection");
  10441. break;
  10442. }
  10443. }
  10444. /* Copy the mask before we shift the queue and destroy it */
  10445. if (mask_len > 0) {
  10446. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10447. } else {
  10448. memset(mask, 0, sizeof(mask));
  10449. }
  10450. /* Read frame payload from the first message in the queue into
  10451. * data and advance the queue by moving the memory in place. */
  10452. DEBUG_ASSERT(body_len >= header_len);
  10453. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10454. mop = buf[0]; /* current mask and opcode */
  10455. /* Overflow case */
  10456. len = body_len - header_len;
  10457. memcpy(data, buf + header_len, len);
  10458. error = 0;
  10459. while ((uint64_t)len < data_len) {
  10460. n = pull_inner(NULL,
  10461. conn,
  10462. (char *)(data + len),
  10463. (int)(data_len - len),
  10464. timeout);
  10465. if (n <= -2) {
  10466. error = 1;
  10467. break;
  10468. } else if (n > 0) {
  10469. len += (size_t)n;
  10470. } else {
  10471. /* Timeout: should retry */
  10472. /* TODO: retry condition */
  10473. }
  10474. }
  10475. if (error) {
  10476. mg_cry_internal(
  10477. conn,
  10478. "%s",
  10479. "Websocket pull failed; closing connection");
  10480. if (data != mem) {
  10481. mg_free(data);
  10482. }
  10483. break;
  10484. }
  10485. conn->data_len = conn->request_len;
  10486. } else {
  10487. mop = buf[0]; /* current mask and opcode, overwritten by
  10488. * memmove() */
  10489. /* Length of the message being read at the front of the
  10490. * queue. Cast to 31 bit is OK, since we limited
  10491. * data_len before. */
  10492. len = (size_t)data_len + header_len;
  10493. /* Copy the data payload into the data pointer for the
  10494. * callback. Cast to 31 bit is OK, since we
  10495. * limited data_len */
  10496. memcpy(data, buf + header_len, (size_t)data_len);
  10497. /* Move the queue forward len bytes */
  10498. memmove(buf, buf + len, body_len - len);
  10499. /* Mark the queue as advanced */
  10500. conn->data_len -= (int)len;
  10501. }
  10502. /* Apply mask if necessary */
  10503. if (mask_len > 0) {
  10504. for (i = 0; i < (size_t)data_len; i++) {
  10505. data[i] ^= mask[i & 3];
  10506. }
  10507. }
  10508. exit_by_callback = 0;
  10509. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10510. /* filter PONG messages */
  10511. DEBUG_TRACE("PONG from %s:%u",
  10512. conn->request_info.remote_addr,
  10513. conn->request_info.remote_port);
  10514. /* No unanwered PINGs left */
  10515. ping_count = 0;
  10516. } else if (enable_ping_pong
  10517. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10518. /* reply PING messages */
  10519. DEBUG_TRACE("Reply PING from %s:%u",
  10520. conn->request_info.remote_addr,
  10521. conn->request_info.remote_port);
  10522. ret = mg_websocket_write(conn,
  10523. MG_WEBSOCKET_OPCODE_PONG,
  10524. (char *)data,
  10525. (size_t)data_len);
  10526. if (ret <= 0) {
  10527. /* Error: send failed */
  10528. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10529. break;
  10530. }
  10531. } else {
  10532. /* Exit the loop if callback signals to exit (server side),
  10533. * or "connection close" opcode received (client side). */
  10534. if ((ws_data_handler != NULL)
  10535. && !ws_data_handler(conn,
  10536. mop,
  10537. (char *)data,
  10538. (size_t)data_len,
  10539. callback_data)) {
  10540. exit_by_callback = 1;
  10541. }
  10542. }
  10543. /* It a buffer has been allocated, free it again */
  10544. if (data != mem) {
  10545. mg_free(data);
  10546. }
  10547. if (exit_by_callback) {
  10548. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10549. conn->request_info.remote_addr,
  10550. conn->request_info.remote_port);
  10551. break;
  10552. }
  10553. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10554. /* Opcode == 8, connection close */
  10555. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10556. conn->request_info.remote_addr,
  10557. conn->request_info.remote_port);
  10558. break;
  10559. }
  10560. /* Not breaking the loop, process next websocket frame. */
  10561. } else {
  10562. /* Read from the socket into the next available location in the
  10563. * message queue. */
  10564. n = pull_inner(NULL,
  10565. conn,
  10566. conn->buf + conn->data_len,
  10567. conn->buf_size - conn->data_len,
  10568. timeout);
  10569. if (n <= -2) {
  10570. /* Error, no bytes read */
  10571. DEBUG_TRACE("PULL from %s:%u failed",
  10572. conn->request_info.remote_addr,
  10573. conn->request_info.remote_port);
  10574. break;
  10575. }
  10576. if (n > 0) {
  10577. conn->data_len += n;
  10578. /* Reset open PING count */
  10579. ping_count = 0;
  10580. } else {
  10581. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10582. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10583. /* Stop sending PING */
  10584. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10585. "- closing connection",
  10586. ping_count,
  10587. conn->request_info.remote_addr,
  10588. conn->request_info.remote_port);
  10589. break;
  10590. }
  10591. if (enable_ping_pong) {
  10592. /* Send Websocket PING message */
  10593. DEBUG_TRACE("PING to %s:%u",
  10594. conn->request_info.remote_addr,
  10595. conn->request_info.remote_port);
  10596. ret = mg_websocket_write(conn,
  10597. MG_WEBSOCKET_OPCODE_PING,
  10598. NULL,
  10599. 0);
  10600. if (ret <= 0) {
  10601. /* Error: send failed */
  10602. DEBUG_TRACE("Send PING failed (%i)", ret);
  10603. break;
  10604. }
  10605. ping_count++;
  10606. }
  10607. }
  10608. /* Timeout: should retry */
  10609. /* TODO: get timeout def */
  10610. }
  10611. }
  10612. }
  10613. /* Leave data processing loop */
  10614. mg_set_thread_name("worker");
  10615. conn->in_websocket_handling = 0;
  10616. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10617. conn->request_info.remote_addr,
  10618. conn->request_info.remote_port);
  10619. }
  10620. static int
  10621. mg_websocket_write_exec(struct mg_connection *conn,
  10622. int opcode,
  10623. const char *data,
  10624. size_t dataLen,
  10625. uint32_t masking_key)
  10626. {
  10627. unsigned char header[14];
  10628. size_t headerLen;
  10629. int retval;
  10630. #if defined(GCC_DIAGNOSTIC)
  10631. /* Disable spurious conversion warning for GCC */
  10632. #pragma GCC diagnostic push
  10633. #pragma GCC diagnostic ignored "-Wconversion"
  10634. #endif
  10635. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10636. #if defined(GCC_DIAGNOSTIC)
  10637. #pragma GCC diagnostic pop
  10638. #endif
  10639. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10640. if (dataLen < 126) {
  10641. /* inline 7-bit length field */
  10642. header[1] = (unsigned char)dataLen;
  10643. headerLen = 2;
  10644. } else if (dataLen <= 0xFFFF) {
  10645. /* 16-bit length field */
  10646. uint16_t len = htons((uint16_t)dataLen);
  10647. header[1] = 126;
  10648. memcpy(header + 2, &len, 2);
  10649. headerLen = 4;
  10650. } else {
  10651. /* 64-bit length field */
  10652. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10653. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10654. header[1] = 127;
  10655. memcpy(header + 2, &len1, 4);
  10656. memcpy(header + 6, &len2, 4);
  10657. headerLen = 10;
  10658. }
  10659. if (masking_key) {
  10660. /* add mask */
  10661. header[1] |= 0x80;
  10662. memcpy(header + headerLen, &masking_key, 4);
  10663. headerLen += 4;
  10664. }
  10665. /* Note that POSIX/Winsock's send() is threadsafe
  10666. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10667. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10668. * push(), although that is only a problem if the packet is large or
  10669. * outgoing buffer is full). */
  10670. /* TODO: Check if this lock should be moved to user land.
  10671. * Currently the server sets this lock for websockets, but
  10672. * not for any other connection. It must be set for every
  10673. * conn read/written by more than one thread, no matter if
  10674. * it is a websocket or regular connection. */
  10675. (void)mg_lock_connection(conn);
  10676. retval = mg_write(conn, header, headerLen);
  10677. if (retval != (int)headerLen) {
  10678. /* Did not send complete header */
  10679. retval = -1;
  10680. } else {
  10681. if (dataLen > 0) {
  10682. retval = mg_write(conn, data, dataLen);
  10683. }
  10684. /* if dataLen == 0, the header length (2) is returned */
  10685. }
  10686. /* TODO: Remove this unlock as well, when lock is removed. */
  10687. mg_unlock_connection(conn);
  10688. return retval;
  10689. }
  10690. int
  10691. mg_websocket_write(struct mg_connection *conn,
  10692. int opcode,
  10693. const char *data,
  10694. size_t dataLen)
  10695. {
  10696. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10697. }
  10698. static void
  10699. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10700. {
  10701. size_t i = 0;
  10702. i = 0;
  10703. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10704. /* Convert in 32 bit words, if data is 4 byte aligned */
  10705. while (i < (in_len - 3)) {
  10706. *(uint32_t *)(void *)(out + i) =
  10707. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10708. i += 4;
  10709. }
  10710. }
  10711. if (i != in_len) {
  10712. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10713. while (i < in_len) {
  10714. *(uint8_t *)(void *)(out + i) =
  10715. *(uint8_t *)(void *)(in + i)
  10716. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10717. i++;
  10718. }
  10719. }
  10720. }
  10721. int
  10722. mg_websocket_client_write(struct mg_connection *conn,
  10723. int opcode,
  10724. const char *data,
  10725. size_t dataLen)
  10726. {
  10727. int retval = -1;
  10728. char *masked_data =
  10729. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10730. uint32_t masking_key = 0;
  10731. if (masked_data == NULL) {
  10732. /* Return -1 in an error case */
  10733. mg_cry_internal(conn,
  10734. "%s",
  10735. "Cannot allocate buffer for masked websocket response: "
  10736. "Out of memory");
  10737. return -1;
  10738. }
  10739. do {
  10740. /* Get a masking key - but not 0 */
  10741. masking_key = (uint32_t)get_random();
  10742. } while (masking_key == 0);
  10743. mask_data(data, dataLen, masking_key, masked_data);
  10744. retval = mg_websocket_write_exec(
  10745. conn, opcode, masked_data, dataLen, masking_key);
  10746. mg_free(masked_data);
  10747. return retval;
  10748. }
  10749. static void
  10750. handle_websocket_request(struct mg_connection *conn,
  10751. const char *path,
  10752. int is_callback_resource,
  10753. struct mg_websocket_subprotocols *subprotocols,
  10754. mg_websocket_connect_handler ws_connect_handler,
  10755. mg_websocket_ready_handler ws_ready_handler,
  10756. mg_websocket_data_handler ws_data_handler,
  10757. mg_websocket_close_handler ws_close_handler,
  10758. void *cbData)
  10759. {
  10760. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10761. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10762. ptrdiff_t lua_websock = 0;
  10763. #if !defined(USE_LUA)
  10764. (void)path;
  10765. #endif
  10766. /* Step 1: Check websocket protocol version. */
  10767. /* Step 1.1: Check Sec-WebSocket-Key. */
  10768. if (!websock_key) {
  10769. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10770. * requires a Sec-WebSocket-Key header.
  10771. */
  10772. /* It could be the hixie draft version
  10773. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10774. */
  10775. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10776. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10777. char key3[8];
  10778. if ((key1 != NULL) && (key2 != NULL)) {
  10779. /* This version uses 8 byte body data in a GET request */
  10780. conn->content_len = 8;
  10781. if (8 == mg_read(conn, key3, 8)) {
  10782. /* This is the hixie version */
  10783. mg_send_http_error(conn,
  10784. 426,
  10785. "%s",
  10786. "Protocol upgrade to RFC 6455 required");
  10787. return;
  10788. }
  10789. }
  10790. /* This is an unknown version */
  10791. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10792. return;
  10793. }
  10794. /* Step 1.2: Check websocket protocol version. */
  10795. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10796. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10797. /* Reject wrong versions */
  10798. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10799. return;
  10800. }
  10801. /* Step 1.3: Could check for "Host", but we do not really nead this
  10802. * value for anything, so just ignore it. */
  10803. /* Step 2: If a callback is responsible, call it. */
  10804. if (is_callback_resource) {
  10805. /* Step 2.1 check and select subprotocol */
  10806. const char *protocols[64]; // max 64 headers
  10807. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10808. "Sec-WebSocket-Protocol",
  10809. protocols,
  10810. 64);
  10811. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10812. int cnt = 0;
  10813. int idx;
  10814. unsigned long len;
  10815. const char *sep, *curSubProtocol,
  10816. *acceptedWebSocketSubprotocol = NULL;
  10817. /* look for matching subprotocol */
  10818. do {
  10819. const char *protocol = protocols[cnt];
  10820. do {
  10821. sep = strchr(protocol, ',');
  10822. curSubProtocol = protocol;
  10823. len = sep ? (unsigned long)(sep - protocol)
  10824. : (unsigned long)strlen(protocol);
  10825. while (sep && isspace(*++sep))
  10826. ; // ignore leading whitespaces
  10827. protocol = sep;
  10828. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10829. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10830. && (strncmp(curSubProtocol,
  10831. subprotocols->subprotocols[idx],
  10832. len)
  10833. == 0)) {
  10834. acceptedWebSocketSubprotocol =
  10835. subprotocols->subprotocols[idx];
  10836. break;
  10837. }
  10838. }
  10839. } while (sep && !acceptedWebSocketSubprotocol);
  10840. } while (++cnt < nbSubprotocolHeader
  10841. && !acceptedWebSocketSubprotocol);
  10842. conn->request_info.acceptedWebSocketSubprotocol =
  10843. acceptedWebSocketSubprotocol;
  10844. } else if (nbSubprotocolHeader > 0) {
  10845. /* keep legacy behavior */
  10846. const char *protocol = protocols[0];
  10847. /* The protocol is a comma separated list of names. */
  10848. /* The server must only return one value from this list. */
  10849. /* First check if it is a list or just a single value. */
  10850. const char *sep = strrchr(protocol, ',');
  10851. if (sep == NULL) {
  10852. /* Just a single protocol -> accept it. */
  10853. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10854. } else {
  10855. /* Multiple protocols -> accept the last one. */
  10856. /* This is just a quick fix if the client offers multiple
  10857. * protocols. The handler should have a list of accepted
  10858. * protocols on his own
  10859. * and use it to select one protocol among those the client
  10860. * has
  10861. * offered.
  10862. */
  10863. while (isspace(*++sep)) {
  10864. ; /* ignore leading whitespaces */
  10865. }
  10866. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10867. }
  10868. }
  10869. if ((ws_connect_handler != NULL)
  10870. && (ws_connect_handler(conn, cbData) != 0)) {
  10871. /* C callback has returned non-zero, do not proceed with
  10872. * handshake.
  10873. */
  10874. /* Note that C callbacks are no longer called when Lua is
  10875. * responsible, so C can no longer filter callbacks for Lua. */
  10876. return;
  10877. }
  10878. }
  10879. #if defined(USE_LUA)
  10880. /* Step 3: No callback. Check if Lua is responsible. */
  10881. else {
  10882. /* Step 3.1: Check if Lua is responsible. */
  10883. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10884. lua_websock = match_prefix(
  10885. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10886. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10887. path);
  10888. }
  10889. if (lua_websock) {
  10890. /* Step 3.2: Lua is responsible: call it. */
  10891. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10892. if (!conn->lua_websocket_state) {
  10893. /* Lua rejected the new client */
  10894. return;
  10895. }
  10896. }
  10897. }
  10898. #endif
  10899. /* Step 4: Check if there is a responsible websocket handler. */
  10900. if (!is_callback_resource && !lua_websock) {
  10901. /* There is no callback, and Lua is not responsible either. */
  10902. /* Reply with a 404 Not Found. We are still at a standard
  10903. * HTTP request here, before the websocket handshake, so
  10904. * we can still send standard HTTP error replies. */
  10905. mg_send_http_error(conn, 404, "%s", "Not found");
  10906. return;
  10907. }
  10908. /* Step 5: The websocket connection has been accepted */
  10909. if (!send_websocket_handshake(conn, websock_key)) {
  10910. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10911. return;
  10912. }
  10913. /* Step 6: Call the ready handler */
  10914. if (is_callback_resource) {
  10915. if (ws_ready_handler != NULL) {
  10916. ws_ready_handler(conn, cbData);
  10917. }
  10918. #if defined(USE_LUA)
  10919. } else if (lua_websock) {
  10920. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10921. /* the ready handler returned false */
  10922. return;
  10923. }
  10924. #endif
  10925. }
  10926. /* Step 7: Enter the read loop */
  10927. if (is_callback_resource) {
  10928. read_websocket(conn, ws_data_handler, cbData);
  10929. #if defined(USE_LUA)
  10930. } else if (lua_websock) {
  10931. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10932. #endif
  10933. }
  10934. /* Step 8: Call the close handler */
  10935. if (ws_close_handler) {
  10936. ws_close_handler(conn, cbData);
  10937. }
  10938. }
  10939. static int
  10940. is_websocket_protocol(const struct mg_connection *conn)
  10941. {
  10942. const char *upgrade, *connection;
  10943. /* A websocket protocoll has the following HTTP headers:
  10944. *
  10945. * Connection: Upgrade
  10946. * Upgrade: Websocket
  10947. */
  10948. upgrade = mg_get_header(conn, "Upgrade");
  10949. if (upgrade == NULL) {
  10950. return 0; /* fail early, don't waste time checking other header
  10951. * fields
  10952. */
  10953. }
  10954. if (!mg_strcasestr(upgrade, "websocket")) {
  10955. return 0;
  10956. }
  10957. connection = mg_get_header(conn, "Connection");
  10958. if (connection == NULL) {
  10959. return 0;
  10960. }
  10961. if (!mg_strcasestr(connection, "upgrade")) {
  10962. return 0;
  10963. }
  10964. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10965. * "Sec-WebSocket-Version" are also required.
  10966. * Don't check them here, since even an unsupported websocket protocol
  10967. * request still IS a websocket request (in contrast to a standard HTTP
  10968. * request). It will fail later in handle_websocket_request.
  10969. */
  10970. return 1;
  10971. }
  10972. #endif /* !USE_WEBSOCKET */
  10973. static int
  10974. isbyte(int n)
  10975. {
  10976. return (n >= 0) && (n <= 255);
  10977. }
  10978. static int
  10979. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10980. {
  10981. int n, a, b, c, d, slash = 32, len = 0;
  10982. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10983. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10984. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10985. && (slash < 33)) {
  10986. len = n;
  10987. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10988. | (uint32_t)d;
  10989. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10990. }
  10991. return len;
  10992. }
  10993. static int
  10994. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10995. {
  10996. int throttle = 0;
  10997. struct vec vec, val;
  10998. uint32_t net, mask;
  10999. char mult;
  11000. double v;
  11001. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11002. mult = ',';
  11003. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11004. || (v < 0)
  11005. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11006. && (mult != ','))) {
  11007. continue;
  11008. }
  11009. v *= (lowercase(&mult) == 'k')
  11010. ? 1024
  11011. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11012. if (vec.len == 1 && vec.ptr[0] == '*') {
  11013. throttle = (int)v;
  11014. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11015. if ((remote_ip & mask) == net) {
  11016. throttle = (int)v;
  11017. }
  11018. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11019. throttle = (int)v;
  11020. }
  11021. }
  11022. return throttle;
  11023. }
  11024. static uint32_t
  11025. get_remote_ip(const struct mg_connection *conn)
  11026. {
  11027. if (!conn) {
  11028. return 0;
  11029. }
  11030. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11031. }
  11032. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11033. #include "handle_form.inl"
  11034. #if defined(MG_LEGACY_INTERFACE)
  11035. /* Implement the deprecated mg_upload function by calling the new
  11036. * mg_handle_form_request function. While mg_upload could only handle
  11037. * HTML forms sent as POST request in multipart/form-data format
  11038. * containing only file input elements, mg_handle_form_request can
  11039. * handle all form input elements and all standard request methods. */
  11040. struct mg_upload_user_data {
  11041. struct mg_connection *conn;
  11042. const char *destination_dir;
  11043. int num_uploaded_files;
  11044. };
  11045. /* Helper function for deprecated mg_upload. */
  11046. static int
  11047. mg_upload_field_found(const char *key,
  11048. const char *filename,
  11049. char *path,
  11050. size_t pathlen,
  11051. void *user_data)
  11052. {
  11053. int truncated = 0;
  11054. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11055. (void)key;
  11056. if (!filename) {
  11057. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11058. return FORM_FIELD_STORAGE_ABORT;
  11059. }
  11060. mg_snprintf(fud->conn,
  11061. &truncated,
  11062. path,
  11063. pathlen - 1,
  11064. "%s/%s",
  11065. fud->destination_dir,
  11066. filename);
  11067. if (truncated) {
  11068. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11069. return FORM_FIELD_STORAGE_ABORT;
  11070. }
  11071. return FORM_FIELD_STORAGE_STORE;
  11072. }
  11073. /* Helper function for deprecated mg_upload. */
  11074. static int
  11075. mg_upload_field_get(const char *key,
  11076. const char *value,
  11077. size_t value_size,
  11078. void *user_data)
  11079. {
  11080. /* Function should never be called */
  11081. (void)key;
  11082. (void)value;
  11083. (void)value_size;
  11084. (void)user_data;
  11085. return 0;
  11086. }
  11087. /* Helper function for deprecated mg_upload. */
  11088. static int
  11089. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11090. {
  11091. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11092. (void)file_size;
  11093. fud->num_uploaded_files++;
  11094. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11095. return 0;
  11096. }
  11097. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11098. int
  11099. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11100. {
  11101. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11102. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11103. mg_upload_field_get,
  11104. mg_upload_field_stored,
  11105. 0};
  11106. int ret;
  11107. fdh.user_data = (void *)&fud;
  11108. ret = mg_handle_form_request(conn, &fdh);
  11109. if (ret < 0) {
  11110. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11111. }
  11112. return fud.num_uploaded_files;
  11113. }
  11114. #endif
  11115. static int
  11116. get_first_ssl_listener_index(const struct mg_context *ctx)
  11117. {
  11118. unsigned int i;
  11119. int idx = -1;
  11120. if (ctx) {
  11121. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11122. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11123. }
  11124. }
  11125. return idx;
  11126. }
  11127. /* Return host (without port) */
  11128. /* Use mg_free to free the result */
  11129. static const char *
  11130. alloc_get_host(struct mg_connection *conn)
  11131. {
  11132. char buf[1025];
  11133. size_t buflen = sizeof(buf);
  11134. const char *host_header = get_header(conn->request_info.http_headers,
  11135. conn->request_info.num_headers,
  11136. "Host");
  11137. char *host;
  11138. if (host_header != NULL) {
  11139. char *pos;
  11140. /* Create a local copy of the "Host" header, since it might be
  11141. * modified here. */
  11142. mg_strlcpy(buf, host_header, buflen);
  11143. buf[buflen - 1] = '\0';
  11144. host = buf;
  11145. while (isspace(*host)) {
  11146. host++;
  11147. }
  11148. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11149. * is found. */
  11150. if (*host == '[') {
  11151. pos = strchr(host, ']');
  11152. if (!pos) {
  11153. /* Malformed hostname starts with '[', but no ']' found */
  11154. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11155. return NULL;
  11156. }
  11157. /* terminate after ']' */
  11158. pos[1] = 0;
  11159. } else {
  11160. /* Otherwise, a ':' separates hostname and port number */
  11161. pos = strchr(host, ':');
  11162. if (pos != NULL) {
  11163. *pos = '\0';
  11164. }
  11165. }
  11166. if (conn->ssl) {
  11167. /* This is a HTTPS connection, maybe we have a hostname
  11168. * from SNI (set in ssl_servername_callback). */
  11169. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11170. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11171. /* We are not using the default domain */
  11172. if (mg_strcasecmp(host, sslhost)) {
  11173. /* Mismatch between SNI domain and HTTP domain */
  11174. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11175. sslhost,
  11176. host);
  11177. return NULL;
  11178. }
  11179. }
  11180. DEBUG_TRACE("HTTPS Host: %s", host);
  11181. } else {
  11182. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11183. while (dom) {
  11184. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11185. /* Found matching domain */
  11186. DEBUG_TRACE("HTTP domain %s found",
  11187. dom->config[AUTHENTICATION_DOMAIN]);
  11188. /* TODO: Check if this is a HTTP or HTTPS domain */
  11189. conn->dom_ctx = dom;
  11190. break;
  11191. }
  11192. dom = dom->next;
  11193. }
  11194. DEBUG_TRACE("HTTP Host: %s", host);
  11195. }
  11196. } else {
  11197. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11198. host = buf;
  11199. DEBUG_TRACE("IP: %s", host);
  11200. }
  11201. return mg_strdup_ctx(host, conn->phys_ctx);
  11202. }
  11203. static void
  11204. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11205. {
  11206. char target_url[MG_BUF_LEN];
  11207. int truncated = 0;
  11208. conn->must_close = 1;
  11209. /* Send host, port, uri and (if it exists) ?query_string */
  11210. if (conn->host) {
  11211. /* Use "308 Permanent Redirect" */
  11212. int redirect_code = 308;
  11213. /* Create target URL */
  11214. mg_snprintf(
  11215. conn,
  11216. &truncated,
  11217. target_url,
  11218. sizeof(target_url),
  11219. "https://%s:%d%s%s%s",
  11220. conn->host,
  11221. #if defined(USE_IPV6)
  11222. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11223. == AF_INET6)
  11224. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11225. .lsa.sin6.sin6_port)
  11226. :
  11227. #endif
  11228. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11229. .lsa.sin.sin_port),
  11230. conn->request_info.local_uri,
  11231. (conn->request_info.query_string == NULL) ? "" : "?",
  11232. (conn->request_info.query_string == NULL)
  11233. ? ""
  11234. : conn->request_info.query_string);
  11235. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11236. * is used as buffer size) */
  11237. if (truncated) {
  11238. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11239. return;
  11240. }
  11241. /* Use redirect helper function */
  11242. mg_send_http_redirect(conn, target_url, redirect_code);
  11243. }
  11244. }
  11245. static void
  11246. handler_info_acquire(struct mg_handler_info *handler_info)
  11247. {
  11248. pthread_mutex_lock(&handler_info->refcount_mutex);
  11249. handler_info->refcount++;
  11250. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11251. }
  11252. static void
  11253. handler_info_release(struct mg_handler_info *handler_info)
  11254. {
  11255. pthread_mutex_lock(&handler_info->refcount_mutex);
  11256. handler_info->refcount--;
  11257. pthread_cond_signal(&handler_info->refcount_cond);
  11258. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11259. }
  11260. static void
  11261. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11262. {
  11263. pthread_mutex_lock(&handler_info->refcount_mutex);
  11264. while (handler_info->refcount) {
  11265. pthread_cond_wait(&handler_info->refcount_cond,
  11266. &handler_info->refcount_mutex);
  11267. }
  11268. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11269. }
  11270. static void
  11271. mg_set_handler_type(struct mg_context *phys_ctx,
  11272. struct mg_domain_context *dom_ctx,
  11273. const char *uri,
  11274. int handler_type,
  11275. int is_delete_request,
  11276. mg_request_handler handler,
  11277. struct mg_websocket_subprotocols *subprotocols,
  11278. mg_websocket_connect_handler connect_handler,
  11279. mg_websocket_ready_handler ready_handler,
  11280. mg_websocket_data_handler data_handler,
  11281. mg_websocket_close_handler close_handler,
  11282. mg_authorization_handler auth_handler,
  11283. void *cbdata)
  11284. {
  11285. struct mg_handler_info *tmp_rh, **lastref;
  11286. size_t urilen = strlen(uri);
  11287. if (handler_type == WEBSOCKET_HANDLER) {
  11288. DEBUG_ASSERT(handler == NULL);
  11289. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11290. || ready_handler != NULL || data_handler != NULL
  11291. || close_handler != NULL);
  11292. DEBUG_ASSERT(auth_handler == NULL);
  11293. if (handler != NULL) {
  11294. return;
  11295. }
  11296. if (!is_delete_request && (connect_handler == NULL)
  11297. && (ready_handler == NULL) && (data_handler == NULL)
  11298. && (close_handler == NULL)) {
  11299. return;
  11300. }
  11301. if (auth_handler != NULL) {
  11302. return;
  11303. }
  11304. } else if (handler_type == REQUEST_HANDLER) {
  11305. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11306. && data_handler == NULL && close_handler == NULL);
  11307. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11308. DEBUG_ASSERT(auth_handler == NULL);
  11309. if ((connect_handler != NULL) || (ready_handler != NULL)
  11310. || (data_handler != NULL) || (close_handler != NULL)) {
  11311. return;
  11312. }
  11313. if (!is_delete_request && (handler == NULL)) {
  11314. return;
  11315. }
  11316. if (auth_handler != NULL) {
  11317. return;
  11318. }
  11319. } else { /* AUTH_HANDLER */
  11320. DEBUG_ASSERT(handler == NULL);
  11321. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11322. && data_handler == NULL && close_handler == NULL);
  11323. DEBUG_ASSERT(auth_handler != NULL);
  11324. if (handler != NULL) {
  11325. return;
  11326. }
  11327. if ((connect_handler != NULL) || (ready_handler != NULL)
  11328. || (data_handler != NULL) || (close_handler != NULL)) {
  11329. return;
  11330. }
  11331. if (!is_delete_request && (auth_handler == NULL)) {
  11332. return;
  11333. }
  11334. }
  11335. if (!phys_ctx || !dom_ctx) {
  11336. return;
  11337. }
  11338. mg_lock_context(phys_ctx);
  11339. /* first try to find an existing handler */
  11340. lastref = &(dom_ctx->handlers);
  11341. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11342. if (tmp_rh->handler_type == handler_type) {
  11343. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11344. if (!is_delete_request) {
  11345. /* update existing handler */
  11346. if (handler_type == REQUEST_HANDLER) {
  11347. /* Wait for end of use before updating */
  11348. handler_info_wait_unused(tmp_rh);
  11349. /* Ok, the handler is no more use -> Update it */
  11350. tmp_rh->handler = handler;
  11351. } else if (handler_type == WEBSOCKET_HANDLER) {
  11352. tmp_rh->subprotocols = subprotocols;
  11353. tmp_rh->connect_handler = connect_handler;
  11354. tmp_rh->ready_handler = ready_handler;
  11355. tmp_rh->data_handler = data_handler;
  11356. tmp_rh->close_handler = close_handler;
  11357. } else { /* AUTH_HANDLER */
  11358. tmp_rh->auth_handler = auth_handler;
  11359. }
  11360. tmp_rh->cbdata = cbdata;
  11361. } else {
  11362. /* remove existing handler */
  11363. if (handler_type == REQUEST_HANDLER) {
  11364. /* Wait for end of use before removing */
  11365. handler_info_wait_unused(tmp_rh);
  11366. /* Ok, the handler is no more used -> Destroy resources
  11367. */
  11368. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11369. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11370. }
  11371. *lastref = tmp_rh->next;
  11372. mg_free(tmp_rh->uri);
  11373. mg_free(tmp_rh);
  11374. }
  11375. mg_unlock_context(phys_ctx);
  11376. return;
  11377. }
  11378. }
  11379. lastref = &(tmp_rh->next);
  11380. }
  11381. if (is_delete_request) {
  11382. /* no handler to set, this was a remove request to a non-existing
  11383. * handler */
  11384. mg_unlock_context(phys_ctx);
  11385. return;
  11386. }
  11387. tmp_rh =
  11388. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11389. 1,
  11390. phys_ctx);
  11391. if (tmp_rh == NULL) {
  11392. mg_unlock_context(phys_ctx);
  11393. mg_cry_internal(fc(phys_ctx),
  11394. "%s",
  11395. "Cannot create new request handler struct, OOM");
  11396. return;
  11397. }
  11398. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11399. if (!tmp_rh->uri) {
  11400. mg_unlock_context(phys_ctx);
  11401. mg_free(tmp_rh);
  11402. mg_cry_internal(fc(phys_ctx),
  11403. "%s",
  11404. "Cannot create new request handler struct, OOM");
  11405. return;
  11406. }
  11407. tmp_rh->uri_len = urilen;
  11408. if (handler_type == REQUEST_HANDLER) {
  11409. /* Init refcount mutex and condition */
  11410. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11411. mg_unlock_context(phys_ctx);
  11412. mg_free(tmp_rh);
  11413. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11414. return;
  11415. }
  11416. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11417. mg_unlock_context(phys_ctx);
  11418. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11419. mg_free(tmp_rh);
  11420. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11421. return;
  11422. }
  11423. tmp_rh->refcount = 0;
  11424. tmp_rh->handler = handler;
  11425. } else if (handler_type == WEBSOCKET_HANDLER) {
  11426. tmp_rh->subprotocols = subprotocols;
  11427. tmp_rh->connect_handler = connect_handler;
  11428. tmp_rh->ready_handler = ready_handler;
  11429. tmp_rh->data_handler = data_handler;
  11430. tmp_rh->close_handler = close_handler;
  11431. } else { /* AUTH_HANDLER */
  11432. tmp_rh->auth_handler = auth_handler;
  11433. }
  11434. tmp_rh->cbdata = cbdata;
  11435. tmp_rh->handler_type = handler_type;
  11436. tmp_rh->next = NULL;
  11437. *lastref = tmp_rh;
  11438. mg_unlock_context(phys_ctx);
  11439. }
  11440. void
  11441. mg_set_request_handler(struct mg_context *ctx,
  11442. const char *uri,
  11443. mg_request_handler handler,
  11444. void *cbdata)
  11445. {
  11446. mg_set_handler_type(ctx,
  11447. &(ctx->dd),
  11448. uri,
  11449. REQUEST_HANDLER,
  11450. handler == NULL,
  11451. handler,
  11452. NULL,
  11453. NULL,
  11454. NULL,
  11455. NULL,
  11456. NULL,
  11457. NULL,
  11458. cbdata);
  11459. }
  11460. void
  11461. mg_set_websocket_handler(struct mg_context *ctx,
  11462. const char *uri,
  11463. mg_websocket_connect_handler connect_handler,
  11464. mg_websocket_ready_handler ready_handler,
  11465. mg_websocket_data_handler data_handler,
  11466. mg_websocket_close_handler close_handler,
  11467. void *cbdata)
  11468. {
  11469. mg_set_websocket_handler_with_subprotocols(ctx,
  11470. uri,
  11471. NULL,
  11472. connect_handler,
  11473. ready_handler,
  11474. data_handler,
  11475. close_handler,
  11476. cbdata);
  11477. }
  11478. void
  11479. mg_set_websocket_handler_with_subprotocols(
  11480. struct mg_context *ctx,
  11481. const char *uri,
  11482. struct mg_websocket_subprotocols *subprotocols,
  11483. mg_websocket_connect_handler connect_handler,
  11484. mg_websocket_ready_handler ready_handler,
  11485. mg_websocket_data_handler data_handler,
  11486. mg_websocket_close_handler close_handler,
  11487. void *cbdata)
  11488. {
  11489. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11490. && (data_handler == NULL)
  11491. && (close_handler == NULL);
  11492. mg_set_handler_type(ctx,
  11493. &(ctx->dd),
  11494. uri,
  11495. WEBSOCKET_HANDLER,
  11496. is_delete_request,
  11497. NULL,
  11498. subprotocols,
  11499. connect_handler,
  11500. ready_handler,
  11501. data_handler,
  11502. close_handler,
  11503. NULL,
  11504. cbdata);
  11505. }
  11506. void
  11507. mg_set_auth_handler(struct mg_context *ctx,
  11508. const char *uri,
  11509. mg_request_handler handler,
  11510. void *cbdata)
  11511. {
  11512. mg_set_handler_type(ctx,
  11513. &(ctx->dd),
  11514. uri,
  11515. AUTH_HANDLER,
  11516. handler == NULL,
  11517. NULL,
  11518. NULL,
  11519. NULL,
  11520. NULL,
  11521. NULL,
  11522. NULL,
  11523. handler,
  11524. cbdata);
  11525. }
  11526. static int
  11527. get_request_handler(struct mg_connection *conn,
  11528. int handler_type,
  11529. mg_request_handler *handler,
  11530. struct mg_websocket_subprotocols **subprotocols,
  11531. mg_websocket_connect_handler *connect_handler,
  11532. mg_websocket_ready_handler *ready_handler,
  11533. mg_websocket_data_handler *data_handler,
  11534. mg_websocket_close_handler *close_handler,
  11535. mg_authorization_handler *auth_handler,
  11536. void **cbdata,
  11537. struct mg_handler_info **handler_info)
  11538. {
  11539. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11540. if (request_info) {
  11541. const char *uri = request_info->local_uri;
  11542. size_t urilen = strlen(uri);
  11543. struct mg_handler_info *tmp_rh;
  11544. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11545. return 0;
  11546. }
  11547. mg_lock_context(conn->phys_ctx);
  11548. /* first try for an exact match */
  11549. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11550. tmp_rh = tmp_rh->next) {
  11551. if (tmp_rh->handler_type == handler_type) {
  11552. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11553. if (handler_type == WEBSOCKET_HANDLER) {
  11554. *subprotocols = tmp_rh->subprotocols;
  11555. *connect_handler = tmp_rh->connect_handler;
  11556. *ready_handler = tmp_rh->ready_handler;
  11557. *data_handler = tmp_rh->data_handler;
  11558. *close_handler = tmp_rh->close_handler;
  11559. } else if (handler_type == REQUEST_HANDLER) {
  11560. *handler = tmp_rh->handler;
  11561. /* Acquire handler and give it back */
  11562. handler_info_acquire(tmp_rh);
  11563. *handler_info = tmp_rh;
  11564. } else { /* AUTH_HANDLER */
  11565. *auth_handler = tmp_rh->auth_handler;
  11566. }
  11567. *cbdata = tmp_rh->cbdata;
  11568. mg_unlock_context(conn->phys_ctx);
  11569. return 1;
  11570. }
  11571. }
  11572. }
  11573. /* next try for a partial match, we will accept uri/something */
  11574. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11575. tmp_rh = tmp_rh->next) {
  11576. if (tmp_rh->handler_type == handler_type) {
  11577. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11578. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11579. if (handler_type == WEBSOCKET_HANDLER) {
  11580. *subprotocols = tmp_rh->subprotocols;
  11581. *connect_handler = tmp_rh->connect_handler;
  11582. *ready_handler = tmp_rh->ready_handler;
  11583. *data_handler = tmp_rh->data_handler;
  11584. *close_handler = tmp_rh->close_handler;
  11585. } else if (handler_type == REQUEST_HANDLER) {
  11586. *handler = tmp_rh->handler;
  11587. /* Acquire handler and give it back */
  11588. handler_info_acquire(tmp_rh);
  11589. *handler_info = tmp_rh;
  11590. } else { /* AUTH_HANDLER */
  11591. *auth_handler = tmp_rh->auth_handler;
  11592. }
  11593. *cbdata = tmp_rh->cbdata;
  11594. mg_unlock_context(conn->phys_ctx);
  11595. return 1;
  11596. }
  11597. }
  11598. }
  11599. /* finally try for pattern match */
  11600. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11601. tmp_rh = tmp_rh->next) {
  11602. if (tmp_rh->handler_type == handler_type) {
  11603. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11604. if (handler_type == WEBSOCKET_HANDLER) {
  11605. *subprotocols = tmp_rh->subprotocols;
  11606. *connect_handler = tmp_rh->connect_handler;
  11607. *ready_handler = tmp_rh->ready_handler;
  11608. *data_handler = tmp_rh->data_handler;
  11609. *close_handler = tmp_rh->close_handler;
  11610. } else if (handler_type == REQUEST_HANDLER) {
  11611. *handler = tmp_rh->handler;
  11612. /* Acquire handler and give it back */
  11613. handler_info_acquire(tmp_rh);
  11614. *handler_info = tmp_rh;
  11615. } else { /* AUTH_HANDLER */
  11616. *auth_handler = tmp_rh->auth_handler;
  11617. }
  11618. *cbdata = tmp_rh->cbdata;
  11619. mg_unlock_context(conn->phys_ctx);
  11620. return 1;
  11621. }
  11622. }
  11623. }
  11624. mg_unlock_context(conn->phys_ctx);
  11625. }
  11626. return 0; /* none found */
  11627. }
  11628. /* Check if the script file is in a path, allowed for script files.
  11629. * This can be used if uploading files is possible not only for the server
  11630. * admin, and the upload mechanism does not check the file extension.
  11631. */
  11632. static int
  11633. is_in_script_path(const struct mg_connection *conn, const char *path)
  11634. {
  11635. /* TODO (Feature): Add config value for allowed script path.
  11636. * Default: All allowed. */
  11637. (void)conn;
  11638. (void)path;
  11639. return 1;
  11640. }
  11641. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11642. static int
  11643. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11644. void *cbdata)
  11645. {
  11646. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11647. if (pcallbacks->websocket_connect) {
  11648. return pcallbacks->websocket_connect(conn);
  11649. }
  11650. /* No handler set - assume "OK" */
  11651. return 0;
  11652. }
  11653. static void
  11654. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11655. {
  11656. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11657. if (pcallbacks->websocket_ready) {
  11658. pcallbacks->websocket_ready(conn);
  11659. }
  11660. }
  11661. static int
  11662. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11663. int bits,
  11664. char *data,
  11665. size_t len,
  11666. void *cbdata)
  11667. {
  11668. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11669. if (pcallbacks->websocket_data) {
  11670. return pcallbacks->websocket_data(conn, bits, data, len);
  11671. }
  11672. /* No handler set - assume "OK" */
  11673. return 1;
  11674. }
  11675. #endif
  11676. /* This is the heart of the Civetweb's logic.
  11677. * This function is called when the request is read, parsed and validated,
  11678. * and Civetweb must decide what action to take: serve a file, or
  11679. * a directory, or call embedded function, etcetera. */
  11680. static void
  11681. handle_request(struct mg_connection *conn)
  11682. {
  11683. struct mg_request_info *ri = &conn->request_info;
  11684. char path[PATH_MAX];
  11685. int uri_len, ssl_index;
  11686. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11687. is_put_or_delete_request = 0, is_callback_resource = 0;
  11688. int i;
  11689. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11690. mg_request_handler callback_handler = NULL;
  11691. struct mg_handler_info *handler_info = NULL;
  11692. struct mg_websocket_subprotocols *subprotocols;
  11693. mg_websocket_connect_handler ws_connect_handler = NULL;
  11694. mg_websocket_ready_handler ws_ready_handler = NULL;
  11695. mg_websocket_data_handler ws_data_handler = NULL;
  11696. mg_websocket_close_handler ws_close_handler = NULL;
  11697. void *callback_data = NULL;
  11698. mg_authorization_handler auth_handler = NULL;
  11699. void *auth_callback_data = NULL;
  11700. int handler_type;
  11701. time_t curtime = time(NULL);
  11702. char date[64];
  11703. path[0] = 0;
  11704. /* 1. get the request url */
  11705. /* 1.1. split into url and query string */
  11706. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11707. != NULL) {
  11708. *((char *)conn->request_info.query_string++) = '\0';
  11709. }
  11710. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11711. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11712. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11713. if (ssl_index >= 0) {
  11714. redirect_to_https_port(conn, ssl_index);
  11715. } else {
  11716. /* A http to https forward port has been specified,
  11717. * but no https port to forward to. */
  11718. mg_send_http_error(conn,
  11719. 503,
  11720. "%s",
  11721. "Error: SSL forward not configured properly");
  11722. mg_cry_internal(conn,
  11723. "%s",
  11724. "Can not redirect to SSL, no SSL port available");
  11725. }
  11726. return;
  11727. }
  11728. uri_len = (int)strlen(ri->local_uri);
  11729. /* 1.3. decode url (if config says so) */
  11730. if (should_decode_url(conn)) {
  11731. mg_url_decode(
  11732. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11733. }
  11734. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11735. * not possible */
  11736. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11737. /* step 1. completed, the url is known now */
  11738. uri_len = (int)strlen(ri->local_uri);
  11739. DEBUG_TRACE("URL: %s", ri->local_uri);
  11740. /* 2. if this ip has limited speed, set it for this connection */
  11741. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11742. get_remote_ip(conn),
  11743. ri->local_uri);
  11744. /* 3. call a "handle everything" callback, if registered */
  11745. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11746. /* Note that since V1.7 the "begin_request" function is called
  11747. * before an authorization check. If an authorization check is
  11748. * required, use a request_handler instead. */
  11749. i = conn->phys_ctx->callbacks.begin_request(conn);
  11750. if (i > 0) {
  11751. /* callback already processed the request. Store the
  11752. return value as a status code for the access log. */
  11753. conn->status_code = i;
  11754. discard_unread_request_data(conn);
  11755. return;
  11756. } else if (i == 0) {
  11757. /* civetweb should process the request */
  11758. } else {
  11759. /* unspecified - may change with the next version */
  11760. return;
  11761. }
  11762. }
  11763. /* request not yet handled by a handler or redirect, so the request
  11764. * is processed here */
  11765. /* 4. Check for CORS preflight requests and handle them (if configured).
  11766. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11767. */
  11768. if (!strcmp(ri->request_method, "OPTIONS")) {
  11769. /* Send a response to CORS preflights only if
  11770. * access_control_allow_methods is not NULL and not an empty string.
  11771. * In this case, scripts can still handle CORS. */
  11772. const char *cors_meth_cfg =
  11773. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11774. const char *cors_orig_cfg =
  11775. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11776. const char *cors_origin =
  11777. get_header(ri->http_headers, ri->num_headers, "Origin");
  11778. const char *cors_acrm = get_header(ri->http_headers,
  11779. ri->num_headers,
  11780. "Access-Control-Request-Method");
  11781. /* Todo: check if cors_origin is in cors_orig_cfg.
  11782. * Or, let the client check this. */
  11783. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11784. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11785. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11786. /* This is a valid CORS preflight, and the server is configured
  11787. * to
  11788. * handle it automatically. */
  11789. const char *cors_acrh =
  11790. get_header(ri->http_headers,
  11791. ri->num_headers,
  11792. "Access-Control-Request-Headers");
  11793. gmt_time_string(date, sizeof(date), &curtime);
  11794. mg_printf(conn,
  11795. "HTTP/1.1 200 OK\r\n"
  11796. "Date: %s\r\n"
  11797. "Access-Control-Allow-Origin: %s\r\n"
  11798. "Access-Control-Allow-Methods: %s\r\n"
  11799. "Content-Length: 0\r\n"
  11800. "Connection: %s\r\n",
  11801. date,
  11802. cors_orig_cfg,
  11803. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11804. suggest_connection_header(conn));
  11805. if (cors_acrh != NULL) {
  11806. /* CORS request is asking for additional headers */
  11807. const char *cors_hdr_cfg =
  11808. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11809. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11810. /* Allow only if access_control_allow_headers is
  11811. * not NULL and not an empty string. If this
  11812. * configuration is set to *, allow everything.
  11813. * Otherwise this configuration must be a list
  11814. * of allowed HTTP header names. */
  11815. mg_printf(conn,
  11816. "Access-Control-Allow-Headers: %s\r\n",
  11817. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11818. : cors_hdr_cfg));
  11819. }
  11820. }
  11821. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11822. mg_printf(conn, "\r\n");
  11823. return;
  11824. }
  11825. }
  11826. /* 5. interpret the url to find out how the request must be handled
  11827. */
  11828. /* 5.1. first test, if the request targets the regular http(s)://
  11829. * protocol namespace or the websocket ws(s):// protocol namespace.
  11830. */
  11831. is_websocket_request = is_websocket_protocol(conn);
  11832. #if defined(USE_WEBSOCKET)
  11833. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11834. #else
  11835. handler_type = REQUEST_HANDLER;
  11836. #endif /* defined(USE_WEBSOCKET) */
  11837. /* 5.2. check if the request will be handled by a callback */
  11838. if (get_request_handler(conn,
  11839. handler_type,
  11840. &callback_handler,
  11841. &subprotocols,
  11842. &ws_connect_handler,
  11843. &ws_ready_handler,
  11844. &ws_data_handler,
  11845. &ws_close_handler,
  11846. NULL,
  11847. &callback_data,
  11848. &handler_info)) {
  11849. /* 5.2.1. A callback will handle this request. All requests
  11850. * handled
  11851. * by a callback have to be considered as requests to a script
  11852. * resource. */
  11853. is_callback_resource = 1;
  11854. is_script_resource = 1;
  11855. is_put_or_delete_request = is_put_or_delete_method(conn);
  11856. } else {
  11857. no_callback_resource:
  11858. /* 5.2.2. No callback is responsible for this request. The URI
  11859. * addresses a file based resource (static content or Lua/cgi
  11860. * scripts in the file system). */
  11861. is_callback_resource = 0;
  11862. interpret_uri(conn,
  11863. path,
  11864. sizeof(path),
  11865. &file.stat,
  11866. &is_found,
  11867. &is_script_resource,
  11868. &is_websocket_request,
  11869. &is_put_or_delete_request);
  11870. }
  11871. /* 6. authorization check */
  11872. /* 6.1. a custom authorization handler is installed */
  11873. if (get_request_handler(conn,
  11874. AUTH_HANDLER,
  11875. NULL,
  11876. NULL,
  11877. NULL,
  11878. NULL,
  11879. NULL,
  11880. NULL,
  11881. &auth_handler,
  11882. &auth_callback_data,
  11883. NULL)) {
  11884. if (!auth_handler(conn, auth_callback_data)) {
  11885. return;
  11886. }
  11887. } else if (is_put_or_delete_request && !is_script_resource
  11888. && !is_callback_resource) {
  11889. /* 6.2. this request is a PUT/DELETE to a real file */
  11890. /* 6.2.1. thus, the server must have real files */
  11891. #if defined(NO_FILES)
  11892. if (1) {
  11893. #else
  11894. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11895. #endif
  11896. /* This server does not have any real files, thus the
  11897. * PUT/DELETE methods are not valid. */
  11898. mg_send_http_error(conn,
  11899. 405,
  11900. "%s method not allowed",
  11901. conn->request_info.request_method);
  11902. return;
  11903. }
  11904. #if !defined(NO_FILES)
  11905. /* 6.2.2. Check if put authorization for static files is
  11906. * available.
  11907. */
  11908. if (!is_authorized_for_put(conn)) {
  11909. send_authorization_request(conn, NULL);
  11910. return;
  11911. }
  11912. #endif
  11913. } else {
  11914. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11915. * or it is a PUT or DELETE request to a resource that does not
  11916. * correspond to a file. Check authorization. */
  11917. if (!check_authorization(conn, path)) {
  11918. send_authorization_request(conn, NULL);
  11919. return;
  11920. }
  11921. }
  11922. /* request is authorized or does not need authorization */
  11923. /* 7. check if there are request handlers for this uri */
  11924. if (is_callback_resource) {
  11925. if (!is_websocket_request) {
  11926. i = callback_handler(conn, callback_data);
  11927. /* Callback handler will not be used anymore. Release it */
  11928. handler_info_release(handler_info);
  11929. if (i > 0) {
  11930. /* Do nothing, callback has served the request. Store
  11931. * then return value as status code for the log and discard
  11932. * all data from the client not used by the callback. */
  11933. conn->status_code = i;
  11934. discard_unread_request_data(conn);
  11935. } else {
  11936. /* The handler did NOT handle the request. */
  11937. /* Some proper reactions would be:
  11938. * a) close the connections without sending anything
  11939. * b) send a 404 not found
  11940. * c) try if there is a file matching the URI
  11941. * It would be possible to do a, b or c in the callback
  11942. * implementation, and return 1 - we cannot do anything
  11943. * here, that is not possible in the callback.
  11944. *
  11945. * TODO: What would be the best reaction here?
  11946. * (Note: The reaction may change, if there is a better
  11947. *idea.)
  11948. */
  11949. /* For the moment, use option c: We look for a proper file,
  11950. * but since a file request is not always a script resource,
  11951. * the authorization check might be different. */
  11952. interpret_uri(conn,
  11953. path,
  11954. sizeof(path),
  11955. &file.stat,
  11956. &is_found,
  11957. &is_script_resource,
  11958. &is_websocket_request,
  11959. &is_put_or_delete_request);
  11960. callback_handler = NULL;
  11961. /* Here we are at a dead end:
  11962. * According to URI matching, a callback should be
  11963. * responsible for handling the request,
  11964. * we called it, but the callback declared itself
  11965. * not responsible.
  11966. * We use a goto here, to get out of this dead end,
  11967. * and continue with the default handling.
  11968. * A goto here is simpler and better to understand
  11969. * than some curious loop. */
  11970. goto no_callback_resource;
  11971. }
  11972. } else {
  11973. #if defined(USE_WEBSOCKET)
  11974. handle_websocket_request(conn,
  11975. path,
  11976. is_callback_resource,
  11977. subprotocols,
  11978. ws_connect_handler,
  11979. ws_ready_handler,
  11980. ws_data_handler,
  11981. ws_close_handler,
  11982. callback_data);
  11983. #endif
  11984. }
  11985. return;
  11986. }
  11987. /* 8. handle websocket requests */
  11988. #if defined(USE_WEBSOCKET)
  11989. if (is_websocket_request) {
  11990. if (is_script_resource) {
  11991. if (is_in_script_path(conn, path)) {
  11992. /* Websocket Lua script */
  11993. handle_websocket_request(conn,
  11994. path,
  11995. 0 /* Lua Script */,
  11996. NULL,
  11997. NULL,
  11998. NULL,
  11999. NULL,
  12000. NULL,
  12001. conn->phys_ctx->user_data);
  12002. } else {
  12003. /* Script was in an illegal path */
  12004. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12005. }
  12006. } else {
  12007. #if defined(MG_LEGACY_INTERFACE)
  12008. handle_websocket_request(
  12009. conn,
  12010. path,
  12011. !is_script_resource /* could be deprecated global callback */,
  12012. NULL,
  12013. deprecated_websocket_connect_wrapper,
  12014. deprecated_websocket_ready_wrapper,
  12015. deprecated_websocket_data_wrapper,
  12016. NULL,
  12017. conn->phys_ctx->user_data);
  12018. #else
  12019. mg_send_http_error(conn, 404, "%s", "Not found");
  12020. #endif
  12021. }
  12022. return;
  12023. } else
  12024. #endif
  12025. #if defined(NO_FILES)
  12026. /* 9a. In case the server uses only callbacks, this uri is
  12027. * unknown.
  12028. * Then, all request handling ends here. */
  12029. mg_send_http_error(conn, 404, "%s", "Not Found");
  12030. #else
  12031. /* 9b. This request is either for a static file or resource handled
  12032. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12033. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12034. mg_send_http_error(conn, 404, "%s", "Not Found");
  12035. return;
  12036. }
  12037. /* 10. Request is handled by a script */
  12038. if (is_script_resource) {
  12039. handle_file_based_request(conn, path, &file);
  12040. return;
  12041. }
  12042. /* 11. Handle put/delete/mkcol requests */
  12043. if (is_put_or_delete_request) {
  12044. /* 11.1. PUT method */
  12045. if (!strcmp(ri->request_method, "PUT")) {
  12046. put_file(conn, path);
  12047. return;
  12048. }
  12049. /* 11.2. DELETE method */
  12050. if (!strcmp(ri->request_method, "DELETE")) {
  12051. delete_file(conn, path);
  12052. return;
  12053. }
  12054. /* 11.3. MKCOL method */
  12055. if (!strcmp(ri->request_method, "MKCOL")) {
  12056. mkcol(conn, path);
  12057. return;
  12058. }
  12059. /* 11.4. PATCH method
  12060. * This method is not supported for static resources,
  12061. * only for scripts (Lua, CGI) and callbacks. */
  12062. mg_send_http_error(conn,
  12063. 405,
  12064. "%s method not allowed",
  12065. conn->request_info.request_method);
  12066. return;
  12067. }
  12068. /* 11. File does not exist, or it was configured that it should be
  12069. * hidden */
  12070. if (!is_found || (must_hide_file(conn, path))) {
  12071. mg_send_http_error(conn, 404, "%s", "Not found");
  12072. return;
  12073. }
  12074. /* 12. Directory uris should end with a slash */
  12075. if (file.stat.is_directory && (uri_len > 0)
  12076. && (ri->local_uri[uri_len - 1] != '/')) {
  12077. gmt_time_string(date, sizeof(date), &curtime);
  12078. mg_printf(conn,
  12079. "HTTP/1.1 301 Moved Permanently\r\n"
  12080. "Location: %s/\r\n"
  12081. "Date: %s\r\n"
  12082. /* "Cache-Control: private\r\n" (= default) */
  12083. "Content-Length: 0\r\n"
  12084. "Connection: %s\r\n",
  12085. ri->request_uri,
  12086. date,
  12087. suggest_connection_header(conn));
  12088. send_additional_header(conn);
  12089. mg_printf(conn, "\r\n");
  12090. return;
  12091. }
  12092. /* 13. Handle other methods than GET/HEAD */
  12093. /* 13.1. Handle PROPFIND */
  12094. if (!strcmp(ri->request_method, "PROPFIND")) {
  12095. handle_propfind(conn, path, &file.stat);
  12096. return;
  12097. }
  12098. /* 13.2. Handle OPTIONS for files */
  12099. if (!strcmp(ri->request_method, "OPTIONS")) {
  12100. /* This standard handler is only used for real files.
  12101. * Scripts should support the OPTIONS method themselves, to allow a
  12102. * maximum flexibility.
  12103. * Lua and CGI scripts may fully support CORS this way (including
  12104. * preflights). */
  12105. send_options(conn);
  12106. return;
  12107. }
  12108. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12109. if ((0 != strcmp(ri->request_method, "GET"))
  12110. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12111. mg_send_http_error(conn,
  12112. 405,
  12113. "%s method not allowed",
  12114. conn->request_info.request_method);
  12115. return;
  12116. }
  12117. /* 14. directories */
  12118. if (file.stat.is_directory) {
  12119. /* Substitute files have already been handled above. */
  12120. /* Here we can either generate and send a directory listing,
  12121. * or send an "access denied" error. */
  12122. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12123. "yes")) {
  12124. handle_directory_request(conn, path);
  12125. } else {
  12126. mg_send_http_error(conn,
  12127. 403,
  12128. "%s",
  12129. "Error: Directory listing denied");
  12130. }
  12131. return;
  12132. }
  12133. /* 15. read a normal file with GET or HEAD */
  12134. handle_file_based_request(conn, path, &file);
  12135. #endif /* !defined(NO_FILES) */
  12136. }
  12137. static void
  12138. handle_file_based_request(struct mg_connection *conn,
  12139. const char *path,
  12140. struct mg_file *file)
  12141. {
  12142. if (!conn || !conn->dom_ctx) {
  12143. return;
  12144. }
  12145. if (0) {
  12146. #if defined(USE_LUA)
  12147. } else if (match_prefix(
  12148. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12149. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12150. path)
  12151. > 0) {
  12152. if (is_in_script_path(conn, path)) {
  12153. /* Lua server page: an SSI like page containing mostly plain
  12154. * html
  12155. * code
  12156. * plus some tags with server generated contents. */
  12157. handle_lsp_request(conn, path, file, NULL);
  12158. } else {
  12159. /* Script was in an illegal path */
  12160. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12161. }
  12162. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12163. strlen(
  12164. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12165. path)
  12166. > 0) {
  12167. if (is_in_script_path(conn, path)) {
  12168. /* Lua in-server module script: a CGI like script used to
  12169. * generate
  12170. * the
  12171. * entire reply. */
  12172. mg_exec_lua_script(conn, path, NULL);
  12173. } else {
  12174. /* Script was in an illegal path */
  12175. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12176. }
  12177. #endif
  12178. #if defined(USE_DUKTAPE)
  12179. } else if (match_prefix(
  12180. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12181. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12182. path)
  12183. > 0) {
  12184. if (is_in_script_path(conn, path)) {
  12185. /* Call duktape to generate the page */
  12186. mg_exec_duktape_script(conn, path);
  12187. } else {
  12188. /* Script was in an illegal path */
  12189. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12190. }
  12191. #endif
  12192. #if !defined(NO_CGI)
  12193. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12194. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12195. path)
  12196. > 0) {
  12197. if (is_in_script_path(conn, path)) {
  12198. /* CGI scripts may support all HTTP methods */
  12199. handle_cgi_request(conn, path);
  12200. } else {
  12201. /* Script was in an illegal path */
  12202. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12203. }
  12204. #endif /* !NO_CGI */
  12205. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12206. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12207. path)
  12208. > 0) {
  12209. if (is_in_script_path(conn, path)) {
  12210. handle_ssi_file_request(conn, path, file);
  12211. } else {
  12212. /* Script was in an illegal path */
  12213. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12214. }
  12215. #if !defined(NO_CACHING)
  12216. } else if ((!conn->in_error_handler)
  12217. && is_not_modified(conn, &file->stat)) {
  12218. /* Send 304 "Not Modified" - this must not send any body data */
  12219. handle_not_modified_static_file_request(conn, file);
  12220. #endif /* !NO_CACHING */
  12221. } else {
  12222. handle_static_file_request(conn, path, file, NULL, NULL);
  12223. }
  12224. }
  12225. static void
  12226. close_all_listening_sockets(struct mg_context *ctx)
  12227. {
  12228. unsigned int i;
  12229. if (!ctx) {
  12230. return;
  12231. }
  12232. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12233. closesocket(ctx->listening_sockets[i].sock);
  12234. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12235. }
  12236. mg_free(ctx->listening_sockets);
  12237. ctx->listening_sockets = NULL;
  12238. mg_free(ctx->listening_socket_fds);
  12239. ctx->listening_socket_fds = NULL;
  12240. }
  12241. /* Valid listening port specification is: [ip_address:]port[s]
  12242. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12243. * Examples for IPv6: [::]:80, [::1]:80,
  12244. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12245. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12246. * In order to bind to both, IPv4 and IPv6, you can either add
  12247. * both ports using 8080,[::]:8080, or the short form +8080.
  12248. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12249. * one only accepting IPv4 the other only IPv6. +8080 creates
  12250. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12251. * environment, they might work differently, or might not work
  12252. * at all - it must be tested what options work best in the
  12253. * relevant network environment.
  12254. */
  12255. static int
  12256. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12257. {
  12258. unsigned int a, b, c, d, port;
  12259. int ch, len;
  12260. const char *cb;
  12261. #if defined(USE_IPV6)
  12262. char buf[100] = {0};
  12263. #endif
  12264. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12265. * Also, all-zeroes in the socket address means binding to all addresses
  12266. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12267. memset(so, 0, sizeof(*so));
  12268. so->lsa.sin.sin_family = AF_INET;
  12269. *ip_version = 0;
  12270. /* Initialize port and len as invalid. */
  12271. port = 0;
  12272. len = 0;
  12273. /* Test for different ways to format this string */
  12274. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12275. == 5) {
  12276. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12277. so->lsa.sin.sin_addr.s_addr =
  12278. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12279. so->lsa.sin.sin_port = htons((uint16_t)port);
  12280. *ip_version = 4;
  12281. #if defined(USE_IPV6)
  12282. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12283. && mg_inet_pton(
  12284. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12285. /* IPv6 address, examples: see above */
  12286. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12287. */
  12288. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12289. *ip_version = 6;
  12290. #endif
  12291. } else if ((vec->ptr[0] == '+')
  12292. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12293. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12294. /* Add 1 to len for the + character we skipped before */
  12295. len++;
  12296. #if defined(USE_IPV6)
  12297. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12298. so->lsa.sin6.sin6_family = AF_INET6;
  12299. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12300. *ip_version = 4 + 6;
  12301. #else
  12302. /* Bind to IPv4 only, since IPv6 is not built in. */
  12303. so->lsa.sin.sin_port = htons((uint16_t)port);
  12304. *ip_version = 4;
  12305. #endif
  12306. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12307. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12308. so->lsa.sin.sin_port = htons((uint16_t)port);
  12309. *ip_version = 4;
  12310. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12311. /* String could be a hostname. This check algotithm
  12312. * will only work for RFC 952 compliant hostnames,
  12313. * starting with a letter, containing only letters,
  12314. * digits and hyphen ('-'). Newer specs may allow
  12315. * more, but this is not guaranteed here, since it
  12316. * may interfere with rules for port option lists. */
  12317. /* According to RFC 1035, hostnames are restricted to 255 characters
  12318. * in total (63 between two dots). */
  12319. char hostname[256];
  12320. size_t hostnlen = (size_t)(cb - vec->ptr);
  12321. if (hostnlen >= sizeof(hostname)) {
  12322. /* This would be invalid in any case */
  12323. *ip_version = 0;
  12324. return 0;
  12325. }
  12326. memcpy(hostname, vec->ptr, hostnlen);
  12327. hostname[hostnlen] = 0;
  12328. if (mg_inet_pton(
  12329. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12330. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12331. *ip_version = 4;
  12332. so->lsa.sin.sin_family = AF_INET;
  12333. so->lsa.sin.sin_port = htons((uint16_t)port);
  12334. len += (int)(hostnlen + 1);
  12335. } else {
  12336. port = 0;
  12337. len = 0;
  12338. }
  12339. #if defined(USE_IPV6)
  12340. } else if (mg_inet_pton(AF_INET6,
  12341. vec->ptr,
  12342. &so->lsa.sin6,
  12343. sizeof(so->lsa.sin6))) {
  12344. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12345. *ip_version = 6;
  12346. so->lsa.sin6.sin6_family = AF_INET6;
  12347. so->lsa.sin.sin_port = htons((uint16_t)port);
  12348. len += (int)(hostnlen + 1);
  12349. } else {
  12350. port = 0;
  12351. len = 0;
  12352. }
  12353. #endif
  12354. }
  12355. } else {
  12356. /* Parsing failure. */
  12357. }
  12358. /* sscanf and the option splitting code ensure the following condition
  12359. */
  12360. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12361. *ip_version = 0;
  12362. return 0;
  12363. }
  12364. ch = vec->ptr[len]; /* Next character after the port number */
  12365. so->is_ssl = (ch == 's');
  12366. so->ssl_redir = (ch == 'r');
  12367. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12368. if (is_valid_port(port)
  12369. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12370. return 1;
  12371. }
  12372. /* Reset ip_version to 0 if there is an error */
  12373. *ip_version = 0;
  12374. return 0;
  12375. }
  12376. /* Is there any SSL port in use? */
  12377. static int
  12378. is_ssl_port_used(const char *ports)
  12379. {
  12380. if (ports) {
  12381. /* There are several different allowed syntax variants:
  12382. * - "80" for a single port using every network interface
  12383. * - "localhost:80" for a single port using only localhost
  12384. * - "80,localhost:8080" for two ports, one bound to localhost
  12385. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12386. * to IPv4 localhost, one to IPv6 localhost
  12387. * - "+80" use port 80 for IPv4 and IPv6
  12388. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12389. * for both: IPv4 and IPv4
  12390. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12391. * additionally port 8080 bound to localhost connections
  12392. *
  12393. * If we just look for 's' anywhere in the string, "localhost:80"
  12394. * will be detected as SSL (false positive).
  12395. * Looking for 's' after a digit may cause false positives in
  12396. * "my24service:8080".
  12397. * Looking from 's' backward if there are only ':' and numbers
  12398. * before will not work for "24service:8080" (non SSL, port 8080)
  12399. * or "24s" (SSL, port 24).
  12400. *
  12401. * Remark: Initially hostnames were not allowed to start with a
  12402. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12403. * Section 2.1).
  12404. *
  12405. * To get this correct, the entire string must be parsed as a whole,
  12406. * reading it as a list element for element and parsing with an
  12407. * algorithm equivalent to parse_port_string.
  12408. *
  12409. * In fact, we use local interface names here, not arbitrary hostnames,
  12410. * so in most cases the only name will be "localhost".
  12411. *
  12412. * So, for now, we use this simple algorithm, that may still return
  12413. * a false positive in bizarre cases.
  12414. */
  12415. int i;
  12416. int portslen = (int)strlen(ports);
  12417. char prevIsNumber = 0;
  12418. for (i = 0; i < portslen; i++) {
  12419. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12420. return 1;
  12421. }
  12422. if (ports[i] >= '0' && ports[i] <= '9') {
  12423. prevIsNumber = 1;
  12424. } else {
  12425. prevIsNumber = 0;
  12426. }
  12427. }
  12428. }
  12429. return 0;
  12430. }
  12431. static int
  12432. set_ports_option(struct mg_context *phys_ctx)
  12433. {
  12434. const char *list;
  12435. int on = 1;
  12436. #if defined(USE_IPV6)
  12437. int off = 0;
  12438. #endif
  12439. struct vec vec;
  12440. struct socket so, *ptr;
  12441. struct pollfd *pfd;
  12442. union usa usa;
  12443. socklen_t len;
  12444. int ip_version;
  12445. int portsTotal = 0;
  12446. int portsOk = 0;
  12447. if (!phys_ctx) {
  12448. return 0;
  12449. }
  12450. memset(&so, 0, sizeof(so));
  12451. memset(&usa, 0, sizeof(usa));
  12452. len = sizeof(usa);
  12453. list = phys_ctx->dd.config[LISTENING_PORTS];
  12454. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12455. portsTotal++;
  12456. if (!parse_port_string(&vec, &so, &ip_version)) {
  12457. mg_cry_internal(
  12458. fc(phys_ctx),
  12459. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12460. (int)vec.len,
  12461. vec.ptr,
  12462. portsTotal,
  12463. "[IP_ADDRESS:]PORT[s|r]");
  12464. continue;
  12465. }
  12466. #if !defined(NO_SSL)
  12467. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12468. mg_cry_internal(fc(phys_ctx),
  12469. "Cannot add SSL socket (entry %i)",
  12470. portsTotal);
  12471. continue;
  12472. }
  12473. #endif
  12474. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12475. == INVALID_SOCKET) {
  12476. mg_cry_internal(fc(phys_ctx),
  12477. "cannot create socket (entry %i)",
  12478. portsTotal);
  12479. continue;
  12480. }
  12481. #if defined(_WIN32)
  12482. /* Windows SO_REUSEADDR lets many procs binds to a
  12483. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12484. * if someone already has the socket -- DTL */
  12485. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12486. * Windows might need a few seconds before
  12487. * the same port can be used again in the
  12488. * same process, so a short Sleep may be
  12489. * required between mg_stop and mg_start.
  12490. */
  12491. if (setsockopt(so.sock,
  12492. SOL_SOCKET,
  12493. SO_EXCLUSIVEADDRUSE,
  12494. (SOCK_OPT_TYPE)&on,
  12495. sizeof(on))
  12496. != 0) {
  12497. /* Set reuse option, but don't abort on errors. */
  12498. mg_cry_internal(
  12499. fc(phys_ctx),
  12500. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12501. portsTotal);
  12502. }
  12503. #else
  12504. if (setsockopt(so.sock,
  12505. SOL_SOCKET,
  12506. SO_REUSEADDR,
  12507. (SOCK_OPT_TYPE)&on,
  12508. sizeof(on))
  12509. != 0) {
  12510. /* Set reuse option, but don't abort on errors. */
  12511. mg_cry_internal(fc(phys_ctx),
  12512. "cannot set socket option SO_REUSEADDR (entry %i)",
  12513. portsTotal);
  12514. }
  12515. #endif
  12516. if (ip_version > 4) {
  12517. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12518. #if defined(USE_IPV6)
  12519. if (ip_version > 6) {
  12520. if (so.lsa.sa.sa_family == AF_INET6
  12521. && setsockopt(so.sock,
  12522. IPPROTO_IPV6,
  12523. IPV6_V6ONLY,
  12524. (void *)&off,
  12525. sizeof(off))
  12526. != 0) {
  12527. /* Set IPv6 only option, but don't abort on errors. */
  12528. mg_cry_internal(
  12529. fc(phys_ctx),
  12530. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12531. portsTotal);
  12532. }
  12533. } else {
  12534. if (so.lsa.sa.sa_family == AF_INET6
  12535. && setsockopt(so.sock,
  12536. IPPROTO_IPV6,
  12537. IPV6_V6ONLY,
  12538. (void *)&on,
  12539. sizeof(on))
  12540. != 0) {
  12541. /* Set IPv6 only option, but don't abort on errors. */
  12542. mg_cry_internal(
  12543. fc(phys_ctx),
  12544. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12545. portsTotal);
  12546. }
  12547. }
  12548. #else
  12549. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12550. closesocket(so.sock);
  12551. so.sock = INVALID_SOCKET;
  12552. continue;
  12553. #endif
  12554. }
  12555. if (so.lsa.sa.sa_family == AF_INET) {
  12556. len = sizeof(so.lsa.sin);
  12557. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12558. mg_cry_internal(fc(phys_ctx),
  12559. "cannot bind to %.*s: %d (%s)",
  12560. (int)vec.len,
  12561. vec.ptr,
  12562. (int)ERRNO,
  12563. strerror(errno));
  12564. closesocket(so.sock);
  12565. so.sock = INVALID_SOCKET;
  12566. continue;
  12567. }
  12568. }
  12569. #if defined(USE_IPV6)
  12570. else if (so.lsa.sa.sa_family == AF_INET6) {
  12571. len = sizeof(so.lsa.sin6);
  12572. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12573. mg_cry_internal(fc(phys_ctx),
  12574. "cannot bind to IPv6 %.*s: %d (%s)",
  12575. (int)vec.len,
  12576. vec.ptr,
  12577. (int)ERRNO,
  12578. strerror(errno));
  12579. closesocket(so.sock);
  12580. so.sock = INVALID_SOCKET;
  12581. continue;
  12582. }
  12583. }
  12584. #endif
  12585. else {
  12586. mg_cry_internal(
  12587. fc(phys_ctx),
  12588. "cannot bind: address family not supported (entry %i)",
  12589. portsTotal);
  12590. closesocket(so.sock);
  12591. so.sock = INVALID_SOCKET;
  12592. continue;
  12593. }
  12594. if (listen(so.sock, SOMAXCONN) != 0) {
  12595. mg_cry_internal(fc(phys_ctx),
  12596. "cannot listen to %.*s: %d (%s)",
  12597. (int)vec.len,
  12598. vec.ptr,
  12599. (int)ERRNO,
  12600. strerror(errno));
  12601. closesocket(so.sock);
  12602. so.sock = INVALID_SOCKET;
  12603. continue;
  12604. }
  12605. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12606. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12607. int err = (int)ERRNO;
  12608. mg_cry_internal(fc(phys_ctx),
  12609. "call to getsockname failed %.*s: %d (%s)",
  12610. (int)vec.len,
  12611. vec.ptr,
  12612. err,
  12613. strerror(errno));
  12614. closesocket(so.sock);
  12615. so.sock = INVALID_SOCKET;
  12616. continue;
  12617. }
  12618. /* Update lsa port in case of random free ports */
  12619. #if defined(USE_IPV6)
  12620. if (so.lsa.sa.sa_family == AF_INET6) {
  12621. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12622. } else
  12623. #endif
  12624. {
  12625. so.lsa.sin.sin_port = usa.sin.sin_port;
  12626. }
  12627. if ((ptr = (struct socket *)
  12628. mg_realloc_ctx(phys_ctx->listening_sockets,
  12629. (phys_ctx->num_listening_sockets + 1)
  12630. * sizeof(phys_ctx->listening_sockets[0]),
  12631. phys_ctx))
  12632. == NULL) {
  12633. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12634. closesocket(so.sock);
  12635. so.sock = INVALID_SOCKET;
  12636. continue;
  12637. }
  12638. if ((pfd = (struct pollfd *)
  12639. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12640. (phys_ctx->num_listening_sockets + 1)
  12641. * sizeof(phys_ctx->listening_socket_fds[0]),
  12642. phys_ctx))
  12643. == NULL) {
  12644. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12645. closesocket(so.sock);
  12646. so.sock = INVALID_SOCKET;
  12647. mg_free(ptr);
  12648. continue;
  12649. }
  12650. set_close_on_exec(so.sock, fc(phys_ctx));
  12651. phys_ctx->listening_sockets = ptr;
  12652. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12653. phys_ctx->listening_socket_fds = pfd;
  12654. phys_ctx->num_listening_sockets++;
  12655. portsOk++;
  12656. }
  12657. if (portsOk != portsTotal) {
  12658. close_all_listening_sockets(phys_ctx);
  12659. portsOk = 0;
  12660. }
  12661. return portsOk;
  12662. }
  12663. static const char *
  12664. header_val(const struct mg_connection *conn, const char *header)
  12665. {
  12666. const char *header_value;
  12667. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12668. return "-";
  12669. } else {
  12670. return header_value;
  12671. }
  12672. }
  12673. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12674. static void log_access(const struct mg_connection *conn);
  12675. #include "external_log_access.inl"
  12676. #else
  12677. static void
  12678. log_access(const struct mg_connection *conn)
  12679. {
  12680. const struct mg_request_info *ri;
  12681. struct mg_file fi;
  12682. char date[64], src_addr[IP_ADDR_STR_LEN];
  12683. struct tm *tm;
  12684. const char *referer;
  12685. const char *user_agent;
  12686. char buf[4096];
  12687. if (!conn || !conn->dom_ctx) {
  12688. return;
  12689. }
  12690. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12691. if (mg_fopen(conn,
  12692. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12693. MG_FOPEN_MODE_APPEND,
  12694. &fi)
  12695. == 0) {
  12696. fi.access.fp = NULL;
  12697. }
  12698. } else {
  12699. fi.access.fp = NULL;
  12700. }
  12701. /* Log is written to a file and/or a callback. If both are not set,
  12702. * executing the rest of the function is pointless. */
  12703. if ((fi.access.fp == NULL)
  12704. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12705. return;
  12706. }
  12707. tm = localtime(&conn->conn_birth_time);
  12708. if (tm != NULL) {
  12709. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12710. } else {
  12711. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12712. date[sizeof(date) - 1] = '\0';
  12713. }
  12714. ri = &conn->request_info;
  12715. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12716. referer = header_val(conn, "Referer");
  12717. user_agent = header_val(conn, "User-Agent");
  12718. mg_snprintf(conn,
  12719. NULL, /* Ignore truncation in access log */
  12720. buf,
  12721. sizeof(buf),
  12722. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12723. src_addr,
  12724. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12725. date,
  12726. ri->request_method ? ri->request_method : "-",
  12727. ri->request_uri ? ri->request_uri : "-",
  12728. ri->query_string ? "?" : "",
  12729. ri->query_string ? ri->query_string : "",
  12730. ri->http_version,
  12731. conn->status_code,
  12732. conn->num_bytes_sent,
  12733. referer,
  12734. user_agent);
  12735. if (conn->phys_ctx->callbacks.log_access) {
  12736. conn->phys_ctx->callbacks.log_access(conn, buf);
  12737. }
  12738. if (fi.access.fp) {
  12739. int ok = 1;
  12740. flockfile(fi.access.fp);
  12741. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12742. ok = 0;
  12743. }
  12744. if (fflush(fi.access.fp) != 0) {
  12745. ok = 0;
  12746. }
  12747. funlockfile(fi.access.fp);
  12748. if (mg_fclose(&fi.access) != 0) {
  12749. ok = 0;
  12750. }
  12751. if (!ok) {
  12752. mg_cry_internal(conn,
  12753. "Error writing log file %s",
  12754. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12755. }
  12756. }
  12757. }
  12758. #endif /* Externally provided function */
  12759. /* Verify given socket address against the ACL.
  12760. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12761. */
  12762. static int
  12763. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12764. {
  12765. int allowed, flag;
  12766. uint32_t net, mask;
  12767. struct vec vec;
  12768. if (phys_ctx) {
  12769. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12770. /* If any ACL is set, deny by default */
  12771. allowed = (list == NULL) ? '+' : '-';
  12772. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12773. flag = vec.ptr[0];
  12774. if ((flag != '+' && flag != '-')
  12775. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12776. mg_cry_internal(fc(phys_ctx),
  12777. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12778. __func__);
  12779. return -1;
  12780. }
  12781. if (net == (remote_ip & mask)) {
  12782. allowed = flag;
  12783. }
  12784. }
  12785. return allowed == '+';
  12786. }
  12787. return -1;
  12788. }
  12789. #if !defined(_WIN32)
  12790. static int
  12791. set_uid_option(struct mg_context *phys_ctx)
  12792. {
  12793. int success = 0;
  12794. if (phys_ctx) {
  12795. /* We are currently running as curr_uid. */
  12796. const uid_t curr_uid = getuid();
  12797. /* If set, we want to run as run_as_user. */
  12798. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12799. const struct passwd *to_pw = NULL;
  12800. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12801. /* run_as_user does not exist on the system. We can't proceed
  12802. * further. */
  12803. mg_cry_internal(fc(phys_ctx),
  12804. "%s: unknown user [%s]",
  12805. __func__,
  12806. run_as_user);
  12807. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12808. /* There was either no request to change user, or we're already
  12809. * running as run_as_user. Nothing else to do.
  12810. */
  12811. success = 1;
  12812. } else {
  12813. /* Valid change request. */
  12814. if (setgid(to_pw->pw_gid) == -1) {
  12815. mg_cry_internal(fc(phys_ctx),
  12816. "%s: setgid(%s): %s",
  12817. __func__,
  12818. run_as_user,
  12819. strerror(errno));
  12820. } else if (setgroups(0, NULL) == -1) {
  12821. mg_cry_internal(fc(phys_ctx),
  12822. "%s: setgroups(): %s",
  12823. __func__,
  12824. strerror(errno));
  12825. } else if (setuid(to_pw->pw_uid) == -1) {
  12826. mg_cry_internal(fc(phys_ctx),
  12827. "%s: setuid(%s): %s",
  12828. __func__,
  12829. run_as_user,
  12830. strerror(errno));
  12831. } else {
  12832. success = 1;
  12833. }
  12834. }
  12835. }
  12836. return success;
  12837. }
  12838. #endif /* !_WIN32 */
  12839. static void
  12840. tls_dtor(void *key)
  12841. {
  12842. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12843. /* key == pthread_getspecific(sTlsKey); */
  12844. if (tls) {
  12845. if (tls->is_master == 2) {
  12846. tls->is_master = -3; /* Mark memory as dead */
  12847. mg_free(tls);
  12848. }
  12849. }
  12850. pthread_setspecific(sTlsKey, NULL);
  12851. }
  12852. #if !defined(NO_SSL)
  12853. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12854. struct mg_domain_context *dom_ctx,
  12855. const char *pem,
  12856. const char *chain);
  12857. static const char *ssl_error(void);
  12858. static int
  12859. refresh_trust(struct mg_connection *conn)
  12860. {
  12861. static int reload_lock = 0;
  12862. static long int data_check = 0;
  12863. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12864. struct stat cert_buf;
  12865. long int t;
  12866. const char *pem;
  12867. const char *chain;
  12868. int should_verify_peer;
  12869. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12870. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12871. * refresh_trust still can not work. */
  12872. return 0;
  12873. }
  12874. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12875. if (chain == NULL) {
  12876. /* pem is not NULL here */
  12877. chain = pem;
  12878. }
  12879. if (*chain == 0) {
  12880. chain = NULL;
  12881. }
  12882. t = data_check;
  12883. if (stat(pem, &cert_buf) != -1) {
  12884. t = (long int)cert_buf.st_mtime;
  12885. }
  12886. if (data_check != t) {
  12887. data_check = t;
  12888. should_verify_peer = 0;
  12889. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12890. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12891. == 0) {
  12892. should_verify_peer = 1;
  12893. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12894. "optional")
  12895. == 0) {
  12896. should_verify_peer = 1;
  12897. }
  12898. }
  12899. if (should_verify_peer) {
  12900. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12901. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12902. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12903. ca_file,
  12904. ca_path)
  12905. != 1) {
  12906. mg_cry_internal(
  12907. fc(conn->phys_ctx),
  12908. "SSL_CTX_load_verify_locations error: %s "
  12909. "ssl_verify_peer requires setting "
  12910. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12911. "present in "
  12912. "the .conf file?",
  12913. ssl_error());
  12914. return 0;
  12915. }
  12916. }
  12917. if (1 == mg_atomic_inc(p_reload_lock)) {
  12918. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12919. == 0) {
  12920. return 0;
  12921. }
  12922. *p_reload_lock = 0;
  12923. }
  12924. }
  12925. /* lock while cert is reloading */
  12926. while (*p_reload_lock) {
  12927. sleep(1);
  12928. }
  12929. return 1;
  12930. }
  12931. #if defined(OPENSSL_API_1_1)
  12932. #else
  12933. static pthread_mutex_t *ssl_mutexes;
  12934. #endif /* OPENSSL_API_1_1 */
  12935. static int
  12936. sslize(struct mg_connection *conn,
  12937. SSL_CTX *s,
  12938. int (*func)(SSL *),
  12939. volatile int *stop_server)
  12940. {
  12941. int ret, err;
  12942. int short_trust;
  12943. unsigned i;
  12944. if (!conn) {
  12945. return 0;
  12946. }
  12947. short_trust =
  12948. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12949. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12950. if (short_trust) {
  12951. int trust_ret = refresh_trust(conn);
  12952. if (!trust_ret) {
  12953. return trust_ret;
  12954. }
  12955. }
  12956. conn->ssl = SSL_new(s);
  12957. if (conn->ssl == NULL) {
  12958. return 0;
  12959. }
  12960. SSL_set_app_data(conn->ssl, (char *)conn);
  12961. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12962. if (ret != 1) {
  12963. err = SSL_get_error(conn->ssl, ret);
  12964. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  12965. SSL_free(conn->ssl);
  12966. conn->ssl = NULL;
  12967. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12968. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12969. #if !defined(OPENSSL_API_1_1)
  12970. ERR_remove_thread_state(NULL);
  12971. #endif
  12972. return 0;
  12973. }
  12974. /* SSL functions may fail and require to be called again:
  12975. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  12976. * Here "func" could be SSL_connect or SSL_accept. */
  12977. for (i = 16; i <= 1024; i *= 2) {
  12978. ret = func(conn->ssl);
  12979. if (ret != 1) {
  12980. err = SSL_get_error(conn->ssl, ret);
  12981. if ((err == SSL_ERROR_WANT_CONNECT)
  12982. || (err == SSL_ERROR_WANT_ACCEPT)
  12983. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  12984. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  12985. /* Need to retry the function call "later".
  12986. * See https://linux.die.net/man/3/ssl_get_error
  12987. * This is typical for non-blocking sockets. */
  12988. if (*stop_server) {
  12989. /* Don't wait if the server is going to be stopped. */
  12990. break;
  12991. }
  12992. mg_sleep(i);
  12993. } else if (err == SSL_ERROR_SYSCALL) {
  12994. /* This is an IO error. Look at errno. */
  12995. err = errno;
  12996. mg_cry_internal(conn, "SSL syscall error %i", err);
  12997. break;
  12998. } else {
  12999. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13000. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13001. break;
  13002. }
  13003. } else {
  13004. /* success */
  13005. break;
  13006. }
  13007. }
  13008. if (ret != 1) {
  13009. SSL_free(conn->ssl);
  13010. conn->ssl = NULL;
  13011. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13012. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13013. #if !defined(OPENSSL_API_1_1)
  13014. ERR_remove_thread_state(NULL);
  13015. #endif
  13016. return 0;
  13017. }
  13018. return 1;
  13019. }
  13020. /* Return OpenSSL error message (from CRYPTO lib) */
  13021. static const char *
  13022. ssl_error(void)
  13023. {
  13024. unsigned long err;
  13025. err = ERR_get_error();
  13026. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13027. }
  13028. static int
  13029. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13030. {
  13031. int i;
  13032. const char hexdigit[] = "0123456789abcdef";
  13033. if ((memlen <= 0) || (buflen <= 0)) {
  13034. return 0;
  13035. }
  13036. if (buflen < (3 * memlen)) {
  13037. return 0;
  13038. }
  13039. for (i = 0; i < memlen; i++) {
  13040. if (i > 0) {
  13041. buf[3 * i - 1] = ' ';
  13042. }
  13043. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13044. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13045. }
  13046. buf[3 * memlen - 1] = 0;
  13047. return 1;
  13048. }
  13049. static void
  13050. ssl_get_client_cert_info(struct mg_connection *conn)
  13051. {
  13052. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13053. if (cert) {
  13054. char str_subject[1024];
  13055. char str_issuer[1024];
  13056. char str_finger[1024];
  13057. unsigned char buf[256];
  13058. char *str_serial = NULL;
  13059. unsigned int ulen;
  13060. int ilen;
  13061. unsigned char *tmp_buf;
  13062. unsigned char *tmp_p;
  13063. /* Handle to algorithm used for fingerprint */
  13064. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13065. /* Get Subject and issuer */
  13066. X509_NAME *subj = X509_get_subject_name(cert);
  13067. X509_NAME *iss = X509_get_issuer_name(cert);
  13068. /* Get serial number */
  13069. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13070. /* Translate serial number to a hex string */
  13071. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13072. str_serial = BN_bn2hex(serial_bn);
  13073. BN_free(serial_bn);
  13074. /* Translate subject and issuer to a string */
  13075. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13076. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13077. /* Calculate SHA1 fingerprint and store as a hex string */
  13078. ulen = 0;
  13079. /* ASN1_digest is deprecated. Do the calculation manually,
  13080. * using EVP_Digest. */
  13081. ilen = i2d_X509(cert, NULL);
  13082. tmp_buf = (ilen > 0)
  13083. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13084. conn->phys_ctx)
  13085. : NULL;
  13086. if (tmp_buf) {
  13087. tmp_p = tmp_buf;
  13088. (void)i2d_X509(cert, &tmp_p);
  13089. if (!EVP_Digest(
  13090. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13091. ulen = 0;
  13092. }
  13093. mg_free(tmp_buf);
  13094. }
  13095. if (!hexdump2string(
  13096. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13097. *str_finger = 0;
  13098. }
  13099. conn->request_info.client_cert = (struct mg_client_cert *)
  13100. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13101. if (conn->request_info.client_cert) {
  13102. conn->request_info.client_cert->peer_cert = (void *)cert;
  13103. conn->request_info.client_cert->subject =
  13104. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13105. conn->request_info.client_cert->issuer =
  13106. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13107. conn->request_info.client_cert->serial =
  13108. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13109. conn->request_info.client_cert->finger =
  13110. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13111. } else {
  13112. mg_cry_internal(conn,
  13113. "%s",
  13114. "Out of memory: Cannot allocate memory for client "
  13115. "certificate");
  13116. }
  13117. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13118. * see https://linux.die.net/man/3/bn_bn2hex */
  13119. OPENSSL_free(str_serial);
  13120. }
  13121. }
  13122. #if defined(OPENSSL_API_1_1)
  13123. #else
  13124. static void
  13125. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13126. {
  13127. (void)line;
  13128. (void)file;
  13129. if (mode & 1) {
  13130. /* 1 is CRYPTO_LOCK */
  13131. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13132. } else {
  13133. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13134. }
  13135. }
  13136. #endif /* OPENSSL_API_1_1 */
  13137. #if !defined(NO_SSL_DL)
  13138. static void *
  13139. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13140. {
  13141. union {
  13142. void *p;
  13143. void (*fp)(void);
  13144. } u;
  13145. void *dll_handle;
  13146. struct ssl_func *fp;
  13147. int ok;
  13148. int truncated = 0;
  13149. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13150. mg_snprintf(NULL,
  13151. NULL, /* No truncation check for ebuf */
  13152. ebuf,
  13153. ebuf_len,
  13154. "%s: cannot load %s",
  13155. __func__,
  13156. dll_name);
  13157. return NULL;
  13158. }
  13159. ok = 1;
  13160. for (fp = sw; fp->name != NULL; fp++) {
  13161. #if defined(_WIN32)
  13162. /* GetProcAddress() returns pointer to function */
  13163. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13164. #else
  13165. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13166. * pointers to function pointers. We need to use a union to make a
  13167. * cast. */
  13168. u.p = dlsym(dll_handle, fp->name);
  13169. #endif /* _WIN32 */
  13170. if (u.fp == NULL) {
  13171. if (ok) {
  13172. mg_snprintf(NULL,
  13173. &truncated,
  13174. ebuf,
  13175. ebuf_len,
  13176. "%s: %s: cannot find %s",
  13177. __func__,
  13178. dll_name,
  13179. fp->name);
  13180. ok = 0;
  13181. } else {
  13182. size_t cur_len = strlen(ebuf);
  13183. if (!truncated) {
  13184. mg_snprintf(NULL,
  13185. &truncated,
  13186. ebuf + cur_len,
  13187. ebuf_len - cur_len - 3,
  13188. ", %s",
  13189. fp->name);
  13190. if (truncated) {
  13191. /* If truncated, add "..." */
  13192. strcat(ebuf, "...");
  13193. }
  13194. }
  13195. }
  13196. /* Debug:
  13197. * printf("Missing function: %s\n", fp->name); */
  13198. } else {
  13199. fp->ptr = u.fp;
  13200. }
  13201. }
  13202. if (!ok) {
  13203. (void)dlclose(dll_handle);
  13204. return NULL;
  13205. }
  13206. return dll_handle;
  13207. }
  13208. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13209. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13210. #endif /* NO_SSL_DL */
  13211. #if defined(SSL_ALREADY_INITIALIZED)
  13212. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13213. #else
  13214. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13215. #endif
  13216. static int
  13217. initialize_ssl(char *ebuf, size_t ebuf_len)
  13218. {
  13219. #if defined(OPENSSL_API_1_1)
  13220. if (ebuf_len > 0) {
  13221. ebuf[0] = 0;
  13222. }
  13223. #if !defined(NO_SSL_DL)
  13224. if (!cryptolib_dll_handle) {
  13225. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13226. if (!cryptolib_dll_handle) {
  13227. mg_snprintf(NULL,
  13228. NULL, /* No truncation check for ebuf */
  13229. ebuf,
  13230. ebuf_len,
  13231. "%s: error loading library %s",
  13232. __func__,
  13233. CRYPTO_LIB);
  13234. DEBUG_TRACE("%s", ebuf);
  13235. return 0;
  13236. }
  13237. }
  13238. #endif /* NO_SSL_DL */
  13239. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13240. return 1;
  13241. }
  13242. #else /* not OPENSSL_API_1_1 */
  13243. int i, num_locks;
  13244. size_t size;
  13245. if (ebuf_len > 0) {
  13246. ebuf[0] = 0;
  13247. }
  13248. #if !defined(NO_SSL_DL)
  13249. if (!cryptolib_dll_handle) {
  13250. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13251. if (!cryptolib_dll_handle) {
  13252. mg_snprintf(NULL,
  13253. NULL, /* No truncation check for ebuf */
  13254. ebuf,
  13255. ebuf_len,
  13256. "%s: error loading library %s",
  13257. __func__,
  13258. CRYPTO_LIB);
  13259. DEBUG_TRACE("%s", ebuf);
  13260. return 0;
  13261. }
  13262. }
  13263. #endif /* NO_SSL_DL */
  13264. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13265. return 1;
  13266. }
  13267. /* Initialize locking callbacks, needed for thread safety.
  13268. * http://www.openssl.org/support/faq.html#PROG1
  13269. */
  13270. num_locks = CRYPTO_num_locks();
  13271. if (num_locks < 0) {
  13272. num_locks = 0;
  13273. }
  13274. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13275. /* allocate mutex array, if required */
  13276. if (num_locks == 0) {
  13277. /* No mutex array required */
  13278. ssl_mutexes = NULL;
  13279. } else {
  13280. /* Mutex array required - allocate it */
  13281. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13282. /* Check OOM */
  13283. if (ssl_mutexes == NULL) {
  13284. mg_snprintf(NULL,
  13285. NULL, /* No truncation check for ebuf */
  13286. ebuf,
  13287. ebuf_len,
  13288. "%s: cannot allocate mutexes: %s",
  13289. __func__,
  13290. ssl_error());
  13291. DEBUG_TRACE("%s", ebuf);
  13292. return 0;
  13293. }
  13294. /* initialize mutex array */
  13295. for (i = 0; i < num_locks; i++) {
  13296. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13297. mg_snprintf(NULL,
  13298. NULL, /* No truncation check for ebuf */
  13299. ebuf,
  13300. ebuf_len,
  13301. "%s: error initializing mutex %i of %i",
  13302. __func__,
  13303. i,
  13304. num_locks);
  13305. DEBUG_TRACE("%s", ebuf);
  13306. mg_free(ssl_mutexes);
  13307. return 0;
  13308. }
  13309. }
  13310. }
  13311. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13312. CRYPTO_set_id_callback(&mg_current_thread_id);
  13313. #endif /* OPENSSL_API_1_1 */
  13314. #if !defined(NO_SSL_DL)
  13315. if (!ssllib_dll_handle) {
  13316. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13317. if (!ssllib_dll_handle) {
  13318. #if !defined(OPENSSL_API_1_1)
  13319. mg_free(ssl_mutexes);
  13320. #endif
  13321. DEBUG_TRACE("%s", ebuf);
  13322. return 0;
  13323. }
  13324. }
  13325. #endif /* NO_SSL_DL */
  13326. #if defined(OPENSSL_API_1_1)
  13327. /* Initialize SSL library */
  13328. OPENSSL_init_ssl(0, NULL);
  13329. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13330. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13331. NULL);
  13332. #else
  13333. /* Initialize SSL library */
  13334. SSL_library_init();
  13335. SSL_load_error_strings();
  13336. #endif
  13337. return 1;
  13338. }
  13339. static int
  13340. ssl_use_pem_file(struct mg_context *phys_ctx,
  13341. struct mg_domain_context *dom_ctx,
  13342. const char *pem,
  13343. const char *chain)
  13344. {
  13345. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13346. mg_cry_internal(fc(phys_ctx),
  13347. "%s: cannot open certificate file %s: %s",
  13348. __func__,
  13349. pem,
  13350. ssl_error());
  13351. return 0;
  13352. }
  13353. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13354. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13355. mg_cry_internal(fc(phys_ctx),
  13356. "%s: cannot open private key file %s: %s",
  13357. __func__,
  13358. pem,
  13359. ssl_error());
  13360. return 0;
  13361. }
  13362. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13363. mg_cry_internal(fc(phys_ctx),
  13364. "%s: certificate and private key do not match: %s",
  13365. __func__,
  13366. pem);
  13367. return 0;
  13368. }
  13369. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13370. * chain files that contain private keys and certificates in
  13371. * SSL_CTX_use_certificate_chain_file.
  13372. * The CivetWeb-Server used pem-Files that contained both information.
  13373. * In order to make wolfSSL work, it is split in two files.
  13374. * One file that contains key and certificate used by the server and
  13375. * an optional chain file for the ssl stack.
  13376. */
  13377. if (chain) {
  13378. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13379. mg_cry_internal(fc(phys_ctx),
  13380. "%s: cannot use certificate chain file %s: %s",
  13381. __func__,
  13382. pem,
  13383. ssl_error());
  13384. return 0;
  13385. }
  13386. }
  13387. return 1;
  13388. }
  13389. #if defined(OPENSSL_API_1_1)
  13390. static unsigned long
  13391. ssl_get_protocol(int version_id)
  13392. {
  13393. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13394. if (version_id > 0)
  13395. ret |= SSL_OP_NO_SSLv2;
  13396. if (version_id > 1)
  13397. ret |= SSL_OP_NO_SSLv3;
  13398. if (version_id > 2)
  13399. ret |= SSL_OP_NO_TLSv1;
  13400. if (version_id > 3)
  13401. ret |= SSL_OP_NO_TLSv1_1;
  13402. return ret;
  13403. }
  13404. #else
  13405. static long
  13406. ssl_get_protocol(int version_id)
  13407. {
  13408. long ret = (long)SSL_OP_ALL;
  13409. if (version_id > 0)
  13410. ret |= SSL_OP_NO_SSLv2;
  13411. if (version_id > 1)
  13412. ret |= SSL_OP_NO_SSLv3;
  13413. if (version_id > 2)
  13414. ret |= SSL_OP_NO_TLSv1;
  13415. if (version_id > 3)
  13416. ret |= SSL_OP_NO_TLSv1_1;
  13417. return ret;
  13418. }
  13419. #endif /* OPENSSL_API_1_1 */
  13420. /* SSL callback documentation:
  13421. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13422. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13423. * https://linux.die.net/man/3/ssl_set_info_callback */
  13424. /* Note: There is no "const" for the first argument in the documentation,
  13425. * however some (maybe most, but not all) headers of OpenSSL versions /
  13426. * OpenSSL compatibility layers have it. Having a different definition
  13427. * will cause a warning in C and an error in C++. With inconsitent
  13428. * definitions of this function, having a warning in one version or
  13429. * another is unavoidable. */
  13430. static void
  13431. ssl_info_callback(const SSL *ssl, int what, int ret)
  13432. {
  13433. (void)ret;
  13434. if (what & SSL_CB_HANDSHAKE_START) {
  13435. SSL_get_app_data(ssl);
  13436. }
  13437. if (what & SSL_CB_HANDSHAKE_DONE) {
  13438. /* TODO: check for openSSL 1.1 */
  13439. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13440. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13441. }
  13442. }
  13443. static int
  13444. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13445. {
  13446. struct mg_context *ctx = (struct mg_context *)arg;
  13447. struct mg_domain_context *dom =
  13448. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13449. #if defined(GCC_DIAGNOSTIC)
  13450. #pragma GCC diagnostic push
  13451. #pragma GCC diagnostic ignored "-Wcast-align"
  13452. #endif /* defined(GCC_DIAGNOSTIC) */
  13453. /* We used an aligned pointer in SSL_set_app_data */
  13454. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13455. #if defined(GCC_DIAGNOSTIC)
  13456. #pragma GCC diagnostic pop
  13457. #endif /* defined(GCC_DIAGNOSTIC) */
  13458. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13459. (void)ad;
  13460. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13461. DEBUG_TRACE("%s", "internal error - assertion failed");
  13462. return SSL_TLSEXT_ERR_NOACK;
  13463. }
  13464. /* Old clients (Win XP) will not support SNI. Then, there
  13465. * is no server name available in the request - we can
  13466. * only work with the default certificate.
  13467. * Multiple HTTPS hosts on one IP+port are only possible
  13468. * with a certificate containing all alternative names.
  13469. */
  13470. if ((servername == NULL) || (*servername == 0)) {
  13471. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13472. conn->dom_ctx = &(ctx->dd);
  13473. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13474. return SSL_TLSEXT_ERR_NOACK;
  13475. }
  13476. DEBUG_TRACE("TLS connection to host %s", servername);
  13477. while (dom) {
  13478. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13479. /* Found matching domain */
  13480. DEBUG_TRACE("TLS domain %s found",
  13481. dom->config[AUTHENTICATION_DOMAIN]);
  13482. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13483. conn->dom_ctx = dom;
  13484. return SSL_TLSEXT_ERR_OK;
  13485. }
  13486. dom = dom->next;
  13487. }
  13488. /* Default domain */
  13489. DEBUG_TRACE("TLS default domain %s used",
  13490. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13491. conn->dom_ctx = &(ctx->dd);
  13492. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13493. return SSL_TLSEXT_ERR_OK;
  13494. }
  13495. /* Setup SSL CTX as required by CivetWeb */
  13496. static int
  13497. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13498. struct mg_domain_context *dom_ctx,
  13499. const char *pem,
  13500. const char *chain)
  13501. {
  13502. int callback_ret;
  13503. int should_verify_peer;
  13504. int peer_certificate_optional;
  13505. const char *ca_path;
  13506. const char *ca_file;
  13507. int use_default_verify_paths;
  13508. int verify_depth;
  13509. struct timespec now_mt;
  13510. md5_byte_t ssl_context_id[16];
  13511. md5_state_t md5state;
  13512. int protocol_ver;
  13513. #if defined(OPENSSL_API_1_1)
  13514. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13515. mg_cry_internal(fc(phys_ctx),
  13516. "SSL_CTX_new (server) error: %s",
  13517. ssl_error());
  13518. return 0;
  13519. }
  13520. #else
  13521. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13522. mg_cry_internal(fc(phys_ctx),
  13523. "SSL_CTX_new (server) error: %s",
  13524. ssl_error());
  13525. return 0;
  13526. }
  13527. #endif /* OPENSSL_API_1_1 */
  13528. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13529. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13530. | SSL_OP_NO_TLSv1_1);
  13531. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13532. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13533. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13534. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13535. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13536. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13537. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13538. #if !defined(NO_SSL_DL)
  13539. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13540. #endif /* NO_SSL_DL */
  13541. /* In SSL documentation examples callback defined without const specifier
  13542. * 'void (*)(SSL *, int, int)' See:
  13543. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13544. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13545. * But in the source code const SSL is used:
  13546. * 'void (*)(const SSL *, int, int)' See:
  13547. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13548. * Problem about wrong documentation described, but not resolved:
  13549. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13550. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13551. * But when compiled with modern C++ compiler, correct const should be provided
  13552. */
  13553. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13554. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13555. ssl_servername_callback);
  13556. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13557. /* If a callback has been specified, call it. */
  13558. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13559. ? 0
  13560. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13561. phys_ctx->user_data));
  13562. /* If callback returns 0, civetweb sets up the SSL certificate.
  13563. * If it returns 1, civetweb assumes the calback already did this.
  13564. * If it returns -1, initializing ssl fails. */
  13565. if (callback_ret < 0) {
  13566. mg_cry_internal(fc(phys_ctx),
  13567. "SSL callback returned error: %i",
  13568. callback_ret);
  13569. return 0;
  13570. }
  13571. if (callback_ret > 0) {
  13572. /* Callback did everything. */
  13573. return 1;
  13574. }
  13575. /* Use some combination of start time, domain and port as a SSL
  13576. * context ID. This should be unique on the current machine. */
  13577. md5_init(&md5state);
  13578. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13579. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13580. md5_append(&md5state,
  13581. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13582. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13583. md5_append(&md5state,
  13584. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13585. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13586. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13587. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13588. md5_finish(&md5state, ssl_context_id);
  13589. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13590. (unsigned char *)ssl_context_id,
  13591. sizeof(ssl_context_id));
  13592. if (pem != NULL) {
  13593. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13594. return 0;
  13595. }
  13596. }
  13597. /* Should we support client certificates? */
  13598. /* Default is "no". */
  13599. should_verify_peer = 0;
  13600. peer_certificate_optional = 0;
  13601. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13602. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13603. /* Yes, they are mandatory */
  13604. should_verify_peer = 1;
  13605. peer_certificate_optional = 0;
  13606. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13607. "optional")
  13608. == 0) {
  13609. /* Yes, they are optional */
  13610. should_verify_peer = 1;
  13611. peer_certificate_optional = 1;
  13612. }
  13613. }
  13614. use_default_verify_paths =
  13615. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13616. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13617. == 0);
  13618. if (should_verify_peer) {
  13619. ca_path = dom_ctx->config[SSL_CA_PATH];
  13620. ca_file = dom_ctx->config[SSL_CA_FILE];
  13621. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13622. != 1) {
  13623. mg_cry_internal(fc(phys_ctx),
  13624. "SSL_CTX_load_verify_locations error: %s "
  13625. "ssl_verify_peer requires setting "
  13626. "either ssl_ca_path or ssl_ca_file. "
  13627. "Is any of them present in the "
  13628. ".conf file?",
  13629. ssl_error());
  13630. return 0;
  13631. }
  13632. if (peer_certificate_optional) {
  13633. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13634. } else {
  13635. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13636. SSL_VERIFY_PEER
  13637. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13638. NULL);
  13639. }
  13640. if (use_default_verify_paths
  13641. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13642. mg_cry_internal(fc(phys_ctx),
  13643. "SSL_CTX_set_default_verify_paths error: %s",
  13644. ssl_error());
  13645. return 0;
  13646. }
  13647. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13648. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13649. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13650. }
  13651. }
  13652. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13653. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13654. dom_ctx->config[SSL_CIPHER_LIST])
  13655. != 1) {
  13656. mg_cry_internal(fc(phys_ctx),
  13657. "SSL_CTX_set_cipher_list error: %s",
  13658. ssl_error());
  13659. }
  13660. }
  13661. return 1;
  13662. }
  13663. /* Check if SSL is required.
  13664. * If so, dynamically load SSL library
  13665. * and set up ctx->ssl_ctx pointer. */
  13666. static int
  13667. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13668. {
  13669. void *ssl_ctx = 0;
  13670. int callback_ret;
  13671. const char *pem;
  13672. const char *chain;
  13673. char ebuf[128];
  13674. if (!phys_ctx) {
  13675. return 0;
  13676. }
  13677. if (!dom_ctx) {
  13678. dom_ctx = &(phys_ctx->dd);
  13679. }
  13680. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13681. /* No SSL port is set. No need to setup SSL. */
  13682. return 1;
  13683. }
  13684. /* Check for external SSL_CTX */
  13685. callback_ret =
  13686. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13687. ? 0
  13688. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13689. phys_ctx->user_data));
  13690. if (callback_ret < 0) {
  13691. mg_cry_internal(fc(phys_ctx),
  13692. "external_ssl_ctx callback returned error: %i",
  13693. callback_ret);
  13694. return 0;
  13695. } else if (callback_ret > 0) {
  13696. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13697. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13698. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13699. return 0;
  13700. }
  13701. return 1;
  13702. }
  13703. /* else: external_ssl_ctx does not exist or returns 0,
  13704. * CivetWeb should continue initializing SSL */
  13705. /* If PEM file is not specified and the init_ssl callback
  13706. * is not specified, setup will fail. */
  13707. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13708. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13709. /* No certificate and no callback:
  13710. * Essential data to set up TLS is missing.
  13711. */
  13712. mg_cry_internal(fc(phys_ctx),
  13713. "Initializing SSL failed: -%s is not set",
  13714. config_options[SSL_CERTIFICATE].name);
  13715. return 0;
  13716. }
  13717. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13718. if (chain == NULL) {
  13719. chain = pem;
  13720. }
  13721. if ((chain != NULL) && (*chain == 0)) {
  13722. chain = NULL;
  13723. }
  13724. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13725. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13726. return 0;
  13727. }
  13728. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13729. }
  13730. static void
  13731. uninitialize_ssl(void)
  13732. {
  13733. #if defined(OPENSSL_API_1_1)
  13734. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13735. /* Shutdown according to
  13736. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13737. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13738. */
  13739. CONF_modules_unload(1);
  13740. #else
  13741. int i;
  13742. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13743. /* Shutdown according to
  13744. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13745. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13746. */
  13747. CRYPTO_set_locking_callback(NULL);
  13748. CRYPTO_set_id_callback(NULL);
  13749. ENGINE_cleanup();
  13750. CONF_modules_unload(1);
  13751. ERR_free_strings();
  13752. EVP_cleanup();
  13753. CRYPTO_cleanup_all_ex_data();
  13754. ERR_remove_thread_state(NULL);
  13755. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13756. pthread_mutex_destroy(&ssl_mutexes[i]);
  13757. }
  13758. mg_free(ssl_mutexes);
  13759. ssl_mutexes = NULL;
  13760. #endif /* OPENSSL_API_1_1 */
  13761. }
  13762. }
  13763. #endif /* !NO_SSL */
  13764. static int
  13765. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13766. {
  13767. if (phys_ctx) {
  13768. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13769. const char *path;
  13770. if (!dom_ctx) {
  13771. dom_ctx = &(phys_ctx->dd);
  13772. }
  13773. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13774. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13775. mg_cry_internal(fc(phys_ctx),
  13776. "Cannot open %s: %s",
  13777. path,
  13778. strerror(ERRNO));
  13779. return 0;
  13780. }
  13781. return 1;
  13782. }
  13783. return 0;
  13784. }
  13785. static int
  13786. set_acl_option(struct mg_context *phys_ctx)
  13787. {
  13788. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13789. }
  13790. static void
  13791. reset_per_request_attributes(struct mg_connection *conn)
  13792. {
  13793. if (!conn) {
  13794. return;
  13795. }
  13796. conn->connection_type =
  13797. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13798. conn->num_bytes_sent = conn->consumed_content = 0;
  13799. conn->path_info = NULL;
  13800. conn->status_code = -1;
  13801. conn->content_len = -1;
  13802. conn->is_chunked = 0;
  13803. conn->must_close = 0;
  13804. conn->request_len = 0;
  13805. conn->throttle = 0;
  13806. conn->data_len = 0;
  13807. conn->chunk_remainder = 0;
  13808. conn->accept_gzip = 0;
  13809. conn->response_info.content_length = conn->request_info.content_length = -1;
  13810. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13811. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13812. conn->response_info.status_text = NULL;
  13813. conn->response_info.status_code = 0;
  13814. conn->request_info.remote_user = NULL;
  13815. conn->request_info.request_method = NULL;
  13816. conn->request_info.request_uri = NULL;
  13817. conn->request_info.local_uri = NULL;
  13818. #if defined(MG_LEGACY_INTERFACE)
  13819. /* Legacy before split into local_uri and request_uri */
  13820. conn->request_info.uri = NULL;
  13821. #endif
  13822. }
  13823. #if 0
  13824. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13825. * Leave this function here (commented out) for reference until
  13826. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13827. * no longer required.
  13828. */
  13829. static int
  13830. set_sock_timeout(SOCKET sock, int milliseconds)
  13831. {
  13832. int r0 = 0, r1, r2;
  13833. #if defined(_WIN32)
  13834. /* Windows specific */
  13835. DWORD tv = (DWORD)milliseconds;
  13836. #else
  13837. /* Linux, ... (not Windows) */
  13838. struct timeval tv;
  13839. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13840. * max. time waiting for the acknowledged of TCP data before the connection
  13841. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13842. * If this option is not set, the default timeout of 20-30 minutes is used.
  13843. */
  13844. /* #define TCP_USER_TIMEOUT (18) */
  13845. #if defined(TCP_USER_TIMEOUT)
  13846. unsigned int uto = (unsigned int)milliseconds;
  13847. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13848. #endif
  13849. memset(&tv, 0, sizeof(tv));
  13850. tv.tv_sec = milliseconds / 1000;
  13851. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13852. #endif /* _WIN32 */
  13853. r1 = setsockopt(
  13854. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13855. r2 = setsockopt(
  13856. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13857. return r0 || r1 || r2;
  13858. }
  13859. #endif
  13860. static int
  13861. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13862. {
  13863. if (setsockopt(sock,
  13864. IPPROTO_TCP,
  13865. TCP_NODELAY,
  13866. (SOCK_OPT_TYPE)&nodelay_on,
  13867. sizeof(nodelay_on))
  13868. != 0) {
  13869. /* Error */
  13870. return 1;
  13871. }
  13872. /* OK */
  13873. return 0;
  13874. }
  13875. static void
  13876. close_socket_gracefully(struct mg_connection *conn)
  13877. {
  13878. #if defined(_WIN32)
  13879. char buf[MG_BUF_LEN];
  13880. int n;
  13881. #endif
  13882. struct linger linger;
  13883. int error_code = 0;
  13884. int linger_timeout = -2;
  13885. socklen_t opt_len = sizeof(error_code);
  13886. if (!conn) {
  13887. return;
  13888. }
  13889. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13890. * "Note that enabling a nonzero timeout on a nonblocking socket
  13891. * is not recommended.", so set it to blocking now */
  13892. set_blocking_mode(conn->client.sock);
  13893. /* Send FIN to the client */
  13894. shutdown(conn->client.sock, SHUTDOWN_WR);
  13895. #if defined(_WIN32)
  13896. /* Read and discard pending incoming data. If we do not do that and
  13897. * close
  13898. * the socket, the data in the send buffer may be discarded. This
  13899. * behaviour is seen on Windows, when client keeps sending data
  13900. * when server decides to close the connection; then when client
  13901. * does recv() it gets no data back. */
  13902. do {
  13903. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13904. } while (n > 0);
  13905. #endif
  13906. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13907. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13908. }
  13909. /* Set linger option according to configuration */
  13910. if (linger_timeout >= 0) {
  13911. /* Set linger option to avoid socket hanging out after close. This
  13912. * prevent ephemeral port exhaust problem under high QPS. */
  13913. linger.l_onoff = 1;
  13914. #if defined(_MSC_VER)
  13915. #pragma warning(push)
  13916. #pragma warning(disable : 4244)
  13917. #endif
  13918. #if defined(GCC_DIAGNOSTIC)
  13919. #pragma GCC diagnostic push
  13920. #pragma GCC diagnostic ignored "-Wconversion"
  13921. #endif
  13922. /* Data type of linger structure elements may differ,
  13923. * so we don't know what cast we need here.
  13924. * Disable type conversion warnings. */
  13925. linger.l_linger = (linger_timeout + 999) / 1000;
  13926. #if defined(GCC_DIAGNOSTIC)
  13927. #pragma GCC diagnostic pop
  13928. #endif
  13929. #if defined(_MSC_VER)
  13930. #pragma warning(pop)
  13931. #endif
  13932. } else {
  13933. linger.l_onoff = 0;
  13934. linger.l_linger = 0;
  13935. }
  13936. if (linger_timeout < -1) {
  13937. /* Default: don't configure any linger */
  13938. } else if (getsockopt(conn->client.sock,
  13939. SOL_SOCKET,
  13940. SO_ERROR,
  13941. #if defined(_WIN32) /* WinSock uses different data type here */
  13942. (char *)&error_code,
  13943. #else
  13944. &error_code,
  13945. #endif
  13946. &opt_len)
  13947. != 0) {
  13948. /* Cannot determine if socket is already closed. This should
  13949. * not occur and never did in a test. Log an error message
  13950. * and continue. */
  13951. mg_cry_internal(conn,
  13952. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13953. __func__,
  13954. strerror(ERRNO));
  13955. } else if (error_code == ECONNRESET) {
  13956. /* Socket already closed by client/peer, close socket without linger
  13957. */
  13958. } else {
  13959. /* Set linger timeout */
  13960. if (setsockopt(conn->client.sock,
  13961. SOL_SOCKET,
  13962. SO_LINGER,
  13963. (char *)&linger,
  13964. sizeof(linger))
  13965. != 0) {
  13966. mg_cry_internal(
  13967. conn,
  13968. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13969. __func__,
  13970. linger.l_onoff,
  13971. linger.l_linger,
  13972. strerror(ERRNO));
  13973. }
  13974. }
  13975. /* Now we know that our FIN is ACK-ed, safe to close */
  13976. closesocket(conn->client.sock);
  13977. conn->client.sock = INVALID_SOCKET;
  13978. }
  13979. static void
  13980. close_connection(struct mg_connection *conn)
  13981. {
  13982. #if defined(USE_SERVER_STATS)
  13983. conn->conn_state = 6; /* to close */
  13984. #endif
  13985. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13986. if (conn->lua_websocket_state) {
  13987. lua_websocket_close(conn, conn->lua_websocket_state);
  13988. conn->lua_websocket_state = NULL;
  13989. }
  13990. #endif
  13991. mg_lock_connection(conn);
  13992. /* Set close flag, so keep-alive loops will stop */
  13993. conn->must_close = 1;
  13994. /* call the connection_close callback if assigned */
  13995. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13996. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13997. conn->phys_ctx->callbacks.connection_close(conn);
  13998. }
  13999. }
  14000. /* Reset user data, after close callback is called.
  14001. * Do not reuse it. If the user needs a destructor,
  14002. * it must be done in the connection_close callback. */
  14003. mg_set_user_connection_data(conn, NULL);
  14004. #if defined(USE_SERVER_STATS)
  14005. conn->conn_state = 7; /* closing */
  14006. #endif
  14007. #if !defined(NO_SSL)
  14008. if (conn->ssl != NULL) {
  14009. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14010. */
  14011. SSL_shutdown(conn->ssl);
  14012. SSL_free(conn->ssl);
  14013. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  14014. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  14015. #if !defined(OPENSSL_API_1_1)
  14016. ERR_remove_thread_state(NULL);
  14017. #endif
  14018. conn->ssl = NULL;
  14019. }
  14020. #endif
  14021. if (conn->client.sock != INVALID_SOCKET) {
  14022. close_socket_gracefully(conn);
  14023. conn->client.sock = INVALID_SOCKET;
  14024. }
  14025. if (conn->host) {
  14026. mg_free((void *)conn->host);
  14027. conn->host = NULL;
  14028. }
  14029. mg_unlock_connection(conn);
  14030. #if defined(USE_SERVER_STATS)
  14031. conn->conn_state = 8; /* closed */
  14032. #endif
  14033. }
  14034. void
  14035. mg_close_connection(struct mg_connection *conn)
  14036. {
  14037. #if defined(USE_WEBSOCKET)
  14038. struct mg_context *client_ctx = NULL;
  14039. #endif /* defined(USE_WEBSOCKET) */
  14040. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14041. return;
  14042. }
  14043. #if defined(USE_WEBSOCKET)
  14044. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14045. if (conn->in_websocket_handling) {
  14046. /* Set close flag, so the server thread can exit. */
  14047. conn->must_close = 1;
  14048. return;
  14049. }
  14050. }
  14051. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14052. unsigned int i;
  14053. /* ws/wss client */
  14054. client_ctx = conn->phys_ctx;
  14055. /* client context: loops must end */
  14056. client_ctx->stop_flag = 1;
  14057. conn->must_close = 1;
  14058. /* We need to get the client thread out of the select/recv call
  14059. * here. */
  14060. /* Since we use a sleep quantum of some seconds to check for recv
  14061. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14062. /* join worker thread */
  14063. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  14064. if (client_ctx->worker_threadids[i] != 0) {
  14065. mg_join_thread(client_ctx->worker_threadids[i]);
  14066. }
  14067. }
  14068. }
  14069. #endif /* defined(USE_WEBSOCKET) */
  14070. close_connection(conn);
  14071. #if !defined(NO_SSL)
  14072. if (conn->client_ssl_ctx != NULL) {
  14073. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  14074. }
  14075. #endif
  14076. #if defined(USE_WEBSOCKET)
  14077. if (client_ctx != NULL) {
  14078. /* free context */
  14079. mg_free(client_ctx->worker_threadids);
  14080. mg_free(client_ctx);
  14081. (void)pthread_mutex_destroy(&conn->mutex);
  14082. mg_free(conn);
  14083. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14084. mg_free(conn);
  14085. }
  14086. #else
  14087. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14088. mg_free(conn);
  14089. }
  14090. #endif /* defined(USE_WEBSOCKET) */
  14091. }
  14092. /* Only for memory statistics */
  14093. static struct mg_context common_client_context;
  14094. static struct mg_connection *
  14095. mg_connect_client_impl(const struct mg_client_options *client_options,
  14096. int use_ssl,
  14097. char *ebuf,
  14098. size_t ebuf_len)
  14099. {
  14100. struct mg_connection *conn = NULL;
  14101. SOCKET sock;
  14102. union usa sa;
  14103. struct sockaddr *psa;
  14104. socklen_t len;
  14105. unsigned max_req_size =
  14106. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14107. /* Size of structures, aligned to 8 bytes */
  14108. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14109. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14110. conn = (struct mg_connection *)mg_calloc_ctx(
  14111. 1, conn_size + ctx_size + max_req_size, &common_client_context);
  14112. if (conn == NULL) {
  14113. mg_snprintf(NULL,
  14114. NULL, /* No truncation check for ebuf */
  14115. ebuf,
  14116. ebuf_len,
  14117. "calloc(): %s",
  14118. strerror(ERRNO));
  14119. return NULL;
  14120. }
  14121. #if defined(GCC_DIAGNOSTIC)
  14122. #pragma GCC diagnostic push
  14123. #pragma GCC diagnostic ignored "-Wcast-align"
  14124. #endif /* defined(GCC_DIAGNOSTIC) */
  14125. /* conn_size is aligned to 8 bytes */
  14126. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14127. #if defined(GCC_DIAGNOSTIC)
  14128. #pragma GCC diagnostic pop
  14129. #endif /* defined(GCC_DIAGNOSTIC) */
  14130. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14131. conn->buf_size = (int)max_req_size;
  14132. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14133. conn->dom_ctx = &(conn->phys_ctx->dd);
  14134. if (!connect_socket(&common_client_context,
  14135. client_options->host,
  14136. client_options->port,
  14137. use_ssl,
  14138. ebuf,
  14139. ebuf_len,
  14140. &sock,
  14141. &sa)) {
  14142. /* ebuf is set by connect_socket,
  14143. * free all memory and return NULL; */
  14144. mg_free(conn);
  14145. return NULL;
  14146. }
  14147. #if !defined(NO_SSL)
  14148. #if defined(OPENSSL_API_1_1)
  14149. if (use_ssl
  14150. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  14151. mg_snprintf(NULL,
  14152. NULL, /* No truncation check for ebuf */
  14153. ebuf,
  14154. ebuf_len,
  14155. "SSL_CTX_new error");
  14156. closesocket(sock);
  14157. mg_free(conn);
  14158. return NULL;
  14159. }
  14160. #else
  14161. if (use_ssl
  14162. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14163. == NULL) {
  14164. mg_snprintf(NULL,
  14165. NULL, /* No truncation check for ebuf */
  14166. ebuf,
  14167. ebuf_len,
  14168. "SSL_CTX_new error");
  14169. closesocket(sock);
  14170. mg_free(conn);
  14171. return NULL;
  14172. }
  14173. #endif /* OPENSSL_API_1_1 */
  14174. #endif /* NO_SSL */
  14175. #if defined(USE_IPV6)
  14176. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14177. : sizeof(conn->client.rsa.sin6);
  14178. psa = (sa.sa.sa_family == AF_INET)
  14179. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14180. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14181. #else
  14182. len = sizeof(conn->client.rsa.sin);
  14183. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14184. #endif
  14185. conn->client.sock = sock;
  14186. conn->client.lsa = sa;
  14187. if (getsockname(sock, psa, &len) != 0) {
  14188. mg_cry_internal(conn,
  14189. "%s: getsockname() failed: %s",
  14190. __func__,
  14191. strerror(ERRNO));
  14192. }
  14193. conn->client.is_ssl = use_ssl ? 1 : 0;
  14194. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14195. mg_snprintf(NULL,
  14196. NULL, /* No truncation check for ebuf */
  14197. ebuf,
  14198. ebuf_len,
  14199. "Can not create mutex");
  14200. #if !defined(NO_SSL)
  14201. SSL_CTX_free(conn->client_ssl_ctx);
  14202. #endif
  14203. closesocket(sock);
  14204. mg_free(conn);
  14205. return NULL;
  14206. }
  14207. #if !defined(NO_SSL)
  14208. if (use_ssl) {
  14209. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  14210. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14211. * SSL_CTX_set_verify call is needed to switch off server
  14212. * certificate checking, which is off by default in OpenSSL and
  14213. * on in yaSSL. */
  14214. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  14215. * SSL_VERIFY_PEER, verify_ssl_server); */
  14216. if (client_options->client_cert) {
  14217. if (!ssl_use_pem_file(&common_client_context,
  14218. &(common_client_context.dd),
  14219. client_options->client_cert,
  14220. NULL)) {
  14221. mg_snprintf(NULL,
  14222. NULL, /* No truncation check for ebuf */
  14223. ebuf,
  14224. ebuf_len,
  14225. "Can not use SSL client certificate");
  14226. SSL_CTX_free(conn->client_ssl_ctx);
  14227. closesocket(sock);
  14228. mg_free(conn);
  14229. return NULL;
  14230. }
  14231. }
  14232. if (client_options->server_cert) {
  14233. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  14234. client_options->server_cert,
  14235. NULL);
  14236. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  14237. } else {
  14238. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  14239. }
  14240. if (!sslize(conn,
  14241. conn->client_ssl_ctx,
  14242. SSL_connect,
  14243. &(conn->phys_ctx->stop_flag))) {
  14244. mg_snprintf(NULL,
  14245. NULL, /* No truncation check for ebuf */
  14246. ebuf,
  14247. ebuf_len,
  14248. "SSL connection error");
  14249. SSL_CTX_free(conn->client_ssl_ctx);
  14250. closesocket(sock);
  14251. mg_free(conn);
  14252. return NULL;
  14253. }
  14254. }
  14255. #endif
  14256. if (0 != set_non_blocking_mode(sock)) {
  14257. mg_cry_internal(conn,
  14258. "Cannot set non-blocking mode for client %s:%i",
  14259. client_options->host,
  14260. client_options->port);
  14261. }
  14262. return conn;
  14263. }
  14264. CIVETWEB_API struct mg_connection *
  14265. mg_connect_client_secure(const struct mg_client_options *client_options,
  14266. char *error_buffer,
  14267. size_t error_buffer_size)
  14268. {
  14269. return mg_connect_client_impl(client_options,
  14270. 1,
  14271. error_buffer,
  14272. error_buffer_size);
  14273. }
  14274. struct mg_connection *
  14275. mg_connect_client(const char *host,
  14276. int port,
  14277. int use_ssl,
  14278. char *error_buffer,
  14279. size_t error_buffer_size)
  14280. {
  14281. struct mg_client_options opts;
  14282. memset(&opts, 0, sizeof(opts));
  14283. opts.host = host;
  14284. opts.port = port;
  14285. return mg_connect_client_impl(&opts,
  14286. use_ssl,
  14287. error_buffer,
  14288. error_buffer_size);
  14289. }
  14290. static const struct {
  14291. const char *proto;
  14292. size_t proto_len;
  14293. unsigned default_port;
  14294. } abs_uri_protocols[] = {{"http://", 7, 80},
  14295. {"https://", 8, 443},
  14296. {"ws://", 5, 80},
  14297. {"wss://", 6, 443},
  14298. {NULL, 0, 0}};
  14299. /* Check if the uri is valid.
  14300. * return 0 for invalid uri,
  14301. * return 1 for *,
  14302. * return 2 for relative uri,
  14303. * return 3 for absolute uri without port,
  14304. * return 4 for absolute uri with port */
  14305. static int
  14306. get_uri_type(const char *uri)
  14307. {
  14308. int i;
  14309. const char *hostend, *portbegin;
  14310. char *portend;
  14311. unsigned long port;
  14312. /* According to the HTTP standard
  14313. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14314. * URI can be an asterisk (*) or should start with slash (relative uri),
  14315. * or it should start with the protocol (absolute uri). */
  14316. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14317. /* asterisk */
  14318. return 1;
  14319. }
  14320. /* Valid URIs according to RFC 3986
  14321. * (https://www.ietf.org/rfc/rfc3986.txt)
  14322. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14323. * and unreserved characters A-Z a-z 0-9 and -._~
  14324. * and % encoded symbols.
  14325. */
  14326. for (i = 0; uri[i] != 0; i++) {
  14327. if (uri[i] < 33) {
  14328. /* control characters and spaces are invalid */
  14329. return 0;
  14330. }
  14331. if (uri[i] > 126) {
  14332. /* non-ascii characters must be % encoded */
  14333. return 0;
  14334. } else {
  14335. switch (uri[i]) {
  14336. case '"': /* 34 */
  14337. case '<': /* 60 */
  14338. case '>': /* 62 */
  14339. case '\\': /* 92 */
  14340. case '^': /* 94 */
  14341. case '`': /* 96 */
  14342. case '{': /* 123 */
  14343. case '|': /* 124 */
  14344. case '}': /* 125 */
  14345. return 0;
  14346. default:
  14347. /* character is ok */
  14348. break;
  14349. }
  14350. }
  14351. }
  14352. /* A relative uri starts with a / character */
  14353. if (uri[0] == '/') {
  14354. /* relative uri */
  14355. return 2;
  14356. }
  14357. /* It could be an absolute uri: */
  14358. /* This function only checks if the uri is valid, not if it is
  14359. * addressing the current server. So civetweb can also be used
  14360. * as a proxy server. */
  14361. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14362. if (mg_strncasecmp(uri,
  14363. abs_uri_protocols[i].proto,
  14364. abs_uri_protocols[i].proto_len)
  14365. == 0) {
  14366. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14367. if (!hostend) {
  14368. return 0;
  14369. }
  14370. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14371. if (!portbegin) {
  14372. return 3;
  14373. }
  14374. port = strtoul(portbegin + 1, &portend, 10);
  14375. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14376. return 0;
  14377. }
  14378. return 4;
  14379. }
  14380. }
  14381. return 0;
  14382. }
  14383. /* Return NULL or the relative uri at the current server */
  14384. static const char *
  14385. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14386. {
  14387. const char *server_domain;
  14388. size_t server_domain_len;
  14389. size_t request_domain_len = 0;
  14390. unsigned long port = 0;
  14391. int i, auth_domain_check_enabled;
  14392. const char *hostbegin = NULL;
  14393. const char *hostend = NULL;
  14394. const char *portbegin;
  14395. char *portend;
  14396. auth_domain_check_enabled =
  14397. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14398. /* DNS is case insensitive, so use case insensitive string compare here
  14399. */
  14400. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14401. if (mg_strncasecmp(uri,
  14402. abs_uri_protocols[i].proto,
  14403. abs_uri_protocols[i].proto_len)
  14404. == 0) {
  14405. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14406. hostend = strchr(hostbegin, '/');
  14407. if (!hostend) {
  14408. return 0;
  14409. }
  14410. portbegin = strchr(hostbegin, ':');
  14411. if ((!portbegin) || (portbegin > hostend)) {
  14412. port = abs_uri_protocols[i].default_port;
  14413. request_domain_len = (size_t)(hostend - hostbegin);
  14414. } else {
  14415. port = strtoul(portbegin + 1, &portend, 10);
  14416. if ((portend != hostend) || (port <= 0)
  14417. || !is_valid_port(port)) {
  14418. return 0;
  14419. }
  14420. request_domain_len = (size_t)(portbegin - hostbegin);
  14421. }
  14422. /* protocol found, port set */
  14423. break;
  14424. }
  14425. }
  14426. if (!port) {
  14427. /* port remains 0 if the protocol is not found */
  14428. return 0;
  14429. }
  14430. /* Check if the request is directed to a different server. */
  14431. /* First check if the port is the same (IPv4 and IPv6). */
  14432. #if defined(USE_IPV6)
  14433. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14434. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14435. /* Request is directed to a different port */
  14436. return 0;
  14437. }
  14438. } else
  14439. #endif
  14440. {
  14441. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14442. /* Request is directed to a different port */
  14443. return 0;
  14444. }
  14445. }
  14446. /* Finally check if the server corresponds to the authentication
  14447. * domain of the server (the server domain).
  14448. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14449. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14450. * but do not allow substrings (like
  14451. * http://notmydomain.com/path/file.ext
  14452. * or http://mydomain.com.fake/path/file.ext).
  14453. */
  14454. if (auth_domain_check_enabled) {
  14455. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14456. server_domain_len = strlen(server_domain);
  14457. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14458. return 0;
  14459. }
  14460. if ((request_domain_len == server_domain_len)
  14461. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14462. /* Request is directed to this server - full name match. */
  14463. } else {
  14464. if (request_domain_len < (server_domain_len + 2)) {
  14465. /* Request is directed to another server: The server name
  14466. * is longer than the request name.
  14467. * Drop this case here to avoid overflows in the
  14468. * following checks. */
  14469. return 0;
  14470. }
  14471. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14472. /* Request is directed to another server: It could be a
  14473. * substring
  14474. * like notmyserver.com */
  14475. return 0;
  14476. }
  14477. if (0
  14478. != memcmp(server_domain,
  14479. hostbegin + request_domain_len - server_domain_len,
  14480. server_domain_len)) {
  14481. /* Request is directed to another server:
  14482. * The server name is different. */
  14483. return 0;
  14484. }
  14485. }
  14486. }
  14487. return hostend;
  14488. }
  14489. static int
  14490. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14491. {
  14492. if (ebuf_len > 0) {
  14493. ebuf[0] = '\0';
  14494. }
  14495. *err = 0;
  14496. reset_per_request_attributes(conn);
  14497. if (!conn) {
  14498. mg_snprintf(conn,
  14499. NULL, /* No truncation check for ebuf */
  14500. ebuf,
  14501. ebuf_len,
  14502. "%s",
  14503. "Internal error");
  14504. *err = 500;
  14505. return 0;
  14506. }
  14507. /* Set the time the request was received. This value should be used for
  14508. * timeouts. */
  14509. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14510. conn->request_len =
  14511. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14512. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14513. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14514. mg_snprintf(conn,
  14515. NULL, /* No truncation check for ebuf */
  14516. ebuf,
  14517. ebuf_len,
  14518. "%s",
  14519. "Invalid message size");
  14520. *err = 500;
  14521. return 0;
  14522. }
  14523. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14524. mg_snprintf(conn,
  14525. NULL, /* No truncation check for ebuf */
  14526. ebuf,
  14527. ebuf_len,
  14528. "%s",
  14529. "Message too large");
  14530. *err = 413;
  14531. return 0;
  14532. }
  14533. if (conn->request_len <= 0) {
  14534. if (conn->data_len > 0) {
  14535. mg_snprintf(conn,
  14536. NULL, /* No truncation check for ebuf */
  14537. ebuf,
  14538. ebuf_len,
  14539. "%s",
  14540. "Malformed message");
  14541. *err = 400;
  14542. } else {
  14543. /* Server did not recv anything -> just close the connection */
  14544. conn->must_close = 1;
  14545. mg_snprintf(conn,
  14546. NULL, /* No truncation check for ebuf */
  14547. ebuf,
  14548. ebuf_len,
  14549. "%s",
  14550. "No data received");
  14551. *err = 0;
  14552. }
  14553. return 0;
  14554. }
  14555. return 1;
  14556. }
  14557. static int
  14558. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14559. {
  14560. const char *cl;
  14561. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14562. return 0;
  14563. }
  14564. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14565. <= 0) {
  14566. mg_snprintf(conn,
  14567. NULL, /* No truncation check for ebuf */
  14568. ebuf,
  14569. ebuf_len,
  14570. "%s",
  14571. "Bad request");
  14572. *err = 400;
  14573. return 0;
  14574. }
  14575. /* Message is a valid request */
  14576. /* Is there a "host" ? */
  14577. conn->host = alloc_get_host(conn);
  14578. if (!conn->host) {
  14579. mg_snprintf(conn,
  14580. NULL, /* No truncation check for ebuf */
  14581. ebuf,
  14582. ebuf_len,
  14583. "%s",
  14584. "Bad request: Host mismatch");
  14585. *err = 400;
  14586. return 0;
  14587. }
  14588. /* Do we know the content length? */
  14589. if ((cl = get_header(conn->request_info.http_headers,
  14590. conn->request_info.num_headers,
  14591. "Content-Length"))
  14592. != NULL) {
  14593. /* Request/response has content length set */
  14594. char *endptr = NULL;
  14595. conn->content_len = strtoll(cl, &endptr, 10);
  14596. if (endptr == cl) {
  14597. mg_snprintf(conn,
  14598. NULL, /* No truncation check for ebuf */
  14599. ebuf,
  14600. ebuf_len,
  14601. "%s",
  14602. "Bad request");
  14603. *err = 411;
  14604. return 0;
  14605. }
  14606. /* Publish the content length back to the request info. */
  14607. conn->request_info.content_length = conn->content_len;
  14608. } else if ((cl = get_header(conn->request_info.http_headers,
  14609. conn->request_info.num_headers,
  14610. "Transfer-Encoding"))
  14611. != NULL
  14612. && !mg_strcasecmp(cl, "chunked")) {
  14613. conn->is_chunked = 1;
  14614. conn->content_len = -1; /* unknown content length */
  14615. } else {
  14616. const struct mg_http_method_info *meth =
  14617. get_http_method_info(conn->request_info.request_method);
  14618. if (!meth) {
  14619. /* No valid HTTP method */
  14620. mg_snprintf(conn,
  14621. NULL, /* No truncation check for ebuf */
  14622. ebuf,
  14623. ebuf_len,
  14624. "%s",
  14625. "Bad request");
  14626. *err = 411;
  14627. return 0;
  14628. }
  14629. if (meth->request_has_body) {
  14630. /* POST or PUT request without content length set */
  14631. conn->content_len = -1; /* unknown content length */
  14632. } else {
  14633. /* Other request */
  14634. conn->content_len = 0; /* No content */
  14635. }
  14636. }
  14637. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14638. return 1;
  14639. }
  14640. /* conn is assumed to be valid in this internal function */
  14641. static int
  14642. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14643. {
  14644. const char *cl;
  14645. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14646. return 0;
  14647. }
  14648. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14649. <= 0) {
  14650. mg_snprintf(conn,
  14651. NULL, /* No truncation check for ebuf */
  14652. ebuf,
  14653. ebuf_len,
  14654. "%s",
  14655. "Bad response");
  14656. *err = 400;
  14657. return 0;
  14658. }
  14659. /* Message is a valid response */
  14660. /* Do we know the content length? */
  14661. if ((cl = get_header(conn->response_info.http_headers,
  14662. conn->response_info.num_headers,
  14663. "Content-Length"))
  14664. != NULL) {
  14665. /* Request/response has content length set */
  14666. char *endptr = NULL;
  14667. conn->content_len = strtoll(cl, &endptr, 10);
  14668. if (endptr == cl) {
  14669. mg_snprintf(conn,
  14670. NULL, /* No truncation check for ebuf */
  14671. ebuf,
  14672. ebuf_len,
  14673. "%s",
  14674. "Bad request");
  14675. *err = 411;
  14676. return 0;
  14677. }
  14678. /* Publish the content length back to the response info. */
  14679. conn->response_info.content_length = conn->content_len;
  14680. /* TODO: check if it is still used in response_info */
  14681. conn->request_info.content_length = conn->content_len;
  14682. } else if ((cl = get_header(conn->response_info.http_headers,
  14683. conn->response_info.num_headers,
  14684. "Transfer-Encoding"))
  14685. != NULL
  14686. && !mg_strcasecmp(cl, "chunked")) {
  14687. conn->is_chunked = 1;
  14688. conn->content_len = -1; /* unknown content length */
  14689. } else {
  14690. conn->content_len = -1; /* unknown content length */
  14691. }
  14692. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14693. return 1;
  14694. }
  14695. int
  14696. mg_get_response(struct mg_connection *conn,
  14697. char *ebuf,
  14698. size_t ebuf_len,
  14699. int timeout)
  14700. {
  14701. int err, ret;
  14702. char txt[32]; /* will not overflow */
  14703. char *save_timeout;
  14704. char *new_timeout;
  14705. if (ebuf_len > 0) {
  14706. ebuf[0] = '\0';
  14707. }
  14708. if (!conn) {
  14709. mg_snprintf(conn,
  14710. NULL, /* No truncation check for ebuf */
  14711. ebuf,
  14712. ebuf_len,
  14713. "%s",
  14714. "Parameter error");
  14715. return -1;
  14716. }
  14717. /* Implementation of API function for HTTP clients */
  14718. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14719. if (timeout >= 0) {
  14720. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14721. new_timeout = txt;
  14722. /* Not required for non-blocking sockets.
  14723. set_sock_timeout(conn->client.sock, timeout);
  14724. */
  14725. } else {
  14726. new_timeout = NULL;
  14727. }
  14728. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14729. ret = get_response(conn, ebuf, ebuf_len, &err);
  14730. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14731. #if defined(MG_LEGACY_INTERFACE)
  14732. /* TODO: 1) uri is deprecated;
  14733. * 2) here, ri.uri is the http response code */
  14734. conn->request_info.uri = conn->request_info.request_uri;
  14735. #endif
  14736. conn->request_info.local_uri = conn->request_info.request_uri;
  14737. /* TODO (mid): Define proper return values - maybe return length?
  14738. * For the first test use <0 for error and >0 for OK */
  14739. return (ret == 0) ? -1 : +1;
  14740. }
  14741. struct mg_connection *
  14742. mg_download(const char *host,
  14743. int port,
  14744. int use_ssl,
  14745. char *ebuf,
  14746. size_t ebuf_len,
  14747. const char *fmt,
  14748. ...)
  14749. {
  14750. struct mg_connection *conn;
  14751. va_list ap;
  14752. int i;
  14753. int reqerr;
  14754. if (ebuf_len > 0) {
  14755. ebuf[0] = '\0';
  14756. }
  14757. va_start(ap, fmt);
  14758. /* open a connection */
  14759. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14760. if (conn != NULL) {
  14761. i = mg_vprintf(conn, fmt, ap);
  14762. if (i <= 0) {
  14763. mg_snprintf(conn,
  14764. NULL, /* No truncation check for ebuf */
  14765. ebuf,
  14766. ebuf_len,
  14767. "%s",
  14768. "Error sending request");
  14769. } else {
  14770. get_response(conn, ebuf, ebuf_len, &reqerr);
  14771. #if defined(MG_LEGACY_INTERFACE)
  14772. /* TODO: 1) uri is deprecated;
  14773. * 2) here, ri.uri is the http response code */
  14774. conn->request_info.uri = conn->request_info.request_uri;
  14775. #endif
  14776. conn->request_info.local_uri = conn->request_info.request_uri;
  14777. }
  14778. }
  14779. /* if an error occurred, close the connection */
  14780. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14781. mg_close_connection(conn);
  14782. conn = NULL;
  14783. }
  14784. va_end(ap);
  14785. return conn;
  14786. }
  14787. struct websocket_client_thread_data {
  14788. struct mg_connection *conn;
  14789. mg_websocket_data_handler data_handler;
  14790. mg_websocket_close_handler close_handler;
  14791. void *callback_data;
  14792. };
  14793. #if defined(USE_WEBSOCKET)
  14794. #if defined(_WIN32)
  14795. static unsigned __stdcall websocket_client_thread(void *data)
  14796. #else
  14797. static void *
  14798. websocket_client_thread(void *data)
  14799. #endif
  14800. {
  14801. struct websocket_client_thread_data *cdata =
  14802. (struct websocket_client_thread_data *)data;
  14803. #if !defined(_WIN32)
  14804. struct sigaction sa;
  14805. /* Ignore SIGPIPE */
  14806. memset(&sa, 0, sizeof(sa));
  14807. sa.sa_handler = SIG_IGN;
  14808. sigaction(SIGPIPE, &sa, NULL);
  14809. #endif
  14810. mg_set_thread_name("ws-clnt");
  14811. if (cdata->conn->phys_ctx) {
  14812. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14813. /* 3 indicates a websocket client thread */
  14814. /* TODO: check if conn->phys_ctx can be set */
  14815. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14816. 3);
  14817. }
  14818. }
  14819. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14820. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14821. if (cdata->close_handler != NULL) {
  14822. cdata->close_handler(cdata->conn, cdata->callback_data);
  14823. }
  14824. /* The websocket_client context has only this thread. If it runs out,
  14825. set the stop_flag to 2 (= "stopped"). */
  14826. cdata->conn->phys_ctx->stop_flag = 2;
  14827. mg_free((void *)cdata);
  14828. #if defined(_WIN32)
  14829. return 0;
  14830. #else
  14831. return NULL;
  14832. #endif
  14833. }
  14834. #endif
  14835. struct mg_connection *
  14836. mg_connect_websocket_client(const char *host,
  14837. int port,
  14838. int use_ssl,
  14839. char *error_buffer,
  14840. size_t error_buffer_size,
  14841. const char *path,
  14842. const char *origin,
  14843. mg_websocket_data_handler data_func,
  14844. mg_websocket_close_handler close_func,
  14845. void *user_data)
  14846. {
  14847. struct mg_connection *conn = NULL;
  14848. #if defined(USE_WEBSOCKET)
  14849. struct mg_context *newctx = NULL;
  14850. struct websocket_client_thread_data *thread_data;
  14851. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14852. static const char *handshake_req;
  14853. if (origin != NULL) {
  14854. handshake_req = "GET %s HTTP/1.1\r\n"
  14855. "Host: %s\r\n"
  14856. "Upgrade: websocket\r\n"
  14857. "Connection: Upgrade\r\n"
  14858. "Sec-WebSocket-Key: %s\r\n"
  14859. "Sec-WebSocket-Version: 13\r\n"
  14860. "Origin: %s\r\n"
  14861. "\r\n";
  14862. } else {
  14863. handshake_req = "GET %s HTTP/1.1\r\n"
  14864. "Host: %s\r\n"
  14865. "Upgrade: websocket\r\n"
  14866. "Connection: Upgrade\r\n"
  14867. "Sec-WebSocket-Key: %s\r\n"
  14868. "Sec-WebSocket-Version: 13\r\n"
  14869. "\r\n";
  14870. }
  14871. #if defined(__clang__)
  14872. #pragma clang diagnostic push
  14873. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14874. #endif
  14875. /* Establish the client connection and request upgrade */
  14876. conn = mg_download(host,
  14877. port,
  14878. use_ssl,
  14879. error_buffer,
  14880. error_buffer_size,
  14881. handshake_req,
  14882. path,
  14883. host,
  14884. magic,
  14885. origin);
  14886. #if defined(__clang__)
  14887. #pragma clang diagnostic pop
  14888. #endif
  14889. /* Connection object will be null if something goes wrong */
  14890. if (conn == NULL) {
  14891. if (!*error_buffer) {
  14892. /* There should be already an error message */
  14893. mg_snprintf(conn,
  14894. NULL, /* No truncation check for ebuf */
  14895. error_buffer,
  14896. error_buffer_size,
  14897. "Unexpected error");
  14898. }
  14899. return NULL;
  14900. }
  14901. if (conn->response_info.status_code != 101) {
  14902. /* We sent an "upgrade" request. For a correct websocket
  14903. * protocol handshake, we expect a "101 Continue" response.
  14904. * Otherwise it is a protocol violation. Maybe the HTTP
  14905. * Server does not know websockets. */
  14906. if (!*error_buffer) {
  14907. /* set an error, if not yet set */
  14908. mg_snprintf(conn,
  14909. NULL, /* No truncation check for ebuf */
  14910. error_buffer,
  14911. error_buffer_size,
  14912. "Unexpected server reply");
  14913. }
  14914. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14915. mg_free(conn);
  14916. return NULL;
  14917. }
  14918. /* For client connections, mg_context is fake. Since we need to set a
  14919. * callback function, we need to create a copy and modify it. */
  14920. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14921. if (!newctx) {
  14922. DEBUG_TRACE("%s\r\n", "Out of memory");
  14923. mg_free(conn);
  14924. return NULL;
  14925. }
  14926. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14927. newctx->user_data = user_data;
  14928. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14929. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14930. newctx->worker_threadids =
  14931. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14932. sizeof(pthread_t),
  14933. newctx);
  14934. conn->phys_ctx = newctx;
  14935. conn->dom_ctx = &(newctx->dd);
  14936. thread_data = (struct websocket_client_thread_data *)
  14937. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14938. if (!thread_data) {
  14939. DEBUG_TRACE("%s\r\n", "Out of memory");
  14940. mg_free(newctx);
  14941. mg_free(conn);
  14942. return NULL;
  14943. }
  14944. thread_data->conn = conn;
  14945. thread_data->data_handler = data_func;
  14946. thread_data->close_handler = close_func;
  14947. thread_data->callback_data = user_data;
  14948. /* Start a thread to read the websocket client connection
  14949. * This thread will automatically stop when mg_disconnect is
  14950. * called on the client connection */
  14951. if (mg_start_thread_with_id(websocket_client_thread,
  14952. (void *)thread_data,
  14953. newctx->worker_threadids)
  14954. != 0) {
  14955. mg_free((void *)thread_data);
  14956. mg_free((void *)newctx->worker_threadids);
  14957. mg_free((void *)newctx);
  14958. mg_free((void *)conn);
  14959. conn = NULL;
  14960. DEBUG_TRACE("%s",
  14961. "Websocket client connect thread could not be started\r\n");
  14962. }
  14963. #else
  14964. /* Appease "unused parameter" warnings */
  14965. (void)host;
  14966. (void)port;
  14967. (void)use_ssl;
  14968. (void)error_buffer;
  14969. (void)error_buffer_size;
  14970. (void)path;
  14971. (void)origin;
  14972. (void)user_data;
  14973. (void)data_func;
  14974. (void)close_func;
  14975. #endif
  14976. return conn;
  14977. }
  14978. /* Prepare connection data structure */
  14979. static void
  14980. init_connection(struct mg_connection *conn)
  14981. {
  14982. /* Is keep alive allowed by the server */
  14983. int keep_alive_enabled =
  14984. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  14985. if (!keep_alive_enabled) {
  14986. conn->must_close = 1;
  14987. }
  14988. /* Important: on new connection, reset the receiving buffer. Credit
  14989. * goes to crule42. */
  14990. conn->data_len = 0;
  14991. conn->handled_requests = 0;
  14992. mg_set_user_connection_data(conn, NULL);
  14993. #if defined(USE_SERVER_STATS)
  14994. conn->conn_state = 2; /* init */
  14995. #endif
  14996. /* call the init_connection callback if assigned */
  14997. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  14998. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14999. void *conn_data = NULL;
  15000. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15001. mg_set_user_connection_data(conn, conn_data);
  15002. }
  15003. }
  15004. }
  15005. /* Process a connection - may handle multiple requests
  15006. * using the same connection.
  15007. * Must be called with a valid connection (conn and
  15008. * conn->phys_ctx must be valid).
  15009. */
  15010. static void
  15011. process_new_connection(struct mg_connection *conn)
  15012. {
  15013. struct mg_request_info *ri = &conn->request_info;
  15014. int keep_alive, discard_len;
  15015. char ebuf[100];
  15016. const char *hostend;
  15017. int reqerr, uri_type;
  15018. #if defined(USE_SERVER_STATS)
  15019. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15020. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15021. if (mcon > (conn->phys_ctx->max_connections)) {
  15022. /* could use atomic compare exchange, but this
  15023. * seems overkill for statistics data */
  15024. conn->phys_ctx->max_connections = mcon;
  15025. }
  15026. #endif
  15027. init_connection(conn);
  15028. DEBUG_TRACE("Start processing connection from %s",
  15029. conn->request_info.remote_addr);
  15030. /* Loop over multiple requests sent using the same connection
  15031. * (while "keep alive"). */
  15032. do {
  15033. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15034. conn->handled_requests + 1);
  15035. #if defined(USE_SERVER_STATS)
  15036. conn->conn_state = 3; /* ready */
  15037. #endif
  15038. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15039. /* The request sent by the client could not be understood by
  15040. * the server, or it was incomplete or a timeout. Send an
  15041. * error message and close the connection. */
  15042. if (reqerr > 0) {
  15043. DEBUG_ASSERT(ebuf[0] != '\0');
  15044. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15045. }
  15046. } else if (strcmp(ri->http_version, "1.0")
  15047. && strcmp(ri->http_version, "1.1")) {
  15048. mg_snprintf(conn,
  15049. NULL, /* No truncation check for ebuf */
  15050. ebuf,
  15051. sizeof(ebuf),
  15052. "Bad HTTP version: [%s]",
  15053. ri->http_version);
  15054. mg_send_http_error(conn, 505, "%s", ebuf);
  15055. }
  15056. if (ebuf[0] == '\0') {
  15057. uri_type = get_uri_type(conn->request_info.request_uri);
  15058. switch (uri_type) {
  15059. case 1:
  15060. /* Asterisk */
  15061. conn->request_info.local_uri = NULL;
  15062. break;
  15063. case 2:
  15064. /* relative uri */
  15065. conn->request_info.local_uri = conn->request_info.request_uri;
  15066. break;
  15067. case 3:
  15068. case 4:
  15069. /* absolute uri (with/without port) */
  15070. hostend = get_rel_url_at_current_server(
  15071. conn->request_info.request_uri, conn);
  15072. if (hostend) {
  15073. conn->request_info.local_uri = hostend;
  15074. } else {
  15075. conn->request_info.local_uri = NULL;
  15076. }
  15077. break;
  15078. default:
  15079. mg_snprintf(conn,
  15080. NULL, /* No truncation check for ebuf */
  15081. ebuf,
  15082. sizeof(ebuf),
  15083. "Invalid URI");
  15084. mg_send_http_error(conn, 400, "%s", ebuf);
  15085. conn->request_info.local_uri = NULL;
  15086. break;
  15087. }
  15088. #if defined(MG_LEGACY_INTERFACE)
  15089. /* Legacy before split into local_uri and request_uri */
  15090. conn->request_info.uri = conn->request_info.local_uri;
  15091. #endif
  15092. }
  15093. DEBUG_TRACE("http: %s, error: %s",
  15094. (ri->http_version ? ri->http_version : "none"),
  15095. (ebuf[0] ? ebuf : "none"));
  15096. if (ebuf[0] == '\0') {
  15097. if (conn->request_info.local_uri) {
  15098. /* handle request to local server */
  15099. #if defined(USE_SERVER_STATS)
  15100. conn->conn_state = 4; /* processing */
  15101. #endif
  15102. handle_request(conn);
  15103. #if defined(USE_SERVER_STATS)
  15104. conn->conn_state = 5; /* processed */
  15105. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15106. conn->consumed_content);
  15107. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15108. conn->num_bytes_sent);
  15109. #endif
  15110. DEBUG_TRACE("%s", "handle_request done");
  15111. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15112. conn->phys_ctx->callbacks.end_request(conn,
  15113. conn->status_code);
  15114. DEBUG_TRACE("%s", "end_request callback done");
  15115. }
  15116. log_access(conn);
  15117. } else {
  15118. /* TODO: handle non-local request (PROXY) */
  15119. conn->must_close = 1;
  15120. }
  15121. } else {
  15122. conn->must_close = 1;
  15123. }
  15124. if (ri->remote_user != NULL) {
  15125. mg_free((void *)ri->remote_user);
  15126. /* Important! When having connections with and without auth
  15127. * would cause double free and then crash */
  15128. ri->remote_user = NULL;
  15129. }
  15130. /* NOTE(lsm): order is important here. should_keep_alive() call
  15131. * is using parsed request, which will be invalid after
  15132. * memmove's below.
  15133. * Therefore, memorize should_keep_alive() result now for later
  15134. * use in loop exit condition. */
  15135. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15136. && (conn->content_len >= 0);
  15137. /* Discard all buffered data for this request */
  15138. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  15139. && ((conn->request_len + conn->content_len)
  15140. < (int64_t)conn->data_len))
  15141. ? (int)(conn->request_len + conn->content_len)
  15142. : conn->data_len;
  15143. DEBUG_ASSERT(discard_len >= 0);
  15144. if (discard_len < 0) {
  15145. DEBUG_TRACE("internal error: discard_len = %li",
  15146. (long int)discard_len);
  15147. break;
  15148. }
  15149. conn->data_len -= discard_len;
  15150. if (conn->data_len > 0) {
  15151. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  15152. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  15153. }
  15154. DEBUG_ASSERT(conn->data_len >= 0);
  15155. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15156. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15157. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15158. (long int)conn->data_len,
  15159. (long int)conn->buf_size);
  15160. break;
  15161. }
  15162. conn->handled_requests++;
  15163. } while (keep_alive);
  15164. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15165. conn->request_info.remote_addr,
  15166. difftime(time(NULL), conn->conn_birth_time));
  15167. close_connection(conn);
  15168. #if defined(USE_SERVER_STATS)
  15169. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15170. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15171. #endif
  15172. }
  15173. #if defined(ALTERNATIVE_QUEUE)
  15174. static void
  15175. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15176. {
  15177. unsigned int i;
  15178. while (!ctx->stop_flag) {
  15179. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15180. /* find a free worker slot and signal it */
  15181. if (ctx->client_socks[i].in_use == 0) {
  15182. ctx->client_socks[i] = *sp;
  15183. ctx->client_socks[i].in_use = 1;
  15184. event_signal(ctx->client_wait_events[i]);
  15185. return;
  15186. }
  15187. }
  15188. /* queue is full */
  15189. mg_sleep(1);
  15190. }
  15191. }
  15192. static int
  15193. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15194. {
  15195. DEBUG_TRACE("%s", "going idle");
  15196. ctx->client_socks[thread_index].in_use = 0;
  15197. event_wait(ctx->client_wait_events[thread_index]);
  15198. *sp = ctx->client_socks[thread_index];
  15199. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15200. return !ctx->stop_flag;
  15201. }
  15202. #else /* ALTERNATIVE_QUEUE */
  15203. /* Worker threads take accepted socket from the queue */
  15204. static int
  15205. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15206. {
  15207. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15208. (void)thread_index;
  15209. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15210. DEBUG_TRACE("%s", "going idle");
  15211. /* If the queue is empty, wait. We're idle at this point. */
  15212. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15213. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15214. }
  15215. /* If we're stopping, sq_head may be equal to sq_tail. */
  15216. if (ctx->sq_head > ctx->sq_tail) {
  15217. /* Copy socket from the queue and increment tail */
  15218. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15219. ctx->sq_tail++;
  15220. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15221. /* Wrap pointers if needed */
  15222. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15223. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15224. ctx->sq_head -= QUEUE_SIZE(ctx);
  15225. }
  15226. }
  15227. (void)pthread_cond_signal(&ctx->sq_empty);
  15228. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15229. return !ctx->stop_flag;
  15230. #undef QUEUE_SIZE
  15231. }
  15232. /* Master thread adds accepted socket to a queue */
  15233. static void
  15234. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15235. {
  15236. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15237. if (!ctx) {
  15238. return;
  15239. }
  15240. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15241. /* If the queue is full, wait */
  15242. while ((ctx->stop_flag == 0)
  15243. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15244. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15245. }
  15246. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15247. /* Copy socket to the queue and increment head */
  15248. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15249. ctx->sq_head++;
  15250. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15251. }
  15252. (void)pthread_cond_signal(&ctx->sq_full);
  15253. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15254. #undef QUEUE_SIZE
  15255. }
  15256. #endif /* ALTERNATIVE_QUEUE */
  15257. struct worker_thread_args {
  15258. struct mg_context *ctx;
  15259. int index;
  15260. };
  15261. static void *
  15262. worker_thread_run(struct worker_thread_args *thread_args)
  15263. {
  15264. struct mg_context *ctx = thread_args->ctx;
  15265. struct mg_connection *conn;
  15266. struct mg_workerTLS tls;
  15267. #if defined(MG_LEGACY_INTERFACE)
  15268. uint32_t addr;
  15269. #endif
  15270. mg_set_thread_name("worker");
  15271. tls.is_master = 0;
  15272. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15273. #if defined(_WIN32)
  15274. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15275. #endif
  15276. /* Initialize thread local storage before calling any callback */
  15277. pthread_setspecific(sTlsKey, &tls);
  15278. if (ctx->callbacks.init_thread) {
  15279. /* call init_thread for a worker thread (type 1) */
  15280. ctx->callbacks.init_thread(ctx, 1);
  15281. }
  15282. /* Connection structure has been pre-allocated */
  15283. if (((int)thread_args->index < 0)
  15284. || ((unsigned)thread_args->index
  15285. >= (unsigned)ctx->cfg_worker_threads)) {
  15286. mg_cry_internal(fc(ctx),
  15287. "Internal error: Invalid worker index %i",
  15288. (int)thread_args->index);
  15289. return NULL;
  15290. }
  15291. conn = ctx->worker_connections + thread_args->index;
  15292. /* Request buffers are not pre-allocated. They are private to the
  15293. * request and do not contain any state information that might be
  15294. * of interest to anyone observing a server status. */
  15295. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15296. if (conn->buf == NULL) {
  15297. mg_cry_internal(fc(ctx),
  15298. "Out of memory: Cannot allocate buffer for worker %i",
  15299. (int)thread_args->index);
  15300. return NULL;
  15301. }
  15302. conn->buf_size = (int)ctx->max_request_size;
  15303. conn->phys_ctx = ctx;
  15304. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15305. conn->host = NULL; /* until we have more information. */
  15306. conn->thread_index = thread_args->index;
  15307. conn->request_info.user_data = ctx->user_data;
  15308. /* Allocate a mutex for this connection to allow communication both
  15309. * within the request handler and from elsewhere in the application
  15310. */
  15311. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15312. mg_free(conn->buf);
  15313. mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
  15314. return NULL;
  15315. }
  15316. #if defined(USE_SERVER_STATS)
  15317. conn->conn_state = 1; /* not consumed */
  15318. #endif
  15319. #if defined(ALTERNATIVE_QUEUE)
  15320. while ((ctx->stop_flag == 0)
  15321. && consume_socket(ctx, &conn->client, conn->thread_index)) {
  15322. #else
  15323. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15324. * signal sq_empty condvar to wake up the master waiting in
  15325. * produce_socket() */
  15326. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  15327. #endif
  15328. conn->conn_birth_time = time(NULL);
  15329. /* Fill in IP, port info early so even if SSL setup below fails,
  15330. * error handler would have the corresponding info.
  15331. * Thanks to Johannes Winkelmann for the patch.
  15332. */
  15333. #if defined(USE_IPV6)
  15334. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15335. conn->request_info.remote_port =
  15336. ntohs(conn->client.rsa.sin6.sin6_port);
  15337. } else
  15338. #endif
  15339. {
  15340. conn->request_info.remote_port =
  15341. ntohs(conn->client.rsa.sin.sin_port);
  15342. }
  15343. sockaddr_to_string(conn->request_info.remote_addr,
  15344. sizeof(conn->request_info.remote_addr),
  15345. &conn->client.rsa);
  15346. DEBUG_TRACE("Start processing connection from %s",
  15347. conn->request_info.remote_addr);
  15348. conn->request_info.is_ssl = conn->client.is_ssl;
  15349. if (conn->client.is_ssl) {
  15350. #if !defined(NO_SSL)
  15351. /* HTTPS connection */
  15352. if (sslize(conn,
  15353. conn->dom_ctx->ssl_ctx,
  15354. SSL_accept,
  15355. &(conn->phys_ctx->stop_flag))) {
  15356. /* conn->dom_ctx is set in get_request */
  15357. /* Get SSL client certificate information (if set) */
  15358. ssl_get_client_cert_info(conn);
  15359. /* process HTTPS connection */
  15360. process_new_connection(conn);
  15361. /* Free client certificate info */
  15362. if (conn->request_info.client_cert) {
  15363. mg_free((void *)(conn->request_info.client_cert->subject));
  15364. mg_free((void *)(conn->request_info.client_cert->issuer));
  15365. mg_free((void *)(conn->request_info.client_cert->serial));
  15366. mg_free((void *)(conn->request_info.client_cert->finger));
  15367. /* Free certificate memory */
  15368. X509_free(
  15369. (X509 *)conn->request_info.client_cert->peer_cert);
  15370. conn->request_info.client_cert->peer_cert = 0;
  15371. conn->request_info.client_cert->subject = 0;
  15372. conn->request_info.client_cert->issuer = 0;
  15373. conn->request_info.client_cert->serial = 0;
  15374. conn->request_info.client_cert->finger = 0;
  15375. mg_free(conn->request_info.client_cert);
  15376. conn->request_info.client_cert = 0;
  15377. }
  15378. } else {
  15379. /* make sure the connection is cleaned up on SSL failure */
  15380. close_connection(conn);
  15381. }
  15382. #endif
  15383. } else {
  15384. /* process HTTP connection */
  15385. process_new_connection(conn);
  15386. }
  15387. DEBUG_TRACE("%s", "Connection closed");
  15388. }
  15389. pthread_setspecific(sTlsKey, NULL);
  15390. #if defined(_WIN32)
  15391. CloseHandle(tls.pthread_cond_helper_mutex);
  15392. #endif
  15393. pthread_mutex_destroy(&conn->mutex);
  15394. /* Free the request buffer. */
  15395. conn->buf_size = 0;
  15396. mg_free(conn->buf);
  15397. conn->buf = NULL;
  15398. #if defined(USE_SERVER_STATS)
  15399. conn->conn_state = 9; /* done */
  15400. #endif
  15401. DEBUG_TRACE("%s", "exiting");
  15402. return NULL;
  15403. }
  15404. /* Threads have different return types on Windows and Unix. */
  15405. #if defined(_WIN32)
  15406. static unsigned __stdcall worker_thread(void *thread_func_param)
  15407. {
  15408. struct worker_thread_args *pwta =
  15409. (struct worker_thread_args *)thread_func_param;
  15410. worker_thread_run(pwta);
  15411. mg_free(thread_func_param);
  15412. return 0;
  15413. }
  15414. #else
  15415. static void *
  15416. worker_thread(void *thread_func_param)
  15417. {
  15418. struct worker_thread_args *pwta =
  15419. (struct worker_thread_args *)thread_func_param;
  15420. struct sigaction sa;
  15421. /* Ignore SIGPIPE */
  15422. memset(&sa, 0, sizeof(sa));
  15423. sa.sa_handler = SIG_IGN;
  15424. sigaction(SIGPIPE, &sa, NULL);
  15425. worker_thread_run(pwta);
  15426. mg_free(thread_func_param);
  15427. return NULL;
  15428. }
  15429. #endif /* _WIN32 */
  15430. /* This is an internal function, thus all arguments are expected to be
  15431. * valid - a NULL check is not required. */
  15432. static void
  15433. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15434. {
  15435. struct socket so;
  15436. char src_addr[IP_ADDR_STR_LEN];
  15437. socklen_t len = sizeof(so.rsa);
  15438. int on = 1;
  15439. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15440. == INVALID_SOCKET) {
  15441. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15442. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15443. mg_cry_internal(fc(ctx),
  15444. "%s: %s is not allowed to connect",
  15445. __func__,
  15446. src_addr);
  15447. closesocket(so.sock);
  15448. } else {
  15449. /* Put so socket structure into the queue */
  15450. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15451. set_close_on_exec(so.sock, fc(ctx));
  15452. so.is_ssl = listener->is_ssl;
  15453. so.ssl_redir = listener->ssl_redir;
  15454. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15455. mg_cry_internal(fc(ctx),
  15456. "%s: getsockname() failed: %s",
  15457. __func__,
  15458. strerror(ERRNO));
  15459. }
  15460. /* Set TCP keep-alive. This is needed because if HTTP-level
  15461. * keep-alive
  15462. * is enabled, and client resets the connection, server won't get
  15463. * TCP FIN or RST and will keep the connection open forever. With
  15464. * TCP keep-alive, next keep-alive handshake will figure out that
  15465. * the client is down and will close the server end.
  15466. * Thanks to Igor Klopov who suggested the patch. */
  15467. if (setsockopt(so.sock,
  15468. SOL_SOCKET,
  15469. SO_KEEPALIVE,
  15470. (SOCK_OPT_TYPE)&on,
  15471. sizeof(on))
  15472. != 0) {
  15473. mg_cry_internal(
  15474. fc(ctx),
  15475. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15476. __func__,
  15477. strerror(ERRNO));
  15478. }
  15479. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15480. * to effectively fill up the underlying IP packet payload and
  15481. * reduce the overhead of sending lots of small buffers. However
  15482. * this hurts the server's throughput (ie. operations per second)
  15483. * when HTTP 1.1 persistent connections are used and the responses
  15484. * are relatively small (eg. less than 1400 bytes).
  15485. */
  15486. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15487. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15488. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15489. mg_cry_internal(
  15490. fc(ctx),
  15491. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15492. __func__,
  15493. strerror(ERRNO));
  15494. }
  15495. }
  15496. /* We are using non-blocking sockets. Thus, the
  15497. * set_sock_timeout(so.sock, timeout);
  15498. * call is no longer required. */
  15499. /* The "non blocking" property should already be
  15500. * inherited from the parent socket. Set it for
  15501. * non-compliant socket implementations. */
  15502. set_non_blocking_mode(so.sock);
  15503. so.in_use = 0;
  15504. produce_socket(ctx, &so);
  15505. }
  15506. }
  15507. static void
  15508. master_thread_run(void *thread_func_param)
  15509. {
  15510. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  15511. struct mg_workerTLS tls;
  15512. struct pollfd *pfd;
  15513. unsigned int i;
  15514. unsigned int workerthreadcount;
  15515. if (!ctx) {
  15516. return;
  15517. }
  15518. mg_set_thread_name("master");
  15519. /* Increase priority of the master thread */
  15520. #if defined(_WIN32)
  15521. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15522. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15523. int min_prio = sched_get_priority_min(SCHED_RR);
  15524. int max_prio = sched_get_priority_max(SCHED_RR);
  15525. if ((min_prio >= 0) && (max_prio >= 0)
  15526. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15527. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15528. struct sched_param sched_param = {0};
  15529. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15530. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15531. }
  15532. #endif
  15533. /* Initialize thread local storage */
  15534. #if defined(_WIN32)
  15535. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15536. #endif
  15537. tls.is_master = 1;
  15538. pthread_setspecific(sTlsKey, &tls);
  15539. if (ctx->callbacks.init_thread) {
  15540. /* Callback for the master thread (type 0) */
  15541. ctx->callbacks.init_thread(ctx, 0);
  15542. }
  15543. /* Server starts *now* */
  15544. ctx->start_time = time(NULL);
  15545. /* Start the server */
  15546. pfd = ctx->listening_socket_fds;
  15547. while (ctx->stop_flag == 0) {
  15548. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15549. pfd[i].fd = ctx->listening_sockets[i].sock;
  15550. pfd[i].events = POLLIN;
  15551. }
  15552. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15553. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15554. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15555. * successful poll, and POLLIN is defined as
  15556. * (POLLRDNORM | POLLRDBAND)
  15557. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15558. * pfd[i].revents == POLLIN. */
  15559. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15560. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15561. }
  15562. }
  15563. }
  15564. }
  15565. /* Here stop_flag is 1 - Initiate shutdown. */
  15566. DEBUG_TRACE("%s", "stopping workers");
  15567. /* Stop signal received: somebody called mg_stop. Quit. */
  15568. close_all_listening_sockets(ctx);
  15569. /* Wakeup workers that are waiting for connections to handle. */
  15570. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15571. #if defined(ALTERNATIVE_QUEUE)
  15572. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15573. event_signal(ctx->client_wait_events[i]);
  15574. /* Since we know all sockets, we can shutdown the connections. */
  15575. if (ctx->client_socks[i].in_use) {
  15576. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  15577. }
  15578. }
  15579. #else
  15580. pthread_cond_broadcast(&ctx->sq_full);
  15581. #endif
  15582. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15583. /* Join all worker threads to avoid leaking threads. */
  15584. workerthreadcount = ctx->cfg_worker_threads;
  15585. for (i = 0; i < workerthreadcount; i++) {
  15586. if (ctx->worker_threadids[i] != 0) {
  15587. mg_join_thread(ctx->worker_threadids[i]);
  15588. }
  15589. }
  15590. #if defined(USE_LUA)
  15591. /* Free Lua state of lua background task */
  15592. if (ctx->lua_background_state) {
  15593. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15594. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15595. if (lua_istable(lstate, -1)) {
  15596. reg_boolean(lstate, "shutdown", 1);
  15597. lua_pop(lstate, 1);
  15598. mg_sleep(2);
  15599. }
  15600. lua_close(lstate);
  15601. ctx->lua_background_state = 0;
  15602. }
  15603. #endif
  15604. DEBUG_TRACE("%s", "exiting");
  15605. #if defined(_WIN32)
  15606. CloseHandle(tls.pthread_cond_helper_mutex);
  15607. #endif
  15608. pthread_setspecific(sTlsKey, NULL);
  15609. /* Signal mg_stop() that we're done.
  15610. * WARNING: This must be the very last thing this
  15611. * thread does, as ctx becomes invalid after this line. */
  15612. ctx->stop_flag = 2;
  15613. }
  15614. /* Threads have different return types on Windows and Unix. */
  15615. #if defined(_WIN32)
  15616. static unsigned __stdcall master_thread(void *thread_func_param)
  15617. {
  15618. master_thread_run(thread_func_param);
  15619. return 0;
  15620. }
  15621. #else
  15622. static void *
  15623. master_thread(void *thread_func_param)
  15624. {
  15625. struct sigaction sa;
  15626. /* Ignore SIGPIPE */
  15627. memset(&sa, 0, sizeof(sa));
  15628. sa.sa_handler = SIG_IGN;
  15629. sigaction(SIGPIPE, &sa, NULL);
  15630. master_thread_run(thread_func_param);
  15631. return NULL;
  15632. }
  15633. #endif /* _WIN32 */
  15634. static void
  15635. free_context(struct mg_context *ctx)
  15636. {
  15637. int i;
  15638. struct mg_handler_info *tmp_rh;
  15639. if (ctx == NULL) {
  15640. return;
  15641. }
  15642. if (ctx->callbacks.exit_context) {
  15643. ctx->callbacks.exit_context(ctx);
  15644. }
  15645. /* All threads exited, no sync is needed. Destroy thread mutex and
  15646. * condvars
  15647. */
  15648. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15649. #if defined(ALTERNATIVE_QUEUE)
  15650. mg_free(ctx->client_socks);
  15651. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15652. event_destroy(ctx->client_wait_events[i]);
  15653. }
  15654. mg_free(ctx->client_wait_events);
  15655. #else
  15656. (void)pthread_cond_destroy(&ctx->sq_empty);
  15657. (void)pthread_cond_destroy(&ctx->sq_full);
  15658. #endif
  15659. /* Destroy other context global data structures mutex */
  15660. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15661. #if defined(USE_TIMERS)
  15662. timers_exit(ctx);
  15663. #endif
  15664. /* Deallocate config parameters */
  15665. for (i = 0; i < NUM_OPTIONS; i++) {
  15666. if (ctx->dd.config[i] != NULL) {
  15667. #if defined(_MSC_VER)
  15668. #pragma warning(suppress : 6001)
  15669. #endif
  15670. mg_free(ctx->dd.config[i]);
  15671. }
  15672. }
  15673. /* Deallocate request handlers */
  15674. while (ctx->dd.handlers) {
  15675. tmp_rh = ctx->dd.handlers;
  15676. ctx->dd.handlers = tmp_rh->next;
  15677. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15678. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15679. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15680. }
  15681. mg_free(tmp_rh->uri);
  15682. mg_free(tmp_rh);
  15683. }
  15684. #if !defined(NO_SSL)
  15685. /* Deallocate SSL context */
  15686. if (ctx->dd.ssl_ctx != NULL) {
  15687. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15688. int callback_ret =
  15689. (ctx->callbacks.external_ssl_ctx == NULL)
  15690. ? 0
  15691. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15692. if (callback_ret == 0) {
  15693. SSL_CTX_free(ctx->dd.ssl_ctx);
  15694. }
  15695. /* else: ignore error and ommit SSL_CTX_free in case
  15696. * callback_ret is 1 */
  15697. }
  15698. #endif /* !NO_SSL */
  15699. /* Deallocate worker thread ID array */
  15700. if (ctx->worker_threadids != NULL) {
  15701. mg_free(ctx->worker_threadids);
  15702. }
  15703. /* Deallocate worker thread ID array */
  15704. if (ctx->worker_connections != NULL) {
  15705. mg_free(ctx->worker_connections);
  15706. }
  15707. /* deallocate system name string */
  15708. mg_free(ctx->systemName);
  15709. /* Deallocate context itself */
  15710. mg_free(ctx);
  15711. }
  15712. void
  15713. mg_stop(struct mg_context *ctx)
  15714. {
  15715. pthread_t mt;
  15716. if (!ctx) {
  15717. return;
  15718. }
  15719. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15720. * two threads is not allowed. */
  15721. mt = ctx->masterthreadid;
  15722. if (mt == 0) {
  15723. return;
  15724. }
  15725. ctx->masterthreadid = 0;
  15726. /* Set stop flag, so all threads know they have to exit. */
  15727. ctx->stop_flag = 1;
  15728. /* Wait until everything has stopped. */
  15729. while (ctx->stop_flag != 2) {
  15730. (void)mg_sleep(10);
  15731. }
  15732. mg_join_thread(mt);
  15733. free_context(ctx);
  15734. #if defined(_WIN32)
  15735. (void)WSACleanup();
  15736. #endif /* _WIN32 */
  15737. }
  15738. static void
  15739. get_system_name(char **sysName)
  15740. {
  15741. #if defined(_WIN32)
  15742. #if !defined(__SYMBIAN32__)
  15743. #if defined(_WIN32_WCE)
  15744. *sysName = mg_strdup("WinCE");
  15745. #else
  15746. char name[128];
  15747. DWORD dwVersion = 0;
  15748. DWORD dwMajorVersion = 0;
  15749. DWORD dwMinorVersion = 0;
  15750. DWORD dwBuild = 0;
  15751. BOOL wowRet, isWoW = FALSE;
  15752. #if defined(_MSC_VER)
  15753. #pragma warning(push)
  15754. /* GetVersion was declared deprecated */
  15755. #pragma warning(disable : 4996)
  15756. #endif
  15757. dwVersion = GetVersion();
  15758. #if defined(_MSC_VER)
  15759. #pragma warning(pop)
  15760. #endif
  15761. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15762. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15763. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15764. (void)dwBuild;
  15765. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15766. sprintf(name,
  15767. "Windows %u.%u%s",
  15768. (unsigned)dwMajorVersion,
  15769. (unsigned)dwMinorVersion,
  15770. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15771. *sysName = mg_strdup(name);
  15772. #endif
  15773. #else
  15774. *sysName = mg_strdup("Symbian");
  15775. #endif
  15776. #else
  15777. struct utsname name;
  15778. memset(&name, 0, sizeof(name));
  15779. uname(&name);
  15780. *sysName = mg_strdup(name.sysname);
  15781. #endif
  15782. }
  15783. struct mg_context *
  15784. mg_start(const struct mg_callbacks *callbacks,
  15785. void *user_data,
  15786. const char **options)
  15787. {
  15788. struct mg_context *ctx;
  15789. const char *name, *value, *default_value;
  15790. int idx, ok, workerthreadcount;
  15791. unsigned int i;
  15792. int itmp;
  15793. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15794. struct mg_workerTLS tls;
  15795. #if defined(_WIN32)
  15796. WSADATA data;
  15797. WSAStartup(MAKEWORD(2, 2), &data);
  15798. #endif /* _WIN32 */
  15799. /* Allocate context and initialize reasonable general case defaults. */
  15800. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15801. return NULL;
  15802. }
  15803. /* Random number generator will initialize at the first call */
  15804. ctx->dd.auth_nonce_mask =
  15805. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15806. if (mg_init_library_called == 0) {
  15807. /* Legacy INIT, if mg_start is called without mg_init_library.
  15808. * Note: This may cause a memory leak */
  15809. const char *ports_option =
  15810. config_options[LISTENING_PORTS].default_value;
  15811. if (options) {
  15812. const char **run_options = options;
  15813. const char *optname = config_options[LISTENING_PORTS].name;
  15814. /* Try to find the "listening_ports" option */
  15815. while (*run_options) {
  15816. if (!strcmp(*run_options, optname)) {
  15817. ports_option = run_options[1];
  15818. }
  15819. run_options += 2;
  15820. }
  15821. }
  15822. if (is_ssl_port_used(ports_option)) {
  15823. /* Initialize with SSL support */
  15824. mg_init_library(MG_FEATURES_TLS);
  15825. } else {
  15826. /* Initialize without SSL support */
  15827. mg_init_library(MG_FEATURES_DEFAULT);
  15828. }
  15829. }
  15830. tls.is_master = -1;
  15831. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15832. #if defined(_WIN32)
  15833. tls.pthread_cond_helper_mutex = NULL;
  15834. #endif
  15835. pthread_setspecific(sTlsKey, &tls);
  15836. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15837. #if !defined(ALTERNATIVE_QUEUE)
  15838. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15839. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15840. #endif
  15841. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15842. if (!ok) {
  15843. /* Fatal error - abort start. However, this situation should never
  15844. * occur in practice. */
  15845. mg_cry_internal(fc(ctx),
  15846. "%s",
  15847. "Cannot initialize thread synchronization objects");
  15848. mg_free(ctx);
  15849. pthread_setspecific(sTlsKey, NULL);
  15850. return NULL;
  15851. }
  15852. if (callbacks) {
  15853. ctx->callbacks = *callbacks;
  15854. exit_callback = callbacks->exit_context;
  15855. ctx->callbacks.exit_context = 0;
  15856. }
  15857. ctx->user_data = user_data;
  15858. ctx->dd.handlers = NULL;
  15859. ctx->dd.next = NULL;
  15860. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15861. ctx->dd.shared_lua_websockets = NULL;
  15862. #endif
  15863. /* Store options */
  15864. while (options && (name = *options++) != NULL) {
  15865. if ((idx = get_option_index(name)) == -1) {
  15866. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15867. free_context(ctx);
  15868. pthread_setspecific(sTlsKey, NULL);
  15869. return NULL;
  15870. } else if ((value = *options++) == NULL) {
  15871. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15872. free_context(ctx);
  15873. pthread_setspecific(sTlsKey, NULL);
  15874. return NULL;
  15875. }
  15876. if (ctx->dd.config[idx] != NULL) {
  15877. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15878. mg_free(ctx->dd.config[idx]);
  15879. }
  15880. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15881. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15882. }
  15883. /* Set default value if needed */
  15884. for (i = 0; config_options[i].name != NULL; i++) {
  15885. default_value = config_options[i].default_value;
  15886. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15887. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15888. }
  15889. }
  15890. /* Request size option */
  15891. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15892. if (itmp < 1024) {
  15893. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15894. free_context(ctx);
  15895. pthread_setspecific(sTlsKey, NULL);
  15896. return NULL;
  15897. }
  15898. ctx->max_request_size = (unsigned)itmp;
  15899. /* Worker thread count option */
  15900. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15901. if (workerthreadcount > MAX_WORKER_THREADS) {
  15902. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15903. free_context(ctx);
  15904. pthread_setspecific(sTlsKey, NULL);
  15905. return NULL;
  15906. }
  15907. if (workerthreadcount <= 0) {
  15908. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15909. free_context(ctx);
  15910. pthread_setspecific(sTlsKey, NULL);
  15911. return NULL;
  15912. }
  15913. /* Document root */
  15914. #if defined(NO_FILES)
  15915. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15916. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15917. free_context(ctx);
  15918. pthread_setspecific(sTlsKey, NULL);
  15919. return NULL;
  15920. }
  15921. #endif
  15922. get_system_name(&ctx->systemName);
  15923. #if defined(USE_LUA)
  15924. /* If a Lua background script has been configured, start it. */
  15925. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15926. char ebuf[256];
  15927. struct vec opt_vec;
  15928. struct vec eq_vec;
  15929. const char *sparams;
  15930. lua_State *state = mg_prepare_lua_context_script(
  15931. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15932. if (!state) {
  15933. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15934. free_context(ctx);
  15935. pthread_setspecific(sTlsKey, NULL);
  15936. return NULL;
  15937. }
  15938. ctx->lua_background_state = (void *)state;
  15939. lua_newtable(state);
  15940. reg_boolean(state, "shutdown", 0);
  15941. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15942. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15943. reg_llstring(
  15944. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15945. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15946. break;
  15947. }
  15948. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15949. } else {
  15950. ctx->lua_background_state = 0;
  15951. }
  15952. #endif
  15953. /* NOTE(lsm): order is important here. SSL certificates must
  15954. * be initialized before listening ports. UID must be set last. */
  15955. if (!set_gpass_option(ctx, NULL) ||
  15956. #if !defined(NO_SSL)
  15957. !init_ssl_ctx(ctx, NULL) ||
  15958. #endif
  15959. !set_ports_option(ctx) ||
  15960. #if !defined(_WIN32)
  15961. !set_uid_option(ctx) ||
  15962. #endif
  15963. !set_acl_option(ctx)) {
  15964. free_context(ctx);
  15965. pthread_setspecific(sTlsKey, NULL);
  15966. return NULL;
  15967. }
  15968. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  15969. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15970. sizeof(pthread_t),
  15971. ctx);
  15972. if (ctx->worker_threadids == NULL) {
  15973. mg_cry_internal(fc(ctx),
  15974. "%s",
  15975. "Not enough memory for worker thread ID array");
  15976. free_context(ctx);
  15977. pthread_setspecific(sTlsKey, NULL);
  15978. return NULL;
  15979. }
  15980. ctx->worker_connections =
  15981. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15982. sizeof(struct mg_connection),
  15983. ctx);
  15984. if (ctx->worker_connections == NULL) {
  15985. mg_cry_internal(fc(ctx),
  15986. "%s",
  15987. "Not enough memory for worker thread connection array");
  15988. free_context(ctx);
  15989. pthread_setspecific(sTlsKey, NULL);
  15990. return NULL;
  15991. }
  15992. #if defined(ALTERNATIVE_QUEUE)
  15993. ctx->client_wait_events =
  15994. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  15995. ctx->cfg_worker_threads,
  15996. ctx);
  15997. if (ctx->client_wait_events == NULL) {
  15998. mg_cry_internal(fc(ctx),
  15999. "%s",
  16000. "Not enough memory for worker event array");
  16001. mg_free(ctx->worker_threadids);
  16002. free_context(ctx);
  16003. pthread_setspecific(sTlsKey, NULL);
  16004. return NULL;
  16005. }
  16006. ctx->client_socks =
  16007. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  16008. ctx->cfg_worker_threads,
  16009. ctx);
  16010. if (ctx->client_socks == NULL) {
  16011. mg_cry_internal(fc(ctx),
  16012. "%s",
  16013. "Not enough memory for worker socket array");
  16014. mg_free(ctx->client_wait_events);
  16015. mg_free(ctx->worker_threadids);
  16016. free_context(ctx);
  16017. pthread_setspecific(sTlsKey, NULL);
  16018. return NULL;
  16019. }
  16020. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16021. ctx->client_wait_events[i] = event_create();
  16022. if (ctx->client_wait_events[i] == 0) {
  16023. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  16024. while (i > 0) {
  16025. i--;
  16026. event_destroy(ctx->client_wait_events[i]);
  16027. }
  16028. mg_free(ctx->client_socks);
  16029. mg_free(ctx->client_wait_events);
  16030. mg_free(ctx->worker_threadids);
  16031. free_context(ctx);
  16032. pthread_setspecific(sTlsKey, NULL);
  16033. return NULL;
  16034. }
  16035. }
  16036. #endif
  16037. #if defined(USE_TIMERS)
  16038. if (timers_init(ctx) != 0) {
  16039. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  16040. free_context(ctx);
  16041. pthread_setspecific(sTlsKey, NULL);
  16042. return NULL;
  16043. }
  16044. #endif
  16045. /* Context has been created - init user libraries */
  16046. if (ctx->callbacks.init_context) {
  16047. ctx->callbacks.init_context(ctx);
  16048. }
  16049. ctx->callbacks.exit_context = exit_callback;
  16050. ctx->context_type = CONTEXT_SERVER; /* server context */
  16051. /* Start master (listening) thread */
  16052. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16053. /* Start worker threads */
  16054. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16055. struct worker_thread_args *wta = (struct worker_thread_args *)
  16056. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  16057. if (wta) {
  16058. wta->ctx = ctx;
  16059. wta->index = (int)i;
  16060. }
  16061. if ((wta == NULL)
  16062. || (mg_start_thread_with_id(worker_thread,
  16063. wta,
  16064. &ctx->worker_threadids[i])
  16065. != 0)) {
  16066. /* thread was not created */
  16067. if (wta != NULL) {
  16068. mg_free(wta);
  16069. }
  16070. if (i > 0) {
  16071. mg_cry_internal(fc(ctx),
  16072. "Cannot start worker thread %i: error %ld",
  16073. i + 1,
  16074. (long)ERRNO);
  16075. } else {
  16076. mg_cry_internal(fc(ctx),
  16077. "Cannot create threads: error %ld",
  16078. (long)ERRNO);
  16079. free_context(ctx);
  16080. pthread_setspecific(sTlsKey, NULL);
  16081. return NULL;
  16082. }
  16083. break;
  16084. }
  16085. }
  16086. pthread_setspecific(sTlsKey, NULL);
  16087. return ctx;
  16088. }
  16089. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16090. /* Add an additional domain to an already running web server. */
  16091. int
  16092. mg_start_domain(struct mg_context *ctx, const char **options)
  16093. {
  16094. const char *name;
  16095. const char *value;
  16096. const char *default_value;
  16097. struct mg_domain_context *new_dom;
  16098. struct mg_domain_context *dom;
  16099. int idx, i;
  16100. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16101. return -1;
  16102. }
  16103. new_dom = (struct mg_domain_context *)
  16104. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16105. if (!new_dom) {
  16106. /* Out of memory */
  16107. return -6;
  16108. }
  16109. /* Store options - TODO: unite duplicate code */
  16110. while (options && (name = *options++) != NULL) {
  16111. if ((idx = get_option_index(name)) == -1) {
  16112. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  16113. mg_free(new_dom);
  16114. return -2;
  16115. } else if ((value = *options++) == NULL) {
  16116. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16117. mg_free(new_dom);
  16118. return -2;
  16119. }
  16120. if (new_dom->config[idx] != NULL) {
  16121. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16122. mg_free(new_dom->config[idx]);
  16123. }
  16124. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16125. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16126. }
  16127. /* Authentication domain is mandatory */
  16128. /* TODO: Maybe use a new option hostname? */
  16129. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16130. mg_cry_internal(fc(ctx), "%s", "authentication domain required");
  16131. mg_free(new_dom);
  16132. return -4;
  16133. }
  16134. /* Set default value if needed. Take the config value from
  16135. * ctx as a default value. */
  16136. for (i = 0; config_options[i].name != NULL; i++) {
  16137. default_value = ctx->dd.config[i];
  16138. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16139. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16140. }
  16141. }
  16142. new_dom->handlers = NULL;
  16143. new_dom->next = NULL;
  16144. new_dom->nonce_count = 0;
  16145. new_dom->auth_nonce_mask =
  16146. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16147. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16148. new_dom->shared_lua_websockets = NULL;
  16149. #endif
  16150. if (!init_ssl_ctx(ctx, new_dom)) {
  16151. /* Init SSL failed */
  16152. mg_free(new_dom);
  16153. return -3;
  16154. }
  16155. /* Add element to linked list. */
  16156. mg_lock_context(ctx);
  16157. idx = 0;
  16158. dom = &(ctx->dd);
  16159. for (;;) {
  16160. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16161. dom->config[AUTHENTICATION_DOMAIN])) {
  16162. /* Domain collision */
  16163. mg_cry_internal(fc(ctx),
  16164. "domain %s already in use",
  16165. new_dom->config[AUTHENTICATION_DOMAIN]);
  16166. mg_free(new_dom);
  16167. return -5;
  16168. }
  16169. /* Count number of domains */
  16170. idx++;
  16171. if (dom->next == NULL) {
  16172. dom->next = new_dom;
  16173. break;
  16174. }
  16175. dom = dom->next;
  16176. }
  16177. mg_unlock_context(ctx);
  16178. /* Return domain number */
  16179. return idx;
  16180. }
  16181. #endif
  16182. /* Feature check API function */
  16183. unsigned
  16184. mg_check_feature(unsigned feature)
  16185. {
  16186. static const unsigned feature_set = 0
  16187. /* Set bits for available features according to API documentation.
  16188. * This bit mask is created at compile time, according to the active
  16189. * preprocessor defines. It is a single const value at runtime. */
  16190. #if !defined(NO_FILES)
  16191. | MG_FEATURES_FILES
  16192. #endif
  16193. #if !defined(NO_SSL)
  16194. | MG_FEATURES_SSL
  16195. #endif
  16196. #if !defined(NO_CGI)
  16197. | MG_FEATURES_CGI
  16198. #endif
  16199. #if defined(USE_IPV6)
  16200. | MG_FEATURES_IPV6
  16201. #endif
  16202. #if defined(USE_WEBSOCKET)
  16203. | MG_FEATURES_WEBSOCKET
  16204. #endif
  16205. #if defined(USE_LUA)
  16206. | MG_FEATURES_LUA
  16207. #endif
  16208. #if defined(USE_DUKTAPE)
  16209. | MG_FEATURES_SSJS
  16210. #endif
  16211. #if !defined(NO_CACHING)
  16212. | MG_FEATURES_CACHE
  16213. #endif
  16214. #if defined(USE_SERVER_STATS)
  16215. | MG_FEATURES_STATS
  16216. #endif
  16217. #if defined(USE_ZLIB)
  16218. | MG_FEATURES_COMPRESSION
  16219. #endif
  16220. /* Set some extra bits not defined in the API documentation.
  16221. * These bits may change without further notice. */
  16222. #if defined(MG_LEGACY_INTERFACE)
  16223. | 0x00008000u
  16224. #endif
  16225. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16226. | 0x00004000u
  16227. #endif
  16228. #if defined(MEMORY_DEBUGGING)
  16229. | 0x00001000u
  16230. #endif
  16231. #if defined(USE_TIMERS)
  16232. | 0x00020000u
  16233. #endif
  16234. #if !defined(NO_NONCE_CHECK)
  16235. | 0x00040000u
  16236. #endif
  16237. #if !defined(NO_POPEN)
  16238. | 0x00080000u
  16239. #endif
  16240. ;
  16241. return (feature & feature_set);
  16242. }
  16243. /* strcat with additional NULL check to avoid clang scan-build warning. */
  16244. #define strcat0(a, b) \
  16245. { \
  16246. if ((a != NULL) && (b != NULL)) { \
  16247. strcat(a, b); \
  16248. } \
  16249. }
  16250. /* Get system information. It can be printed or stored by the caller.
  16251. * Return the size of available information. */
  16252. static int
  16253. mg_get_system_info_impl(char *buffer, int buflen)
  16254. {
  16255. char block[256];
  16256. int system_info_length = 0;
  16257. #if defined(_WIN32)
  16258. const char *eol = "\r\n";
  16259. #else
  16260. const char *eol = "\n";
  16261. #endif
  16262. const char *eoobj = "}";
  16263. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16264. if ((buffer == NULL) || (buflen < 1)) {
  16265. buflen = 0;
  16266. } else {
  16267. *buffer = 0;
  16268. }
  16269. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16270. system_info_length += (int)strlen(block);
  16271. if (system_info_length < buflen) {
  16272. strcat0(buffer, block);
  16273. }
  16274. /* Server version */
  16275. {
  16276. const char *version = mg_version();
  16277. mg_snprintf(NULL,
  16278. NULL,
  16279. block,
  16280. sizeof(block),
  16281. "\"version\" : \"%s\",%s",
  16282. version,
  16283. eol);
  16284. system_info_length += (int)strlen(block);
  16285. if (system_info_length < buflen) {
  16286. strcat0(buffer, block);
  16287. }
  16288. }
  16289. /* System info */
  16290. {
  16291. #if defined(_WIN32)
  16292. DWORD dwVersion = 0;
  16293. DWORD dwMajorVersion = 0;
  16294. DWORD dwMinorVersion = 0;
  16295. SYSTEM_INFO si;
  16296. GetSystemInfo(&si);
  16297. #if defined(_MSC_VER)
  16298. #pragma warning(push)
  16299. /* GetVersion was declared deprecated */
  16300. #pragma warning(disable : 4996)
  16301. #endif
  16302. dwVersion = GetVersion();
  16303. #if defined(_MSC_VER)
  16304. #pragma warning(pop)
  16305. #endif
  16306. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16307. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16308. mg_snprintf(NULL,
  16309. NULL,
  16310. block,
  16311. sizeof(block),
  16312. "\"os\" : \"Windows %u.%u\",%s",
  16313. (unsigned)dwMajorVersion,
  16314. (unsigned)dwMinorVersion,
  16315. eol);
  16316. system_info_length += (int)strlen(block);
  16317. if (system_info_length < buflen) {
  16318. strcat0(buffer, block);
  16319. }
  16320. mg_snprintf(NULL,
  16321. NULL,
  16322. block,
  16323. sizeof(block),
  16324. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  16325. (unsigned)si.wProcessorArchitecture,
  16326. (unsigned)si.dwNumberOfProcessors,
  16327. (unsigned)si.dwActiveProcessorMask,
  16328. eol);
  16329. system_info_length += (int)strlen(block);
  16330. if (system_info_length < buflen) {
  16331. strcat0(buffer, block);
  16332. }
  16333. #else
  16334. struct utsname name;
  16335. memset(&name, 0, sizeof(name));
  16336. uname(&name);
  16337. mg_snprintf(NULL,
  16338. NULL,
  16339. block,
  16340. sizeof(block),
  16341. "\"os\" : \"%s %s (%s) - %s\",%s",
  16342. name.sysname,
  16343. name.version,
  16344. name.release,
  16345. name.machine,
  16346. eol);
  16347. system_info_length += (int)strlen(block);
  16348. if (system_info_length < buflen) {
  16349. strcat0(buffer, block);
  16350. }
  16351. #endif
  16352. }
  16353. /* Features */
  16354. {
  16355. mg_snprintf(NULL,
  16356. NULL,
  16357. block,
  16358. sizeof(block),
  16359. "\"features\" : %lu,%s"
  16360. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  16361. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16362. eol,
  16363. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16364. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16365. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16366. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16367. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16368. : "",
  16369. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16370. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16371. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16372. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  16373. eol);
  16374. system_info_length += (int)strlen(block);
  16375. if (system_info_length < buflen) {
  16376. strcat0(buffer, block);
  16377. }
  16378. #if defined(USE_LUA)
  16379. mg_snprintf(NULL,
  16380. NULL,
  16381. block,
  16382. sizeof(block),
  16383. "\"lua_version\" : \"%u (%s)\",%s",
  16384. (unsigned)LUA_VERSION_NUM,
  16385. LUA_RELEASE,
  16386. eol);
  16387. system_info_length += (int)strlen(block);
  16388. if (system_info_length < buflen) {
  16389. strcat0(buffer, block);
  16390. }
  16391. #endif
  16392. #if defined(USE_DUKTAPE)
  16393. mg_snprintf(NULL,
  16394. NULL,
  16395. block,
  16396. sizeof(block),
  16397. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  16398. (unsigned)DUK_VERSION / 10000,
  16399. ((unsigned)DUK_VERSION / 100) % 100,
  16400. (unsigned)DUK_VERSION % 100,
  16401. eol);
  16402. system_info_length += (int)strlen(block);
  16403. if (system_info_length < buflen) {
  16404. strcat0(buffer, block);
  16405. }
  16406. #endif
  16407. }
  16408. /* Build date */
  16409. {
  16410. #if defined(GCC_DIAGNOSTIC)
  16411. #pragma GCC diagnostic push
  16412. /* Disable bogus compiler warning -Wdate-time */
  16413. #pragma GCC diagnostic ignored "-Wdate-time"
  16414. #endif
  16415. mg_snprintf(NULL,
  16416. NULL,
  16417. block,
  16418. sizeof(block),
  16419. "\"build\" : \"%s\",%s",
  16420. __DATE__,
  16421. eol);
  16422. #if defined(GCC_DIAGNOSTIC)
  16423. #pragma GCC diagnostic pop
  16424. #endif
  16425. system_info_length += (int)strlen(block);
  16426. if (system_info_length < buflen) {
  16427. strcat0(buffer, block);
  16428. }
  16429. }
  16430. /* Compiler information */
  16431. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16432. {
  16433. #if defined(_MSC_VER)
  16434. mg_snprintf(NULL,
  16435. NULL,
  16436. block,
  16437. sizeof(block),
  16438. "\"compiler\" : \"MSC: %u (%u)\",%s",
  16439. (unsigned)_MSC_VER,
  16440. (unsigned)_MSC_FULL_VER,
  16441. eol);
  16442. system_info_length += (int)strlen(block);
  16443. if (system_info_length < buflen) {
  16444. strcat0(buffer, block);
  16445. }
  16446. #elif defined(__MINGW64__)
  16447. mg_snprintf(NULL,
  16448. NULL,
  16449. block,
  16450. sizeof(block),
  16451. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  16452. (unsigned)__MINGW64_VERSION_MAJOR,
  16453. (unsigned)__MINGW64_VERSION_MINOR,
  16454. eol);
  16455. system_info_length += (int)strlen(block);
  16456. if (system_info_length < buflen) {
  16457. strcat0(buffer, block);
  16458. }
  16459. mg_snprintf(NULL,
  16460. NULL,
  16461. block,
  16462. sizeof(block),
  16463. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16464. (unsigned)__MINGW32_MAJOR_VERSION,
  16465. (unsigned)__MINGW32_MINOR_VERSION,
  16466. eol);
  16467. system_info_length += (int)strlen(block);
  16468. if (system_info_length < buflen) {
  16469. strcat0(buffer, block);
  16470. }
  16471. #elif defined(__MINGW32__)
  16472. mg_snprintf(NULL,
  16473. NULL,
  16474. block,
  16475. sizeof(block),
  16476. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16477. (unsigned)__MINGW32_MAJOR_VERSION,
  16478. (unsigned)__MINGW32_MINOR_VERSION,
  16479. eol);
  16480. system_info_length += (int)strlen(block);
  16481. if (system_info_length < buflen) {
  16482. strcat0(buffer, block);
  16483. }
  16484. #elif defined(__clang__)
  16485. mg_snprintf(NULL,
  16486. NULL,
  16487. block,
  16488. sizeof(block),
  16489. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  16490. __clang_major__,
  16491. __clang_minor__,
  16492. __clang_patchlevel__,
  16493. __clang_version__,
  16494. eol);
  16495. system_info_length += (int)strlen(block);
  16496. if (system_info_length < buflen) {
  16497. strcat0(buffer, block);
  16498. }
  16499. #elif defined(__GNUC__)
  16500. mg_snprintf(NULL,
  16501. NULL,
  16502. block,
  16503. sizeof(block),
  16504. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  16505. (unsigned)__GNUC__,
  16506. (unsigned)__GNUC_MINOR__,
  16507. (unsigned)__GNUC_PATCHLEVEL__,
  16508. eol);
  16509. system_info_length += (int)strlen(block);
  16510. if (system_info_length < buflen) {
  16511. strcat0(buffer, block);
  16512. }
  16513. #elif defined(__INTEL_COMPILER)
  16514. mg_snprintf(NULL,
  16515. NULL,
  16516. block,
  16517. sizeof(block),
  16518. "\"compiler\" : \"Intel C/C++: %u\",%s",
  16519. (unsigned)__INTEL_COMPILER,
  16520. eol);
  16521. system_info_length += (int)strlen(block);
  16522. if (system_info_length < buflen) {
  16523. strcat0(buffer, block);
  16524. }
  16525. #elif defined(__BORLANDC__)
  16526. mg_snprintf(NULL,
  16527. NULL,
  16528. block,
  16529. sizeof(block),
  16530. "\"compiler\" : \"Borland C: 0x%x\",%s",
  16531. (unsigned)__BORLANDC__,
  16532. eol);
  16533. system_info_length += (int)strlen(block);
  16534. if (system_info_length < buflen) {
  16535. strcat0(buffer, block);
  16536. }
  16537. #elif defined(__SUNPRO_C)
  16538. mg_snprintf(NULL,
  16539. NULL,
  16540. block,
  16541. sizeof(block),
  16542. "\"compiler\" : \"Solaris: 0x%x\",%s",
  16543. (unsigned)__SUNPRO_C,
  16544. eol);
  16545. system_info_length += (int)strlen(block);
  16546. if (system_info_length < buflen) {
  16547. strcat0(buffer, block);
  16548. }
  16549. #else
  16550. mg_snprintf(NULL,
  16551. NULL,
  16552. block,
  16553. sizeof(block),
  16554. "\"compiler\" : \"other\",%s",
  16555. eol);
  16556. system_info_length += (int)strlen(block);
  16557. if (system_info_length < buflen) {
  16558. strcat0(buffer, block);
  16559. }
  16560. #endif
  16561. }
  16562. /* Determine 32/64 bit data mode.
  16563. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16564. {
  16565. mg_snprintf(NULL,
  16566. NULL,
  16567. block,
  16568. sizeof(block),
  16569. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16570. "char:%u/%u, "
  16571. "ptr:%u, size:%u, time:%u\"%s",
  16572. (unsigned)sizeof(short),
  16573. (unsigned)sizeof(int),
  16574. (unsigned)sizeof(long),
  16575. (unsigned)sizeof(long long),
  16576. (unsigned)sizeof(float),
  16577. (unsigned)sizeof(double),
  16578. (unsigned)sizeof(long double),
  16579. (unsigned)sizeof(char),
  16580. (unsigned)sizeof(wchar_t),
  16581. (unsigned)sizeof(void *),
  16582. (unsigned)sizeof(size_t),
  16583. (unsigned)sizeof(time_t),
  16584. eol);
  16585. system_info_length += (int)strlen(block);
  16586. if (system_info_length < buflen) {
  16587. strcat0(buffer, block);
  16588. }
  16589. }
  16590. /* Terminate string */
  16591. if ((buflen > 0) && buffer && buffer[0]) {
  16592. if (system_info_length < buflen) {
  16593. strcat0(buffer, eoobj);
  16594. strcat0(buffer, eol);
  16595. }
  16596. }
  16597. system_info_length += reserved_len;
  16598. return system_info_length;
  16599. }
  16600. #if defined(USE_SERVER_STATS)
  16601. /* Get context information. It can be printed or stored by the caller.
  16602. * Return the size of available information. */
  16603. static int
  16604. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  16605. {
  16606. char block[256];
  16607. int context_info_length = 0;
  16608. #if defined(_WIN32)
  16609. const char *eol = "\r\n";
  16610. #else
  16611. const char *eol = "\n";
  16612. #endif
  16613. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16614. const char *eoobj = "}";
  16615. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16616. if ((buffer == NULL) || (buflen < 1)) {
  16617. buflen = 0;
  16618. } else {
  16619. *buffer = 0;
  16620. }
  16621. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16622. context_info_length += (int)strlen(block);
  16623. if (context_info_length < buflen) {
  16624. strcat0(buffer, block);
  16625. }
  16626. if (ms) { /* <-- should be always true */
  16627. /* Memory information */
  16628. mg_snprintf(NULL,
  16629. NULL,
  16630. block,
  16631. sizeof(block),
  16632. "\"memory\" : {%s"
  16633. "\"blocks\" : %i,%s"
  16634. "\"used\" : %" INT64_FMT ",%s"
  16635. "\"maxUsed\" : %" INT64_FMT "%s"
  16636. "}%s%s",
  16637. eol,
  16638. ms->blockCount,
  16639. eol,
  16640. ms->totalMemUsed,
  16641. eol,
  16642. ms->maxMemUsed,
  16643. eol,
  16644. (ctx ? "," : ""),
  16645. eol);
  16646. context_info_length += (int)strlen(block);
  16647. if (context_info_length + reserved_len < buflen) {
  16648. strcat0(buffer, block);
  16649. }
  16650. }
  16651. if (ctx) {
  16652. /* Declare all variables at begin of the block, to comply
  16653. * with old C standards. */
  16654. char start_time_str[64] = {0};
  16655. char now_str[64] = {0};
  16656. time_t start_time = ctx->start_time;
  16657. time_t now = time(NULL);
  16658. /* Connections information */
  16659. mg_snprintf(NULL,
  16660. NULL,
  16661. block,
  16662. sizeof(block),
  16663. "\"connections\" : {%s"
  16664. "\"active\" : %i,%s"
  16665. "\"maxActive\" : %i,%s"
  16666. "\"total\" : %" INT64_FMT "%s"
  16667. "},%s",
  16668. eol,
  16669. ctx->active_connections,
  16670. eol,
  16671. ctx->max_connections,
  16672. eol,
  16673. ctx->total_connections,
  16674. eol,
  16675. eol);
  16676. context_info_length += (int)strlen(block);
  16677. if (context_info_length + reserved_len < buflen) {
  16678. strcat0(buffer, block);
  16679. }
  16680. /* Requests information */
  16681. mg_snprintf(NULL,
  16682. NULL,
  16683. block,
  16684. sizeof(block),
  16685. "\"requests\" : {%s"
  16686. "\"total\" : %" INT64_FMT "%s"
  16687. "},%s",
  16688. eol,
  16689. ctx->total_requests,
  16690. eol,
  16691. eol);
  16692. context_info_length += (int)strlen(block);
  16693. if (context_info_length + reserved_len < buflen) {
  16694. strcat0(buffer, block);
  16695. }
  16696. /* Data information */
  16697. mg_snprintf(NULL,
  16698. NULL,
  16699. block,
  16700. sizeof(block),
  16701. "\"data\" : {%s"
  16702. "\"read\" : %" INT64_FMT "%s,"
  16703. "\"written\" : %" INT64_FMT "%s"
  16704. "},%s",
  16705. eol,
  16706. ctx->total_data_read,
  16707. eol,
  16708. ctx->total_data_written,
  16709. eol,
  16710. eol);
  16711. context_info_length += (int)strlen(block);
  16712. if (context_info_length + reserved_len < buflen) {
  16713. strcat0(buffer, block);
  16714. }
  16715. /* Execution time information */
  16716. gmt_time_string(start_time_str,
  16717. sizeof(start_time_str) - 1,
  16718. &start_time);
  16719. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16720. mg_snprintf(NULL,
  16721. NULL,
  16722. block,
  16723. sizeof(block),
  16724. "\"time\" : {%s"
  16725. "\"uptime\" : %.0f,%s"
  16726. "\"start\" : \"%s\",%s"
  16727. "\"now\" : \"%s\"%s"
  16728. "}%s",
  16729. eol,
  16730. difftime(now, start_time),
  16731. eol,
  16732. start_time_str,
  16733. eol,
  16734. now_str,
  16735. eol,
  16736. eol);
  16737. context_info_length += (int)strlen(block);
  16738. if (context_info_length + reserved_len < buflen) {
  16739. strcat0(buffer, block);
  16740. }
  16741. }
  16742. /* Terminate string */
  16743. if ((buflen > 0) && buffer && buffer[0]) {
  16744. if (context_info_length < buflen) {
  16745. strcat0(buffer, eoobj);
  16746. strcat0(buffer, eol);
  16747. }
  16748. }
  16749. context_info_length += reserved_len;
  16750. return context_info_length;
  16751. }
  16752. #endif
  16753. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16754. /* Get connection information. It can be printed or stored by the caller.
  16755. * Return the size of available information. */
  16756. static int
  16757. mg_get_connection_info_impl(const struct mg_context *ctx,
  16758. int idx,
  16759. char *buffer,
  16760. int buflen)
  16761. {
  16762. const struct mg_connection *conn;
  16763. const struct mg_request_info *ri;
  16764. char block[256];
  16765. int connection_info_length = 0;
  16766. int state = 0;
  16767. const char *state_str = "unknown";
  16768. #if defined(_WIN32)
  16769. const char *eol = "\r\n";
  16770. #else
  16771. const char *eol = "\n";
  16772. #endif
  16773. const char *eoobj = "}";
  16774. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16775. if ((buffer == NULL) || (buflen < 1)) {
  16776. buflen = 0;
  16777. } else {
  16778. *buffer = 0;
  16779. }
  16780. if ((ctx == NULL) || (idx < 0)) {
  16781. /* Parameter error */
  16782. return 0;
  16783. }
  16784. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16785. /* Out of range */
  16786. return 0;
  16787. }
  16788. /* Take connection [idx]. This connection is not locked in
  16789. * any way, so some other thread might use it. */
  16790. conn = (ctx->worker_connections) + idx;
  16791. /* Initialize output string */
  16792. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16793. connection_info_length += (int)strlen(block);
  16794. if (connection_info_length < buflen) {
  16795. strcat0(buffer, block);
  16796. }
  16797. /* Init variables */
  16798. ri = &(conn->request_info);
  16799. #if defined(USE_SERVER_STATS)
  16800. state = conn->conn_state;
  16801. /* State as string */
  16802. switch (state) {
  16803. case 0:
  16804. state_str = "undefined";
  16805. break;
  16806. case 1:
  16807. state_str = "not used";
  16808. break;
  16809. case 2:
  16810. state_str = "init";
  16811. break;
  16812. case 3:
  16813. state_str = "ready";
  16814. break;
  16815. case 4:
  16816. state_str = "processing";
  16817. break;
  16818. case 5:
  16819. state_str = "processed";
  16820. break;
  16821. case 6:
  16822. state_str = "to close";
  16823. break;
  16824. case 7:
  16825. state_str = "closing";
  16826. break;
  16827. case 8:
  16828. state_str = "closed";
  16829. break;
  16830. case 9:
  16831. state_str = "done";
  16832. break;
  16833. }
  16834. #endif
  16835. /* Connection info */
  16836. if ((state >= 3) && (state < 9)) {
  16837. mg_snprintf(NULL,
  16838. NULL,
  16839. block,
  16840. sizeof(block),
  16841. "\"connection\" : {%s"
  16842. "\"remote\" : {%s"
  16843. "\"protocol\" : \"%s\",%s"
  16844. "\"addr\" : \"%s\",%s"
  16845. "\"port\" : %u%s"
  16846. "},%s"
  16847. "\"handled_requests\" : %u%s"
  16848. "},%s",
  16849. eol,
  16850. eol,
  16851. get_proto_name(conn),
  16852. eol,
  16853. ri->remote_addr,
  16854. eol,
  16855. ri->remote_port,
  16856. eol,
  16857. eol,
  16858. conn->handled_requests,
  16859. eol,
  16860. eol);
  16861. connection_info_length += (int)strlen(block);
  16862. if (connection_info_length + reserved_len < buflen) {
  16863. strcat0(buffer, block);
  16864. }
  16865. }
  16866. /* Request info */
  16867. if ((state >= 4) && (state < 6)) {
  16868. mg_snprintf(NULL,
  16869. NULL,
  16870. block,
  16871. sizeof(block),
  16872. "\"request_info\" : {%s"
  16873. "\"method\" : \"%s\",%s"
  16874. "\"uri\" : \"%s\",%s"
  16875. "\"query\" : %s%s%s%s"
  16876. "},%s",
  16877. eol,
  16878. ri->request_method,
  16879. eol,
  16880. ri->request_uri,
  16881. eol,
  16882. ri->query_string ? "\"" : "",
  16883. ri->query_string ? ri->query_string : "null",
  16884. ri->query_string ? "\"" : "",
  16885. eol,
  16886. eol);
  16887. connection_info_length += (int)strlen(block);
  16888. if (connection_info_length + reserved_len < buflen) {
  16889. strcat0(buffer, block);
  16890. }
  16891. }
  16892. /* Execution time information */
  16893. if ((state >= 2) && (state < 9)) {
  16894. char start_time_str[64] = {0};
  16895. char now_str[64] = {0};
  16896. time_t start_time = conn->conn_birth_time;
  16897. time_t now = time(NULL);
  16898. gmt_time_string(start_time_str,
  16899. sizeof(start_time_str) - 1,
  16900. &start_time);
  16901. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16902. mg_snprintf(NULL,
  16903. NULL,
  16904. block,
  16905. sizeof(block),
  16906. "\"time\" : {%s"
  16907. "\"uptime\" : %.0f,%s"
  16908. "\"start\" : \"%s\",%s"
  16909. "\"now\" : \"%s\"%s"
  16910. "},%s",
  16911. eol,
  16912. difftime(now, start_time),
  16913. eol,
  16914. start_time_str,
  16915. eol,
  16916. now_str,
  16917. eol,
  16918. eol);
  16919. connection_info_length += (int)strlen(block);
  16920. if (connection_info_length + reserved_len < buflen) {
  16921. strcat0(buffer, block);
  16922. }
  16923. }
  16924. /* Remote user name */
  16925. if ((ri->remote_user) && (state < 9)) {
  16926. mg_snprintf(NULL,
  16927. NULL,
  16928. block,
  16929. sizeof(block),
  16930. "\"user\" : {%s"
  16931. "\"name\" : \"%s\",%s"
  16932. "},%s",
  16933. eol,
  16934. ri->remote_user,
  16935. eol,
  16936. eol);
  16937. connection_info_length += (int)strlen(block);
  16938. if (connection_info_length + reserved_len < buflen) {
  16939. strcat0(buffer, block);
  16940. }
  16941. }
  16942. /* Data block */
  16943. if (state >= 3) {
  16944. mg_snprintf(NULL,
  16945. NULL,
  16946. block,
  16947. sizeof(block),
  16948. "\"data\" : {%s"
  16949. "\"read\" : %" INT64_FMT ",%s"
  16950. "\"written\" : %" INT64_FMT "%s"
  16951. "},%s",
  16952. eol,
  16953. conn->consumed_content,
  16954. eol,
  16955. conn->num_bytes_sent,
  16956. eol,
  16957. eol);
  16958. connection_info_length += (int)strlen(block);
  16959. if (connection_info_length + reserved_len < buflen) {
  16960. strcat0(buffer, block);
  16961. }
  16962. }
  16963. /* State */
  16964. mg_snprintf(NULL,
  16965. NULL,
  16966. block,
  16967. sizeof(block),
  16968. "\"state\" : \"%s\"%s",
  16969. state_str,
  16970. eol);
  16971. connection_info_length += (int)strlen(block);
  16972. if (connection_info_length + reserved_len < buflen) {
  16973. strcat0(buffer, block);
  16974. }
  16975. /* Terminate string */
  16976. if ((buflen > 0) && buffer && buffer[0]) {
  16977. if (connection_info_length < buflen) {
  16978. strcat0(buffer, eoobj);
  16979. strcat0(buffer, eol);
  16980. }
  16981. }
  16982. connection_info_length += reserved_len;
  16983. return connection_info_length;
  16984. }
  16985. #endif
  16986. /* Get system information. It can be printed or stored by the caller.
  16987. * Return the size of available information. */
  16988. int
  16989. mg_get_system_info(char *buffer, int buflen)
  16990. {
  16991. if ((buffer == NULL) || (buflen < 1)) {
  16992. return mg_get_system_info_impl(NULL, 0);
  16993. } else {
  16994. /* Reset buffer, so we can always use strcat. */
  16995. buffer[0] = 0;
  16996. return mg_get_system_info_impl(buffer, buflen);
  16997. }
  16998. }
  16999. /* Get context information. It can be printed or stored by the caller.
  17000. * Return the size of available information. */
  17001. int
  17002. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17003. {
  17004. #if defined(USE_SERVER_STATS)
  17005. if ((buffer == NULL) || (buflen < 1)) {
  17006. return mg_get_context_info_impl(ctx, NULL, 0);
  17007. } else {
  17008. /* Reset buffer, so we can always use strcat. */
  17009. buffer[0] = 0;
  17010. return mg_get_context_info_impl(ctx, buffer, buflen);
  17011. }
  17012. #else
  17013. (void)ctx;
  17014. if ((buffer != NULL) && (buflen > 0)) {
  17015. buffer[0] = 0;
  17016. }
  17017. return 0;
  17018. #endif
  17019. }
  17020. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17021. int
  17022. mg_get_connection_info(const struct mg_context *ctx,
  17023. int idx,
  17024. char *buffer,
  17025. int buflen)
  17026. {
  17027. if ((buffer == NULL) || (buflen < 1)) {
  17028. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  17029. } else {
  17030. /* Reset buffer, so we can always use strcat. */
  17031. buffer[0] = 0;
  17032. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  17033. }
  17034. }
  17035. #endif
  17036. /* Initialize this library. This function does not need to be thread safe.
  17037. */
  17038. unsigned
  17039. mg_init_library(unsigned features)
  17040. {
  17041. #if !defined(NO_SSL)
  17042. char ebuf[128];
  17043. #endif
  17044. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17045. unsigned features_inited = features_to_init;
  17046. if (mg_init_library_called <= 0) {
  17047. /* Not initialized yet */
  17048. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17049. return 0;
  17050. }
  17051. }
  17052. mg_global_lock();
  17053. if (mg_init_library_called <= 0) {
  17054. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17055. /* Fatal error - abort start. However, this situation should
  17056. * never occur in practice. */
  17057. mg_global_unlock();
  17058. return 0;
  17059. }
  17060. #if defined(_WIN32)
  17061. InitializeCriticalSection(&global_log_file_lock);
  17062. #endif
  17063. #if !defined(_WIN32)
  17064. pthread_mutexattr_init(&pthread_mutex_attr);
  17065. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17066. #endif
  17067. #if defined(USE_LUA)
  17068. lua_init_optional_libraries();
  17069. #endif
  17070. }
  17071. mg_global_unlock();
  17072. #if !defined(NO_SSL)
  17073. if (features_to_init & MG_FEATURES_SSL) {
  17074. if (!mg_ssl_initialized) {
  17075. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17076. mg_ssl_initialized = 1;
  17077. } else {
  17078. (void)ebuf;
  17079. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17080. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17081. }
  17082. } else {
  17083. /* ssl already initialized */
  17084. }
  17085. }
  17086. #endif
  17087. /* Start WinSock for Windows */
  17088. mg_global_lock();
  17089. if (mg_init_library_called <= 0) {
  17090. #if defined(_WIN32)
  17091. WSADATA data;
  17092. WSAStartup(MAKEWORD(2, 2), &data);
  17093. #endif /* _WIN32 */
  17094. mg_init_library_called = 1;
  17095. } else {
  17096. mg_init_library_called++;
  17097. }
  17098. mg_global_unlock();
  17099. return features_inited;
  17100. }
  17101. /* Un-initialize this library. */
  17102. unsigned
  17103. mg_exit_library(void)
  17104. {
  17105. if (mg_init_library_called <= 0) {
  17106. return 0;
  17107. }
  17108. mg_global_lock();
  17109. mg_init_library_called--;
  17110. if (mg_init_library_called == 0) {
  17111. #if defined(_WIN32)
  17112. (void)WSACleanup();
  17113. #endif /* _WIN32 */
  17114. #if !defined(NO_SSL)
  17115. if (mg_ssl_initialized) {
  17116. uninitialize_ssl();
  17117. mg_ssl_initialized = 0;
  17118. }
  17119. #endif
  17120. #if defined(_WIN32)
  17121. (void)DeleteCriticalSection(&global_log_file_lock);
  17122. #endif /* _WIN32 */
  17123. #if !defined(_WIN32)
  17124. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17125. #endif
  17126. (void)pthread_key_delete(sTlsKey);
  17127. #if defined(USE_LUA)
  17128. lua_exit_optional_libraries();
  17129. #endif
  17130. mg_global_unlock();
  17131. (void)pthread_mutex_destroy(&global_lock_mutex);
  17132. return 1;
  17133. }
  17134. mg_global_unlock();
  17135. return 1;
  17136. }
  17137. /* End of civetweb.c */