civetweb.c 526 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720
  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. /* Disable unused macros warnings - not all defines are required
  24. * for all systems and all compilers. */
  25. #pragma GCC diagnostic ignored "-Wunused-macros"
  26. /* A padding warning is just plain useless */
  27. #pragma GCC diagnostic ignored "-Wpadded"
  28. #endif
  29. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  30. /* We must set some flags for the headers we include. These flags
  31. * are reserved ids according to C99, so we need to disable a
  32. * warning for that. */
  33. #pragma GCC diagnostic push
  34. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  35. #endif
  36. #if defined(_WIN32)
  37. #if !defined(_CRT_SECURE_NO_WARNINGS)
  38. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  39. #endif
  40. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  41. #define _WIN32_WINNT 0x0501
  42. #endif
  43. #else
  44. #if !defined(_GNU_SOURCE)
  45. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  46. #endif
  47. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  48. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  49. #endif
  50. #if !defined(_LARGEFILE_SOURCE)
  51. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  52. #endif
  53. #if !defined(_FILE_OFFSET_BITS)
  54. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  55. #endif
  56. #if !defined(__STDC_FORMAT_MACROS)
  57. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  58. #endif
  59. #if !defined(__STDC_LIMIT_MACROS)
  60. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  61. #endif
  62. #if !defined(_DARWIN_UNLIMITED_SELECT)
  63. #define _DARWIN_UNLIMITED_SELECT
  64. #endif
  65. #if defined(__sun)
  66. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  67. #define __inline inline /* not recognized on older compiler versions */
  68. #endif
  69. #endif
  70. #if defined(__clang__)
  71. /* Enable reserved-id-macro warning again. */
  72. #pragma GCC diagnostic pop
  73. #endif
  74. #if defined(USE_LUA)
  75. #define USE_TIMERS
  76. #endif
  77. #if defined(_MSC_VER)
  78. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  79. #pragma warning(disable : 4306)
  80. /* conditional expression is constant: introduced by FD_SET(..) */
  81. #pragma warning(disable : 4127)
  82. /* non-constant aggregate initializer: issued due to missing C99 support */
  83. #pragma warning(disable : 4204)
  84. /* padding added after data member */
  85. #pragma warning(disable : 4820)
  86. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  87. #pragma warning(disable : 4668)
  88. /* no function prototype given: converting '()' to '(void)' */
  89. #pragma warning(disable : 4255)
  90. /* function has been selected for automatic inline expansion */
  91. #pragma warning(disable : 4711)
  92. #endif
  93. /* This code uses static_assert to check some conditions.
  94. * Unfortunately some compilers still do not support it, so we have a
  95. * replacement function here. */
  96. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  97. #define mg_static_assert _Static_assert
  98. #elif defined(__cplusplus) && __cplusplus >= 201103L
  99. #define mg_static_assert static_assert
  100. #else
  101. char static_assert_replacement[1];
  102. #define mg_static_assert(cond, txt) \
  103. extern char static_assert_replacement[(cond) ? 1 : -1]
  104. #endif
  105. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  106. "int data type size check");
  107. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  108. "pointer data type size check");
  109. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  110. /* Alternative queue is well tested and should be the new default */
  111. #if defined(NO_ALTERNATIVE_QUEUE)
  112. #if defined(ALTERNATIVE_QUEUE)
  113. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  114. #endif
  115. #else
  116. #define ALTERNATIVE_QUEUE
  117. #endif
  118. /* DTL -- including winsock2.h works better if lean and mean */
  119. #if !defined(WIN32_LEAN_AND_MEAN)
  120. #define WIN32_LEAN_AND_MEAN
  121. #endif
  122. #if defined(__SYMBIAN32__)
  123. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  124. * Symbian is no longer maintained since 2014-01-01.
  125. * Recent versions of CivetWeb are no longer tested for Symbian.
  126. * It makes no sense, to support an abandoned operating system.
  127. * All remaining "#ifdef __SYMBIAN__" cases will be dropped from
  128. * the code sooner or later.
  129. */
  130. #pragma message \
  131. "Symbian is no longer maintained. CivetWeb will drop Symbian support."
  132. #define NO_SSL /* SSL is not supported */
  133. #define NO_CGI /* CGI is not supported */
  134. #define PATH_MAX FILENAME_MAX
  135. #endif /* __SYMBIAN32__ */
  136. #if !defined(CIVETWEB_HEADER_INCLUDED)
  137. /* Include the header file here, so the CivetWeb interface is defined for the
  138. * entire implementation, including the following forward definitions. */
  139. #include "civetweb.h"
  140. #endif
  141. #if !defined(DEBUG_TRACE)
  142. #if defined(DEBUG)
  143. static void DEBUG_TRACE_FUNC(const char *func,
  144. unsigned line,
  145. PRINTF_FORMAT_STRING(const char *fmt),
  146. ...) PRINTF_ARGS(3, 4);
  147. #define DEBUG_TRACE(fmt, ...) \
  148. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  149. #define NEED_DEBUG_TRACE_FUNC
  150. #else
  151. #define DEBUG_TRACE(fmt, ...) \
  152. do { \
  153. } while (0)
  154. #endif /* DEBUG */
  155. #endif /* DEBUG_TRACE */
  156. #if !defined(DEBUG_ASSERT)
  157. #if defined(DEBUG)
  158. #define DEBUG_ASSERT(cond) \
  159. do { \
  160. if (!(cond)) { \
  161. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  162. exit(2); /* Exit with error */ \
  163. } \
  164. } while (0)
  165. #else
  166. #define DEBUG_ASSERT(cond)
  167. #endif /* DEBUG */
  168. #endif
  169. #if !defined(IGNORE_UNUSED_RESULT)
  170. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  171. #endif
  172. #if defined(__GNUC__) || defined(__MINGW32__)
  173. /* GCC unused function attribute seems fundamentally broken.
  174. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  175. * OR UNUSED" for individual functions failed.
  176. * Either the compiler creates an "unused-function" warning if a
  177. * function is not marked with __attribute__((unused)).
  178. * On the other hand, if the function is marked with this attribute,
  179. * but is used, the compiler raises a completely idiotic
  180. * "used-but-marked-unused" warning - and
  181. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  182. * raises error: unknown option after "#pragma GCC diagnostic".
  183. * Disable this warning completely, until the GCC guys sober up
  184. * again.
  185. */
  186. #pragma GCC diagnostic ignored "-Wunused-function"
  187. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  188. #else
  189. #define FUNCTION_MAY_BE_UNUSED
  190. #endif
  191. /* Some ANSI #includes are not available on Windows CE */
  192. #if !defined(_WIN32_WCE)
  193. #include <sys/types.h>
  194. #include <sys/stat.h>
  195. #include <errno.h>
  196. #include <signal.h>
  197. #include <fcntl.h>
  198. #endif /* !_WIN32_WCE */
  199. #if defined(__clang__)
  200. /* When using -Weverything, clang does not accept it's own headers
  201. * in a release build configuration. Disable what is too much in
  202. * -Weverything. */
  203. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  204. #endif
  205. #if defined(__GNUC__) || defined(__MINGW32__)
  206. /* Who on earth came to the conclusion, using __DATE__ should rise
  207. * an "expansion of date or time macro is not reproducible"
  208. * warning. That's exactly what was intended by using this macro.
  209. * Just disable this nonsense warning. */
  210. /* And disabling them does not work either:
  211. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  212. * #pragma clang diagnostic ignored "-Wdate-time"
  213. * So we just have to disable ALL warnings for some lines
  214. * of code.
  215. * This seems to be a known GCC bug, not resolved since 2012:
  216. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  217. */
  218. #endif
  219. #if defined(__MACH__) /* Apple OSX section */
  220. #if defined(__clang__)
  221. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  222. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  223. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  224. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  225. #endif
  226. #endif
  227. #define CLOCK_MONOTONIC (1)
  228. #define CLOCK_REALTIME (2)
  229. #include <sys/errno.h>
  230. #include <sys/time.h>
  231. #include <mach/clock.h>
  232. #include <mach/mach.h>
  233. #include <mach/mach_time.h>
  234. /* clock_gettime is not implemented on OSX prior to 10.12 */
  235. static int
  236. _civet_clock_gettime(int clk_id, struct timespec *t)
  237. {
  238. memset(t, 0, sizeof(*t));
  239. if (clk_id == CLOCK_REALTIME) {
  240. struct timeval now;
  241. int rv = gettimeofday(&now, NULL);
  242. if (rv) {
  243. return rv;
  244. }
  245. t->tv_sec = now.tv_sec;
  246. t->tv_nsec = now.tv_usec * 1000;
  247. return 0;
  248. } else if (clk_id == CLOCK_MONOTONIC) {
  249. static uint64_t clock_start_time = 0;
  250. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  251. uint64_t now = mach_absolute_time();
  252. if (clock_start_time == 0) {
  253. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  254. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  255. /* appease "unused variable" warning for release builds */
  256. (void)mach_status;
  257. clock_start_time = now;
  258. }
  259. now = (uint64_t)((double)(now - clock_start_time)
  260. * (double)timebase_ifo.numer
  261. / (double)timebase_ifo.denom);
  262. t->tv_sec = now / 1000000000;
  263. t->tv_nsec = now % 1000000000;
  264. return 0;
  265. }
  266. return -1; /* EINVAL - Clock ID is unknown */
  267. }
  268. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  269. #if defined(__CLOCK_AVAILABILITY)
  270. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  271. * declared but it may be NULL at runtime. So we need to check before using
  272. * it. */
  273. static int
  274. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  275. {
  276. if (clock_gettime) {
  277. return clock_gettime(clk_id, t);
  278. }
  279. return _civet_clock_gettime(clk_id, t);
  280. }
  281. #define clock_gettime _civet_safe_clock_gettime
  282. #else
  283. #define clock_gettime _civet_clock_gettime
  284. #endif
  285. #endif
  286. #include <time.h>
  287. #include <stdlib.h>
  288. #include <stdarg.h>
  289. #include <string.h>
  290. #include <ctype.h>
  291. #include <limits.h>
  292. #include <stddef.h>
  293. #include <stdio.h>
  294. #include <stdint.h>
  295. /********************************************************************/
  296. /* CivetWeb configuration defines */
  297. /********************************************************************/
  298. /* Maximum number of threads that can be configured.
  299. * The number of threads actually created depends on the "num_threads"
  300. * configuration parameter, but this is the upper limit. */
  301. #if !defined(MAX_WORKER_THREADS)
  302. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  303. #endif
  304. /* Timeout interval for select/poll calls.
  305. * The timeouts depend on "*_timeout_ms" configuration values, but long
  306. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  307. * This reduces the time required to stop the server. */
  308. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  309. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  310. #endif
  311. /* Do not try to compress files smaller than this limit. */
  312. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  313. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  314. #endif
  315. #if !defined(PASSWORDS_FILE_NAME)
  316. #define PASSWORDS_FILE_NAME ".htpasswd"
  317. #endif
  318. /* Initial buffer size for all CGI environment variables. In case there is
  319. * not enough space, another block is allocated. */
  320. #if !defined(CGI_ENVIRONMENT_SIZE)
  321. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  322. #endif
  323. /* Maximum number of environment variables. */
  324. #if !defined(MAX_CGI_ENVIR_VARS)
  325. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  326. #endif
  327. /* General purpose buffer size. */
  328. #if !defined(MG_BUF_LEN) /* in bytes */
  329. #define MG_BUF_LEN (1024 * 8)
  330. #endif
  331. /* Maximum queue length for pending connections. This value is passed as
  332. * parameter to the "listen" socket call. */
  333. #if !defined(SOMAXCONN)
  334. #define SOMAXCONN (100) /* in pending connections (count) */
  335. #endif
  336. /* Size of the accepted socket queue (in case the old queue implementation
  337. * is used). */
  338. #if !defined(MGSQLEN)
  339. #define MGSQLEN (20) /* count */
  340. #endif
  341. /********************************************************************/
  342. /* Helper makros */
  343. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  344. /* Standard defines */
  345. #if !defined(INT64_MAX)
  346. #define INT64_MAX (9223372036854775807)
  347. #endif
  348. #define SHUTDOWN_RD (0)
  349. #define SHUTDOWN_WR (1)
  350. #define SHUTDOWN_BOTH (2)
  351. mg_static_assert(MAX_WORKER_THREADS >= 1,
  352. "worker threads must be a positive number");
  353. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  354. "size_t data type size check");
  355. #if defined(_WIN32) && !defined(__SYMBIAN32__) /* WINDOWS include block */
  356. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  357. #include <ws2tcpip.h>
  358. #include <windows.h>
  359. typedef const char *SOCK_OPT_TYPE;
  360. #if !defined(PATH_MAX)
  361. #define W_PATH_MAX (MAX_PATH)
  362. /* at most three UTF-8 chars per wchar_t */
  363. #define PATH_MAX (W_PATH_MAX * 3)
  364. #else
  365. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  366. #endif
  367. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  368. #if !defined(_IN_PORT_T)
  369. #if !defined(in_port_t)
  370. #define in_port_t u_short
  371. #endif
  372. #endif
  373. #if !defined(_WIN32_WCE)
  374. #include <process.h>
  375. #include <direct.h>
  376. #include <io.h>
  377. #else /* _WIN32_WCE */
  378. #define NO_CGI /* WinCE has no pipes */
  379. #define NO_POPEN /* WinCE has no popen */
  380. typedef long off_t;
  381. #define errno ((int)(GetLastError()))
  382. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  383. #endif /* _WIN32_WCE */
  384. #define MAKEUQUAD(lo, hi) \
  385. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  386. #define RATE_DIFF (10000000) /* 100 nsecs */
  387. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  388. #define SYS2UNIX_TIME(lo, hi) \
  389. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  390. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  391. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  392. * Also use _strtoui64 on modern M$ compilers */
  393. #if defined(_MSC_VER)
  394. #if (_MSC_VER < 1300)
  395. #define STRX(x) #x
  396. #define STR(x) STRX(x)
  397. #define __func__ __FILE__ ":" STR(__LINE__)
  398. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  399. #define strtoll(x, y, z) (_atoi64(x))
  400. #else
  401. #define __func__ __FUNCTION__
  402. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  403. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  404. #endif
  405. #endif /* _MSC_VER */
  406. #define ERRNO ((int)(GetLastError()))
  407. #define NO_SOCKLEN_T
  408. #if defined(_WIN64) || defined(__MINGW64__)
  409. #if !defined(SSL_LIB)
  410. #define SSL_LIB "ssleay64.dll"
  411. #endif
  412. #if !defined(CRYPTO_LIB)
  413. #define CRYPTO_LIB "libeay64.dll"
  414. #endif
  415. #else
  416. #if !defined(SSL_LIB)
  417. #define SSL_LIB "ssleay32.dll"
  418. #endif
  419. #if !defined(CRYPTO_LIB)
  420. #define CRYPTO_LIB "libeay32.dll"
  421. #endif
  422. #endif
  423. #define O_NONBLOCK (0)
  424. #if !defined(W_OK)
  425. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  426. #endif
  427. #if !defined(EWOULDBLOCK)
  428. #define EWOULDBLOCK WSAEWOULDBLOCK
  429. #endif /* !EWOULDBLOCK */
  430. #define _POSIX_
  431. #define INT64_FMT "I64d"
  432. #define UINT64_FMT "I64u"
  433. #define WINCDECL __cdecl
  434. #define vsnprintf_impl _vsnprintf
  435. #define access _access
  436. #define mg_sleep(x) (Sleep(x))
  437. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  438. #if !defined(popen)
  439. #define popen(x, y) (_popen(x, y))
  440. #endif
  441. #if !defined(pclose)
  442. #define pclose(x) (_pclose(x))
  443. #endif
  444. #define close(x) (_close(x))
  445. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  446. #define RTLD_LAZY (0)
  447. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  448. #define fdopen(x, y) (_fdopen((x), (y)))
  449. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  450. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  451. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  452. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  453. #define sleep(x) (Sleep((x)*1000))
  454. #define rmdir(x) (_rmdir(x))
  455. #if defined(_WIN64) || !defined(__MINGW32__)
  456. /* Only MinGW 32 bit is missing this function */
  457. #define timegm(x) (_mkgmtime(x))
  458. #else
  459. time_t timegm(struct tm *tm);
  460. #define NEED_TIMEGM
  461. #endif
  462. #if !defined(fileno)
  463. #define fileno(x) (_fileno(x))
  464. #endif /* !fileno MINGW #defines fileno */
  465. typedef HANDLE pthread_mutex_t;
  466. typedef DWORD pthread_key_t;
  467. typedef HANDLE pthread_t;
  468. typedef struct {
  469. CRITICAL_SECTION threadIdSec;
  470. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  471. } pthread_cond_t;
  472. #if !defined(__clockid_t_defined)
  473. typedef DWORD clockid_t;
  474. #endif
  475. #if !defined(CLOCK_MONOTONIC)
  476. #define CLOCK_MONOTONIC (1)
  477. #endif
  478. #if !defined(CLOCK_REALTIME)
  479. #define CLOCK_REALTIME (2)
  480. #endif
  481. #if !defined(CLOCK_THREAD)
  482. #define CLOCK_THREAD (3)
  483. #endif
  484. #if !defined(CLOCK_PROCESS)
  485. #define CLOCK_PROCESS (4)
  486. #endif
  487. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  488. #define _TIMESPEC_DEFINED
  489. #endif
  490. #if !defined(_TIMESPEC_DEFINED)
  491. struct timespec {
  492. time_t tv_sec; /* seconds */
  493. long tv_nsec; /* nanoseconds */
  494. };
  495. #endif
  496. #if !defined(WIN_PTHREADS_TIME_H)
  497. #define MUST_IMPLEMENT_CLOCK_GETTIME
  498. #endif
  499. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  500. #define clock_gettime mg_clock_gettime
  501. static int
  502. clock_gettime(clockid_t clk_id, struct timespec *tp)
  503. {
  504. FILETIME ft;
  505. ULARGE_INTEGER li, li2;
  506. BOOL ok = FALSE;
  507. double d;
  508. static double perfcnt_per_sec = 0.0;
  509. static BOOL initialized = FALSE;
  510. if (!initialized) {
  511. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  512. perfcnt_per_sec = 1.0 / li.QuadPart;
  513. initialized = TRUE;
  514. }
  515. if (tp) {
  516. memset(tp, 0, sizeof(*tp));
  517. if (clk_id == CLOCK_REALTIME) {
  518. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  519. GetSystemTimeAsFileTime(&ft);
  520. li.LowPart = ft.dwLowDateTime;
  521. li.HighPart = ft.dwHighDateTime;
  522. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  523. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  524. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  525. ok = TRUE;
  526. /* END: CLOCK_REALTIME */
  527. } else if (clk_id == CLOCK_MONOTONIC) {
  528. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  529. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  530. d = li.QuadPart * perfcnt_per_sec;
  531. tp->tv_sec = (time_t)d;
  532. d -= (double)tp->tv_sec;
  533. tp->tv_nsec = (long)(d * 1.0E9);
  534. ok = TRUE;
  535. /* END: CLOCK_MONOTONIC */
  536. } else if (clk_id == CLOCK_THREAD) {
  537. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  538. FILETIME t_create, t_exit, t_kernel, t_user;
  539. if (GetThreadTimes(GetCurrentThread(),
  540. &t_create,
  541. &t_exit,
  542. &t_kernel,
  543. &t_user)) {
  544. li.LowPart = t_user.dwLowDateTime;
  545. li.HighPart = t_user.dwHighDateTime;
  546. li2.LowPart = t_kernel.dwLowDateTime;
  547. li2.HighPart = t_kernel.dwHighDateTime;
  548. li.QuadPart += li2.QuadPart;
  549. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  550. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  551. ok = TRUE;
  552. }
  553. /* END: CLOCK_THREAD */
  554. } else if (clk_id == CLOCK_PROCESS) {
  555. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  556. FILETIME t_create, t_exit, t_kernel, t_user;
  557. if (GetProcessTimes(GetCurrentProcess(),
  558. &t_create,
  559. &t_exit,
  560. &t_kernel,
  561. &t_user)) {
  562. li.LowPart = t_user.dwLowDateTime;
  563. li.HighPart = t_user.dwHighDateTime;
  564. li2.LowPart = t_kernel.dwLowDateTime;
  565. li2.HighPart = t_kernel.dwHighDateTime;
  566. li.QuadPart += li2.QuadPart;
  567. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  568. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  569. ok = TRUE;
  570. }
  571. /* END: CLOCK_PROCESS */
  572. } else {
  573. /* BEGIN: unknown clock */
  574. /* ok = FALSE; already set by init */
  575. /* END: unknown clock */
  576. }
  577. }
  578. return ok ? 0 : -1;
  579. }
  580. #endif
  581. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  582. static int pthread_mutex_lock(pthread_mutex_t *);
  583. static int pthread_mutex_unlock(pthread_mutex_t *);
  584. static void path_to_unicode(const struct mg_connection *conn,
  585. const char *path,
  586. wchar_t *wbuf,
  587. size_t wbuf_len);
  588. /* All file operations need to be rewritten to solve #246. */
  589. struct mg_file;
  590. static const char *
  591. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  592. /* POSIX dirent interface */
  593. struct dirent {
  594. char d_name[PATH_MAX];
  595. };
  596. typedef struct DIR {
  597. HANDLE handle;
  598. WIN32_FIND_DATAW info;
  599. struct dirent result;
  600. } DIR;
  601. #if defined(_WIN32) && !defined(POLLIN)
  602. #if !defined(HAVE_POLL)
  603. struct pollfd {
  604. SOCKET fd;
  605. short events;
  606. short revents;
  607. };
  608. #define POLLIN (0x0300)
  609. #endif
  610. #endif
  611. /* Mark required libraries */
  612. #if defined(_MSC_VER)
  613. #pragma comment(lib, "Ws2_32.lib")
  614. #endif
  615. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  616. WINDOWS / UNIX include block */
  617. #include <sys/wait.h>
  618. #include <sys/socket.h>
  619. #include <sys/poll.h>
  620. #include <netinet/in.h>
  621. #include <arpa/inet.h>
  622. #include <sys/time.h>
  623. #include <sys/utsname.h>
  624. #include <stdint.h>
  625. #include <inttypes.h>
  626. #include <netdb.h>
  627. #include <netinet/tcp.h>
  628. typedef const void *SOCK_OPT_TYPE;
  629. #if defined(ANDROID)
  630. typedef unsigned short int in_port_t;
  631. #endif
  632. #include <pwd.h>
  633. #include <unistd.h>
  634. #include <grp.h>
  635. #include <dirent.h>
  636. #define vsnprintf_impl vsnprintf
  637. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  638. #include <dlfcn.h>
  639. #endif
  640. #include <pthread.h>
  641. #if defined(__MACH__)
  642. #define SSL_LIB "libssl.dylib"
  643. #define CRYPTO_LIB "libcrypto.dylib"
  644. #else
  645. #if !defined(SSL_LIB)
  646. #define SSL_LIB "libssl.so"
  647. #endif
  648. #if !defined(CRYPTO_LIB)
  649. #define CRYPTO_LIB "libcrypto.so"
  650. #endif
  651. #endif
  652. #if !defined(O_BINARY)
  653. #define O_BINARY (0)
  654. #endif /* O_BINARY */
  655. #define closesocket(a) (close(a))
  656. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  657. #define mg_remove(conn, x) (remove(x))
  658. #define mg_sleep(x) (usleep((x)*1000))
  659. #define mg_opendir(conn, x) (opendir(x))
  660. #define mg_closedir(x) (closedir(x))
  661. #define mg_readdir(x) (readdir(x))
  662. #define ERRNO (errno)
  663. #define INVALID_SOCKET (-1)
  664. #define INT64_FMT PRId64
  665. #define UINT64_FMT PRIu64
  666. typedef int SOCKET;
  667. #define WINCDECL
  668. #if defined(__hpux)
  669. /* HPUX 11 does not have monotonic, fall back to realtime */
  670. #if !defined(CLOCK_MONOTONIC)
  671. #define CLOCK_MONOTONIC CLOCK_REALTIME
  672. #endif
  673. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  674. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  675. * the prototypes use int* rather than socklen_t* which matches the
  676. * actual library expectation. When called with the wrong size arg
  677. * accept() returns a zero client inet addr and check_acl() always
  678. * fails. Since socklen_t is widely used below, just force replace
  679. * their typedef with int. - DTL
  680. */
  681. #define socklen_t int
  682. #endif /* hpux */
  683. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  684. WINDOWS / UNIX include block */
  685. /* In case our C library is missing "timegm", provide an implementation */
  686. #if defined(NEED_TIMEGM)
  687. static inline int
  688. is_leap(int y)
  689. {
  690. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  691. }
  692. static inline int
  693. count_leap(int y)
  694. {
  695. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  696. }
  697. time_t
  698. timegm(struct tm *tm)
  699. {
  700. static const unsigned short ydays[] = {
  701. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  702. int year = tm->tm_year + 1900;
  703. int mon = tm->tm_mon;
  704. int mday = tm->tm_mday - 1;
  705. int hour = tm->tm_hour;
  706. int min = tm->tm_min;
  707. int sec = tm->tm_sec;
  708. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  709. || (mday >= ydays[mon + 1] - ydays[mon]
  710. + (mon == 1 && is_leap(year) ? 1 : 0)) || hour < 0
  711. || hour > 23
  712. || min < 0
  713. || min > 59
  714. || sec < 0
  715. || sec > 60)
  716. return -1;
  717. time_t res = year - 1970;
  718. res *= 365;
  719. res += mday;
  720. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  721. res += count_leap(year);
  722. res *= 24;
  723. res += hour;
  724. res *= 60;
  725. res += min;
  726. res *= 60;
  727. res += sec;
  728. return res;
  729. }
  730. #endif /* NEED_TIMEGM */
  731. /* va_copy should always be a macro, C99 and C++11 - DTL */
  732. #if !defined(va_copy)
  733. #define va_copy(x, y) ((x) = (y))
  734. #endif
  735. #if defined(_WIN32)
  736. /* Create substitutes for POSIX functions in Win32. */
  737. #if defined(__MINGW32__)
  738. /* Show no warning in case system functions are not used. */
  739. #pragma GCC diagnostic push
  740. #pragma GCC diagnostic ignored "-Wunused-function"
  741. #endif
  742. static CRITICAL_SECTION global_log_file_lock;
  743. FUNCTION_MAY_BE_UNUSED
  744. static DWORD
  745. pthread_self(void)
  746. {
  747. return GetCurrentThreadId();
  748. }
  749. FUNCTION_MAY_BE_UNUSED
  750. static int
  751. pthread_key_create(
  752. pthread_key_t *key,
  753. void (*_ignored)(void *) /* destructor not supported for Windows */
  754. )
  755. {
  756. (void)_ignored;
  757. if ((key != 0)) {
  758. *key = TlsAlloc();
  759. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  760. }
  761. return -2;
  762. }
  763. FUNCTION_MAY_BE_UNUSED
  764. static int
  765. pthread_key_delete(pthread_key_t key)
  766. {
  767. return TlsFree(key) ? 0 : 1;
  768. }
  769. FUNCTION_MAY_BE_UNUSED
  770. static int
  771. pthread_setspecific(pthread_key_t key, void *value)
  772. {
  773. return TlsSetValue(key, value) ? 0 : 1;
  774. }
  775. FUNCTION_MAY_BE_UNUSED
  776. static void *
  777. pthread_getspecific(pthread_key_t key)
  778. {
  779. return TlsGetValue(key);
  780. }
  781. #if defined(__MINGW32__)
  782. /* Enable unused function warning again */
  783. #pragma GCC diagnostic pop
  784. #endif
  785. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  786. #else
  787. static pthread_mutexattr_t pthread_mutex_attr;
  788. #endif /* _WIN32 */
  789. #if defined(_WIN32_WCE)
  790. /* Create substitutes for POSIX functions in Win32. */
  791. #if defined(__MINGW32__)
  792. /* Show no warning in case system functions are not used. */
  793. #pragma GCC diagnostic push
  794. #pragma GCC diagnostic ignored "-Wunused-function"
  795. #endif
  796. FUNCTION_MAY_BE_UNUSED
  797. static time_t
  798. time(time_t *ptime)
  799. {
  800. time_t t;
  801. SYSTEMTIME st;
  802. FILETIME ft;
  803. GetSystemTime(&st);
  804. SystemTimeToFileTime(&st, &ft);
  805. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  806. if (ptime != NULL) {
  807. *ptime = t;
  808. }
  809. return t;
  810. }
  811. FUNCTION_MAY_BE_UNUSED
  812. static struct tm *
  813. localtime_s(const time_t *ptime, struct tm *ptm)
  814. {
  815. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  816. FILETIME ft, lft;
  817. SYSTEMTIME st;
  818. TIME_ZONE_INFORMATION tzinfo;
  819. if (ptm == NULL) {
  820. return NULL;
  821. }
  822. *(int64_t *)&ft = t;
  823. FileTimeToLocalFileTime(&ft, &lft);
  824. FileTimeToSystemTime(&lft, &st);
  825. ptm->tm_year = st.wYear - 1900;
  826. ptm->tm_mon = st.wMonth - 1;
  827. ptm->tm_wday = st.wDayOfWeek;
  828. ptm->tm_mday = st.wDay;
  829. ptm->tm_hour = st.wHour;
  830. ptm->tm_min = st.wMinute;
  831. ptm->tm_sec = st.wSecond;
  832. ptm->tm_yday = 0; /* hope nobody uses this */
  833. ptm->tm_isdst =
  834. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  835. return ptm;
  836. }
  837. FUNCTION_MAY_BE_UNUSED
  838. static struct tm *
  839. gmtime_s(const time_t *ptime, struct tm *ptm)
  840. {
  841. /* FIXME(lsm): fix this. */
  842. return localtime_s(ptime, ptm);
  843. }
  844. static int mg_atomic_inc(volatile int *addr);
  845. static struct tm tm_array[MAX_WORKER_THREADS];
  846. static int tm_index = 0;
  847. FUNCTION_MAY_BE_UNUSED
  848. static struct tm *
  849. localtime(const time_t *ptime)
  850. {
  851. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  852. return localtime_s(ptime, tm_array + i);
  853. }
  854. FUNCTION_MAY_BE_UNUSED
  855. static struct tm *
  856. gmtime(const time_t *ptime)
  857. {
  858. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  859. return gmtime_s(ptime, tm_array + i);
  860. }
  861. FUNCTION_MAY_BE_UNUSED
  862. static size_t
  863. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  864. {
  865. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  866. * for WinCE"); */
  867. return 0;
  868. }
  869. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  870. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  871. #define remove(f) mg_remove(NULL, f)
  872. FUNCTION_MAY_BE_UNUSED
  873. static int
  874. rename(const char *a, const char *b)
  875. {
  876. wchar_t wa[W_PATH_MAX];
  877. wchar_t wb[W_PATH_MAX];
  878. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  879. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  880. return MoveFileW(wa, wb) ? 0 : -1;
  881. }
  882. struct stat {
  883. int64_t st_size;
  884. time_t st_mtime;
  885. };
  886. FUNCTION_MAY_BE_UNUSED
  887. static int
  888. stat(const char *name, struct stat *st)
  889. {
  890. wchar_t wbuf[W_PATH_MAX];
  891. WIN32_FILE_ATTRIBUTE_DATA attr;
  892. time_t creation_time, write_time;
  893. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  894. memset(&attr, 0, sizeof(attr));
  895. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  896. st->st_size =
  897. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  898. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  899. attr.ftLastWriteTime.dwHighDateTime);
  900. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  901. attr.ftCreationTime.dwHighDateTime);
  902. if (creation_time > write_time) {
  903. st->st_mtime = creation_time;
  904. } else {
  905. st->st_mtime = write_time;
  906. }
  907. return 0;
  908. }
  909. #define access(x, a) 1 /* not required anyway */
  910. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  911. /* Values from errno.h in Windows SDK (Visual Studio). */
  912. #define EEXIST 17
  913. #define EACCES 13
  914. #define ENOENT 2
  915. #if defined(__MINGW32__)
  916. /* Enable unused function warning again */
  917. #pragma GCC diagnostic pop
  918. #endif
  919. #endif /* defined(_WIN32_WCE) */
  920. #if defined(__GNUC__) || defined(__MINGW32__)
  921. /* Show no warning in case system functions are not used. */
  922. #define GCC_VERSION \
  923. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  924. #if GCC_VERSION >= 40500
  925. #pragma GCC diagnostic push
  926. #pragma GCC diagnostic ignored "-Wunused-function"
  927. #endif /* GCC_VERSION >= 40500 */
  928. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  929. #if defined(__clang__)
  930. /* Show no warning in case system functions are not used. */
  931. #pragma clang diagnostic push
  932. #pragma clang diagnostic ignored "-Wunused-function"
  933. #endif
  934. static pthread_mutex_t global_lock_mutex;
  935. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  936. /* Forward declaration for Windows */
  937. FUNCTION_MAY_BE_UNUSED
  938. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  939. FUNCTION_MAY_BE_UNUSED
  940. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  941. #endif
  942. FUNCTION_MAY_BE_UNUSED
  943. static void
  944. mg_global_lock(void)
  945. {
  946. (void)pthread_mutex_lock(&global_lock_mutex);
  947. }
  948. FUNCTION_MAY_BE_UNUSED
  949. static void
  950. mg_global_unlock(void)
  951. {
  952. (void)pthread_mutex_unlock(&global_lock_mutex);
  953. }
  954. FUNCTION_MAY_BE_UNUSED
  955. static int
  956. mg_atomic_inc(volatile int *addr)
  957. {
  958. int ret;
  959. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  960. /* Depending on the SDK, this function uses either
  961. * (volatile unsigned int *) or (volatile LONG *),
  962. * so whatever you use, the other SDK is likely to raise a warning. */
  963. ret = InterlockedIncrement((volatile long *)addr);
  964. #elif defined(__GNUC__) \
  965. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  966. && !defined(NO_ATOMICS)
  967. ret = __sync_add_and_fetch(addr, 1);
  968. #else
  969. mg_global_lock();
  970. ret = (++(*addr));
  971. mg_global_unlock();
  972. #endif
  973. return ret;
  974. }
  975. FUNCTION_MAY_BE_UNUSED
  976. static int
  977. mg_atomic_dec(volatile int *addr)
  978. {
  979. int ret;
  980. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  981. /* Depending on the SDK, this function uses either
  982. * (volatile unsigned int *) or (volatile LONG *),
  983. * so whatever you use, the other SDK is likely to raise a warning. */
  984. ret = InterlockedDecrement((volatile long *)addr);
  985. #elif defined(__GNUC__) \
  986. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  987. && !defined(NO_ATOMICS)
  988. ret = __sync_sub_and_fetch(addr, 1);
  989. #else
  990. mg_global_lock();
  991. ret = (--(*addr));
  992. mg_global_unlock();
  993. #endif
  994. return ret;
  995. }
  996. #if defined(USE_SERVER_STATS)
  997. static int64_t
  998. mg_atomic_add(volatile int64_t *addr, int64_t value)
  999. {
  1000. int64_t ret;
  1001. #if defined(_WIN64) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  1002. ret = InterlockedAdd64(addr, value);
  1003. #elif defined(__GNUC__) \
  1004. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1005. && !defined(NO_ATOMICS)
  1006. ret = __sync_add_and_fetch(addr, value);
  1007. #else
  1008. mg_global_lock();
  1009. *addr += value;
  1010. ret = (*addr);
  1011. mg_global_unlock();
  1012. #endif
  1013. return ret;
  1014. }
  1015. #endif
  1016. #if defined(__GNUC__)
  1017. /* Show no warning in case system functions are not used. */
  1018. #if GCC_VERSION >= 40500
  1019. #pragma GCC diagnostic pop
  1020. #endif /* GCC_VERSION >= 40500 */
  1021. #endif /* defined(__GNUC__) */
  1022. #if defined(__clang__)
  1023. /* Show no warning in case system functions are not used. */
  1024. #pragma clang diagnostic pop
  1025. #endif
  1026. #if defined(USE_SERVER_STATS)
  1027. struct mg_memory_stat {
  1028. volatile int64_t totalMemUsed;
  1029. volatile int64_t maxMemUsed;
  1030. volatile int blockCount;
  1031. };
  1032. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1033. static void *
  1034. mg_malloc_ex(size_t size,
  1035. struct mg_context *ctx,
  1036. const char *file,
  1037. unsigned line)
  1038. {
  1039. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1040. void *memory = 0;
  1041. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1042. #if defined(MEMORY_DEBUGGING)
  1043. char mallocStr[256];
  1044. #else
  1045. (void)file;
  1046. (void)line;
  1047. #endif
  1048. if (data) {
  1049. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1050. if (mmem > mstat->maxMemUsed) {
  1051. /* could use atomic compare exchange, but this
  1052. * seems overkill for statistics data */
  1053. mstat->maxMemUsed = mmem;
  1054. }
  1055. mg_atomic_inc(&mstat->blockCount);
  1056. ((uintptr_t *)data)[0] = size;
  1057. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1058. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1059. }
  1060. #if defined(MEMORY_DEBUGGING)
  1061. sprintf(mallocStr,
  1062. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1063. memory,
  1064. (unsigned long)size,
  1065. (unsigned long)mstat->totalMemUsed,
  1066. (unsigned long)mstat->blockCount,
  1067. file,
  1068. line);
  1069. #if defined(_WIN32)
  1070. OutputDebugStringA(mallocStr);
  1071. #else
  1072. DEBUG_TRACE("%s", mallocStr);
  1073. #endif
  1074. #endif
  1075. return memory;
  1076. }
  1077. static void *
  1078. mg_calloc_ex(size_t count,
  1079. size_t size,
  1080. struct mg_context *ctx,
  1081. const char *file,
  1082. unsigned line)
  1083. {
  1084. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1085. if (data) {
  1086. memset(data, 0, size * count);
  1087. }
  1088. return data;
  1089. }
  1090. static void
  1091. mg_free_ex(void *memory, const char *file, unsigned line)
  1092. {
  1093. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1094. #if defined(MEMORY_DEBUGGING)
  1095. char mallocStr[256];
  1096. #else
  1097. (void)file;
  1098. (void)line;
  1099. #endif
  1100. if (memory) {
  1101. uintptr_t size = ((uintptr_t *)data)[0];
  1102. struct mg_memory_stat *mstat =
  1103. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1104. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1105. mg_atomic_dec(&mstat->blockCount);
  1106. #if defined(MEMORY_DEBUGGING)
  1107. sprintf(mallocStr,
  1108. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1109. memory,
  1110. (unsigned long)size,
  1111. (unsigned long)mstat->totalMemUsed,
  1112. (unsigned long)mstat->blockCount,
  1113. file,
  1114. line);
  1115. #if defined(_WIN32)
  1116. OutputDebugStringA(mallocStr);
  1117. #else
  1118. DEBUG_TRACE("%s", mallocStr);
  1119. #endif
  1120. #endif
  1121. free(data);
  1122. }
  1123. }
  1124. static void *
  1125. mg_realloc_ex(void *memory,
  1126. size_t newsize,
  1127. struct mg_context *ctx,
  1128. const char *file,
  1129. unsigned line)
  1130. {
  1131. void *data;
  1132. void *_realloc;
  1133. uintptr_t oldsize;
  1134. #if defined(MEMORY_DEBUGGING)
  1135. char mallocStr[256];
  1136. #else
  1137. (void)file;
  1138. (void)line;
  1139. #endif
  1140. if (newsize) {
  1141. if (memory) {
  1142. /* Reallocate existing block */
  1143. struct mg_memory_stat *mstat;
  1144. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1145. oldsize = ((uintptr_t *)data)[0];
  1146. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1147. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1148. if (_realloc) {
  1149. data = _realloc;
  1150. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1151. #if defined(MEMORY_DEBUGGING)
  1152. sprintf(mallocStr,
  1153. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1154. memory,
  1155. (unsigned long)oldsize,
  1156. (unsigned long)mstat->totalMemUsed,
  1157. (unsigned long)mstat->blockCount,
  1158. file,
  1159. line);
  1160. #if defined(_WIN32)
  1161. OutputDebugStringA(mallocStr);
  1162. #else
  1163. DEBUG_TRACE("%s", mallocStr);
  1164. #endif
  1165. #endif
  1166. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1167. #if defined(MEMORY_DEBUGGING)
  1168. sprintf(mallocStr,
  1169. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1170. memory,
  1171. (unsigned long)newsize,
  1172. (unsigned long)mstat->totalMemUsed,
  1173. (unsigned long)mstat->blockCount,
  1174. file,
  1175. line);
  1176. #if defined(_WIN32)
  1177. OutputDebugStringA(mallocStr);
  1178. #else
  1179. DEBUG_TRACE("%s", mallocStr);
  1180. #endif
  1181. #endif
  1182. *(uintptr_t *)data = newsize;
  1183. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1184. } else {
  1185. #if defined(MEMORY_DEBUGGING)
  1186. #if defined(_WIN32)
  1187. OutputDebugStringA("MEM: realloc failed\n");
  1188. #else
  1189. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1190. #endif
  1191. #endif
  1192. return _realloc;
  1193. }
  1194. } else {
  1195. /* Allocate new block */
  1196. data = mg_malloc_ex(newsize, ctx, file, line);
  1197. }
  1198. } else {
  1199. /* Free existing block */
  1200. data = 0;
  1201. mg_free_ex(memory, file, line);
  1202. }
  1203. return data;
  1204. }
  1205. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1206. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1207. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1208. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1209. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1210. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1211. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1212. #else /* USE_SERVER_STATS */
  1213. static __inline void *
  1214. mg_malloc(size_t a)
  1215. {
  1216. return malloc(a);
  1217. }
  1218. static __inline void *
  1219. mg_calloc(size_t a, size_t b)
  1220. {
  1221. return calloc(a, b);
  1222. }
  1223. static __inline void *
  1224. mg_realloc(void *a, size_t b)
  1225. {
  1226. return realloc(a, b);
  1227. }
  1228. static __inline void
  1229. mg_free(void *a)
  1230. {
  1231. free(a);
  1232. }
  1233. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1234. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1235. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1236. #define mg_free_ctx(a, c) mg_free(a)
  1237. #endif /* USE_SERVER_STATS */
  1238. static void mg_vsnprintf(const struct mg_connection *conn,
  1239. int *truncated,
  1240. char *buf,
  1241. size_t buflen,
  1242. const char *fmt,
  1243. va_list ap);
  1244. static void mg_snprintf(const struct mg_connection *conn,
  1245. int *truncated,
  1246. char *buf,
  1247. size_t buflen,
  1248. PRINTF_FORMAT_STRING(const char *fmt),
  1249. ...) PRINTF_ARGS(5, 6);
  1250. /* This following lines are just meant as a reminder to use the mg-functions
  1251. * for memory management */
  1252. #if defined(malloc)
  1253. #undef malloc
  1254. #endif
  1255. #if defined(calloc)
  1256. #undef calloc
  1257. #endif
  1258. #if defined(realloc)
  1259. #undef realloc
  1260. #endif
  1261. #if defined(free)
  1262. #undef free
  1263. #endif
  1264. #if defined(snprintf)
  1265. #undef snprintf
  1266. #endif
  1267. #if defined(vsnprintf)
  1268. #undef vsnprintf
  1269. #endif
  1270. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1271. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1272. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1273. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1274. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1275. #if defined(_WIN32)
  1276. /* vsnprintf must not be used in any system,
  1277. * but this define only works well for Windows. */
  1278. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1279. #endif
  1280. /* mg_init_library counter */
  1281. static int mg_init_library_called = 0;
  1282. #if !defined(NO_SSL)
  1283. static int mg_ssl_initialized = 0;
  1284. #endif
  1285. static pthread_key_t sTlsKey; /* Thread local storage index */
  1286. static int thread_idx_max = 0;
  1287. #if defined(MG_LEGACY_INTERFACE)
  1288. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1289. #endif
  1290. struct mg_workerTLS {
  1291. int is_master;
  1292. unsigned long thread_idx;
  1293. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1294. HANDLE pthread_cond_helper_mutex;
  1295. struct mg_workerTLS *next_waiting_thread;
  1296. #endif
  1297. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1298. char txtbuf[4];
  1299. #endif
  1300. };
  1301. #if defined(__GNUC__) || defined(__MINGW32__)
  1302. /* Show no warning in case system functions are not used. */
  1303. #if GCC_VERSION >= 40500
  1304. #pragma GCC diagnostic push
  1305. #pragma GCC diagnostic ignored "-Wunused-function"
  1306. #endif /* GCC_VERSION >= 40500 */
  1307. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1308. #if defined(__clang__)
  1309. /* Show no warning in case system functions are not used. */
  1310. #pragma clang diagnostic push
  1311. #pragma clang diagnostic ignored "-Wunused-function"
  1312. #endif
  1313. /* Get a unique thread ID as unsigned long, independent from the data type
  1314. * of thread IDs defined by the operating system API.
  1315. * If two calls to mg_current_thread_id return the same value, they calls
  1316. * are done from the same thread. If they return different values, they are
  1317. * done from different threads. (Provided this function is used in the same
  1318. * process context and threads are not repeatedly created and deleted, but
  1319. * CivetWeb does not do that).
  1320. * This function must match the signature required for SSL id callbacks:
  1321. * CRYPTO_set_id_callback
  1322. */
  1323. FUNCTION_MAY_BE_UNUSED
  1324. static unsigned long
  1325. mg_current_thread_id(void)
  1326. {
  1327. #if defined(_WIN32)
  1328. return GetCurrentThreadId();
  1329. #else
  1330. #if defined(__clang__)
  1331. #pragma clang diagnostic push
  1332. #pragma clang diagnostic ignored "-Wunreachable-code"
  1333. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1334. * or not, so one of the two conditions will be unreachable by construction.
  1335. * Unfortunately the C standard does not define a way to check this at
  1336. * compile time, since the #if preprocessor conditions can not use the sizeof
  1337. * operator as an argument. */
  1338. #endif
  1339. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1340. /* This is the problematic case for CRYPTO_set_id_callback:
  1341. * The OS pthread_t can not be cast to unsigned long. */
  1342. struct mg_workerTLS *tls =
  1343. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1344. if (tls == NULL) {
  1345. /* SSL called from an unknown thread: Create some thread index.
  1346. */
  1347. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1348. tls->is_master = -2; /* -2 means "3rd party thread" */
  1349. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1350. pthread_setspecific(sTlsKey, tls);
  1351. }
  1352. return tls->thread_idx;
  1353. } else {
  1354. /* pthread_t may be any data type, so a simple cast to unsigned long
  1355. * can rise a warning/error, depending on the platform.
  1356. * Here memcpy is used as an anything-to-anything cast. */
  1357. unsigned long ret = 0;
  1358. pthread_t t = pthread_self();
  1359. memcpy(&ret, &t, sizeof(pthread_t));
  1360. return ret;
  1361. }
  1362. #if defined(__clang__)
  1363. #pragma clang diagnostic pop
  1364. #endif
  1365. #endif
  1366. }
  1367. FUNCTION_MAY_BE_UNUSED
  1368. static uint64_t
  1369. mg_get_current_time_ns(void)
  1370. {
  1371. struct timespec tsnow;
  1372. clock_gettime(CLOCK_REALTIME, &tsnow);
  1373. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1374. }
  1375. #if defined(__GNUC__)
  1376. /* Show no warning in case system functions are not used. */
  1377. #if GCC_VERSION >= 40500
  1378. #pragma GCC diagnostic pop
  1379. #endif /* GCC_VERSION >= 40500 */
  1380. #endif /* defined(__GNUC__) */
  1381. #if defined(__clang__)
  1382. /* Show no warning in case system functions are not used. */
  1383. #pragma clang diagnostic pop
  1384. #endif
  1385. #if defined(NEED_DEBUG_TRACE_FUNC)
  1386. static void
  1387. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1388. {
  1389. va_list args;
  1390. uint64_t nsnow;
  1391. static uint64_t nslast;
  1392. struct timespec tsnow;
  1393. /* Get some operating system independent thread id */
  1394. unsigned long thread_id = mg_current_thread_id();
  1395. clock_gettime(CLOCK_REALTIME, &tsnow);
  1396. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1397. + ((uint64_t)tsnow.tv_nsec);
  1398. if (!nslast) {
  1399. nslast = nsnow;
  1400. }
  1401. flockfile(stdout);
  1402. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1403. (unsigned long)tsnow.tv_sec,
  1404. (unsigned long)tsnow.tv_nsec,
  1405. nsnow - nslast,
  1406. thread_id,
  1407. func,
  1408. line);
  1409. va_start(args, fmt);
  1410. vprintf(fmt, args);
  1411. va_end(args);
  1412. putchar('\n');
  1413. fflush(stdout);
  1414. funlockfile(stdout);
  1415. nslast = nsnow;
  1416. }
  1417. #endif /* NEED_DEBUG_TRACE_FUNC */
  1418. #define MD5_STATIC static
  1419. #include "md5.inl"
  1420. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1421. #if defined(NO_SOCKLEN_T)
  1422. typedef int socklen_t;
  1423. #endif /* NO_SOCKLEN_T */
  1424. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1425. #if !defined(MSG_NOSIGNAL)
  1426. #define MSG_NOSIGNAL (0)
  1427. #endif
  1428. #if defined(NO_SSL)
  1429. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1430. typedef struct SSL_CTX SSL_CTX;
  1431. #else
  1432. #if defined(NO_SSL_DL)
  1433. #include <openssl/ssl.h>
  1434. #include <openssl/err.h>
  1435. #include <openssl/crypto.h>
  1436. #include <openssl/x509.h>
  1437. #include <openssl/pem.h>
  1438. #include <openssl/engine.h>
  1439. #include <openssl/conf.h>
  1440. #include <openssl/dh.h>
  1441. #include <openssl/bn.h>
  1442. #include <openssl/opensslv.h>
  1443. #if defined(WOLFSSL_VERSION)
  1444. /* Additional defines for WolfSSL, see
  1445. * https://github.com/civetweb/civetweb/issues/583 */
  1446. #include "wolfssl_extras.inl"
  1447. #endif
  1448. #else
  1449. /* SSL loaded dynamically from DLL.
  1450. * I put the prototypes here to be independent from OpenSSL source
  1451. * installation. */
  1452. typedef struct ssl_st SSL;
  1453. typedef struct ssl_method_st SSL_METHOD;
  1454. typedef struct ssl_ctx_st SSL_CTX;
  1455. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1456. typedef struct x509_name X509_NAME;
  1457. typedef struct asn1_integer ASN1_INTEGER;
  1458. typedef struct bignum BIGNUM;
  1459. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1460. typedef struct evp_md EVP_MD;
  1461. typedef struct x509 X509;
  1462. #define SSL_CTRL_OPTIONS (32)
  1463. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1464. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1465. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1466. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1467. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1468. #define SSL_VERIFY_NONE (0)
  1469. #define SSL_VERIFY_PEER (1)
  1470. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1471. #define SSL_VERIFY_CLIENT_ONCE (4)
  1472. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1473. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1474. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1475. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1476. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1477. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1478. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1479. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1480. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1481. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1482. #define SSL_CB_HANDSHAKE_START (0x10)
  1483. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1484. #define SSL_ERROR_NONE (0)
  1485. #define SSL_ERROR_SSL (1)
  1486. #define SSL_ERROR_WANT_READ (2)
  1487. #define SSL_ERROR_WANT_WRITE (3)
  1488. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1489. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1490. #define SSL_ERROR_ZERO_RETURN (6)
  1491. #define SSL_ERROR_WANT_CONNECT (7)
  1492. #define SSL_ERROR_WANT_ACCEPT (8)
  1493. #define TLSEXT_TYPE_server_name (0)
  1494. #define TLSEXT_NAMETYPE_host_name (0)
  1495. #define SSL_TLSEXT_ERR_OK (0)
  1496. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1497. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1498. #define SSL_TLSEXT_ERR_NOACK (3)
  1499. struct ssl_func {
  1500. const char *name; /* SSL function name */
  1501. void (*ptr)(void); /* Function pointer */
  1502. };
  1503. #if defined(OPENSSL_API_1_1)
  1504. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1505. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1506. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1507. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1508. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1509. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1510. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1511. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1512. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1513. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1514. #define OPENSSL_init_ssl \
  1515. (*(int (*)(uint64_t opts, \
  1516. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1517. #define SSL_CTX_use_PrivateKey_file \
  1518. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1519. #define SSL_CTX_use_certificate_file \
  1520. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1521. #define SSL_CTX_set_default_passwd_cb \
  1522. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1523. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1524. #define SSL_CTX_use_certificate_chain_file \
  1525. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1526. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1527. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1528. #define SSL_CTX_set_verify \
  1529. (*(void (*)(SSL_CTX *, \
  1530. int, \
  1531. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1532. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1533. #define SSL_CTX_load_verify_locations \
  1534. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1535. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1536. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1537. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1538. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1539. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1540. #define SSL_CIPHER_get_name \
  1541. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1542. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1543. #define SSL_CTX_set_session_id_context \
  1544. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1545. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1546. #define SSL_CTX_set_cipher_list \
  1547. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1548. #define SSL_CTX_set_options \
  1549. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1550. #define SSL_CTX_set_info_callback \
  1551. (*(void (*)(SSL_CTX * ctx, \
  1552. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1553. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1554. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1555. #define SSL_CTX_callback_ctrl \
  1556. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1557. #define SSL_get_servername \
  1558. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1559. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1560. #define SSL_CTX_clear_options(ctx, op) \
  1561. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1562. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1563. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1564. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1565. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1566. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1567. SSL_CTX_callback_ctrl(ctx, \
  1568. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1569. (void (*)(void))cb)
  1570. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1571. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1572. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1573. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1574. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1575. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1576. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1577. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1578. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1579. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1580. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1581. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1582. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1583. #define X509_NAME_oneline \
  1584. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1585. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1586. #define EVP_get_digestbyname \
  1587. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1588. #define EVP_Digest \
  1589. (*(int (*)( \
  1590. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1591. crypto_sw[10].ptr)
  1592. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1593. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1594. #define ASN1_INTEGER_to_BN \
  1595. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1596. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1597. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1598. #define OPENSSL_free(a) CRYPTO_free(a)
  1599. /* init_ssl_ctx() function updates this array.
  1600. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1601. * of respective functions. The macros above (like SSL_connect()) are really
  1602. * just calling these functions indirectly via the pointer. */
  1603. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1604. {"SSL_accept", NULL},
  1605. {"SSL_connect", NULL},
  1606. {"SSL_read", NULL},
  1607. {"SSL_write", NULL},
  1608. {"SSL_get_error", NULL},
  1609. {"SSL_set_fd", NULL},
  1610. {"SSL_new", NULL},
  1611. {"SSL_CTX_new", NULL},
  1612. {"TLS_server_method", NULL},
  1613. {"OPENSSL_init_ssl", NULL},
  1614. {"SSL_CTX_use_PrivateKey_file", NULL},
  1615. {"SSL_CTX_use_certificate_file", NULL},
  1616. {"SSL_CTX_set_default_passwd_cb", NULL},
  1617. {"SSL_CTX_free", NULL},
  1618. {"SSL_CTX_use_certificate_chain_file", NULL},
  1619. {"TLS_client_method", NULL},
  1620. {"SSL_pending", NULL},
  1621. {"SSL_CTX_set_verify", NULL},
  1622. {"SSL_shutdown", NULL},
  1623. {"SSL_CTX_load_verify_locations", NULL},
  1624. {"SSL_CTX_set_default_verify_paths", NULL},
  1625. {"SSL_CTX_set_verify_depth", NULL},
  1626. {"SSL_get_peer_certificate", NULL},
  1627. {"SSL_get_version", NULL},
  1628. {"SSL_get_current_cipher", NULL},
  1629. {"SSL_CIPHER_get_name", NULL},
  1630. {"SSL_CTX_check_private_key", NULL},
  1631. {"SSL_CTX_set_session_id_context", NULL},
  1632. {"SSL_CTX_ctrl", NULL},
  1633. {"SSL_CTX_set_cipher_list", NULL},
  1634. {"SSL_CTX_set_options", NULL},
  1635. {"SSL_CTX_set_info_callback", NULL},
  1636. {"SSL_get_ex_data", NULL},
  1637. {"SSL_set_ex_data", NULL},
  1638. {"SSL_CTX_callback_ctrl", NULL},
  1639. {"SSL_get_servername", NULL},
  1640. {"SSL_set_SSL_CTX", NULL},
  1641. {NULL, NULL}};
  1642. /* Similar array as ssl_sw. These functions could be located in different
  1643. * lib. */
  1644. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1645. {"ERR_error_string", NULL},
  1646. {"ERR_remove_state", NULL},
  1647. {"CONF_modules_unload", NULL},
  1648. {"X509_free", NULL},
  1649. {"X509_get_subject_name", NULL},
  1650. {"X509_get_issuer_name", NULL},
  1651. {"X509_NAME_oneline", NULL},
  1652. {"X509_get_serialNumber", NULL},
  1653. {"EVP_get_digestbyname", NULL},
  1654. {"EVP_Digest", NULL},
  1655. {"i2d_X509", NULL},
  1656. {"BN_bn2hex", NULL},
  1657. {"ASN1_INTEGER_to_BN", NULL},
  1658. {"BN_free", NULL},
  1659. {"CRYPTO_free", NULL},
  1660. {NULL, NULL}};
  1661. #else
  1662. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1663. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1664. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1665. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1666. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1667. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1668. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1669. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1670. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1671. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1672. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1673. #define SSL_CTX_use_PrivateKey_file \
  1674. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1675. #define SSL_CTX_use_certificate_file \
  1676. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1677. #define SSL_CTX_set_default_passwd_cb \
  1678. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1679. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1680. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1681. #define SSL_CTX_use_certificate_chain_file \
  1682. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1683. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1684. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1685. #define SSL_CTX_set_verify \
  1686. (*(void (*)(SSL_CTX *, \
  1687. int, \
  1688. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1689. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1690. #define SSL_CTX_load_verify_locations \
  1691. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1692. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1693. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1694. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1695. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1696. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1697. #define SSL_CIPHER_get_name \
  1698. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1699. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1700. #define SSL_CTX_set_session_id_context \
  1701. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1702. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1703. #define SSL_CTX_set_cipher_list \
  1704. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1705. #define SSL_CTX_set_info_callback \
  1706. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1707. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1708. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1709. #define SSL_CTX_callback_ctrl \
  1710. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1711. #define SSL_get_servername \
  1712. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1713. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1714. #define SSL_CTX_set_options(ctx, op) \
  1715. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1716. #define SSL_CTX_clear_options(ctx, op) \
  1717. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1718. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1719. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1720. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1721. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1722. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1723. SSL_CTX_callback_ctrl(ctx, \
  1724. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1725. (void (*)(void))cb)
  1726. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1727. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1728. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1729. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1730. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1731. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1732. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1733. #define CRYPTO_set_locking_callback \
  1734. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1735. #define CRYPTO_set_id_callback \
  1736. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1737. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1738. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1739. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1740. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1741. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1742. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1743. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1744. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1745. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1746. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1747. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1748. #define X509_NAME_oneline \
  1749. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1750. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1751. #define i2c_ASN1_INTEGER \
  1752. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1753. #define EVP_get_digestbyname \
  1754. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1755. #define EVP_Digest \
  1756. (*(int (*)( \
  1757. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1758. crypto_sw[18].ptr)
  1759. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1760. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1761. #define ASN1_INTEGER_to_BN \
  1762. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1763. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1764. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1765. #define OPENSSL_free(a) CRYPTO_free(a)
  1766. /* init_ssl_ctx() function updates this array.
  1767. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1768. * of respective functions. The macros above (like SSL_connect()) are really
  1769. * just calling these functions indirectly via the pointer. */
  1770. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1771. {"SSL_accept", NULL},
  1772. {"SSL_connect", NULL},
  1773. {"SSL_read", NULL},
  1774. {"SSL_write", NULL},
  1775. {"SSL_get_error", NULL},
  1776. {"SSL_set_fd", NULL},
  1777. {"SSL_new", NULL},
  1778. {"SSL_CTX_new", NULL},
  1779. {"SSLv23_server_method", NULL},
  1780. {"SSL_library_init", NULL},
  1781. {"SSL_CTX_use_PrivateKey_file", NULL},
  1782. {"SSL_CTX_use_certificate_file", NULL},
  1783. {"SSL_CTX_set_default_passwd_cb", NULL},
  1784. {"SSL_CTX_free", NULL},
  1785. {"SSL_load_error_strings", NULL},
  1786. {"SSL_CTX_use_certificate_chain_file", NULL},
  1787. {"SSLv23_client_method", NULL},
  1788. {"SSL_pending", NULL},
  1789. {"SSL_CTX_set_verify", NULL},
  1790. {"SSL_shutdown", NULL},
  1791. {"SSL_CTX_load_verify_locations", NULL},
  1792. {"SSL_CTX_set_default_verify_paths", NULL},
  1793. {"SSL_CTX_set_verify_depth", NULL},
  1794. {"SSL_get_peer_certificate", NULL},
  1795. {"SSL_get_version", NULL},
  1796. {"SSL_get_current_cipher", NULL},
  1797. {"SSL_CIPHER_get_name", NULL},
  1798. {"SSL_CTX_check_private_key", NULL},
  1799. {"SSL_CTX_set_session_id_context", NULL},
  1800. {"SSL_CTX_ctrl", NULL},
  1801. {"SSL_CTX_set_cipher_list", NULL},
  1802. {"SSL_CTX_set_info_callback", NULL},
  1803. {"SSL_get_ex_data", NULL},
  1804. {"SSL_set_ex_data", NULL},
  1805. {"SSL_CTX_callback_ctrl", NULL},
  1806. {"SSL_get_servername", NULL},
  1807. {"SSL_set_SSL_CTX", NULL},
  1808. {NULL, NULL}};
  1809. /* Similar array as ssl_sw. These functions could be located in different
  1810. * lib. */
  1811. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1812. {"CRYPTO_set_locking_callback", NULL},
  1813. {"CRYPTO_set_id_callback", NULL},
  1814. {"ERR_get_error", NULL},
  1815. {"ERR_error_string", NULL},
  1816. {"ERR_remove_state", NULL},
  1817. {"ERR_free_strings", NULL},
  1818. {"ENGINE_cleanup", NULL},
  1819. {"CONF_modules_unload", NULL},
  1820. {"CRYPTO_cleanup_all_ex_data", NULL},
  1821. {"EVP_cleanup", NULL},
  1822. {"X509_free", NULL},
  1823. {"X509_get_subject_name", NULL},
  1824. {"X509_get_issuer_name", NULL},
  1825. {"X509_NAME_oneline", NULL},
  1826. {"X509_get_serialNumber", NULL},
  1827. {"i2c_ASN1_INTEGER", NULL},
  1828. {"EVP_get_digestbyname", NULL},
  1829. {"EVP_Digest", NULL},
  1830. {"i2d_X509", NULL},
  1831. {"BN_bn2hex", NULL},
  1832. {"ASN1_INTEGER_to_BN", NULL},
  1833. {"BN_free", NULL},
  1834. {"CRYPTO_free", NULL},
  1835. {NULL, NULL}};
  1836. #endif /* OPENSSL_API_1_1 */
  1837. #endif /* NO_SSL_DL */
  1838. #endif /* NO_SSL */
  1839. #if !defined(NO_CACHING)
  1840. static const char *month_names[] = {"Jan",
  1841. "Feb",
  1842. "Mar",
  1843. "Apr",
  1844. "May",
  1845. "Jun",
  1846. "Jul",
  1847. "Aug",
  1848. "Sep",
  1849. "Oct",
  1850. "Nov",
  1851. "Dec"};
  1852. #endif /* !NO_CACHING */
  1853. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1854. * the
  1855. * union u. */
  1856. union usa {
  1857. struct sockaddr sa;
  1858. struct sockaddr_in sin;
  1859. #if defined(USE_IPV6)
  1860. struct sockaddr_in6 sin6;
  1861. #endif
  1862. };
  1863. /* Describes a string (chunk of memory). */
  1864. struct vec {
  1865. const char *ptr;
  1866. size_t len;
  1867. };
  1868. struct mg_file_stat {
  1869. /* File properties filled by mg_stat: */
  1870. uint64_t size;
  1871. time_t last_modified;
  1872. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1873. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1874. * case we need a "Content-Eencoding: gzip" header */
  1875. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1876. };
  1877. struct mg_file_in_memory {
  1878. char *p;
  1879. uint32_t pos;
  1880. char mode;
  1881. };
  1882. struct mg_file_access {
  1883. /* File properties filled by mg_fopen: */
  1884. FILE *fp;
  1885. #if defined(MG_USE_OPEN_FILE)
  1886. /* TODO (low): Remove obsolete "file in memory" implementation.
  1887. * In an "early 2017" discussion at Google groups
  1888. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1889. * we decided to get rid of this feature (after some fade-out
  1890. * phase). */
  1891. const char *membuf;
  1892. #endif
  1893. };
  1894. struct mg_file {
  1895. struct mg_file_stat stat;
  1896. struct mg_file_access access;
  1897. };
  1898. #if defined(MG_USE_OPEN_FILE)
  1899. #define STRUCT_FILE_INITIALIZER \
  1900. { \
  1901. { \
  1902. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1903. } \
  1904. , \
  1905. { \
  1906. (FILE *) NULL, (const char *)NULL \
  1907. } \
  1908. }
  1909. #else
  1910. #define STRUCT_FILE_INITIALIZER \
  1911. { \
  1912. { \
  1913. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1914. } \
  1915. , \
  1916. { \
  1917. (FILE *) NULL \
  1918. } \
  1919. }
  1920. #endif
  1921. /* Describes listening socket, or socket which was accept()-ed by the master
  1922. * thread and queued for future handling by the worker thread. */
  1923. struct socket {
  1924. SOCKET sock; /* Listening socket */
  1925. union usa lsa; /* Local socket address */
  1926. union usa rsa; /* Remote socket address */
  1927. unsigned char is_ssl; /* Is port SSL-ed */
  1928. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1929. * port */
  1930. unsigned char in_use; /* Is valid */
  1931. };
  1932. /* Enum const for all options must be in sync with
  1933. * static struct mg_option config_options[]
  1934. * This is tested in the unit test (test/private.c)
  1935. * "Private Config Options"
  1936. */
  1937. enum {
  1938. LISTENING_PORTS,
  1939. NUM_THREADS,
  1940. RUN_AS_USER,
  1941. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1942. * socket option typedef TCP_NODELAY. */
  1943. MAX_REQUEST_SIZE,
  1944. LINGER_TIMEOUT,
  1945. #if defined(__linux__)
  1946. ALLOW_SENDFILE_CALL,
  1947. #endif
  1948. #if defined(_WIN32)
  1949. CASE_SENSITIVE_FILES,
  1950. #endif
  1951. THROTTLE,
  1952. ACCESS_LOG_FILE,
  1953. ERROR_LOG_FILE,
  1954. ENABLE_KEEP_ALIVE,
  1955. REQUEST_TIMEOUT,
  1956. KEEP_ALIVE_TIMEOUT,
  1957. #if defined(USE_WEBSOCKET)
  1958. WEBSOCKET_TIMEOUT,
  1959. ENABLE_WEBSOCKET_PING_PONG,
  1960. #endif
  1961. DECODE_URL,
  1962. #if defined(USE_LUA)
  1963. LUA_BACKGROUND_SCRIPT,
  1964. LUA_BACKGROUND_SCRIPT_PARAMS,
  1965. #endif
  1966. DOCUMENT_ROOT,
  1967. CGI_EXTENSIONS,
  1968. CGI_ENVIRONMENT,
  1969. PUT_DELETE_PASSWORDS_FILE,
  1970. CGI_INTERPRETER,
  1971. PROTECT_URI,
  1972. AUTHENTICATION_DOMAIN,
  1973. ENABLE_AUTH_DOMAIN_CHECK,
  1974. SSI_EXTENSIONS,
  1975. ENABLE_DIRECTORY_LISTING,
  1976. GLOBAL_PASSWORDS_FILE,
  1977. INDEX_FILES,
  1978. ACCESS_CONTROL_LIST,
  1979. EXTRA_MIME_TYPES,
  1980. SSL_CERTIFICATE,
  1981. SSL_CERTIFICATE_CHAIN,
  1982. URL_REWRITE_PATTERN,
  1983. HIDE_FILES,
  1984. SSL_DO_VERIFY_PEER,
  1985. SSL_CA_PATH,
  1986. SSL_CA_FILE,
  1987. SSL_VERIFY_DEPTH,
  1988. SSL_DEFAULT_VERIFY_PATHS,
  1989. SSL_CIPHER_LIST,
  1990. SSL_PROTOCOL_VERSION,
  1991. SSL_SHORT_TRUST,
  1992. #if defined(USE_LUA)
  1993. LUA_PRELOAD_FILE,
  1994. LUA_SCRIPT_EXTENSIONS,
  1995. LUA_SERVER_PAGE_EXTENSIONS,
  1996. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1997. LUA_DEBUG_PARAMS,
  1998. #endif
  1999. #endif
  2000. #if defined(USE_DUKTAPE)
  2001. DUKTAPE_SCRIPT_EXTENSIONS,
  2002. #endif
  2003. #if defined(USE_WEBSOCKET)
  2004. WEBSOCKET_ROOT,
  2005. #endif
  2006. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2007. LUA_WEBSOCKET_EXTENSIONS,
  2008. #endif
  2009. ACCESS_CONTROL_ALLOW_ORIGIN,
  2010. ACCESS_CONTROL_ALLOW_METHODS,
  2011. ACCESS_CONTROL_ALLOW_HEADERS,
  2012. ERROR_PAGES,
  2013. #if !defined(NO_CACHING)
  2014. STATIC_FILE_MAX_AGE,
  2015. #endif
  2016. #if !defined(NO_SSL)
  2017. STRICT_HTTPS_MAX_AGE,
  2018. #endif
  2019. ADDITIONAL_HEADER,
  2020. ALLOW_INDEX_SCRIPT_SUB_RES,
  2021. NUM_OPTIONS
  2022. };
  2023. /* Config option name, config types, default value.
  2024. * Must be in the same order as the enum const above.
  2025. */
  2026. static const struct mg_option config_options[] = {
  2027. /* Once for each server */
  2028. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2029. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2030. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2031. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2032. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2033. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2034. #if defined(__linux__)
  2035. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2036. #endif
  2037. #if defined(_WIN32)
  2038. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2039. #endif
  2040. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2041. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2042. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2043. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2044. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2045. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2046. #if defined(USE_WEBSOCKET)
  2047. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2048. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2049. #endif
  2050. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2051. #if defined(USE_LUA)
  2052. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2053. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2054. #endif
  2055. /* Once for each domain */
  2056. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2057. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2058. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2059. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2060. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2061. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2062. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2063. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2064. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2065. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2066. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2067. {"index_files",
  2068. MG_CONFIG_TYPE_STRING_LIST,
  2069. #if defined(USE_LUA)
  2070. "index.xhtml,index.html,index.htm,"
  2071. "index.lp,index.lsp,index.lua,index.cgi,"
  2072. "index.shtml,index.php"},
  2073. #else
  2074. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2075. #endif
  2076. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2077. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2078. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2079. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2080. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2081. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2082. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2083. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2084. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2085. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2086. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2087. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2088. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2089. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2090. #if defined(USE_LUA)
  2091. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2092. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2093. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2094. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2095. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2096. #endif
  2097. #endif
  2098. #if defined(USE_DUKTAPE)
  2099. /* The support for duktape is still in alpha version state.
  2100. * The name of this config option might change. */
  2101. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2102. #endif
  2103. #if defined(USE_WEBSOCKET)
  2104. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2105. #endif
  2106. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2107. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2108. #endif
  2109. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2110. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2111. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2112. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2113. #if !defined(NO_CACHING)
  2114. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2115. #endif
  2116. #if !defined(NO_SSL)
  2117. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2118. #endif
  2119. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2120. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2121. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2122. /* Check if the config_options and the corresponding enum have compatible
  2123. * sizes. */
  2124. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2125. == (NUM_OPTIONS + 1),
  2126. "config_options and enum not sync");
  2127. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2128. struct mg_handler_info {
  2129. /* Name/Pattern of the URI. */
  2130. char *uri;
  2131. size_t uri_len;
  2132. /* handler type */
  2133. int handler_type;
  2134. /* Handler for http/https or authorization requests. */
  2135. mg_request_handler handler;
  2136. unsigned int refcount;
  2137. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2138. pthread_cond_t
  2139. refcount_cond; /* Signaled when handler refcount is decremented */
  2140. /* Handler for ws/wss (websocket) requests. */
  2141. mg_websocket_connect_handler connect_handler;
  2142. mg_websocket_ready_handler ready_handler;
  2143. mg_websocket_data_handler data_handler;
  2144. mg_websocket_close_handler close_handler;
  2145. /* accepted subprotocols for ws/wss requests. */
  2146. struct mg_websocket_subprotocols *subprotocols;
  2147. /* Handler for authorization requests */
  2148. mg_authorization_handler auth_handler;
  2149. /* User supplied argument for the handler function. */
  2150. void *cbdata;
  2151. /* next handler in a linked list */
  2152. struct mg_handler_info *next;
  2153. };
  2154. enum {
  2155. CONTEXT_INVALID,
  2156. CONTEXT_SERVER,
  2157. CONTEXT_HTTP_CLIENT,
  2158. CONTEXT_WS_CLIENT
  2159. };
  2160. struct mg_domain_context {
  2161. SSL_CTX *ssl_ctx; /* SSL context */
  2162. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2163. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2164. /* Server nonce */
  2165. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2166. unsigned long nonce_count; /* Used nonces, used for authentication */
  2167. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2168. /* linked list of shared lua websockets */
  2169. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2170. #endif
  2171. /* Linked list of domains */
  2172. struct mg_domain_context *next;
  2173. };
  2174. struct mg_context {
  2175. /* Part 1 - Physical context:
  2176. * This holds threads, ports, timeouts, ...
  2177. * set for the entire server, independent from the
  2178. * addressed hostname.
  2179. */
  2180. /* Connection related */
  2181. int context_type; /* See CONTEXT_* above */
  2182. struct socket *listening_sockets;
  2183. struct pollfd *listening_socket_fds;
  2184. unsigned int num_listening_sockets;
  2185. struct mg_connection *worker_connections; /* The connection struct, pre-
  2186. * allocated for each worker */
  2187. #if defined(USE_SERVER_STATS)
  2188. int active_connections;
  2189. int max_connections;
  2190. int64_t total_connections;
  2191. int64_t total_requests;
  2192. int64_t total_data_read;
  2193. int64_t total_data_written;
  2194. #endif
  2195. /* Thread related */
  2196. volatile int stop_flag; /* Should we stop event loop */
  2197. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2198. pthread_t masterthreadid; /* The master thread ID */
  2199. unsigned int
  2200. cfg_worker_threads; /* The number of configured worker threads. */
  2201. pthread_t *worker_threadids; /* The worker thread IDs */
  2202. /* Connection to thread dispatching */
  2203. #if defined(ALTERNATIVE_QUEUE)
  2204. struct socket *client_socks;
  2205. void **client_wait_events;
  2206. #else
  2207. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2208. volatile int sq_head; /* Head of the socket queue */
  2209. volatile int sq_tail; /* Tail of the socket queue */
  2210. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2211. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2212. #endif
  2213. /* Memory related */
  2214. unsigned int max_request_size; /* The max request size */
  2215. #if defined(USE_SERVER_STATS)
  2216. struct mg_memory_stat ctx_memory;
  2217. #endif
  2218. /* Operating system related */
  2219. char *systemName; /* What operating system is running */
  2220. time_t start_time; /* Server start time, used for authentication
  2221. * and for diagnstics. */
  2222. #if defined(USE_TIMERS)
  2223. struct ttimers *timers;
  2224. #endif
  2225. /* Lua specific: Background operations and shared websockets */
  2226. #if defined(USE_LUA)
  2227. void *lua_background_state;
  2228. #endif
  2229. /* Server nonce */
  2230. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2231. /* Server callbacks */
  2232. struct mg_callbacks callbacks; /* User-defined callback function */
  2233. void *user_data; /* User-defined data */
  2234. /* Part 2 - Logical domain:
  2235. * This holds hostname, TLS certificate, document root, ...
  2236. * set for a domain hosted at the server.
  2237. * There may be multiple domains hosted at one physical server.
  2238. * The default domain "dd" is the first element of a list of
  2239. * domains.
  2240. */
  2241. struct mg_domain_context dd; /* default domain */
  2242. };
  2243. #if defined(USE_SERVER_STATS)
  2244. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2245. static struct mg_memory_stat *
  2246. get_memory_stat(struct mg_context *ctx)
  2247. {
  2248. if (ctx) {
  2249. return &(ctx->ctx_memory);
  2250. }
  2251. return &mg_common_memory;
  2252. }
  2253. #endif
  2254. enum {
  2255. CONNECTION_TYPE_INVALID,
  2256. CONNECTION_TYPE_REQUEST,
  2257. CONNECTION_TYPE_RESPONSE
  2258. };
  2259. struct mg_connection {
  2260. int connection_type; /* see CONNECTION_TYPE_* above */
  2261. struct mg_request_info request_info;
  2262. struct mg_response_info response_info;
  2263. struct mg_context *phys_ctx;
  2264. struct mg_domain_context *dom_ctx;
  2265. #if defined(USE_SERVER_STATS)
  2266. int conn_state; /* 0 = undef, numerical value may change in different
  2267. * versions. For the current definition, see
  2268. * mg_get_connection_info_impl */
  2269. #endif
  2270. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2271. SSL *ssl; /* SSL descriptor */
  2272. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2273. struct socket client; /* Connected client */
  2274. time_t conn_birth_time; /* Time (wall clock) when connection was
  2275. * established */
  2276. struct timespec req_time; /* Time (since system start) when the request
  2277. * was received */
  2278. int64_t num_bytes_sent; /* Total bytes sent to client */
  2279. int64_t content_len; /* Content-Length header value */
  2280. int64_t consumed_content; /* How many bytes of content have been read */
  2281. int is_chunked; /* Transfer-Encoding is chunked:
  2282. * 0 = not chunked,
  2283. * 1 = chunked, do data read yet,
  2284. * 2 = chunked, some data read,
  2285. * 3 = chunked, all data read
  2286. */
  2287. size_t chunk_remainder; /* Unread data from the last chunk */
  2288. char *buf; /* Buffer for received data */
  2289. char *path_info; /* PATH_INFO part of the URL */
  2290. int must_close; /* 1 if connection must be closed */
  2291. int accept_gzip; /* 1 if gzip encoding is accepted */
  2292. int in_error_handler; /* 1 if in handler for user defined error
  2293. * pages */
  2294. #if defined(USE_WEBSOCKET)
  2295. int in_websocket_handling; /* 1 if in read_websocket */
  2296. #endif
  2297. int handled_requests; /* Number of requests handled by this connection
  2298. */
  2299. int buf_size; /* Buffer size */
  2300. int request_len; /* Size of the request + headers in a buffer */
  2301. int data_len; /* Total size of data in a buffer */
  2302. int status_code; /* HTTP reply status code, e.g. 200 */
  2303. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2304. * throttle */
  2305. time_t last_throttle_time; /* Last time throttled data was sent */
  2306. int64_t last_throttle_bytes; /* Bytes sent this second */
  2307. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2308. * atomic transmissions for websockets */
  2309. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2310. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2311. #endif
  2312. int thread_index; /* Thread index within ctx */
  2313. };
  2314. /* Directory entry */
  2315. struct de {
  2316. struct mg_connection *conn;
  2317. char *file_name;
  2318. struct mg_file_stat file;
  2319. };
  2320. #if defined(USE_WEBSOCKET)
  2321. static int is_websocket_protocol(const struct mg_connection *conn);
  2322. #else
  2323. #define is_websocket_protocol(conn) (0)
  2324. #endif
  2325. #define mg_cry_internal(conn, fmt, ...) \
  2326. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2327. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2328. const char *func,
  2329. unsigned line,
  2330. const char *fmt,
  2331. ...) PRINTF_ARGS(4, 5);
  2332. #if !defined(NO_THREAD_NAME)
  2333. #if defined(_WIN32) && defined(_MSC_VER)
  2334. /* Set the thread name for debugging purposes in Visual Studio
  2335. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2336. */
  2337. #pragma pack(push, 8)
  2338. typedef struct tagTHREADNAME_INFO {
  2339. DWORD dwType; /* Must be 0x1000. */
  2340. LPCSTR szName; /* Pointer to name (in user addr space). */
  2341. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2342. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2343. } THREADNAME_INFO;
  2344. #pragma pack(pop)
  2345. #elif defined(__linux__)
  2346. #include <sys/prctl.h>
  2347. #include <sys/sendfile.h>
  2348. #if defined(ALTERNATIVE_QUEUE)
  2349. #include <sys/eventfd.h>
  2350. #endif /* ALTERNATIVE_QUEUE */
  2351. #if defined(ALTERNATIVE_QUEUE)
  2352. static void *
  2353. event_create(void)
  2354. {
  2355. int evhdl = eventfd(0, EFD_CLOEXEC);
  2356. int *ret;
  2357. if (evhdl == -1) {
  2358. /* Linux uses -1 on error, Windows NULL. */
  2359. /* However, Linux does not return 0 on success either. */
  2360. return 0;
  2361. }
  2362. ret = (int *)mg_malloc(sizeof(int));
  2363. if (ret) {
  2364. *ret = evhdl;
  2365. } else {
  2366. (void)close(evhdl);
  2367. }
  2368. return (void *)ret;
  2369. }
  2370. static int
  2371. event_wait(void *eventhdl)
  2372. {
  2373. uint64_t u;
  2374. int evhdl, s;
  2375. if (!eventhdl) {
  2376. /* error */
  2377. return 0;
  2378. }
  2379. evhdl = *(int *)eventhdl;
  2380. s = (int)read(evhdl, &u, sizeof(u));
  2381. if (s != sizeof(u)) {
  2382. /* error */
  2383. return 0;
  2384. }
  2385. (void)u; /* the value is not required */
  2386. return 1;
  2387. }
  2388. static int
  2389. event_signal(void *eventhdl)
  2390. {
  2391. uint64_t u = 1;
  2392. int evhdl, s;
  2393. if (!eventhdl) {
  2394. /* error */
  2395. return 0;
  2396. }
  2397. evhdl = *(int *)eventhdl;
  2398. s = (int)write(evhdl, &u, sizeof(u));
  2399. if (s != sizeof(u)) {
  2400. /* error */
  2401. return 0;
  2402. }
  2403. return 1;
  2404. }
  2405. static void
  2406. event_destroy(void *eventhdl)
  2407. {
  2408. int evhdl;
  2409. if (!eventhdl) {
  2410. /* error */
  2411. return;
  2412. }
  2413. evhdl = *(int *)eventhdl;
  2414. close(evhdl);
  2415. mg_free(eventhdl);
  2416. }
  2417. #endif
  2418. #endif
  2419. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2420. struct posix_event {
  2421. pthread_mutex_t mutex;
  2422. pthread_cond_t cond;
  2423. };
  2424. static void *
  2425. event_create(void)
  2426. {
  2427. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2428. if (ret == 0) {
  2429. /* out of memory */
  2430. return 0;
  2431. }
  2432. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2433. /* pthread mutex not available */
  2434. mg_free(ret);
  2435. return 0;
  2436. }
  2437. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2438. /* pthread cond not available */
  2439. pthread_mutex_destroy(&(ret->mutex));
  2440. mg_free(ret);
  2441. return 0;
  2442. }
  2443. return (void *)ret;
  2444. }
  2445. static int
  2446. event_wait(void *eventhdl)
  2447. {
  2448. struct posix_event *ev = (struct posix_event *)eventhdl;
  2449. pthread_mutex_lock(&(ev->mutex));
  2450. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2451. pthread_mutex_unlock(&(ev->mutex));
  2452. return 1;
  2453. }
  2454. static int
  2455. event_signal(void *eventhdl)
  2456. {
  2457. struct posix_event *ev = (struct posix_event *)eventhdl;
  2458. pthread_mutex_lock(&(ev->mutex));
  2459. pthread_cond_signal(&(ev->cond));
  2460. pthread_mutex_unlock(&(ev->mutex));
  2461. return 1;
  2462. }
  2463. static void
  2464. event_destroy(void *eventhdl)
  2465. {
  2466. struct posix_event *ev = (struct posix_event *)eventhdl;
  2467. pthread_cond_destroy(&(ev->cond));
  2468. pthread_mutex_destroy(&(ev->mutex));
  2469. mg_free(ev);
  2470. }
  2471. #endif
  2472. static void
  2473. mg_set_thread_name(const char *name)
  2474. {
  2475. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2476. mg_snprintf(
  2477. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2478. #if defined(_WIN32)
  2479. #if defined(_MSC_VER)
  2480. /* Windows and Visual Studio Compiler */
  2481. __try
  2482. {
  2483. THREADNAME_INFO info;
  2484. info.dwType = 0x1000;
  2485. info.szName = threadName;
  2486. info.dwThreadID = ~0U;
  2487. info.dwFlags = 0;
  2488. RaiseException(0x406D1388,
  2489. 0,
  2490. sizeof(info) / sizeof(ULONG_PTR),
  2491. (ULONG_PTR *)&info);
  2492. }
  2493. __except(EXCEPTION_EXECUTE_HANDLER)
  2494. {
  2495. }
  2496. #elif defined(__MINGW32__)
  2497. /* No option known to set thread name for MinGW */
  2498. #endif
  2499. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2500. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2501. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2502. (void)pthread_setname_np(pthread_self(), threadName);
  2503. #elif defined(__linux__)
  2504. /* on linux we can use the old prctl function */
  2505. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2506. #endif
  2507. }
  2508. #else /* !defined(NO_THREAD_NAME) */
  2509. void
  2510. mg_set_thread_name(const char *threadName)
  2511. {
  2512. }
  2513. #endif
  2514. #if defined(MG_LEGACY_INTERFACE)
  2515. const char **
  2516. mg_get_valid_option_names(void)
  2517. {
  2518. /* This function is deprecated. Use mg_get_valid_options instead. */
  2519. static const char *
  2520. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2521. int i;
  2522. for (i = 0; config_options[i].name != NULL; i++) {
  2523. data[i * 2] = config_options[i].name;
  2524. data[i * 2 + 1] = config_options[i].default_value;
  2525. }
  2526. return data;
  2527. }
  2528. #endif
  2529. const struct mg_option *
  2530. mg_get_valid_options(void)
  2531. {
  2532. return config_options;
  2533. }
  2534. /* Do not open file (used in is_file_in_memory) */
  2535. #define MG_FOPEN_MODE_NONE (0)
  2536. /* Open file for read only access */
  2537. #define MG_FOPEN_MODE_READ (1)
  2538. /* Open file for writing, create and overwrite */
  2539. #define MG_FOPEN_MODE_WRITE (2)
  2540. /* Open file for writing, create and append */
  2541. #define MG_FOPEN_MODE_APPEND (4)
  2542. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2543. * output filep and return 1, otherwise return 0 and don't modify anything.
  2544. */
  2545. static int
  2546. open_file_in_memory(const struct mg_connection *conn,
  2547. const char *path,
  2548. struct mg_file *filep,
  2549. int mode)
  2550. {
  2551. #if defined(MG_USE_OPEN_FILE)
  2552. size_t size = 0;
  2553. const char *buf = NULL;
  2554. if (!conn) {
  2555. return 0;
  2556. }
  2557. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2558. return 0;
  2559. }
  2560. if (conn->phys_ctx->callbacks.open_file) {
  2561. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2562. if (buf != NULL) {
  2563. if (filep == NULL) {
  2564. /* This is a file in memory, but we cannot store the
  2565. * properties
  2566. * now.
  2567. * Called from "is_file_in_memory" function. */
  2568. return 1;
  2569. }
  2570. /* NOTE: override filep->size only on success. Otherwise, it
  2571. * might
  2572. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2573. filep->access.membuf = buf;
  2574. filep->access.fp = NULL;
  2575. /* Size was set by the callback */
  2576. filep->stat.size = size;
  2577. /* Assume the data may change during runtime by setting
  2578. * last_modified = now */
  2579. filep->stat.last_modified = time(NULL);
  2580. filep->stat.is_directory = 0;
  2581. filep->stat.is_gzipped = 0;
  2582. }
  2583. }
  2584. return (buf != NULL);
  2585. #else
  2586. (void)conn;
  2587. (void)path;
  2588. (void)filep;
  2589. (void)mode;
  2590. return 0;
  2591. #endif
  2592. }
  2593. static int
  2594. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2595. {
  2596. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2597. }
  2598. static int
  2599. is_file_opened(const struct mg_file_access *fileacc)
  2600. {
  2601. if (!fileacc) {
  2602. return 0;
  2603. }
  2604. #if defined(MG_USE_OPEN_FILE)
  2605. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2606. #else
  2607. return (fileacc->fp != NULL);
  2608. #endif
  2609. }
  2610. static int mg_stat(const struct mg_connection *conn,
  2611. const char *path,
  2612. struct mg_file_stat *filep);
  2613. /* mg_fopen will open a file either in memory or on the disk.
  2614. * The input parameter path is a string in UTF-8 encoding.
  2615. * The input parameter mode is MG_FOPEN_MODE_*
  2616. * On success, either fp or membuf will be set in the output
  2617. * struct file. All status members will also be set.
  2618. * The function returns 1 on success, 0 on error. */
  2619. static int
  2620. mg_fopen(const struct mg_connection *conn,
  2621. const char *path,
  2622. int mode,
  2623. struct mg_file *filep)
  2624. {
  2625. int found;
  2626. if (!filep) {
  2627. return 0;
  2628. }
  2629. filep->access.fp = NULL;
  2630. #if defined(MG_USE_OPEN_FILE)
  2631. filep->access.membuf = NULL;
  2632. #endif
  2633. if (!is_file_in_memory(conn, path)) {
  2634. /* filep is initialized in mg_stat: all fields with memset to,
  2635. * some fields like size and modification date with values */
  2636. found = mg_stat(conn, path, &(filep->stat));
  2637. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2638. /* file does not exist and will not be created */
  2639. return 0;
  2640. }
  2641. #if defined(_WIN32)
  2642. {
  2643. wchar_t wbuf[W_PATH_MAX];
  2644. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2645. switch (mode) {
  2646. case MG_FOPEN_MODE_READ:
  2647. filep->access.fp = _wfopen(wbuf, L"rb");
  2648. break;
  2649. case MG_FOPEN_MODE_WRITE:
  2650. filep->access.fp = _wfopen(wbuf, L"wb");
  2651. break;
  2652. case MG_FOPEN_MODE_APPEND:
  2653. filep->access.fp = _wfopen(wbuf, L"ab");
  2654. break;
  2655. }
  2656. }
  2657. #else
  2658. /* Linux et al already use unicode. No need to convert. */
  2659. switch (mode) {
  2660. case MG_FOPEN_MODE_READ:
  2661. filep->access.fp = fopen(path, "r");
  2662. break;
  2663. case MG_FOPEN_MODE_WRITE:
  2664. filep->access.fp = fopen(path, "w");
  2665. break;
  2666. case MG_FOPEN_MODE_APPEND:
  2667. filep->access.fp = fopen(path, "a");
  2668. break;
  2669. }
  2670. #endif
  2671. if (!found) {
  2672. /* File did not exist before fopen was called.
  2673. * Maybe it has been created now. Get stat info
  2674. * like creation time now. */
  2675. found = mg_stat(conn, path, &(filep->stat));
  2676. (void)found;
  2677. }
  2678. /* file is on disk */
  2679. return (filep->access.fp != NULL);
  2680. } else {
  2681. #if defined(MG_USE_OPEN_FILE)
  2682. /* is_file_in_memory returned true */
  2683. if (open_file_in_memory(conn, path, filep, mode)) {
  2684. /* file is in memory */
  2685. return (filep->access.membuf != NULL);
  2686. }
  2687. #endif
  2688. }
  2689. /* Open failed */
  2690. return 0;
  2691. }
  2692. /* return 0 on success, just like fclose */
  2693. static int
  2694. mg_fclose(struct mg_file_access *fileacc)
  2695. {
  2696. int ret = -1;
  2697. if (fileacc != NULL) {
  2698. if (fileacc->fp != NULL) {
  2699. ret = fclose(fileacc->fp);
  2700. #if defined(MG_USE_OPEN_FILE)
  2701. } else if (fileacc->membuf != NULL) {
  2702. ret = 0;
  2703. #endif
  2704. }
  2705. /* reset all members of fileacc */
  2706. memset(fileacc, 0, sizeof(*fileacc));
  2707. }
  2708. return ret;
  2709. }
  2710. static void
  2711. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2712. {
  2713. for (; *src != '\0' && n > 1; n--) {
  2714. *dst++ = *src++;
  2715. }
  2716. *dst = '\0';
  2717. }
  2718. static int
  2719. lowercase(const char *s)
  2720. {
  2721. return tolower(*(const unsigned char *)s);
  2722. }
  2723. int
  2724. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2725. {
  2726. int diff = 0;
  2727. if (len > 0) {
  2728. do {
  2729. diff = lowercase(s1++) - lowercase(s2++);
  2730. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2731. }
  2732. return diff;
  2733. }
  2734. int
  2735. mg_strcasecmp(const char *s1, const char *s2)
  2736. {
  2737. int diff;
  2738. do {
  2739. diff = lowercase(s1++) - lowercase(s2++);
  2740. } while (diff == 0 && s1[-1] != '\0');
  2741. return diff;
  2742. }
  2743. static char *
  2744. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2745. {
  2746. char *p;
  2747. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2748. * defined */
  2749. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2750. mg_strlcpy(p, ptr, len + 1);
  2751. }
  2752. return p;
  2753. }
  2754. static char *
  2755. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2756. {
  2757. return mg_strndup_ctx(str, strlen(str), ctx);
  2758. }
  2759. static char *
  2760. mg_strdup(const char *str)
  2761. {
  2762. return mg_strndup_ctx(str, strlen(str), NULL);
  2763. }
  2764. static const char *
  2765. mg_strcasestr(const char *big_str, const char *small_str)
  2766. {
  2767. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2768. if (big_len >= small_len) {
  2769. for (i = 0; i <= (big_len - small_len); i++) {
  2770. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2771. return big_str + i;
  2772. }
  2773. }
  2774. }
  2775. return NULL;
  2776. }
  2777. /* Return null terminated string of given maximum length.
  2778. * Report errors if length is exceeded. */
  2779. static void
  2780. mg_vsnprintf(const struct mg_connection *conn,
  2781. int *truncated,
  2782. char *buf,
  2783. size_t buflen,
  2784. const char *fmt,
  2785. va_list ap)
  2786. {
  2787. int n, ok;
  2788. if (buflen == 0) {
  2789. if (truncated) {
  2790. *truncated = 1;
  2791. }
  2792. return;
  2793. }
  2794. #if defined(__clang__)
  2795. #pragma clang diagnostic push
  2796. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2797. /* Using fmt as a non-literal is intended here, since it is mostly called
  2798. * indirectly by mg_snprintf */
  2799. #endif
  2800. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2801. ok = (n >= 0) && ((size_t)n < buflen);
  2802. #if defined(__clang__)
  2803. #pragma clang diagnostic pop
  2804. #endif
  2805. if (ok) {
  2806. if (truncated) {
  2807. *truncated = 0;
  2808. }
  2809. } else {
  2810. if (truncated) {
  2811. *truncated = 1;
  2812. }
  2813. mg_cry_internal(conn,
  2814. "truncating vsnprintf buffer: [%.*s]",
  2815. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2816. buf);
  2817. n = (int)buflen - 1;
  2818. }
  2819. buf[n] = '\0';
  2820. }
  2821. static void
  2822. mg_snprintf(const struct mg_connection *conn,
  2823. int *truncated,
  2824. char *buf,
  2825. size_t buflen,
  2826. const char *fmt,
  2827. ...)
  2828. {
  2829. va_list ap;
  2830. va_start(ap, fmt);
  2831. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2832. va_end(ap);
  2833. }
  2834. static int
  2835. get_option_index(const char *name)
  2836. {
  2837. int i;
  2838. for (i = 0; config_options[i].name != NULL; i++) {
  2839. if (strcmp(config_options[i].name, name) == 0) {
  2840. return i;
  2841. }
  2842. }
  2843. return -1;
  2844. }
  2845. const char *
  2846. mg_get_option(const struct mg_context *ctx, const char *name)
  2847. {
  2848. int i;
  2849. if ((i = get_option_index(name)) == -1) {
  2850. return NULL;
  2851. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2852. return "";
  2853. } else {
  2854. return ctx->dd.config[i];
  2855. }
  2856. }
  2857. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2858. struct mg_context *
  2859. mg_get_context(const struct mg_connection *conn)
  2860. {
  2861. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2862. }
  2863. void *
  2864. mg_get_user_data(const struct mg_context *ctx)
  2865. {
  2866. return (ctx == NULL) ? NULL : ctx->user_data;
  2867. }
  2868. void
  2869. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2870. {
  2871. if (conn != NULL) {
  2872. conn->request_info.conn_data = data;
  2873. }
  2874. }
  2875. void *
  2876. mg_get_user_connection_data(const struct mg_connection *conn)
  2877. {
  2878. if (conn != NULL) {
  2879. return conn->request_info.conn_data;
  2880. }
  2881. return NULL;
  2882. }
  2883. #if defined(MG_LEGACY_INTERFACE)
  2884. /* Deprecated: Use mg_get_server_ports instead. */
  2885. size_t
  2886. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2887. {
  2888. size_t i;
  2889. if (!ctx) {
  2890. return 0;
  2891. }
  2892. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2893. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2894. ports[i] =
  2895. #if defined(USE_IPV6)
  2896. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2897. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2898. :
  2899. #endif
  2900. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2901. }
  2902. return i;
  2903. }
  2904. #endif
  2905. int
  2906. mg_get_server_ports(const struct mg_context *ctx,
  2907. int size,
  2908. struct mg_server_ports *ports)
  2909. {
  2910. int i, cnt = 0;
  2911. if (size <= 0) {
  2912. return -1;
  2913. }
  2914. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2915. if (!ctx) {
  2916. return -1;
  2917. }
  2918. if (!ctx->listening_sockets) {
  2919. return -1;
  2920. }
  2921. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2922. ports[cnt].port =
  2923. #if defined(USE_IPV6)
  2924. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2925. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2926. :
  2927. #endif
  2928. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2929. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2930. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2931. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2932. /* IPv4 */
  2933. ports[cnt].protocol = 1;
  2934. cnt++;
  2935. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2936. /* IPv6 */
  2937. ports[cnt].protocol = 3;
  2938. cnt++;
  2939. }
  2940. }
  2941. return cnt;
  2942. }
  2943. static void
  2944. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2945. {
  2946. buf[0] = '\0';
  2947. if (!usa) {
  2948. return;
  2949. }
  2950. if (usa->sa.sa_family == AF_INET) {
  2951. getnameinfo(&usa->sa,
  2952. sizeof(usa->sin),
  2953. buf,
  2954. (unsigned)len,
  2955. NULL,
  2956. 0,
  2957. NI_NUMERICHOST);
  2958. }
  2959. #if defined(USE_IPV6)
  2960. else if (usa->sa.sa_family == AF_INET6) {
  2961. getnameinfo(&usa->sa,
  2962. sizeof(usa->sin6),
  2963. buf,
  2964. (unsigned)len,
  2965. NULL,
  2966. 0,
  2967. NI_NUMERICHOST);
  2968. }
  2969. #endif
  2970. }
  2971. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2972. * included in all responses other than 100, 101, 5xx. */
  2973. static void
  2974. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2975. {
  2976. #if !defined(REENTRANT_TIME)
  2977. struct tm *tm;
  2978. tm = ((t != NULL) ? gmtime(t) : NULL);
  2979. if (tm != NULL) {
  2980. #else
  2981. struct tm _tm;
  2982. struct tm *tm = &_tm;
  2983. if (t != NULL) {
  2984. gmtime_r(t, tm);
  2985. #endif
  2986. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2987. } else {
  2988. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2989. buf[buf_len - 1] = '\0';
  2990. }
  2991. }
  2992. /* difftime for struct timespec. Return value is in seconds. */
  2993. static double
  2994. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2995. {
  2996. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2997. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2998. }
  2999. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3000. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3001. const char *func,
  3002. unsigned line,
  3003. const char *fmt,
  3004. va_list ap);
  3005. #include "external_mg_cry_internal_impl.inl"
  3006. #else
  3007. /* Print error message to the opened error log stream. */
  3008. static void
  3009. mg_cry_internal_impl(const struct mg_connection *conn,
  3010. const char *func,
  3011. unsigned line,
  3012. const char *fmt,
  3013. va_list ap)
  3014. {
  3015. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3016. struct mg_file fi;
  3017. time_t timestamp;
  3018. /* Unused, in the RELEASE build */
  3019. (void)func;
  3020. (void)line;
  3021. #if defined(__GNUC__) || defined(__MINGW32__)
  3022. #pragma GCC diagnostic push
  3023. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3024. #endif
  3025. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3026. #if defined(__GNUC__) || defined(__MINGW32__)
  3027. #pragma GCC diagnostic pop
  3028. #endif
  3029. buf[sizeof(buf) - 1] = 0;
  3030. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3031. if (!conn) {
  3032. puts(buf);
  3033. return;
  3034. }
  3035. /* Do not lock when getting the callback value, here and below.
  3036. * I suppose this is fine, since function cannot disappear in the
  3037. * same way string option can. */
  3038. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3039. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3040. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3041. if (mg_fopen(conn,
  3042. conn->dom_ctx->config[ERROR_LOG_FILE],
  3043. MG_FOPEN_MODE_APPEND,
  3044. &fi) == 0) {
  3045. fi.access.fp = NULL;
  3046. }
  3047. } else {
  3048. fi.access.fp = NULL;
  3049. }
  3050. if (fi.access.fp != NULL) {
  3051. flockfile(fi.access.fp);
  3052. timestamp = time(NULL);
  3053. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3054. fprintf(fi.access.fp,
  3055. "[%010lu] [error] [client %s] ",
  3056. (unsigned long)timestamp,
  3057. src_addr);
  3058. if (conn->request_info.request_method != NULL) {
  3059. fprintf(fi.access.fp,
  3060. "%s %s: ",
  3061. conn->request_info.request_method,
  3062. conn->request_info.request_uri
  3063. ? conn->request_info.request_uri
  3064. : "");
  3065. }
  3066. fprintf(fi.access.fp, "%s", buf);
  3067. fputc('\n', fi.access.fp);
  3068. fflush(fi.access.fp);
  3069. funlockfile(fi.access.fp);
  3070. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3071. * mg_cry here anyway ;-) */
  3072. }
  3073. }
  3074. }
  3075. #endif /* Externally provided function */
  3076. static void
  3077. mg_cry_internal_wrap(const struct mg_connection *conn,
  3078. const char *func,
  3079. unsigned line,
  3080. const char *fmt,
  3081. ...)
  3082. {
  3083. va_list ap;
  3084. va_start(ap, fmt);
  3085. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3086. va_end(ap);
  3087. }
  3088. void
  3089. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3090. {
  3091. va_list ap;
  3092. va_start(ap, fmt);
  3093. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3094. va_end(ap);
  3095. }
  3096. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3097. /* Return fake connection structure. Used for logging, if connection
  3098. * is not applicable at the moment of logging. */
  3099. static struct mg_connection *
  3100. fc(struct mg_context *ctx)
  3101. {
  3102. static struct mg_connection fake_connection;
  3103. fake_connection.phys_ctx = ctx;
  3104. fake_connection.dom_ctx = &(ctx->dd);
  3105. return &fake_connection;
  3106. }
  3107. const char *
  3108. mg_version(void)
  3109. {
  3110. return CIVETWEB_VERSION;
  3111. }
  3112. const struct mg_request_info *
  3113. mg_get_request_info(const struct mg_connection *conn)
  3114. {
  3115. if (!conn) {
  3116. return NULL;
  3117. }
  3118. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3119. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3120. char txt[16];
  3121. struct mg_workerTLS *tls =
  3122. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3123. sprintf(txt, "%03i", conn->response_info.status_code);
  3124. if (strlen(txt) == 3) {
  3125. memcpy(tls->txtbuf, txt, 4);
  3126. } else {
  3127. strcpy(tls->txtbuf, "ERR");
  3128. }
  3129. ((struct mg_connection *)conn)->request_info.local_uri =
  3130. ((struct mg_connection *)conn)->request_info.request_uri =
  3131. tls->txtbuf; /* use thread safe buffer */
  3132. ((struct mg_connection *)conn)->request_info.num_headers =
  3133. conn->response_info.num_headers;
  3134. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3135. conn->response_info.http_headers,
  3136. sizeof(conn->response_info.http_headers));
  3137. } else
  3138. #endif
  3139. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3140. return NULL;
  3141. }
  3142. return &conn->request_info;
  3143. }
  3144. const struct mg_response_info *
  3145. mg_get_response_info(const struct mg_connection *conn)
  3146. {
  3147. if (!conn) {
  3148. return NULL;
  3149. }
  3150. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3151. return NULL;
  3152. }
  3153. return &conn->response_info;
  3154. }
  3155. static const char *
  3156. get_proto_name(const struct mg_connection *conn)
  3157. {
  3158. #if defined(__clang__)
  3159. #pragma clang diagnostic push
  3160. #pragma clang diagnostic ignored "-Wunreachable-code"
  3161. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3162. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3163. * unreachable, but splitting into four different #ifdef clauses here is more
  3164. * complicated.
  3165. */
  3166. #endif
  3167. const struct mg_request_info *ri = &conn->request_info;
  3168. const char *proto =
  3169. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3170. : (ri->is_ssl ? "https" : "http"));
  3171. return proto;
  3172. #if defined(__clang__)
  3173. #pragma clang diagnostic pop
  3174. #endif
  3175. }
  3176. int
  3177. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3178. {
  3179. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3180. return -1;
  3181. } else {
  3182. int truncated = 0;
  3183. const struct mg_request_info *ri = &conn->request_info;
  3184. const char *proto = get_proto_name(conn);
  3185. if (ri->local_uri == NULL) {
  3186. return -1;
  3187. }
  3188. if ((ri->request_uri != NULL)
  3189. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3190. /* The request uri is different from the local uri.
  3191. * This is usually if an absolute URI, including server
  3192. * name has been provided. */
  3193. mg_snprintf(conn,
  3194. &truncated,
  3195. buf,
  3196. buflen,
  3197. "%s://%s",
  3198. proto,
  3199. ri->request_uri);
  3200. if (truncated) {
  3201. return -1;
  3202. }
  3203. return 0;
  3204. } else {
  3205. /* The common case is a relative URI, so we have to
  3206. * construct an absolute URI from server name and port */
  3207. #if defined(USE_IPV6)
  3208. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3209. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3210. : htons(conn->client.lsa.sin.sin_port);
  3211. #else
  3212. int port = htons(conn->client.lsa.sin.sin_port);
  3213. #endif
  3214. int def_port = ri->is_ssl ? 443 : 80;
  3215. int auth_domain_check_enabled =
  3216. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3217. && (!mg_strcasecmp(
  3218. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3219. "yes"));
  3220. const char *server_domain =
  3221. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3222. char portstr[16];
  3223. char server_ip[48];
  3224. if (port != def_port) {
  3225. sprintf(portstr, ":%u", (unsigned)port);
  3226. } else {
  3227. portstr[0] = 0;
  3228. }
  3229. if (!auth_domain_check_enabled || !server_domain) {
  3230. sockaddr_to_string(server_ip,
  3231. sizeof(server_ip),
  3232. &conn->client.lsa);
  3233. server_domain = server_ip;
  3234. }
  3235. mg_snprintf(conn,
  3236. &truncated,
  3237. buf,
  3238. buflen,
  3239. "%s://%s%s%s",
  3240. proto,
  3241. server_domain,
  3242. portstr,
  3243. ri->local_uri);
  3244. if (truncated) {
  3245. return -1;
  3246. }
  3247. return 0;
  3248. }
  3249. }
  3250. }
  3251. /* Skip the characters until one of the delimiters characters found.
  3252. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3253. * Advance pointer to buffer to the next word. Return found 0-terminated
  3254. * word.
  3255. * Delimiters can be quoted with quotechar. */
  3256. static char *
  3257. skip_quoted(char **buf,
  3258. const char *delimiters,
  3259. const char *whitespace,
  3260. char quotechar)
  3261. {
  3262. char *p, *begin_word, *end_word, *end_whitespace;
  3263. begin_word = *buf;
  3264. end_word = begin_word + strcspn(begin_word, delimiters);
  3265. /* Check for quotechar */
  3266. if (end_word > begin_word) {
  3267. p = end_word - 1;
  3268. while (*p == quotechar) {
  3269. /* While the delimiter is quoted, look for the next delimiter.
  3270. */
  3271. /* This happens, e.g., in calls from parse_auth_header,
  3272. * if the user name contains a " character. */
  3273. /* If there is anything beyond end_word, copy it. */
  3274. if (*end_word != '\0') {
  3275. size_t end_off = strcspn(end_word + 1, delimiters);
  3276. memmove(p, end_word, end_off + 1);
  3277. p += end_off; /* p must correspond to end_word - 1 */
  3278. end_word += end_off + 1;
  3279. } else {
  3280. *p = '\0';
  3281. break;
  3282. }
  3283. }
  3284. for (p++; p < end_word; p++) {
  3285. *p = '\0';
  3286. }
  3287. }
  3288. if (*end_word == '\0') {
  3289. *buf = end_word;
  3290. } else {
  3291. #if defined(__GNUC__) || defined(__MINGW32__)
  3292. /* Disable spurious conversion warning for GCC */
  3293. #if GCC_VERSION >= 40500
  3294. #pragma GCC diagnostic push
  3295. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3296. #endif /* GCC_VERSION >= 40500 */
  3297. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3298. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3299. #if defined(__GNUC__) || defined(__MINGW32__)
  3300. #if GCC_VERSION >= 40500
  3301. #pragma GCC diagnostic pop
  3302. #endif /* GCC_VERSION >= 40500 */
  3303. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3304. for (p = end_word; p < end_whitespace; p++) {
  3305. *p = '\0';
  3306. }
  3307. *buf = end_whitespace;
  3308. }
  3309. return begin_word;
  3310. }
  3311. /* Return HTTP header value, or NULL if not found. */
  3312. static const char *
  3313. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3314. {
  3315. int i;
  3316. for (i = 0; i < num_hdr; i++) {
  3317. if (!mg_strcasecmp(name, hdr[i].name)) {
  3318. return hdr[i].value;
  3319. }
  3320. }
  3321. return NULL;
  3322. }
  3323. #if defined(USE_WEBSOCKET)
  3324. /* Retrieve requested HTTP header multiple values, and return the number of
  3325. * found occurrences */
  3326. static int
  3327. get_req_headers(const struct mg_request_info *ri,
  3328. const char *name,
  3329. const char **output,
  3330. int output_max_size)
  3331. {
  3332. int i;
  3333. int cnt = 0;
  3334. if (ri) {
  3335. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3336. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3337. output[cnt++] = ri->http_headers[i].value;
  3338. }
  3339. }
  3340. }
  3341. return cnt;
  3342. }
  3343. #endif
  3344. const char *
  3345. mg_get_header(const struct mg_connection *conn, const char *name)
  3346. {
  3347. if (!conn) {
  3348. return NULL;
  3349. }
  3350. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3351. return get_header(conn->request_info.http_headers,
  3352. conn->request_info.num_headers,
  3353. name);
  3354. }
  3355. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3356. return get_header(conn->response_info.http_headers,
  3357. conn->response_info.num_headers,
  3358. name);
  3359. }
  3360. return NULL;
  3361. }
  3362. static const char *
  3363. get_http_version(const struct mg_connection *conn)
  3364. {
  3365. if (!conn) {
  3366. return NULL;
  3367. }
  3368. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3369. return conn->request_info.http_version;
  3370. }
  3371. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3372. return conn->response_info.http_version;
  3373. }
  3374. return NULL;
  3375. }
  3376. /* A helper function for traversing a comma separated list of values.
  3377. * It returns a list pointer shifted to the next value, or NULL if the end
  3378. * of the list found.
  3379. * Value is stored in val vector. If value has form "x=y", then eq_val
  3380. * vector is initialized to point to the "y" part, and val vector length
  3381. * is adjusted to point only to "x". */
  3382. static const char *
  3383. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3384. {
  3385. int end;
  3386. reparse:
  3387. if (val == NULL || list == NULL || *list == '\0') {
  3388. /* End of the list */
  3389. return NULL;
  3390. }
  3391. /* Skip over leading LWS */
  3392. while (*list == ' ' || *list == '\t')
  3393. list++;
  3394. val->ptr = list;
  3395. if ((list = strchr(val->ptr, ',')) != NULL) {
  3396. /* Comma found. Store length and shift the list ptr */
  3397. val->len = ((size_t)(list - val->ptr));
  3398. list++;
  3399. } else {
  3400. /* This value is the last one */
  3401. list = val->ptr + strlen(val->ptr);
  3402. val->len = ((size_t)(list - val->ptr));
  3403. }
  3404. /* Adjust length for trailing LWS */
  3405. end = (int)val->len - 1;
  3406. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3407. end--;
  3408. val->len = (size_t)(end + 1);
  3409. if (val->len == 0) {
  3410. /* Ignore any empty entries. */
  3411. goto reparse;
  3412. }
  3413. if (eq_val != NULL) {
  3414. /* Value has form "x=y", adjust pointers and lengths
  3415. * so that val points to "x", and eq_val points to "y". */
  3416. eq_val->len = 0;
  3417. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3418. if (eq_val->ptr != NULL) {
  3419. eq_val->ptr++; /* Skip over '=' character */
  3420. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3421. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3422. }
  3423. }
  3424. return list;
  3425. }
  3426. /* A helper function for checking if a comma separated list of values
  3427. * contains
  3428. * the given option (case insensitvely).
  3429. * 'header' can be NULL, in which case false is returned. */
  3430. static int
  3431. header_has_option(const char *header, const char *option)
  3432. {
  3433. struct vec opt_vec;
  3434. struct vec eq_vec;
  3435. DEBUG_ASSERT(option != NULL);
  3436. DEBUG_ASSERT(option[0] != '\0');
  3437. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3438. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3439. return 1;
  3440. }
  3441. return 0;
  3442. }
  3443. /* Perform case-insensitive match of string against pattern */
  3444. static ptrdiff_t
  3445. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3446. {
  3447. const char *or_str;
  3448. ptrdiff_t i, j, len, res;
  3449. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3450. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3451. return (res > 0) ? res : match_prefix(or_str + 1,
  3452. (size_t)((pattern + pattern_len)
  3453. - (or_str + 1)),
  3454. str);
  3455. }
  3456. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3457. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3458. continue;
  3459. } else if (pattern[i] == '$') {
  3460. return (str[j] == '\0') ? j : -1;
  3461. } else if (pattern[i] == '*') {
  3462. i++;
  3463. if (pattern[i] == '*') {
  3464. i++;
  3465. len = strlen(str + j);
  3466. } else {
  3467. len = strcspn(str + j, "/");
  3468. }
  3469. if (i == (ptrdiff_t)pattern_len) {
  3470. return j + len;
  3471. }
  3472. do {
  3473. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3474. } while (res == -1 && len-- > 0);
  3475. return (res == -1) ? -1 : j + res + len;
  3476. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3477. return -1;
  3478. }
  3479. }
  3480. return (ptrdiff_t)j;
  3481. }
  3482. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3483. * This function must tolerate situations when connection info is not
  3484. * set up, for example if request parsing failed. */
  3485. static int
  3486. should_keep_alive(const struct mg_connection *conn)
  3487. {
  3488. const char *http_version;
  3489. const char *header;
  3490. /* First satisfy needs of the server */
  3491. if ((conn == NULL) || conn->must_close) {
  3492. /* Close, if civetweb framework needs to close */
  3493. return 0;
  3494. }
  3495. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3496. /* Close, if keep alive is not enabled */
  3497. return 0;
  3498. }
  3499. /* Check explicit wish of the client */
  3500. header = mg_get_header(conn, "Connection");
  3501. if (header) {
  3502. /* If there is a connection header from the client, obey */
  3503. if (header_has_option(header, "keep-alive")) {
  3504. return 1;
  3505. }
  3506. return 0;
  3507. }
  3508. /* Use default of the standard */
  3509. http_version = get_http_version(conn);
  3510. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3511. /* HTTP 1.1 default is keep alive */
  3512. return 1;
  3513. }
  3514. /* HTTP 1.0 (and earlier) default is to close the connection */
  3515. return 0;
  3516. }
  3517. static int
  3518. should_decode_url(const struct mg_connection *conn)
  3519. {
  3520. if (!conn || !conn->dom_ctx) {
  3521. return 0;
  3522. }
  3523. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3524. }
  3525. static const char *
  3526. suggest_connection_header(const struct mg_connection *conn)
  3527. {
  3528. return should_keep_alive(conn) ? "keep-alive" : "close";
  3529. }
  3530. static int
  3531. send_no_cache_header(struct mg_connection *conn)
  3532. {
  3533. /* Send all current and obsolete cache opt-out directives. */
  3534. return mg_printf(conn,
  3535. "Cache-Control: no-cache, no-store, "
  3536. "must-revalidate, private, max-age=0\r\n"
  3537. "Pragma: no-cache\r\n"
  3538. "Expires: 0\r\n");
  3539. }
  3540. static int
  3541. send_static_cache_header(struct mg_connection *conn)
  3542. {
  3543. #if !defined(NO_CACHING)
  3544. /* Read the server config to check how long a file may be cached.
  3545. * The configuration is in seconds. */
  3546. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3547. if (max_age <= 0) {
  3548. /* 0 means "do not cache". All values <0 are reserved
  3549. * and may be used differently in the future. */
  3550. /* If a file should not be cached, do not only send
  3551. * max-age=0, but also pragmas and Expires headers. */
  3552. return send_no_cache_header(conn);
  3553. }
  3554. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3555. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3556. /* See also https://www.mnot.net/cache_docs/ */
  3557. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3558. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3559. * leap
  3560. * year to 31622400 seconds. For the moment, we just send whatever has
  3561. * been configured, still the behavior for >1 year should be considered
  3562. * as undefined. */
  3563. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3564. #else /* NO_CACHING */
  3565. return send_no_cache_header(conn);
  3566. #endif /* !NO_CACHING */
  3567. }
  3568. static int
  3569. send_additional_header(struct mg_connection *conn)
  3570. {
  3571. int i = 0;
  3572. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3573. #if !defined(NO_SSL)
  3574. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3575. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3576. if (max_age >= 0) {
  3577. i += mg_printf(conn,
  3578. "Strict-Transport-Security: max-age=%u\r\n",
  3579. (unsigned)max_age);
  3580. }
  3581. }
  3582. #endif
  3583. if (header && header[0]) {
  3584. i += mg_printf(conn, "%s\r\n", header);
  3585. }
  3586. return i;
  3587. }
  3588. static void handle_file_based_request(struct mg_connection *conn,
  3589. const char *path,
  3590. struct mg_file *filep);
  3591. const char *
  3592. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3593. {
  3594. /* See IANA HTTP status code assignment:
  3595. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3596. */
  3597. switch (response_code) {
  3598. /* RFC2616 Section 10.1 - Informational 1xx */
  3599. case 100:
  3600. return "Continue"; /* RFC2616 Section 10.1.1 */
  3601. case 101:
  3602. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3603. case 102:
  3604. return "Processing"; /* RFC2518 Section 10.1 */
  3605. /* RFC2616 Section 10.2 - Successful 2xx */
  3606. case 200:
  3607. return "OK"; /* RFC2616 Section 10.2.1 */
  3608. case 201:
  3609. return "Created"; /* RFC2616 Section 10.2.2 */
  3610. case 202:
  3611. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3612. case 203:
  3613. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3614. case 204:
  3615. return "No Content"; /* RFC2616 Section 10.2.5 */
  3616. case 205:
  3617. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3618. case 206:
  3619. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3620. case 207:
  3621. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3622. */
  3623. case 208:
  3624. return "Already Reported"; /* RFC5842 Section 7.1 */
  3625. case 226:
  3626. return "IM used"; /* RFC3229 Section 10.4.1 */
  3627. /* RFC2616 Section 10.3 - Redirection 3xx */
  3628. case 300:
  3629. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3630. case 301:
  3631. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3632. case 302:
  3633. return "Found"; /* RFC2616 Section 10.3.3 */
  3634. case 303:
  3635. return "See Other"; /* RFC2616 Section 10.3.4 */
  3636. case 304:
  3637. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3638. case 305:
  3639. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3640. case 307:
  3641. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3642. case 308:
  3643. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3644. /* RFC2616 Section 10.4 - Client Error 4xx */
  3645. case 400:
  3646. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3647. case 401:
  3648. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3649. case 402:
  3650. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3651. case 403:
  3652. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3653. case 404:
  3654. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3655. case 405:
  3656. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3657. case 406:
  3658. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3659. case 407:
  3660. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3661. case 408:
  3662. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3663. case 409:
  3664. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3665. case 410:
  3666. return "Gone"; /* RFC2616 Section 10.4.11 */
  3667. case 411:
  3668. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3669. case 412:
  3670. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3671. case 413:
  3672. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3673. case 414:
  3674. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3675. case 415:
  3676. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3677. case 416:
  3678. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3679. */
  3680. case 417:
  3681. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3682. case 421:
  3683. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3684. case 422:
  3685. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3686. * Section 11.2 */
  3687. case 423:
  3688. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3689. case 424:
  3690. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3691. * Section 11.4 */
  3692. case 426:
  3693. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3694. case 428:
  3695. return "Precondition Required"; /* RFC 6585, Section 3 */
  3696. case 429:
  3697. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3698. case 431:
  3699. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3700. case 451:
  3701. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3702. * Section 3 */
  3703. /* RFC2616 Section 10.5 - Server Error 5xx */
  3704. case 500:
  3705. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3706. case 501:
  3707. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3708. case 502:
  3709. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3710. case 503:
  3711. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3712. case 504:
  3713. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3714. case 505:
  3715. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3716. case 506:
  3717. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3718. case 507:
  3719. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3720. * Section 11.5 */
  3721. case 508:
  3722. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3723. case 510:
  3724. return "Not Extended"; /* RFC 2774, Section 7 */
  3725. case 511:
  3726. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3727. /* Other status codes, not shown in the IANA HTTP status code
  3728. * assignment.
  3729. * E.g., "de facto" standards due to common use, ... */
  3730. case 418:
  3731. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3732. case 419:
  3733. return "Authentication Timeout"; /* common use */
  3734. case 420:
  3735. return "Enhance Your Calm"; /* common use */
  3736. case 440:
  3737. return "Login Timeout"; /* common use */
  3738. case 509:
  3739. return "Bandwidth Limit Exceeded"; /* common use */
  3740. default:
  3741. /* This error code is unknown. This should not happen. */
  3742. if (conn) {
  3743. mg_cry_internal(conn,
  3744. "Unknown HTTP response code: %u",
  3745. response_code);
  3746. }
  3747. /* Return at least a category according to RFC 2616 Section 10. */
  3748. if (response_code >= 100 && response_code < 200) {
  3749. /* Unknown informational status code */
  3750. return "Information";
  3751. }
  3752. if (response_code >= 200 && response_code < 300) {
  3753. /* Unknown success code */
  3754. return "Success";
  3755. }
  3756. if (response_code >= 300 && response_code < 400) {
  3757. /* Unknown redirection code */
  3758. return "Redirection";
  3759. }
  3760. if (response_code >= 400 && response_code < 500) {
  3761. /* Unknown request error code */
  3762. return "Client Error";
  3763. }
  3764. if (response_code >= 500 && response_code < 600) {
  3765. /* Unknown server error code */
  3766. return "Server Error";
  3767. }
  3768. /* Response code not even within reasonable range */
  3769. return "";
  3770. }
  3771. }
  3772. static int
  3773. mg_send_http_error_impl(struct mg_connection *conn,
  3774. int status,
  3775. const char *fmt,
  3776. va_list args)
  3777. {
  3778. char errmsg_buf[MG_BUF_LEN];
  3779. char path_buf[PATH_MAX];
  3780. va_list ap;
  3781. int len, i, page_handler_found, scope, truncated, has_body;
  3782. char date[64];
  3783. time_t curtime = time(NULL);
  3784. const char *error_handler = NULL;
  3785. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3786. const char *error_page_file_ext, *tstr;
  3787. int handled_by_callback = 0;
  3788. const char *status_text = mg_get_response_code_text(conn, status);
  3789. if ((conn == NULL) || (fmt == NULL)) {
  3790. return -2;
  3791. }
  3792. /* Set status (for log) */
  3793. conn->status_code = status;
  3794. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3795. has_body = ((status > 199) && (status != 204) && (status != 304));
  3796. /* Prepare message in buf, if required */
  3797. if (has_body || (!conn->in_error_handler
  3798. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3799. /* Store error message in errmsg_buf */
  3800. va_copy(ap, args);
  3801. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3802. va_end(ap);
  3803. /* In a debug build, print all html errors */
  3804. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3805. }
  3806. /* If there is a http_error callback, call it.
  3807. * But don't do it recursively, if callback calls mg_send_http_error again.
  3808. */
  3809. if (!conn->in_error_handler
  3810. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3811. /* Mark in_error_handler to avoid recursion and call user callback. */
  3812. conn->in_error_handler = 1;
  3813. handled_by_callback =
  3814. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3815. == 0);
  3816. conn->in_error_handler = 0;
  3817. }
  3818. if (!handled_by_callback) {
  3819. /* Check for recursion */
  3820. if (conn->in_error_handler) {
  3821. DEBUG_TRACE(
  3822. "Recursion when handling error %u - fall back to default",
  3823. status);
  3824. } else {
  3825. /* Send user defined error pages, if defined */
  3826. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3827. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3828. page_handler_found = 0;
  3829. if (error_handler != NULL) {
  3830. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3831. switch (scope) {
  3832. case 1: /* Handler for specific error, e.g. 404 error */
  3833. mg_snprintf(conn,
  3834. &truncated,
  3835. path_buf,
  3836. sizeof(path_buf) - 32,
  3837. "%serror%03u.",
  3838. error_handler,
  3839. status);
  3840. break;
  3841. case 2: /* Handler for error group, e.g., 5xx error
  3842. * handler
  3843. * for all server errors (500-599) */
  3844. mg_snprintf(conn,
  3845. &truncated,
  3846. path_buf,
  3847. sizeof(path_buf) - 32,
  3848. "%serror%01uxx.",
  3849. error_handler,
  3850. status / 100);
  3851. break;
  3852. default: /* Handler for all errors */
  3853. mg_snprintf(conn,
  3854. &truncated,
  3855. path_buf,
  3856. sizeof(path_buf) - 32,
  3857. "%serror.",
  3858. error_handler);
  3859. break;
  3860. }
  3861. /* String truncation in buf may only occur if
  3862. * error_handler is too long. This string is
  3863. * from the config, not from a client. */
  3864. (void)truncated;
  3865. len = (int)strlen(path_buf);
  3866. tstr = strchr(error_page_file_ext, '.');
  3867. while (tstr) {
  3868. for (i = 1;
  3869. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3870. i++) {
  3871. /* buffer overrun is not possible here, since
  3872. * (i < 32) && (len < sizeof(path_buf) - 32)
  3873. * ==> (i + len) < sizeof(path_buf) */
  3874. path_buf[len + i - 1] = tstr[i];
  3875. }
  3876. /* buffer overrun is not possible here, since
  3877. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3878. * ==> (i + len) <= sizeof(path_buf) */
  3879. path_buf[len + i - 1] = 0;
  3880. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3881. DEBUG_TRACE("Check error page %s - found",
  3882. path_buf);
  3883. page_handler_found = 1;
  3884. break;
  3885. }
  3886. DEBUG_TRACE("Check error page %s - not found",
  3887. path_buf);
  3888. tstr = strchr(tstr + i, '.');
  3889. }
  3890. }
  3891. }
  3892. if (page_handler_found) {
  3893. conn->in_error_handler = 1;
  3894. handle_file_based_request(conn, path_buf, &error_page_file);
  3895. conn->in_error_handler = 0;
  3896. return 0;
  3897. }
  3898. }
  3899. /* No custom error page. Send default error page. */
  3900. gmt_time_string(date, sizeof(date), &curtime);
  3901. conn->must_close = 1;
  3902. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3903. send_no_cache_header(conn);
  3904. send_additional_header(conn);
  3905. if (has_body) {
  3906. mg_printf(conn,
  3907. "%s",
  3908. "Content-Type: text/plain; charset=utf-8\r\n");
  3909. }
  3910. mg_printf(conn,
  3911. "Date: %s\r\n"
  3912. "Connection: close\r\n\r\n",
  3913. date);
  3914. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3915. if (has_body) {
  3916. /* For other errors, send a generic error message. */
  3917. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3918. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3919. } else {
  3920. /* No body allowed. Close the connection. */
  3921. DEBUG_TRACE("Error %i", status);
  3922. }
  3923. }
  3924. return 0;
  3925. }
  3926. int
  3927. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3928. {
  3929. va_list ap;
  3930. int ret;
  3931. va_start(ap, fmt);
  3932. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3933. va_end(ap);
  3934. return ret;
  3935. }
  3936. int
  3937. mg_send_http_ok(struct mg_connection *conn,
  3938. const char *mime_type,
  3939. long long content_length)
  3940. {
  3941. char date[64];
  3942. time_t curtime = time(NULL);
  3943. if ((mime_type == NULL) || (*mime_type == 0)) {
  3944. /* Parameter error */
  3945. return -2;
  3946. }
  3947. gmt_time_string(date, sizeof(date), &curtime);
  3948. mg_printf(conn,
  3949. "HTTP/1.1 200 OK\r\n"
  3950. "Content-Type: %s\r\n"
  3951. "Date: %s\r\n"
  3952. "Connection: %s\r\n",
  3953. mime_type,
  3954. date,
  3955. suggest_connection_header(conn));
  3956. send_no_cache_header(conn);
  3957. send_additional_header(conn);
  3958. if (content_length < 0) {
  3959. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  3960. } else {
  3961. mg_printf(conn,
  3962. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  3963. (uint64_t)content_length);
  3964. }
  3965. return 0;
  3966. }
  3967. int
  3968. mg_send_http_redirect(struct mg_connection *conn,
  3969. const char *target_url,
  3970. int redirect_code)
  3971. {
  3972. /* Send a 30x redirect response.
  3973. *
  3974. * Redirect types (status codes):
  3975. *
  3976. * Status | Perm/Temp | Method | Version
  3977. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3978. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3979. * 303 | temporary | always use GET | HTTP/1.1
  3980. * 307 | temporary | always keep method | HTTP/1.1
  3981. * 308 | permanent | always keep method | HTTP/1.1
  3982. */
  3983. const char *redirect_text;
  3984. int ret;
  3985. size_t content_len = 0;
  3986. char reply[MG_BUF_LEN];
  3987. /* In case redirect_code=0, use 307. */
  3988. if (redirect_code == 0) {
  3989. redirect_code = 307;
  3990. }
  3991. /* In case redirect_code is none of the above, return error. */
  3992. if ((redirect_code != 301) && (redirect_code != 302)
  3993. && (redirect_code != 303) && (redirect_code != 307)
  3994. && (redirect_code != 308)) {
  3995. /* Parameter error */
  3996. return -2;
  3997. }
  3998. /* Get proper text for response code */
  3999. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4000. /* If target_url is not defined, redirect to "/". */
  4001. if ((target_url == NULL) || (*target_url == 0)) {
  4002. target_url = "/";
  4003. }
  4004. #if defined(MG_SEND_REDIRECT_BODY)
  4005. /* TODO: condition name? */
  4006. /* Prepare a response body with a hyperlink.
  4007. *
  4008. * According to RFC2616 (and RFC1945 before):
  4009. * Unless the request method was HEAD, the entity of the
  4010. * response SHOULD contain a short hypertext note with a hyperlink to
  4011. * the new URI(s).
  4012. *
  4013. * However, this response body is not useful in M2M communication.
  4014. * Probably the original reason in the RFC was, clients not supporting
  4015. * a 30x HTTP redirect could still show the HTML page and let the user
  4016. * press the link. Since current browsers support 30x HTTP, the additional
  4017. * HTML body does not seem to make sense anymore.
  4018. *
  4019. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4020. * but it only notes:
  4021. * The server's response payload usually contains a short
  4022. * hypertext note with a hyperlink to the new URI(s).
  4023. *
  4024. * Deactivated by default. If you need the 30x body, set the define.
  4025. */
  4026. mg_snprintf(
  4027. conn,
  4028. NULL /* ignore truncation */,
  4029. reply,
  4030. sizeof(reply),
  4031. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4032. redirect_text,
  4033. target_url,
  4034. target_url);
  4035. content_len = strlen(reply);
  4036. #else
  4037. reply[0] = 0;
  4038. #endif
  4039. /* Do not send any additional header. For all other options,
  4040. * including caching, there are suitable defaults. */
  4041. ret = mg_printf(conn,
  4042. "HTTP/1.1 %i %s\r\n"
  4043. "Location: %s\r\n"
  4044. "Content-Length: %u\r\n"
  4045. "Connection: %s\r\n\r\n",
  4046. redirect_code,
  4047. redirect_text,
  4048. target_url,
  4049. (unsigned int)content_len,
  4050. suggest_connection_header(conn));
  4051. /* Send response body */
  4052. if (ret > 0) {
  4053. /* ... unless it is a HEAD request */
  4054. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4055. ret = mg_write(conn, reply, content_len);
  4056. }
  4057. }
  4058. return (ret > 0) ? ret : -1;
  4059. }
  4060. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4061. /* Create substitutes for POSIX functions in Win32. */
  4062. #if defined(__MINGW32__)
  4063. /* Show no warning in case system functions are not used. */
  4064. #pragma GCC diagnostic push
  4065. #pragma GCC diagnostic ignored "-Wunused-function"
  4066. #endif
  4067. FUNCTION_MAY_BE_UNUSED
  4068. static int
  4069. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4070. {
  4071. (void)unused;
  4072. *mutex = CreateMutex(NULL, FALSE, NULL);
  4073. return (*mutex == NULL) ? -1 : 0;
  4074. }
  4075. FUNCTION_MAY_BE_UNUSED
  4076. static int
  4077. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4078. {
  4079. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  4080. }
  4081. FUNCTION_MAY_BE_UNUSED
  4082. static int
  4083. pthread_mutex_lock(pthread_mutex_t *mutex)
  4084. {
  4085. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  4086. : -1;
  4087. }
  4088. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  4089. FUNCTION_MAY_BE_UNUSED
  4090. static int
  4091. pthread_mutex_trylock(pthread_mutex_t *mutex)
  4092. {
  4093. switch (WaitForSingleObject(*mutex, 0)) {
  4094. case WAIT_OBJECT_0:
  4095. return 0;
  4096. case WAIT_TIMEOUT:
  4097. return -2; /* EBUSY */
  4098. }
  4099. return -1;
  4100. }
  4101. #endif
  4102. FUNCTION_MAY_BE_UNUSED
  4103. static int
  4104. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4105. {
  4106. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  4107. }
  4108. FUNCTION_MAY_BE_UNUSED
  4109. static int
  4110. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4111. {
  4112. (void)unused;
  4113. InitializeCriticalSection(&cv->threadIdSec);
  4114. cv->waiting_thread = NULL;
  4115. return 0;
  4116. }
  4117. FUNCTION_MAY_BE_UNUSED
  4118. static int
  4119. pthread_cond_timedwait(pthread_cond_t *cv,
  4120. pthread_mutex_t *mutex,
  4121. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4122. {
  4123. struct mg_workerTLS **ptls,
  4124. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4125. int ok;
  4126. int64_t nsnow, nswaitabs, nswaitrel;
  4127. DWORD mswaitrel;
  4128. EnterCriticalSection(&cv->threadIdSec);
  4129. /* Add this thread to cv's waiting list */
  4130. ptls = &cv->waiting_thread;
  4131. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4132. ;
  4133. tls->next_waiting_thread = NULL;
  4134. *ptls = tls;
  4135. LeaveCriticalSection(&cv->threadIdSec);
  4136. if (abstime) {
  4137. nsnow = mg_get_current_time_ns();
  4138. nswaitabs =
  4139. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4140. nswaitrel = nswaitabs - nsnow;
  4141. if (nswaitrel < 0) {
  4142. nswaitrel = 0;
  4143. }
  4144. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4145. } else {
  4146. mswaitrel = (DWORD)INFINITE;
  4147. }
  4148. pthread_mutex_unlock(mutex);
  4149. ok = (WAIT_OBJECT_0
  4150. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4151. if (!ok) {
  4152. ok = 1;
  4153. EnterCriticalSection(&cv->threadIdSec);
  4154. ptls = &cv->waiting_thread;
  4155. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4156. if (*ptls == tls) {
  4157. *ptls = tls->next_waiting_thread;
  4158. ok = 0;
  4159. break;
  4160. }
  4161. }
  4162. LeaveCriticalSection(&cv->threadIdSec);
  4163. if (ok) {
  4164. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4165. (DWORD)INFINITE);
  4166. }
  4167. }
  4168. /* This thread has been removed from cv's waiting list */
  4169. pthread_mutex_lock(mutex);
  4170. return ok ? 0 : -1;
  4171. }
  4172. FUNCTION_MAY_BE_UNUSED
  4173. static int
  4174. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4175. {
  4176. return pthread_cond_timedwait(cv, mutex, NULL);
  4177. }
  4178. FUNCTION_MAY_BE_UNUSED
  4179. static int
  4180. pthread_cond_signal(pthread_cond_t *cv)
  4181. {
  4182. HANDLE wkup = NULL;
  4183. BOOL ok = FALSE;
  4184. EnterCriticalSection(&cv->threadIdSec);
  4185. if (cv->waiting_thread) {
  4186. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4187. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4188. ok = SetEvent(wkup);
  4189. DEBUG_ASSERT(ok);
  4190. }
  4191. LeaveCriticalSection(&cv->threadIdSec);
  4192. return ok ? 0 : 1;
  4193. }
  4194. FUNCTION_MAY_BE_UNUSED
  4195. static int
  4196. pthread_cond_broadcast(pthread_cond_t *cv)
  4197. {
  4198. EnterCriticalSection(&cv->threadIdSec);
  4199. while (cv->waiting_thread) {
  4200. pthread_cond_signal(cv);
  4201. }
  4202. LeaveCriticalSection(&cv->threadIdSec);
  4203. return 0;
  4204. }
  4205. FUNCTION_MAY_BE_UNUSED
  4206. static int
  4207. pthread_cond_destroy(pthread_cond_t *cv)
  4208. {
  4209. EnterCriticalSection(&cv->threadIdSec);
  4210. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4211. LeaveCriticalSection(&cv->threadIdSec);
  4212. DeleteCriticalSection(&cv->threadIdSec);
  4213. return 0;
  4214. }
  4215. #if defined(ALTERNATIVE_QUEUE)
  4216. FUNCTION_MAY_BE_UNUSED
  4217. static void *
  4218. event_create(void)
  4219. {
  4220. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4221. }
  4222. FUNCTION_MAY_BE_UNUSED
  4223. static int
  4224. event_wait(void *eventhdl)
  4225. {
  4226. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4227. return (res == WAIT_OBJECT_0);
  4228. }
  4229. FUNCTION_MAY_BE_UNUSED
  4230. static int
  4231. event_signal(void *eventhdl)
  4232. {
  4233. return (int)SetEvent((HANDLE)eventhdl);
  4234. }
  4235. FUNCTION_MAY_BE_UNUSED
  4236. static void
  4237. event_destroy(void *eventhdl)
  4238. {
  4239. CloseHandle((HANDLE)eventhdl);
  4240. }
  4241. #endif
  4242. #if defined(__MINGW32__)
  4243. /* Enable unused function warning again */
  4244. #pragma GCC diagnostic pop
  4245. #endif
  4246. /* For Windows, change all slashes to backslashes in path names. */
  4247. static void
  4248. change_slashes_to_backslashes(char *path)
  4249. {
  4250. int i;
  4251. for (i = 0; path[i] != '\0'; i++) {
  4252. if (path[i] == '/') {
  4253. path[i] = '\\';
  4254. }
  4255. /* remove double backslash (check i > 0 to preserve UNC paths,
  4256. * like \\server\file.txt) */
  4257. if ((path[i] == '\\') && (i > 0)) {
  4258. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4259. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4260. }
  4261. }
  4262. }
  4263. }
  4264. static int
  4265. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4266. {
  4267. int diff;
  4268. do {
  4269. diff = tolower(*s1) - tolower(*s2);
  4270. s1++;
  4271. s2++;
  4272. } while ((diff == 0) && (s1[-1] != '\0'));
  4273. return diff;
  4274. }
  4275. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4276. * wbuf and wbuf_len is a target buffer and its length. */
  4277. static void
  4278. path_to_unicode(const struct mg_connection *conn,
  4279. const char *path,
  4280. wchar_t *wbuf,
  4281. size_t wbuf_len)
  4282. {
  4283. char buf[PATH_MAX], buf2[PATH_MAX];
  4284. wchar_t wbuf2[W_PATH_MAX + 1];
  4285. DWORD long_len, err;
  4286. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4287. mg_strlcpy(buf, path, sizeof(buf));
  4288. change_slashes_to_backslashes(buf);
  4289. /* Convert to Unicode and back. If doubly-converted string does not
  4290. * match the original, something is fishy, reject. */
  4291. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4292. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4293. WideCharToMultiByte(
  4294. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4295. if (strcmp(buf, buf2) != 0) {
  4296. wbuf[0] = L'\0';
  4297. }
  4298. /* Windows file systems are not case sensitive, but you can still use
  4299. * uppercase and lowercase letters (on all modern file systems).
  4300. * The server can check if the URI uses the same upper/lowercase
  4301. * letters an the file system, effectively making Windows servers
  4302. * case sensitive (like Linux servers are). It is still not possible
  4303. * to use two files with the same name in different cases on Windows
  4304. * (like /a and /A) - this would be possible in Linux.
  4305. * As a default, Windows is not case sensitive, but the case sensitive
  4306. * file name check can be activated by an additional configuration. */
  4307. if (conn) {
  4308. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4309. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4310. "yes")) {
  4311. /* Use case sensitive compare function */
  4312. fcompare = wcscmp;
  4313. }
  4314. }
  4315. (void)conn; /* conn is currently unused */
  4316. #if !defined(_WIN32_WCE)
  4317. /* Only accept a full file path, not a Windows short (8.3) path. */
  4318. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4319. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4320. if (long_len == 0) {
  4321. err = GetLastError();
  4322. if (err == ERROR_FILE_NOT_FOUND) {
  4323. /* File does not exist. This is not always a problem here. */
  4324. return;
  4325. }
  4326. }
  4327. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4328. /* Short name is used. */
  4329. wbuf[0] = L'\0';
  4330. }
  4331. #else
  4332. (void)long_len;
  4333. (void)wbuf2;
  4334. (void)err;
  4335. if (strchr(path, '~')) {
  4336. wbuf[0] = L'\0';
  4337. }
  4338. #endif
  4339. }
  4340. /* Windows happily opens files with some garbage at the end of file name.
  4341. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4342. * "a.cgi", despite one would expect an error back.
  4343. * This function returns non-0 if path ends with some garbage. */
  4344. static int
  4345. path_cannot_disclose_cgi(const char *path)
  4346. {
  4347. static const char *allowed_last_characters = "_-";
  4348. int last = path[strlen(path) - 1];
  4349. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4350. }
  4351. static int
  4352. mg_stat(const struct mg_connection *conn,
  4353. const char *path,
  4354. struct mg_file_stat *filep)
  4355. {
  4356. wchar_t wbuf[W_PATH_MAX];
  4357. WIN32_FILE_ATTRIBUTE_DATA info;
  4358. time_t creation_time;
  4359. if (!filep) {
  4360. return 0;
  4361. }
  4362. memset(filep, 0, sizeof(*filep));
  4363. if (conn && is_file_in_memory(conn, path)) {
  4364. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4365. * memset */
  4366. /* Quick fix (for 1.9.x): */
  4367. /* mg_stat must fill all fields, also for files in memory */
  4368. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4369. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4370. filep->size = tmp_file.stat.size;
  4371. filep->location = 2;
  4372. /* TODO: for 1.10: restructure how files in memory are handled */
  4373. /* The "file in memory" feature is a candidate for deletion.
  4374. * Please join the discussion at
  4375. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4376. */
  4377. filep->last_modified = time(NULL); /* TODO */
  4378. /* last_modified = now ... assumes the file may change during
  4379. * runtime,
  4380. * so every mg_fopen call may return different data */
  4381. /* last_modified = conn->phys_ctx.start_time;
  4382. * May be used it the data does not change during runtime. This
  4383. * allows
  4384. * browser caching. Since we do not know, we have to assume the file
  4385. * in memory may change. */
  4386. return 1;
  4387. }
  4388. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4389. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4390. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4391. filep->last_modified =
  4392. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4393. info.ftLastWriteTime.dwHighDateTime);
  4394. /* On Windows, the file creation time can be higher than the
  4395. * modification time, e.g. when a file is copied.
  4396. * Since the Last-Modified timestamp is used for caching
  4397. * it should be based on the most recent timestamp. */
  4398. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4399. info.ftCreationTime.dwHighDateTime);
  4400. if (creation_time > filep->last_modified) {
  4401. filep->last_modified = creation_time;
  4402. }
  4403. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4404. /* If file name is fishy, reset the file structure and return
  4405. * error.
  4406. * Note it is important to reset, not just return the error, cause
  4407. * functions like is_file_opened() check the struct. */
  4408. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4409. memset(filep, 0, sizeof(*filep));
  4410. return 0;
  4411. }
  4412. return 1;
  4413. }
  4414. return 0;
  4415. }
  4416. static int
  4417. mg_remove(const struct mg_connection *conn, const char *path)
  4418. {
  4419. wchar_t wbuf[W_PATH_MAX];
  4420. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4421. return DeleteFileW(wbuf) ? 0 : -1;
  4422. }
  4423. static int
  4424. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4425. {
  4426. wchar_t wbuf[W_PATH_MAX];
  4427. (void)mode;
  4428. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4429. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4430. }
  4431. /* Create substitutes for POSIX functions in Win32. */
  4432. #if defined(__MINGW32__)
  4433. /* Show no warning in case system functions are not used. */
  4434. #pragma GCC diagnostic push
  4435. #pragma GCC diagnostic ignored "-Wunused-function"
  4436. #endif
  4437. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4438. FUNCTION_MAY_BE_UNUSED
  4439. static DIR *
  4440. mg_opendir(const struct mg_connection *conn, const char *name)
  4441. {
  4442. DIR *dir = NULL;
  4443. wchar_t wpath[W_PATH_MAX];
  4444. DWORD attrs;
  4445. if (name == NULL) {
  4446. SetLastError(ERROR_BAD_ARGUMENTS);
  4447. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4448. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4449. } else {
  4450. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4451. attrs = GetFileAttributesW(wpath);
  4452. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4453. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4454. (void)wcscat(wpath, L"\\*");
  4455. dir->handle = FindFirstFileW(wpath, &dir->info);
  4456. dir->result.d_name[0] = '\0';
  4457. } else {
  4458. mg_free(dir);
  4459. dir = NULL;
  4460. }
  4461. }
  4462. return dir;
  4463. }
  4464. FUNCTION_MAY_BE_UNUSED
  4465. static int
  4466. mg_closedir(DIR *dir)
  4467. {
  4468. int result = 0;
  4469. if (dir != NULL) {
  4470. if (dir->handle != INVALID_HANDLE_VALUE)
  4471. result = FindClose(dir->handle) ? 0 : -1;
  4472. mg_free(dir);
  4473. } else {
  4474. result = -1;
  4475. SetLastError(ERROR_BAD_ARGUMENTS);
  4476. }
  4477. return result;
  4478. }
  4479. FUNCTION_MAY_BE_UNUSED
  4480. static struct dirent *
  4481. mg_readdir(DIR *dir)
  4482. {
  4483. struct dirent *result = 0;
  4484. if (dir) {
  4485. if (dir->handle != INVALID_HANDLE_VALUE) {
  4486. result = &dir->result;
  4487. (void)WideCharToMultiByte(CP_UTF8,
  4488. 0,
  4489. dir->info.cFileName,
  4490. -1,
  4491. result->d_name,
  4492. sizeof(result->d_name),
  4493. NULL,
  4494. NULL);
  4495. if (!FindNextFileW(dir->handle, &dir->info)) {
  4496. (void)FindClose(dir->handle);
  4497. dir->handle = INVALID_HANDLE_VALUE;
  4498. }
  4499. } else {
  4500. SetLastError(ERROR_FILE_NOT_FOUND);
  4501. }
  4502. } else {
  4503. SetLastError(ERROR_BAD_ARGUMENTS);
  4504. }
  4505. return result;
  4506. }
  4507. #if !defined(HAVE_POLL)
  4508. FUNCTION_MAY_BE_UNUSED
  4509. static int
  4510. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4511. {
  4512. struct timeval tv;
  4513. fd_set set;
  4514. unsigned int i;
  4515. int result;
  4516. SOCKET maxfd = 0;
  4517. memset(&tv, 0, sizeof(tv));
  4518. tv.tv_sec = milliseconds / 1000;
  4519. tv.tv_usec = (milliseconds % 1000) * 1000;
  4520. FD_ZERO(&set);
  4521. for (i = 0; i < n; i++) {
  4522. FD_SET((SOCKET)pfd[i].fd, &set);
  4523. pfd[i].revents = 0;
  4524. if (pfd[i].fd > maxfd) {
  4525. maxfd = pfd[i].fd;
  4526. }
  4527. }
  4528. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4529. for (i = 0; i < n; i++) {
  4530. if (FD_ISSET(pfd[i].fd, &set)) {
  4531. pfd[i].revents = POLLIN;
  4532. }
  4533. }
  4534. }
  4535. /* We should subtract the time used in select from remaining
  4536. * "milliseconds", in particular if called from mg_poll with a
  4537. * timeout quantum.
  4538. * Unfortunately, the remaining time is not stored in "tv" in all
  4539. * implementations, so the result in "tv" must be considered undefined.
  4540. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4541. return result;
  4542. }
  4543. #endif /* HAVE_POLL */
  4544. #if defined(__MINGW32__)
  4545. /* Enable unused function warning again */
  4546. #pragma GCC diagnostic pop
  4547. #endif
  4548. static void
  4549. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4550. {
  4551. (void)conn; /* Unused. */
  4552. #if defined(_WIN32_WCE)
  4553. (void)sock;
  4554. #else
  4555. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4556. #endif
  4557. }
  4558. int
  4559. mg_start_thread(mg_thread_func_t f, void *p)
  4560. {
  4561. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4562. /* Compile-time option to control stack size, e.g.
  4563. * -DUSE_STACK_SIZE=16384
  4564. */
  4565. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4566. == ((uintptr_t)(-1L)))
  4567. ? -1
  4568. : 0);
  4569. #else
  4570. return (
  4571. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4572. ? -1
  4573. : 0);
  4574. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4575. }
  4576. /* Start a thread storing the thread context. */
  4577. static int
  4578. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4579. void *p,
  4580. pthread_t *threadidptr)
  4581. {
  4582. uintptr_t uip;
  4583. HANDLE threadhandle;
  4584. int result = -1;
  4585. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4586. threadhandle = (HANDLE)uip;
  4587. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4588. *threadidptr = threadhandle;
  4589. result = 0;
  4590. }
  4591. return result;
  4592. }
  4593. /* Wait for a thread to finish. */
  4594. static int
  4595. mg_join_thread(pthread_t threadid)
  4596. {
  4597. int result;
  4598. DWORD dwevent;
  4599. result = -1;
  4600. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4601. if (dwevent == WAIT_FAILED) {
  4602. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4603. } else {
  4604. if (dwevent == WAIT_OBJECT_0) {
  4605. CloseHandle(threadid);
  4606. result = 0;
  4607. }
  4608. }
  4609. return result;
  4610. }
  4611. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4612. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4613. /* Create substitutes for POSIX functions in Win32. */
  4614. #if defined(__MINGW32__)
  4615. /* Show no warning in case system functions are not used. */
  4616. #pragma GCC diagnostic push
  4617. #pragma GCC diagnostic ignored "-Wunused-function"
  4618. #endif
  4619. FUNCTION_MAY_BE_UNUSED
  4620. static HANDLE
  4621. dlopen(const char *dll_name, int flags)
  4622. {
  4623. wchar_t wbuf[W_PATH_MAX];
  4624. (void)flags;
  4625. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4626. return LoadLibraryW(wbuf);
  4627. }
  4628. FUNCTION_MAY_BE_UNUSED
  4629. static int
  4630. dlclose(void *handle)
  4631. {
  4632. int result;
  4633. if (FreeLibrary((HMODULE)handle) != 0) {
  4634. result = 0;
  4635. } else {
  4636. result = -1;
  4637. }
  4638. return result;
  4639. }
  4640. #if defined(__MINGW32__)
  4641. /* Enable unused function warning again */
  4642. #pragma GCC diagnostic pop
  4643. #endif
  4644. #endif
  4645. #if !defined(NO_CGI)
  4646. #define SIGKILL (0)
  4647. static int
  4648. kill(pid_t pid, int sig_num)
  4649. {
  4650. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4651. (void)CloseHandle((HANDLE)pid);
  4652. return 0;
  4653. }
  4654. #ifndef WNOHANG
  4655. #define WNOHANG (1)
  4656. #endif
  4657. #if defined(USE_TIMERS)
  4658. pid_t
  4659. waitpid(pid_t pid, int *status, int flags)
  4660. {
  4661. DWORD timeout = INFINITE;
  4662. DWORD waitres;
  4663. (void)status; /* Currently not used by any client here */
  4664. if ((flags | WNOHANG) == WNOHANG) {
  4665. timeout = 0;
  4666. }
  4667. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4668. if (waitres == WAIT_OBJECT_0) {
  4669. return pid;
  4670. }
  4671. if (waitres == WAIT_TIMEOUT) {
  4672. return 0;
  4673. }
  4674. return (pid_t)-1;
  4675. }
  4676. #endif /* USE_TIMERS */
  4677. static void
  4678. trim_trailing_whitespaces(char *s)
  4679. {
  4680. char *e = s + strlen(s) - 1;
  4681. while ((e > s) && isspace(*(unsigned char *)e)) {
  4682. *e-- = '\0';
  4683. }
  4684. }
  4685. static pid_t
  4686. spawn_process(struct mg_connection *conn,
  4687. const char *prog,
  4688. char *envblk,
  4689. char *envp[],
  4690. int fdin[2],
  4691. int fdout[2],
  4692. int fderr[2],
  4693. const char *dir)
  4694. {
  4695. HANDLE me;
  4696. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4697. cmdline[PATH_MAX], buf[PATH_MAX];
  4698. int truncated;
  4699. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4700. STARTUPINFOA si;
  4701. PROCESS_INFORMATION pi = {0};
  4702. (void)envp;
  4703. memset(&si, 0, sizeof(si));
  4704. si.cb = sizeof(si);
  4705. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4706. si.wShowWindow = SW_HIDE;
  4707. me = GetCurrentProcess();
  4708. DuplicateHandle(me,
  4709. (HANDLE)_get_osfhandle(fdin[0]),
  4710. me,
  4711. &si.hStdInput,
  4712. 0,
  4713. TRUE,
  4714. DUPLICATE_SAME_ACCESS);
  4715. DuplicateHandle(me,
  4716. (HANDLE)_get_osfhandle(fdout[1]),
  4717. me,
  4718. &si.hStdOutput,
  4719. 0,
  4720. TRUE,
  4721. DUPLICATE_SAME_ACCESS);
  4722. DuplicateHandle(me,
  4723. (HANDLE)_get_osfhandle(fderr[1]),
  4724. me,
  4725. &si.hStdError,
  4726. 0,
  4727. TRUE,
  4728. DUPLICATE_SAME_ACCESS);
  4729. /* Mark handles that should not be inherited. See
  4730. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4731. */
  4732. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4733. HANDLE_FLAG_INHERIT,
  4734. 0);
  4735. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4736. HANDLE_FLAG_INHERIT,
  4737. 0);
  4738. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4739. HANDLE_FLAG_INHERIT,
  4740. 0);
  4741. /* If CGI file is a script, try to read the interpreter line */
  4742. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4743. if (interp == NULL) {
  4744. buf[0] = buf[1] = '\0';
  4745. /* Read the first line of the script into the buffer */
  4746. mg_snprintf(
  4747. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4748. if (truncated) {
  4749. pi.hProcess = (pid_t)-1;
  4750. goto spawn_cleanup;
  4751. }
  4752. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4753. #if defined(MG_USE_OPEN_FILE)
  4754. p = (char *)file.access.membuf;
  4755. #else
  4756. p = (char *)NULL;
  4757. #endif
  4758. mg_fgets(buf, sizeof(buf), &file, &p);
  4759. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4760. buf[sizeof(buf) - 1] = '\0';
  4761. }
  4762. if ((buf[0] == '#') && (buf[1] == '!')) {
  4763. trim_trailing_whitespaces(buf + 2);
  4764. } else {
  4765. buf[2] = '\0';
  4766. }
  4767. interp = buf + 2;
  4768. }
  4769. if (interp[0] != '\0') {
  4770. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4771. interp = full_interp;
  4772. }
  4773. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4774. if (interp[0] != '\0') {
  4775. mg_snprintf(conn,
  4776. &truncated,
  4777. cmdline,
  4778. sizeof(cmdline),
  4779. "\"%s\" \"%s\\%s\"",
  4780. interp,
  4781. full_dir,
  4782. prog);
  4783. } else {
  4784. mg_snprintf(conn,
  4785. &truncated,
  4786. cmdline,
  4787. sizeof(cmdline),
  4788. "\"%s\\%s\"",
  4789. full_dir,
  4790. prog);
  4791. }
  4792. if (truncated) {
  4793. pi.hProcess = (pid_t)-1;
  4794. goto spawn_cleanup;
  4795. }
  4796. DEBUG_TRACE("Running [%s]", cmdline);
  4797. if (CreateProcessA(NULL,
  4798. cmdline,
  4799. NULL,
  4800. NULL,
  4801. TRUE,
  4802. CREATE_NEW_PROCESS_GROUP,
  4803. envblk,
  4804. NULL,
  4805. &si,
  4806. &pi) == 0) {
  4807. mg_cry_internal(
  4808. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4809. pi.hProcess = (pid_t)-1;
  4810. /* goto spawn_cleanup; */
  4811. }
  4812. spawn_cleanup:
  4813. (void)CloseHandle(si.hStdOutput);
  4814. (void)CloseHandle(si.hStdError);
  4815. (void)CloseHandle(si.hStdInput);
  4816. if (pi.hThread != NULL) {
  4817. (void)CloseHandle(pi.hThread);
  4818. }
  4819. return (pid_t)pi.hProcess;
  4820. }
  4821. #endif /* !NO_CGI */
  4822. static int
  4823. set_blocking_mode(SOCKET sock)
  4824. {
  4825. unsigned long non_blocking = 0;
  4826. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4827. }
  4828. static int
  4829. set_non_blocking_mode(SOCKET sock)
  4830. {
  4831. unsigned long non_blocking = 1;
  4832. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4833. }
  4834. #else
  4835. static int
  4836. mg_stat(const struct mg_connection *conn,
  4837. const char *path,
  4838. struct mg_file_stat *filep)
  4839. {
  4840. struct stat st;
  4841. if (!filep) {
  4842. return 0;
  4843. }
  4844. memset(filep, 0, sizeof(*filep));
  4845. if (conn && is_file_in_memory(conn, path)) {
  4846. /* Quick fix (for 1.9.x): */
  4847. /* mg_stat must fill all fields, also for files in memory */
  4848. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4849. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4850. filep->size = tmp_file.stat.size;
  4851. filep->last_modified = time(NULL);
  4852. filep->location = 2;
  4853. /* TODO: remove legacy "files in memory" feature */
  4854. return 1;
  4855. }
  4856. if (0 == stat(path, &st)) {
  4857. filep->size = (uint64_t)(st.st_size);
  4858. filep->last_modified = st.st_mtime;
  4859. filep->is_directory = S_ISDIR(st.st_mode);
  4860. return 1;
  4861. }
  4862. return 0;
  4863. }
  4864. static void
  4865. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4866. {
  4867. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4868. if (conn) {
  4869. mg_cry_internal(conn,
  4870. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4871. __func__,
  4872. strerror(ERRNO));
  4873. }
  4874. }
  4875. }
  4876. int
  4877. mg_start_thread(mg_thread_func_t func, void *param)
  4878. {
  4879. pthread_t thread_id;
  4880. pthread_attr_t attr;
  4881. int result;
  4882. (void)pthread_attr_init(&attr);
  4883. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4884. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4885. /* Compile-time option to control stack size,
  4886. * e.g. -DUSE_STACK_SIZE=16384 */
  4887. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4888. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4889. result = pthread_create(&thread_id, &attr, func, param);
  4890. pthread_attr_destroy(&attr);
  4891. return result;
  4892. }
  4893. /* Start a thread storing the thread context. */
  4894. static int
  4895. mg_start_thread_with_id(mg_thread_func_t func,
  4896. void *param,
  4897. pthread_t *threadidptr)
  4898. {
  4899. pthread_t thread_id;
  4900. pthread_attr_t attr;
  4901. int result;
  4902. (void)pthread_attr_init(&attr);
  4903. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4904. /* Compile-time option to control stack size,
  4905. * e.g. -DUSE_STACK_SIZE=16384 */
  4906. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4907. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4908. result = pthread_create(&thread_id, &attr, func, param);
  4909. pthread_attr_destroy(&attr);
  4910. if ((result == 0) && (threadidptr != NULL)) {
  4911. *threadidptr = thread_id;
  4912. }
  4913. return result;
  4914. }
  4915. /* Wait for a thread to finish. */
  4916. static int
  4917. mg_join_thread(pthread_t threadid)
  4918. {
  4919. int result;
  4920. result = pthread_join(threadid, NULL);
  4921. return result;
  4922. }
  4923. #if !defined(NO_CGI)
  4924. static pid_t
  4925. spawn_process(struct mg_connection *conn,
  4926. const char *prog,
  4927. char *envblk,
  4928. char *envp[],
  4929. int fdin[2],
  4930. int fdout[2],
  4931. int fderr[2],
  4932. const char *dir)
  4933. {
  4934. pid_t pid;
  4935. const char *interp;
  4936. (void)envblk;
  4937. if (conn == NULL) {
  4938. return 0;
  4939. }
  4940. if ((pid = fork()) == -1) {
  4941. /* Parent */
  4942. mg_send_http_error(conn,
  4943. 500,
  4944. "Error: Creating CGI process\nfork(): %s",
  4945. strerror(ERRNO));
  4946. } else if (pid == 0) {
  4947. /* Child */
  4948. if (chdir(dir) != 0) {
  4949. mg_cry_internal(
  4950. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4951. } else if (dup2(fdin[0], 0) == -1) {
  4952. mg_cry_internal(conn,
  4953. "%s: dup2(%d, 0): %s",
  4954. __func__,
  4955. fdin[0],
  4956. strerror(ERRNO));
  4957. } else if (dup2(fdout[1], 1) == -1) {
  4958. mg_cry_internal(conn,
  4959. "%s: dup2(%d, 1): %s",
  4960. __func__,
  4961. fdout[1],
  4962. strerror(ERRNO));
  4963. } else if (dup2(fderr[1], 2) == -1) {
  4964. mg_cry_internal(conn,
  4965. "%s: dup2(%d, 2): %s",
  4966. __func__,
  4967. fderr[1],
  4968. strerror(ERRNO));
  4969. } else {
  4970. /* Keep stderr and stdout in two different pipes.
  4971. * Stdout will be sent back to the client,
  4972. * stderr should go into a server error log. */
  4973. (void)close(fdin[0]);
  4974. (void)close(fdout[1]);
  4975. (void)close(fderr[1]);
  4976. /* Close write end fdin and read end fdout and fderr */
  4977. (void)close(fdin[1]);
  4978. (void)close(fdout[0]);
  4979. (void)close(fderr[0]);
  4980. /* After exec, all signal handlers are restored to their default
  4981. * values, with one exception of SIGCHLD. According to
  4982. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4983. * will leave unchanged after exec if it was set to be ignored.
  4984. * Restore it to default action. */
  4985. signal(SIGCHLD, SIG_DFL);
  4986. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4987. if (interp == NULL) {
  4988. (void)execle(prog, prog, NULL, envp);
  4989. mg_cry_internal(conn,
  4990. "%s: execle(%s): %s",
  4991. __func__,
  4992. prog,
  4993. strerror(ERRNO));
  4994. } else {
  4995. (void)execle(interp, interp, prog, NULL, envp);
  4996. mg_cry_internal(conn,
  4997. "%s: execle(%s %s): %s",
  4998. __func__,
  4999. interp,
  5000. prog,
  5001. strerror(ERRNO));
  5002. }
  5003. }
  5004. exit(EXIT_FAILURE);
  5005. }
  5006. return pid;
  5007. }
  5008. #endif /* !NO_CGI */
  5009. static int
  5010. set_non_blocking_mode(SOCKET sock)
  5011. {
  5012. int flags = fcntl(sock, F_GETFL, 0);
  5013. if (flags < 0) {
  5014. return -1;
  5015. }
  5016. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5017. return -1;
  5018. }
  5019. return 0;
  5020. }
  5021. static int
  5022. set_blocking_mode(SOCKET sock)
  5023. {
  5024. int flags = fcntl(sock, F_GETFL, 0);
  5025. if (flags < 0) {
  5026. return -1;
  5027. }
  5028. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5029. return -1;
  5030. }
  5031. return 0;
  5032. }
  5033. #endif /* _WIN32 / else */
  5034. /* End of initial operating system specific define block. */
  5035. /* Get a random number (independent of C rand function) */
  5036. static uint64_t
  5037. get_random(void)
  5038. {
  5039. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5040. static uint64_t lcg = 0; /* Linear congruential generator */
  5041. uint64_t now = mg_get_current_time_ns();
  5042. if (lfsr == 0) {
  5043. /* lfsr will be only 0 if has not been initialized,
  5044. * so this code is called only once. */
  5045. lfsr = mg_get_current_time_ns();
  5046. lcg = mg_get_current_time_ns();
  5047. } else {
  5048. /* Get the next step of both random number generators. */
  5049. lfsr = (lfsr >> 1)
  5050. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5051. << 63);
  5052. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5053. }
  5054. /* Combining two pseudo-random number generators and a high resolution
  5055. * part
  5056. * of the current server time will make it hard (impossible?) to guess
  5057. * the
  5058. * next number. */
  5059. return (lfsr ^ lcg ^ now);
  5060. }
  5061. static int
  5062. mg_poll(struct pollfd *pfd,
  5063. unsigned int n,
  5064. int milliseconds,
  5065. volatile int *stop_server)
  5066. {
  5067. /* Call poll, but only for a maximum time of a few seconds.
  5068. * This will allow to stop the server after some seconds, instead
  5069. * of having to wait for a long socket timeout. */
  5070. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5071. do {
  5072. int result;
  5073. if (*stop_server) {
  5074. /* Shut down signal */
  5075. return -2;
  5076. }
  5077. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5078. ms_now = milliseconds;
  5079. }
  5080. result = poll(pfd, n, ms_now);
  5081. if (result != 0) {
  5082. /* Poll returned either success (1) or error (-1).
  5083. * Forward both to the caller. */
  5084. return result;
  5085. }
  5086. /* Poll returned timeout (0). */
  5087. if (milliseconds > 0) {
  5088. milliseconds -= ms_now;
  5089. }
  5090. } while (milliseconds != 0);
  5091. /* timeout: return 0 */
  5092. return 0;
  5093. }
  5094. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5095. * descriptor.
  5096. * Return value:
  5097. * >=0 .. number of bytes successfully written
  5098. * -1 .. timeout
  5099. * -2 .. error
  5100. */
  5101. static int
  5102. push_inner(struct mg_context *ctx,
  5103. FILE *fp,
  5104. SOCKET sock,
  5105. SSL *ssl,
  5106. const char *buf,
  5107. int len,
  5108. double timeout)
  5109. {
  5110. uint64_t start = 0, now = 0, timeout_ns = 0;
  5111. int n, err;
  5112. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5113. #if defined(_WIN32)
  5114. typedef int len_t;
  5115. #else
  5116. typedef size_t len_t;
  5117. #endif
  5118. if (timeout > 0) {
  5119. now = mg_get_current_time_ns();
  5120. start = now;
  5121. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5122. }
  5123. if (ctx == NULL) {
  5124. return -2;
  5125. }
  5126. #if defined(NO_SSL)
  5127. if (ssl) {
  5128. return -2;
  5129. }
  5130. #endif
  5131. /* Try to read until it succeeds, fails, times out, or the server
  5132. * shuts down. */
  5133. for (;;) {
  5134. #if !defined(NO_SSL)
  5135. if (ssl != NULL) {
  5136. n = SSL_write(ssl, buf, len);
  5137. if (n <= 0) {
  5138. err = SSL_get_error(ssl, n);
  5139. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5140. err = ERRNO;
  5141. } else if ((err == SSL_ERROR_WANT_READ)
  5142. || (err == SSL_ERROR_WANT_WRITE)) {
  5143. n = 0;
  5144. } else {
  5145. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5146. return -2;
  5147. }
  5148. } else {
  5149. err = 0;
  5150. }
  5151. } else
  5152. #endif
  5153. if (fp != NULL) {
  5154. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5155. if (ferror(fp)) {
  5156. n = -1;
  5157. err = ERRNO;
  5158. } else {
  5159. err = 0;
  5160. }
  5161. } else {
  5162. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5163. err = (n < 0) ? ERRNO : 0;
  5164. #if defined(_WIN32)
  5165. if (err == WSAEWOULDBLOCK) {
  5166. err = 0;
  5167. n = 0;
  5168. }
  5169. #else
  5170. if (err == EWOULDBLOCK) {
  5171. err = 0;
  5172. n = 0;
  5173. }
  5174. #endif
  5175. if (n < 0) {
  5176. /* shutdown of the socket at client side */
  5177. return -2;
  5178. }
  5179. }
  5180. if (ctx->stop_flag) {
  5181. return -2;
  5182. }
  5183. if ((n > 0) || ((n == 0) && (len == 0))) {
  5184. /* some data has been read, or no data was requested */
  5185. return n;
  5186. }
  5187. if (n < 0) {
  5188. /* socket error - check errno */
  5189. DEBUG_TRACE("send() failed, error %d", err);
  5190. /* TODO (mid): error handling depending on the error code.
  5191. * These codes are different between Windows and Linux.
  5192. * Currently there is no problem with failing send calls,
  5193. * if there is a reproducible situation, it should be
  5194. * investigated in detail.
  5195. */
  5196. return -2;
  5197. }
  5198. /* Only in case n=0 (timeout), repeat calling the write function */
  5199. /* If send failed, wait before retry */
  5200. if (fp != NULL) {
  5201. /* For files, just wait a fixed time.
  5202. * Maybe it helps, maybe not. */
  5203. mg_sleep(5);
  5204. } else {
  5205. /* For sockets, wait for the socket using select */
  5206. fd_set wfds;
  5207. struct timeval tv;
  5208. int sret;
  5209. #if defined(__GNUC__) || defined(__MINGW32__)
  5210. /* GCC seems to have a flaw with it's own socket macros:
  5211. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  5212. */
  5213. #pragma GCC diagnostic push
  5214. #pragma GCC diagnostic ignored "-Wsign-conversion"
  5215. #endif
  5216. FD_ZERO(&wfds);
  5217. FD_SET(sock, &wfds);
  5218. tv.tv_sec = (time_t)(ms_wait / 1000);
  5219. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  5220. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  5221. #if defined(__GNUC__) || defined(__MINGW32__)
  5222. #pragma GCC diagnostic pop
  5223. #endif
  5224. if (sret > 0) {
  5225. /* We got ready to write. Don't check the timeout
  5226. * but directly go back to write again. */
  5227. continue;
  5228. }
  5229. }
  5230. if (timeout > 0) {
  5231. now = mg_get_current_time_ns();
  5232. if ((now - start) > timeout_ns) {
  5233. /* Timeout */
  5234. break;
  5235. }
  5236. }
  5237. }
  5238. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5239. used */
  5240. return -1;
  5241. }
  5242. static int64_t
  5243. push_all(struct mg_context *ctx,
  5244. FILE *fp,
  5245. SOCKET sock,
  5246. SSL *ssl,
  5247. const char *buf,
  5248. int64_t len)
  5249. {
  5250. double timeout = -1.0;
  5251. int64_t n, nwritten = 0;
  5252. if (ctx == NULL) {
  5253. return -1;
  5254. }
  5255. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5256. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5257. }
  5258. while ((len > 0) && (ctx->stop_flag == 0)) {
  5259. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  5260. if (n < 0) {
  5261. if (nwritten == 0) {
  5262. nwritten = n; /* Propagate the error */
  5263. }
  5264. break;
  5265. } else if (n == 0) {
  5266. break; /* No more data to write */
  5267. } else {
  5268. nwritten += n;
  5269. len -= n;
  5270. }
  5271. }
  5272. return nwritten;
  5273. }
  5274. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5275. * Return value:
  5276. * >=0 .. number of bytes successfully read
  5277. * -1 .. timeout
  5278. * -2 .. error
  5279. */
  5280. static int
  5281. pull_inner(FILE *fp,
  5282. struct mg_connection *conn,
  5283. char *buf,
  5284. int len,
  5285. double timeout)
  5286. {
  5287. int nread, err = 0;
  5288. #if defined(_WIN32)
  5289. typedef int len_t;
  5290. #else
  5291. typedef size_t len_t;
  5292. #endif
  5293. #if !defined(NO_SSL)
  5294. int ssl_pending;
  5295. #endif
  5296. /* We need an additional wait loop around this, because in some cases
  5297. * with TLSwe may get data from the socket but not from SSL_read.
  5298. * In this case we need to repeat at least once.
  5299. */
  5300. if (fp != NULL) {
  5301. #if !defined(_WIN32_WCE)
  5302. /* Use read() instead of fread(), because if we're reading from the
  5303. * CGI pipe, fread() may block until IO buffer is filled up. We
  5304. * cannot afford to block and must pass all read bytes immediately
  5305. * to the client. */
  5306. nread = (int)read(fileno(fp), buf, (size_t)len);
  5307. #else
  5308. /* WinCE does not support CGI pipes */
  5309. nread = (int)fread(buf, 1, (size_t)len, fp);
  5310. #endif
  5311. err = (nread < 0) ? ERRNO : 0;
  5312. if ((nread == 0) && (len > 0)) {
  5313. /* Should get data, but got EOL */
  5314. return -2;
  5315. }
  5316. #if !defined(NO_SSL)
  5317. } else if ((conn->ssl != NULL)
  5318. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5319. /* We already know there is no more data buffered in conn->buf
  5320. * but there is more available in the SSL layer. So don't poll
  5321. * conn->client.sock yet. */
  5322. if (ssl_pending > len) {
  5323. ssl_pending = len;
  5324. }
  5325. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5326. if (nread <= 0) {
  5327. err = SSL_get_error(conn->ssl, nread);
  5328. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5329. err = ERRNO;
  5330. } else if ((err == SSL_ERROR_WANT_READ)
  5331. || (err == SSL_ERROR_WANT_WRITE)) {
  5332. nread = 0;
  5333. } else {
  5334. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5335. return -1;
  5336. }
  5337. } else {
  5338. err = 0;
  5339. }
  5340. } else if (conn->ssl != NULL) {
  5341. struct pollfd pfd[1];
  5342. int pollres;
  5343. pfd[0].fd = conn->client.sock;
  5344. pfd[0].events = POLLIN;
  5345. pollres = mg_poll(pfd,
  5346. 1,
  5347. (int)(timeout * 1000.0),
  5348. &(conn->phys_ctx->stop_flag));
  5349. if (conn->phys_ctx->stop_flag) {
  5350. return -2;
  5351. }
  5352. if (pollres > 0) {
  5353. nread = SSL_read(conn->ssl, buf, len);
  5354. if (nread <= 0) {
  5355. err = SSL_get_error(conn->ssl, nread);
  5356. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5357. err = ERRNO;
  5358. } else if ((err == SSL_ERROR_WANT_READ)
  5359. || (err == SSL_ERROR_WANT_WRITE)) {
  5360. nread = 0;
  5361. } else {
  5362. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5363. return -2;
  5364. }
  5365. } else {
  5366. err = 0;
  5367. }
  5368. } else if (pollres < 0) {
  5369. /* Error */
  5370. return -2;
  5371. } else {
  5372. /* pollres = 0 means timeout */
  5373. nread = 0;
  5374. }
  5375. #endif
  5376. } else {
  5377. struct pollfd pfd[1];
  5378. int pollres;
  5379. pfd[0].fd = conn->client.sock;
  5380. pfd[0].events = POLLIN;
  5381. pollres = mg_poll(pfd,
  5382. 1,
  5383. (int)(timeout * 1000.0),
  5384. &(conn->phys_ctx->stop_flag));
  5385. if (conn->phys_ctx->stop_flag) {
  5386. return -2;
  5387. }
  5388. if (pollres > 0) {
  5389. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5390. err = (nread < 0) ? ERRNO : 0;
  5391. if (nread <= 0) {
  5392. /* shutdown of the socket at client side */
  5393. return -2;
  5394. }
  5395. } else if (pollres < 0) {
  5396. /* error callint poll */
  5397. return -2;
  5398. } else {
  5399. /* pollres = 0 means timeout */
  5400. nread = 0;
  5401. }
  5402. }
  5403. if (conn->phys_ctx->stop_flag) {
  5404. return -2;
  5405. }
  5406. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5407. /* some data has been read, or no data was requested */
  5408. return nread;
  5409. }
  5410. if (nread < 0) {
  5411. /* socket error - check errno */
  5412. #if defined(_WIN32)
  5413. if (err == WSAEWOULDBLOCK) {
  5414. /* TODO (low): check if this is still required */
  5415. /* standard case if called from close_socket_gracefully */
  5416. return -2;
  5417. } else if (err == WSAETIMEDOUT) {
  5418. /* TODO (low): check if this is still required */
  5419. /* timeout is handled by the while loop */
  5420. return 0;
  5421. } else if (err == WSAECONNABORTED) {
  5422. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5423. return -2;
  5424. } else {
  5425. DEBUG_TRACE("recv() failed, error %d", err);
  5426. return -2;
  5427. }
  5428. #else
  5429. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5430. * if the timeout is reached and if the socket was set to non-
  5431. * blocking in close_socket_gracefully, so we can not distinguish
  5432. * here. We have to wait for the timeout in both cases for now.
  5433. */
  5434. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5435. /* TODO (low): check if this is still required */
  5436. /* EAGAIN/EWOULDBLOCK:
  5437. * standard case if called from close_socket_gracefully
  5438. * => should return -1 */
  5439. /* or timeout occurred
  5440. * => the code must stay in the while loop */
  5441. /* EINTR can be generated on a socket with a timeout set even
  5442. * when SA_RESTART is effective for all relevant signals
  5443. * (see signal(7)).
  5444. * => stay in the while loop */
  5445. } else {
  5446. DEBUG_TRACE("recv() failed, error %d", err);
  5447. return -2;
  5448. }
  5449. #endif
  5450. }
  5451. /* Timeout occurred, but no data available. */
  5452. return -1;
  5453. }
  5454. static int
  5455. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5456. {
  5457. int n, nread = 0;
  5458. double timeout = -1.0;
  5459. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5460. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5461. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5462. }
  5463. if (timeout >= 0.0) {
  5464. start_time = mg_get_current_time_ns();
  5465. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5466. }
  5467. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5468. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5469. if (n == -2) {
  5470. if (nread == 0) {
  5471. nread = -1; /* Propagate the error */
  5472. }
  5473. break;
  5474. } else if (n == -1) {
  5475. /* timeout */
  5476. if (timeout >= 0.0) {
  5477. now = mg_get_current_time_ns();
  5478. if ((now - start_time) <= timeout_ns) {
  5479. continue;
  5480. }
  5481. }
  5482. break;
  5483. } else if (n == 0) {
  5484. break; /* No more data to read */
  5485. } else {
  5486. conn->consumed_content += n;
  5487. nread += n;
  5488. len -= n;
  5489. }
  5490. }
  5491. return nread;
  5492. }
  5493. static void
  5494. discard_unread_request_data(struct mg_connection *conn)
  5495. {
  5496. char buf[MG_BUF_LEN];
  5497. size_t to_read;
  5498. int nread;
  5499. if (conn == NULL) {
  5500. return;
  5501. }
  5502. to_read = sizeof(buf);
  5503. if (conn->is_chunked) {
  5504. /* Chunked encoding: 3=chunk read completely
  5505. * completely */
  5506. while (conn->is_chunked != 3) {
  5507. nread = mg_read(conn, buf, to_read);
  5508. if (nread <= 0) {
  5509. break;
  5510. }
  5511. }
  5512. } else {
  5513. /* Not chunked: content length is known */
  5514. while (conn->consumed_content < conn->content_len) {
  5515. if (to_read
  5516. > (size_t)(conn->content_len - conn->consumed_content)) {
  5517. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5518. }
  5519. nread = mg_read(conn, buf, to_read);
  5520. if (nread <= 0) {
  5521. break;
  5522. }
  5523. }
  5524. }
  5525. }
  5526. static int
  5527. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5528. {
  5529. int64_t n, buffered_len, nread;
  5530. int64_t len64 =
  5531. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5532. * int, we may not read more
  5533. * bytes */
  5534. const char *body;
  5535. if (conn == NULL) {
  5536. return 0;
  5537. }
  5538. /* If Content-Length is not set for a request with body data
  5539. * (e.g., a PUT or POST request), we do not know in advance
  5540. * how much data should be read. */
  5541. if (conn->consumed_content == 0) {
  5542. if (conn->is_chunked == 1) {
  5543. conn->content_len = len64;
  5544. conn->is_chunked = 2;
  5545. } else if (conn->content_len == -1) {
  5546. /* The body data is completed when the connection
  5547. * is closed. */
  5548. conn->content_len = INT64_MAX;
  5549. conn->must_close = 1;
  5550. }
  5551. }
  5552. nread = 0;
  5553. if (conn->consumed_content < conn->content_len) {
  5554. /* Adjust number of bytes to read. */
  5555. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5556. if (left_to_read < len64) {
  5557. /* Do not read more than the total content length of the
  5558. * request.
  5559. */
  5560. len64 = left_to_read;
  5561. }
  5562. /* Return buffered data */
  5563. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5564. - conn->consumed_content;
  5565. if (buffered_len > 0) {
  5566. if (len64 < buffered_len) {
  5567. buffered_len = len64;
  5568. }
  5569. body = conn->buf + conn->request_len + conn->consumed_content;
  5570. memcpy(buf, body, (size_t)buffered_len);
  5571. len64 -= buffered_len;
  5572. conn->consumed_content += buffered_len;
  5573. nread += buffered_len;
  5574. buf = (char *)buf + buffered_len;
  5575. }
  5576. /* We have returned all buffered data. Read new data from the remote
  5577. * socket.
  5578. */
  5579. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5580. nread += n;
  5581. } else {
  5582. nread = ((nread > 0) ? nread : n);
  5583. }
  5584. }
  5585. return (int)nread;
  5586. }
  5587. static char
  5588. mg_getc(struct mg_connection *conn)
  5589. {
  5590. char c;
  5591. if (conn == NULL) {
  5592. return 0;
  5593. }
  5594. if (mg_read_inner(conn, &c, 1) <= 0) {
  5595. return (char)0;
  5596. }
  5597. return c;
  5598. }
  5599. int
  5600. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5601. {
  5602. if (len > INT_MAX) {
  5603. len = INT_MAX;
  5604. }
  5605. if (conn == NULL) {
  5606. return 0;
  5607. }
  5608. if (conn->is_chunked) {
  5609. size_t all_read = 0;
  5610. while (len > 0) {
  5611. if (conn->is_chunked == 3) {
  5612. /* No more data left to read */
  5613. return 0;
  5614. }
  5615. if (conn->chunk_remainder) {
  5616. /* copy from the remainder of the last received chunk */
  5617. long read_ret;
  5618. size_t read_now =
  5619. ((conn->chunk_remainder > len) ? (len)
  5620. : (conn->chunk_remainder));
  5621. conn->content_len += (int)read_now;
  5622. read_ret =
  5623. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5624. if (read_ret < 1) {
  5625. /* read error */
  5626. return -1;
  5627. }
  5628. all_read += (size_t)read_ret;
  5629. conn->chunk_remainder -= (size_t)read_ret;
  5630. len -= (size_t)read_ret;
  5631. if (conn->chunk_remainder == 0) {
  5632. /* Add data bytes in the current chunk have been read,
  5633. * so we are expecting \r\n now. */
  5634. char x1, x2;
  5635. conn->content_len += 2;
  5636. x1 = mg_getc(conn);
  5637. x2 = mg_getc(conn);
  5638. if ((x1 != '\r') || (x2 != '\n')) {
  5639. /* Protocol violation */
  5640. return -1;
  5641. }
  5642. }
  5643. } else {
  5644. /* fetch a new chunk */
  5645. int i = 0;
  5646. char lenbuf[64];
  5647. char *end = 0;
  5648. unsigned long chunkSize = 0;
  5649. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5650. conn->content_len++;
  5651. lenbuf[i] = mg_getc(conn);
  5652. if ((i > 0) && (lenbuf[i] == '\r')
  5653. && (lenbuf[i - 1] != '\r')) {
  5654. continue;
  5655. }
  5656. if ((i > 1) && (lenbuf[i] == '\n')
  5657. && (lenbuf[i - 1] == '\r')) {
  5658. lenbuf[i + 1] = 0;
  5659. chunkSize = strtoul(lenbuf, &end, 16);
  5660. if (chunkSize == 0) {
  5661. /* regular end of content */
  5662. conn->is_chunked = 3;
  5663. }
  5664. break;
  5665. }
  5666. if (!isxdigit(lenbuf[i])) {
  5667. /* illegal character for chunk length */
  5668. return -1;
  5669. }
  5670. }
  5671. if ((end == NULL) || (*end != '\r')) {
  5672. /* chunksize not set correctly */
  5673. return -1;
  5674. }
  5675. if (chunkSize == 0) {
  5676. break;
  5677. }
  5678. conn->chunk_remainder = chunkSize;
  5679. }
  5680. }
  5681. return (int)all_read;
  5682. }
  5683. return mg_read_inner(conn, buf, len);
  5684. }
  5685. int
  5686. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5687. {
  5688. time_t now;
  5689. int64_t n, total, allowed;
  5690. if (conn == NULL) {
  5691. return 0;
  5692. }
  5693. if (conn->throttle > 0) {
  5694. if ((now = time(NULL)) != conn->last_throttle_time) {
  5695. conn->last_throttle_time = now;
  5696. conn->last_throttle_bytes = 0;
  5697. }
  5698. allowed = conn->throttle - conn->last_throttle_bytes;
  5699. if (allowed > (int64_t)len) {
  5700. allowed = (int64_t)len;
  5701. }
  5702. if ((total = push_all(conn->phys_ctx,
  5703. NULL,
  5704. conn->client.sock,
  5705. conn->ssl,
  5706. (const char *)buf,
  5707. (int64_t)allowed)) == allowed) {
  5708. buf = (const char *)buf + total;
  5709. conn->last_throttle_bytes += total;
  5710. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5711. allowed = (conn->throttle > ((int64_t)len - total))
  5712. ? (int64_t)len - total
  5713. : conn->throttle;
  5714. if ((n = push_all(conn->phys_ctx,
  5715. NULL,
  5716. conn->client.sock,
  5717. conn->ssl,
  5718. (const char *)buf,
  5719. (int64_t)allowed)) != allowed) {
  5720. break;
  5721. }
  5722. sleep(1);
  5723. conn->last_throttle_bytes = allowed;
  5724. conn->last_throttle_time = time(NULL);
  5725. buf = (const char *)buf + n;
  5726. total += n;
  5727. }
  5728. }
  5729. } else {
  5730. total = push_all(conn->phys_ctx,
  5731. NULL,
  5732. conn->client.sock,
  5733. conn->ssl,
  5734. (const char *)buf,
  5735. (int64_t)len);
  5736. }
  5737. if (total > 0) {
  5738. conn->num_bytes_sent += total;
  5739. }
  5740. return (int)total;
  5741. }
  5742. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5743. int
  5744. mg_send_chunk(struct mg_connection *conn,
  5745. const char *chunk,
  5746. unsigned int chunk_len)
  5747. {
  5748. char lenbuf[16];
  5749. size_t lenbuf_len;
  5750. int ret;
  5751. int t;
  5752. /* First store the length information in a text buffer. */
  5753. sprintf(lenbuf, "%x\r\n", chunk_len);
  5754. lenbuf_len = strlen(lenbuf);
  5755. /* Then send length information, chunk and terminating \r\n. */
  5756. ret = mg_write(conn, lenbuf, lenbuf_len);
  5757. if (ret != (int)lenbuf_len) {
  5758. return -1;
  5759. }
  5760. t = ret;
  5761. ret = mg_write(conn, chunk, chunk_len);
  5762. if (ret != (int)chunk_len) {
  5763. return -1;
  5764. }
  5765. t += ret;
  5766. ret = mg_write(conn, "\r\n", 2);
  5767. if (ret != 2) {
  5768. return -1;
  5769. }
  5770. t += ret;
  5771. return t;
  5772. }
  5773. #if defined(__GNUC__) || defined(__MINGW32__)
  5774. /* This block forwards format strings to printf implementations,
  5775. * so we need to disable the format-nonliteral warning. */
  5776. #pragma GCC diagnostic push
  5777. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5778. #endif
  5779. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5780. static int
  5781. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5782. {
  5783. va_list ap_copy;
  5784. size_t size = MG_BUF_LEN / 4;
  5785. int len = -1;
  5786. *buf = NULL;
  5787. while (len < 0) {
  5788. if (*buf) {
  5789. mg_free(*buf);
  5790. }
  5791. size *= 4;
  5792. *buf = (char *)mg_malloc(size);
  5793. if (!*buf) {
  5794. break;
  5795. }
  5796. va_copy(ap_copy, ap);
  5797. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5798. va_end(ap_copy);
  5799. (*buf)[size - 1] = 0;
  5800. }
  5801. return len;
  5802. }
  5803. /* Print message to buffer. If buffer is large enough to hold the message,
  5804. * return buffer. If buffer is to small, allocate large enough buffer on
  5805. * heap,
  5806. * and return allocated buffer. */
  5807. static int
  5808. alloc_vprintf(char **out_buf,
  5809. char *prealloc_buf,
  5810. size_t prealloc_size,
  5811. const char *fmt,
  5812. va_list ap)
  5813. {
  5814. va_list ap_copy;
  5815. int len;
  5816. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5817. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5818. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5819. * Therefore, we make two passes: on first pass, get required message
  5820. * length.
  5821. * On second pass, actually print the message. */
  5822. va_copy(ap_copy, ap);
  5823. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5824. va_end(ap_copy);
  5825. if (len < 0) {
  5826. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5827. * Switch to alternative code path that uses incremental
  5828. * allocations.
  5829. */
  5830. va_copy(ap_copy, ap);
  5831. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5832. va_end(ap_copy);
  5833. } else if ((size_t)(len) >= prealloc_size) {
  5834. /* The pre-allocated buffer not large enough. */
  5835. /* Allocate a new buffer. */
  5836. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5837. if (!*out_buf) {
  5838. /* Allocation failed. Return -1 as "out of memory" error. */
  5839. return -1;
  5840. }
  5841. /* Buffer allocation successful. Store the string there. */
  5842. va_copy(ap_copy, ap);
  5843. IGNORE_UNUSED_RESULT(
  5844. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5845. va_end(ap_copy);
  5846. } else {
  5847. /* The pre-allocated buffer is large enough.
  5848. * Use it to store the string and return the address. */
  5849. va_copy(ap_copy, ap);
  5850. IGNORE_UNUSED_RESULT(
  5851. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5852. va_end(ap_copy);
  5853. *out_buf = prealloc_buf;
  5854. }
  5855. return len;
  5856. }
  5857. #if defined(__GNUC__) || defined(__MINGW32__)
  5858. /* Enable format-nonliteral warning again. */
  5859. #pragma GCC diagnostic pop
  5860. #endif
  5861. static int
  5862. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5863. {
  5864. char mem[MG_BUF_LEN];
  5865. char *buf = NULL;
  5866. int len;
  5867. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5868. len = mg_write(conn, buf, (size_t)len);
  5869. }
  5870. if ((buf != mem) && (buf != NULL)) {
  5871. mg_free(buf);
  5872. }
  5873. return len;
  5874. }
  5875. int
  5876. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5877. {
  5878. va_list ap;
  5879. int result;
  5880. va_start(ap, fmt);
  5881. result = mg_vprintf(conn, fmt, ap);
  5882. va_end(ap);
  5883. return result;
  5884. }
  5885. int
  5886. mg_url_decode(const char *src,
  5887. int src_len,
  5888. char *dst,
  5889. int dst_len,
  5890. int is_form_url_encoded)
  5891. {
  5892. int i, j, a, b;
  5893. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5894. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5895. if ((i < src_len - 2) && (src[i] == '%')
  5896. && isxdigit(*(const unsigned char *)(src + i + 1))
  5897. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5898. a = tolower(*(const unsigned char *)(src + i + 1));
  5899. b = tolower(*(const unsigned char *)(src + i + 2));
  5900. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5901. i += 2;
  5902. } else if (is_form_url_encoded && (src[i] == '+')) {
  5903. dst[j] = ' ';
  5904. } else {
  5905. dst[j] = src[i];
  5906. }
  5907. }
  5908. dst[j] = '\0'; /* Null-terminate the destination */
  5909. return (i >= src_len) ? j : -1;
  5910. }
  5911. int
  5912. mg_get_var(const char *data,
  5913. size_t data_len,
  5914. const char *name,
  5915. char *dst,
  5916. size_t dst_len)
  5917. {
  5918. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5919. }
  5920. int
  5921. mg_get_var2(const char *data,
  5922. size_t data_len,
  5923. const char *name,
  5924. char *dst,
  5925. size_t dst_len,
  5926. size_t occurrence)
  5927. {
  5928. const char *p, *e, *s;
  5929. size_t name_len;
  5930. int len;
  5931. if ((dst == NULL) || (dst_len == 0)) {
  5932. len = -2;
  5933. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5934. len = -1;
  5935. dst[0] = '\0';
  5936. } else {
  5937. name_len = strlen(name);
  5938. e = data + data_len;
  5939. len = -1;
  5940. dst[0] = '\0';
  5941. /* data is "var1=val1&var2=val2...". Find variable first */
  5942. for (p = data; p + name_len < e; p++) {
  5943. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5944. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5945. /* Point p to variable value */
  5946. p += name_len + 1;
  5947. /* Point s to the end of the value */
  5948. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5949. if (s == NULL) {
  5950. s = e;
  5951. }
  5952. DEBUG_ASSERT(s >= p);
  5953. if (s < p) {
  5954. return -3;
  5955. }
  5956. /* Decode variable into destination buffer */
  5957. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5958. /* Redirect error code from -1 to -2 (destination buffer too
  5959. * small). */
  5960. if (len == -1) {
  5961. len = -2;
  5962. }
  5963. break;
  5964. }
  5965. }
  5966. }
  5967. return len;
  5968. }
  5969. /* HCP24: some changes to compare hole var_name */
  5970. int
  5971. mg_get_cookie(const char *cookie_header,
  5972. const char *var_name,
  5973. char *dst,
  5974. size_t dst_size)
  5975. {
  5976. const char *s, *p, *end;
  5977. int name_len, len = -1;
  5978. if ((dst == NULL) || (dst_size == 0)) {
  5979. return -2;
  5980. }
  5981. dst[0] = '\0';
  5982. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5983. return -1;
  5984. }
  5985. name_len = (int)strlen(var_name);
  5986. end = s + strlen(s);
  5987. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5988. if (s[name_len] == '=') {
  5989. /* HCP24: now check is it a substring or a full cookie name */
  5990. if ((s == cookie_header) || (s[-1] == ' ')) {
  5991. s += name_len + 1;
  5992. if ((p = strchr(s, ' ')) == NULL) {
  5993. p = end;
  5994. }
  5995. if (p[-1] == ';') {
  5996. p--;
  5997. }
  5998. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5999. s++;
  6000. p--;
  6001. }
  6002. if ((size_t)(p - s) < dst_size) {
  6003. len = (int)(p - s);
  6004. mg_strlcpy(dst, s, (size_t)len + 1);
  6005. } else {
  6006. len = -3;
  6007. }
  6008. break;
  6009. }
  6010. }
  6011. }
  6012. return len;
  6013. }
  6014. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6015. static void
  6016. base64_encode(const unsigned char *src, int src_len, char *dst)
  6017. {
  6018. static const char *b64 =
  6019. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6020. int i, j, a, b, c;
  6021. for (i = j = 0; i < src_len; i += 3) {
  6022. a = src[i];
  6023. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6024. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6025. dst[j++] = b64[a >> 2];
  6026. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6027. if (i + 1 < src_len) {
  6028. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6029. }
  6030. if (i + 2 < src_len) {
  6031. dst[j++] = b64[c & 63];
  6032. }
  6033. }
  6034. while (j % 4 != 0) {
  6035. dst[j++] = '=';
  6036. }
  6037. dst[j++] = '\0';
  6038. }
  6039. #endif
  6040. #if defined(USE_LUA)
  6041. static unsigned char
  6042. b64reverse(char letter)
  6043. {
  6044. if ((letter >= 'A') && (letter <= 'Z')) {
  6045. return letter - 'A';
  6046. }
  6047. if ((letter >= 'a') && (letter <= 'z')) {
  6048. return letter - 'a' + 26;
  6049. }
  6050. if ((letter >= '0') && (letter <= '9')) {
  6051. return letter - '0' + 52;
  6052. }
  6053. if (letter == '+') {
  6054. return 62;
  6055. }
  6056. if (letter == '/') {
  6057. return 63;
  6058. }
  6059. if (letter == '=') {
  6060. return 255; /* normal end */
  6061. }
  6062. return 254; /* error */
  6063. }
  6064. static int
  6065. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6066. {
  6067. int i;
  6068. unsigned char a, b, c, d;
  6069. *dst_len = 0;
  6070. for (i = 0; i < src_len; i += 4) {
  6071. a = b64reverse(src[i]);
  6072. if (a >= 254) {
  6073. return i;
  6074. }
  6075. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6076. if (b >= 254) {
  6077. return i + 1;
  6078. }
  6079. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6080. if (c == 254) {
  6081. return i + 2;
  6082. }
  6083. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6084. if (d == 254) {
  6085. return i + 3;
  6086. }
  6087. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6088. if (c != 255) {
  6089. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6090. if (d != 255) {
  6091. dst[(*dst_len)++] = (c << 6) + d;
  6092. }
  6093. }
  6094. }
  6095. return -1;
  6096. }
  6097. #endif
  6098. static int
  6099. is_put_or_delete_method(const struct mg_connection *conn)
  6100. {
  6101. if (conn) {
  6102. const char *s = conn->request_info.request_method;
  6103. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6104. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6105. }
  6106. return 0;
  6107. }
  6108. #if !defined(NO_FILES)
  6109. static int
  6110. extention_matches_script(
  6111. struct mg_connection *conn, /* in: request (must be valid) */
  6112. const char *filename /* in: filename (must be valid) */
  6113. )
  6114. {
  6115. #if !defined(NO_CGI)
  6116. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6117. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6118. filename) > 0) {
  6119. return 1;
  6120. }
  6121. #endif
  6122. #if defined(USE_LUA)
  6123. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6124. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6125. filename) > 0) {
  6126. return 1;
  6127. }
  6128. #endif
  6129. #if defined(USE_DUKTAPE)
  6130. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6131. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6132. filename) > 0) {
  6133. return 1;
  6134. }
  6135. #endif
  6136. /* filename and conn could be unused, if all preocessor conditions
  6137. * are false (no script language supported). */
  6138. (void)filename;
  6139. (void)conn;
  6140. return 0;
  6141. }
  6142. /* For given directory path, substitute it to valid index file.
  6143. * Return 1 if index file has been found, 0 if not found.
  6144. * If the file is found, it's stats is returned in stp. */
  6145. static int
  6146. substitute_index_file(struct mg_connection *conn,
  6147. char *path,
  6148. size_t path_len,
  6149. struct mg_file_stat *filestat)
  6150. {
  6151. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6152. struct vec filename_vec;
  6153. size_t n = strlen(path);
  6154. int found = 0;
  6155. /* The 'path' given to us points to the directory. Remove all trailing
  6156. * directory separator characters from the end of the path, and
  6157. * then append single directory separator character. */
  6158. while ((n > 0) && (path[n - 1] == '/')) {
  6159. n--;
  6160. }
  6161. path[n] = '/';
  6162. /* Traverse index files list. For each entry, append it to the given
  6163. * path and see if the file exists. If it exists, break the loop */
  6164. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6165. /* Ignore too long entries that may overflow path buffer */
  6166. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6167. continue;
  6168. }
  6169. /* Prepare full path to the index file */
  6170. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6171. /* Does it exist? */
  6172. if (mg_stat(conn, path, filestat)) {
  6173. /* Yes it does, break the loop */
  6174. found = 1;
  6175. break;
  6176. }
  6177. }
  6178. /* If no index file exists, restore directory path */
  6179. if (!found) {
  6180. path[n] = '\0';
  6181. }
  6182. return found;
  6183. }
  6184. #endif
  6185. static void
  6186. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6187. char *filename, /* out: filename */
  6188. size_t filename_buf_len, /* in: size of filename buffer */
  6189. struct mg_file_stat *filestat, /* out: file status structure */
  6190. int *is_found, /* out: file found (directly) */
  6191. int *is_script_resource, /* out: handled by a script? */
  6192. int *is_websocket_request, /* out: websocket connetion? */
  6193. int *is_put_or_delete_request /* out: put/delete a file? */
  6194. )
  6195. {
  6196. char const *accept_encoding;
  6197. #if !defined(NO_FILES)
  6198. const char *uri = conn->request_info.local_uri;
  6199. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6200. const char *rewrite;
  6201. struct vec a, b;
  6202. ptrdiff_t match_len;
  6203. char gz_path[PATH_MAX];
  6204. int truncated;
  6205. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6206. char *tmp_str;
  6207. size_t tmp_str_len, sep_pos;
  6208. int allow_substitute_script_subresources;
  6209. #endif
  6210. #else
  6211. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6212. #endif
  6213. /* Step 1: Set all initially unknown outputs to zero */
  6214. memset(filestat, 0, sizeof(*filestat));
  6215. *filename = 0;
  6216. *is_found = 0;
  6217. *is_script_resource = 0;
  6218. /* Step 2: Check if the request attempts to modify the file system */
  6219. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6220. /* Step 3: Check if it is a websocket request, and modify the document
  6221. * root if required */
  6222. #if defined(USE_WEBSOCKET)
  6223. *is_websocket_request = is_websocket_protocol(conn);
  6224. #if !defined(NO_FILES)
  6225. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6226. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6227. }
  6228. #endif /* !NO_FILES */
  6229. #else /* USE_WEBSOCKET */
  6230. *is_websocket_request = 0;
  6231. #endif /* USE_WEBSOCKET */
  6232. /* Step 4: Check if gzip encoded response is allowed */
  6233. conn->accept_gzip = 0;
  6234. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6235. if (strstr(accept_encoding, "gzip") != NULL) {
  6236. conn->accept_gzip = 1;
  6237. }
  6238. }
  6239. #if !defined(NO_FILES)
  6240. /* Step 5: If there is no root directory, don't look for files. */
  6241. /* Note that root == NULL is a regular use case here. This occurs,
  6242. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6243. * config is not required. */
  6244. if (root == NULL) {
  6245. /* all file related outputs have already been set to 0, just return
  6246. */
  6247. return;
  6248. }
  6249. /* Step 6: Determine the local file path from the root path and the
  6250. * request uri. */
  6251. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6252. * part of the path one byte on the right. */
  6253. mg_snprintf(
  6254. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6255. if (truncated) {
  6256. goto interpret_cleanup;
  6257. }
  6258. /* Step 7: URI rewriting */
  6259. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6260. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6261. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6262. mg_snprintf(conn,
  6263. &truncated,
  6264. filename,
  6265. filename_buf_len - 1,
  6266. "%.*s%s",
  6267. (int)b.len,
  6268. b.ptr,
  6269. uri + match_len);
  6270. break;
  6271. }
  6272. }
  6273. if (truncated) {
  6274. goto interpret_cleanup;
  6275. }
  6276. /* Step 8: Check if the file exists at the server */
  6277. /* Local file path and name, corresponding to requested URI
  6278. * is now stored in "filename" variable. */
  6279. if (mg_stat(conn, filename, filestat)) {
  6280. int uri_len = (int)strlen(uri);
  6281. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6282. /* 8.1: File exists. */
  6283. *is_found = 1;
  6284. /* 8.2: Check if it is a script type. */
  6285. if (extention_matches_script(conn, filename)) {
  6286. /* The request addresses a CGI resource, Lua script or
  6287. * server-side javascript.
  6288. * The URI corresponds to the script itself (like
  6289. * /path/script.cgi), and there is no additional resource
  6290. * path (like /path/script.cgi/something).
  6291. * Requests that modify (replace or delete) a resource, like
  6292. * PUT and DELETE requests, should replace/delete the script
  6293. * file.
  6294. * Requests that read or write from/to a resource, like GET and
  6295. * POST requests, should call the script and return the
  6296. * generated response. */
  6297. *is_script_resource = (!*is_put_or_delete_request);
  6298. }
  6299. /* 8.3: If the request target is a directory, there could be
  6300. * a substitute file (index.html, index.cgi, ...). */
  6301. if (filestat->is_directory && is_uri_end_slash) {
  6302. /* Use a local copy here, since substitute_index_file will
  6303. * change the content of the file status */
  6304. struct mg_file_stat tmp_filestat;
  6305. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6306. if (substitute_index_file(
  6307. conn, filename, filename_buf_len, &tmp_filestat)) {
  6308. /* Substitute file found. Copy stat to the output, then
  6309. * check if the file is a script file */
  6310. *filestat = tmp_filestat;
  6311. if (extention_matches_script(conn, filename)) {
  6312. /* Substitute file is a script file */
  6313. *is_script_resource = 1;
  6314. } else {
  6315. /* Substitute file is a regular file */
  6316. *is_script_resource = 0;
  6317. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6318. }
  6319. }
  6320. /* If there is no substitute file, the server could return
  6321. * a directory listing in a later step */
  6322. }
  6323. return;
  6324. }
  6325. /* Step 9: Check for zipped files: */
  6326. /* If we can't find the actual file, look for the file
  6327. * with the same name but a .gz extension. If we find it,
  6328. * use that and set the gzipped flag in the file struct
  6329. * to indicate that the response need to have the content-
  6330. * encoding: gzip header.
  6331. * We can only do this if the browser declares support. */
  6332. if (conn->accept_gzip) {
  6333. mg_snprintf(
  6334. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6335. if (truncated) {
  6336. goto interpret_cleanup;
  6337. }
  6338. if (mg_stat(conn, gz_path, filestat)) {
  6339. if (filestat) {
  6340. filestat->is_gzipped = 1;
  6341. *is_found = 1;
  6342. }
  6343. /* Currently gz files can not be scripts. */
  6344. return;
  6345. }
  6346. }
  6347. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6348. /* Step 10: Script resources may handle sub-resources */
  6349. /* Support PATH_INFO for CGI scripts. */
  6350. tmp_str_len = strlen(filename);
  6351. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6352. if (!tmp_str) {
  6353. /* Out of memory */
  6354. goto interpret_cleanup;
  6355. }
  6356. memcpy(tmp_str, filename, tmp_str_len + 1);
  6357. /* Check config, if index scripts may have sub-resources */
  6358. allow_substitute_script_subresources =
  6359. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6360. "yes");
  6361. sep_pos = tmp_str_len;
  6362. while (sep_pos > 0) {
  6363. sep_pos--;
  6364. if (tmp_str[sep_pos] == '/') {
  6365. int is_script = 0, does_exist = 0;
  6366. tmp_str[sep_pos] = 0;
  6367. if (tmp_str[0]) {
  6368. is_script = extention_matches_script(conn, tmp_str);
  6369. does_exist = mg_stat(conn, tmp_str, filestat);
  6370. }
  6371. if (does_exist && is_script) {
  6372. filename[sep_pos] = 0;
  6373. memmove(filename + sep_pos + 2,
  6374. filename + sep_pos + 1,
  6375. strlen(filename + sep_pos + 1) + 1);
  6376. conn->path_info = filename + sep_pos + 1;
  6377. filename[sep_pos + 1] = '/';
  6378. *is_script_resource = 1;
  6379. *is_found = 1;
  6380. break;
  6381. }
  6382. if (allow_substitute_script_subresources) {
  6383. if (substitute_index_file(
  6384. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6385. /* some intermediate directory has an index file */
  6386. if (extention_matches_script(conn, tmp_str)) {
  6387. char *tmp_str2;
  6388. DEBUG_TRACE("Substitute script %s serving path %s",
  6389. tmp_str,
  6390. filename);
  6391. /* this index file is a script */
  6392. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6393. conn->phys_ctx);
  6394. mg_snprintf(conn,
  6395. &truncated,
  6396. filename,
  6397. filename_buf_len,
  6398. "%s//%s",
  6399. tmp_str,
  6400. tmp_str2);
  6401. mg_free(tmp_str2);
  6402. if (truncated) {
  6403. mg_free(tmp_str);
  6404. goto interpret_cleanup;
  6405. }
  6406. sep_pos = strlen(tmp_str);
  6407. filename[sep_pos] = 0;
  6408. conn->path_info = filename + sep_pos + 1;
  6409. *is_script_resource = 1;
  6410. *is_found = 1;
  6411. break;
  6412. } else {
  6413. DEBUG_TRACE("Substitute file %s serving path %s",
  6414. tmp_str,
  6415. filename);
  6416. /* non-script files will not have sub-resources */
  6417. filename[sep_pos] = 0;
  6418. conn->path_info = 0;
  6419. *is_script_resource = 0;
  6420. *is_found = 0;
  6421. break;
  6422. }
  6423. }
  6424. }
  6425. tmp_str[sep_pos] = '/';
  6426. }
  6427. }
  6428. mg_free(tmp_str);
  6429. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6430. #endif /* !defined(NO_FILES) */
  6431. return;
  6432. #if !defined(NO_FILES)
  6433. /* Reset all outputs */
  6434. interpret_cleanup:
  6435. memset(filestat, 0, sizeof(*filestat));
  6436. *filename = 0;
  6437. *is_found = 0;
  6438. *is_script_resource = 0;
  6439. *is_websocket_request = 0;
  6440. *is_put_or_delete_request = 0;
  6441. #endif /* !defined(NO_FILES) */
  6442. }
  6443. /* Check whether full request is buffered. Return:
  6444. * -1 if request or response is malformed
  6445. * 0 if request or response is not yet fully buffered
  6446. * >0 actual request length, including last \r\n\r\n */
  6447. static int
  6448. get_http_header_len(const char *buf, int buflen)
  6449. {
  6450. int i;
  6451. for (i = 0; i < buflen; i++) {
  6452. /* Do an unsigned comparison in some conditions below */
  6453. const unsigned char c = ((const unsigned char *)buf)[i];
  6454. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6455. && !isprint(c)) {
  6456. /* abort scan as soon as one malformed character is found */
  6457. return -1;
  6458. }
  6459. if (i < buflen - 1) {
  6460. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6461. /* Two newline, no carriage return - not standard compliant,
  6462. * but
  6463. * it
  6464. * should be accepted */
  6465. return i + 2;
  6466. }
  6467. }
  6468. if (i < buflen - 3) {
  6469. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6470. && (buf[i + 3] == '\n')) {
  6471. /* Two \r\n - standard compliant */
  6472. return i + 4;
  6473. }
  6474. }
  6475. }
  6476. return 0;
  6477. }
  6478. #if !defined(NO_CACHING)
  6479. /* Convert month to the month number. Return -1 on error, or month number */
  6480. static int
  6481. get_month_index(const char *s)
  6482. {
  6483. size_t i;
  6484. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6485. if (!strcmp(s, month_names[i])) {
  6486. return (int)i;
  6487. }
  6488. }
  6489. return -1;
  6490. }
  6491. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6492. static time_t
  6493. parse_date_string(const char *datetime)
  6494. {
  6495. char month_str[32] = {0};
  6496. int second, minute, hour, day, month, year;
  6497. time_t result = (time_t)0;
  6498. struct tm tm;
  6499. if ((sscanf(datetime,
  6500. "%d/%3s/%d %d:%d:%d",
  6501. &day,
  6502. month_str,
  6503. &year,
  6504. &hour,
  6505. &minute,
  6506. &second) == 6) || (sscanf(datetime,
  6507. "%d %3s %d %d:%d:%d",
  6508. &day,
  6509. month_str,
  6510. &year,
  6511. &hour,
  6512. &minute,
  6513. &second) == 6)
  6514. || (sscanf(datetime,
  6515. "%*3s, %d %3s %d %d:%d:%d",
  6516. &day,
  6517. month_str,
  6518. &year,
  6519. &hour,
  6520. &minute,
  6521. &second) == 6) || (sscanf(datetime,
  6522. "%d-%3s-%d %d:%d:%d",
  6523. &day,
  6524. month_str,
  6525. &year,
  6526. &hour,
  6527. &minute,
  6528. &second) == 6)) {
  6529. month = get_month_index(month_str);
  6530. if ((month >= 0) && (year >= 1970)) {
  6531. memset(&tm, 0, sizeof(tm));
  6532. tm.tm_year = year - 1900;
  6533. tm.tm_mon = month;
  6534. tm.tm_mday = day;
  6535. tm.tm_hour = hour;
  6536. tm.tm_min = minute;
  6537. tm.tm_sec = second;
  6538. result = timegm(&tm);
  6539. }
  6540. }
  6541. return result;
  6542. }
  6543. #endif /* !NO_CACHING */
  6544. /* Protect against directory disclosure attack by removing '..',
  6545. * excessive '/' and '\' characters */
  6546. static void
  6547. remove_double_dots_and_double_slashes(char *s)
  6548. {
  6549. char *p = s;
  6550. while ((s[0] == '.') && (s[1] == '.')) {
  6551. s++;
  6552. }
  6553. while (*s != '\0') {
  6554. *p++ = *s++;
  6555. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6556. /* Skip all following slashes, backslashes and double-dots */
  6557. while (s[0] != '\0') {
  6558. if ((s[0] == '/') || (s[0] == '\\')) {
  6559. s++;
  6560. } else if ((s[0] == '.') && (s[1] == '.')) {
  6561. s += 2;
  6562. } else {
  6563. break;
  6564. }
  6565. }
  6566. }
  6567. }
  6568. *p = '\0';
  6569. }
  6570. static const struct {
  6571. const char *extension;
  6572. size_t ext_len;
  6573. const char *mime_type;
  6574. } builtin_mime_types[] = {
  6575. /* IANA registered MIME types
  6576. * (http://www.iana.org/assignments/media-types)
  6577. * application types */
  6578. {".doc", 4, "application/msword"},
  6579. {".eps", 4, "application/postscript"},
  6580. {".exe", 4, "application/octet-stream"},
  6581. {".js", 3, "application/javascript"},
  6582. {".json", 5, "application/json"},
  6583. {".pdf", 4, "application/pdf"},
  6584. {".ps", 3, "application/postscript"},
  6585. {".rtf", 4, "application/rtf"},
  6586. {".xhtml", 6, "application/xhtml+xml"},
  6587. {".xsl", 4, "application/xml"},
  6588. {".xslt", 5, "application/xml"},
  6589. /* fonts */
  6590. {".ttf", 4, "application/font-sfnt"},
  6591. {".cff", 4, "application/font-sfnt"},
  6592. {".otf", 4, "application/font-sfnt"},
  6593. {".aat", 4, "application/font-sfnt"},
  6594. {".sil", 4, "application/font-sfnt"},
  6595. {".pfr", 4, "application/font-tdpfr"},
  6596. {".woff", 5, "application/font-woff"},
  6597. /* audio */
  6598. {".mp3", 4, "audio/mpeg"},
  6599. {".oga", 4, "audio/ogg"},
  6600. {".ogg", 4, "audio/ogg"},
  6601. /* image */
  6602. {".gif", 4, "image/gif"},
  6603. {".ief", 4, "image/ief"},
  6604. {".jpeg", 5, "image/jpeg"},
  6605. {".jpg", 4, "image/jpeg"},
  6606. {".jpm", 4, "image/jpm"},
  6607. {".jpx", 4, "image/jpx"},
  6608. {".png", 4, "image/png"},
  6609. {".svg", 4, "image/svg+xml"},
  6610. {".tif", 4, "image/tiff"},
  6611. {".tiff", 5, "image/tiff"},
  6612. /* model */
  6613. {".wrl", 4, "model/vrml"},
  6614. /* text */
  6615. {".css", 4, "text/css"},
  6616. {".csv", 4, "text/csv"},
  6617. {".htm", 4, "text/html"},
  6618. {".html", 5, "text/html"},
  6619. {".sgm", 4, "text/sgml"},
  6620. {".shtm", 5, "text/html"},
  6621. {".shtml", 6, "text/html"},
  6622. {".txt", 4, "text/plain"},
  6623. {".xml", 4, "text/xml"},
  6624. /* video */
  6625. {".mov", 4, "video/quicktime"},
  6626. {".mp4", 4, "video/mp4"},
  6627. {".mpeg", 5, "video/mpeg"},
  6628. {".mpg", 4, "video/mpeg"},
  6629. {".ogv", 4, "video/ogg"},
  6630. {".qt", 3, "video/quicktime"},
  6631. /* not registered types
  6632. * (http://reference.sitepoint.com/html/mime-types-full,
  6633. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6634. {".arj", 4, "application/x-arj-compressed"},
  6635. {".gz", 3, "application/x-gunzip"},
  6636. {".rar", 4, "application/x-arj-compressed"},
  6637. {".swf", 4, "application/x-shockwave-flash"},
  6638. {".tar", 4, "application/x-tar"},
  6639. {".tgz", 4, "application/x-tar-gz"},
  6640. {".torrent", 8, "application/x-bittorrent"},
  6641. {".ppt", 4, "application/x-mspowerpoint"},
  6642. {".xls", 4, "application/x-msexcel"},
  6643. {".zip", 4, "application/x-zip-compressed"},
  6644. {".aac",
  6645. 4,
  6646. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6647. {".aif", 4, "audio/x-aif"},
  6648. {".m3u", 4, "audio/x-mpegurl"},
  6649. {".mid", 4, "audio/x-midi"},
  6650. {".ra", 3, "audio/x-pn-realaudio"},
  6651. {".ram", 4, "audio/x-pn-realaudio"},
  6652. {".wav", 4, "audio/x-wav"},
  6653. {".bmp", 4, "image/bmp"},
  6654. {".ico", 4, "image/x-icon"},
  6655. {".pct", 4, "image/x-pct"},
  6656. {".pict", 5, "image/pict"},
  6657. {".rgb", 4, "image/x-rgb"},
  6658. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6659. {".asf", 4, "video/x-ms-asf"},
  6660. {".avi", 4, "video/x-msvideo"},
  6661. {".m4v", 4, "video/x-m4v"},
  6662. {NULL, 0, NULL}};
  6663. const char *
  6664. mg_get_builtin_mime_type(const char *path)
  6665. {
  6666. const char *ext;
  6667. size_t i, path_len;
  6668. path_len = strlen(path);
  6669. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6670. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6671. if ((path_len > builtin_mime_types[i].ext_len)
  6672. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6673. return builtin_mime_types[i].mime_type;
  6674. }
  6675. }
  6676. return "text/plain";
  6677. }
  6678. /* Look at the "path" extension and figure what mime type it has.
  6679. * Store mime type in the vector. */
  6680. static void
  6681. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6682. {
  6683. struct vec ext_vec, mime_vec;
  6684. const char *list, *ext;
  6685. size_t path_len;
  6686. path_len = strlen(path);
  6687. if ((conn == NULL) || (vec == NULL)) {
  6688. if (vec != NULL) {
  6689. memset(vec, '\0', sizeof(struct vec));
  6690. }
  6691. return;
  6692. }
  6693. /* Scan user-defined mime types first, in case user wants to
  6694. * override default mime types. */
  6695. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6696. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6697. /* ext now points to the path suffix */
  6698. ext = path + path_len - ext_vec.len;
  6699. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6700. *vec = mime_vec;
  6701. return;
  6702. }
  6703. }
  6704. vec->ptr = mg_get_builtin_mime_type(path);
  6705. vec->len = strlen(vec->ptr);
  6706. }
  6707. /* Stringify binary data. Output buffer must be twice as big as input,
  6708. * because each byte takes 2 bytes in string representation */
  6709. static void
  6710. bin2str(char *to, const unsigned char *p, size_t len)
  6711. {
  6712. static const char *hex = "0123456789abcdef";
  6713. for (; len--; p++) {
  6714. *to++ = hex[p[0] >> 4];
  6715. *to++ = hex[p[0] & 0x0f];
  6716. }
  6717. *to = '\0';
  6718. }
  6719. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6720. */
  6721. char *
  6722. mg_md5(char buf[33], ...)
  6723. {
  6724. md5_byte_t hash[16];
  6725. const char *p;
  6726. va_list ap;
  6727. md5_state_t ctx;
  6728. md5_init(&ctx);
  6729. va_start(ap, buf);
  6730. while ((p = va_arg(ap, const char *)) != NULL) {
  6731. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6732. }
  6733. va_end(ap);
  6734. md5_finish(&ctx, hash);
  6735. bin2str(buf, hash, sizeof(hash));
  6736. return buf;
  6737. }
  6738. /* Check the user's password, return 1 if OK */
  6739. static int
  6740. check_password(const char *method,
  6741. const char *ha1,
  6742. const char *uri,
  6743. const char *nonce,
  6744. const char *nc,
  6745. const char *cnonce,
  6746. const char *qop,
  6747. const char *response)
  6748. {
  6749. char ha2[32 + 1], expected_response[32 + 1];
  6750. /* Some of the parameters may be NULL */
  6751. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6752. || (qop == NULL) || (response == NULL)) {
  6753. return 0;
  6754. }
  6755. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6756. if (strlen(response) != 32) {
  6757. return 0;
  6758. }
  6759. mg_md5(ha2, method, ":", uri, NULL);
  6760. mg_md5(expected_response,
  6761. ha1,
  6762. ":",
  6763. nonce,
  6764. ":",
  6765. nc,
  6766. ":",
  6767. cnonce,
  6768. ":",
  6769. qop,
  6770. ":",
  6771. ha2,
  6772. NULL);
  6773. return mg_strcasecmp(response, expected_response) == 0;
  6774. }
  6775. /* Use the global passwords file, if specified by auth_gpass option,
  6776. * or search for .htpasswd in the requested directory. */
  6777. static void
  6778. open_auth_file(struct mg_connection *conn,
  6779. const char *path,
  6780. struct mg_file *filep)
  6781. {
  6782. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6783. char name[PATH_MAX];
  6784. const char *p, *e,
  6785. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6786. int truncated;
  6787. if (gpass != NULL) {
  6788. /* Use global passwords file */
  6789. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6790. #if defined(DEBUG)
  6791. /* Use mg_cry_internal here, since gpass has been configured. */
  6792. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6793. #endif
  6794. }
  6795. /* Important: using local struct mg_file to test path for
  6796. * is_directory flag. If filep is used, mg_stat() makes it
  6797. * appear as if auth file was opened.
  6798. * TODO(mid): Check if this is still required after rewriting
  6799. * mg_stat */
  6800. } else if (mg_stat(conn, path, &filep->stat)
  6801. && filep->stat.is_directory) {
  6802. mg_snprintf(conn,
  6803. &truncated,
  6804. name,
  6805. sizeof(name),
  6806. "%s/%s",
  6807. path,
  6808. PASSWORDS_FILE_NAME);
  6809. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6810. #if defined(DEBUG)
  6811. /* Don't use mg_cry_internal here, but only a trace, since this
  6812. * is
  6813. * a typical case. It will occur for every directory
  6814. * without a password file. */
  6815. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6816. #endif
  6817. }
  6818. } else {
  6819. /* Try to find .htpasswd in requested directory. */
  6820. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6821. if (e[0] == '/') {
  6822. break;
  6823. }
  6824. }
  6825. mg_snprintf(conn,
  6826. &truncated,
  6827. name,
  6828. sizeof(name),
  6829. "%.*s/%s",
  6830. (int)(e - p),
  6831. p,
  6832. PASSWORDS_FILE_NAME);
  6833. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6834. #if defined(DEBUG)
  6835. /* Don't use mg_cry_internal here, but only a trace, since this
  6836. * is
  6837. * a typical case. It will occur for every directory
  6838. * without a password file. */
  6839. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6840. #endif
  6841. }
  6842. }
  6843. }
  6844. }
  6845. /* Parsed Authorization header */
  6846. struct ah {
  6847. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6848. };
  6849. /* Return 1 on success. Always initializes the ah structure. */
  6850. static int
  6851. parse_auth_header(struct mg_connection *conn,
  6852. char *buf,
  6853. size_t buf_size,
  6854. struct ah *ah)
  6855. {
  6856. char *name, *value, *s;
  6857. const char *auth_header;
  6858. uint64_t nonce;
  6859. if (!ah || !conn) {
  6860. return 0;
  6861. }
  6862. (void)memset(ah, 0, sizeof(*ah));
  6863. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6864. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6865. return 0;
  6866. }
  6867. /* Make modifiable copy of the auth header */
  6868. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6869. s = buf;
  6870. /* Parse authorization header */
  6871. for (;;) {
  6872. /* Gobble initial spaces */
  6873. while (isspace(*(unsigned char *)s)) {
  6874. s++;
  6875. }
  6876. name = skip_quoted(&s, "=", " ", 0);
  6877. /* Value is either quote-delimited, or ends at first comma or space.
  6878. */
  6879. if (s[0] == '\"') {
  6880. s++;
  6881. value = skip_quoted(&s, "\"", " ", '\\');
  6882. if (s[0] == ',') {
  6883. s++;
  6884. }
  6885. } else {
  6886. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6887. * spaces */
  6888. }
  6889. if (*name == '\0') {
  6890. break;
  6891. }
  6892. if (!strcmp(name, "username")) {
  6893. ah->user = value;
  6894. } else if (!strcmp(name, "cnonce")) {
  6895. ah->cnonce = value;
  6896. } else if (!strcmp(name, "response")) {
  6897. ah->response = value;
  6898. } else if (!strcmp(name, "uri")) {
  6899. ah->uri = value;
  6900. } else if (!strcmp(name, "qop")) {
  6901. ah->qop = value;
  6902. } else if (!strcmp(name, "nc")) {
  6903. ah->nc = value;
  6904. } else if (!strcmp(name, "nonce")) {
  6905. ah->nonce = value;
  6906. }
  6907. }
  6908. #if !defined(NO_NONCE_CHECK)
  6909. /* Read the nonce from the response. */
  6910. if (ah->nonce == NULL) {
  6911. return 0;
  6912. }
  6913. s = NULL;
  6914. nonce = strtoull(ah->nonce, &s, 10);
  6915. if ((s == NULL) || (*s != 0)) {
  6916. return 0;
  6917. }
  6918. /* Convert the nonce from the client to a number. */
  6919. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6920. /* The converted number corresponds to the time the nounce has been
  6921. * created. This should not be earlier than the server start. */
  6922. /* Server side nonce check is valuable in all situations but one:
  6923. * if the server restarts frequently, but the client should not see
  6924. * that, so the server should accept nonces from previous starts. */
  6925. /* However, the reasonable default is to not accept a nonce from a
  6926. * previous start, so if anyone changed the access rights between
  6927. * two restarts, a new login is required. */
  6928. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6929. /* nonce is from a previous start of the server and no longer valid
  6930. * (replay attack?) */
  6931. return 0;
  6932. }
  6933. /* Check if the nonce is too high, so it has not (yet) been used by the
  6934. * server. */
  6935. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6936. + conn->dom_ctx->nonce_count)) {
  6937. return 0;
  6938. }
  6939. #else
  6940. (void)nonce;
  6941. #endif
  6942. /* CGI needs it as REMOTE_USER */
  6943. if (ah->user != NULL) {
  6944. conn->request_info.remote_user =
  6945. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6946. } else {
  6947. return 0;
  6948. }
  6949. return 1;
  6950. }
  6951. static const char *
  6952. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6953. {
  6954. #if defined(MG_USE_OPEN_FILE)
  6955. const char *eof;
  6956. size_t len;
  6957. const char *memend;
  6958. #else
  6959. (void)p; /* parameter is unused */
  6960. #endif
  6961. if (!filep) {
  6962. return NULL;
  6963. }
  6964. #if defined(MG_USE_OPEN_FILE)
  6965. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6966. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6967. /* Search for \n from p till the end of stream */
  6968. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6969. if (eof != NULL) {
  6970. eof += 1; /* Include \n */
  6971. } else {
  6972. eof = memend; /* Copy remaining data */
  6973. }
  6974. len =
  6975. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6976. memcpy(buf, *p, len);
  6977. buf[len] = '\0';
  6978. *p += len;
  6979. return len ? eof : NULL;
  6980. } else /* filep->access.fp block below */
  6981. #endif
  6982. if (filep->access.fp != NULL) {
  6983. return fgets(buf, (int)size, filep->access.fp);
  6984. } else {
  6985. return NULL;
  6986. }
  6987. }
  6988. /* Define the initial recursion depth for procesesing htpasswd files that
  6989. * include other htpasswd
  6990. * (or even the same) files. It is not difficult to provide a file or files
  6991. * s.t. they force civetweb
  6992. * to infinitely recurse and then crash.
  6993. */
  6994. #define INITIAL_DEPTH 9
  6995. #if INITIAL_DEPTH <= 0
  6996. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6997. #endif
  6998. struct read_auth_file_struct {
  6999. struct mg_connection *conn;
  7000. struct ah ah;
  7001. const char *domain;
  7002. char buf[256 + 256 + 40];
  7003. const char *f_user;
  7004. const char *f_domain;
  7005. const char *f_ha1;
  7006. };
  7007. static int
  7008. read_auth_file(struct mg_file *filep,
  7009. struct read_auth_file_struct *workdata,
  7010. int depth)
  7011. {
  7012. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7013. int is_authorized = 0;
  7014. struct mg_file fp;
  7015. size_t l;
  7016. if (!filep || !workdata || (0 == depth)) {
  7017. return 0;
  7018. }
  7019. /* Loop over passwords file */
  7020. #if defined(MG_USE_OPEN_FILE)
  7021. p = (char *)filep->access.membuf;
  7022. #endif
  7023. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7024. l = strlen(workdata->buf);
  7025. while (l > 0) {
  7026. if (isspace(workdata->buf[l - 1])
  7027. || iscntrl(workdata->buf[l - 1])) {
  7028. l--;
  7029. workdata->buf[l] = 0;
  7030. } else
  7031. break;
  7032. }
  7033. if (l < 1) {
  7034. continue;
  7035. }
  7036. workdata->f_user = workdata->buf;
  7037. if (workdata->f_user[0] == ':') {
  7038. /* user names may not contain a ':' and may not be empty,
  7039. * so lines starting with ':' may be used for a special purpose
  7040. */
  7041. if (workdata->f_user[1] == '#') {
  7042. /* :# is a comment */
  7043. continue;
  7044. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7045. if (mg_fopen(workdata->conn,
  7046. workdata->f_user + 9,
  7047. MG_FOPEN_MODE_READ,
  7048. &fp)) {
  7049. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7050. (void)mg_fclose(
  7051. &fp.access); /* ignore error on read only file */
  7052. /* No need to continue processing files once we have a
  7053. * match, since nothing will reset it back
  7054. * to 0.
  7055. */
  7056. if (is_authorized) {
  7057. return is_authorized;
  7058. }
  7059. } else {
  7060. mg_cry_internal(workdata->conn,
  7061. "%s: cannot open authorization file: %s",
  7062. __func__,
  7063. workdata->buf);
  7064. }
  7065. continue;
  7066. }
  7067. /* everything is invalid for the moment (might change in the
  7068. * future) */
  7069. mg_cry_internal(workdata->conn,
  7070. "%s: syntax error in authorization file: %s",
  7071. __func__,
  7072. workdata->buf);
  7073. continue;
  7074. }
  7075. workdata->f_domain = strchr(workdata->f_user, ':');
  7076. if (workdata->f_domain == NULL) {
  7077. mg_cry_internal(workdata->conn,
  7078. "%s: syntax error in authorization file: %s",
  7079. __func__,
  7080. workdata->buf);
  7081. continue;
  7082. }
  7083. *(char *)(workdata->f_domain) = 0;
  7084. (workdata->f_domain)++;
  7085. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7086. if (workdata->f_ha1 == NULL) {
  7087. mg_cry_internal(workdata->conn,
  7088. "%s: syntax error in authorization file: %s",
  7089. __func__,
  7090. workdata->buf);
  7091. continue;
  7092. }
  7093. *(char *)(workdata->f_ha1) = 0;
  7094. (workdata->f_ha1)++;
  7095. if (!strcmp(workdata->ah.user, workdata->f_user)
  7096. && !strcmp(workdata->domain, workdata->f_domain)) {
  7097. return check_password(workdata->conn->request_info.request_method,
  7098. workdata->f_ha1,
  7099. workdata->ah.uri,
  7100. workdata->ah.nonce,
  7101. workdata->ah.nc,
  7102. workdata->ah.cnonce,
  7103. workdata->ah.qop,
  7104. workdata->ah.response);
  7105. }
  7106. }
  7107. return is_authorized;
  7108. }
  7109. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7110. static int
  7111. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7112. {
  7113. struct read_auth_file_struct workdata;
  7114. char buf[MG_BUF_LEN];
  7115. if (!conn || !conn->dom_ctx) {
  7116. return 0;
  7117. }
  7118. memset(&workdata, 0, sizeof(workdata));
  7119. workdata.conn = conn;
  7120. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7121. return 0;
  7122. }
  7123. if (realm) {
  7124. workdata.domain = realm;
  7125. } else {
  7126. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7127. }
  7128. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7129. }
  7130. /* Public function to check http digest authentication header */
  7131. int
  7132. mg_check_digest_access_authentication(struct mg_connection *conn,
  7133. const char *realm,
  7134. const char *filename)
  7135. {
  7136. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7137. int auth;
  7138. if (!conn || !filename) {
  7139. return -1;
  7140. }
  7141. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7142. return -2;
  7143. }
  7144. auth = authorize(conn, &file, realm);
  7145. mg_fclose(&file.access);
  7146. return auth;
  7147. }
  7148. /* Return 1 if request is authorised, 0 otherwise. */
  7149. static int
  7150. check_authorization(struct mg_connection *conn, const char *path)
  7151. {
  7152. char fname[PATH_MAX];
  7153. struct vec uri_vec, filename_vec;
  7154. const char *list;
  7155. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7156. int authorized = 1, truncated;
  7157. if (!conn || !conn->dom_ctx) {
  7158. return 0;
  7159. }
  7160. list = conn->dom_ctx->config[PROTECT_URI];
  7161. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7162. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7163. mg_snprintf(conn,
  7164. &truncated,
  7165. fname,
  7166. sizeof(fname),
  7167. "%.*s",
  7168. (int)filename_vec.len,
  7169. filename_vec.ptr);
  7170. if (truncated
  7171. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7172. mg_cry_internal(conn,
  7173. "%s: cannot open %s: %s",
  7174. __func__,
  7175. fname,
  7176. strerror(errno));
  7177. }
  7178. break;
  7179. }
  7180. }
  7181. if (!is_file_opened(&file.access)) {
  7182. open_auth_file(conn, path, &file);
  7183. }
  7184. if (is_file_opened(&file.access)) {
  7185. authorized = authorize(conn, &file, NULL);
  7186. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7187. }
  7188. return authorized;
  7189. }
  7190. /* Internal function. Assumes conn is valid */
  7191. static void
  7192. send_authorization_request(struct mg_connection *conn, const char *realm)
  7193. {
  7194. char date[64];
  7195. time_t curtime = time(NULL);
  7196. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7197. if (!realm) {
  7198. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7199. }
  7200. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7201. nonce += conn->dom_ctx->nonce_count;
  7202. ++conn->dom_ctx->nonce_count;
  7203. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7204. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7205. conn->status_code = 401;
  7206. conn->must_close = 1;
  7207. gmt_time_string(date, sizeof(date), &curtime);
  7208. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7209. send_no_cache_header(conn);
  7210. send_additional_header(conn);
  7211. mg_printf(conn,
  7212. "Date: %s\r\n"
  7213. "Connection: %s\r\n"
  7214. "Content-Length: 0\r\n"
  7215. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7216. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7217. date,
  7218. suggest_connection_header(conn),
  7219. realm,
  7220. nonce);
  7221. }
  7222. /* Interface function. Parameters are provided by the user, so do
  7223. * at least some basic checks.
  7224. */
  7225. int
  7226. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7227. const char *realm)
  7228. {
  7229. if (conn && conn->dom_ctx) {
  7230. send_authorization_request(conn, realm);
  7231. return 0;
  7232. }
  7233. return -1;
  7234. }
  7235. #if !defined(NO_FILES)
  7236. static int
  7237. is_authorized_for_put(struct mg_connection *conn)
  7238. {
  7239. if (conn) {
  7240. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7241. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7242. int ret = 0;
  7243. if (passfile != NULL
  7244. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7245. ret = authorize(conn, &file, NULL);
  7246. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7247. }
  7248. return ret;
  7249. }
  7250. return 0;
  7251. }
  7252. #endif
  7253. int
  7254. mg_modify_passwords_file(const char *fname,
  7255. const char *domain,
  7256. const char *user,
  7257. const char *pass)
  7258. {
  7259. int found, i;
  7260. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7261. FILE *fp, *fp2;
  7262. found = 0;
  7263. fp = fp2 = NULL;
  7264. /* Regard empty password as no password - remove user record. */
  7265. if ((pass != NULL) && (pass[0] == '\0')) {
  7266. pass = NULL;
  7267. }
  7268. /* Other arguments must not be empty */
  7269. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7270. return 0;
  7271. }
  7272. /* Using the given file format, user name and domain must not contain
  7273. * ':'
  7274. */
  7275. if (strchr(user, ':') != NULL) {
  7276. return 0;
  7277. }
  7278. if (strchr(domain, ':') != NULL) {
  7279. return 0;
  7280. }
  7281. /* Do not allow control characters like newline in user name and domain.
  7282. * Do not allow excessively long names either. */
  7283. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7284. if (iscntrl(user[i])) {
  7285. return 0;
  7286. }
  7287. }
  7288. if (user[i]) {
  7289. return 0;
  7290. }
  7291. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7292. if (iscntrl(domain[i])) {
  7293. return 0;
  7294. }
  7295. }
  7296. if (domain[i]) {
  7297. return 0;
  7298. }
  7299. /* The maximum length of the path to the password file is limited */
  7300. if ((strlen(fname) + 4) >= PATH_MAX) {
  7301. return 0;
  7302. }
  7303. /* Create a temporary file name. Length has been checked before. */
  7304. strcpy(tmp, fname);
  7305. strcat(tmp, ".tmp");
  7306. /* Create the file if does not exist */
  7307. /* Use of fopen here is OK, since fname is only ASCII */
  7308. if ((fp = fopen(fname, "a+")) != NULL) {
  7309. (void)fclose(fp);
  7310. }
  7311. /* Open the given file and temporary file */
  7312. if ((fp = fopen(fname, "r")) == NULL) {
  7313. return 0;
  7314. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7315. fclose(fp);
  7316. return 0;
  7317. }
  7318. /* Copy the stuff to temporary file */
  7319. while (fgets(line, sizeof(line), fp) != NULL) {
  7320. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7321. continue;
  7322. }
  7323. u[255] = 0;
  7324. d[255] = 0;
  7325. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7326. found++;
  7327. if (pass != NULL) {
  7328. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7329. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7330. }
  7331. } else {
  7332. fprintf(fp2, "%s", line);
  7333. }
  7334. }
  7335. /* If new user, just add it */
  7336. if (!found && (pass != NULL)) {
  7337. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7338. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7339. }
  7340. /* Close files */
  7341. fclose(fp);
  7342. fclose(fp2);
  7343. /* Put the temp file in place of real file */
  7344. IGNORE_UNUSED_RESULT(remove(fname));
  7345. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7346. return 1;
  7347. }
  7348. static int
  7349. is_valid_port(unsigned long port)
  7350. {
  7351. return (port <= 0xffff);
  7352. }
  7353. static int
  7354. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7355. {
  7356. struct addrinfo hints, *res, *ressave;
  7357. int func_ret = 0;
  7358. int gai_ret;
  7359. memset(&hints, 0, sizeof(struct addrinfo));
  7360. hints.ai_family = af;
  7361. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7362. if (gai_ret != 0) {
  7363. /* gai_strerror could be used to convert gai_ret to a string */
  7364. /* POSIX return values: see
  7365. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7366. */
  7367. /* Windows return values: see
  7368. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7369. */
  7370. return 0;
  7371. }
  7372. ressave = res;
  7373. while (res) {
  7374. if (dstlen >= (size_t)res->ai_addrlen) {
  7375. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7376. func_ret = 1;
  7377. }
  7378. res = res->ai_next;
  7379. }
  7380. freeaddrinfo(ressave);
  7381. return func_ret;
  7382. }
  7383. static int
  7384. connect_socket(struct mg_context *ctx /* may be NULL */,
  7385. const char *host,
  7386. int port,
  7387. int use_ssl,
  7388. char *ebuf,
  7389. size_t ebuf_len,
  7390. SOCKET *sock /* output: socket, must not be NULL */,
  7391. union usa *sa /* output: socket address, must not be NULL */
  7392. )
  7393. {
  7394. int ip_ver = 0;
  7395. int conn_ret = -1;
  7396. *sock = INVALID_SOCKET;
  7397. memset(sa, 0, sizeof(*sa));
  7398. if (ebuf_len > 0) {
  7399. *ebuf = 0;
  7400. }
  7401. if (host == NULL) {
  7402. mg_snprintf(NULL,
  7403. NULL, /* No truncation check for ebuf */
  7404. ebuf,
  7405. ebuf_len,
  7406. "%s",
  7407. "NULL host");
  7408. return 0;
  7409. }
  7410. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7411. mg_snprintf(NULL,
  7412. NULL, /* No truncation check for ebuf */
  7413. ebuf,
  7414. ebuf_len,
  7415. "%s",
  7416. "invalid port");
  7417. return 0;
  7418. }
  7419. #if !defined(NO_SSL)
  7420. #if !defined(NO_SSL_DL)
  7421. #if defined(OPENSSL_API_1_1)
  7422. if (use_ssl && (TLS_client_method == NULL)) {
  7423. mg_snprintf(NULL,
  7424. NULL, /* No truncation check for ebuf */
  7425. ebuf,
  7426. ebuf_len,
  7427. "%s",
  7428. "SSL is not initialized");
  7429. return 0;
  7430. }
  7431. #else
  7432. if (use_ssl && (SSLv23_client_method == NULL)) {
  7433. mg_snprintf(NULL,
  7434. NULL, /* No truncation check for ebuf */
  7435. ebuf,
  7436. ebuf_len,
  7437. "%s",
  7438. "SSL is not initialized");
  7439. return 0;
  7440. }
  7441. #endif /* OPENSSL_API_1_1 */
  7442. #else
  7443. (void)use_ssl;
  7444. #endif /* NO_SSL_DL */
  7445. #else
  7446. (void)use_ssl;
  7447. #endif /* !defined(NO_SSL) */
  7448. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7449. sa->sin.sin_family = AF_INET;
  7450. sa->sin.sin_port = htons((uint16_t)port);
  7451. ip_ver = 4;
  7452. #if defined(USE_IPV6)
  7453. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7454. sa->sin6.sin6_family = AF_INET6;
  7455. sa->sin6.sin6_port = htons((uint16_t)port);
  7456. ip_ver = 6;
  7457. } else if (host[0] == '[') {
  7458. /* While getaddrinfo on Windows will work with [::1],
  7459. * getaddrinfo on Linux only works with ::1 (without []). */
  7460. size_t l = strlen(host + 1);
  7461. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7462. if (h) {
  7463. h[l - 1] = 0;
  7464. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7465. sa->sin6.sin6_family = AF_INET6;
  7466. sa->sin6.sin6_port = htons((uint16_t)port);
  7467. ip_ver = 6;
  7468. }
  7469. mg_free(h);
  7470. }
  7471. #endif
  7472. }
  7473. if (ip_ver == 0) {
  7474. mg_snprintf(NULL,
  7475. NULL, /* No truncation check for ebuf */
  7476. ebuf,
  7477. ebuf_len,
  7478. "%s",
  7479. "host not found");
  7480. return 0;
  7481. }
  7482. if (ip_ver == 4) {
  7483. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7484. }
  7485. #if defined(USE_IPV6)
  7486. else if (ip_ver == 6) {
  7487. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7488. }
  7489. #endif
  7490. if (*sock == INVALID_SOCKET) {
  7491. mg_snprintf(NULL,
  7492. NULL, /* No truncation check for ebuf */
  7493. ebuf,
  7494. ebuf_len,
  7495. "socket(): %s",
  7496. strerror(ERRNO));
  7497. return 0;
  7498. }
  7499. if (0 != set_non_blocking_mode(*sock)) {
  7500. mg_snprintf(NULL,
  7501. NULL, /* No truncation check for ebuf */
  7502. ebuf,
  7503. ebuf_len,
  7504. "Cannot set socket to non-blocking: %s",
  7505. strerror(ERRNO));
  7506. closesocket(*sock);
  7507. *sock = INVALID_SOCKET;
  7508. return 0;
  7509. }
  7510. set_close_on_exec(*sock, fc(ctx));
  7511. if (ip_ver == 4) {
  7512. /* connected with IPv4 */
  7513. conn_ret = connect(*sock,
  7514. (struct sockaddr *)((void *)&sa->sin),
  7515. sizeof(sa->sin));
  7516. }
  7517. #if defined(USE_IPV6)
  7518. else if (ip_ver == 6) {
  7519. /* connected with IPv6 */
  7520. conn_ret = connect(*sock,
  7521. (struct sockaddr *)((void *)&sa->sin6),
  7522. sizeof(sa->sin6));
  7523. }
  7524. #endif
  7525. if (conn_ret != 0) {
  7526. fd_set fdset;
  7527. struct timeval timeout;
  7528. int sockerr = -1;
  7529. void *psockerr = &sockerr;
  7530. #if defined(_WIN32)
  7531. int len = (int)sizeof(sockerr);
  7532. #else
  7533. socklen_t len = (socklen_t)sizeof(sockerr);
  7534. #endif
  7535. FD_ZERO(&fdset);
  7536. FD_SET(*sock, &fdset);
  7537. timeout.tv_sec = 10; /* 10 second timeout */
  7538. timeout.tv_usec = 0;
  7539. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7540. /* Not connected */
  7541. mg_snprintf(NULL,
  7542. NULL, /* No truncation check for ebuf */
  7543. ebuf,
  7544. ebuf_len,
  7545. "connect(%s:%d): timeout",
  7546. host,
  7547. port);
  7548. closesocket(*sock);
  7549. *sock = INVALID_SOCKET;
  7550. return 0;
  7551. }
  7552. #if defined(_WIN32)
  7553. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7554. #else
  7555. getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7556. #endif
  7557. if (sockerr != 0) {
  7558. /* Not connected */
  7559. mg_snprintf(NULL,
  7560. NULL, /* No truncation check for ebuf */
  7561. ebuf,
  7562. ebuf_len,
  7563. "connect(%s:%d): error %s",
  7564. host,
  7565. port,
  7566. strerror(sockerr));
  7567. closesocket(*sock);
  7568. *sock = INVALID_SOCKET;
  7569. return 0;
  7570. }
  7571. }
  7572. return 1;
  7573. }
  7574. int
  7575. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7576. {
  7577. static const char *dont_escape = "._-$,;~()";
  7578. static const char *hex = "0123456789abcdef";
  7579. char *pos = dst;
  7580. const char *end = dst + dst_len - 1;
  7581. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7582. if (isalnum(*(const unsigned char *)src)
  7583. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7584. *pos = *src;
  7585. } else if (pos + 2 < end) {
  7586. pos[0] = '%';
  7587. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7588. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7589. pos += 2;
  7590. } else {
  7591. break;
  7592. }
  7593. }
  7594. *pos = '\0';
  7595. return (*src == '\0') ? (int)(pos - dst) : -1;
  7596. }
  7597. /* Return 0 on success, non-zero if an error occurs. */
  7598. static int
  7599. print_dir_entry(struct de *de)
  7600. {
  7601. size_t hrefsize;
  7602. char *href;
  7603. char size[64], mod[64];
  7604. #if defined(REENTRANT_TIME)
  7605. struct tm _tm;
  7606. struct tm *tm = &_tm;
  7607. #else
  7608. struct tm *tm;
  7609. #endif
  7610. hrefsize = PATH_MAX * 3; /* worst case */
  7611. href = (char *)mg_malloc(hrefsize);
  7612. if (href == NULL) {
  7613. return -1;
  7614. }
  7615. if (de->file.is_directory) {
  7616. mg_snprintf(de->conn,
  7617. NULL, /* Buffer is big enough */
  7618. size,
  7619. sizeof(size),
  7620. "%s",
  7621. "[DIRECTORY]");
  7622. } else {
  7623. /* We use (signed) cast below because MSVC 6 compiler cannot
  7624. * convert unsigned __int64 to double. Sigh. */
  7625. if (de->file.size < 1024) {
  7626. mg_snprintf(de->conn,
  7627. NULL, /* Buffer is big enough */
  7628. size,
  7629. sizeof(size),
  7630. "%d",
  7631. (int)de->file.size);
  7632. } else if (de->file.size < 0x100000) {
  7633. mg_snprintf(de->conn,
  7634. NULL, /* Buffer is big enough */
  7635. size,
  7636. sizeof(size),
  7637. "%.1fk",
  7638. (double)de->file.size / 1024.0);
  7639. } else if (de->file.size < 0x40000000) {
  7640. mg_snprintf(de->conn,
  7641. NULL, /* Buffer is big enough */
  7642. size,
  7643. sizeof(size),
  7644. "%.1fM",
  7645. (double)de->file.size / 1048576);
  7646. } else {
  7647. mg_snprintf(de->conn,
  7648. NULL, /* Buffer is big enough */
  7649. size,
  7650. sizeof(size),
  7651. "%.1fG",
  7652. (double)de->file.size / 1073741824);
  7653. }
  7654. }
  7655. /* Note: mg_snprintf will not cause a buffer overflow above.
  7656. * So, string truncation checks are not required here. */
  7657. #if defined(REENTRANT_TIME)
  7658. localtime_r(&de->file.last_modified, tm);
  7659. #else
  7660. tm = localtime(&de->file.last_modified);
  7661. #endif
  7662. if (tm != NULL) {
  7663. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7664. } else {
  7665. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7666. mod[sizeof(mod) - 1] = '\0';
  7667. }
  7668. mg_url_encode(de->file_name, href, hrefsize);
  7669. mg_printf(de->conn,
  7670. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7671. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7672. de->conn->request_info.local_uri,
  7673. href,
  7674. de->file.is_directory ? "/" : "",
  7675. de->file_name,
  7676. de->file.is_directory ? "/" : "",
  7677. mod,
  7678. size);
  7679. mg_free(href);
  7680. return 0;
  7681. }
  7682. /* This function is called from send_directory() and used for
  7683. * sorting directory entries by size, or name, or modification time.
  7684. * On windows, __cdecl specification is needed in case if project is built
  7685. * with __stdcall convention. qsort always requires __cdels callback. */
  7686. static int WINCDECL
  7687. compare_dir_entries(const void *p1, const void *p2)
  7688. {
  7689. if (p1 && p2) {
  7690. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7691. const char *query_string = a->conn->request_info.query_string;
  7692. int cmp_result = 0;
  7693. if (query_string == NULL) {
  7694. query_string = "na";
  7695. }
  7696. if (a->file.is_directory && !b->file.is_directory) {
  7697. return -1; /* Always put directories on top */
  7698. } else if (!a->file.is_directory && b->file.is_directory) {
  7699. return 1; /* Always put directories on top */
  7700. } else if (*query_string == 'n') {
  7701. cmp_result = strcmp(a->file_name, b->file_name);
  7702. } else if (*query_string == 's') {
  7703. cmp_result = (a->file.size == b->file.size)
  7704. ? 0
  7705. : ((a->file.size > b->file.size) ? 1 : -1);
  7706. } else if (*query_string == 'd') {
  7707. cmp_result =
  7708. (a->file.last_modified == b->file.last_modified)
  7709. ? 0
  7710. : ((a->file.last_modified > b->file.last_modified) ? 1
  7711. : -1);
  7712. }
  7713. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7714. }
  7715. return 0;
  7716. }
  7717. static int
  7718. must_hide_file(struct mg_connection *conn, const char *path)
  7719. {
  7720. if (conn && conn->dom_ctx) {
  7721. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7722. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7723. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7724. || ((pattern != NULL)
  7725. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7726. }
  7727. return 0;
  7728. }
  7729. static int
  7730. scan_directory(struct mg_connection *conn,
  7731. const char *dir,
  7732. void *data,
  7733. int (*cb)(struct de *, void *))
  7734. {
  7735. char path[PATH_MAX];
  7736. struct dirent *dp;
  7737. DIR *dirp;
  7738. struct de de;
  7739. int truncated;
  7740. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7741. return 0;
  7742. } else {
  7743. de.conn = conn;
  7744. while ((dp = mg_readdir(dirp)) != NULL) {
  7745. /* Do not show current dir and hidden files */
  7746. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7747. || must_hide_file(conn, dp->d_name)) {
  7748. continue;
  7749. }
  7750. mg_snprintf(
  7751. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7752. /* If we don't memset stat structure to zero, mtime will have
  7753. * garbage and strftime() will segfault later on in
  7754. * print_dir_entry(). memset is required only if mg_stat()
  7755. * fails. For more details, see
  7756. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7757. memset(&de.file, 0, sizeof(de.file));
  7758. if (truncated) {
  7759. /* If the path is not complete, skip processing. */
  7760. continue;
  7761. }
  7762. if (!mg_stat(conn, path, &de.file)) {
  7763. mg_cry_internal(conn,
  7764. "%s: mg_stat(%s) failed: %s",
  7765. __func__,
  7766. path,
  7767. strerror(ERRNO));
  7768. }
  7769. de.file_name = dp->d_name;
  7770. cb(&de, data);
  7771. }
  7772. (void)mg_closedir(dirp);
  7773. }
  7774. return 1;
  7775. }
  7776. #if !defined(NO_FILES)
  7777. static int
  7778. remove_directory(struct mg_connection *conn, const char *dir)
  7779. {
  7780. char path[PATH_MAX];
  7781. struct dirent *dp;
  7782. DIR *dirp;
  7783. struct de de;
  7784. int truncated;
  7785. int ok = 1;
  7786. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7787. return 0;
  7788. } else {
  7789. de.conn = conn;
  7790. while ((dp = mg_readdir(dirp)) != NULL) {
  7791. /* Do not show current dir (but show hidden files as they will
  7792. * also be removed) */
  7793. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7794. continue;
  7795. }
  7796. mg_snprintf(
  7797. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7798. /* If we don't memset stat structure to zero, mtime will have
  7799. * garbage and strftime() will segfault later on in
  7800. * print_dir_entry(). memset is required only if mg_stat()
  7801. * fails. For more details, see
  7802. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7803. memset(&de.file, 0, sizeof(de.file));
  7804. if (truncated) {
  7805. /* Do not delete anything shorter */
  7806. ok = 0;
  7807. continue;
  7808. }
  7809. if (!mg_stat(conn, path, &de.file)) {
  7810. mg_cry_internal(conn,
  7811. "%s: mg_stat(%s) failed: %s",
  7812. __func__,
  7813. path,
  7814. strerror(ERRNO));
  7815. ok = 0;
  7816. }
  7817. if (de.file.is_directory) {
  7818. if (remove_directory(conn, path) == 0) {
  7819. ok = 0;
  7820. }
  7821. } else {
  7822. /* This will fail file is the file is in memory */
  7823. if (mg_remove(conn, path) == 0) {
  7824. ok = 0;
  7825. }
  7826. }
  7827. }
  7828. (void)mg_closedir(dirp);
  7829. IGNORE_UNUSED_RESULT(rmdir(dir));
  7830. }
  7831. return ok;
  7832. }
  7833. #endif
  7834. struct dir_scan_data {
  7835. struct de *entries;
  7836. unsigned int num_entries;
  7837. unsigned int arr_size;
  7838. };
  7839. /* Behaves like realloc(), but frees original pointer on failure */
  7840. static void *
  7841. realloc2(void *ptr, size_t size)
  7842. {
  7843. void *new_ptr = mg_realloc(ptr, size);
  7844. if (new_ptr == NULL) {
  7845. mg_free(ptr);
  7846. }
  7847. return new_ptr;
  7848. }
  7849. static int
  7850. dir_scan_callback(struct de *de, void *data)
  7851. {
  7852. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7853. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7854. dsd->arr_size *= 2;
  7855. dsd->entries =
  7856. (struct de *)realloc2(dsd->entries,
  7857. dsd->arr_size * sizeof(dsd->entries[0]));
  7858. }
  7859. if (dsd->entries == NULL) {
  7860. /* TODO(lsm, low): propagate an error to the caller */
  7861. dsd->num_entries = 0;
  7862. } else {
  7863. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7864. dsd->entries[dsd->num_entries].file = de->file;
  7865. dsd->entries[dsd->num_entries].conn = de->conn;
  7866. dsd->num_entries++;
  7867. }
  7868. return 0;
  7869. }
  7870. static void
  7871. handle_directory_request(struct mg_connection *conn, const char *dir)
  7872. {
  7873. unsigned int i;
  7874. int sort_direction;
  7875. struct dir_scan_data data = {NULL, 0, 128};
  7876. char date[64];
  7877. time_t curtime = time(NULL);
  7878. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7879. mg_send_http_error(conn,
  7880. 500,
  7881. "Error: Cannot open directory\nopendir(%s): %s",
  7882. dir,
  7883. strerror(ERRNO));
  7884. return;
  7885. }
  7886. gmt_time_string(date, sizeof(date), &curtime);
  7887. if (!conn) {
  7888. return;
  7889. }
  7890. sort_direction = ((conn->request_info.query_string != NULL)
  7891. && (conn->request_info.query_string[1] == 'd'))
  7892. ? 'a'
  7893. : 'd';
  7894. conn->must_close = 1;
  7895. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7896. send_static_cache_header(conn);
  7897. send_additional_header(conn);
  7898. mg_printf(conn,
  7899. "Date: %s\r\n"
  7900. "Connection: close\r\n"
  7901. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7902. date);
  7903. mg_printf(conn,
  7904. "<html><head><title>Index of %s</title>"
  7905. "<style>th {text-align: left;}</style></head>"
  7906. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7907. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7908. "<th><a href=\"?d%c\">Modified</a></th>"
  7909. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7910. "<tr><td colspan=\"3\"><hr></td></tr>",
  7911. conn->request_info.local_uri,
  7912. conn->request_info.local_uri,
  7913. sort_direction,
  7914. sort_direction,
  7915. sort_direction);
  7916. /* Print first entry - link to a parent directory */
  7917. mg_printf(conn,
  7918. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7919. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7920. conn->request_info.local_uri,
  7921. "..",
  7922. "Parent directory",
  7923. "-",
  7924. "-");
  7925. /* Sort and print directory entries */
  7926. if (data.entries != NULL) {
  7927. qsort(data.entries,
  7928. (size_t)data.num_entries,
  7929. sizeof(data.entries[0]),
  7930. compare_dir_entries);
  7931. for (i = 0; i < data.num_entries; i++) {
  7932. print_dir_entry(&data.entries[i]);
  7933. mg_free(data.entries[i].file_name);
  7934. }
  7935. mg_free(data.entries);
  7936. }
  7937. mg_printf(conn, "%s", "</table></body></html>");
  7938. conn->status_code = 200;
  7939. }
  7940. /* Send len bytes from the opened file to the client. */
  7941. static void
  7942. send_file_data(struct mg_connection *conn,
  7943. struct mg_file *filep,
  7944. int64_t offset,
  7945. int64_t len)
  7946. {
  7947. char buf[MG_BUF_LEN];
  7948. int to_read, num_read, num_written;
  7949. int64_t size;
  7950. if (!filep || !conn) {
  7951. return;
  7952. }
  7953. /* Sanity check the offset */
  7954. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7955. : (int64_t)(filep->stat.size);
  7956. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7957. #if defined(MG_USE_OPEN_FILE)
  7958. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7959. /* file stored in memory */
  7960. if (len > size - offset) {
  7961. len = size - offset;
  7962. }
  7963. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7964. } else /* else block below */
  7965. #endif
  7966. if (len > 0 && filep->access.fp != NULL) {
  7967. /* file stored on disk */
  7968. #if defined(__linux__)
  7969. /* sendfile is only available for Linux */
  7970. if ((conn->ssl == 0) && (conn->throttle == 0)
  7971. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7972. "yes"))) {
  7973. off_t sf_offs = (off_t)offset;
  7974. ssize_t sf_sent;
  7975. int sf_file = fileno(filep->access.fp);
  7976. int loop_cnt = 0;
  7977. do {
  7978. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7979. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7980. size_t sf_tosend =
  7981. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7982. sf_sent =
  7983. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7984. if (sf_sent > 0) {
  7985. len -= sf_sent;
  7986. offset += sf_sent;
  7987. } else if (loop_cnt == 0) {
  7988. /* This file can not be sent using sendfile.
  7989. * This might be the case for pseudo-files in the
  7990. * /sys/ and /proc/ file system.
  7991. * Use the regular user mode copy code instead. */
  7992. break;
  7993. } else if (sf_sent == 0) {
  7994. /* No error, but 0 bytes sent. May be EOF? */
  7995. return;
  7996. }
  7997. loop_cnt++;
  7998. } while ((len > 0) && (sf_sent >= 0));
  7999. if (sf_sent > 0) {
  8000. return; /* OK */
  8001. }
  8002. /* sf_sent<0 means error, thus fall back to the classic way */
  8003. /* This is always the case, if sf_file is not a "normal" file,
  8004. * e.g., for sending data from the output of a CGI process. */
  8005. offset = (int64_t)sf_offs;
  8006. }
  8007. #endif
  8008. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8009. mg_cry_internal(conn,
  8010. "%s: fseeko() failed: %s",
  8011. __func__,
  8012. strerror(ERRNO));
  8013. mg_send_http_error(
  8014. conn,
  8015. 500,
  8016. "%s",
  8017. "Error: Unable to access file at requested position.");
  8018. } else {
  8019. while (len > 0) {
  8020. /* Calculate how much to read from the file in the buffer */
  8021. to_read = sizeof(buf);
  8022. if ((int64_t)to_read > len) {
  8023. to_read = (int)len;
  8024. }
  8025. /* Read from file, exit the loop on error */
  8026. if ((num_read =
  8027. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8028. <= 0) {
  8029. break;
  8030. }
  8031. /* Send read bytes to the client, exit the loop on error */
  8032. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8033. != num_read) {
  8034. break;
  8035. }
  8036. /* Both read and were successful, adjust counters */
  8037. len -= num_written;
  8038. }
  8039. }
  8040. }
  8041. }
  8042. static int
  8043. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8044. {
  8045. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8046. }
  8047. static void
  8048. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8049. {
  8050. if ((filestat != NULL) && (buf != NULL)) {
  8051. mg_snprintf(NULL,
  8052. NULL, /* All calls to construct_etag use 64 byte buffer */
  8053. buf,
  8054. buf_len,
  8055. "\"%lx.%" INT64_FMT "\"",
  8056. (unsigned long)filestat->last_modified,
  8057. filestat->size);
  8058. }
  8059. }
  8060. static void
  8061. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8062. {
  8063. if (filep != NULL && filep->fp != NULL) {
  8064. #if defined(_WIN32)
  8065. (void)conn; /* Unused. */
  8066. #else
  8067. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8068. mg_cry_internal(conn,
  8069. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8070. __func__,
  8071. strerror(ERRNO));
  8072. }
  8073. #endif
  8074. }
  8075. }
  8076. #if defined(USE_ZLIB)
  8077. #include "mod_zlib.inl"
  8078. #endif
  8079. static void
  8080. handle_static_file_request(struct mg_connection *conn,
  8081. const char *path,
  8082. struct mg_file *filep,
  8083. const char *mime_type,
  8084. const char *additional_headers)
  8085. {
  8086. char date[64], lm[64], etag[64];
  8087. char range[128]; /* large enough, so there will be no overflow */
  8088. const char *msg = "OK", *hdr;
  8089. time_t curtime = time(NULL);
  8090. int64_t cl, r1, r2;
  8091. struct vec mime_vec;
  8092. int n, truncated;
  8093. char gz_path[PATH_MAX];
  8094. const char *encoding = "";
  8095. const char *cors1, *cors2, *cors3;
  8096. int is_head_request;
  8097. #if defined(USE_ZLIB)
  8098. /* Compression is allowed, unless there is a reason not to use compression.
  8099. * If the file is already compressed, too small or a "range" request was
  8100. * made, on the fly compression is not possible. */
  8101. int allow_on_the_fly_compression = 1;
  8102. #endif
  8103. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8104. return;
  8105. }
  8106. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8107. if (mime_type == NULL) {
  8108. get_mime_type(conn, path, &mime_vec);
  8109. } else {
  8110. mime_vec.ptr = mime_type;
  8111. mime_vec.len = strlen(mime_type);
  8112. }
  8113. if (filep->stat.size > INT64_MAX) {
  8114. mg_send_http_error(conn,
  8115. 500,
  8116. "Error: File size is too large to send\n%" INT64_FMT,
  8117. filep->stat.size);
  8118. return;
  8119. }
  8120. cl = (int64_t)filep->stat.size;
  8121. conn->status_code = 200;
  8122. range[0] = '\0';
  8123. #if defined(USE_ZLIB)
  8124. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8125. * it's important to rewrite the filename after resolving
  8126. * the mime type from it, to preserve the actual file's type */
  8127. if (!conn->accept_gzip) {
  8128. allow_on_the_fly_compression = 0;
  8129. }
  8130. #endif
  8131. if (filep->stat.is_gzipped) {
  8132. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8133. if (truncated) {
  8134. mg_send_http_error(conn,
  8135. 500,
  8136. "Error: Path of zipped file too long (%s)",
  8137. path);
  8138. return;
  8139. }
  8140. path = gz_path;
  8141. encoding = "Content-Encoding: gzip\r\n";
  8142. #if defined(USE_ZLIB)
  8143. /* File is already compressed. No "on the fly" compression. */
  8144. allow_on_the_fly_compression = 0;
  8145. #endif
  8146. }
  8147. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8148. mg_send_http_error(conn,
  8149. 500,
  8150. "Error: Cannot open file\nfopen(%s): %s",
  8151. path,
  8152. strerror(ERRNO));
  8153. return;
  8154. }
  8155. fclose_on_exec(&filep->access, conn);
  8156. /* If "Range" request was made: parse header, send only selected part
  8157. * of the file. */
  8158. r1 = r2 = 0;
  8159. hdr = mg_get_header(conn, "Range");
  8160. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  8161. && (r1 >= 0) && (r2 >= 0)) {
  8162. /* actually, range requests don't play well with a pre-gzipped
  8163. * file (since the range is specified in the uncompressed space) */
  8164. if (filep->stat.is_gzipped) {
  8165. mg_send_http_error(
  8166. conn,
  8167. 416, /* 416 = Range Not Satisfiable */
  8168. "%s",
  8169. "Error: Range requests in gzipped files are not supported");
  8170. (void)mg_fclose(
  8171. &filep->access); /* ignore error on read only file */
  8172. return;
  8173. }
  8174. conn->status_code = 206;
  8175. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8176. mg_snprintf(conn,
  8177. NULL, /* range buffer is big enough */
  8178. range,
  8179. sizeof(range),
  8180. "Content-Range: bytes "
  8181. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8182. r1,
  8183. r1 + cl - 1,
  8184. filep->stat.size);
  8185. msg = "Partial Content";
  8186. #if defined(USE_ZLIB)
  8187. /* Do not compress ranges. */
  8188. allow_on_the_fly_compression = 0;
  8189. #endif
  8190. }
  8191. /* Do not compress small files. Small files do not benefit from file
  8192. * compression, but there is still some overhead. */
  8193. #if defined(USE_ZLIB)
  8194. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8195. /* File is below the size limit. */
  8196. allow_on_the_fly_compression = 0;
  8197. }
  8198. #endif
  8199. /* Standard CORS header */
  8200. hdr = mg_get_header(conn, "Origin");
  8201. if (hdr) {
  8202. /* Cross-origin resource sharing (CORS), see
  8203. * http://www.html5rocks.com/en/tutorials/cors/,
  8204. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8205. * -
  8206. * preflight is not supported for files. */
  8207. cors1 = "Access-Control-Allow-Origin: ";
  8208. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8209. cors3 = "\r\n";
  8210. } else {
  8211. cors1 = cors2 = cors3 = "";
  8212. }
  8213. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8214. * according to
  8215. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8216. gmt_time_string(date, sizeof(date), &curtime);
  8217. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8218. construct_etag(etag, sizeof(etag), &filep->stat);
  8219. /* Send header */
  8220. (void)mg_printf(conn,
  8221. "HTTP/1.1 %d %s\r\n"
  8222. "%s%s%s" /* CORS */
  8223. "Date: %s\r\n"
  8224. "Last-Modified: %s\r\n"
  8225. "Etag: %s\r\n"
  8226. "Content-Type: %.*s\r\n"
  8227. "Connection: %s\r\n",
  8228. conn->status_code,
  8229. msg,
  8230. cors1,
  8231. cors2,
  8232. cors3,
  8233. date,
  8234. lm,
  8235. etag,
  8236. (int)mime_vec.len,
  8237. mime_vec.ptr,
  8238. suggest_connection_header(conn));
  8239. send_static_cache_header(conn);
  8240. send_additional_header(conn);
  8241. #if defined(USE_ZLIB)
  8242. /* On the fly compression allowed */
  8243. if (allow_on_the_fly_compression) {
  8244. /* For on the fly compression, we don't know the content size in
  8245. * advance, so we have to use chunked encoding */
  8246. (void)mg_printf(conn,
  8247. "Content-Encoding: gzip\r\n"
  8248. "Transfer-Encoding: chunked\r\n");
  8249. } else
  8250. #endif
  8251. {
  8252. /* Without on-the-fly compression, we know the content-length
  8253. * and we can use ranges (with on-the-fly compression we cannot).
  8254. * So we send these response headers only in this case. */
  8255. (void)mg_printf(conn,
  8256. "Content-Length: %" INT64_FMT "\r\n"
  8257. "Accept-Ranges: bytes\r\n"
  8258. "%s" /* range */
  8259. "%s" /* encoding */,
  8260. cl,
  8261. range,
  8262. encoding);
  8263. }
  8264. /* The previous code must not add any header starting with X- to make
  8265. * sure no one of the additional_headers is included twice */
  8266. if (additional_headers != NULL) {
  8267. (void)mg_printf(conn,
  8268. "%.*s\r\n\r\n",
  8269. (int)strlen(additional_headers),
  8270. additional_headers);
  8271. } else {
  8272. (void)mg_printf(conn, "\r\n");
  8273. }
  8274. if (!is_head_request) {
  8275. #if defined(USE_ZLIB)
  8276. if (allow_on_the_fly_compression) {
  8277. /* Compress and send */
  8278. send_compressed_data(conn, filep);
  8279. } else
  8280. #endif
  8281. {
  8282. /* Send file directly */
  8283. send_file_data(conn, filep, r1, cl);
  8284. }
  8285. }
  8286. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8287. }
  8288. #if !defined(NO_CACHING)
  8289. /* Return True if we should reply 304 Not Modified. */
  8290. static int
  8291. is_not_modified(const struct mg_connection *conn,
  8292. const struct mg_file_stat *filestat)
  8293. {
  8294. char etag[64];
  8295. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8296. const char *inm = mg_get_header(conn, "If-None-Match");
  8297. construct_etag(etag, sizeof(etag), filestat);
  8298. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8299. || ((ims != NULL)
  8300. && (filestat->last_modified <= parse_date_string(ims)));
  8301. }
  8302. static void
  8303. handle_not_modified_static_file_request(struct mg_connection *conn,
  8304. struct mg_file *filep)
  8305. {
  8306. char date[64], lm[64], etag[64];
  8307. time_t curtime = time(NULL);
  8308. if ((conn == NULL) || (filep == NULL)) {
  8309. return;
  8310. }
  8311. conn->status_code = 304;
  8312. gmt_time_string(date, sizeof(date), &curtime);
  8313. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8314. construct_etag(etag, sizeof(etag), &filep->stat);
  8315. (void)mg_printf(conn,
  8316. "HTTP/1.1 %d %s\r\n"
  8317. "Date: %s\r\n",
  8318. conn->status_code,
  8319. mg_get_response_code_text(conn, conn->status_code),
  8320. date);
  8321. send_static_cache_header(conn);
  8322. send_additional_header(conn);
  8323. (void)mg_printf(conn,
  8324. "Last-Modified: %s\r\n"
  8325. "Etag: %s\r\n"
  8326. "Connection: %s\r\n"
  8327. "\r\n",
  8328. lm,
  8329. etag,
  8330. suggest_connection_header(conn));
  8331. }
  8332. #endif
  8333. void
  8334. mg_send_file(struct mg_connection *conn, const char *path)
  8335. {
  8336. mg_send_mime_file(conn, path, NULL);
  8337. }
  8338. void
  8339. mg_send_mime_file(struct mg_connection *conn,
  8340. const char *path,
  8341. const char *mime_type)
  8342. {
  8343. mg_send_mime_file2(conn, path, mime_type, NULL);
  8344. }
  8345. void
  8346. mg_send_mime_file2(struct mg_connection *conn,
  8347. const char *path,
  8348. const char *mime_type,
  8349. const char *additional_headers)
  8350. {
  8351. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8352. if (!conn) {
  8353. /* No conn */
  8354. return;
  8355. }
  8356. if (mg_stat(conn, path, &file.stat)) {
  8357. #if !defined(NO_CACHING)
  8358. if (is_not_modified(conn, &file.stat)) {
  8359. /* Send 304 "Not Modified" - this must not send any body data */
  8360. handle_not_modified_static_file_request(conn, &file);
  8361. } else
  8362. #endif /* NO_CACHING */
  8363. if (file.stat.is_directory) {
  8364. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8365. "yes")) {
  8366. handle_directory_request(conn, path);
  8367. } else {
  8368. mg_send_http_error(conn,
  8369. 403,
  8370. "%s",
  8371. "Error: Directory listing denied");
  8372. }
  8373. } else {
  8374. handle_static_file_request(
  8375. conn, path, &file, mime_type, additional_headers);
  8376. }
  8377. } else {
  8378. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8379. }
  8380. }
  8381. /* For a given PUT path, create all intermediate subdirectories.
  8382. * Return 0 if the path itself is a directory.
  8383. * Return 1 if the path leads to a file.
  8384. * Return -1 for if the path is too long.
  8385. * Return -2 if path can not be created.
  8386. */
  8387. static int
  8388. put_dir(struct mg_connection *conn, const char *path)
  8389. {
  8390. char buf[PATH_MAX];
  8391. const char *s, *p;
  8392. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8393. size_t len;
  8394. int res = 1;
  8395. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8396. len = (size_t)(p - path);
  8397. if (len >= sizeof(buf)) {
  8398. /* path too long */
  8399. res = -1;
  8400. break;
  8401. }
  8402. memcpy(buf, path, len);
  8403. buf[len] = '\0';
  8404. /* Try to create intermediate directory */
  8405. DEBUG_TRACE("mkdir(%s)", buf);
  8406. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8407. /* path does not exixt and can not be created */
  8408. res = -2;
  8409. break;
  8410. }
  8411. /* Is path itself a directory? */
  8412. if (p[1] == '\0') {
  8413. res = 0;
  8414. }
  8415. }
  8416. return res;
  8417. }
  8418. static void
  8419. remove_bad_file(const struct mg_connection *conn, const char *path)
  8420. {
  8421. int r = mg_remove(conn, path);
  8422. if (r != 0) {
  8423. mg_cry_internal(conn,
  8424. "%s: Cannot remove invalid file %s",
  8425. __func__,
  8426. path);
  8427. }
  8428. }
  8429. long long
  8430. mg_store_body(struct mg_connection *conn, const char *path)
  8431. {
  8432. char buf[MG_BUF_LEN];
  8433. long long len = 0;
  8434. int ret, n;
  8435. struct mg_file fi;
  8436. if (conn->consumed_content != 0) {
  8437. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8438. return -11;
  8439. }
  8440. ret = put_dir(conn, path);
  8441. if (ret < 0) {
  8442. /* -1 for path too long,
  8443. * -2 for path can not be created. */
  8444. return ret;
  8445. }
  8446. if (ret != 1) {
  8447. /* Return 0 means, path itself is a directory. */
  8448. return 0;
  8449. }
  8450. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8451. return -12;
  8452. }
  8453. ret = mg_read(conn, buf, sizeof(buf));
  8454. while (ret > 0) {
  8455. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8456. if (n != ret) {
  8457. (void)mg_fclose(
  8458. &fi.access); /* File is bad and will be removed anyway. */
  8459. remove_bad_file(conn, path);
  8460. return -13;
  8461. }
  8462. len += ret;
  8463. ret = mg_read(conn, buf, sizeof(buf));
  8464. }
  8465. /* File is open for writing. If fclose fails, there was probably an
  8466. * error flushing the buffer to disk, so the file on disk might be
  8467. * broken. Delete it and return an error to the caller. */
  8468. if (mg_fclose(&fi.access) != 0) {
  8469. remove_bad_file(conn, path);
  8470. return -14;
  8471. }
  8472. return len;
  8473. }
  8474. /* Parse a buffer:
  8475. * Forward the string pointer till the end of a word, then
  8476. * terminate it and forward till the begin of the next word.
  8477. */
  8478. static int
  8479. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8480. {
  8481. /* Forward until a space is found - use isgraph here */
  8482. /* See http://www.cplusplus.com/reference/cctype/ */
  8483. while (isgraph(**ppw)) {
  8484. (*ppw)++;
  8485. }
  8486. /* Check end of word */
  8487. if (eol) {
  8488. /* must be a end of line */
  8489. if ((**ppw != '\r') && (**ppw != '\n')) {
  8490. return -1;
  8491. }
  8492. } else {
  8493. /* must be a end of a word, but not a line */
  8494. if (**ppw != ' ') {
  8495. return -1;
  8496. }
  8497. }
  8498. /* Terminate and forward to the next word */
  8499. do {
  8500. **ppw = 0;
  8501. (*ppw)++;
  8502. } while ((**ppw) && isspace(**ppw));
  8503. /* Check after term */
  8504. if (!eol) {
  8505. /* if it's not the end of line, there must be a next word */
  8506. if (!isgraph(**ppw)) {
  8507. return -1;
  8508. }
  8509. }
  8510. /* ok */
  8511. return 1;
  8512. }
  8513. /* Parse HTTP headers from the given buffer, advance buf pointer
  8514. * to the point where parsing stopped.
  8515. * All parameters must be valid pointers (not NULL).
  8516. * Return <0 on error. */
  8517. static int
  8518. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8519. {
  8520. int i;
  8521. int num_headers = 0;
  8522. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8523. char *dp = *buf;
  8524. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8525. dp++;
  8526. }
  8527. if (dp == *buf) {
  8528. /* End of headers reached. */
  8529. break;
  8530. }
  8531. if (*dp != ':') {
  8532. /* This is not a valid field. */
  8533. return -1;
  8534. }
  8535. /* End of header key (*dp == ':') */
  8536. /* Truncate here and set the key name */
  8537. *dp = 0;
  8538. hdr[i].name = *buf;
  8539. do {
  8540. dp++;
  8541. } while (*dp == ' ');
  8542. /* The rest of the line is the value */
  8543. hdr[i].value = dp;
  8544. *buf = dp + strcspn(dp, "\r\n");
  8545. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8546. *buf = NULL;
  8547. }
  8548. num_headers = i + 1;
  8549. if (*buf) {
  8550. (*buf)[0] = 0;
  8551. (*buf)[1] = 0;
  8552. *buf += 2;
  8553. } else {
  8554. *buf = dp;
  8555. break;
  8556. }
  8557. if ((*buf)[0] == '\r') {
  8558. /* This is the end of the header */
  8559. break;
  8560. }
  8561. }
  8562. return num_headers;
  8563. }
  8564. struct mg_http_method_info {
  8565. const char *name;
  8566. int request_has_body;
  8567. int response_has_body;
  8568. int is_safe;
  8569. int is_idempotent;
  8570. int is_cacheable;
  8571. };
  8572. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8573. static struct mg_http_method_info http_methods[] = {
  8574. /* HTTP (RFC 2616) */
  8575. {"GET", 0, 1, 1, 1, 1},
  8576. {"POST", 1, 1, 0, 0, 0},
  8577. {"PUT", 1, 0, 0, 1, 0},
  8578. {"DELETE", 0, 0, 0, 1, 0},
  8579. {"HEAD", 0, 0, 1, 1, 1},
  8580. {"OPTIONS", 0, 0, 1, 1, 0},
  8581. {"CONNECT", 1, 1, 0, 0, 0},
  8582. /* TRACE method (RFC 2616) is not supported for security reasons */
  8583. /* PATCH method (RFC 5789) */
  8584. {"PATCH", 1, 0, 0, 0, 0},
  8585. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8586. /* WEBDAV (RFC 2518) */
  8587. {"PROPFIND", 0, 1, 1, 1, 0},
  8588. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8589. * Some PROPFIND results MAY be cached, with care,
  8590. * as there is no cache validation mechanism for
  8591. * most properties. This method is both safe and
  8592. * idempotent (see Section 9.1 of [RFC2616]). */
  8593. {"MKCOL", 0, 0, 0, 1, 0},
  8594. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8595. * When MKCOL is invoked without a request body,
  8596. * the newly created collection SHOULD have no
  8597. * members. A MKCOL request message may contain
  8598. * a message body. The precise behavior of a MKCOL
  8599. * request when the body is present is undefined,
  8600. * ... ==> We do not support MKCOL with body data.
  8601. * This method is idempotent, but not safe (see
  8602. * Section 9.1 of [RFC2616]). Responses to this
  8603. * method MUST NOT be cached. */
  8604. /* Unsupported WEBDAV Methods: */
  8605. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8606. /* + 11 methods from RFC 3253 */
  8607. /* ORDERPATCH (RFC 3648) */
  8608. /* ACL (RFC 3744) */
  8609. /* SEARCH (RFC 5323) */
  8610. /* + MicroSoft extensions
  8611. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8612. /* REPORT method (RFC 3253) */
  8613. {"REPORT", 1, 1, 1, 1, 1},
  8614. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8615. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8616. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8617. * to be useful for REST in case a "GET request with body" is
  8618. * required. */
  8619. {NULL, 0, 0, 0, 0, 0}
  8620. /* end of list */
  8621. };
  8622. static const struct mg_http_method_info *
  8623. get_http_method_info(const char *method)
  8624. {
  8625. /* Check if the method is known to the server. The list of all known
  8626. * HTTP methods can be found here at
  8627. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8628. */
  8629. const struct mg_http_method_info *m = http_methods;
  8630. while (m->name) {
  8631. if (!strcmp(m->name, method)) {
  8632. return m;
  8633. }
  8634. m++;
  8635. }
  8636. return NULL;
  8637. }
  8638. static int
  8639. is_valid_http_method(const char *method)
  8640. {
  8641. return (get_http_method_info(method) != NULL);
  8642. }
  8643. /* Parse HTTP request, fill in mg_request_info structure.
  8644. * This function modifies the buffer by NUL-terminating
  8645. * HTTP request components, header names and header values.
  8646. * Parameters:
  8647. * buf (in/out): pointer to the HTTP header to parse and split
  8648. * len (in): length of HTTP header buffer
  8649. * re (out): parsed header as mg_request_info
  8650. * buf and ri must be valid pointers (not NULL), len>0.
  8651. * Returns <0 on error. */
  8652. static int
  8653. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8654. {
  8655. int request_length;
  8656. int init_skip = 0;
  8657. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8658. * remote_port */
  8659. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8660. NULL;
  8661. ri->num_headers = 0;
  8662. /* RFC says that all initial whitespaces should be ingored */
  8663. /* This included all leading \r and \n (isspace) */
  8664. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8665. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8666. buf++;
  8667. len--;
  8668. init_skip++;
  8669. }
  8670. if (len == 0) {
  8671. /* Incomplete request */
  8672. return 0;
  8673. }
  8674. /* Control characters are not allowed, including zero */
  8675. if (iscntrl(*(unsigned char *)buf)) {
  8676. return -1;
  8677. }
  8678. /* Find end of HTTP header */
  8679. request_length = get_http_header_len(buf, len);
  8680. if (request_length <= 0) {
  8681. return request_length;
  8682. }
  8683. buf[request_length - 1] = '\0';
  8684. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8685. return -1;
  8686. }
  8687. /* The first word has to be the HTTP method */
  8688. ri->request_method = buf;
  8689. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8690. return -1;
  8691. }
  8692. /* Check for a valid http method */
  8693. if (!is_valid_http_method(ri->request_method)) {
  8694. return -1;
  8695. }
  8696. /* The second word is the URI */
  8697. ri->request_uri = buf;
  8698. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8699. return -1;
  8700. }
  8701. /* Next would be the HTTP version */
  8702. ri->http_version = buf;
  8703. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8704. return -1;
  8705. }
  8706. /* Check for a valid HTTP version key */
  8707. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8708. /* Invalid request */
  8709. return -1;
  8710. }
  8711. ri->http_version += 5;
  8712. /* Parse all HTTP headers */
  8713. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8714. if (ri->num_headers < 0) {
  8715. /* Error while parsing headers */
  8716. return -1;
  8717. }
  8718. return request_length + init_skip;
  8719. }
  8720. static int
  8721. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8722. {
  8723. int response_length;
  8724. int init_skip = 0;
  8725. char *tmp, *tmp2;
  8726. long l;
  8727. /* Initialize elements. */
  8728. ri->http_version = ri->status_text = NULL;
  8729. ri->num_headers = ri->status_code = 0;
  8730. /* RFC says that all initial whitespaces should be ingored */
  8731. /* This included all leading \r and \n (isspace) */
  8732. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8733. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8734. buf++;
  8735. len--;
  8736. init_skip++;
  8737. }
  8738. if (len == 0) {
  8739. /* Incomplete request */
  8740. return 0;
  8741. }
  8742. /* Control characters are not allowed, including zero */
  8743. if (iscntrl(*(unsigned char *)buf)) {
  8744. return -1;
  8745. }
  8746. /* Find end of HTTP header */
  8747. response_length = get_http_header_len(buf, len);
  8748. if (response_length <= 0) {
  8749. return response_length;
  8750. }
  8751. buf[response_length - 1] = '\0';
  8752. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8753. return -1;
  8754. }
  8755. /* The first word is the HTTP version */
  8756. /* Check for a valid HTTP version key */
  8757. if (strncmp(buf, "HTTP/", 5) != 0) {
  8758. /* Invalid request */
  8759. return -1;
  8760. }
  8761. buf += 5;
  8762. if (!isgraph(buf[0])) {
  8763. /* Invalid request */
  8764. return -1;
  8765. }
  8766. ri->http_version = buf;
  8767. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8768. return -1;
  8769. }
  8770. /* The second word is the status as a number */
  8771. tmp = buf;
  8772. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8773. return -1;
  8774. }
  8775. l = strtol(tmp, &tmp2, 10);
  8776. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8777. /* Everything else but a 3 digit code is invalid */
  8778. return -1;
  8779. }
  8780. ri->status_code = (int)l;
  8781. /* The rest of the line is the status text */
  8782. ri->status_text = buf;
  8783. /* Find end of status text */
  8784. /* isgraph or isspace = isprint */
  8785. while (isprint(*buf)) {
  8786. buf++;
  8787. }
  8788. if ((*buf != '\r') && (*buf != '\n')) {
  8789. return -1;
  8790. }
  8791. /* Terminate string and forward buf to next line */
  8792. do {
  8793. *buf = 0;
  8794. buf++;
  8795. } while ((*buf) && isspace(*buf));
  8796. /* Parse all HTTP headers */
  8797. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8798. if (ri->num_headers < 0) {
  8799. /* Error while parsing headers */
  8800. return -1;
  8801. }
  8802. return response_length + init_skip;
  8803. }
  8804. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8805. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8806. * buffer (which marks the end of HTTP request). Buffer buf may already
  8807. * have some data. The length of the data is stored in nread.
  8808. * Upon every read operation, increase nread by the number of bytes read. */
  8809. static int
  8810. read_message(FILE *fp,
  8811. struct mg_connection *conn,
  8812. char *buf,
  8813. int bufsiz,
  8814. int *nread)
  8815. {
  8816. int request_len, n = 0;
  8817. struct timespec last_action_time;
  8818. double request_timeout;
  8819. if (!conn) {
  8820. return 0;
  8821. }
  8822. memset(&last_action_time, 0, sizeof(last_action_time));
  8823. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8824. /* value of request_timeout is in seconds, config in milliseconds */
  8825. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8826. } else {
  8827. request_timeout = -1.0;
  8828. }
  8829. if (conn->handled_requests > 0) {
  8830. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8831. request_timeout =
  8832. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8833. }
  8834. }
  8835. request_len = get_http_header_len(buf, *nread);
  8836. /* first time reading from this connection */
  8837. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8838. while (request_len == 0) {
  8839. /* Full request not yet received */
  8840. if (conn->phys_ctx->stop_flag != 0) {
  8841. /* Server is to be stopped. */
  8842. return -1;
  8843. }
  8844. if (*nread >= bufsiz) {
  8845. /* Request too long */
  8846. return -2;
  8847. }
  8848. n = pull_inner(
  8849. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8850. if (n == -2) {
  8851. /* Receive error */
  8852. return -1;
  8853. }
  8854. if (n > 0) {
  8855. *nread += n;
  8856. request_len = get_http_header_len(buf, *nread);
  8857. } else {
  8858. request_len = 0;
  8859. }
  8860. if ((request_len == 0) && (request_timeout >= 0)) {
  8861. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8862. > request_timeout) {
  8863. /* Timeout */
  8864. return -1;
  8865. }
  8866. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8867. }
  8868. }
  8869. return request_len;
  8870. }
  8871. #if !defined(NO_CGI) || !defined(NO_FILES)
  8872. static int
  8873. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8874. {
  8875. const char *expect, *body;
  8876. char buf[MG_BUF_LEN];
  8877. int to_read, nread, success = 0;
  8878. int64_t buffered_len;
  8879. double timeout = -1.0;
  8880. if (!conn) {
  8881. return 0;
  8882. }
  8883. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8884. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8885. }
  8886. expect = mg_get_header(conn, "Expect");
  8887. DEBUG_ASSERT(fp != NULL);
  8888. if (!fp) {
  8889. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8890. return 0;
  8891. }
  8892. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8893. /* Content length is not specified by the client. */
  8894. mg_send_http_error(conn,
  8895. 411,
  8896. "%s",
  8897. "Error: Client did not specify content length");
  8898. } else if ((expect != NULL)
  8899. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8900. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8901. */
  8902. mg_send_http_error(conn,
  8903. 417,
  8904. "Error: Can not fulfill expectation %s",
  8905. expect);
  8906. } else {
  8907. if (expect != NULL) {
  8908. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8909. conn->status_code = 100;
  8910. } else {
  8911. conn->status_code = 200;
  8912. }
  8913. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8914. - conn->consumed_content;
  8915. DEBUG_ASSERT(buffered_len >= 0);
  8916. DEBUG_ASSERT(conn->consumed_content == 0);
  8917. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8918. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8919. return 0;
  8920. }
  8921. if (buffered_len > 0) {
  8922. if ((int64_t)buffered_len > conn->content_len) {
  8923. buffered_len = (int)conn->content_len;
  8924. }
  8925. body = conn->buf + conn->request_len + conn->consumed_content;
  8926. push_all(
  8927. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8928. conn->consumed_content += buffered_len;
  8929. }
  8930. nread = 0;
  8931. while (conn->consumed_content < conn->content_len) {
  8932. to_read = sizeof(buf);
  8933. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8934. to_read = (int)(conn->content_len - conn->consumed_content);
  8935. }
  8936. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8937. if (nread == -2) {
  8938. /* error */
  8939. break;
  8940. }
  8941. if (nread > 0) {
  8942. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8943. != nread) {
  8944. break;
  8945. }
  8946. }
  8947. conn->consumed_content += nread;
  8948. }
  8949. if (conn->consumed_content == conn->content_len) {
  8950. success = (nread >= 0);
  8951. }
  8952. /* Each error code path in this function must send an error */
  8953. if (!success) {
  8954. /* NOTE: Maybe some data has already been sent. */
  8955. /* TODO (low): If some data has been sent, a correct error
  8956. * reply can no longer be sent, so just close the connection */
  8957. mg_send_http_error(conn, 500, "%s", "");
  8958. }
  8959. }
  8960. return success;
  8961. }
  8962. #endif
  8963. #if !defined(NO_CGI)
  8964. /* This structure helps to create an environment for the spawned CGI
  8965. * program.
  8966. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8967. * last element must be NULL.
  8968. * However, on Windows there is a requirement that all these
  8969. * VARIABLE=VALUE\0
  8970. * strings must reside in a contiguous buffer. The end of the buffer is
  8971. * marked by two '\0' characters.
  8972. * We satisfy both worlds: we create an envp array (which is vars), all
  8973. * entries are actually pointers inside buf. */
  8974. struct cgi_environment {
  8975. struct mg_connection *conn;
  8976. /* Data block */
  8977. char *buf; /* Environment buffer */
  8978. size_t buflen; /* Space available in buf */
  8979. size_t bufused; /* Space taken in buf */
  8980. /* Index block */
  8981. char **var; /* char **envp */
  8982. size_t varlen; /* Number of variables available in var */
  8983. size_t varused; /* Number of variables stored in var */
  8984. };
  8985. static void addenv(struct cgi_environment *env,
  8986. PRINTF_FORMAT_STRING(const char *fmt),
  8987. ...) PRINTF_ARGS(2, 3);
  8988. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8989. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8990. static void
  8991. addenv(struct cgi_environment *env, const char *fmt, ...)
  8992. {
  8993. size_t n, space;
  8994. int truncated = 0;
  8995. char *added;
  8996. va_list ap;
  8997. /* Calculate how much space is left in the buffer */
  8998. space = (env->buflen - env->bufused);
  8999. /* Calculate an estimate for the required space */
  9000. n = strlen(fmt) + 2 + 128;
  9001. do {
  9002. if (space <= n) {
  9003. /* Allocate new buffer */
  9004. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9005. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9006. if (!added) {
  9007. /* Out of memory */
  9008. mg_cry_internal(
  9009. env->conn,
  9010. "%s: Cannot allocate memory for CGI variable [%s]",
  9011. __func__,
  9012. fmt);
  9013. return;
  9014. }
  9015. env->buf = added;
  9016. env->buflen = n;
  9017. space = (env->buflen - env->bufused);
  9018. }
  9019. /* Make a pointer to the free space int the buffer */
  9020. added = env->buf + env->bufused;
  9021. /* Copy VARIABLE=VALUE\0 string into the free space */
  9022. va_start(ap, fmt);
  9023. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  9024. va_end(ap);
  9025. /* Do not add truncated strings to the environment */
  9026. if (truncated) {
  9027. /* Reallocate the buffer */
  9028. space = 0;
  9029. n = 1;
  9030. }
  9031. } while (truncated);
  9032. /* Calculate number of bytes added to the environment */
  9033. n = strlen(added) + 1;
  9034. env->bufused += n;
  9035. /* Now update the variable index */
  9036. space = (env->varlen - env->varused);
  9037. if (space < 2) {
  9038. mg_cry_internal(env->conn,
  9039. "%s: Cannot register CGI variable [%s]",
  9040. __func__,
  9041. fmt);
  9042. return;
  9043. }
  9044. /* Append a pointer to the added string into the envp array */
  9045. env->var[env->varused] = added;
  9046. env->varused++;
  9047. }
  9048. /* Return 0 on success, non-zero if an error occurs. */
  9049. static int
  9050. prepare_cgi_environment(struct mg_connection *conn,
  9051. const char *prog,
  9052. struct cgi_environment *env)
  9053. {
  9054. const char *s;
  9055. struct vec var_vec;
  9056. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9057. int i, truncated, uri_len;
  9058. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9059. return -1;
  9060. }
  9061. env->conn = conn;
  9062. env->buflen = CGI_ENVIRONMENT_SIZE;
  9063. env->bufused = 0;
  9064. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9065. if (env->buf == NULL) {
  9066. mg_cry_internal(conn,
  9067. "%s: Not enough memory for environmental buffer",
  9068. __func__);
  9069. return -1;
  9070. }
  9071. env->varlen = MAX_CGI_ENVIR_VARS;
  9072. env->varused = 0;
  9073. env->var =
  9074. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  9075. if (env->var == NULL) {
  9076. mg_cry_internal(conn,
  9077. "%s: Not enough memory for environmental variables",
  9078. __func__);
  9079. mg_free(env->buf);
  9080. return -1;
  9081. }
  9082. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9083. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9084. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9085. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9086. /* Prepare the environment block */
  9087. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9088. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9089. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9090. #if defined(USE_IPV6)
  9091. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9092. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9093. } else
  9094. #endif
  9095. {
  9096. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9097. }
  9098. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9099. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9100. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9101. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9102. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9103. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9104. /* SCRIPT_NAME */
  9105. uri_len = (int)strlen(conn->request_info.local_uri);
  9106. if (conn->path_info == NULL) {
  9107. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9108. /* URI: /path_to_script/script.cgi */
  9109. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9110. } else {
  9111. /* URI: /path_to_script/ ... using index.cgi */
  9112. const char *index_file = strrchr(prog, '/');
  9113. if (index_file) {
  9114. addenv(env,
  9115. "SCRIPT_NAME=%s%s",
  9116. conn->request_info.local_uri,
  9117. index_file + 1);
  9118. }
  9119. }
  9120. } else {
  9121. /* URI: /path_to_script/script.cgi/path_info */
  9122. addenv(env,
  9123. "SCRIPT_NAME=%.*s",
  9124. uri_len - (int)strlen(conn->path_info),
  9125. conn->request_info.local_uri);
  9126. }
  9127. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9128. if (conn->path_info == NULL) {
  9129. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9130. } else {
  9131. addenv(env,
  9132. "PATH_TRANSLATED=%s%s",
  9133. conn->dom_ctx->config[DOCUMENT_ROOT],
  9134. conn->path_info);
  9135. }
  9136. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9137. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9138. addenv(env, "CONTENT_TYPE=%s", s);
  9139. }
  9140. if (conn->request_info.query_string != NULL) {
  9141. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9142. }
  9143. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9144. addenv(env, "CONTENT_LENGTH=%s", s);
  9145. }
  9146. if ((s = getenv("PATH")) != NULL) {
  9147. addenv(env, "PATH=%s", s);
  9148. }
  9149. if (conn->path_info != NULL) {
  9150. addenv(env, "PATH_INFO=%s", conn->path_info);
  9151. }
  9152. if (conn->status_code > 0) {
  9153. /* CGI error handler should show the status code */
  9154. addenv(env, "STATUS=%d", conn->status_code);
  9155. }
  9156. #if defined(_WIN32)
  9157. if ((s = getenv("COMSPEC")) != NULL) {
  9158. addenv(env, "COMSPEC=%s", s);
  9159. }
  9160. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9161. addenv(env, "SYSTEMROOT=%s", s);
  9162. }
  9163. if ((s = getenv("SystemDrive")) != NULL) {
  9164. addenv(env, "SystemDrive=%s", s);
  9165. }
  9166. if ((s = getenv("ProgramFiles")) != NULL) {
  9167. addenv(env, "ProgramFiles=%s", s);
  9168. }
  9169. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9170. addenv(env, "ProgramFiles(x86)=%s", s);
  9171. }
  9172. #else
  9173. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9174. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9175. }
  9176. #endif /* _WIN32 */
  9177. if ((s = getenv("PERLLIB")) != NULL) {
  9178. addenv(env, "PERLLIB=%s", s);
  9179. }
  9180. if (conn->request_info.remote_user != NULL) {
  9181. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9182. addenv(env, "%s", "AUTH_TYPE=Digest");
  9183. }
  9184. /* Add all headers as HTTP_* variables */
  9185. for (i = 0; i < conn->request_info.num_headers; i++) {
  9186. (void)mg_snprintf(conn,
  9187. &truncated,
  9188. http_var_name,
  9189. sizeof(http_var_name),
  9190. "HTTP_%s",
  9191. conn->request_info.http_headers[i].name);
  9192. if (truncated) {
  9193. mg_cry_internal(conn,
  9194. "%s: HTTP header variable too long [%s]",
  9195. __func__,
  9196. conn->request_info.http_headers[i].name);
  9197. continue;
  9198. }
  9199. /* Convert variable name into uppercase, and change - to _ */
  9200. for (p = http_var_name; *p != '\0'; p++) {
  9201. if (*p == '-') {
  9202. *p = '_';
  9203. }
  9204. *p = (char)toupper(*(unsigned char *)p);
  9205. }
  9206. addenv(env,
  9207. "%s=%s",
  9208. http_var_name,
  9209. conn->request_info.http_headers[i].value);
  9210. }
  9211. /* Add user-specified variables */
  9212. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9213. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9214. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9215. }
  9216. env->var[env->varused] = NULL;
  9217. env->buf[env->bufused] = '\0';
  9218. return 0;
  9219. }
  9220. #if defined(USE_TIMERS)
  9221. #define TIMER_API static
  9222. #include "timer.inl"
  9223. static int
  9224. abort_process(void *data)
  9225. {
  9226. /* Waitpid checks for child status and won't work for a pid that does not
  9227. * identify a child of the current process. Thus, if the pid is reused,
  9228. * we will not affect a different process. */
  9229. pid_t pid = (pid_t)data;
  9230. int status = 0;
  9231. pid_t rpid = waitpid(pid, &status, WNOHANG);
  9232. if ((rpid != (pid_t)-1) && (status == 0)) {
  9233. /* Stop child process */
  9234. DEBUG_TRACE("CGI timer: Stop child process %p\n", pid);
  9235. kill(pid, SIGABRT);
  9236. /* Wait until process is terminated (don't leave zombies) */
  9237. while (waitpid(pid, &status, 0) != -1) /* nop */
  9238. ;
  9239. } else {
  9240. DEBUG_TRACE("CGI timer: Child process %p already stopped in time\n",
  9241. pid);
  9242. }
  9243. return 0;
  9244. }
  9245. #endif /* USE_TIMERS */
  9246. static void
  9247. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9248. {
  9249. char *buf;
  9250. size_t buflen;
  9251. int headers_len, data_len, i, truncated;
  9252. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9253. const char *status, *status_text, *connection_state;
  9254. char *pbuf, dir[PATH_MAX], *p;
  9255. struct mg_request_info ri;
  9256. struct cgi_environment blk;
  9257. FILE *in = NULL, *out = NULL, *err = NULL;
  9258. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9259. pid_t pid = (pid_t)-1;
  9260. if (conn == NULL) {
  9261. return;
  9262. }
  9263. buf = NULL;
  9264. buflen = conn->phys_ctx->max_request_size;
  9265. i = prepare_cgi_environment(conn, prog, &blk);
  9266. if (i != 0) {
  9267. blk.buf = NULL;
  9268. blk.var = NULL;
  9269. goto done;
  9270. }
  9271. /* CGI must be executed in its own directory. 'dir' must point to the
  9272. * directory containing executable program, 'p' must point to the
  9273. * executable program name relative to 'dir'. */
  9274. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9275. if (truncated) {
  9276. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9277. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9278. goto done;
  9279. }
  9280. if ((p = strrchr(dir, '/')) != NULL) {
  9281. *p++ = '\0';
  9282. } else {
  9283. dir[0] = '.';
  9284. dir[1] = '\0';
  9285. p = (char *)prog;
  9286. }
  9287. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9288. status = strerror(ERRNO);
  9289. mg_cry_internal(
  9290. conn,
  9291. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9292. prog,
  9293. status);
  9294. mg_send_http_error(conn,
  9295. 500,
  9296. "Error: Cannot create CGI pipe: %s",
  9297. status);
  9298. goto done;
  9299. }
  9300. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9301. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9302. if (pid == (pid_t)-1) {
  9303. status = strerror(ERRNO);
  9304. mg_cry_internal(
  9305. conn,
  9306. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9307. prog,
  9308. status);
  9309. mg_send_http_error(conn,
  9310. 500,
  9311. "Error: Cannot spawn CGI process [%s]: %s",
  9312. prog,
  9313. status);
  9314. goto done;
  9315. }
  9316. #if defined(USE_TIMERS)
  9317. // TODO (#618): set a timeout
  9318. timer_add(
  9319. conn->phys_ctx, /* one minute */ 60.0, 0.0, 1, abort_process, (void*)pid);
  9320. #endif
  9321. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  9322. */
  9323. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9324. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9325. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9326. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9327. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9328. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9329. /* Parent closes only one side of the pipes.
  9330. * If we don't mark them as closed, close() attempt before
  9331. * return from this function throws an exception on Windows.
  9332. * Windows does not like when closed descriptor is closed again. */
  9333. (void)close(fdin[0]);
  9334. (void)close(fdout[1]);
  9335. (void)close(fderr[1]);
  9336. fdin[0] = fdout[1] = fderr[1] = -1;
  9337. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9338. status = strerror(ERRNO);
  9339. mg_cry_internal(conn,
  9340. "Error: CGI program \"%s\": Can not open stdin: %s",
  9341. prog,
  9342. status);
  9343. mg_send_http_error(conn,
  9344. 500,
  9345. "Error: CGI can not open fdin\nfopen: %s",
  9346. status);
  9347. goto done;
  9348. }
  9349. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9350. status = strerror(ERRNO);
  9351. mg_cry_internal(conn,
  9352. "Error: CGI program \"%s\": Can not open stdout: %s",
  9353. prog,
  9354. status);
  9355. mg_send_http_error(conn,
  9356. 500,
  9357. "Error: CGI can not open fdout\nfopen: %s",
  9358. status);
  9359. goto done;
  9360. }
  9361. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9362. status = strerror(ERRNO);
  9363. mg_cry_internal(conn,
  9364. "Error: CGI program \"%s\": Can not open stderr: %s",
  9365. prog,
  9366. status);
  9367. mg_send_http_error(conn,
  9368. 500,
  9369. "Error: CGI can not open fderr\nfopen: %s",
  9370. status);
  9371. goto done;
  9372. }
  9373. setbuf(in, NULL);
  9374. setbuf(out, NULL);
  9375. setbuf(err, NULL);
  9376. fout.access.fp = out;
  9377. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9378. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9379. (signed long long)conn->request_info.content_length);
  9380. /* This is a POST/PUT request, or another request with body data. */
  9381. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9382. /* Error sending the body data */
  9383. mg_cry_internal(
  9384. conn,
  9385. "Error: CGI program \"%s\": Forward body data failed",
  9386. prog);
  9387. goto done;
  9388. }
  9389. }
  9390. /* Close so child gets an EOF. */
  9391. fclose(in);
  9392. in = NULL;
  9393. fdin[1] = -1;
  9394. /* Now read CGI reply into a buffer. We need to set correct
  9395. * status code, thus we need to see all HTTP headers first.
  9396. * Do not send anything back to client, until we buffer in all
  9397. * HTTP headers. */
  9398. data_len = 0;
  9399. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9400. if (buf == NULL) {
  9401. mg_send_http_error(conn,
  9402. 500,
  9403. "Error: Not enough memory for CGI buffer (%u bytes)",
  9404. (unsigned int)buflen);
  9405. mg_cry_internal(
  9406. conn,
  9407. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9408. "bytes)",
  9409. prog,
  9410. (unsigned int)buflen);
  9411. goto done;
  9412. }
  9413. DEBUG_TRACE("CGI: %s", "wait for response");
  9414. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9415. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9416. if (headers_len <= 0) {
  9417. /* Could not parse the CGI response. Check if some error message on
  9418. * stderr. */
  9419. i = pull_all(err, conn, buf, (int)buflen);
  9420. if (i > 0) {
  9421. /* CGI program explicitly sent an error */
  9422. /* Write the error message to the internal log */
  9423. mg_cry_internal(conn,
  9424. "Error: CGI program \"%s\" sent error "
  9425. "message: [%.*s]",
  9426. prog,
  9427. i,
  9428. buf);
  9429. /* Don't send the error message back to the client */
  9430. mg_send_http_error(conn,
  9431. 500,
  9432. "Error: CGI program \"%s\" failed.",
  9433. prog);
  9434. } else {
  9435. /* CGI program did not explicitly send an error, but a broken
  9436. * respon header */
  9437. mg_cry_internal(conn,
  9438. "Error: CGI program sent malformed or too big "
  9439. "(>%u bytes) HTTP headers: [%.*s]",
  9440. (unsigned)buflen,
  9441. data_len,
  9442. buf);
  9443. mg_send_http_error(conn,
  9444. 500,
  9445. "Error: CGI program sent malformed or too big "
  9446. "(>%u bytes) HTTP headers: [%.*s]",
  9447. (unsigned)buflen,
  9448. data_len,
  9449. buf);
  9450. }
  9451. /* in both cases, abort processing CGI */
  9452. goto done;
  9453. }
  9454. pbuf = buf;
  9455. buf[headers_len - 1] = '\0';
  9456. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9457. /* Make up and send the status line */
  9458. status_text = "OK";
  9459. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9460. != NULL) {
  9461. conn->status_code = atoi(status);
  9462. status_text = status;
  9463. while (isdigit(*(const unsigned char *)status_text)
  9464. || *status_text == ' ') {
  9465. status_text++;
  9466. }
  9467. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9468. != NULL) {
  9469. conn->status_code = 307;
  9470. } else {
  9471. conn->status_code = 200;
  9472. }
  9473. connection_state =
  9474. get_header(ri.http_headers, ri.num_headers, "Connection");
  9475. if (!header_has_option(connection_state, "keep-alive")) {
  9476. conn->must_close = 1;
  9477. }
  9478. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9479. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9480. /* Send headers */
  9481. for (i = 0; i < ri.num_headers; i++) {
  9482. mg_printf(conn,
  9483. "%s: %s\r\n",
  9484. ri.http_headers[i].name,
  9485. ri.http_headers[i].value);
  9486. }
  9487. mg_write(conn, "\r\n", 2);
  9488. /* Send chunk of data that may have been read after the headers */
  9489. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9490. /* Read the rest of CGI output and send to the client */
  9491. DEBUG_TRACE("CGI: %s", "forward all data");
  9492. send_file_data(conn, &fout, 0, INT64_MAX);
  9493. DEBUG_TRACE("CGI: %s", "all data sent");
  9494. done:
  9495. mg_free(blk.var);
  9496. mg_free(blk.buf);
  9497. #if defined(USE_TIMERS)
  9498. if (pid != (pid_t)-1) {
  9499. abort_process((void *)pid);
  9500. }
  9501. #endif /* USE_TIMERS */
  9502. if (fdin[0] != -1) {
  9503. close(fdin[0]);
  9504. }
  9505. if (fdout[1] != -1) {
  9506. close(fdout[1]);
  9507. }
  9508. if (in != NULL) {
  9509. fclose(in);
  9510. } else if (fdin[1] != -1) {
  9511. close(fdin[1]);
  9512. }
  9513. if (out != NULL) {
  9514. fclose(out);
  9515. } else if (fdout[0] != -1) {
  9516. close(fdout[0]);
  9517. }
  9518. if (err != NULL) {
  9519. fclose(err);
  9520. } else if (fderr[0] != -1) {
  9521. close(fderr[0]);
  9522. }
  9523. if (buf != NULL) {
  9524. mg_free(buf);
  9525. }
  9526. }
  9527. #endif /* !NO_CGI */
  9528. #if !defined(NO_FILES)
  9529. static void
  9530. mkcol(struct mg_connection *conn, const char *path)
  9531. {
  9532. int rc, body_len;
  9533. struct de de;
  9534. char date[64];
  9535. time_t curtime = time(NULL);
  9536. if (conn == NULL) {
  9537. return;
  9538. }
  9539. /* TODO (mid): Check the mg_send_http_error situations in this function
  9540. */
  9541. memset(&de.file, 0, sizeof(de.file));
  9542. if (!mg_stat(conn, path, &de.file)) {
  9543. mg_cry_internal(conn,
  9544. "%s: mg_stat(%s) failed: %s",
  9545. __func__,
  9546. path,
  9547. strerror(ERRNO));
  9548. }
  9549. if (de.file.last_modified) {
  9550. /* TODO (mid): This check does not seem to make any sense ! */
  9551. /* TODO (mid): Add a webdav unit test first, before changing
  9552. * anything here. */
  9553. mg_send_http_error(
  9554. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9555. return;
  9556. }
  9557. body_len = conn->data_len - conn->request_len;
  9558. if (body_len > 0) {
  9559. mg_send_http_error(
  9560. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9561. return;
  9562. }
  9563. rc = mg_mkdir(conn, path, 0755);
  9564. if (rc == 0) {
  9565. conn->status_code = 201;
  9566. gmt_time_string(date, sizeof(date), &curtime);
  9567. mg_printf(conn,
  9568. "HTTP/1.1 %d Created\r\n"
  9569. "Date: %s\r\n",
  9570. conn->status_code,
  9571. date);
  9572. send_static_cache_header(conn);
  9573. send_additional_header(conn);
  9574. mg_printf(conn,
  9575. "Content-Length: 0\r\n"
  9576. "Connection: %s\r\n\r\n",
  9577. suggest_connection_header(conn));
  9578. } else {
  9579. if (errno == EEXIST) {
  9580. mg_send_http_error(
  9581. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9582. } else if (errno == EACCES) {
  9583. mg_send_http_error(
  9584. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9585. } else if (errno == ENOENT) {
  9586. mg_send_http_error(
  9587. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9588. } else {
  9589. mg_send_http_error(
  9590. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9591. }
  9592. }
  9593. }
  9594. static void
  9595. put_file(struct mg_connection *conn, const char *path)
  9596. {
  9597. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9598. const char *range;
  9599. int64_t r1, r2;
  9600. int rc;
  9601. char date[64];
  9602. time_t curtime = time(NULL);
  9603. if (conn == NULL) {
  9604. return;
  9605. }
  9606. if (mg_stat(conn, path, &file.stat)) {
  9607. /* File already exists */
  9608. conn->status_code = 200;
  9609. if (file.stat.is_directory) {
  9610. /* This is an already existing directory,
  9611. * so there is nothing to do for the server. */
  9612. rc = 0;
  9613. } else {
  9614. /* File exists and is not a directory. */
  9615. /* Can it be replaced? */
  9616. #if defined(MG_USE_OPEN_FILE)
  9617. if (file.access.membuf != NULL) {
  9618. /* This is an "in-memory" file, that can not be replaced */
  9619. mg_send_http_error(conn,
  9620. 405,
  9621. "Error: Put not possible\nReplacing %s "
  9622. "is not supported",
  9623. path);
  9624. return;
  9625. }
  9626. #endif
  9627. /* Check if the server may write this file */
  9628. if (access(path, W_OK) == 0) {
  9629. /* Access granted */
  9630. conn->status_code = 200;
  9631. rc = 1;
  9632. } else {
  9633. mg_send_http_error(
  9634. conn,
  9635. 403,
  9636. "Error: Put not possible\nReplacing %s is not allowed",
  9637. path);
  9638. return;
  9639. }
  9640. }
  9641. } else {
  9642. /* File should be created */
  9643. conn->status_code = 201;
  9644. rc = put_dir(conn, path);
  9645. }
  9646. if (rc == 0) {
  9647. /* put_dir returns 0 if path is a directory */
  9648. gmt_time_string(date, sizeof(date), &curtime);
  9649. mg_printf(conn,
  9650. "HTTP/1.1 %d %s\r\n",
  9651. conn->status_code,
  9652. mg_get_response_code_text(NULL, conn->status_code));
  9653. send_no_cache_header(conn);
  9654. send_additional_header(conn);
  9655. mg_printf(conn,
  9656. "Date: %s\r\n"
  9657. "Content-Length: 0\r\n"
  9658. "Connection: %s\r\n\r\n",
  9659. date,
  9660. suggest_connection_header(conn));
  9661. /* Request to create a directory has been fulfilled successfully.
  9662. * No need to put a file. */
  9663. return;
  9664. }
  9665. if (rc == -1) {
  9666. /* put_dir returns -1 if the path is too long */
  9667. mg_send_http_error(conn,
  9668. 414,
  9669. "Error: Path too long\nput_dir(%s): %s",
  9670. path,
  9671. strerror(ERRNO));
  9672. return;
  9673. }
  9674. if (rc == -2) {
  9675. /* put_dir returns -2 if the directory can not be created */
  9676. mg_send_http_error(conn,
  9677. 500,
  9678. "Error: Can not create directory\nput_dir(%s): %s",
  9679. path,
  9680. strerror(ERRNO));
  9681. return;
  9682. }
  9683. /* A file should be created or overwritten. */
  9684. /* Currently CivetWeb does not nead read+write access. */
  9685. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9686. || file.access.fp == NULL) {
  9687. (void)mg_fclose(&file.access);
  9688. mg_send_http_error(conn,
  9689. 500,
  9690. "Error: Can not create file\nfopen(%s): %s",
  9691. path,
  9692. strerror(ERRNO));
  9693. return;
  9694. }
  9695. fclose_on_exec(&file.access, conn);
  9696. range = mg_get_header(conn, "Content-Range");
  9697. r1 = r2 = 0;
  9698. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9699. conn->status_code = 206; /* Partial content */
  9700. fseeko(file.access.fp, r1, SEEK_SET);
  9701. }
  9702. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9703. /* forward_body_data failed.
  9704. * The error code has already been sent to the client,
  9705. * and conn->status_code is already set. */
  9706. (void)mg_fclose(&file.access);
  9707. return;
  9708. }
  9709. if (mg_fclose(&file.access) != 0) {
  9710. /* fclose failed. This might have different reasons, but a likely
  9711. * one is "no space on disk", http 507. */
  9712. conn->status_code = 507;
  9713. }
  9714. gmt_time_string(date, sizeof(date), &curtime);
  9715. mg_printf(conn,
  9716. "HTTP/1.1 %d %s\r\n",
  9717. conn->status_code,
  9718. mg_get_response_code_text(NULL, conn->status_code));
  9719. send_no_cache_header(conn);
  9720. send_additional_header(conn);
  9721. mg_printf(conn,
  9722. "Date: %s\r\n"
  9723. "Content-Length: 0\r\n"
  9724. "Connection: %s\r\n\r\n",
  9725. date,
  9726. suggest_connection_header(conn));
  9727. }
  9728. static void
  9729. delete_file(struct mg_connection *conn, const char *path)
  9730. {
  9731. struct de de;
  9732. memset(&de.file, 0, sizeof(de.file));
  9733. if (!mg_stat(conn, path, &de.file)) {
  9734. /* mg_stat returns 0 if the file does not exist */
  9735. mg_send_http_error(conn,
  9736. 404,
  9737. "Error: Cannot delete file\nFile %s not found",
  9738. path);
  9739. return;
  9740. }
  9741. #if 0 /* Ignore if a file in memory is inside a folder */
  9742. if (de.access.membuf != NULL) {
  9743. /* the file is cached in memory */
  9744. mg_send_http_error(
  9745. conn,
  9746. 405,
  9747. "Error: Delete not possible\nDeleting %s is not supported",
  9748. path);
  9749. return;
  9750. }
  9751. #endif
  9752. if (de.file.is_directory) {
  9753. if (remove_directory(conn, path)) {
  9754. /* Delete is successful: Return 204 without content. */
  9755. mg_send_http_error(conn, 204, "%s", "");
  9756. } else {
  9757. /* Delete is not successful: Return 500 (Server error). */
  9758. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9759. }
  9760. return;
  9761. }
  9762. /* This is an existing file (not a directory).
  9763. * Check if write permission is granted. */
  9764. if (access(path, W_OK) != 0) {
  9765. /* File is read only */
  9766. mg_send_http_error(
  9767. conn,
  9768. 403,
  9769. "Error: Delete not possible\nDeleting %s is not allowed",
  9770. path);
  9771. return;
  9772. }
  9773. /* Try to delete it. */
  9774. if (mg_remove(conn, path) == 0) {
  9775. /* Delete was successful: Return 204 without content. */
  9776. mg_send_http_error(conn, 204, "%s", "");
  9777. } else {
  9778. /* Delete not successful (file locked). */
  9779. mg_send_http_error(conn,
  9780. 423,
  9781. "Error: Cannot delete file\nremove(%s): %s",
  9782. path,
  9783. strerror(ERRNO));
  9784. }
  9785. }
  9786. #endif /* !NO_FILES */
  9787. static void
  9788. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9789. static void
  9790. do_ssi_include(struct mg_connection *conn,
  9791. const char *ssi,
  9792. char *tag,
  9793. int include_level)
  9794. {
  9795. char file_name[MG_BUF_LEN], path[512], *p;
  9796. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9797. size_t len;
  9798. int truncated = 0;
  9799. if (conn == NULL) {
  9800. return;
  9801. }
  9802. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9803. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9804. * always < MG_BUF_LEN. */
  9805. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9806. /* File name is relative to the webserver root */
  9807. file_name[511] = 0;
  9808. (void)mg_snprintf(conn,
  9809. &truncated,
  9810. path,
  9811. sizeof(path),
  9812. "%s/%s",
  9813. conn->dom_ctx->config[DOCUMENT_ROOT],
  9814. file_name);
  9815. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9816. /* File name is relative to the webserver working directory
  9817. * or it is absolute system path */
  9818. file_name[511] = 0;
  9819. (void)
  9820. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9821. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9822. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9823. /* File name is relative to the currect document */
  9824. file_name[511] = 0;
  9825. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9826. if (!truncated) {
  9827. if ((p = strrchr(path, '/')) != NULL) {
  9828. p[1] = '\0';
  9829. }
  9830. len = strlen(path);
  9831. (void)mg_snprintf(conn,
  9832. &truncated,
  9833. path + len,
  9834. sizeof(path) - len,
  9835. "%s",
  9836. file_name);
  9837. }
  9838. } else {
  9839. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9840. return;
  9841. }
  9842. if (truncated) {
  9843. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9844. return;
  9845. }
  9846. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9847. mg_cry_internal(conn,
  9848. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9849. tag,
  9850. path,
  9851. strerror(ERRNO));
  9852. } else {
  9853. fclose_on_exec(&file.access, conn);
  9854. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9855. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9856. path) > 0) {
  9857. send_ssi_file(conn, path, &file, include_level + 1);
  9858. } else {
  9859. send_file_data(conn, &file, 0, INT64_MAX);
  9860. }
  9861. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9862. }
  9863. }
  9864. #if !defined(NO_POPEN)
  9865. static void
  9866. do_ssi_exec(struct mg_connection *conn, char *tag)
  9867. {
  9868. char cmd[1024] = "";
  9869. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9870. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9871. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9872. } else {
  9873. cmd[1023] = 0;
  9874. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9875. mg_cry_internal(conn,
  9876. "Cannot SSI #exec: [%s]: %s",
  9877. cmd,
  9878. strerror(ERRNO));
  9879. } else {
  9880. send_file_data(conn, &file, 0, INT64_MAX);
  9881. pclose(file.access.fp);
  9882. }
  9883. }
  9884. }
  9885. #endif /* !NO_POPEN */
  9886. static int
  9887. mg_fgetc(struct mg_file *filep, int offset)
  9888. {
  9889. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  9890. if (filep == NULL) {
  9891. return EOF;
  9892. }
  9893. #if defined(MG_USE_OPEN_FILE)
  9894. if ((filep->access.membuf != NULL) && (offset >= 0)
  9895. && (((unsigned int)(offset)) < filep->stat.size)) {
  9896. return ((const unsigned char *)filep->access.membuf)[offset];
  9897. } else /* else block below */
  9898. #endif
  9899. if (filep->access.fp != NULL) {
  9900. return fgetc(filep->access.fp);
  9901. } else {
  9902. return EOF;
  9903. }
  9904. }
  9905. static void
  9906. send_ssi_file(struct mg_connection *conn,
  9907. const char *path,
  9908. struct mg_file *filep,
  9909. int include_level)
  9910. {
  9911. char buf[MG_BUF_LEN];
  9912. int ch, offset, len, in_tag, in_ssi_tag;
  9913. if (include_level > 10) {
  9914. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  9915. return;
  9916. }
  9917. in_tag = in_ssi_tag = len = offset = 0;
  9918. /* Read file, byte by byte, and look for SSI include tags */
  9919. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9920. if (in_tag) {
  9921. /* We are in a tag, either SSI tag or html tag */
  9922. if (ch == '>') {
  9923. /* Tag is closing */
  9924. buf[len++] = '>';
  9925. if (in_ssi_tag) {
  9926. /* Handle SSI tag */
  9927. buf[len] = 0;
  9928. if (!memcmp(buf + 5, "include", 7)) {
  9929. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9930. #if !defined(NO_POPEN)
  9931. } else if (!memcmp(buf + 5, "exec", 4)) {
  9932. do_ssi_exec(conn, buf + 9);
  9933. #endif /* !NO_POPEN */
  9934. } else {
  9935. mg_cry_internal(conn,
  9936. "%s: unknown SSI "
  9937. "command: \"%s\"",
  9938. path,
  9939. buf);
  9940. }
  9941. len = 0;
  9942. in_ssi_tag = in_tag = 0;
  9943. } else {
  9944. /* Not an SSI tag */
  9945. /* Flush buffer */
  9946. (void)mg_write(conn, buf, (size_t)len);
  9947. len = 0;
  9948. in_tag = 0;
  9949. }
  9950. } else {
  9951. /* Tag is still open */
  9952. buf[len++] = (char)(ch & 0xff);
  9953. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9954. /* All SSI tags start with <!--# */
  9955. in_ssi_tag = 1;
  9956. }
  9957. if ((len + 2) > (int)sizeof(buf)) {
  9958. /* Tag to long for buffer */
  9959. mg_cry_internal(conn, "%s: tag is too large", path);
  9960. return;
  9961. }
  9962. }
  9963. } else {
  9964. /* We are not in a tag yet. */
  9965. if (ch == '<') {
  9966. /* Tag is opening */
  9967. in_tag = 1;
  9968. if (len > 0) {
  9969. /* Flush current buffer.
  9970. * Buffer is filled with "len" bytes. */
  9971. (void)mg_write(conn, buf, (size_t)len);
  9972. }
  9973. /* Store the < */
  9974. len = 1;
  9975. buf[0] = '<';
  9976. } else {
  9977. /* No Tag */
  9978. /* Add data to buffer */
  9979. buf[len++] = (char)(ch & 0xff);
  9980. /* Flush if buffer is full */
  9981. if (len == (int)sizeof(buf)) {
  9982. mg_write(conn, buf, (size_t)len);
  9983. len = 0;
  9984. }
  9985. }
  9986. }
  9987. }
  9988. /* Send the rest of buffered data */
  9989. if (len > 0) {
  9990. mg_write(conn, buf, (size_t)len);
  9991. }
  9992. }
  9993. static void
  9994. handle_ssi_file_request(struct mg_connection *conn,
  9995. const char *path,
  9996. struct mg_file *filep)
  9997. {
  9998. char date[64];
  9999. time_t curtime = time(NULL);
  10000. const char *cors1, *cors2, *cors3;
  10001. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10002. return;
  10003. }
  10004. if (mg_get_header(conn, "Origin")) {
  10005. /* Cross-origin resource sharing (CORS). */
  10006. cors1 = "Access-Control-Allow-Origin: ";
  10007. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10008. cors3 = "\r\n";
  10009. } else {
  10010. cors1 = cors2 = cors3 = "";
  10011. }
  10012. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10013. /* File exists (precondition for calling this function),
  10014. * but can not be opened by the server. */
  10015. mg_send_http_error(conn,
  10016. 500,
  10017. "Error: Cannot read file\nfopen(%s): %s",
  10018. path,
  10019. strerror(ERRNO));
  10020. } else {
  10021. conn->must_close = 1;
  10022. gmt_time_string(date, sizeof(date), &curtime);
  10023. fclose_on_exec(&filep->access, conn);
  10024. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10025. send_no_cache_header(conn);
  10026. send_additional_header(conn);
  10027. mg_printf(conn,
  10028. "%s%s%s"
  10029. "Date: %s\r\n"
  10030. "Content-Type: text/html\r\n"
  10031. "Connection: %s\r\n\r\n",
  10032. cors1,
  10033. cors2,
  10034. cors3,
  10035. date,
  10036. suggest_connection_header(conn));
  10037. send_ssi_file(conn, path, filep, 0);
  10038. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10039. }
  10040. }
  10041. #if !defined(NO_FILES)
  10042. static void
  10043. send_options(struct mg_connection *conn)
  10044. {
  10045. char date[64];
  10046. time_t curtime = time(NULL);
  10047. if (!conn) {
  10048. return;
  10049. }
  10050. conn->status_code = 200;
  10051. conn->must_close = 1;
  10052. gmt_time_string(date, sizeof(date), &curtime);
  10053. /* We do not set a "Cache-Control" header here, but leave the default.
  10054. * Since browsers do not send an OPTIONS request, we can not test the
  10055. * effect anyway. */
  10056. mg_printf(conn,
  10057. "HTTP/1.1 200 OK\r\n"
  10058. "Date: %s\r\n"
  10059. "Connection: %s\r\n"
  10060. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10061. "PROPFIND, MKCOL\r\n"
  10062. "DAV: 1\r\n",
  10063. date,
  10064. suggest_connection_header(conn));
  10065. send_additional_header(conn);
  10066. mg_printf(conn, "\r\n");
  10067. }
  10068. /* Writes PROPFIND properties for a collection element */
  10069. static void
  10070. print_props(struct mg_connection *conn,
  10071. const char *uri,
  10072. struct mg_file_stat *filep)
  10073. {
  10074. char mtime[64];
  10075. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  10076. return;
  10077. }
  10078. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10079. mg_printf(conn,
  10080. "<d:response>"
  10081. "<d:href>%s</d:href>"
  10082. "<d:propstat>"
  10083. "<d:prop>"
  10084. "<d:resourcetype>%s</d:resourcetype>"
  10085. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10086. "<d:getlastmodified>%s</d:getlastmodified>"
  10087. "</d:prop>"
  10088. "<d:status>HTTP/1.1 200 OK</d:status>"
  10089. "</d:propstat>"
  10090. "</d:response>\n",
  10091. uri,
  10092. filep->is_directory ? "<d:collection/>" : "",
  10093. filep->size,
  10094. mtime);
  10095. }
  10096. static int
  10097. print_dav_dir_entry(struct de *de, void *data)
  10098. {
  10099. char href[PATH_MAX];
  10100. int truncated;
  10101. struct mg_connection *conn = (struct mg_connection *)data;
  10102. if (!de || !conn) {
  10103. return -1;
  10104. }
  10105. mg_snprintf(conn,
  10106. &truncated,
  10107. href,
  10108. sizeof(href),
  10109. "%s%s",
  10110. conn->request_info.local_uri,
  10111. de->file_name);
  10112. if (!truncated) {
  10113. size_t href_encoded_size;
  10114. char *href_encoded;
  10115. href_encoded_size = PATH_MAX * 3; /* worst case */
  10116. href_encoded = (char *)mg_malloc(href_encoded_size);
  10117. if (href_encoded == NULL) {
  10118. return -1;
  10119. }
  10120. mg_url_encode(href, href_encoded, href_encoded_size);
  10121. print_props(conn, href_encoded, &de->file);
  10122. mg_free(href_encoded);
  10123. }
  10124. return 0;
  10125. }
  10126. static void
  10127. handle_propfind(struct mg_connection *conn,
  10128. const char *path,
  10129. struct mg_file_stat *filep)
  10130. {
  10131. const char *depth = mg_get_header(conn, "Depth");
  10132. char date[64];
  10133. time_t curtime = time(NULL);
  10134. gmt_time_string(date, sizeof(date), &curtime);
  10135. if (!conn || !path || !filep || !conn->dom_ctx) {
  10136. return;
  10137. }
  10138. conn->must_close = 1;
  10139. conn->status_code = 207;
  10140. mg_printf(conn,
  10141. "HTTP/1.1 207 Multi-Status\r\n"
  10142. "Date: %s\r\n",
  10143. date);
  10144. send_static_cache_header(conn);
  10145. send_additional_header(conn);
  10146. mg_printf(conn,
  10147. "Connection: %s\r\n"
  10148. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10149. suggest_connection_header(conn));
  10150. mg_printf(conn,
  10151. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10152. "<d:multistatus xmlns:d='DAV:'>\n");
  10153. /* Print properties for the requested resource itself */
  10154. print_props(conn, conn->request_info.local_uri, filep);
  10155. /* If it is a directory, print directory entries too if Depth is not 0
  10156. */
  10157. if (filep->is_directory
  10158. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10159. "yes")
  10160. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10161. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10162. }
  10163. mg_printf(conn, "%s\n", "</d:multistatus>");
  10164. }
  10165. #endif
  10166. void
  10167. mg_lock_connection(struct mg_connection *conn)
  10168. {
  10169. if (conn) {
  10170. (void)pthread_mutex_lock(&conn->mutex);
  10171. }
  10172. }
  10173. void
  10174. mg_unlock_connection(struct mg_connection *conn)
  10175. {
  10176. if (conn) {
  10177. (void)pthread_mutex_unlock(&conn->mutex);
  10178. }
  10179. }
  10180. void
  10181. mg_lock_context(struct mg_context *ctx)
  10182. {
  10183. if (ctx) {
  10184. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10185. }
  10186. }
  10187. void
  10188. mg_unlock_context(struct mg_context *ctx)
  10189. {
  10190. if (ctx) {
  10191. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10192. }
  10193. }
  10194. #if defined(USE_LUA)
  10195. #include "mod_lua.inl"
  10196. #endif /* USE_LUA */
  10197. #if defined(USE_DUKTAPE)
  10198. #include "mod_duktape.inl"
  10199. #endif /* USE_DUKTAPE */
  10200. #if defined(USE_WEBSOCKET)
  10201. #if !defined(NO_SSL_DL)
  10202. #define SHA_API static
  10203. #include "sha1.inl"
  10204. #endif
  10205. static int
  10206. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10207. {
  10208. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10209. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10210. SHA_CTX sha_ctx;
  10211. int truncated;
  10212. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10213. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10214. if (truncated) {
  10215. conn->must_close = 1;
  10216. return 0;
  10217. }
  10218. DEBUG_TRACE("%s", "Send websocket handshake");
  10219. SHA1_Init(&sha_ctx);
  10220. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10221. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10222. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10223. mg_printf(conn,
  10224. "HTTP/1.1 101 Switching Protocols\r\n"
  10225. "Upgrade: websocket\r\n"
  10226. "Connection: Upgrade\r\n"
  10227. "Sec-WebSocket-Accept: %s\r\n",
  10228. b64_sha);
  10229. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10230. mg_printf(conn,
  10231. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10232. conn->request_info.acceptedWebSocketSubprotocol);
  10233. } else {
  10234. mg_printf(conn, "%s", "\r\n");
  10235. }
  10236. return 1;
  10237. }
  10238. #if !defined(MG_MAX_UNANSWERED_PING)
  10239. /* Configuration of the maximum number of websocket PINGs that might
  10240. * stay unanswered before the connection is considered broken.
  10241. * Note: The name of this define may still change (until it is
  10242. * defined as a compile parameter in a documentation).
  10243. */
  10244. #define MG_MAX_UNANSWERED_PING (5)
  10245. #endif
  10246. static void
  10247. read_websocket(struct mg_connection *conn,
  10248. mg_websocket_data_handler ws_data_handler,
  10249. void *callback_data)
  10250. {
  10251. /* Pointer to the beginning of the portion of the incoming websocket
  10252. * message queue.
  10253. * The original websocket upgrade request is never removed, so the queue
  10254. * begins after it. */
  10255. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10256. int n, error, exit_by_callback;
  10257. int ret;
  10258. /* body_len is the length of the entire queue in bytes
  10259. * len is the length of the current message
  10260. * data_len is the length of the current message's data payload
  10261. * header_len is the length of the current message's header */
  10262. size_t i, len, mask_len = 0, header_len, body_len;
  10263. uint64_t data_len = 0;
  10264. /* "The masking key is a 32-bit value chosen at random by the client."
  10265. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10266. */
  10267. unsigned char mask[4];
  10268. /* data points to the place where the message is stored when passed to
  10269. * the websocket_data callback. This is either mem on the stack, or a
  10270. * dynamically allocated buffer if it is too large. */
  10271. unsigned char mem[4096];
  10272. unsigned char mop; /* mask flag and opcode */
  10273. /* Variables used for connection monitoring */
  10274. double timeout = -1.0;
  10275. int enable_ping_pong = 0;
  10276. int ping_count = 0;
  10277. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10278. enable_ping_pong =
  10279. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10280. "yes");
  10281. }
  10282. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10283. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10284. }
  10285. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10286. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10287. }
  10288. /* Enter data processing loop */
  10289. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10290. conn->request_info.remote_addr,
  10291. conn->request_info.remote_port);
  10292. conn->in_websocket_handling = 1;
  10293. mg_set_thread_name("wsock");
  10294. /* Loop continuously, reading messages from the socket, invoking the
  10295. * callback, and waiting repeatedly until an error occurs. */
  10296. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10297. header_len = 0;
  10298. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10299. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10300. len = buf[1] & 127;
  10301. mask_len = (buf[1] & 128) ? 4 : 0;
  10302. if ((len < 126) && (body_len >= mask_len)) {
  10303. /* inline 7-bit length field */
  10304. data_len = len;
  10305. header_len = 2 + mask_len;
  10306. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10307. /* 16-bit length field */
  10308. header_len = 4 + mask_len;
  10309. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10310. } else if (body_len >= (10 + mask_len)) {
  10311. /* 64-bit length field */
  10312. uint32_t l1, l2;
  10313. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10314. memcpy(&l2, &buf[6], 4);
  10315. header_len = 10 + mask_len;
  10316. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10317. if (data_len > (uint64_t)0x7FFF0000ul) {
  10318. /* no can do */
  10319. mg_cry_internal(
  10320. conn,
  10321. "%s",
  10322. "websocket out of memory; closing connection");
  10323. break;
  10324. }
  10325. }
  10326. }
  10327. if ((header_len > 0) && (body_len >= header_len)) {
  10328. /* Allocate space to hold websocket payload */
  10329. unsigned char *data = mem;
  10330. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10331. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10332. conn->phys_ctx);
  10333. if (data == NULL) {
  10334. /* Allocation failed, exit the loop and then close the
  10335. * connection */
  10336. mg_cry_internal(
  10337. conn,
  10338. "%s",
  10339. "websocket out of memory; closing connection");
  10340. break;
  10341. }
  10342. }
  10343. /* Copy the mask before we shift the queue and destroy it */
  10344. if (mask_len > 0) {
  10345. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10346. } else {
  10347. memset(mask, 0, sizeof(mask));
  10348. }
  10349. /* Read frame payload from the first message in the queue into
  10350. * data and advance the queue by moving the memory in place. */
  10351. DEBUG_ASSERT(body_len >= header_len);
  10352. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10353. mop = buf[0]; /* current mask and opcode */
  10354. /* Overflow case */
  10355. len = body_len - header_len;
  10356. memcpy(data, buf + header_len, len);
  10357. error = 0;
  10358. while ((uint64_t)len < data_len) {
  10359. n = pull_inner(NULL,
  10360. conn,
  10361. (char *)(data + len),
  10362. (int)(data_len - len),
  10363. timeout);
  10364. if (n <= -2) {
  10365. error = 1;
  10366. break;
  10367. } else if (n > 0) {
  10368. len += (size_t)n;
  10369. } else {
  10370. /* Timeout: should retry */
  10371. /* TODO: retry condition */
  10372. }
  10373. }
  10374. if (error) {
  10375. mg_cry_internal(
  10376. conn,
  10377. "%s",
  10378. "Websocket pull failed; closing connection");
  10379. if (data != mem) {
  10380. mg_free(data);
  10381. }
  10382. break;
  10383. }
  10384. conn->data_len = conn->request_len;
  10385. } else {
  10386. mop = buf[0]; /* current mask and opcode, overwritten by
  10387. * memmove() */
  10388. /* Length of the message being read at the front of the
  10389. * queue. Cast to 31 bit is OK, since we limited
  10390. * data_len before. */
  10391. len = (size_t)data_len + header_len;
  10392. /* Copy the data payload into the data pointer for the
  10393. * callback. Cast to 31 bit is OK, since we
  10394. * limited data_len */
  10395. memcpy(data, buf + header_len, (size_t)data_len);
  10396. /* Move the queue forward len bytes */
  10397. memmove(buf, buf + len, body_len - len);
  10398. /* Mark the queue as advanced */
  10399. conn->data_len -= (int)len;
  10400. }
  10401. /* Apply mask if necessary */
  10402. if (mask_len > 0) {
  10403. for (i = 0; i < (size_t)data_len; i++) {
  10404. data[i] ^= mask[i & 3];
  10405. }
  10406. }
  10407. exit_by_callback = 0;
  10408. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10409. /* filter PONG messages */
  10410. DEBUG_TRACE("PONG from %s:%u",
  10411. conn->request_info.remote_addr,
  10412. conn->request_info.remote_port);
  10413. /* No unanwered PINGs left */
  10414. ping_count = 0;
  10415. } else if (enable_ping_pong
  10416. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10417. /* reply PING messages */
  10418. DEBUG_TRACE("Reply PING from %s:%u",
  10419. conn->request_info.remote_addr,
  10420. conn->request_info.remote_port);
  10421. ret = mg_websocket_write(conn,
  10422. MG_WEBSOCKET_OPCODE_PONG,
  10423. (char *)data,
  10424. (size_t)data_len);
  10425. if (ret <= 0) {
  10426. /* Error: send failed */
  10427. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10428. break;
  10429. }
  10430. } else {
  10431. /* Exit the loop if callback signals to exit (server side),
  10432. * or "connection close" opcode received (client side). */
  10433. if ((ws_data_handler != NULL)
  10434. && !ws_data_handler(conn,
  10435. mop,
  10436. (char *)data,
  10437. (size_t)data_len,
  10438. callback_data)) {
  10439. exit_by_callback = 1;
  10440. }
  10441. }
  10442. /* It a buffer has been allocated, free it again */
  10443. if (data != mem) {
  10444. mg_free(data);
  10445. }
  10446. if (exit_by_callback) {
  10447. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10448. conn->request_info.remote_addr,
  10449. conn->request_info.remote_port);
  10450. break;
  10451. }
  10452. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10453. /* Opcode == 8, connection close */
  10454. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10455. conn->request_info.remote_addr,
  10456. conn->request_info.remote_port);
  10457. break;
  10458. }
  10459. /* Not breaking the loop, process next websocket frame. */
  10460. } else {
  10461. /* Read from the socket into the next available location in the
  10462. * message queue. */
  10463. n = pull_inner(NULL,
  10464. conn,
  10465. conn->buf + conn->data_len,
  10466. conn->buf_size - conn->data_len,
  10467. timeout);
  10468. if (n <= -2) {
  10469. /* Error, no bytes read */
  10470. DEBUG_TRACE("PULL from %s:%u failed",
  10471. conn->request_info.remote_addr,
  10472. conn->request_info.remote_port);
  10473. break;
  10474. }
  10475. if (n > 0) {
  10476. conn->data_len += n;
  10477. /* Reset open PING count */
  10478. ping_count = 0;
  10479. } else {
  10480. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10481. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10482. /* Stop sending PING */
  10483. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10484. "- closing connection",
  10485. ping_count,
  10486. conn->request_info.remote_addr,
  10487. conn->request_info.remote_port);
  10488. break;
  10489. }
  10490. if (enable_ping_pong) {
  10491. /* Send Websocket PING message */
  10492. DEBUG_TRACE("PING to %s:%u",
  10493. conn->request_info.remote_addr,
  10494. conn->request_info.remote_port);
  10495. ret = mg_websocket_write(conn,
  10496. MG_WEBSOCKET_OPCODE_PING,
  10497. NULL,
  10498. 0);
  10499. if (ret <= 0) {
  10500. /* Error: send failed */
  10501. DEBUG_TRACE("Send PING failed (%i)", ret);
  10502. break;
  10503. }
  10504. ping_count++;
  10505. }
  10506. }
  10507. /* Timeout: should retry */
  10508. /* TODO: get timeout def */
  10509. }
  10510. }
  10511. }
  10512. /* Leave data processing loop */
  10513. mg_set_thread_name("worker");
  10514. conn->in_websocket_handling = 0;
  10515. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10516. conn->request_info.remote_addr,
  10517. conn->request_info.remote_port);
  10518. }
  10519. static int
  10520. mg_websocket_write_exec(struct mg_connection *conn,
  10521. int opcode,
  10522. const char *data,
  10523. size_t dataLen,
  10524. uint32_t masking_key)
  10525. {
  10526. unsigned char header[14];
  10527. size_t headerLen;
  10528. int retval;
  10529. #if defined(__GNUC__) || defined(__MINGW32__)
  10530. /* Disable spurious conversion warning for GCC */
  10531. #pragma GCC diagnostic push
  10532. #pragma GCC diagnostic ignored "-Wconversion"
  10533. #endif
  10534. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10535. #if defined(__GNUC__) || defined(__MINGW32__)
  10536. #pragma GCC diagnostic pop
  10537. #endif
  10538. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10539. if (dataLen < 126) {
  10540. /* inline 7-bit length field */
  10541. header[1] = (unsigned char)dataLen;
  10542. headerLen = 2;
  10543. } else if (dataLen <= 0xFFFF) {
  10544. /* 16-bit length field */
  10545. uint16_t len = htons((uint16_t)dataLen);
  10546. header[1] = 126;
  10547. memcpy(header + 2, &len, 2);
  10548. headerLen = 4;
  10549. } else {
  10550. /* 64-bit length field */
  10551. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10552. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10553. header[1] = 127;
  10554. memcpy(header + 2, &len1, 4);
  10555. memcpy(header + 6, &len2, 4);
  10556. headerLen = 10;
  10557. }
  10558. if (masking_key) {
  10559. /* add mask */
  10560. header[1] |= 0x80;
  10561. memcpy(header + headerLen, &masking_key, 4);
  10562. headerLen += 4;
  10563. }
  10564. /* Note that POSIX/Winsock's send() is threadsafe
  10565. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10566. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10567. * push(), although that is only a problem if the packet is large or
  10568. * outgoing buffer is full). */
  10569. /* TODO: Check if this lock should be moved to user land.
  10570. * Currently the server sets this lock for websockets, but
  10571. * not for any other connection. It must be set for every
  10572. * conn read/written by more than one thread, no matter if
  10573. * it is a websocket or regular connection. */
  10574. (void)mg_lock_connection(conn);
  10575. retval = mg_write(conn, header, headerLen);
  10576. if (retval != (int)headerLen) {
  10577. /* Did not send complete header */
  10578. retval = -1;
  10579. } else {
  10580. if (dataLen > 0) {
  10581. retval = mg_write(conn, data, dataLen);
  10582. }
  10583. /* if dataLen == 0, the header length (2) is returned */
  10584. }
  10585. /* TODO: Remove this unlock as well, when lock is removed. */
  10586. mg_unlock_connection(conn);
  10587. return retval;
  10588. }
  10589. int
  10590. mg_websocket_write(struct mg_connection *conn,
  10591. int opcode,
  10592. const char *data,
  10593. size_t dataLen)
  10594. {
  10595. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10596. }
  10597. static void
  10598. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10599. {
  10600. size_t i = 0;
  10601. i = 0;
  10602. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10603. /* Convert in 32 bit words, if data is 4 byte aligned */
  10604. while (i < (in_len - 3)) {
  10605. *(uint32_t *)(void *)(out + i) =
  10606. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10607. i += 4;
  10608. }
  10609. }
  10610. if (i != in_len) {
  10611. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10612. while (i < in_len) {
  10613. *(uint8_t *)(void *)(out + i) =
  10614. *(uint8_t *)(void *)(in + i)
  10615. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10616. i++;
  10617. }
  10618. }
  10619. }
  10620. int
  10621. mg_websocket_client_write(struct mg_connection *conn,
  10622. int opcode,
  10623. const char *data,
  10624. size_t dataLen)
  10625. {
  10626. int retval = -1;
  10627. char *masked_data =
  10628. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10629. uint32_t masking_key = 0;
  10630. if (masked_data == NULL) {
  10631. /* Return -1 in an error case */
  10632. mg_cry_internal(conn,
  10633. "%s",
  10634. "Cannot allocate buffer for masked websocket response: "
  10635. "Out of memory");
  10636. return -1;
  10637. }
  10638. do {
  10639. /* Get a masking key - but not 0 */
  10640. masking_key = (uint32_t)get_random();
  10641. } while (masking_key == 0);
  10642. mask_data(data, dataLen, masking_key, masked_data);
  10643. retval = mg_websocket_write_exec(
  10644. conn, opcode, masked_data, dataLen, masking_key);
  10645. mg_free(masked_data);
  10646. return retval;
  10647. }
  10648. static void
  10649. handle_websocket_request(struct mg_connection *conn,
  10650. const char *path,
  10651. int is_callback_resource,
  10652. struct mg_websocket_subprotocols *subprotocols,
  10653. mg_websocket_connect_handler ws_connect_handler,
  10654. mg_websocket_ready_handler ws_ready_handler,
  10655. mg_websocket_data_handler ws_data_handler,
  10656. mg_websocket_close_handler ws_close_handler,
  10657. void *cbData)
  10658. {
  10659. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10660. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10661. ptrdiff_t lua_websock = 0;
  10662. #if !defined(USE_LUA)
  10663. (void)path;
  10664. #endif
  10665. /* Step 1: Check websocket protocol version. */
  10666. /* Step 1.1: Check Sec-WebSocket-Key. */
  10667. if (!websock_key) {
  10668. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10669. * requires a Sec-WebSocket-Key header.
  10670. */
  10671. /* It could be the hixie draft version
  10672. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10673. */
  10674. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10675. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10676. char key3[8];
  10677. if ((key1 != NULL) && (key2 != NULL)) {
  10678. /* This version uses 8 byte body data in a GET request */
  10679. conn->content_len = 8;
  10680. if (8 == mg_read(conn, key3, 8)) {
  10681. /* This is the hixie version */
  10682. mg_send_http_error(conn,
  10683. 426,
  10684. "%s",
  10685. "Protocol upgrade to RFC 6455 required");
  10686. return;
  10687. }
  10688. }
  10689. /* This is an unknown version */
  10690. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10691. return;
  10692. }
  10693. /* Step 1.2: Check websocket protocol version. */
  10694. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10695. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10696. /* Reject wrong versions */
  10697. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10698. return;
  10699. }
  10700. /* Step 1.3: Could check for "Host", but we do not really nead this
  10701. * value for anything, so just ignore it. */
  10702. /* Step 2: If a callback is responsible, call it. */
  10703. if (is_callback_resource) {
  10704. /* Step 2.1 check and select subprotocol */
  10705. const char *protocols[64]; // max 64 headers
  10706. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10707. "Sec-WebSocket-Protocol",
  10708. protocols,
  10709. 64);
  10710. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10711. int cnt = 0;
  10712. int idx;
  10713. unsigned long len;
  10714. const char *sep, *curSubProtocol,
  10715. *acceptedWebSocketSubprotocol = NULL;
  10716. /* look for matching subprotocol */
  10717. do {
  10718. const char *protocol = protocols[cnt];
  10719. do {
  10720. sep = strchr(protocol, ',');
  10721. curSubProtocol = protocol;
  10722. len = sep ? (unsigned long)(sep - protocol)
  10723. : (unsigned long)strlen(protocol);
  10724. while (sep && isspace(*++sep))
  10725. ; // ignore leading whitespaces
  10726. protocol = sep;
  10727. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10728. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10729. && (strncmp(curSubProtocol,
  10730. subprotocols->subprotocols[idx],
  10731. len) == 0)) {
  10732. acceptedWebSocketSubprotocol =
  10733. subprotocols->subprotocols[idx];
  10734. break;
  10735. }
  10736. }
  10737. } while (sep && !acceptedWebSocketSubprotocol);
  10738. } while (++cnt < nbSubprotocolHeader
  10739. && !acceptedWebSocketSubprotocol);
  10740. conn->request_info.acceptedWebSocketSubprotocol =
  10741. acceptedWebSocketSubprotocol;
  10742. } else if (nbSubprotocolHeader > 0) {
  10743. /* keep legacy behavior */
  10744. const char *protocol = protocols[0];
  10745. /* The protocol is a comma separated list of names. */
  10746. /* The server must only return one value from this list. */
  10747. /* First check if it is a list or just a single value. */
  10748. const char *sep = strrchr(protocol, ',');
  10749. if (sep == NULL) {
  10750. /* Just a single protocol -> accept it. */
  10751. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10752. } else {
  10753. /* Multiple protocols -> accept the last one. */
  10754. /* This is just a quick fix if the client offers multiple
  10755. * protocols. The handler should have a list of accepted
  10756. * protocols on his own
  10757. * and use it to select one protocol among those the client
  10758. * has
  10759. * offered.
  10760. */
  10761. while (isspace(*++sep)) {
  10762. ; /* ignore leading whitespaces */
  10763. }
  10764. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10765. }
  10766. }
  10767. if ((ws_connect_handler != NULL)
  10768. && (ws_connect_handler(conn, cbData) != 0)) {
  10769. /* C callback has returned non-zero, do not proceed with
  10770. * handshake.
  10771. */
  10772. /* Note that C callbacks are no longer called when Lua is
  10773. * responsible, so C can no longer filter callbacks for Lua. */
  10774. return;
  10775. }
  10776. }
  10777. #if defined(USE_LUA)
  10778. /* Step 3: No callback. Check if Lua is responsible. */
  10779. else {
  10780. /* Step 3.1: Check if Lua is responsible. */
  10781. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10782. lua_websock = match_prefix(
  10783. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10784. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10785. path);
  10786. }
  10787. if (lua_websock) {
  10788. /* Step 3.2: Lua is responsible: call it. */
  10789. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10790. if (!conn->lua_websocket_state) {
  10791. /* Lua rejected the new client */
  10792. return;
  10793. }
  10794. }
  10795. }
  10796. #endif
  10797. /* Step 4: Check if there is a responsible websocket handler. */
  10798. if (!is_callback_resource && !lua_websock) {
  10799. /* There is no callback, and Lua is not responsible either. */
  10800. /* Reply with a 404 Not Found. We are still at a standard
  10801. * HTTP request here, before the websocket handshake, so
  10802. * we can still send standard HTTP error replies. */
  10803. mg_send_http_error(conn, 404, "%s", "Not found");
  10804. return;
  10805. }
  10806. /* Step 5: The websocket connection has been accepted */
  10807. if (!send_websocket_handshake(conn, websock_key)) {
  10808. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10809. return;
  10810. }
  10811. /* Step 6: Call the ready handler */
  10812. if (is_callback_resource) {
  10813. if (ws_ready_handler != NULL) {
  10814. ws_ready_handler(conn, cbData);
  10815. }
  10816. #if defined(USE_LUA)
  10817. } else if (lua_websock) {
  10818. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10819. /* the ready handler returned false */
  10820. return;
  10821. }
  10822. #endif
  10823. }
  10824. /* Step 7: Enter the read loop */
  10825. if (is_callback_resource) {
  10826. read_websocket(conn, ws_data_handler, cbData);
  10827. #if defined(USE_LUA)
  10828. } else if (lua_websock) {
  10829. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10830. #endif
  10831. }
  10832. /* Step 8: Call the close handler */
  10833. if (ws_close_handler) {
  10834. ws_close_handler(conn, cbData);
  10835. }
  10836. }
  10837. static int
  10838. is_websocket_protocol(const struct mg_connection *conn)
  10839. {
  10840. const char *upgrade, *connection;
  10841. /* A websocket protocoll has the following HTTP headers:
  10842. *
  10843. * Connection: Upgrade
  10844. * Upgrade: Websocket
  10845. */
  10846. upgrade = mg_get_header(conn, "Upgrade");
  10847. if (upgrade == NULL) {
  10848. return 0; /* fail early, don't waste time checking other header
  10849. * fields
  10850. */
  10851. }
  10852. if (!mg_strcasestr(upgrade, "websocket")) {
  10853. return 0;
  10854. }
  10855. connection = mg_get_header(conn, "Connection");
  10856. if (connection == NULL) {
  10857. return 0;
  10858. }
  10859. if (!mg_strcasestr(connection, "upgrade")) {
  10860. return 0;
  10861. }
  10862. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10863. * "Sec-WebSocket-Version" are also required.
  10864. * Don't check them here, since even an unsupported websocket protocol
  10865. * request still IS a websocket request (in contrast to a standard HTTP
  10866. * request). It will fail later in handle_websocket_request.
  10867. */
  10868. return 1;
  10869. }
  10870. #endif /* !USE_WEBSOCKET */
  10871. static int
  10872. isbyte(int n)
  10873. {
  10874. return (n >= 0) && (n <= 255);
  10875. }
  10876. static int
  10877. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10878. {
  10879. int n, a, b, c, d, slash = 32, len = 0;
  10880. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10881. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10882. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10883. && (slash < 33)) {
  10884. len = n;
  10885. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10886. | (uint32_t)d;
  10887. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10888. }
  10889. return len;
  10890. }
  10891. static int
  10892. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10893. {
  10894. int throttle = 0;
  10895. struct vec vec, val;
  10896. uint32_t net, mask;
  10897. char mult;
  10898. double v;
  10899. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10900. mult = ',';
  10901. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10902. || (v < 0) || ((lowercase(&mult) != 'k')
  10903. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10904. continue;
  10905. }
  10906. v *= (lowercase(&mult) == 'k')
  10907. ? 1024
  10908. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10909. if (vec.len == 1 && vec.ptr[0] == '*') {
  10910. throttle = (int)v;
  10911. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10912. if ((remote_ip & mask) == net) {
  10913. throttle = (int)v;
  10914. }
  10915. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10916. throttle = (int)v;
  10917. }
  10918. }
  10919. return throttle;
  10920. }
  10921. static uint32_t
  10922. get_remote_ip(const struct mg_connection *conn)
  10923. {
  10924. if (!conn) {
  10925. return 0;
  10926. }
  10927. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10928. }
  10929. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10930. #include "handle_form.inl"
  10931. #if defined(MG_LEGACY_INTERFACE)
  10932. /* Implement the deprecated mg_upload function by calling the new
  10933. * mg_handle_form_request function. While mg_upload could only handle
  10934. * HTML forms sent as POST request in multipart/form-data format
  10935. * containing only file input elements, mg_handle_form_request can
  10936. * handle all form input elements and all standard request methods. */
  10937. struct mg_upload_user_data {
  10938. struct mg_connection *conn;
  10939. const char *destination_dir;
  10940. int num_uploaded_files;
  10941. };
  10942. /* Helper function for deprecated mg_upload. */
  10943. static int
  10944. mg_upload_field_found(const char *key,
  10945. const char *filename,
  10946. char *path,
  10947. size_t pathlen,
  10948. void *user_data)
  10949. {
  10950. int truncated = 0;
  10951. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10952. (void)key;
  10953. if (!filename) {
  10954. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  10955. return FORM_FIELD_STORAGE_ABORT;
  10956. }
  10957. mg_snprintf(fud->conn,
  10958. &truncated,
  10959. path,
  10960. pathlen - 1,
  10961. "%s/%s",
  10962. fud->destination_dir,
  10963. filename);
  10964. if (truncated) {
  10965. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  10966. return FORM_FIELD_STORAGE_ABORT;
  10967. }
  10968. return FORM_FIELD_STORAGE_STORE;
  10969. }
  10970. /* Helper function for deprecated mg_upload. */
  10971. static int
  10972. mg_upload_field_get(const char *key,
  10973. const char *value,
  10974. size_t value_size,
  10975. void *user_data)
  10976. {
  10977. /* Function should never be called */
  10978. (void)key;
  10979. (void)value;
  10980. (void)value_size;
  10981. (void)user_data;
  10982. return 0;
  10983. }
  10984. /* Helper function for deprecated mg_upload. */
  10985. static int
  10986. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10987. {
  10988. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10989. (void)file_size;
  10990. fud->num_uploaded_files++;
  10991. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  10992. return 0;
  10993. }
  10994. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10995. int
  10996. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10997. {
  10998. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10999. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11000. mg_upload_field_get,
  11001. mg_upload_field_stored,
  11002. 0};
  11003. int ret;
  11004. fdh.user_data = (void *)&fud;
  11005. ret = mg_handle_form_request(conn, &fdh);
  11006. if (ret < 0) {
  11007. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11008. }
  11009. return fud.num_uploaded_files;
  11010. }
  11011. #endif
  11012. static int
  11013. get_first_ssl_listener_index(const struct mg_context *ctx)
  11014. {
  11015. unsigned int i;
  11016. int idx = -1;
  11017. if (ctx) {
  11018. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11019. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11020. }
  11021. }
  11022. return idx;
  11023. }
  11024. /* Return host (without port) */
  11025. /* Use mg_free to free the result */
  11026. static const char *
  11027. alloc_get_host(struct mg_connection *conn)
  11028. {
  11029. char buf[1025];
  11030. size_t buflen = sizeof(buf);
  11031. const char *host_header = get_header(conn->request_info.http_headers,
  11032. conn->request_info.num_headers,
  11033. "Host");
  11034. char *host;
  11035. if (host_header != NULL) {
  11036. char *pos;
  11037. /* Create a local copy of the "Host" header, since it might be
  11038. * modified here. */
  11039. mg_strlcpy(buf, host_header, buflen);
  11040. buf[buflen - 1] = '\0';
  11041. host = buf;
  11042. while (isspace(*host)) {
  11043. host++;
  11044. }
  11045. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11046. * is found. */
  11047. if (*host == '[') {
  11048. pos = strchr(host, ']');
  11049. if (!pos) {
  11050. /* Malformed hostname starts with '[', but no ']' found */
  11051. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11052. return NULL;
  11053. }
  11054. /* terminate after ']' */
  11055. pos[1] = 0;
  11056. } else {
  11057. /* Otherwise, a ':' separates hostname and port number */
  11058. pos = strchr(host, ':');
  11059. if (pos != NULL) {
  11060. *pos = '\0';
  11061. }
  11062. }
  11063. if (conn->ssl) {
  11064. /* This is a HTTPS connection, maybe we have a hostname
  11065. * from SNI (set in ssl_servername_callback). */
  11066. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11067. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11068. /* We are not using the default domain */
  11069. if (mg_strcasecmp(host, sslhost)) {
  11070. /* Mismatch between SNI domain and HTTP domain */
  11071. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11072. sslhost,
  11073. host);
  11074. return NULL;
  11075. }
  11076. }
  11077. DEBUG_TRACE("HTTPS Host: %s", host);
  11078. } else {
  11079. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11080. while (dom) {
  11081. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11082. /* Found matching domain */
  11083. DEBUG_TRACE("HTTP domain %s found",
  11084. dom->config[AUTHENTICATION_DOMAIN]);
  11085. /* TODO: Check if this is a HTTP or HTTPS domain */
  11086. conn->dom_ctx = dom;
  11087. break;
  11088. }
  11089. dom = dom->next;
  11090. }
  11091. DEBUG_TRACE("HTTP Host: %s", host);
  11092. }
  11093. } else {
  11094. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11095. host = buf;
  11096. DEBUG_TRACE("IP: %s", host);
  11097. }
  11098. return mg_strdup_ctx(host, conn->phys_ctx);
  11099. }
  11100. static void
  11101. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11102. {
  11103. char target_url[MG_BUF_LEN];
  11104. int truncated = 0;
  11105. conn->must_close = 1;
  11106. /* Send host, port, uri and (if it exists) ?query_string */
  11107. if (conn->host) {
  11108. /* Use "308 Permanent Redirect" */
  11109. int redirect_code = 308;
  11110. /* Create target URL */
  11111. mg_snprintf(
  11112. conn,
  11113. &truncated,
  11114. target_url,
  11115. sizeof(target_url),
  11116. "Location: https://%s:%d%s%s%s",
  11117. conn->host,
  11118. #if defined(USE_IPV6)
  11119. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11120. == AF_INET6)
  11121. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11122. .lsa.sin6.sin6_port)
  11123. :
  11124. #endif
  11125. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11126. .lsa.sin.sin_port),
  11127. conn->request_info.local_uri,
  11128. (conn->request_info.query_string == NULL) ? "" : "?",
  11129. (conn->request_info.query_string == NULL)
  11130. ? ""
  11131. : conn->request_info.query_string);
  11132. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11133. * is used as buffer size) */
  11134. if (truncated) {
  11135. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11136. return;
  11137. }
  11138. /* Use redirect helper function */
  11139. mg_send_http_redirect(conn, target_url, redirect_code);
  11140. }
  11141. }
  11142. static void
  11143. handler_info_acquire(struct mg_handler_info *handler_info)
  11144. {
  11145. pthread_mutex_lock(&handler_info->refcount_mutex);
  11146. handler_info->refcount++;
  11147. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11148. }
  11149. static void
  11150. handler_info_release(struct mg_handler_info *handler_info)
  11151. {
  11152. pthread_mutex_lock(&handler_info->refcount_mutex);
  11153. handler_info->refcount--;
  11154. pthread_cond_signal(&handler_info->refcount_cond);
  11155. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11156. }
  11157. static void
  11158. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11159. {
  11160. pthread_mutex_lock(&handler_info->refcount_mutex);
  11161. while (handler_info->refcount) {
  11162. pthread_cond_wait(&handler_info->refcount_cond,
  11163. &handler_info->refcount_mutex);
  11164. }
  11165. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11166. }
  11167. static void
  11168. mg_set_handler_type(struct mg_context *phys_ctx,
  11169. struct mg_domain_context *dom_ctx,
  11170. const char *uri,
  11171. int handler_type,
  11172. int is_delete_request,
  11173. mg_request_handler handler,
  11174. struct mg_websocket_subprotocols *subprotocols,
  11175. mg_websocket_connect_handler connect_handler,
  11176. mg_websocket_ready_handler ready_handler,
  11177. mg_websocket_data_handler data_handler,
  11178. mg_websocket_close_handler close_handler,
  11179. mg_authorization_handler auth_handler,
  11180. void *cbdata)
  11181. {
  11182. struct mg_handler_info *tmp_rh, **lastref;
  11183. size_t urilen = strlen(uri);
  11184. if (handler_type == WEBSOCKET_HANDLER) {
  11185. DEBUG_ASSERT(handler == NULL);
  11186. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11187. || ready_handler != NULL
  11188. || data_handler != NULL
  11189. || close_handler != NULL);
  11190. DEBUG_ASSERT(auth_handler == NULL);
  11191. if (handler != NULL) {
  11192. return;
  11193. }
  11194. if (!is_delete_request && (connect_handler == NULL)
  11195. && (ready_handler == NULL) && (data_handler == NULL)
  11196. && (close_handler == NULL)) {
  11197. return;
  11198. }
  11199. if (auth_handler != NULL) {
  11200. return;
  11201. }
  11202. } else if (handler_type == REQUEST_HANDLER) {
  11203. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11204. && data_handler == NULL
  11205. && close_handler == NULL);
  11206. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11207. DEBUG_ASSERT(auth_handler == NULL);
  11208. if ((connect_handler != NULL) || (ready_handler != NULL)
  11209. || (data_handler != NULL) || (close_handler != NULL)) {
  11210. return;
  11211. }
  11212. if (!is_delete_request && (handler == NULL)) {
  11213. return;
  11214. }
  11215. if (auth_handler != NULL) {
  11216. return;
  11217. }
  11218. } else { /* AUTH_HANDLER */
  11219. DEBUG_ASSERT(handler == NULL);
  11220. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11221. && data_handler == NULL
  11222. && close_handler == NULL);
  11223. DEBUG_ASSERT(auth_handler != NULL);
  11224. if (handler != NULL) {
  11225. return;
  11226. }
  11227. if ((connect_handler != NULL) || (ready_handler != NULL)
  11228. || (data_handler != NULL) || (close_handler != NULL)) {
  11229. return;
  11230. }
  11231. if (!is_delete_request && (auth_handler == NULL)) {
  11232. return;
  11233. }
  11234. }
  11235. if (!phys_ctx || !dom_ctx) {
  11236. return;
  11237. }
  11238. mg_lock_context(phys_ctx);
  11239. /* first try to find an existing handler */
  11240. lastref = &(dom_ctx->handlers);
  11241. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11242. if (tmp_rh->handler_type == handler_type) {
  11243. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11244. if (!is_delete_request) {
  11245. /* update existing handler */
  11246. if (handler_type == REQUEST_HANDLER) {
  11247. /* Wait for end of use before updating */
  11248. handler_info_wait_unused(tmp_rh);
  11249. /* Ok, the handler is no more use -> Update it */
  11250. tmp_rh->handler = handler;
  11251. } else if (handler_type == WEBSOCKET_HANDLER) {
  11252. tmp_rh->subprotocols = subprotocols;
  11253. tmp_rh->connect_handler = connect_handler;
  11254. tmp_rh->ready_handler = ready_handler;
  11255. tmp_rh->data_handler = data_handler;
  11256. tmp_rh->close_handler = close_handler;
  11257. } else { /* AUTH_HANDLER */
  11258. tmp_rh->auth_handler = auth_handler;
  11259. }
  11260. tmp_rh->cbdata = cbdata;
  11261. } else {
  11262. /* remove existing handler */
  11263. if (handler_type == REQUEST_HANDLER) {
  11264. /* Wait for end of use before removing */
  11265. handler_info_wait_unused(tmp_rh);
  11266. /* Ok, the handler is no more used -> Destroy resources
  11267. */
  11268. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11269. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11270. }
  11271. *lastref = tmp_rh->next;
  11272. mg_free(tmp_rh->uri);
  11273. mg_free(tmp_rh);
  11274. }
  11275. mg_unlock_context(phys_ctx);
  11276. return;
  11277. }
  11278. }
  11279. lastref = &(tmp_rh->next);
  11280. }
  11281. if (is_delete_request) {
  11282. /* no handler to set, this was a remove request to a non-existing
  11283. * handler */
  11284. mg_unlock_context(phys_ctx);
  11285. return;
  11286. }
  11287. tmp_rh =
  11288. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11289. 1,
  11290. phys_ctx);
  11291. if (tmp_rh == NULL) {
  11292. mg_unlock_context(phys_ctx);
  11293. mg_cry_internal(fc(phys_ctx),
  11294. "%s",
  11295. "Cannot create new request handler struct, OOM");
  11296. return;
  11297. }
  11298. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11299. if (!tmp_rh->uri) {
  11300. mg_unlock_context(phys_ctx);
  11301. mg_free(tmp_rh);
  11302. mg_cry_internal(fc(phys_ctx),
  11303. "%s",
  11304. "Cannot create new request handler struct, OOM");
  11305. return;
  11306. }
  11307. tmp_rh->uri_len = urilen;
  11308. if (handler_type == REQUEST_HANDLER) {
  11309. /* Init refcount mutex and condition */
  11310. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11311. mg_unlock_context(phys_ctx);
  11312. mg_free(tmp_rh);
  11313. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11314. return;
  11315. }
  11316. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11317. mg_unlock_context(phys_ctx);
  11318. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11319. mg_free(tmp_rh);
  11320. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11321. return;
  11322. }
  11323. tmp_rh->refcount = 0;
  11324. tmp_rh->handler = handler;
  11325. } else if (handler_type == WEBSOCKET_HANDLER) {
  11326. tmp_rh->subprotocols = subprotocols;
  11327. tmp_rh->connect_handler = connect_handler;
  11328. tmp_rh->ready_handler = ready_handler;
  11329. tmp_rh->data_handler = data_handler;
  11330. tmp_rh->close_handler = close_handler;
  11331. } else { /* AUTH_HANDLER */
  11332. tmp_rh->auth_handler = auth_handler;
  11333. }
  11334. tmp_rh->cbdata = cbdata;
  11335. tmp_rh->handler_type = handler_type;
  11336. tmp_rh->next = NULL;
  11337. *lastref = tmp_rh;
  11338. mg_unlock_context(phys_ctx);
  11339. }
  11340. void
  11341. mg_set_request_handler(struct mg_context *ctx,
  11342. const char *uri,
  11343. mg_request_handler handler,
  11344. void *cbdata)
  11345. {
  11346. mg_set_handler_type(ctx,
  11347. &(ctx->dd),
  11348. uri,
  11349. REQUEST_HANDLER,
  11350. handler == NULL,
  11351. handler,
  11352. NULL,
  11353. NULL,
  11354. NULL,
  11355. NULL,
  11356. NULL,
  11357. NULL,
  11358. cbdata);
  11359. }
  11360. void
  11361. mg_set_websocket_handler(struct mg_context *ctx,
  11362. const char *uri,
  11363. mg_websocket_connect_handler connect_handler,
  11364. mg_websocket_ready_handler ready_handler,
  11365. mg_websocket_data_handler data_handler,
  11366. mg_websocket_close_handler close_handler,
  11367. void *cbdata)
  11368. {
  11369. mg_set_websocket_handler_with_subprotocols(ctx,
  11370. uri,
  11371. NULL,
  11372. connect_handler,
  11373. ready_handler,
  11374. data_handler,
  11375. close_handler,
  11376. cbdata);
  11377. }
  11378. void
  11379. mg_set_websocket_handler_with_subprotocols(
  11380. struct mg_context *ctx,
  11381. const char *uri,
  11382. struct mg_websocket_subprotocols *subprotocols,
  11383. mg_websocket_connect_handler connect_handler,
  11384. mg_websocket_ready_handler ready_handler,
  11385. mg_websocket_data_handler data_handler,
  11386. mg_websocket_close_handler close_handler,
  11387. void *cbdata)
  11388. {
  11389. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11390. && (data_handler == NULL)
  11391. && (close_handler == NULL);
  11392. mg_set_handler_type(ctx,
  11393. &(ctx->dd),
  11394. uri,
  11395. WEBSOCKET_HANDLER,
  11396. is_delete_request,
  11397. NULL,
  11398. subprotocols,
  11399. connect_handler,
  11400. ready_handler,
  11401. data_handler,
  11402. close_handler,
  11403. NULL,
  11404. cbdata);
  11405. }
  11406. void
  11407. mg_set_auth_handler(struct mg_context *ctx,
  11408. const char *uri,
  11409. mg_request_handler handler,
  11410. void *cbdata)
  11411. {
  11412. mg_set_handler_type(ctx,
  11413. &(ctx->dd),
  11414. uri,
  11415. AUTH_HANDLER,
  11416. handler == NULL,
  11417. NULL,
  11418. NULL,
  11419. NULL,
  11420. NULL,
  11421. NULL,
  11422. NULL,
  11423. handler,
  11424. cbdata);
  11425. }
  11426. static int
  11427. get_request_handler(struct mg_connection *conn,
  11428. int handler_type,
  11429. mg_request_handler *handler,
  11430. struct mg_websocket_subprotocols **subprotocols,
  11431. mg_websocket_connect_handler *connect_handler,
  11432. mg_websocket_ready_handler *ready_handler,
  11433. mg_websocket_data_handler *data_handler,
  11434. mg_websocket_close_handler *close_handler,
  11435. mg_authorization_handler *auth_handler,
  11436. void **cbdata,
  11437. struct mg_handler_info **handler_info)
  11438. {
  11439. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11440. if (request_info) {
  11441. const char *uri = request_info->local_uri;
  11442. size_t urilen = strlen(uri);
  11443. struct mg_handler_info *tmp_rh;
  11444. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11445. return 0;
  11446. }
  11447. mg_lock_context(conn->phys_ctx);
  11448. /* first try for an exact match */
  11449. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11450. tmp_rh = tmp_rh->next) {
  11451. if (tmp_rh->handler_type == handler_type) {
  11452. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11453. if (handler_type == WEBSOCKET_HANDLER) {
  11454. *subprotocols = tmp_rh->subprotocols;
  11455. *connect_handler = tmp_rh->connect_handler;
  11456. *ready_handler = tmp_rh->ready_handler;
  11457. *data_handler = tmp_rh->data_handler;
  11458. *close_handler = tmp_rh->close_handler;
  11459. } else if (handler_type == REQUEST_HANDLER) {
  11460. *handler = tmp_rh->handler;
  11461. /* Acquire handler and give it back */
  11462. handler_info_acquire(tmp_rh);
  11463. *handler_info = tmp_rh;
  11464. } else { /* AUTH_HANDLER */
  11465. *auth_handler = tmp_rh->auth_handler;
  11466. }
  11467. *cbdata = tmp_rh->cbdata;
  11468. mg_unlock_context(conn->phys_ctx);
  11469. return 1;
  11470. }
  11471. }
  11472. }
  11473. /* next try for a partial match, we will accept uri/something */
  11474. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11475. tmp_rh = tmp_rh->next) {
  11476. if (tmp_rh->handler_type == handler_type) {
  11477. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11478. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11479. if (handler_type == WEBSOCKET_HANDLER) {
  11480. *subprotocols = tmp_rh->subprotocols;
  11481. *connect_handler = tmp_rh->connect_handler;
  11482. *ready_handler = tmp_rh->ready_handler;
  11483. *data_handler = tmp_rh->data_handler;
  11484. *close_handler = tmp_rh->close_handler;
  11485. } else if (handler_type == REQUEST_HANDLER) {
  11486. *handler = tmp_rh->handler;
  11487. /* Acquire handler and give it back */
  11488. handler_info_acquire(tmp_rh);
  11489. *handler_info = tmp_rh;
  11490. } else { /* AUTH_HANDLER */
  11491. *auth_handler = tmp_rh->auth_handler;
  11492. }
  11493. *cbdata = tmp_rh->cbdata;
  11494. mg_unlock_context(conn->phys_ctx);
  11495. return 1;
  11496. }
  11497. }
  11498. }
  11499. /* finally try for pattern match */
  11500. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11501. tmp_rh = tmp_rh->next) {
  11502. if (tmp_rh->handler_type == handler_type) {
  11503. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11504. if (handler_type == WEBSOCKET_HANDLER) {
  11505. *subprotocols = tmp_rh->subprotocols;
  11506. *connect_handler = tmp_rh->connect_handler;
  11507. *ready_handler = tmp_rh->ready_handler;
  11508. *data_handler = tmp_rh->data_handler;
  11509. *close_handler = tmp_rh->close_handler;
  11510. } else if (handler_type == REQUEST_HANDLER) {
  11511. *handler = tmp_rh->handler;
  11512. /* Acquire handler and give it back */
  11513. handler_info_acquire(tmp_rh);
  11514. *handler_info = tmp_rh;
  11515. } else { /* AUTH_HANDLER */
  11516. *auth_handler = tmp_rh->auth_handler;
  11517. }
  11518. *cbdata = tmp_rh->cbdata;
  11519. mg_unlock_context(conn->phys_ctx);
  11520. return 1;
  11521. }
  11522. }
  11523. }
  11524. mg_unlock_context(conn->phys_ctx);
  11525. }
  11526. return 0; /* none found */
  11527. }
  11528. /* Check if the script file is in a path, allowed for script files.
  11529. * This can be used if uploading files is possible not only for the server
  11530. * admin, and the upload mechanism does not check the file extension.
  11531. */
  11532. static int
  11533. is_in_script_path(const struct mg_connection *conn, const char *path)
  11534. {
  11535. /* TODO (Feature): Add config value for allowed script path.
  11536. * Default: All allowed. */
  11537. (void)conn;
  11538. (void)path;
  11539. return 1;
  11540. }
  11541. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11542. static int
  11543. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11544. void *cbdata)
  11545. {
  11546. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11547. if (pcallbacks->websocket_connect) {
  11548. return pcallbacks->websocket_connect(conn);
  11549. }
  11550. /* No handler set - assume "OK" */
  11551. return 0;
  11552. }
  11553. static void
  11554. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11555. {
  11556. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11557. if (pcallbacks->websocket_ready) {
  11558. pcallbacks->websocket_ready(conn);
  11559. }
  11560. }
  11561. static int
  11562. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11563. int bits,
  11564. char *data,
  11565. size_t len,
  11566. void *cbdata)
  11567. {
  11568. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11569. if (pcallbacks->websocket_data) {
  11570. return pcallbacks->websocket_data(conn, bits, data, len);
  11571. }
  11572. /* No handler set - assume "OK" */
  11573. return 1;
  11574. }
  11575. #endif
  11576. /* This is the heart of the Civetweb's logic.
  11577. * This function is called when the request is read, parsed and validated,
  11578. * and Civetweb must decide what action to take: serve a file, or
  11579. * a directory, or call embedded function, etcetera. */
  11580. static void
  11581. handle_request(struct mg_connection *conn)
  11582. {
  11583. struct mg_request_info *ri = &conn->request_info;
  11584. char path[PATH_MAX];
  11585. int uri_len, ssl_index;
  11586. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11587. is_put_or_delete_request = 0, is_callback_resource = 0;
  11588. int i;
  11589. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11590. mg_request_handler callback_handler = NULL;
  11591. struct mg_handler_info *handler_info = NULL;
  11592. struct mg_websocket_subprotocols *subprotocols;
  11593. mg_websocket_connect_handler ws_connect_handler = NULL;
  11594. mg_websocket_ready_handler ws_ready_handler = NULL;
  11595. mg_websocket_data_handler ws_data_handler = NULL;
  11596. mg_websocket_close_handler ws_close_handler = NULL;
  11597. void *callback_data = NULL;
  11598. mg_authorization_handler auth_handler = NULL;
  11599. void *auth_callback_data = NULL;
  11600. int handler_type;
  11601. time_t curtime = time(NULL);
  11602. char date[64];
  11603. path[0] = 0;
  11604. /* 1. get the request url */
  11605. /* 1.1. split into url and query string */
  11606. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11607. != NULL) {
  11608. *((char *)conn->request_info.query_string++) = '\0';
  11609. }
  11610. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11611. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11612. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11613. if (ssl_index >= 0) {
  11614. redirect_to_https_port(conn, ssl_index);
  11615. } else {
  11616. /* A http to https forward port has been specified,
  11617. * but no https port to forward to. */
  11618. mg_send_http_error(conn,
  11619. 503,
  11620. "%s",
  11621. "Error: SSL forward not configured properly");
  11622. mg_cry_internal(conn,
  11623. "%s",
  11624. "Can not redirect to SSL, no SSL port available");
  11625. }
  11626. return;
  11627. }
  11628. uri_len = (int)strlen(ri->local_uri);
  11629. /* 1.3. decode url (if config says so) */
  11630. if (should_decode_url(conn)) {
  11631. mg_url_decode(
  11632. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11633. }
  11634. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11635. * not possible */
  11636. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11637. /* step 1. completed, the url is known now */
  11638. uri_len = (int)strlen(ri->local_uri);
  11639. DEBUG_TRACE("URL: %s", ri->local_uri);
  11640. /* 2. if this ip has limited speed, set it for this connection */
  11641. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11642. get_remote_ip(conn),
  11643. ri->local_uri);
  11644. /* 3. call a "handle everything" callback, if registered */
  11645. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11646. /* Note that since V1.7 the "begin_request" function is called
  11647. * before an authorization check. If an authorization check is
  11648. * required, use a request_handler instead. */
  11649. i = conn->phys_ctx->callbacks.begin_request(conn);
  11650. if (i > 0) {
  11651. /* callback already processed the request. Store the
  11652. return value as a status code for the access log. */
  11653. conn->status_code = i;
  11654. discard_unread_request_data(conn);
  11655. return;
  11656. } else if (i == 0) {
  11657. /* civetweb should process the request */
  11658. } else {
  11659. /* unspecified - may change with the next version */
  11660. return;
  11661. }
  11662. }
  11663. /* request not yet handled by a handler or redirect, so the request
  11664. * is processed here */
  11665. /* 4. Check for CORS preflight requests and handle them (if configured).
  11666. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11667. */
  11668. if (!strcmp(ri->request_method, "OPTIONS")) {
  11669. /* Send a response to CORS preflights only if
  11670. * access_control_allow_methods is not NULL and not an empty string.
  11671. * In this case, scripts can still handle CORS. */
  11672. const char *cors_meth_cfg =
  11673. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11674. const char *cors_orig_cfg =
  11675. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11676. const char *cors_origin =
  11677. get_header(ri->http_headers, ri->num_headers, "Origin");
  11678. const char *cors_acrm = get_header(ri->http_headers,
  11679. ri->num_headers,
  11680. "Access-Control-Request-Method");
  11681. /* Todo: check if cors_origin is in cors_orig_cfg.
  11682. * Or, let the client check this. */
  11683. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11684. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11685. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11686. /* This is a valid CORS preflight, and the server is configured
  11687. * to
  11688. * handle it automatically. */
  11689. const char *cors_acrh =
  11690. get_header(ri->http_headers,
  11691. ri->num_headers,
  11692. "Access-Control-Request-Headers");
  11693. gmt_time_string(date, sizeof(date), &curtime);
  11694. mg_printf(conn,
  11695. "HTTP/1.1 200 OK\r\n"
  11696. "Date: %s\r\n"
  11697. "Access-Control-Allow-Origin: %s\r\n"
  11698. "Access-Control-Allow-Methods: %s\r\n"
  11699. "Content-Length: 0\r\n"
  11700. "Connection: %s\r\n",
  11701. date,
  11702. cors_orig_cfg,
  11703. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11704. suggest_connection_header(conn));
  11705. if (cors_acrh != NULL) {
  11706. /* CORS request is asking for additional headers */
  11707. const char *cors_hdr_cfg =
  11708. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11709. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11710. /* Allow only if access_control_allow_headers is
  11711. * not NULL and not an empty string. If this
  11712. * configuration is set to *, allow everything.
  11713. * Otherwise this configuration must be a list
  11714. * of allowed HTTP header names. */
  11715. mg_printf(conn,
  11716. "Access-Control-Allow-Headers: %s\r\n",
  11717. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11718. : cors_hdr_cfg));
  11719. }
  11720. }
  11721. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11722. mg_printf(conn, "\r\n");
  11723. return;
  11724. }
  11725. }
  11726. /* 5. interpret the url to find out how the request must be handled
  11727. */
  11728. /* 5.1. first test, if the request targets the regular http(s)://
  11729. * protocol namespace or the websocket ws(s):// protocol namespace.
  11730. */
  11731. is_websocket_request = is_websocket_protocol(conn);
  11732. #if defined(USE_WEBSOCKET)
  11733. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11734. #else
  11735. handler_type = REQUEST_HANDLER;
  11736. #endif /* defined(USE_WEBSOCKET) */
  11737. /* 5.2. check if the request will be handled by a callback */
  11738. if (get_request_handler(conn,
  11739. handler_type,
  11740. &callback_handler,
  11741. &subprotocols,
  11742. &ws_connect_handler,
  11743. &ws_ready_handler,
  11744. &ws_data_handler,
  11745. &ws_close_handler,
  11746. NULL,
  11747. &callback_data,
  11748. &handler_info)) {
  11749. /* 5.2.1. A callback will handle this request. All requests
  11750. * handled
  11751. * by a callback have to be considered as requests to a script
  11752. * resource. */
  11753. is_callback_resource = 1;
  11754. is_script_resource = 1;
  11755. is_put_or_delete_request = is_put_or_delete_method(conn);
  11756. } else {
  11757. no_callback_resource:
  11758. /* 5.2.2. No callback is responsible for this request. The URI
  11759. * addresses a file based resource (static content or Lua/cgi
  11760. * scripts in the file system). */
  11761. is_callback_resource = 0;
  11762. interpret_uri(conn,
  11763. path,
  11764. sizeof(path),
  11765. &file.stat,
  11766. &is_found,
  11767. &is_script_resource,
  11768. &is_websocket_request,
  11769. &is_put_or_delete_request);
  11770. }
  11771. /* 6. authorization check */
  11772. /* 6.1. a custom authorization handler is installed */
  11773. if (get_request_handler(conn,
  11774. AUTH_HANDLER,
  11775. NULL,
  11776. NULL,
  11777. NULL,
  11778. NULL,
  11779. NULL,
  11780. NULL,
  11781. &auth_handler,
  11782. &auth_callback_data,
  11783. NULL)) {
  11784. if (!auth_handler(conn, auth_callback_data)) {
  11785. return;
  11786. }
  11787. } else if (is_put_or_delete_request && !is_script_resource
  11788. && !is_callback_resource) {
  11789. /* 6.2. this request is a PUT/DELETE to a real file */
  11790. /* 6.2.1. thus, the server must have real files */
  11791. #if defined(NO_FILES)
  11792. if (1) {
  11793. #else
  11794. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11795. #endif
  11796. /* This server does not have any real files, thus the
  11797. * PUT/DELETE methods are not valid. */
  11798. mg_send_http_error(conn,
  11799. 405,
  11800. "%s method not allowed",
  11801. conn->request_info.request_method);
  11802. return;
  11803. }
  11804. #if !defined(NO_FILES)
  11805. /* 6.2.2. Check if put authorization for static files is
  11806. * available.
  11807. */
  11808. if (!is_authorized_for_put(conn)) {
  11809. send_authorization_request(conn, NULL);
  11810. return;
  11811. }
  11812. #endif
  11813. } else {
  11814. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11815. * or it is a PUT or DELETE request to a resource that does not
  11816. * correspond to a file. Check authorization. */
  11817. if (!check_authorization(conn, path)) {
  11818. send_authorization_request(conn, NULL);
  11819. return;
  11820. }
  11821. }
  11822. /* request is authorized or does not need authorization */
  11823. /* 7. check if there are request handlers for this uri */
  11824. if (is_callback_resource) {
  11825. if (!is_websocket_request) {
  11826. i = callback_handler(conn, callback_data);
  11827. /* Callback handler will not be used anymore. Release it */
  11828. handler_info_release(handler_info);
  11829. if (i > 0) {
  11830. /* Do nothing, callback has served the request. Store
  11831. * then return value as status code for the log and discard
  11832. * all data from the client not used by the callback. */
  11833. conn->status_code = i;
  11834. discard_unread_request_data(conn);
  11835. } else {
  11836. /* The handler did NOT handle the request. */
  11837. /* Some proper reactions would be:
  11838. * a) close the connections without sending anything
  11839. * b) send a 404 not found
  11840. * c) try if there is a file matching the URI
  11841. * It would be possible to do a, b or c in the callback
  11842. * implementation, and return 1 - we cannot do anything
  11843. * here, that is not possible in the callback.
  11844. *
  11845. * TODO: What would be the best reaction here?
  11846. * (Note: The reaction may change, if there is a better
  11847. *idea.)
  11848. */
  11849. /* For the moment, use option c: We look for a proper file,
  11850. * but since a file request is not always a script resource,
  11851. * the authorization check might be different. */
  11852. interpret_uri(conn,
  11853. path,
  11854. sizeof(path),
  11855. &file.stat,
  11856. &is_found,
  11857. &is_script_resource,
  11858. &is_websocket_request,
  11859. &is_put_or_delete_request);
  11860. callback_handler = NULL;
  11861. /* Here we are at a dead end:
  11862. * According to URI matching, a callback should be
  11863. * responsible for handling the request,
  11864. * we called it, but the callback declared itself
  11865. * not responsible.
  11866. * We use a goto here, to get out of this dead end,
  11867. * and continue with the default handling.
  11868. * A goto here is simpler and better to understand
  11869. * than some curious loop. */
  11870. goto no_callback_resource;
  11871. }
  11872. } else {
  11873. #if defined(USE_WEBSOCKET)
  11874. handle_websocket_request(conn,
  11875. path,
  11876. is_callback_resource,
  11877. subprotocols,
  11878. ws_connect_handler,
  11879. ws_ready_handler,
  11880. ws_data_handler,
  11881. ws_close_handler,
  11882. callback_data);
  11883. #endif
  11884. }
  11885. return;
  11886. }
  11887. /* 8. handle websocket requests */
  11888. #if defined(USE_WEBSOCKET)
  11889. if (is_websocket_request) {
  11890. if (is_script_resource) {
  11891. if (is_in_script_path(conn, path)) {
  11892. /* Websocket Lua script */
  11893. handle_websocket_request(conn,
  11894. path,
  11895. 0 /* Lua Script */,
  11896. NULL,
  11897. NULL,
  11898. NULL,
  11899. NULL,
  11900. NULL,
  11901. conn->phys_ctx->user_data);
  11902. } else {
  11903. /* Script was in an illegal path */
  11904. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11905. }
  11906. } else {
  11907. #if defined(MG_LEGACY_INTERFACE)
  11908. handle_websocket_request(
  11909. conn,
  11910. path,
  11911. !is_script_resource /* could be deprecated global callback */,
  11912. NULL,
  11913. deprecated_websocket_connect_wrapper,
  11914. deprecated_websocket_ready_wrapper,
  11915. deprecated_websocket_data_wrapper,
  11916. NULL,
  11917. conn->phys_ctx->user_data);
  11918. #else
  11919. mg_send_http_error(conn, 404, "%s", "Not found");
  11920. #endif
  11921. }
  11922. return;
  11923. } else
  11924. #endif
  11925. #if defined(NO_FILES)
  11926. /* 9a. In case the server uses only callbacks, this uri is
  11927. * unknown.
  11928. * Then, all request handling ends here. */
  11929. mg_send_http_error(conn, 404, "%s", "Not Found");
  11930. #else
  11931. /* 9b. This request is either for a static file or resource handled
  11932. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11933. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11934. mg_send_http_error(conn, 404, "%s", "Not Found");
  11935. return;
  11936. }
  11937. /* 10. Request is handled by a script */
  11938. if (is_script_resource) {
  11939. handle_file_based_request(conn, path, &file);
  11940. return;
  11941. }
  11942. /* 11. Handle put/delete/mkcol requests */
  11943. if (is_put_or_delete_request) {
  11944. /* 11.1. PUT method */
  11945. if (!strcmp(ri->request_method, "PUT")) {
  11946. put_file(conn, path);
  11947. return;
  11948. }
  11949. /* 11.2. DELETE method */
  11950. if (!strcmp(ri->request_method, "DELETE")) {
  11951. delete_file(conn, path);
  11952. return;
  11953. }
  11954. /* 11.3. MKCOL method */
  11955. if (!strcmp(ri->request_method, "MKCOL")) {
  11956. mkcol(conn, path);
  11957. return;
  11958. }
  11959. /* 11.4. PATCH method
  11960. * This method is not supported for static resources,
  11961. * only for scripts (Lua, CGI) and callbacks. */
  11962. mg_send_http_error(conn,
  11963. 405,
  11964. "%s method not allowed",
  11965. conn->request_info.request_method);
  11966. return;
  11967. }
  11968. /* 11. File does not exist, or it was configured that it should be
  11969. * hidden */
  11970. if (!is_found || (must_hide_file(conn, path))) {
  11971. mg_send_http_error(conn, 404, "%s", "Not found");
  11972. return;
  11973. }
  11974. /* 12. Directory uris should end with a slash */
  11975. if (file.stat.is_directory && (uri_len > 0)
  11976. && (ri->local_uri[uri_len - 1] != '/')) {
  11977. gmt_time_string(date, sizeof(date), &curtime);
  11978. mg_printf(conn,
  11979. "HTTP/1.1 301 Moved Permanently\r\n"
  11980. "Location: %s/\r\n"
  11981. "Date: %s\r\n"
  11982. /* "Cache-Control: private\r\n" (= default) */
  11983. "Content-Length: 0\r\n"
  11984. "Connection: %s\r\n",
  11985. ri->request_uri,
  11986. date,
  11987. suggest_connection_header(conn));
  11988. send_additional_header(conn);
  11989. mg_printf(conn, "\r\n");
  11990. return;
  11991. }
  11992. /* 13. Handle other methods than GET/HEAD */
  11993. /* 13.1. Handle PROPFIND */
  11994. if (!strcmp(ri->request_method, "PROPFIND")) {
  11995. handle_propfind(conn, path, &file.stat);
  11996. return;
  11997. }
  11998. /* 13.2. Handle OPTIONS for files */
  11999. if (!strcmp(ri->request_method, "OPTIONS")) {
  12000. /* This standard handler is only used for real files.
  12001. * Scripts should support the OPTIONS method themselves, to allow a
  12002. * maximum flexibility.
  12003. * Lua and CGI scripts may fully support CORS this way (including
  12004. * preflights). */
  12005. send_options(conn);
  12006. return;
  12007. }
  12008. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12009. if ((0 != strcmp(ri->request_method, "GET"))
  12010. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12011. mg_send_http_error(conn,
  12012. 405,
  12013. "%s method not allowed",
  12014. conn->request_info.request_method);
  12015. return;
  12016. }
  12017. /* 14. directories */
  12018. if (file.stat.is_directory) {
  12019. /* Substitute files have already been handled above. */
  12020. /* Here we can either generate and send a directory listing,
  12021. * or send an "access denied" error. */
  12022. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12023. "yes")) {
  12024. handle_directory_request(conn, path);
  12025. } else {
  12026. mg_send_http_error(conn,
  12027. 403,
  12028. "%s",
  12029. "Error: Directory listing denied");
  12030. }
  12031. return;
  12032. }
  12033. /* 15. read a normal file with GET or HEAD */
  12034. handle_file_based_request(conn, path, &file);
  12035. #endif /* !defined(NO_FILES) */
  12036. }
  12037. static void
  12038. handle_file_based_request(struct mg_connection *conn,
  12039. const char *path,
  12040. struct mg_file *file)
  12041. {
  12042. if (!conn || !conn->dom_ctx) {
  12043. return;
  12044. }
  12045. if (0) {
  12046. #if defined(USE_LUA)
  12047. } else if (match_prefix(
  12048. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12049. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12050. path) > 0) {
  12051. if (is_in_script_path(conn, path)) {
  12052. /* Lua server page: an SSI like page containing mostly plain
  12053. * html
  12054. * code
  12055. * plus some tags with server generated contents. */
  12056. handle_lsp_request(conn, path, file, NULL);
  12057. } else {
  12058. /* Script was in an illegal path */
  12059. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12060. }
  12061. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12062. strlen(
  12063. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12064. path) > 0) {
  12065. if (is_in_script_path(conn, path)) {
  12066. /* Lua in-server module script: a CGI like script used to
  12067. * generate
  12068. * the
  12069. * entire reply. */
  12070. mg_exec_lua_script(conn, path, NULL);
  12071. } else {
  12072. /* Script was in an illegal path */
  12073. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12074. }
  12075. #endif
  12076. #if defined(USE_DUKTAPE)
  12077. } else if (match_prefix(
  12078. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12079. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12080. path) > 0) {
  12081. if (is_in_script_path(conn, path)) {
  12082. /* Call duktape to generate the page */
  12083. mg_exec_duktape_script(conn, path);
  12084. } else {
  12085. /* Script was in an illegal path */
  12086. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12087. }
  12088. #endif
  12089. #if !defined(NO_CGI)
  12090. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12091. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12092. path) > 0) {
  12093. if (is_in_script_path(conn, path)) {
  12094. /* CGI scripts may support all HTTP methods */
  12095. handle_cgi_request(conn, path);
  12096. } else {
  12097. /* Script was in an illegal path */
  12098. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12099. }
  12100. #endif /* !NO_CGI */
  12101. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12102. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12103. path) > 0) {
  12104. if (is_in_script_path(conn, path)) {
  12105. handle_ssi_file_request(conn, path, file);
  12106. } else {
  12107. /* Script was in an illegal path */
  12108. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12109. }
  12110. #if !defined(NO_CACHING)
  12111. } else if ((!conn->in_error_handler)
  12112. && is_not_modified(conn, &file->stat)) {
  12113. /* Send 304 "Not Modified" - this must not send any body data */
  12114. handle_not_modified_static_file_request(conn, file);
  12115. #endif /* !NO_CACHING */
  12116. } else {
  12117. handle_static_file_request(conn, path, file, NULL, NULL);
  12118. }
  12119. }
  12120. static void
  12121. close_all_listening_sockets(struct mg_context *ctx)
  12122. {
  12123. unsigned int i;
  12124. if (!ctx) {
  12125. return;
  12126. }
  12127. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12128. closesocket(ctx->listening_sockets[i].sock);
  12129. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12130. }
  12131. mg_free(ctx->listening_sockets);
  12132. ctx->listening_sockets = NULL;
  12133. mg_free(ctx->listening_socket_fds);
  12134. ctx->listening_socket_fds = NULL;
  12135. }
  12136. /* Valid listening port specification is: [ip_address:]port[s]
  12137. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12138. * Examples for IPv6: [::]:80, [::1]:80,
  12139. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12140. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12141. * In order to bind to both, IPv4 and IPv6, you can either add
  12142. * both ports using 8080,[::]:8080, or the short form +8080.
  12143. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12144. * one only accepting IPv4 the other only IPv6. +8080 creates
  12145. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12146. * environment, they might work differently, or might not work
  12147. * at all - it must be tested what options work best in the
  12148. * relevant network environment.
  12149. */
  12150. static int
  12151. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12152. {
  12153. unsigned int a, b, c, d, port;
  12154. int ch, len;
  12155. const char *cb;
  12156. #if defined(USE_IPV6)
  12157. char buf[100] = {0};
  12158. #endif
  12159. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12160. * Also, all-zeroes in the socket address means binding to all addresses
  12161. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12162. memset(so, 0, sizeof(*so));
  12163. so->lsa.sin.sin_family = AF_INET;
  12164. *ip_version = 0;
  12165. /* Initialize port and len as invalid. */
  12166. port = 0;
  12167. len = 0;
  12168. /* Test for different ways to format this string */
  12169. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12170. == 5) {
  12171. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12172. so->lsa.sin.sin_addr.s_addr =
  12173. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12174. so->lsa.sin.sin_port = htons((uint16_t)port);
  12175. *ip_version = 4;
  12176. #if defined(USE_IPV6)
  12177. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12178. && mg_inet_pton(
  12179. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12180. /* IPv6 address, examples: see above */
  12181. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12182. */
  12183. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12184. *ip_version = 6;
  12185. #endif
  12186. } else if ((vec->ptr[0] == '+')
  12187. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12188. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12189. /* Add 1 to len for the + character we skipped before */
  12190. len++;
  12191. #if defined(USE_IPV6)
  12192. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12193. so->lsa.sin6.sin6_family = AF_INET6;
  12194. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12195. *ip_version = 4 + 6;
  12196. #else
  12197. /* Bind to IPv4 only, since IPv6 is not built in. */
  12198. so->lsa.sin.sin_port = htons((uint16_t)port);
  12199. *ip_version = 4;
  12200. #endif
  12201. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12202. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12203. so->lsa.sin.sin_port = htons((uint16_t)port);
  12204. *ip_version = 4;
  12205. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12206. /* String could be a hostname. This check algotithm
  12207. * will only work for RFC 952 compliant hostnames,
  12208. * starting with a letter, containing only letters,
  12209. * digits and hyphen ('-'). Newer specs may allow
  12210. * more, but this is not guaranteed here, since it
  12211. * may interfere with rules for port option lists. */
  12212. /* According to RFC 1035, hostnames are restricted to 255 characters
  12213. * in total (63 between two dots). */
  12214. char hostname[256];
  12215. size_t hostnlen = (size_t)(cb - vec->ptr);
  12216. if (hostnlen >= sizeof(hostname)) {
  12217. /* This would be invalid in any case */
  12218. *ip_version = 0;
  12219. return 0;
  12220. }
  12221. memcpy(hostname, vec->ptr, hostnlen);
  12222. hostname[hostnlen] = 0;
  12223. if (mg_inet_pton(
  12224. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12225. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12226. *ip_version = 4;
  12227. so->lsa.sin.sin_family = AF_INET;
  12228. so->lsa.sin.sin_port = htons((uint16_t)port);
  12229. len += (int)(hostnlen + 1);
  12230. } else {
  12231. port = 0;
  12232. len = 0;
  12233. }
  12234. #if defined(USE_IPV6)
  12235. } else if (mg_inet_pton(AF_INET6,
  12236. vec->ptr,
  12237. &so->lsa.sin6,
  12238. sizeof(so->lsa.sin6))) {
  12239. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12240. *ip_version = 6;
  12241. so->lsa.sin6.sin6_family = AF_INET6;
  12242. so->lsa.sin.sin_port = htons((uint16_t)port);
  12243. len += (int)(hostnlen + 1);
  12244. } else {
  12245. port = 0;
  12246. len = 0;
  12247. }
  12248. #endif
  12249. }
  12250. } else {
  12251. /* Parsing failure. */
  12252. }
  12253. /* sscanf and the option splitting code ensure the following condition
  12254. */
  12255. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12256. *ip_version = 0;
  12257. return 0;
  12258. }
  12259. ch = vec->ptr[len]; /* Next character after the port number */
  12260. so->is_ssl = (ch == 's');
  12261. so->ssl_redir = (ch == 'r');
  12262. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12263. if (is_valid_port(port)
  12264. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12265. return 1;
  12266. }
  12267. /* Reset ip_version to 0 if there is an error */
  12268. *ip_version = 0;
  12269. return 0;
  12270. }
  12271. /* Is there any SSL port in use? */
  12272. static int
  12273. is_ssl_port_used(const char *ports)
  12274. {
  12275. if (ports) {
  12276. /* There are several different allowed syntax variants:
  12277. * - "80" for a single port using every network interface
  12278. * - "localhost:80" for a single port using only localhost
  12279. * - "80,localhost:8080" for two ports, one bound to localhost
  12280. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12281. * to IPv4 localhost, one to IPv6 localhost
  12282. * - "+80" use port 80 for IPv4 and IPv6
  12283. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12284. * for both: IPv4 and IPv4
  12285. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12286. * additionally port 8080 bound to localhost connections
  12287. *
  12288. * If we just look for 's' anywhere in the string, "localhost:80"
  12289. * will be detected as SSL (false positive).
  12290. * Looking for 's' after a digit may cause false positives in
  12291. * "my24service:8080".
  12292. * Looking from 's' backward if there are only ':' and numbers
  12293. * before will not work for "24service:8080" (non SSL, port 8080)
  12294. * or "24s" (SSL, port 24).
  12295. *
  12296. * Remark: Initially hostnames were not allowed to start with a
  12297. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12298. * Section 2.1).
  12299. *
  12300. * To get this correct, the entire string must be parsed as a whole,
  12301. * reading it as a list element for element and parsing with an
  12302. * algorithm equivalent to parse_port_string.
  12303. *
  12304. * In fact, we use local interface names here, not arbitrary hostnames,
  12305. * so in most cases the only name will be "localhost".
  12306. *
  12307. * So, for now, we use this simple algorithm, that may still return
  12308. * a false positive in bizarre cases.
  12309. */
  12310. int i;
  12311. int portslen = (int)strlen(ports);
  12312. char prevIsNumber = 0;
  12313. for (i = 0; i < portslen; i++) {
  12314. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12315. return 1;
  12316. }
  12317. if (ports[i] >= '0' && ports[i] <= '9') {
  12318. prevIsNumber = 1;
  12319. } else {
  12320. prevIsNumber = 0;
  12321. }
  12322. }
  12323. }
  12324. return 0;
  12325. }
  12326. static int
  12327. set_ports_option(struct mg_context *phys_ctx)
  12328. {
  12329. const char *list;
  12330. int on = 1;
  12331. #if defined(USE_IPV6)
  12332. int off = 0;
  12333. #endif
  12334. struct vec vec;
  12335. struct socket so, *ptr;
  12336. struct pollfd *pfd;
  12337. union usa usa;
  12338. socklen_t len;
  12339. int ip_version;
  12340. int portsTotal = 0;
  12341. int portsOk = 0;
  12342. if (!phys_ctx) {
  12343. return 0;
  12344. }
  12345. memset(&so, 0, sizeof(so));
  12346. memset(&usa, 0, sizeof(usa));
  12347. len = sizeof(usa);
  12348. list = phys_ctx->dd.config[LISTENING_PORTS];
  12349. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12350. portsTotal++;
  12351. if (!parse_port_string(&vec, &so, &ip_version)) {
  12352. mg_cry_internal(
  12353. fc(phys_ctx),
  12354. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12355. (int)vec.len,
  12356. vec.ptr,
  12357. portsTotal,
  12358. "[IP_ADDRESS:]PORT[s|r]");
  12359. continue;
  12360. }
  12361. #if !defined(NO_SSL)
  12362. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12363. mg_cry_internal(fc(phys_ctx),
  12364. "Cannot add SSL socket (entry %i)",
  12365. portsTotal);
  12366. continue;
  12367. }
  12368. #endif
  12369. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12370. == INVALID_SOCKET) {
  12371. mg_cry_internal(fc(phys_ctx),
  12372. "cannot create socket (entry %i)",
  12373. portsTotal);
  12374. continue;
  12375. }
  12376. #if defined(_WIN32)
  12377. /* Windows SO_REUSEADDR lets many procs binds to a
  12378. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12379. * if someone already has the socket -- DTL */
  12380. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12381. * Windows might need a few seconds before
  12382. * the same port can be used again in the
  12383. * same process, so a short Sleep may be
  12384. * required between mg_stop and mg_start.
  12385. */
  12386. if (setsockopt(so.sock,
  12387. SOL_SOCKET,
  12388. SO_EXCLUSIVEADDRUSE,
  12389. (SOCK_OPT_TYPE)&on,
  12390. sizeof(on)) != 0) {
  12391. /* Set reuse option, but don't abort on errors. */
  12392. mg_cry_internal(
  12393. fc(phys_ctx),
  12394. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12395. portsTotal);
  12396. }
  12397. #else
  12398. if (setsockopt(so.sock,
  12399. SOL_SOCKET,
  12400. SO_REUSEADDR,
  12401. (SOCK_OPT_TYPE)&on,
  12402. sizeof(on)) != 0) {
  12403. /* Set reuse option, but don't abort on errors. */
  12404. mg_cry_internal(fc(phys_ctx),
  12405. "cannot set socket option SO_REUSEADDR (entry %i)",
  12406. portsTotal);
  12407. }
  12408. #endif
  12409. if (ip_version > 4) {
  12410. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12411. #if defined(USE_IPV6)
  12412. if (ip_version > 6) {
  12413. if (so.lsa.sa.sa_family == AF_INET6
  12414. && setsockopt(so.sock,
  12415. IPPROTO_IPV6,
  12416. IPV6_V6ONLY,
  12417. (void *)&off,
  12418. sizeof(off)) != 0) {
  12419. /* Set IPv6 only option, but don't abort on errors. */
  12420. mg_cry_internal(
  12421. fc(phys_ctx),
  12422. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12423. portsTotal);
  12424. }
  12425. } else {
  12426. if (so.lsa.sa.sa_family == AF_INET6
  12427. && setsockopt(so.sock,
  12428. IPPROTO_IPV6,
  12429. IPV6_V6ONLY,
  12430. (void *)&on,
  12431. sizeof(on)) != 0) {
  12432. /* Set IPv6 only option, but don't abort on errors. */
  12433. mg_cry_internal(
  12434. fc(phys_ctx),
  12435. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12436. portsTotal);
  12437. }
  12438. }
  12439. #else
  12440. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12441. closesocket(so.sock);
  12442. so.sock = INVALID_SOCKET;
  12443. continue;
  12444. #endif
  12445. }
  12446. if (so.lsa.sa.sa_family == AF_INET) {
  12447. len = sizeof(so.lsa.sin);
  12448. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12449. mg_cry_internal(fc(phys_ctx),
  12450. "cannot bind to %.*s: %d (%s)",
  12451. (int)vec.len,
  12452. vec.ptr,
  12453. (int)ERRNO,
  12454. strerror(errno));
  12455. closesocket(so.sock);
  12456. so.sock = INVALID_SOCKET;
  12457. continue;
  12458. }
  12459. }
  12460. #if defined(USE_IPV6)
  12461. else if (so.lsa.sa.sa_family == AF_INET6) {
  12462. len = sizeof(so.lsa.sin6);
  12463. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12464. mg_cry_internal(fc(phys_ctx),
  12465. "cannot bind to IPv6 %.*s: %d (%s)",
  12466. (int)vec.len,
  12467. vec.ptr,
  12468. (int)ERRNO,
  12469. strerror(errno));
  12470. closesocket(so.sock);
  12471. so.sock = INVALID_SOCKET;
  12472. continue;
  12473. }
  12474. }
  12475. #endif
  12476. else {
  12477. mg_cry_internal(
  12478. fc(phys_ctx),
  12479. "cannot bind: address family not supported (entry %i)",
  12480. portsTotal);
  12481. closesocket(so.sock);
  12482. so.sock = INVALID_SOCKET;
  12483. continue;
  12484. }
  12485. if (listen(so.sock, SOMAXCONN) != 0) {
  12486. mg_cry_internal(fc(phys_ctx),
  12487. "cannot listen to %.*s: %d (%s)",
  12488. (int)vec.len,
  12489. vec.ptr,
  12490. (int)ERRNO,
  12491. strerror(errno));
  12492. closesocket(so.sock);
  12493. so.sock = INVALID_SOCKET;
  12494. continue;
  12495. }
  12496. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12497. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12498. int err = (int)ERRNO;
  12499. mg_cry_internal(fc(phys_ctx),
  12500. "call to getsockname failed %.*s: %d (%s)",
  12501. (int)vec.len,
  12502. vec.ptr,
  12503. err,
  12504. strerror(errno));
  12505. closesocket(so.sock);
  12506. so.sock = INVALID_SOCKET;
  12507. continue;
  12508. }
  12509. /* Update lsa port in case of random free ports */
  12510. #if defined(USE_IPV6)
  12511. if (so.lsa.sa.sa_family == AF_INET6) {
  12512. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12513. } else
  12514. #endif
  12515. {
  12516. so.lsa.sin.sin_port = usa.sin.sin_port;
  12517. }
  12518. if ((ptr = (struct socket *)
  12519. mg_realloc_ctx(phys_ctx->listening_sockets,
  12520. (phys_ctx->num_listening_sockets + 1)
  12521. * sizeof(phys_ctx->listening_sockets[0]),
  12522. phys_ctx)) == NULL) {
  12523. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12524. closesocket(so.sock);
  12525. so.sock = INVALID_SOCKET;
  12526. continue;
  12527. }
  12528. if ((pfd = (struct pollfd *)
  12529. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12530. (phys_ctx->num_listening_sockets + 1)
  12531. * sizeof(phys_ctx->listening_socket_fds[0]),
  12532. phys_ctx)) == NULL) {
  12533. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12534. closesocket(so.sock);
  12535. so.sock = INVALID_SOCKET;
  12536. mg_free(ptr);
  12537. continue;
  12538. }
  12539. set_close_on_exec(so.sock, fc(phys_ctx));
  12540. phys_ctx->listening_sockets = ptr;
  12541. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12542. phys_ctx->listening_socket_fds = pfd;
  12543. phys_ctx->num_listening_sockets++;
  12544. portsOk++;
  12545. }
  12546. if (portsOk != portsTotal) {
  12547. close_all_listening_sockets(phys_ctx);
  12548. portsOk = 0;
  12549. }
  12550. return portsOk;
  12551. }
  12552. static const char *
  12553. header_val(const struct mg_connection *conn, const char *header)
  12554. {
  12555. const char *header_value;
  12556. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12557. return "-";
  12558. } else {
  12559. return header_value;
  12560. }
  12561. }
  12562. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12563. static void log_access(const struct mg_connection *conn);
  12564. #include "external_log_access.inl"
  12565. #else
  12566. static void
  12567. log_access(const struct mg_connection *conn)
  12568. {
  12569. const struct mg_request_info *ri;
  12570. struct mg_file fi;
  12571. char date[64], src_addr[IP_ADDR_STR_LEN];
  12572. struct tm *tm;
  12573. const char *referer;
  12574. const char *user_agent;
  12575. char buf[4096];
  12576. if (!conn || !conn->dom_ctx) {
  12577. return;
  12578. }
  12579. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12580. if (mg_fopen(conn,
  12581. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12582. MG_FOPEN_MODE_APPEND,
  12583. &fi) == 0) {
  12584. fi.access.fp = NULL;
  12585. }
  12586. } else {
  12587. fi.access.fp = NULL;
  12588. }
  12589. /* Log is written to a file and/or a callback. If both are not set,
  12590. * executing the rest of the function is pointless. */
  12591. if ((fi.access.fp == NULL)
  12592. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12593. return;
  12594. }
  12595. tm = localtime(&conn->conn_birth_time);
  12596. if (tm != NULL) {
  12597. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12598. } else {
  12599. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12600. date[sizeof(date) - 1] = '\0';
  12601. }
  12602. ri = &conn->request_info;
  12603. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12604. referer = header_val(conn, "Referer");
  12605. user_agent = header_val(conn, "User-Agent");
  12606. mg_snprintf(conn,
  12607. NULL, /* Ignore truncation in access log */
  12608. buf,
  12609. sizeof(buf),
  12610. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12611. src_addr,
  12612. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12613. date,
  12614. ri->request_method ? ri->request_method : "-",
  12615. ri->request_uri ? ri->request_uri : "-",
  12616. ri->query_string ? "?" : "",
  12617. ri->query_string ? ri->query_string : "",
  12618. ri->http_version,
  12619. conn->status_code,
  12620. conn->num_bytes_sent,
  12621. referer,
  12622. user_agent);
  12623. if (conn->phys_ctx->callbacks.log_access) {
  12624. conn->phys_ctx->callbacks.log_access(conn, buf);
  12625. }
  12626. if (fi.access.fp) {
  12627. int ok = 1;
  12628. flockfile(fi.access.fp);
  12629. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12630. ok = 0;
  12631. }
  12632. if (fflush(fi.access.fp) != 0) {
  12633. ok = 0;
  12634. }
  12635. funlockfile(fi.access.fp);
  12636. if (mg_fclose(&fi.access) != 0) {
  12637. ok = 0;
  12638. }
  12639. if (!ok) {
  12640. mg_cry_internal(conn,
  12641. "Error writing log file %s",
  12642. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12643. }
  12644. }
  12645. }
  12646. #endif /* Externally provided function */
  12647. /* Verify given socket address against the ACL.
  12648. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12649. */
  12650. static int
  12651. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12652. {
  12653. int allowed, flag;
  12654. uint32_t net, mask;
  12655. struct vec vec;
  12656. if (phys_ctx) {
  12657. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12658. /* If any ACL is set, deny by default */
  12659. allowed = (list == NULL) ? '+' : '-';
  12660. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12661. flag = vec.ptr[0];
  12662. if ((flag != '+' && flag != '-')
  12663. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12664. mg_cry_internal(fc(phys_ctx),
  12665. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12666. __func__);
  12667. return -1;
  12668. }
  12669. if (net == (remote_ip & mask)) {
  12670. allowed = flag;
  12671. }
  12672. }
  12673. return allowed == '+';
  12674. }
  12675. return -1;
  12676. }
  12677. #if !defined(_WIN32)
  12678. static int
  12679. set_uid_option(struct mg_context *phys_ctx)
  12680. {
  12681. int success = 0;
  12682. if (phys_ctx) {
  12683. /* We are currently running as curr_uid. */
  12684. const uid_t curr_uid = getuid();
  12685. /* If set, we want to run as run_as_user. */
  12686. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12687. const struct passwd *to_pw = NULL;
  12688. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12689. /* run_as_user does not exist on the system. We can't proceed
  12690. * further. */
  12691. mg_cry_internal(fc(phys_ctx),
  12692. "%s: unknown user [%s]",
  12693. __func__,
  12694. run_as_user);
  12695. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12696. /* There was either no request to change user, or we're already
  12697. * running as run_as_user. Nothing else to do.
  12698. */
  12699. success = 1;
  12700. } else {
  12701. /* Valid change request. */
  12702. if (setgid(to_pw->pw_gid) == -1) {
  12703. mg_cry_internal(fc(phys_ctx),
  12704. "%s: setgid(%s): %s",
  12705. __func__,
  12706. run_as_user,
  12707. strerror(errno));
  12708. } else if (setgroups(0, NULL) == -1) {
  12709. mg_cry_internal(fc(phys_ctx),
  12710. "%s: setgroups(): %s",
  12711. __func__,
  12712. strerror(errno));
  12713. } else if (setuid(to_pw->pw_uid) == -1) {
  12714. mg_cry_internal(fc(phys_ctx),
  12715. "%s: setuid(%s): %s",
  12716. __func__,
  12717. run_as_user,
  12718. strerror(errno));
  12719. } else {
  12720. success = 1;
  12721. }
  12722. }
  12723. }
  12724. return success;
  12725. }
  12726. #endif /* !_WIN32 */
  12727. static void
  12728. tls_dtor(void *key)
  12729. {
  12730. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12731. /* key == pthread_getspecific(sTlsKey); */
  12732. if (tls) {
  12733. if (tls->is_master == 2) {
  12734. tls->is_master = -3; /* Mark memory as dead */
  12735. mg_free(tls);
  12736. }
  12737. }
  12738. pthread_setspecific(sTlsKey, NULL);
  12739. }
  12740. #if !defined(NO_SSL)
  12741. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12742. struct mg_domain_context *dom_ctx,
  12743. const char *pem,
  12744. const char *chain);
  12745. static const char *ssl_error(void);
  12746. static int
  12747. refresh_trust(struct mg_connection *conn)
  12748. {
  12749. static int reload_lock = 0;
  12750. static long int data_check = 0;
  12751. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12752. struct stat cert_buf;
  12753. long int t;
  12754. const char *pem;
  12755. const char *chain;
  12756. int should_verify_peer;
  12757. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12758. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12759. * refresh_trust still can not work. */
  12760. return 0;
  12761. }
  12762. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12763. if (chain == NULL) {
  12764. /* pem is not NULL here */
  12765. chain = pem;
  12766. }
  12767. if (*chain == 0) {
  12768. chain = NULL;
  12769. }
  12770. t = data_check;
  12771. if (stat(pem, &cert_buf) != -1) {
  12772. t = (long int)cert_buf.st_mtime;
  12773. }
  12774. if (data_check != t) {
  12775. data_check = t;
  12776. should_verify_peer = 0;
  12777. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12778. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12779. == 0) {
  12780. should_verify_peer = 1;
  12781. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12782. "optional") == 0) {
  12783. should_verify_peer = 1;
  12784. }
  12785. }
  12786. if (should_verify_peer) {
  12787. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12788. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12789. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12790. ca_file,
  12791. ca_path) != 1) {
  12792. mg_cry_internal(
  12793. fc(conn->phys_ctx),
  12794. "SSL_CTX_load_verify_locations error: %s "
  12795. "ssl_verify_peer requires setting "
  12796. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12797. "present in "
  12798. "the .conf file?",
  12799. ssl_error());
  12800. return 0;
  12801. }
  12802. }
  12803. if (1 == mg_atomic_inc(p_reload_lock)) {
  12804. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12805. == 0) {
  12806. return 0;
  12807. }
  12808. *p_reload_lock = 0;
  12809. }
  12810. }
  12811. /* lock while cert is reloading */
  12812. while (*p_reload_lock) {
  12813. sleep(1);
  12814. }
  12815. return 1;
  12816. }
  12817. #if defined(OPENSSL_API_1_1)
  12818. #else
  12819. static pthread_mutex_t *ssl_mutexes;
  12820. #endif /* OPENSSL_API_1_1 */
  12821. static int
  12822. sslize(struct mg_connection *conn,
  12823. SSL_CTX *s,
  12824. int (*func)(SSL *),
  12825. volatile int *stop_server)
  12826. {
  12827. int ret, err;
  12828. int short_trust;
  12829. unsigned i;
  12830. if (!conn) {
  12831. return 0;
  12832. }
  12833. short_trust =
  12834. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12835. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12836. if (short_trust) {
  12837. int trust_ret = refresh_trust(conn);
  12838. if (!trust_ret) {
  12839. return trust_ret;
  12840. }
  12841. }
  12842. conn->ssl = SSL_new(s);
  12843. if (conn->ssl == NULL) {
  12844. return 0;
  12845. }
  12846. SSL_set_app_data(conn->ssl, (char *)conn);
  12847. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12848. if (ret != 1) {
  12849. err = SSL_get_error(conn->ssl, ret);
  12850. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  12851. SSL_free(conn->ssl);
  12852. conn->ssl = NULL;
  12853. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12854. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12855. #if !defined(OPENSSL_API_1_1)
  12856. ERR_remove_state(0);
  12857. #endif
  12858. return 0;
  12859. }
  12860. /* SSL functions may fail and require to be called again:
  12861. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  12862. * Here "func" could be SSL_connect or SSL_accept. */
  12863. for (i = 16; i <= 1024; i *= 2) {
  12864. ret = func(conn->ssl);
  12865. if (ret != 1) {
  12866. err = SSL_get_error(conn->ssl, ret);
  12867. if ((err == SSL_ERROR_WANT_CONNECT)
  12868. || (err == SSL_ERROR_WANT_ACCEPT)
  12869. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  12870. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  12871. /* Need to retry the function call "later".
  12872. * See https://linux.die.net/man/3/ssl_get_error
  12873. * This is typical for non-blocking sockets. */
  12874. if (*stop_server) {
  12875. /* Don't wait if the server is going to be stopped. */
  12876. break;
  12877. }
  12878. mg_sleep(i);
  12879. } else if (err == SSL_ERROR_SYSCALL) {
  12880. /* This is an IO error. Look at errno. */
  12881. err = errno;
  12882. mg_cry_internal(conn, "SSL syscall error %i", err);
  12883. break;
  12884. } else {
  12885. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  12886. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  12887. break;
  12888. }
  12889. } else {
  12890. /* success */
  12891. break;
  12892. }
  12893. }
  12894. if (ret != 1) {
  12895. SSL_free(conn->ssl);
  12896. conn->ssl = NULL;
  12897. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12898. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12899. #if !defined(OPENSSL_API_1_1)
  12900. ERR_remove_state(0);
  12901. #endif
  12902. return 0;
  12903. }
  12904. return 1;
  12905. }
  12906. /* Return OpenSSL error message (from CRYPTO lib) */
  12907. static const char *
  12908. ssl_error(void)
  12909. {
  12910. unsigned long err;
  12911. err = ERR_get_error();
  12912. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  12913. }
  12914. static int
  12915. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  12916. {
  12917. int i;
  12918. const char hexdigit[] = "0123456789abcdef";
  12919. if ((memlen <= 0) || (buflen <= 0)) {
  12920. return 0;
  12921. }
  12922. if (buflen < (3 * memlen)) {
  12923. return 0;
  12924. }
  12925. for (i = 0; i < memlen; i++) {
  12926. if (i > 0) {
  12927. buf[3 * i - 1] = ' ';
  12928. }
  12929. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12930. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12931. }
  12932. buf[3 * memlen - 1] = 0;
  12933. return 1;
  12934. }
  12935. static void
  12936. ssl_get_client_cert_info(struct mg_connection *conn)
  12937. {
  12938. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12939. if (cert) {
  12940. char str_subject[1024];
  12941. char str_issuer[1024];
  12942. char str_finger[1024];
  12943. unsigned char buf[256];
  12944. char *str_serial = NULL;
  12945. unsigned int ulen;
  12946. int ilen;
  12947. unsigned char *tmp_buf;
  12948. unsigned char *tmp_p;
  12949. /* Handle to algorithm used for fingerprint */
  12950. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12951. /* Get Subject and issuer */
  12952. X509_NAME *subj = X509_get_subject_name(cert);
  12953. X509_NAME *iss = X509_get_issuer_name(cert);
  12954. /* Get serial number */
  12955. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12956. /* Translate serial number to a hex string */
  12957. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12958. str_serial = BN_bn2hex(serial_bn);
  12959. BN_free(serial_bn);
  12960. /* Translate subject and issuer to a string */
  12961. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12962. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12963. /* Calculate SHA1 fingerprint and store as a hex string */
  12964. ulen = 0;
  12965. /* ASN1_digest is deprecated. Do the calculation manually,
  12966. * using EVP_Digest. */
  12967. ilen = i2d_X509(cert, NULL);
  12968. tmp_buf = (ilen > 0)
  12969. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  12970. conn->phys_ctx)
  12971. : NULL;
  12972. if (tmp_buf) {
  12973. tmp_p = tmp_buf;
  12974. (void)i2d_X509(cert, &tmp_p);
  12975. if (!EVP_Digest(
  12976. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12977. ulen = 0;
  12978. }
  12979. mg_free(tmp_buf);
  12980. }
  12981. if (!hexdump2string(
  12982. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12983. *str_finger = 0;
  12984. }
  12985. conn->request_info.client_cert = (struct mg_client_cert *)
  12986. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  12987. if (conn->request_info.client_cert) {
  12988. conn->request_info.client_cert->peer_cert = (void *)cert;
  12989. conn->request_info.client_cert->subject =
  12990. mg_strdup_ctx(str_subject, conn->phys_ctx);
  12991. conn->request_info.client_cert->issuer =
  12992. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  12993. conn->request_info.client_cert->serial =
  12994. mg_strdup_ctx(str_serial, conn->phys_ctx);
  12995. conn->request_info.client_cert->finger =
  12996. mg_strdup_ctx(str_finger, conn->phys_ctx);
  12997. } else {
  12998. mg_cry_internal(conn,
  12999. "%s",
  13000. "Out of memory: Cannot allocate memory for client "
  13001. "certificate");
  13002. }
  13003. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13004. * see https://linux.die.net/man/3/bn_bn2hex */
  13005. OPENSSL_free(str_serial);
  13006. }
  13007. }
  13008. #if defined(OPENSSL_API_1_1)
  13009. #else
  13010. static void
  13011. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13012. {
  13013. (void)line;
  13014. (void)file;
  13015. if (mode & 1) {
  13016. /* 1 is CRYPTO_LOCK */
  13017. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13018. } else {
  13019. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13020. }
  13021. }
  13022. #endif /* OPENSSL_API_1_1 */
  13023. #if !defined(NO_SSL_DL)
  13024. static void *
  13025. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13026. {
  13027. union {
  13028. void *p;
  13029. void (*fp)(void);
  13030. } u;
  13031. void *dll_handle;
  13032. struct ssl_func *fp;
  13033. int ok;
  13034. int truncated = 0;
  13035. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13036. mg_snprintf(NULL,
  13037. NULL, /* No truncation check for ebuf */
  13038. ebuf,
  13039. ebuf_len,
  13040. "%s: cannot load %s",
  13041. __func__,
  13042. dll_name);
  13043. return NULL;
  13044. }
  13045. ok = 1;
  13046. for (fp = sw; fp->name != NULL; fp++) {
  13047. #if defined(_WIN32)
  13048. /* GetProcAddress() returns pointer to function */
  13049. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13050. #else
  13051. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13052. * pointers to function pointers. We need to use a union to make a
  13053. * cast. */
  13054. u.p = dlsym(dll_handle, fp->name);
  13055. #endif /* _WIN32 */
  13056. if (u.fp == NULL) {
  13057. if (ok) {
  13058. mg_snprintf(NULL,
  13059. &truncated,
  13060. ebuf,
  13061. ebuf_len,
  13062. "%s: %s: cannot find %s",
  13063. __func__,
  13064. dll_name,
  13065. fp->name);
  13066. ok = 0;
  13067. } else {
  13068. size_t cur_len = strlen(ebuf);
  13069. if (!truncated) {
  13070. mg_snprintf(NULL,
  13071. &truncated,
  13072. ebuf + cur_len,
  13073. ebuf_len - cur_len - 3,
  13074. ", %s",
  13075. fp->name);
  13076. if (truncated) {
  13077. /* If truncated, add "..." */
  13078. strcat(ebuf, "...");
  13079. }
  13080. }
  13081. }
  13082. /* Debug:
  13083. * printf("Missing function: %s\n", fp->name); */
  13084. } else {
  13085. fp->ptr = u.fp;
  13086. }
  13087. }
  13088. if (!ok) {
  13089. (void)dlclose(dll_handle);
  13090. return NULL;
  13091. }
  13092. return dll_handle;
  13093. }
  13094. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13095. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13096. #endif /* NO_SSL_DL */
  13097. #if defined(SSL_ALREADY_INITIALIZED)
  13098. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13099. #else
  13100. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13101. #endif
  13102. static int
  13103. initialize_ssl(char *ebuf, size_t ebuf_len)
  13104. {
  13105. #if defined(OPENSSL_API_1_1)
  13106. if (ebuf_len > 0) {
  13107. ebuf[0] = 0;
  13108. }
  13109. #if !defined(NO_SSL_DL)
  13110. if (!cryptolib_dll_handle) {
  13111. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13112. if (!cryptolib_dll_handle) {
  13113. mg_snprintf(NULL,
  13114. NULL, /* No truncation check for ebuf */
  13115. ebuf,
  13116. ebuf_len,
  13117. "%s: error loading library %s",
  13118. __func__,
  13119. CRYPTO_LIB);
  13120. DEBUG_TRACE("%s", ebuf);
  13121. return 0;
  13122. }
  13123. }
  13124. #endif /* NO_SSL_DL */
  13125. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13126. return 1;
  13127. }
  13128. #else /* not OPENSSL_API_1_1 */
  13129. int i, num_locks;
  13130. size_t size;
  13131. if (ebuf_len > 0) {
  13132. ebuf[0] = 0;
  13133. }
  13134. #if !defined(NO_SSL_DL)
  13135. if (!cryptolib_dll_handle) {
  13136. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13137. if (!cryptolib_dll_handle) {
  13138. mg_snprintf(NULL,
  13139. NULL, /* No truncation check for ebuf */
  13140. ebuf,
  13141. ebuf_len,
  13142. "%s: error loading library %s",
  13143. __func__,
  13144. CRYPTO_LIB);
  13145. DEBUG_TRACE("%s", ebuf);
  13146. return 0;
  13147. }
  13148. }
  13149. #endif /* NO_SSL_DL */
  13150. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13151. return 1;
  13152. }
  13153. /* Initialize locking callbacks, needed for thread safety.
  13154. * http://www.openssl.org/support/faq.html#PROG1
  13155. */
  13156. num_locks = CRYPTO_num_locks();
  13157. if (num_locks < 0) {
  13158. num_locks = 0;
  13159. }
  13160. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13161. /* allocate mutex array, if required */
  13162. if (num_locks == 0) {
  13163. /* No mutex array required */
  13164. ssl_mutexes = NULL;
  13165. } else {
  13166. /* Mutex array required - allocate it */
  13167. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13168. /* Check OOM */
  13169. if (ssl_mutexes == NULL) {
  13170. mg_snprintf(NULL,
  13171. NULL, /* No truncation check for ebuf */
  13172. ebuf,
  13173. ebuf_len,
  13174. "%s: cannot allocate mutexes: %s",
  13175. __func__,
  13176. ssl_error());
  13177. DEBUG_TRACE("%s", ebuf);
  13178. return 0;
  13179. }
  13180. /* initialize mutex array */
  13181. for (i = 0; i < num_locks; i++) {
  13182. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13183. mg_snprintf(NULL,
  13184. NULL, /* No truncation check for ebuf */
  13185. ebuf,
  13186. ebuf_len,
  13187. "%s: error initializing mutex %i of %i",
  13188. __func__,
  13189. i,
  13190. num_locks);
  13191. DEBUG_TRACE("%s", ebuf);
  13192. mg_free(ssl_mutexes);
  13193. return 0;
  13194. }
  13195. }
  13196. }
  13197. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13198. CRYPTO_set_id_callback(&mg_current_thread_id);
  13199. #endif /* OPENSSL_API_1_1 */
  13200. #if !defined(NO_SSL_DL)
  13201. if (!ssllib_dll_handle) {
  13202. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13203. if (!ssllib_dll_handle) {
  13204. #if !defined(OPENSSL_API_1_1)
  13205. mg_free(ssl_mutexes);
  13206. #endif
  13207. DEBUG_TRACE("%s", ebuf);
  13208. return 0;
  13209. }
  13210. }
  13211. #endif /* NO_SSL_DL */
  13212. #if defined(OPENSSL_API_1_1)
  13213. /* Initialize SSL library */
  13214. OPENSSL_init_ssl(0, NULL);
  13215. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13216. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13217. NULL);
  13218. #else
  13219. /* Initialize SSL library */
  13220. SSL_library_init();
  13221. SSL_load_error_strings();
  13222. #endif
  13223. return 1;
  13224. }
  13225. static int
  13226. ssl_use_pem_file(struct mg_context *phys_ctx,
  13227. struct mg_domain_context *dom_ctx,
  13228. const char *pem,
  13229. const char *chain)
  13230. {
  13231. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13232. mg_cry_internal(fc(phys_ctx),
  13233. "%s: cannot open certificate file %s: %s",
  13234. __func__,
  13235. pem,
  13236. ssl_error());
  13237. return 0;
  13238. }
  13239. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13240. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13241. mg_cry_internal(fc(phys_ctx),
  13242. "%s: cannot open private key file %s: %s",
  13243. __func__,
  13244. pem,
  13245. ssl_error());
  13246. return 0;
  13247. }
  13248. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13249. mg_cry_internal(fc(phys_ctx),
  13250. "%s: certificate and private key do not match: %s",
  13251. __func__,
  13252. pem);
  13253. return 0;
  13254. }
  13255. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13256. * chain files that contain private keys and certificates in
  13257. * SSL_CTX_use_certificate_chain_file.
  13258. * The CivetWeb-Server used pem-Files that contained both information.
  13259. * In order to make wolfSSL work, it is split in two files.
  13260. * One file that contains key and certificate used by the server and
  13261. * an optional chain file for the ssl stack.
  13262. */
  13263. if (chain) {
  13264. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13265. mg_cry_internal(fc(phys_ctx),
  13266. "%s: cannot use certificate chain file %s: %s",
  13267. __func__,
  13268. pem,
  13269. ssl_error());
  13270. return 0;
  13271. }
  13272. }
  13273. return 1;
  13274. }
  13275. #if defined(OPENSSL_API_1_1)
  13276. static unsigned long
  13277. ssl_get_protocol(int version_id)
  13278. {
  13279. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13280. if (version_id > 0)
  13281. ret |= SSL_OP_NO_SSLv2;
  13282. if (version_id > 1)
  13283. ret |= SSL_OP_NO_SSLv3;
  13284. if (version_id > 2)
  13285. ret |= SSL_OP_NO_TLSv1;
  13286. if (version_id > 3)
  13287. ret |= SSL_OP_NO_TLSv1_1;
  13288. return ret;
  13289. }
  13290. #else
  13291. static long
  13292. ssl_get_protocol(int version_id)
  13293. {
  13294. long ret = (long)SSL_OP_ALL;
  13295. if (version_id > 0)
  13296. ret |= SSL_OP_NO_SSLv2;
  13297. if (version_id > 1)
  13298. ret |= SSL_OP_NO_SSLv3;
  13299. if (version_id > 2)
  13300. ret |= SSL_OP_NO_TLSv1;
  13301. if (version_id > 3)
  13302. ret |= SSL_OP_NO_TLSv1_1;
  13303. return ret;
  13304. }
  13305. #endif /* OPENSSL_API_1_1 */
  13306. /* SSL callback documentation:
  13307. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13308. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13309. * https://linux.die.net/man/3/ssl_set_info_callback */
  13310. /* Note: There is no "const" for the first argument in the documentation,
  13311. * however some (maybe most, but not all) headers of OpenSSL versions /
  13312. * OpenSSL compatibility layers have it. Having a different definition
  13313. * will cause a warning in C and an error in C++. With inconsitent
  13314. * definitions of this function, having a warning in one version or
  13315. * another is unavoidable. */
  13316. static void
  13317. ssl_info_callback(SSL *ssl, int what, int ret)
  13318. {
  13319. (void)ret;
  13320. if (what & SSL_CB_HANDSHAKE_START) {
  13321. SSL_get_app_data(ssl);
  13322. }
  13323. if (what & SSL_CB_HANDSHAKE_DONE) {
  13324. /* TODO: check for openSSL 1.1 */
  13325. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13326. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13327. }
  13328. }
  13329. static int
  13330. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13331. {
  13332. struct mg_context *ctx = (struct mg_context *)arg;
  13333. struct mg_domain_context *dom =
  13334. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13335. #if defined(__GNUC__) || defined(__MINGW32__)
  13336. #pragma GCC diagnostic push
  13337. #pragma GCC diagnostic ignored "-Wcast-align"
  13338. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13339. /* We used an aligned pointer in SSL_set_app_data */
  13340. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13341. #if defined(__GNUC__) || defined(__MINGW32__)
  13342. #pragma GCC diagnostic pop
  13343. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13344. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13345. (void)ad;
  13346. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13347. DEBUG_TRACE("%s", "internal error - assertion failed");
  13348. return SSL_TLSEXT_ERR_NOACK;
  13349. }
  13350. /* Old clients (Win XP) will not support SNI. Then, there
  13351. * is no server name available in the request - we can
  13352. * only work with the default certificate.
  13353. * Multiple HTTPS hosts on one IP+port are only possible
  13354. * with a certificate containing all alternative names.
  13355. */
  13356. if ((servername == NULL) || (*servername == 0)) {
  13357. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13358. conn->dom_ctx = &(ctx->dd);
  13359. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13360. return SSL_TLSEXT_ERR_NOACK;
  13361. }
  13362. DEBUG_TRACE("TLS connection to host %s", servername);
  13363. while (dom) {
  13364. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13365. /* Found matching domain */
  13366. DEBUG_TRACE("TLS domain %s found",
  13367. dom->config[AUTHENTICATION_DOMAIN]);
  13368. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13369. conn->dom_ctx = dom;
  13370. return SSL_TLSEXT_ERR_OK;
  13371. }
  13372. dom = dom->next;
  13373. }
  13374. /* Default domain */
  13375. DEBUG_TRACE("TLS default domain %s used",
  13376. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13377. conn->dom_ctx = &(ctx->dd);
  13378. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13379. return SSL_TLSEXT_ERR_OK;
  13380. }
  13381. /* Setup SSL CTX as required by CivetWeb */
  13382. static int
  13383. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13384. struct mg_domain_context *dom_ctx,
  13385. const char *pem,
  13386. const char *chain)
  13387. {
  13388. int callback_ret;
  13389. int should_verify_peer;
  13390. int peer_certificate_optional;
  13391. const char *ca_path;
  13392. const char *ca_file;
  13393. int use_default_verify_paths;
  13394. int verify_depth;
  13395. struct timespec now_mt;
  13396. md5_byte_t ssl_context_id[16];
  13397. md5_state_t md5state;
  13398. int protocol_ver;
  13399. #if defined(OPENSSL_API_1_1)
  13400. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13401. mg_cry_internal(fc(phys_ctx),
  13402. "SSL_CTX_new (server) error: %s",
  13403. ssl_error());
  13404. return 0;
  13405. }
  13406. #else
  13407. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13408. mg_cry_internal(fc(phys_ctx),
  13409. "SSL_CTX_new (server) error: %s",
  13410. ssl_error());
  13411. return 0;
  13412. }
  13413. #endif /* OPENSSL_API_1_1 */
  13414. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13415. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13416. | SSL_OP_NO_TLSv1_1);
  13417. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13418. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13419. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13420. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13421. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13422. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13423. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13424. #if !defined(NO_SSL_DL)
  13425. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13426. #endif /* NO_SSL_DL */
  13427. #if defined(__clang__)
  13428. #pragma clang diagnostic push
  13429. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  13430. #endif
  13431. #if defined(__GNUC__) || defined(__MINGW32__)
  13432. #pragma GCC diagnostic push
  13433. #pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
  13434. #endif
  13435. /* Depending on the OpenSSL version, the callback may be
  13436. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  13437. * yielding in an "incompatible-pointer-type" warning for the other
  13438. * version. It seems to be "unclear" what is correct:
  13439. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13440. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13441. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13442. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13443. * Disable this warning here.
  13444. * Alternative would be a version dependent ssl_info_callback and
  13445. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  13446. */
  13447. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13448. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13449. ssl_servername_callback);
  13450. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13451. #if defined(__GNUC__) || defined(__MINGW32__)
  13452. #pragma GCC diagnostic pop
  13453. #endif
  13454. #if defined(__clang__)
  13455. #pragma clang diagnostic pop
  13456. #endif
  13457. /* If a callback has been specified, call it. */
  13458. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13459. ? 0
  13460. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13461. phys_ctx->user_data));
  13462. /* If callback returns 0, civetweb sets up the SSL certificate.
  13463. * If it returns 1, civetweb assumes the calback already did this.
  13464. * If it returns -1, initializing ssl fails. */
  13465. if (callback_ret < 0) {
  13466. mg_cry_internal(fc(phys_ctx),
  13467. "SSL callback returned error: %i",
  13468. callback_ret);
  13469. return 0;
  13470. }
  13471. if (callback_ret > 0) {
  13472. /* Callback did everything. */
  13473. return 1;
  13474. }
  13475. /* Use some combination of start time, domain and port as a SSL
  13476. * context ID. This should be unique on the current machine. */
  13477. md5_init(&md5state);
  13478. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13479. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13480. md5_append(&md5state,
  13481. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13482. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13483. md5_append(&md5state,
  13484. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13485. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13486. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13487. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13488. md5_finish(&md5state, ssl_context_id);
  13489. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13490. (unsigned char *)ssl_context_id,
  13491. sizeof(ssl_context_id));
  13492. if (pem != NULL) {
  13493. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13494. return 0;
  13495. }
  13496. }
  13497. /* Should we support client certificates? */
  13498. /* Default is "no". */
  13499. should_verify_peer = 0;
  13500. peer_certificate_optional = 0;
  13501. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13502. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13503. /* Yes, they are mandatory */
  13504. should_verify_peer = 1;
  13505. peer_certificate_optional = 0;
  13506. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13507. "optional") == 0) {
  13508. /* Yes, they are optional */
  13509. should_verify_peer = 1;
  13510. peer_certificate_optional = 1;
  13511. }
  13512. }
  13513. use_default_verify_paths =
  13514. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13515. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13516. == 0);
  13517. if (should_verify_peer) {
  13518. ca_path = dom_ctx->config[SSL_CA_PATH];
  13519. ca_file = dom_ctx->config[SSL_CA_FILE];
  13520. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13521. != 1) {
  13522. mg_cry_internal(fc(phys_ctx),
  13523. "SSL_CTX_load_verify_locations error: %s "
  13524. "ssl_verify_peer requires setting "
  13525. "either ssl_ca_path or ssl_ca_file. "
  13526. "Is any of them present in the "
  13527. ".conf file?",
  13528. ssl_error());
  13529. return 0;
  13530. }
  13531. if (peer_certificate_optional) {
  13532. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13533. } else {
  13534. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13535. SSL_VERIFY_PEER
  13536. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13537. NULL);
  13538. }
  13539. if (use_default_verify_paths
  13540. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13541. mg_cry_internal(fc(phys_ctx),
  13542. "SSL_CTX_set_default_verify_paths error: %s",
  13543. ssl_error());
  13544. return 0;
  13545. }
  13546. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13547. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13548. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13549. }
  13550. }
  13551. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13552. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13553. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  13554. mg_cry_internal(fc(phys_ctx),
  13555. "SSL_CTX_set_cipher_list error: %s",
  13556. ssl_error());
  13557. }
  13558. }
  13559. return 1;
  13560. }
  13561. /* Check if SSL is required.
  13562. * If so, dynamically load SSL library
  13563. * and set up ctx->ssl_ctx pointer. */
  13564. static int
  13565. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13566. {
  13567. void *ssl_ctx = 0;
  13568. int callback_ret;
  13569. const char *pem;
  13570. const char *chain;
  13571. char ebuf[128];
  13572. if (!phys_ctx) {
  13573. return 0;
  13574. }
  13575. if (!dom_ctx) {
  13576. dom_ctx = &(phys_ctx->dd);
  13577. }
  13578. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13579. /* No SSL port is set. No need to setup SSL. */
  13580. return 1;
  13581. }
  13582. /* Check for external SSL_CTX */
  13583. callback_ret =
  13584. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13585. ? 0
  13586. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13587. phys_ctx->user_data));
  13588. if (callback_ret < 0) {
  13589. mg_cry_internal(fc(phys_ctx),
  13590. "external_ssl_ctx callback returned error: %i",
  13591. callback_ret);
  13592. return 0;
  13593. } else if (callback_ret > 0) {
  13594. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13595. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13596. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13597. return 0;
  13598. }
  13599. return 1;
  13600. }
  13601. /* else: external_ssl_ctx does not exist or returns 0,
  13602. * CivetWeb should continue initializing SSL */
  13603. /* If PEM file is not specified and the init_ssl callback
  13604. * is not specified, setup will fail. */
  13605. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13606. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13607. /* No certificate and no callback:
  13608. * Essential data to set up TLS is missing.
  13609. */
  13610. mg_cry_internal(fc(phys_ctx),
  13611. "Initializing SSL failed: -%s is not set",
  13612. config_options[SSL_CERTIFICATE].name);
  13613. return 0;
  13614. }
  13615. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13616. if (chain == NULL) {
  13617. chain = pem;
  13618. }
  13619. if ((chain != NULL) && (*chain == 0)) {
  13620. chain = NULL;
  13621. }
  13622. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13623. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13624. return 0;
  13625. }
  13626. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13627. }
  13628. static void
  13629. uninitialize_ssl(void)
  13630. {
  13631. #if defined(OPENSSL_API_1_1)
  13632. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13633. /* Shutdown according to
  13634. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13635. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13636. */
  13637. CONF_modules_unload(1);
  13638. #else
  13639. int i;
  13640. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13641. /* Shutdown according to
  13642. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13643. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13644. */
  13645. CRYPTO_set_locking_callback(NULL);
  13646. CRYPTO_set_id_callback(NULL);
  13647. ENGINE_cleanup();
  13648. CONF_modules_unload(1);
  13649. ERR_free_strings();
  13650. EVP_cleanup();
  13651. CRYPTO_cleanup_all_ex_data();
  13652. ERR_remove_state(0);
  13653. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13654. pthread_mutex_destroy(&ssl_mutexes[i]);
  13655. }
  13656. mg_free(ssl_mutexes);
  13657. ssl_mutexes = NULL;
  13658. #endif /* OPENSSL_API_1_1 */
  13659. }
  13660. }
  13661. #endif /* !NO_SSL */
  13662. static int
  13663. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13664. {
  13665. if (phys_ctx) {
  13666. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13667. const char *path;
  13668. if (!dom_ctx) {
  13669. dom_ctx = &(phys_ctx->dd);
  13670. }
  13671. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13672. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13673. mg_cry_internal(fc(phys_ctx),
  13674. "Cannot open %s: %s",
  13675. path,
  13676. strerror(ERRNO));
  13677. return 0;
  13678. }
  13679. return 1;
  13680. }
  13681. return 0;
  13682. }
  13683. static int
  13684. set_acl_option(struct mg_context *phys_ctx)
  13685. {
  13686. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13687. }
  13688. static void
  13689. reset_per_request_attributes(struct mg_connection *conn)
  13690. {
  13691. if (!conn) {
  13692. return;
  13693. }
  13694. conn->connection_type =
  13695. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13696. conn->num_bytes_sent = conn->consumed_content = 0;
  13697. conn->path_info = NULL;
  13698. conn->status_code = -1;
  13699. conn->content_len = -1;
  13700. conn->is_chunked = 0;
  13701. conn->must_close = 0;
  13702. conn->request_len = 0;
  13703. conn->throttle = 0;
  13704. conn->data_len = 0;
  13705. conn->chunk_remainder = 0;
  13706. conn->accept_gzip = 0;
  13707. conn->response_info.content_length = conn->request_info.content_length = -1;
  13708. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13709. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13710. conn->response_info.status_text = NULL;
  13711. conn->response_info.status_code = 0;
  13712. conn->request_info.remote_user = NULL;
  13713. conn->request_info.request_method = NULL;
  13714. conn->request_info.request_uri = NULL;
  13715. conn->request_info.local_uri = NULL;
  13716. #if defined(MG_LEGACY_INTERFACE)
  13717. /* Legacy before split into local_uri and request_uri */
  13718. conn->request_info.uri = NULL;
  13719. #endif
  13720. }
  13721. #if 0
  13722. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13723. * Leave this function here (commented out) for reference until
  13724. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13725. * no longer required.
  13726. */
  13727. static int
  13728. set_sock_timeout(SOCKET sock, int milliseconds)
  13729. {
  13730. int r0 = 0, r1, r2;
  13731. #if defined(_WIN32)
  13732. /* Windows specific */
  13733. DWORD tv = (DWORD)milliseconds;
  13734. #else
  13735. /* Linux, ... (not Windows) */
  13736. struct timeval tv;
  13737. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13738. * max. time waiting for the acknowledged of TCP data before the connection
  13739. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13740. * If this option is not set, the default timeout of 20-30 minutes is used.
  13741. */
  13742. /* #define TCP_USER_TIMEOUT (18) */
  13743. #if defined(TCP_USER_TIMEOUT)
  13744. unsigned int uto = (unsigned int)milliseconds;
  13745. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13746. #endif
  13747. memset(&tv, 0, sizeof(tv));
  13748. tv.tv_sec = milliseconds / 1000;
  13749. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13750. #endif /* _WIN32 */
  13751. r1 = setsockopt(
  13752. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13753. r2 = setsockopt(
  13754. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13755. return r0 || r1 || r2;
  13756. }
  13757. #endif
  13758. static int
  13759. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13760. {
  13761. if (setsockopt(sock,
  13762. IPPROTO_TCP,
  13763. TCP_NODELAY,
  13764. (SOCK_OPT_TYPE)&nodelay_on,
  13765. sizeof(nodelay_on)) != 0) {
  13766. /* Error */
  13767. return 1;
  13768. }
  13769. /* OK */
  13770. return 0;
  13771. }
  13772. static void
  13773. close_socket_gracefully(struct mg_connection *conn)
  13774. {
  13775. #if defined(_WIN32)
  13776. char buf[MG_BUF_LEN];
  13777. int n;
  13778. #endif
  13779. struct linger linger;
  13780. int error_code = 0;
  13781. int linger_timeout = -2;
  13782. socklen_t opt_len = sizeof(error_code);
  13783. if (!conn) {
  13784. return;
  13785. }
  13786. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13787. * "Note that enabling a nonzero timeout on a nonblocking socket
  13788. * is not recommended.", so set it to blocking now */
  13789. set_blocking_mode(conn->client.sock);
  13790. /* Send FIN to the client */
  13791. shutdown(conn->client.sock, SHUTDOWN_WR);
  13792. #if defined(_WIN32)
  13793. /* Read and discard pending incoming data. If we do not do that and
  13794. * close
  13795. * the socket, the data in the send buffer may be discarded. This
  13796. * behaviour is seen on Windows, when client keeps sending data
  13797. * when server decides to close the connection; then when client
  13798. * does recv() it gets no data back. */
  13799. do {
  13800. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13801. } while (n > 0);
  13802. #endif
  13803. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13804. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13805. }
  13806. /* Set linger option according to configuration */
  13807. if (linger_timeout >= 0) {
  13808. /* Set linger option to avoid socket hanging out after close. This
  13809. * prevent ephemeral port exhaust problem under high QPS. */
  13810. linger.l_onoff = 1;
  13811. #if defined(_MSC_VER)
  13812. #pragma warning(push)
  13813. #pragma warning(disable : 4244)
  13814. #endif
  13815. #if defined(__GNUC__) || defined(__MINGW32__)
  13816. #pragma GCC diagnostic push
  13817. #pragma GCC diagnostic ignored "-Wconversion"
  13818. #endif
  13819. /* Data type of linger structure elements may differ,
  13820. * so we don't know what cast we need here.
  13821. * Disable type conversion warnings. */
  13822. linger.l_linger = (linger_timeout + 999) / 1000;
  13823. #if defined(__GNUC__) || defined(__MINGW32__)
  13824. #pragma GCC diagnostic pop
  13825. #endif
  13826. #if defined(_MSC_VER)
  13827. #pragma warning(pop)
  13828. #endif
  13829. } else {
  13830. linger.l_onoff = 0;
  13831. linger.l_linger = 0;
  13832. }
  13833. if (linger_timeout < -1) {
  13834. /* Default: don't configure any linger */
  13835. } else if (getsockopt(conn->client.sock,
  13836. SOL_SOCKET,
  13837. SO_ERROR,
  13838. #if defined(_WIN32) /* WinSock uses different data type here */
  13839. (char *)&error_code,
  13840. #else
  13841. &error_code,
  13842. #endif
  13843. &opt_len) != 0) {
  13844. /* Cannot determine if socket is already closed. This should
  13845. * not occur and never did in a test. Log an error message
  13846. * and continue. */
  13847. mg_cry_internal(conn,
  13848. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13849. __func__,
  13850. strerror(ERRNO));
  13851. } else if (error_code == ECONNRESET) {
  13852. /* Socket already closed by client/peer, close socket without linger
  13853. */
  13854. } else {
  13855. /* Set linger timeout */
  13856. if (setsockopt(conn->client.sock,
  13857. SOL_SOCKET,
  13858. SO_LINGER,
  13859. (char *)&linger,
  13860. sizeof(linger)) != 0) {
  13861. mg_cry_internal(
  13862. conn,
  13863. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13864. __func__,
  13865. linger.l_onoff,
  13866. linger.l_linger,
  13867. strerror(ERRNO));
  13868. }
  13869. }
  13870. /* Now we know that our FIN is ACK-ed, safe to close */
  13871. closesocket(conn->client.sock);
  13872. conn->client.sock = INVALID_SOCKET;
  13873. }
  13874. static void
  13875. close_connection(struct mg_connection *conn)
  13876. {
  13877. #if defined(USE_SERVER_STATS)
  13878. conn->conn_state = 6; /* to close */
  13879. #endif
  13880. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13881. if (conn->lua_websocket_state) {
  13882. lua_websocket_close(conn, conn->lua_websocket_state);
  13883. conn->lua_websocket_state = NULL;
  13884. }
  13885. #endif
  13886. mg_lock_connection(conn);
  13887. /* Set close flag, so keep-alive loops will stop */
  13888. conn->must_close = 1;
  13889. /* call the connection_close callback if assigned */
  13890. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13891. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13892. conn->phys_ctx->callbacks.connection_close(conn);
  13893. }
  13894. }
  13895. /* Reset user data, after close callback is called.
  13896. * Do not reuse it. If the user needs a destructor,
  13897. * it must be done in the connection_close callback. */
  13898. mg_set_user_connection_data(conn, NULL);
  13899. #if defined(USE_SERVER_STATS)
  13900. conn->conn_state = 7; /* closing */
  13901. #endif
  13902. #if !defined(NO_SSL)
  13903. if (conn->ssl != NULL) {
  13904. /* Run SSL_shutdown twice to ensure completely close SSL connection
  13905. */
  13906. SSL_shutdown(conn->ssl);
  13907. SSL_free(conn->ssl);
  13908. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13909. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13910. #if !defined(OPENSSL_API_1_1)
  13911. ERR_remove_state(0);
  13912. #endif
  13913. conn->ssl = NULL;
  13914. }
  13915. #endif
  13916. if (conn->client.sock != INVALID_SOCKET) {
  13917. close_socket_gracefully(conn);
  13918. conn->client.sock = INVALID_SOCKET;
  13919. }
  13920. if (conn->host) {
  13921. mg_free((void *)conn->host);
  13922. conn->host = NULL;
  13923. }
  13924. mg_unlock_connection(conn);
  13925. #if defined(USE_SERVER_STATS)
  13926. conn->conn_state = 8; /* closed */
  13927. #endif
  13928. }
  13929. void
  13930. mg_close_connection(struct mg_connection *conn)
  13931. {
  13932. #if defined(USE_WEBSOCKET)
  13933. struct mg_context *client_ctx = NULL;
  13934. #endif /* defined(USE_WEBSOCKET) */
  13935. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13936. return;
  13937. }
  13938. #if defined(USE_WEBSOCKET)
  13939. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13940. if (conn->in_websocket_handling) {
  13941. /* Set close flag, so the server thread can exit. */
  13942. conn->must_close = 1;
  13943. return;
  13944. }
  13945. }
  13946. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  13947. unsigned int i;
  13948. /* ws/wss client */
  13949. client_ctx = conn->phys_ctx;
  13950. /* client context: loops must end */
  13951. client_ctx->stop_flag = 1;
  13952. conn->must_close = 1;
  13953. /* We need to get the client thread out of the select/recv call
  13954. * here. */
  13955. /* Since we use a sleep quantum of some seconds to check for recv
  13956. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13957. /* join worker thread */
  13958. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13959. if (client_ctx->worker_threadids[i] != 0) {
  13960. mg_join_thread(client_ctx->worker_threadids[i]);
  13961. }
  13962. }
  13963. }
  13964. #endif /* defined(USE_WEBSOCKET) */
  13965. close_connection(conn);
  13966. #if !defined(NO_SSL)
  13967. if (conn->client_ssl_ctx != NULL) {
  13968. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13969. }
  13970. #endif
  13971. #if defined(USE_WEBSOCKET)
  13972. if (client_ctx != NULL) {
  13973. /* free context */
  13974. mg_free(client_ctx->worker_threadids);
  13975. mg_free(client_ctx);
  13976. (void)pthread_mutex_destroy(&conn->mutex);
  13977. mg_free(conn);
  13978. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13979. mg_free(conn);
  13980. }
  13981. #else
  13982. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13983. mg_free(conn);
  13984. }
  13985. #endif /* defined(USE_WEBSOCKET) */
  13986. }
  13987. /* Only for memory statistics */
  13988. static struct mg_context common_client_context;
  13989. static struct mg_connection *
  13990. mg_connect_client_impl(const struct mg_client_options *client_options,
  13991. int use_ssl,
  13992. char *ebuf,
  13993. size_t ebuf_len)
  13994. {
  13995. struct mg_connection *conn = NULL;
  13996. SOCKET sock;
  13997. union usa sa;
  13998. struct sockaddr *psa;
  13999. socklen_t len;
  14000. unsigned max_req_size =
  14001. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14002. /* Size of structures, aligned to 8 bytes */
  14003. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14004. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14005. conn = (struct mg_connection *)mg_calloc_ctx(1,
  14006. conn_size + ctx_size
  14007. + max_req_size,
  14008. &common_client_context);
  14009. if (conn == NULL) {
  14010. mg_snprintf(NULL,
  14011. NULL, /* No truncation check for ebuf */
  14012. ebuf,
  14013. ebuf_len,
  14014. "calloc(): %s",
  14015. strerror(ERRNO));
  14016. return NULL;
  14017. }
  14018. #if defined(__GNUC__) || defined(__MINGW32__)
  14019. #pragma GCC diagnostic push
  14020. #pragma GCC diagnostic ignored "-Wcast-align"
  14021. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  14022. /* conn_size is aligned to 8 bytes */
  14023. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14024. #if defined(__GNUC__) || defined(__MINGW32__)
  14025. #pragma GCC diagnostic pop
  14026. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  14027. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14028. conn->buf_size = (int)max_req_size;
  14029. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14030. conn->dom_ctx = &(conn->phys_ctx->dd);
  14031. if (!connect_socket(&common_client_context,
  14032. client_options->host,
  14033. client_options->port,
  14034. use_ssl,
  14035. ebuf,
  14036. ebuf_len,
  14037. &sock,
  14038. &sa)) {
  14039. /* ebuf is set by connect_socket,
  14040. * free all memory and return NULL; */
  14041. mg_free(conn);
  14042. return NULL;
  14043. }
  14044. #if !defined(NO_SSL)
  14045. #if defined(OPENSSL_API_1_1)
  14046. if (use_ssl
  14047. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  14048. mg_snprintf(NULL,
  14049. NULL, /* No truncation check for ebuf */
  14050. ebuf,
  14051. ebuf_len,
  14052. "SSL_CTX_new error");
  14053. closesocket(sock);
  14054. mg_free(conn);
  14055. return NULL;
  14056. }
  14057. #else
  14058. if (use_ssl
  14059. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14060. == NULL) {
  14061. mg_snprintf(NULL,
  14062. NULL, /* No truncation check for ebuf */
  14063. ebuf,
  14064. ebuf_len,
  14065. "SSL_CTX_new error");
  14066. closesocket(sock);
  14067. mg_free(conn);
  14068. return NULL;
  14069. }
  14070. #endif /* OPENSSL_API_1_1 */
  14071. #endif /* NO_SSL */
  14072. #if defined(USE_IPV6)
  14073. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14074. : sizeof(conn->client.rsa.sin6);
  14075. psa = (sa.sa.sa_family == AF_INET)
  14076. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14077. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14078. #else
  14079. len = sizeof(conn->client.rsa.sin);
  14080. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14081. #endif
  14082. conn->client.sock = sock;
  14083. conn->client.lsa = sa;
  14084. if (getsockname(sock, psa, &len) != 0) {
  14085. mg_cry_internal(conn,
  14086. "%s: getsockname() failed: %s",
  14087. __func__,
  14088. strerror(ERRNO));
  14089. }
  14090. conn->client.is_ssl = use_ssl ? 1 : 0;
  14091. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14092. mg_snprintf(NULL,
  14093. NULL, /* No truncation check for ebuf */
  14094. ebuf,
  14095. ebuf_len,
  14096. "Can not create mutex");
  14097. #if !defined(NO_SSL)
  14098. SSL_CTX_free(conn->client_ssl_ctx);
  14099. #endif
  14100. closesocket(sock);
  14101. mg_free(conn);
  14102. return NULL;
  14103. }
  14104. #if !defined(NO_SSL)
  14105. if (use_ssl) {
  14106. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  14107. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14108. * SSL_CTX_set_verify call is needed to switch off server
  14109. * certificate checking, which is off by default in OpenSSL and
  14110. * on in yaSSL. */
  14111. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  14112. * SSL_VERIFY_PEER, verify_ssl_server); */
  14113. if (client_options->client_cert) {
  14114. if (!ssl_use_pem_file(&common_client_context,
  14115. &(common_client_context.dd),
  14116. client_options->client_cert,
  14117. NULL)) {
  14118. mg_snprintf(NULL,
  14119. NULL, /* No truncation check for ebuf */
  14120. ebuf,
  14121. ebuf_len,
  14122. "Can not use SSL client certificate");
  14123. SSL_CTX_free(conn->client_ssl_ctx);
  14124. closesocket(sock);
  14125. mg_free(conn);
  14126. return NULL;
  14127. }
  14128. }
  14129. if (client_options->server_cert) {
  14130. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  14131. client_options->server_cert,
  14132. NULL);
  14133. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  14134. } else {
  14135. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  14136. }
  14137. if (!sslize(conn,
  14138. conn->client_ssl_ctx,
  14139. SSL_connect,
  14140. &(conn->phys_ctx->stop_flag))) {
  14141. mg_snprintf(NULL,
  14142. NULL, /* No truncation check for ebuf */
  14143. ebuf,
  14144. ebuf_len,
  14145. "SSL connection error");
  14146. SSL_CTX_free(conn->client_ssl_ctx);
  14147. closesocket(sock);
  14148. mg_free(conn);
  14149. return NULL;
  14150. }
  14151. }
  14152. #endif
  14153. if (0 != set_non_blocking_mode(sock)) {
  14154. mg_cry_internal(conn,
  14155. "Cannot set non-blocking mode for client %s:%i",
  14156. client_options->host,
  14157. client_options->port);
  14158. }
  14159. return conn;
  14160. }
  14161. CIVETWEB_API struct mg_connection *
  14162. mg_connect_client_secure(const struct mg_client_options *client_options,
  14163. char *error_buffer,
  14164. size_t error_buffer_size)
  14165. {
  14166. return mg_connect_client_impl(client_options,
  14167. 1,
  14168. error_buffer,
  14169. error_buffer_size);
  14170. }
  14171. struct mg_connection *
  14172. mg_connect_client(const char *host,
  14173. int port,
  14174. int use_ssl,
  14175. char *error_buffer,
  14176. size_t error_buffer_size)
  14177. {
  14178. struct mg_client_options opts;
  14179. memset(&opts, 0, sizeof(opts));
  14180. opts.host = host;
  14181. opts.port = port;
  14182. return mg_connect_client_impl(&opts,
  14183. use_ssl,
  14184. error_buffer,
  14185. error_buffer_size);
  14186. }
  14187. static const struct {
  14188. const char *proto;
  14189. size_t proto_len;
  14190. unsigned default_port;
  14191. } abs_uri_protocols[] = {{"http://", 7, 80},
  14192. {"https://", 8, 443},
  14193. {"ws://", 5, 80},
  14194. {"wss://", 6, 443},
  14195. {NULL, 0, 0}};
  14196. /* Check if the uri is valid.
  14197. * return 0 for invalid uri,
  14198. * return 1 for *,
  14199. * return 2 for relative uri,
  14200. * return 3 for absolute uri without port,
  14201. * return 4 for absolute uri with port */
  14202. static int
  14203. get_uri_type(const char *uri)
  14204. {
  14205. int i;
  14206. const char *hostend, *portbegin;
  14207. char *portend;
  14208. unsigned long port;
  14209. /* According to the HTTP standard
  14210. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14211. * URI can be an asterisk (*) or should start with slash (relative uri),
  14212. * or it should start with the protocol (absolute uri). */
  14213. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14214. /* asterisk */
  14215. return 1;
  14216. }
  14217. /* Valid URIs according to RFC 3986
  14218. * (https://www.ietf.org/rfc/rfc3986.txt)
  14219. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14220. * and unreserved characters A-Z a-z 0-9 and -._~
  14221. * and % encoded symbols.
  14222. */
  14223. for (i = 0; uri[i] != 0; i++) {
  14224. if (uri[i] < 33) {
  14225. /* control characters and spaces are invalid */
  14226. return 0;
  14227. }
  14228. if (uri[i] > 126) {
  14229. /* non-ascii characters must be % encoded */
  14230. return 0;
  14231. } else {
  14232. switch (uri[i]) {
  14233. case '"': /* 34 */
  14234. case '<': /* 60 */
  14235. case '>': /* 62 */
  14236. case '\\': /* 92 */
  14237. case '^': /* 94 */
  14238. case '`': /* 96 */
  14239. case '{': /* 123 */
  14240. case '|': /* 124 */
  14241. case '}': /* 125 */
  14242. return 0;
  14243. default:
  14244. /* character is ok */
  14245. break;
  14246. }
  14247. }
  14248. }
  14249. /* A relative uri starts with a / character */
  14250. if (uri[0] == '/') {
  14251. /* relative uri */
  14252. return 2;
  14253. }
  14254. /* It could be an absolute uri: */
  14255. /* This function only checks if the uri is valid, not if it is
  14256. * addressing the current server. So civetweb can also be used
  14257. * as a proxy server. */
  14258. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14259. if (mg_strncasecmp(uri,
  14260. abs_uri_protocols[i].proto,
  14261. abs_uri_protocols[i].proto_len) == 0) {
  14262. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14263. if (!hostend) {
  14264. return 0;
  14265. }
  14266. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14267. if (!portbegin) {
  14268. return 3;
  14269. }
  14270. port = strtoul(portbegin + 1, &portend, 10);
  14271. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14272. return 0;
  14273. }
  14274. return 4;
  14275. }
  14276. }
  14277. return 0;
  14278. }
  14279. /* Return NULL or the relative uri at the current server */
  14280. static const char *
  14281. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14282. {
  14283. const char *server_domain;
  14284. size_t server_domain_len;
  14285. size_t request_domain_len = 0;
  14286. unsigned long port = 0;
  14287. int i, auth_domain_check_enabled;
  14288. const char *hostbegin = NULL;
  14289. const char *hostend = NULL;
  14290. const char *portbegin;
  14291. char *portend;
  14292. auth_domain_check_enabled =
  14293. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14294. /* DNS is case insensitive, so use case insensitive string compare here
  14295. */
  14296. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14297. if (mg_strncasecmp(uri,
  14298. abs_uri_protocols[i].proto,
  14299. abs_uri_protocols[i].proto_len) == 0) {
  14300. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14301. hostend = strchr(hostbegin, '/');
  14302. if (!hostend) {
  14303. return 0;
  14304. }
  14305. portbegin = strchr(hostbegin, ':');
  14306. if ((!portbegin) || (portbegin > hostend)) {
  14307. port = abs_uri_protocols[i].default_port;
  14308. request_domain_len = (size_t)(hostend - hostbegin);
  14309. } else {
  14310. port = strtoul(portbegin + 1, &portend, 10);
  14311. if ((portend != hostend) || (port <= 0)
  14312. || !is_valid_port(port)) {
  14313. return 0;
  14314. }
  14315. request_domain_len = (size_t)(portbegin - hostbegin);
  14316. }
  14317. /* protocol found, port set */
  14318. break;
  14319. }
  14320. }
  14321. if (!port) {
  14322. /* port remains 0 if the protocol is not found */
  14323. return 0;
  14324. }
  14325. /* Check if the request is directed to a different server. */
  14326. /* First check if the port is the same (IPv4 and IPv6). */
  14327. #if defined(USE_IPV6)
  14328. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14329. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14330. /* Request is directed to a different port */
  14331. return 0;
  14332. }
  14333. } else
  14334. #endif
  14335. {
  14336. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14337. /* Request is directed to a different port */
  14338. return 0;
  14339. }
  14340. }
  14341. /* Finally check if the server corresponds to the authentication
  14342. * domain of the server (the server domain).
  14343. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14344. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14345. * but do not allow substrings (like
  14346. * http://notmydomain.com/path/file.ext
  14347. * or http://mydomain.com.fake/path/file.ext).
  14348. */
  14349. if (auth_domain_check_enabled) {
  14350. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14351. server_domain_len = strlen(server_domain);
  14352. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14353. return 0;
  14354. }
  14355. if ((request_domain_len == server_domain_len)
  14356. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14357. /* Request is directed to this server - full name match. */
  14358. } else {
  14359. if (request_domain_len < (server_domain_len + 2)) {
  14360. /* Request is directed to another server: The server name
  14361. * is longer than the request name.
  14362. * Drop this case here to avoid overflows in the
  14363. * following checks. */
  14364. return 0;
  14365. }
  14366. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14367. /* Request is directed to another server: It could be a
  14368. * substring
  14369. * like notmyserver.com */
  14370. return 0;
  14371. }
  14372. if (0 != memcmp(server_domain,
  14373. hostbegin + request_domain_len - server_domain_len,
  14374. server_domain_len)) {
  14375. /* Request is directed to another server:
  14376. * The server name is different. */
  14377. return 0;
  14378. }
  14379. }
  14380. }
  14381. return hostend;
  14382. }
  14383. static int
  14384. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14385. {
  14386. if (ebuf_len > 0) {
  14387. ebuf[0] = '\0';
  14388. }
  14389. *err = 0;
  14390. reset_per_request_attributes(conn);
  14391. if (!conn) {
  14392. mg_snprintf(conn,
  14393. NULL, /* No truncation check for ebuf */
  14394. ebuf,
  14395. ebuf_len,
  14396. "%s",
  14397. "Internal error");
  14398. *err = 500;
  14399. return 0;
  14400. }
  14401. /* Set the time the request was received. This value should be used for
  14402. * timeouts. */
  14403. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14404. conn->request_len =
  14405. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14406. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14407. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14408. mg_snprintf(conn,
  14409. NULL, /* No truncation check for ebuf */
  14410. ebuf,
  14411. ebuf_len,
  14412. "%s",
  14413. "Invalid message size");
  14414. *err = 500;
  14415. return 0;
  14416. }
  14417. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14418. mg_snprintf(conn,
  14419. NULL, /* No truncation check for ebuf */
  14420. ebuf,
  14421. ebuf_len,
  14422. "%s",
  14423. "Message too large");
  14424. *err = 413;
  14425. return 0;
  14426. }
  14427. if (conn->request_len <= 0) {
  14428. if (conn->data_len > 0) {
  14429. mg_snprintf(conn,
  14430. NULL, /* No truncation check for ebuf */
  14431. ebuf,
  14432. ebuf_len,
  14433. "%s",
  14434. "Malformed message");
  14435. *err = 400;
  14436. } else {
  14437. /* Server did not recv anything -> just close the connection */
  14438. conn->must_close = 1;
  14439. mg_snprintf(conn,
  14440. NULL, /* No truncation check for ebuf */
  14441. ebuf,
  14442. ebuf_len,
  14443. "%s",
  14444. "No data received");
  14445. *err = 0;
  14446. }
  14447. return 0;
  14448. }
  14449. return 1;
  14450. }
  14451. static int
  14452. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14453. {
  14454. const char *cl;
  14455. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14456. return 0;
  14457. }
  14458. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14459. <= 0) {
  14460. mg_snprintf(conn,
  14461. NULL, /* No truncation check for ebuf */
  14462. ebuf,
  14463. ebuf_len,
  14464. "%s",
  14465. "Bad request");
  14466. *err = 400;
  14467. return 0;
  14468. }
  14469. /* Message is a valid request */
  14470. /* Is there a "host" ? */
  14471. conn->host = alloc_get_host(conn);
  14472. if (!conn->host) {
  14473. mg_snprintf(conn,
  14474. NULL, /* No truncation check for ebuf */
  14475. ebuf,
  14476. ebuf_len,
  14477. "%s",
  14478. "Bad request: Host mismatch");
  14479. *err = 400;
  14480. return 0;
  14481. }
  14482. /* Do we know the content length? */
  14483. if ((cl = get_header(conn->request_info.http_headers,
  14484. conn->request_info.num_headers,
  14485. "Content-Length")) != NULL) {
  14486. /* Request/response has content length set */
  14487. char *endptr = NULL;
  14488. conn->content_len = strtoll(cl, &endptr, 10);
  14489. if (endptr == cl) {
  14490. mg_snprintf(conn,
  14491. NULL, /* No truncation check for ebuf */
  14492. ebuf,
  14493. ebuf_len,
  14494. "%s",
  14495. "Bad request");
  14496. *err = 411;
  14497. return 0;
  14498. }
  14499. /* Publish the content length back to the request info. */
  14500. conn->request_info.content_length = conn->content_len;
  14501. } else if ((cl = get_header(conn->request_info.http_headers,
  14502. conn->request_info.num_headers,
  14503. "Transfer-Encoding")) != NULL
  14504. && !mg_strcasecmp(cl, "chunked")) {
  14505. conn->is_chunked = 1;
  14506. conn->content_len = -1; /* unknown content length */
  14507. } else {
  14508. const struct mg_http_method_info *meth =
  14509. get_http_method_info(conn->request_info.request_method);
  14510. if (!meth) {
  14511. /* No valid HTTP method */
  14512. mg_snprintf(conn,
  14513. NULL, /* No truncation check for ebuf */
  14514. ebuf,
  14515. ebuf_len,
  14516. "%s",
  14517. "Bad request");
  14518. *err = 411;
  14519. return 0;
  14520. }
  14521. if (meth->request_has_body) {
  14522. /* POST or PUT request without content length set */
  14523. conn->content_len = -1; /* unknown content length */
  14524. } else {
  14525. /* Other request */
  14526. conn->content_len = 0; /* No content */
  14527. }
  14528. }
  14529. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14530. return 1;
  14531. }
  14532. /* conn is assumed to be valid in this internal function */
  14533. static int
  14534. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14535. {
  14536. const char *cl;
  14537. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14538. return 0;
  14539. }
  14540. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14541. <= 0) {
  14542. mg_snprintf(conn,
  14543. NULL, /* No truncation check for ebuf */
  14544. ebuf,
  14545. ebuf_len,
  14546. "%s",
  14547. "Bad response");
  14548. *err = 400;
  14549. return 0;
  14550. }
  14551. /* Message is a valid response */
  14552. /* Do we know the content length? */
  14553. if ((cl = get_header(conn->response_info.http_headers,
  14554. conn->response_info.num_headers,
  14555. "Content-Length")) != NULL) {
  14556. /* Request/response has content length set */
  14557. char *endptr = NULL;
  14558. conn->content_len = strtoll(cl, &endptr, 10);
  14559. if (endptr == cl) {
  14560. mg_snprintf(conn,
  14561. NULL, /* No truncation check for ebuf */
  14562. ebuf,
  14563. ebuf_len,
  14564. "%s",
  14565. "Bad request");
  14566. *err = 411;
  14567. return 0;
  14568. }
  14569. /* Publish the content length back to the response info. */
  14570. conn->response_info.content_length = conn->content_len;
  14571. /* TODO: check if it is still used in response_info */
  14572. conn->request_info.content_length = conn->content_len;
  14573. } else if ((cl = get_header(conn->response_info.http_headers,
  14574. conn->response_info.num_headers,
  14575. "Transfer-Encoding")) != NULL
  14576. && !mg_strcasecmp(cl, "chunked")) {
  14577. conn->is_chunked = 1;
  14578. conn->content_len = -1; /* unknown content length */
  14579. } else {
  14580. conn->content_len = -1; /* unknown content length */
  14581. }
  14582. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14583. return 1;
  14584. }
  14585. int
  14586. mg_get_response(struct mg_connection *conn,
  14587. char *ebuf,
  14588. size_t ebuf_len,
  14589. int timeout)
  14590. {
  14591. int err, ret;
  14592. char txt[32]; /* will not overflow */
  14593. char *save_timeout;
  14594. char *new_timeout;
  14595. if (ebuf_len > 0) {
  14596. ebuf[0] = '\0';
  14597. }
  14598. if (!conn) {
  14599. mg_snprintf(conn,
  14600. NULL, /* No truncation check for ebuf */
  14601. ebuf,
  14602. ebuf_len,
  14603. "%s",
  14604. "Parameter error");
  14605. return -1;
  14606. }
  14607. /* Implementation of API function for HTTP clients */
  14608. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14609. if (timeout >= 0) {
  14610. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14611. new_timeout = txt;
  14612. /* Not required for non-blocking sockets.
  14613. set_sock_timeout(conn->client.sock, timeout);
  14614. */
  14615. } else {
  14616. new_timeout = NULL;
  14617. }
  14618. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14619. ret = get_response(conn, ebuf, ebuf_len, &err);
  14620. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14621. #if defined(MG_LEGACY_INTERFACE)
  14622. /* TODO: 1) uri is deprecated;
  14623. * 2) here, ri.uri is the http response code */
  14624. conn->request_info.uri = conn->request_info.request_uri;
  14625. #endif
  14626. conn->request_info.local_uri = conn->request_info.request_uri;
  14627. /* TODO (mid): Define proper return values - maybe return length?
  14628. * For the first test use <0 for error and >0 for OK */
  14629. return (ret == 0) ? -1 : +1;
  14630. }
  14631. struct mg_connection *
  14632. mg_download(const char *host,
  14633. int port,
  14634. int use_ssl,
  14635. char *ebuf,
  14636. size_t ebuf_len,
  14637. const char *fmt,
  14638. ...)
  14639. {
  14640. struct mg_connection *conn;
  14641. va_list ap;
  14642. int i;
  14643. int reqerr;
  14644. if (ebuf_len > 0) {
  14645. ebuf[0] = '\0';
  14646. }
  14647. va_start(ap, fmt);
  14648. /* open a connection */
  14649. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14650. if (conn != NULL) {
  14651. i = mg_vprintf(conn, fmt, ap);
  14652. if (i <= 0) {
  14653. mg_snprintf(conn,
  14654. NULL, /* No truncation check for ebuf */
  14655. ebuf,
  14656. ebuf_len,
  14657. "%s",
  14658. "Error sending request");
  14659. } else {
  14660. get_response(conn, ebuf, ebuf_len, &reqerr);
  14661. #if defined(MG_LEGACY_INTERFACE)
  14662. /* TODO: 1) uri is deprecated;
  14663. * 2) here, ri.uri is the http response code */
  14664. conn->request_info.uri = conn->request_info.request_uri;
  14665. #endif
  14666. conn->request_info.local_uri = conn->request_info.request_uri;
  14667. }
  14668. }
  14669. /* if an error occurred, close the connection */
  14670. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14671. mg_close_connection(conn);
  14672. conn = NULL;
  14673. }
  14674. va_end(ap);
  14675. return conn;
  14676. }
  14677. struct websocket_client_thread_data {
  14678. struct mg_connection *conn;
  14679. mg_websocket_data_handler data_handler;
  14680. mg_websocket_close_handler close_handler;
  14681. void *callback_data;
  14682. };
  14683. #if defined(USE_WEBSOCKET)
  14684. #if defined(_WIN32)
  14685. static unsigned __stdcall websocket_client_thread(void *data)
  14686. #else
  14687. static void *
  14688. websocket_client_thread(void *data)
  14689. #endif
  14690. {
  14691. struct websocket_client_thread_data *cdata =
  14692. (struct websocket_client_thread_data *)data;
  14693. #if !defined(_WIN32)
  14694. struct sigaction sa;
  14695. /* Ignore SIGPIPE */
  14696. memset(&sa, 0, sizeof(sa));
  14697. sa.sa_handler = SIG_IGN;
  14698. sigaction(SIGPIPE, &sa, NULL);
  14699. #endif
  14700. mg_set_thread_name("ws-clnt");
  14701. if (cdata->conn->phys_ctx) {
  14702. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14703. /* 3 indicates a websocket client thread */
  14704. /* TODO: check if conn->phys_ctx can be set */
  14705. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14706. 3);
  14707. }
  14708. }
  14709. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14710. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14711. if (cdata->close_handler != NULL) {
  14712. cdata->close_handler(cdata->conn, cdata->callback_data);
  14713. }
  14714. /* The websocket_client context has only this thread. If it runs out,
  14715. set the stop_flag to 2 (= "stopped"). */
  14716. cdata->conn->phys_ctx->stop_flag = 2;
  14717. mg_free((void *)cdata);
  14718. #if defined(_WIN32)
  14719. return 0;
  14720. #else
  14721. return NULL;
  14722. #endif
  14723. }
  14724. #endif
  14725. struct mg_connection *
  14726. mg_connect_websocket_client(const char *host,
  14727. int port,
  14728. int use_ssl,
  14729. char *error_buffer,
  14730. size_t error_buffer_size,
  14731. const char *path,
  14732. const char *origin,
  14733. mg_websocket_data_handler data_func,
  14734. mg_websocket_close_handler close_func,
  14735. void *user_data)
  14736. {
  14737. struct mg_connection *conn = NULL;
  14738. #if defined(USE_WEBSOCKET)
  14739. struct mg_context *newctx = NULL;
  14740. struct websocket_client_thread_data *thread_data;
  14741. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14742. static const char *handshake_req;
  14743. if (origin != NULL) {
  14744. handshake_req = "GET %s HTTP/1.1\r\n"
  14745. "Host: %s\r\n"
  14746. "Upgrade: websocket\r\n"
  14747. "Connection: Upgrade\r\n"
  14748. "Sec-WebSocket-Key: %s\r\n"
  14749. "Sec-WebSocket-Version: 13\r\n"
  14750. "Origin: %s\r\n"
  14751. "\r\n";
  14752. } else {
  14753. handshake_req = "GET %s HTTP/1.1\r\n"
  14754. "Host: %s\r\n"
  14755. "Upgrade: websocket\r\n"
  14756. "Connection: Upgrade\r\n"
  14757. "Sec-WebSocket-Key: %s\r\n"
  14758. "Sec-WebSocket-Version: 13\r\n"
  14759. "\r\n";
  14760. }
  14761. #if defined(__clang__)
  14762. #pragma clang diagnostic push
  14763. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14764. #endif
  14765. /* Establish the client connection and request upgrade */
  14766. conn = mg_download(host,
  14767. port,
  14768. use_ssl,
  14769. error_buffer,
  14770. error_buffer_size,
  14771. handshake_req,
  14772. path,
  14773. host,
  14774. magic,
  14775. origin);
  14776. #if defined(__clang__)
  14777. #pragma clang diagnostic pop
  14778. #endif
  14779. /* Connection object will be null if something goes wrong */
  14780. if (conn == NULL) {
  14781. if (!*error_buffer) {
  14782. /* There should be already an error message */
  14783. mg_snprintf(conn,
  14784. NULL, /* No truncation check for ebuf */
  14785. error_buffer,
  14786. error_buffer_size,
  14787. "Unexpected error");
  14788. }
  14789. return NULL;
  14790. }
  14791. if (conn->response_info.status_code != 101) {
  14792. /* We sent an "upgrade" request. For a correct websocket
  14793. * protocol handshake, we expect a "101 Continue" response.
  14794. * Otherwise it is a protocol violation. Maybe the HTTP
  14795. * Server does not know websockets. */
  14796. if (!*error_buffer) {
  14797. /* set an error, if not yet set */
  14798. mg_snprintf(conn,
  14799. NULL, /* No truncation check for ebuf */
  14800. error_buffer,
  14801. error_buffer_size,
  14802. "Unexpected server reply");
  14803. }
  14804. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14805. mg_free(conn);
  14806. return NULL;
  14807. }
  14808. /* For client connections, mg_context is fake. Since we need to set a
  14809. * callback function, we need to create a copy and modify it. */
  14810. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14811. if (!newctx) {
  14812. DEBUG_TRACE("%s\r\n", "Out of memory");
  14813. mg_free(conn);
  14814. return NULL;
  14815. }
  14816. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14817. newctx->user_data = user_data;
  14818. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14819. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14820. newctx->worker_threadids =
  14821. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14822. sizeof(pthread_t),
  14823. newctx);
  14824. conn->phys_ctx = newctx;
  14825. conn->dom_ctx = &(newctx->dd);
  14826. thread_data = (struct websocket_client_thread_data *)
  14827. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14828. if (!thread_data) {
  14829. DEBUG_TRACE("%s\r\n", "Out of memory");
  14830. mg_free(newctx);
  14831. mg_free(conn);
  14832. return NULL;
  14833. }
  14834. thread_data->conn = conn;
  14835. thread_data->data_handler = data_func;
  14836. thread_data->close_handler = close_func;
  14837. thread_data->callback_data = user_data;
  14838. /* Start a thread to read the websocket client connection
  14839. * This thread will automatically stop when mg_disconnect is
  14840. * called on the client connection */
  14841. if (mg_start_thread_with_id(websocket_client_thread,
  14842. (void *)thread_data,
  14843. newctx->worker_threadids) != 0) {
  14844. mg_free((void *)thread_data);
  14845. mg_free((void *)newctx->worker_threadids);
  14846. mg_free((void *)newctx);
  14847. mg_free((void *)conn);
  14848. conn = NULL;
  14849. DEBUG_TRACE("%s",
  14850. "Websocket client connect thread could not be started\r\n");
  14851. }
  14852. #else
  14853. /* Appease "unused parameter" warnings */
  14854. (void)host;
  14855. (void)port;
  14856. (void)use_ssl;
  14857. (void)error_buffer;
  14858. (void)error_buffer_size;
  14859. (void)path;
  14860. (void)origin;
  14861. (void)user_data;
  14862. (void)data_func;
  14863. (void)close_func;
  14864. #endif
  14865. return conn;
  14866. }
  14867. /* Prepare connection data structure */
  14868. static void
  14869. init_connection(struct mg_connection *conn)
  14870. {
  14871. /* Is keep alive allowed by the server */
  14872. int keep_alive_enabled =
  14873. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  14874. if (!keep_alive_enabled) {
  14875. conn->must_close = 1;
  14876. }
  14877. /* Important: on new connection, reset the receiving buffer. Credit
  14878. * goes to crule42. */
  14879. conn->data_len = 0;
  14880. conn->handled_requests = 0;
  14881. mg_set_user_connection_data(conn, NULL);
  14882. #if defined(USE_SERVER_STATS)
  14883. conn->conn_state = 2; /* init */
  14884. #endif
  14885. /* call the init_connection callback if assigned */
  14886. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  14887. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14888. void *conn_data = NULL;
  14889. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  14890. mg_set_user_connection_data(conn, conn_data);
  14891. }
  14892. }
  14893. }
  14894. /* Process a connection - may handle multiple requests
  14895. * using the same connection.
  14896. * Must be called with a valid connection (conn and
  14897. * conn->phys_ctx must be valid).
  14898. */
  14899. static void
  14900. process_new_connection(struct mg_connection *conn)
  14901. {
  14902. struct mg_request_info *ri = &conn->request_info;
  14903. int keep_alive, discard_len;
  14904. char ebuf[100];
  14905. const char *hostend;
  14906. int reqerr, uri_type;
  14907. #if defined(USE_SERVER_STATS)
  14908. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  14909. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  14910. if (mcon > (conn->phys_ctx->max_connections)) {
  14911. /* could use atomic compare exchange, but this
  14912. * seems overkill for statistics data */
  14913. conn->phys_ctx->max_connections = mcon;
  14914. }
  14915. #endif
  14916. init_connection(conn);
  14917. DEBUG_TRACE("Start processing connection from %s",
  14918. conn->request_info.remote_addr);
  14919. /* Loop over multiple requests sent using the same connection
  14920. * (while "keep alive"). */
  14921. do {
  14922. DEBUG_TRACE("calling get_request (%i times for this connection)",
  14923. conn->handled_requests + 1);
  14924. #if defined(USE_SERVER_STATS)
  14925. conn->conn_state = 3; /* ready */
  14926. #endif
  14927. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  14928. /* The request sent by the client could not be understood by
  14929. * the server, or it was incomplete or a timeout. Send an
  14930. * error message and close the connection. */
  14931. if (reqerr > 0) {
  14932. DEBUG_ASSERT(ebuf[0] != '\0');
  14933. mg_send_http_error(conn, reqerr, "%s", ebuf);
  14934. }
  14935. } else if (strcmp(ri->http_version, "1.0")
  14936. && strcmp(ri->http_version, "1.1")) {
  14937. mg_snprintf(conn,
  14938. NULL, /* No truncation check for ebuf */
  14939. ebuf,
  14940. sizeof(ebuf),
  14941. "Bad HTTP version: [%s]",
  14942. ri->http_version);
  14943. mg_send_http_error(conn, 505, "%s", ebuf);
  14944. }
  14945. if (ebuf[0] == '\0') {
  14946. uri_type = get_uri_type(conn->request_info.request_uri);
  14947. switch (uri_type) {
  14948. case 1:
  14949. /* Asterisk */
  14950. conn->request_info.local_uri = NULL;
  14951. break;
  14952. case 2:
  14953. /* relative uri */
  14954. conn->request_info.local_uri = conn->request_info.request_uri;
  14955. break;
  14956. case 3:
  14957. case 4:
  14958. /* absolute uri (with/without port) */
  14959. hostend = get_rel_url_at_current_server(
  14960. conn->request_info.request_uri, conn);
  14961. if (hostend) {
  14962. conn->request_info.local_uri = hostend;
  14963. } else {
  14964. conn->request_info.local_uri = NULL;
  14965. }
  14966. break;
  14967. default:
  14968. mg_snprintf(conn,
  14969. NULL, /* No truncation check for ebuf */
  14970. ebuf,
  14971. sizeof(ebuf),
  14972. "Invalid URI");
  14973. mg_send_http_error(conn, 400, "%s", ebuf);
  14974. conn->request_info.local_uri = NULL;
  14975. break;
  14976. }
  14977. #if defined(MG_LEGACY_INTERFACE)
  14978. /* Legacy before split into local_uri and request_uri */
  14979. conn->request_info.uri = conn->request_info.local_uri;
  14980. #endif
  14981. }
  14982. DEBUG_TRACE("http: %s, error: %s",
  14983. (ri->http_version ? ri->http_version : "none"),
  14984. (ebuf[0] ? ebuf : "none"));
  14985. if (ebuf[0] == '\0') {
  14986. if (conn->request_info.local_uri) {
  14987. /* handle request to local server */
  14988. #if defined(USE_SERVER_STATS)
  14989. conn->conn_state = 4; /* processing */
  14990. #endif
  14991. handle_request(conn);
  14992. #if defined(USE_SERVER_STATS)
  14993. conn->conn_state = 5; /* processed */
  14994. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  14995. conn->consumed_content);
  14996. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  14997. conn->num_bytes_sent);
  14998. #endif
  14999. DEBUG_TRACE("%s", "handle_request done");
  15000. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15001. conn->phys_ctx->callbacks.end_request(conn,
  15002. conn->status_code);
  15003. DEBUG_TRACE("%s", "end_request callback done");
  15004. }
  15005. log_access(conn);
  15006. } else {
  15007. /* TODO: handle non-local request (PROXY) */
  15008. conn->must_close = 1;
  15009. }
  15010. } else {
  15011. conn->must_close = 1;
  15012. }
  15013. if (ri->remote_user != NULL) {
  15014. mg_free((void *)ri->remote_user);
  15015. /* Important! When having connections with and without auth
  15016. * would cause double free and then crash */
  15017. ri->remote_user = NULL;
  15018. }
  15019. /* NOTE(lsm): order is important here. should_keep_alive() call
  15020. * is using parsed request, which will be invalid after
  15021. * memmove's below.
  15022. * Therefore, memorize should_keep_alive() result now for later
  15023. * use in loop exit condition. */
  15024. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15025. && (conn->content_len >= 0);
  15026. /* Discard all buffered data for this request */
  15027. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  15028. && ((conn->request_len + conn->content_len)
  15029. < (int64_t)conn->data_len))
  15030. ? (int)(conn->request_len + conn->content_len)
  15031. : conn->data_len;
  15032. DEBUG_ASSERT(discard_len >= 0);
  15033. if (discard_len < 0) {
  15034. DEBUG_TRACE("internal error: discard_len = %li",
  15035. (long int)discard_len);
  15036. break;
  15037. }
  15038. conn->data_len -= discard_len;
  15039. if (conn->data_len > 0) {
  15040. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  15041. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  15042. }
  15043. DEBUG_ASSERT(conn->data_len >= 0);
  15044. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15045. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15046. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15047. (long int)conn->data_len,
  15048. (long int)conn->buf_size);
  15049. break;
  15050. }
  15051. conn->handled_requests++;
  15052. } while (keep_alive);
  15053. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15054. conn->request_info.remote_addr,
  15055. difftime(time(NULL), conn->conn_birth_time));
  15056. close_connection(conn);
  15057. #if defined(USE_SERVER_STATS)
  15058. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15059. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15060. #endif
  15061. }
  15062. #if defined(ALTERNATIVE_QUEUE)
  15063. static void
  15064. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15065. {
  15066. unsigned int i;
  15067. while (!ctx->stop_flag) {
  15068. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15069. /* find a free worker slot and signal it */
  15070. if (ctx->client_socks[i].in_use == 0) {
  15071. ctx->client_socks[i] = *sp;
  15072. ctx->client_socks[i].in_use = 1;
  15073. event_signal(ctx->client_wait_events[i]);
  15074. return;
  15075. }
  15076. }
  15077. /* queue is full */
  15078. mg_sleep(1);
  15079. }
  15080. }
  15081. static int
  15082. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15083. {
  15084. DEBUG_TRACE("%s", "going idle");
  15085. ctx->client_socks[thread_index].in_use = 0;
  15086. event_wait(ctx->client_wait_events[thread_index]);
  15087. *sp = ctx->client_socks[thread_index];
  15088. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15089. return !ctx->stop_flag;
  15090. }
  15091. #else /* ALTERNATIVE_QUEUE */
  15092. /* Worker threads take accepted socket from the queue */
  15093. static int
  15094. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15095. {
  15096. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15097. (void)thread_index;
  15098. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15099. DEBUG_TRACE("%s", "going idle");
  15100. /* If the queue is empty, wait. We're idle at this point. */
  15101. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15102. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15103. }
  15104. /* If we're stopping, sq_head may be equal to sq_tail. */
  15105. if (ctx->sq_head > ctx->sq_tail) {
  15106. /* Copy socket from the queue and increment tail */
  15107. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15108. ctx->sq_tail++;
  15109. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15110. /* Wrap pointers if needed */
  15111. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15112. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15113. ctx->sq_head -= QUEUE_SIZE(ctx);
  15114. }
  15115. }
  15116. (void)pthread_cond_signal(&ctx->sq_empty);
  15117. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15118. return !ctx->stop_flag;
  15119. #undef QUEUE_SIZE
  15120. }
  15121. /* Master thread adds accepted socket to a queue */
  15122. static void
  15123. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15124. {
  15125. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15126. if (!ctx) {
  15127. return;
  15128. }
  15129. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15130. /* If the queue is full, wait */
  15131. while ((ctx->stop_flag == 0)
  15132. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15133. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15134. }
  15135. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15136. /* Copy socket to the queue and increment head */
  15137. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15138. ctx->sq_head++;
  15139. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15140. }
  15141. (void)pthread_cond_signal(&ctx->sq_full);
  15142. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15143. #undef QUEUE_SIZE
  15144. }
  15145. #endif /* ALTERNATIVE_QUEUE */
  15146. struct worker_thread_args {
  15147. struct mg_context *ctx;
  15148. int index;
  15149. };
  15150. static void *
  15151. worker_thread_run(struct worker_thread_args *thread_args)
  15152. {
  15153. struct mg_context *ctx = thread_args->ctx;
  15154. struct mg_connection *conn;
  15155. struct mg_workerTLS tls;
  15156. #if defined(MG_LEGACY_INTERFACE)
  15157. uint32_t addr;
  15158. #endif
  15159. mg_set_thread_name("worker");
  15160. tls.is_master = 0;
  15161. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15162. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15163. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15164. #endif
  15165. /* Initialize thread local storage before calling any callback */
  15166. pthread_setspecific(sTlsKey, &tls);
  15167. if (ctx->callbacks.init_thread) {
  15168. /* call init_thread for a worker thread (type 1) */
  15169. ctx->callbacks.init_thread(ctx, 1);
  15170. }
  15171. /* Connection structure has been pre-allocated */
  15172. if (((int)thread_args->index < 0)
  15173. || ((unsigned)thread_args->index
  15174. >= (unsigned)ctx->cfg_worker_threads)) {
  15175. mg_cry_internal(fc(ctx),
  15176. "Internal error: Invalid worker index %i",
  15177. (int)thread_args->index);
  15178. return NULL;
  15179. }
  15180. conn = ctx->worker_connections + thread_args->index;
  15181. /* Request buffers are not pre-allocated. They are private to the
  15182. * request and do not contain any state information that might be
  15183. * of interest to anyone observing a server status. */
  15184. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15185. if (conn->buf == NULL) {
  15186. mg_cry_internal(fc(ctx),
  15187. "Out of memory: Cannot allocate buffer for worker %i",
  15188. (int)thread_args->index);
  15189. return NULL;
  15190. }
  15191. conn->buf_size = (int)ctx->max_request_size;
  15192. conn->phys_ctx = ctx;
  15193. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15194. conn->host = NULL; /* until we have more information. */
  15195. conn->thread_index = thread_args->index;
  15196. conn->request_info.user_data = ctx->user_data;
  15197. /* Allocate a mutex for this connection to allow communication both
  15198. * within the request handler and from elsewhere in the application
  15199. */
  15200. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15201. mg_free(conn->buf);
  15202. mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
  15203. return NULL;
  15204. }
  15205. #if defined(USE_SERVER_STATS)
  15206. conn->conn_state = 1; /* not consumed */
  15207. #endif
  15208. #if defined(ALTERNATIVE_QUEUE)
  15209. while ((ctx->stop_flag == 0)
  15210. && consume_socket(ctx, &conn->client, conn->thread_index)) {
  15211. #else
  15212. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15213. * signal sq_empty condvar to wake up the master waiting in
  15214. * produce_socket() */
  15215. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  15216. #endif
  15217. conn->conn_birth_time = time(NULL);
  15218. /* Fill in IP, port info early so even if SSL setup below fails,
  15219. * error handler would have the corresponding info.
  15220. * Thanks to Johannes Winkelmann for the patch.
  15221. */
  15222. #if defined(USE_IPV6)
  15223. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15224. conn->request_info.remote_port =
  15225. ntohs(conn->client.rsa.sin6.sin6_port);
  15226. } else
  15227. #endif
  15228. {
  15229. conn->request_info.remote_port =
  15230. ntohs(conn->client.rsa.sin.sin_port);
  15231. }
  15232. sockaddr_to_string(conn->request_info.remote_addr,
  15233. sizeof(conn->request_info.remote_addr),
  15234. &conn->client.rsa);
  15235. DEBUG_TRACE("Start processing connection from %s",
  15236. conn->request_info.remote_addr);
  15237. conn->request_info.is_ssl = conn->client.is_ssl;
  15238. if (conn->client.is_ssl) {
  15239. #if !defined(NO_SSL)
  15240. /* HTTPS connection */
  15241. if (sslize(conn,
  15242. conn->dom_ctx->ssl_ctx,
  15243. SSL_accept,
  15244. &(conn->phys_ctx->stop_flag))) {
  15245. /* conn->dom_ctx is set in get_request */
  15246. /* Get SSL client certificate information (if set) */
  15247. ssl_get_client_cert_info(conn);
  15248. /* process HTTPS connection */
  15249. process_new_connection(conn);
  15250. /* Free client certificate info */
  15251. if (conn->request_info.client_cert) {
  15252. mg_free((void *)(conn->request_info.client_cert->subject));
  15253. mg_free((void *)(conn->request_info.client_cert->issuer));
  15254. mg_free((void *)(conn->request_info.client_cert->serial));
  15255. mg_free((void *)(conn->request_info.client_cert->finger));
  15256. /* Free certificate memory */
  15257. X509_free(
  15258. (X509 *)conn->request_info.client_cert->peer_cert);
  15259. conn->request_info.client_cert->peer_cert = 0;
  15260. conn->request_info.client_cert->subject = 0;
  15261. conn->request_info.client_cert->issuer = 0;
  15262. conn->request_info.client_cert->serial = 0;
  15263. conn->request_info.client_cert->finger = 0;
  15264. mg_free(conn->request_info.client_cert);
  15265. conn->request_info.client_cert = 0;
  15266. }
  15267. }
  15268. #endif
  15269. } else {
  15270. /* process HTTP connection */
  15271. process_new_connection(conn);
  15272. }
  15273. DEBUG_TRACE("%s", "Connection closed");
  15274. }
  15275. pthread_setspecific(sTlsKey, NULL);
  15276. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15277. CloseHandle(tls.pthread_cond_helper_mutex);
  15278. #endif
  15279. pthread_mutex_destroy(&conn->mutex);
  15280. /* Free the request buffer. */
  15281. conn->buf_size = 0;
  15282. mg_free(conn->buf);
  15283. conn->buf = NULL;
  15284. #if defined(USE_SERVER_STATS)
  15285. conn->conn_state = 9; /* done */
  15286. #endif
  15287. DEBUG_TRACE("%s", "exiting");
  15288. return NULL;
  15289. }
  15290. /* Threads have different return types on Windows and Unix. */
  15291. #if defined(_WIN32)
  15292. static unsigned __stdcall worker_thread(void *thread_func_param)
  15293. {
  15294. struct worker_thread_args *pwta =
  15295. (struct worker_thread_args *)thread_func_param;
  15296. worker_thread_run(pwta);
  15297. mg_free(thread_func_param);
  15298. return 0;
  15299. }
  15300. #else
  15301. static void *
  15302. worker_thread(void *thread_func_param)
  15303. {
  15304. struct worker_thread_args *pwta =
  15305. (struct worker_thread_args *)thread_func_param;
  15306. struct sigaction sa;
  15307. /* Ignore SIGPIPE */
  15308. memset(&sa, 0, sizeof(sa));
  15309. sa.sa_handler = SIG_IGN;
  15310. sigaction(SIGPIPE, &sa, NULL);
  15311. worker_thread_run(pwta);
  15312. mg_free(thread_func_param);
  15313. return NULL;
  15314. }
  15315. #endif /* _WIN32 */
  15316. /* This is an internal function, thus all arguments are expected to be
  15317. * valid - a NULL check is not required. */
  15318. static void
  15319. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15320. {
  15321. struct socket so;
  15322. char src_addr[IP_ADDR_STR_LEN];
  15323. socklen_t len = sizeof(so.rsa);
  15324. int on = 1;
  15325. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15326. == INVALID_SOCKET) {
  15327. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15328. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15329. mg_cry_internal(fc(ctx),
  15330. "%s: %s is not allowed to connect",
  15331. __func__,
  15332. src_addr);
  15333. closesocket(so.sock);
  15334. } else {
  15335. /* Put so socket structure into the queue */
  15336. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15337. set_close_on_exec(so.sock, fc(ctx));
  15338. so.is_ssl = listener->is_ssl;
  15339. so.ssl_redir = listener->ssl_redir;
  15340. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15341. mg_cry_internal(fc(ctx),
  15342. "%s: getsockname() failed: %s",
  15343. __func__,
  15344. strerror(ERRNO));
  15345. }
  15346. /* Set TCP keep-alive. This is needed because if HTTP-level
  15347. * keep-alive
  15348. * is enabled, and client resets the connection, server won't get
  15349. * TCP FIN or RST and will keep the connection open forever. With
  15350. * TCP keep-alive, next keep-alive handshake will figure out that
  15351. * the client is down and will close the server end.
  15352. * Thanks to Igor Klopov who suggested the patch. */
  15353. if (setsockopt(so.sock,
  15354. SOL_SOCKET,
  15355. SO_KEEPALIVE,
  15356. (SOCK_OPT_TYPE)&on,
  15357. sizeof(on)) != 0) {
  15358. mg_cry_internal(
  15359. fc(ctx),
  15360. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15361. __func__,
  15362. strerror(ERRNO));
  15363. }
  15364. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15365. * to effectively fill up the underlying IP packet payload and
  15366. * reduce the overhead of sending lots of small buffers. However
  15367. * this hurts the server's throughput (ie. operations per second)
  15368. * when HTTP 1.1 persistent connections are used and the responses
  15369. * are relatively small (eg. less than 1400 bytes).
  15370. */
  15371. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15372. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15373. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15374. mg_cry_internal(
  15375. fc(ctx),
  15376. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15377. __func__,
  15378. strerror(ERRNO));
  15379. }
  15380. }
  15381. /* We are using non-blocking sockets. Thus, the
  15382. * set_sock_timeout(so.sock, timeout);
  15383. * call is no longer required. */
  15384. /* The "non blocking" property should already be
  15385. * inherited from the parent socket. Set it for
  15386. * non-compliant socket implementations. */
  15387. set_non_blocking_mode(so.sock);
  15388. so.in_use = 0;
  15389. produce_socket(ctx, &so);
  15390. }
  15391. }
  15392. static void
  15393. master_thread_run(void *thread_func_param)
  15394. {
  15395. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  15396. struct mg_workerTLS tls;
  15397. struct pollfd *pfd;
  15398. unsigned int i;
  15399. unsigned int workerthreadcount;
  15400. if (!ctx) {
  15401. return;
  15402. }
  15403. mg_set_thread_name("master");
  15404. /* Increase priority of the master thread */
  15405. #if defined(_WIN32)
  15406. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15407. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15408. int min_prio = sched_get_priority_min(SCHED_RR);
  15409. int max_prio = sched_get_priority_max(SCHED_RR);
  15410. if ((min_prio >= 0) && (max_prio >= 0)
  15411. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15412. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15413. struct sched_param sched_param = {0};
  15414. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15415. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15416. }
  15417. #endif
  15418. /* Initialize thread local storage */
  15419. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15420. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15421. #endif
  15422. tls.is_master = 1;
  15423. pthread_setspecific(sTlsKey, &tls);
  15424. if (ctx->callbacks.init_thread) {
  15425. /* Callback for the master thread (type 0) */
  15426. ctx->callbacks.init_thread(ctx, 0);
  15427. }
  15428. /* Server starts *now* */
  15429. ctx->start_time = time(NULL);
  15430. /* Start the server */
  15431. pfd = ctx->listening_socket_fds;
  15432. while (ctx->stop_flag == 0) {
  15433. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15434. pfd[i].fd = ctx->listening_sockets[i].sock;
  15435. pfd[i].events = POLLIN;
  15436. }
  15437. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15438. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15439. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15440. * successful poll, and POLLIN is defined as
  15441. * (POLLRDNORM | POLLRDBAND)
  15442. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15443. * pfd[i].revents == POLLIN. */
  15444. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15445. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15446. }
  15447. }
  15448. }
  15449. }
  15450. /* Here stop_flag is 1 - Initiate shutdown. */
  15451. DEBUG_TRACE("%s", "stopping workers");
  15452. /* Stop signal received: somebody called mg_stop. Quit. */
  15453. close_all_listening_sockets(ctx);
  15454. /* Wakeup workers that are waiting for connections to handle. */
  15455. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15456. #if defined(ALTERNATIVE_QUEUE)
  15457. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15458. event_signal(ctx->client_wait_events[i]);
  15459. /* Since we know all sockets, we can shutdown the connections. */
  15460. if (ctx->client_socks[i].in_use) {
  15461. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  15462. }
  15463. }
  15464. #else
  15465. pthread_cond_broadcast(&ctx->sq_full);
  15466. #endif
  15467. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15468. /* Join all worker threads to avoid leaking threads. */
  15469. workerthreadcount = ctx->cfg_worker_threads;
  15470. for (i = 0; i < workerthreadcount; i++) {
  15471. if (ctx->worker_threadids[i] != 0) {
  15472. mg_join_thread(ctx->worker_threadids[i]);
  15473. }
  15474. }
  15475. #if defined(USE_LUA)
  15476. /* Free Lua state of lua background task */
  15477. if (ctx->lua_background_state) {
  15478. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15479. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15480. if (lua_istable(lstate, -1)) {
  15481. reg_boolean(lstate, "shutdown", 1);
  15482. lua_pop(lstate, 1);
  15483. mg_sleep(2);
  15484. }
  15485. lua_close(lstate);
  15486. ctx->lua_background_state = 0;
  15487. }
  15488. #endif
  15489. DEBUG_TRACE("%s", "exiting");
  15490. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15491. CloseHandle(tls.pthread_cond_helper_mutex);
  15492. #endif
  15493. pthread_setspecific(sTlsKey, NULL);
  15494. /* Signal mg_stop() that we're done.
  15495. * WARNING: This must be the very last thing this
  15496. * thread does, as ctx becomes invalid after this line. */
  15497. ctx->stop_flag = 2;
  15498. }
  15499. /* Threads have different return types on Windows and Unix. */
  15500. #if defined(_WIN32)
  15501. static unsigned __stdcall master_thread(void *thread_func_param)
  15502. {
  15503. master_thread_run(thread_func_param);
  15504. return 0;
  15505. }
  15506. #else
  15507. static void *
  15508. master_thread(void *thread_func_param)
  15509. {
  15510. struct sigaction sa;
  15511. /* Ignore SIGPIPE */
  15512. memset(&sa, 0, sizeof(sa));
  15513. sa.sa_handler = SIG_IGN;
  15514. sigaction(SIGPIPE, &sa, NULL);
  15515. master_thread_run(thread_func_param);
  15516. return NULL;
  15517. }
  15518. #endif /* _WIN32 */
  15519. static void
  15520. free_context(struct mg_context *ctx)
  15521. {
  15522. int i;
  15523. struct mg_handler_info *tmp_rh;
  15524. if (ctx == NULL) {
  15525. return;
  15526. }
  15527. if (ctx->callbacks.exit_context) {
  15528. ctx->callbacks.exit_context(ctx);
  15529. }
  15530. /* All threads exited, no sync is needed. Destroy thread mutex and
  15531. * condvars
  15532. */
  15533. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15534. #if defined(ALTERNATIVE_QUEUE)
  15535. mg_free(ctx->client_socks);
  15536. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15537. event_destroy(ctx->client_wait_events[i]);
  15538. }
  15539. mg_free(ctx->client_wait_events);
  15540. #else
  15541. (void)pthread_cond_destroy(&ctx->sq_empty);
  15542. (void)pthread_cond_destroy(&ctx->sq_full);
  15543. #endif
  15544. /* Destroy other context global data structures mutex */
  15545. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15546. #if defined(USE_TIMERS)
  15547. timers_exit(ctx);
  15548. #endif
  15549. /* Deallocate config parameters */
  15550. for (i = 0; i < NUM_OPTIONS; i++) {
  15551. if (ctx->dd.config[i] != NULL) {
  15552. #if defined(_MSC_VER)
  15553. #pragma warning(suppress : 6001)
  15554. #endif
  15555. mg_free(ctx->dd.config[i]);
  15556. }
  15557. }
  15558. /* Deallocate request handlers */
  15559. while (ctx->dd.handlers) {
  15560. tmp_rh = ctx->dd.handlers;
  15561. ctx->dd.handlers = tmp_rh->next;
  15562. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15563. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15564. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15565. }
  15566. mg_free(tmp_rh->uri);
  15567. mg_free(tmp_rh);
  15568. }
  15569. #if !defined(NO_SSL)
  15570. /* Deallocate SSL context */
  15571. if (ctx->dd.ssl_ctx != NULL) {
  15572. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15573. int callback_ret =
  15574. (ctx->callbacks.external_ssl_ctx == NULL)
  15575. ? 0
  15576. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15577. if (callback_ret == 0) {
  15578. SSL_CTX_free(ctx->dd.ssl_ctx);
  15579. }
  15580. /* else: ignore error and ommit SSL_CTX_free in case
  15581. * callback_ret is 1 */
  15582. }
  15583. #endif /* !NO_SSL */
  15584. /* Deallocate worker thread ID array */
  15585. if (ctx->worker_threadids != NULL) {
  15586. mg_free(ctx->worker_threadids);
  15587. }
  15588. /* Deallocate worker thread ID array */
  15589. if (ctx->worker_connections != NULL) {
  15590. mg_free(ctx->worker_connections);
  15591. }
  15592. /* deallocate system name string */
  15593. mg_free(ctx->systemName);
  15594. /* Deallocate context itself */
  15595. mg_free(ctx);
  15596. }
  15597. void
  15598. mg_stop(struct mg_context *ctx)
  15599. {
  15600. pthread_t mt;
  15601. if (!ctx) {
  15602. return;
  15603. }
  15604. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15605. * two threads is not allowed. */
  15606. mt = ctx->masterthreadid;
  15607. if (mt == 0) {
  15608. return;
  15609. }
  15610. ctx->masterthreadid = 0;
  15611. /* Set stop flag, so all threads know they have to exit. */
  15612. ctx->stop_flag = 1;
  15613. /* Wait until everything has stopped. */
  15614. while (ctx->stop_flag != 2) {
  15615. (void)mg_sleep(10);
  15616. }
  15617. mg_join_thread(mt);
  15618. free_context(ctx);
  15619. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15620. (void)WSACleanup();
  15621. #endif /* _WIN32 && !__SYMBIAN32__ */
  15622. }
  15623. static void
  15624. get_system_name(char **sysName)
  15625. {
  15626. #if defined(_WIN32)
  15627. #if !defined(__SYMBIAN32__)
  15628. #if defined(_WIN32_WCE)
  15629. *sysName = mg_strdup("WinCE");
  15630. #else
  15631. char name[128];
  15632. DWORD dwVersion = 0;
  15633. DWORD dwMajorVersion = 0;
  15634. DWORD dwMinorVersion = 0;
  15635. DWORD dwBuild = 0;
  15636. BOOL wowRet, isWoW = FALSE;
  15637. #if defined(_MSC_VER)
  15638. #pragma warning(push)
  15639. /* GetVersion was declared deprecated */
  15640. #pragma warning(disable : 4996)
  15641. #endif
  15642. dwVersion = GetVersion();
  15643. #if defined(_MSC_VER)
  15644. #pragma warning(pop)
  15645. #endif
  15646. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15647. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15648. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15649. (void)dwBuild;
  15650. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15651. sprintf(name,
  15652. "Windows %u.%u%s",
  15653. (unsigned)dwMajorVersion,
  15654. (unsigned)dwMinorVersion,
  15655. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15656. *sysName = mg_strdup(name);
  15657. #endif
  15658. #else
  15659. *sysName = mg_strdup("Symbian");
  15660. #endif
  15661. #else
  15662. struct utsname name;
  15663. memset(&name, 0, sizeof(name));
  15664. uname(&name);
  15665. *sysName = mg_strdup(name.sysname);
  15666. #endif
  15667. }
  15668. struct mg_context *
  15669. mg_start(const struct mg_callbacks *callbacks,
  15670. void *user_data,
  15671. const char **options)
  15672. {
  15673. struct mg_context *ctx;
  15674. const char *name, *value, *default_value;
  15675. int idx, ok, workerthreadcount;
  15676. unsigned int i;
  15677. int itmp;
  15678. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15679. struct mg_workerTLS tls;
  15680. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15681. WSADATA data;
  15682. WSAStartup(MAKEWORD(2, 2), &data);
  15683. #endif /* _WIN32 && !__SYMBIAN32__ */
  15684. /* Allocate context and initialize reasonable general case defaults. */
  15685. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15686. return NULL;
  15687. }
  15688. /* Random number generator will initialize at the first call */
  15689. ctx->dd.auth_nonce_mask =
  15690. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15691. if (mg_init_library_called == 0) {
  15692. /* Legacy INIT, if mg_start is called without mg_init_library.
  15693. * Note: This may cause a memory leak */
  15694. const char *ports_option =
  15695. config_options[LISTENING_PORTS].default_value;
  15696. if (options) {
  15697. const char **run_options = options;
  15698. const char *optname = config_options[LISTENING_PORTS].name;
  15699. /* Try to find the "listening_ports" option */
  15700. while (*run_options) {
  15701. if (!strcmp(*run_options, optname)) {
  15702. ports_option = run_options[1];
  15703. }
  15704. run_options += 2;
  15705. }
  15706. }
  15707. if (is_ssl_port_used(ports_option)) {
  15708. /* Initialize with SSL support */
  15709. mg_init_library(MG_FEATURES_TLS);
  15710. } else {
  15711. /* Initialize without SSL support */
  15712. mg_init_library(MG_FEATURES_DEFAULT);
  15713. }
  15714. }
  15715. tls.is_master = -1;
  15716. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15717. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15718. tls.pthread_cond_helper_mutex = NULL;
  15719. #endif
  15720. pthread_setspecific(sTlsKey, &tls);
  15721. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15722. #if !defined(ALTERNATIVE_QUEUE)
  15723. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15724. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15725. #endif
  15726. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15727. if (!ok) {
  15728. /* Fatal error - abort start. However, this situation should never
  15729. * occur in practice. */
  15730. mg_cry_internal(fc(ctx),
  15731. "%s",
  15732. "Cannot initialize thread synchronization objects");
  15733. mg_free(ctx);
  15734. pthread_setspecific(sTlsKey, NULL);
  15735. return NULL;
  15736. }
  15737. if (callbacks) {
  15738. ctx->callbacks = *callbacks;
  15739. exit_callback = callbacks->exit_context;
  15740. ctx->callbacks.exit_context = 0;
  15741. }
  15742. ctx->user_data = user_data;
  15743. ctx->dd.handlers = NULL;
  15744. ctx->dd.next = NULL;
  15745. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15746. ctx->dd.shared_lua_websockets = NULL;
  15747. #endif
  15748. /* Store options */
  15749. while (options && (name = *options++) != NULL) {
  15750. if ((idx = get_option_index(name)) == -1) {
  15751. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15752. free_context(ctx);
  15753. pthread_setspecific(sTlsKey, NULL);
  15754. return NULL;
  15755. } else if ((value = *options++) == NULL) {
  15756. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15757. free_context(ctx);
  15758. pthread_setspecific(sTlsKey, NULL);
  15759. return NULL;
  15760. }
  15761. if (ctx->dd.config[idx] != NULL) {
  15762. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15763. mg_free(ctx->dd.config[idx]);
  15764. }
  15765. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15766. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15767. }
  15768. /* Set default value if needed */
  15769. for (i = 0; config_options[i].name != NULL; i++) {
  15770. default_value = config_options[i].default_value;
  15771. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15772. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15773. }
  15774. }
  15775. /* Request size option */
  15776. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15777. if (itmp < 1024) {
  15778. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15779. free_context(ctx);
  15780. pthread_setspecific(sTlsKey, NULL);
  15781. return NULL;
  15782. }
  15783. ctx->max_request_size = (unsigned)itmp;
  15784. /* Worker thread count option */
  15785. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15786. if (workerthreadcount > MAX_WORKER_THREADS) {
  15787. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15788. free_context(ctx);
  15789. pthread_setspecific(sTlsKey, NULL);
  15790. return NULL;
  15791. }
  15792. if (workerthreadcount <= 0) {
  15793. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15794. free_context(ctx);
  15795. pthread_setspecific(sTlsKey, NULL);
  15796. return NULL;
  15797. }
  15798. /* Document root */
  15799. #if defined(NO_FILES)
  15800. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15801. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15802. free_context(ctx);
  15803. pthread_setspecific(sTlsKey, NULL);
  15804. return NULL;
  15805. }
  15806. #endif
  15807. get_system_name(&ctx->systemName);
  15808. #if defined(USE_LUA)
  15809. /* If a Lua background script has been configured, start it. */
  15810. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15811. char ebuf[256];
  15812. struct vec opt_vec;
  15813. struct vec eq_vec;
  15814. const char *sparams;
  15815. lua_State *state = mg_prepare_lua_context_script(
  15816. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15817. if (!state) {
  15818. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15819. free_context(ctx);
  15820. pthread_setspecific(sTlsKey, NULL);
  15821. return NULL;
  15822. }
  15823. ctx->lua_background_state = (void *)state;
  15824. lua_newtable(state);
  15825. reg_boolean(state, "shutdown", 0);
  15826. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15827. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15828. reg_llstring(
  15829. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15830. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15831. break;
  15832. }
  15833. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15834. } else {
  15835. ctx->lua_background_state = 0;
  15836. }
  15837. #endif
  15838. /* NOTE(lsm): order is important here. SSL certificates must
  15839. * be initialized before listening ports. UID must be set last. */
  15840. if (!set_gpass_option(ctx, NULL) ||
  15841. #if !defined(NO_SSL)
  15842. !init_ssl_ctx(ctx, NULL) ||
  15843. #endif
  15844. !set_ports_option(ctx) ||
  15845. #if !defined(_WIN32)
  15846. !set_uid_option(ctx) ||
  15847. #endif
  15848. !set_acl_option(ctx)) {
  15849. free_context(ctx);
  15850. pthread_setspecific(sTlsKey, NULL);
  15851. return NULL;
  15852. }
  15853. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  15854. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15855. sizeof(pthread_t),
  15856. ctx);
  15857. if (ctx->worker_threadids == NULL) {
  15858. mg_cry_internal(fc(ctx),
  15859. "%s",
  15860. "Not enough memory for worker thread ID array");
  15861. free_context(ctx);
  15862. pthread_setspecific(sTlsKey, NULL);
  15863. return NULL;
  15864. }
  15865. ctx->worker_connections =
  15866. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15867. sizeof(struct mg_connection),
  15868. ctx);
  15869. if (ctx->worker_connections == NULL) {
  15870. mg_cry_internal(fc(ctx),
  15871. "%s",
  15872. "Not enough memory for worker thread connection array");
  15873. free_context(ctx);
  15874. pthread_setspecific(sTlsKey, NULL);
  15875. return NULL;
  15876. }
  15877. #if defined(ALTERNATIVE_QUEUE)
  15878. ctx->client_wait_events =
  15879. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  15880. ctx->cfg_worker_threads,
  15881. ctx);
  15882. if (ctx->client_wait_events == NULL) {
  15883. mg_cry_internal(fc(ctx),
  15884. "%s",
  15885. "Not enough memory for worker event array");
  15886. mg_free(ctx->worker_threadids);
  15887. free_context(ctx);
  15888. pthread_setspecific(sTlsKey, NULL);
  15889. return NULL;
  15890. }
  15891. ctx->client_socks =
  15892. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  15893. ctx->cfg_worker_threads,
  15894. ctx);
  15895. if (ctx->client_socks == NULL) {
  15896. mg_cry_internal(fc(ctx),
  15897. "%s",
  15898. "Not enough memory for worker socket array");
  15899. mg_free(ctx->client_wait_events);
  15900. mg_free(ctx->worker_threadids);
  15901. free_context(ctx);
  15902. pthread_setspecific(sTlsKey, NULL);
  15903. return NULL;
  15904. }
  15905. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15906. ctx->client_wait_events[i] = event_create();
  15907. if (ctx->client_wait_events[i] == 0) {
  15908. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  15909. while (i > 0) {
  15910. i--;
  15911. event_destroy(ctx->client_wait_events[i]);
  15912. }
  15913. mg_free(ctx->client_socks);
  15914. mg_free(ctx->client_wait_events);
  15915. mg_free(ctx->worker_threadids);
  15916. free_context(ctx);
  15917. pthread_setspecific(sTlsKey, NULL);
  15918. return NULL;
  15919. }
  15920. }
  15921. #endif
  15922. #if defined(USE_TIMERS)
  15923. if (timers_init(ctx) != 0) {
  15924. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  15925. free_context(ctx);
  15926. pthread_setspecific(sTlsKey, NULL);
  15927. return NULL;
  15928. }
  15929. #endif
  15930. /* Context has been created - init user libraries */
  15931. if (ctx->callbacks.init_context) {
  15932. ctx->callbacks.init_context(ctx);
  15933. }
  15934. ctx->callbacks.exit_context = exit_callback;
  15935. ctx->context_type = CONTEXT_SERVER; /* server context */
  15936. /* Start master (listening) thread */
  15937. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  15938. /* Start worker threads */
  15939. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15940. struct worker_thread_args *wta = (struct worker_thread_args *)
  15941. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  15942. if (wta) {
  15943. wta->ctx = ctx;
  15944. wta->index = (int)i;
  15945. }
  15946. if ((wta == NULL)
  15947. || (mg_start_thread_with_id(worker_thread,
  15948. wta,
  15949. &ctx->worker_threadids[i]) != 0)) {
  15950. /* thread was not created */
  15951. if (wta != NULL) {
  15952. mg_free(wta);
  15953. }
  15954. if (i > 0) {
  15955. mg_cry_internal(fc(ctx),
  15956. "Cannot start worker thread %i: error %ld",
  15957. i + 1,
  15958. (long)ERRNO);
  15959. } else {
  15960. mg_cry_internal(fc(ctx),
  15961. "Cannot create threads: error %ld",
  15962. (long)ERRNO);
  15963. free_context(ctx);
  15964. pthread_setspecific(sTlsKey, NULL);
  15965. return NULL;
  15966. }
  15967. break;
  15968. }
  15969. }
  15970. pthread_setspecific(sTlsKey, NULL);
  15971. return ctx;
  15972. }
  15973. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15974. /* Add an additional domain to an already running web server. */
  15975. int
  15976. mg_start_domain(struct mg_context *ctx, const char **options)
  15977. {
  15978. const char *name;
  15979. const char *value;
  15980. const char *default_value;
  15981. struct mg_domain_context *new_dom;
  15982. struct mg_domain_context *dom;
  15983. int idx, i;
  15984. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  15985. return -1;
  15986. }
  15987. new_dom = (struct mg_domain_context *)
  15988. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  15989. if (!new_dom) {
  15990. /* Out of memory */
  15991. return -6;
  15992. }
  15993. /* Store options - TODO: unite duplicate code */
  15994. while (options && (name = *options++) != NULL) {
  15995. if ((idx = get_option_index(name)) == -1) {
  15996. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15997. mg_free(new_dom);
  15998. return -2;
  15999. } else if ((value = *options++) == NULL) {
  16000. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16001. mg_free(new_dom);
  16002. return -2;
  16003. }
  16004. if (new_dom->config[idx] != NULL) {
  16005. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16006. mg_free(new_dom->config[idx]);
  16007. }
  16008. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16009. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16010. }
  16011. /* Authentication domain is mandatory */
  16012. /* TODO: Maybe use a new option hostname? */
  16013. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16014. mg_cry_internal(fc(ctx), "%s", "authentication domain required");
  16015. mg_free(new_dom);
  16016. return -4;
  16017. }
  16018. /* Set default value if needed. Take the config value from
  16019. * ctx as a default value. */
  16020. for (i = 0; config_options[i].name != NULL; i++) {
  16021. default_value = ctx->dd.config[i];
  16022. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16023. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16024. }
  16025. }
  16026. new_dom->handlers = NULL;
  16027. new_dom->next = NULL;
  16028. new_dom->nonce_count = 0;
  16029. new_dom->auth_nonce_mask =
  16030. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16031. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16032. new_dom->shared_lua_websockets = NULL;
  16033. #endif
  16034. if (!init_ssl_ctx(ctx, new_dom)) {
  16035. /* Init SSL failed */
  16036. mg_free(new_dom);
  16037. return -3;
  16038. }
  16039. /* Add element to linked list. */
  16040. mg_lock_context(ctx);
  16041. idx = 0;
  16042. dom = &(ctx->dd);
  16043. for (;;) {
  16044. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16045. dom->config[AUTHENTICATION_DOMAIN])) {
  16046. /* Domain collision */
  16047. mg_cry_internal(fc(ctx),
  16048. "domain %s already in use",
  16049. new_dom->config[AUTHENTICATION_DOMAIN]);
  16050. mg_free(new_dom);
  16051. return -5;
  16052. }
  16053. /* Count number of domains */
  16054. idx++;
  16055. if (dom->next == NULL) {
  16056. dom->next = new_dom;
  16057. break;
  16058. }
  16059. dom = dom->next;
  16060. }
  16061. mg_unlock_context(ctx);
  16062. /* Return domain number */
  16063. return idx;
  16064. }
  16065. #endif
  16066. /* Feature check API function */
  16067. unsigned
  16068. mg_check_feature(unsigned feature)
  16069. {
  16070. static const unsigned feature_set = 0
  16071. /* Set bits for available features according to API documentation.
  16072. * This bit mask is created at compile time, according to the active
  16073. * preprocessor defines. It is a single const value at runtime. */
  16074. #if !defined(NO_FILES)
  16075. | MG_FEATURES_FILES
  16076. #endif
  16077. #if !defined(NO_SSL)
  16078. | MG_FEATURES_SSL
  16079. #endif
  16080. #if !defined(NO_CGI)
  16081. | MG_FEATURES_CGI
  16082. #endif
  16083. #if defined(USE_IPV6)
  16084. | MG_FEATURES_IPV6
  16085. #endif
  16086. #if defined(USE_WEBSOCKET)
  16087. | MG_FEATURES_WEBSOCKET
  16088. #endif
  16089. #if defined(USE_LUA)
  16090. | MG_FEATURES_LUA
  16091. #endif
  16092. #if defined(USE_DUKTAPE)
  16093. | MG_FEATURES_SSJS
  16094. #endif
  16095. #if !defined(NO_CACHING)
  16096. | MG_FEATURES_CACHE
  16097. #endif
  16098. #if defined(USE_SERVER_STATS)
  16099. | MG_FEATURES_STATS
  16100. #endif
  16101. #if defined(USE_ZLIB)
  16102. | MG_FEATURES_COMPRESSION
  16103. #endif
  16104. /* Set some extra bits not defined in the API documentation.
  16105. * These bits may change without further notice. */
  16106. #if defined(MG_LEGACY_INTERFACE)
  16107. | 0x00008000u
  16108. #endif
  16109. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16110. | 0x00004000u
  16111. #endif
  16112. #if defined(MEMORY_DEBUGGING)
  16113. | 0x00001000u
  16114. #endif
  16115. #if defined(USE_TIMERS)
  16116. | 0x00020000u
  16117. #endif
  16118. #if !defined(NO_NONCE_CHECK)
  16119. | 0x00040000u
  16120. #endif
  16121. #if !defined(NO_POPEN)
  16122. | 0x00080000u
  16123. #endif
  16124. ;
  16125. return (feature & feature_set);
  16126. }
  16127. /* strcat with additional NULL check to avoid clang scan-build warning. */
  16128. #define strcat0(a, b) \
  16129. { \
  16130. if ((a != NULL) && (b != NULL)) { \
  16131. strcat(a, b); \
  16132. } \
  16133. }
  16134. /* Get system information. It can be printed or stored by the caller.
  16135. * Return the size of available information. */
  16136. static int
  16137. mg_get_system_info_impl(char *buffer, int buflen)
  16138. {
  16139. char block[256];
  16140. int system_info_length = 0;
  16141. #if defined(_WIN32)
  16142. const char *eol = "\r\n";
  16143. #else
  16144. const char *eol = "\n";
  16145. #endif
  16146. const char *eoobj = "}";
  16147. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16148. if ((buffer == NULL) || (buflen < 1)) {
  16149. buflen = 0;
  16150. } else {
  16151. *buffer = 0;
  16152. }
  16153. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16154. system_info_length += (int)strlen(block);
  16155. if (system_info_length < buflen) {
  16156. strcat0(buffer, block);
  16157. }
  16158. /* Server version */
  16159. {
  16160. const char *version = mg_version();
  16161. mg_snprintf(NULL,
  16162. NULL,
  16163. block,
  16164. sizeof(block),
  16165. "\"version\" : \"%s\",%s",
  16166. version,
  16167. eol);
  16168. system_info_length += (int)strlen(block);
  16169. if (system_info_length < buflen) {
  16170. strcat0(buffer, block);
  16171. }
  16172. }
  16173. /* System info */
  16174. {
  16175. #if defined(_WIN32)
  16176. #if !defined(__SYMBIAN32__)
  16177. DWORD dwVersion = 0;
  16178. DWORD dwMajorVersion = 0;
  16179. DWORD dwMinorVersion = 0;
  16180. SYSTEM_INFO si;
  16181. GetSystemInfo(&si);
  16182. #if defined(_MSC_VER)
  16183. #pragma warning(push)
  16184. /* GetVersion was declared deprecated */
  16185. #pragma warning(disable : 4996)
  16186. #endif
  16187. dwVersion = GetVersion();
  16188. #if defined(_MSC_VER)
  16189. #pragma warning(pop)
  16190. #endif
  16191. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16192. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16193. mg_snprintf(NULL,
  16194. NULL,
  16195. block,
  16196. sizeof(block),
  16197. "\"os\" : \"Windows %u.%u\",%s",
  16198. (unsigned)dwMajorVersion,
  16199. (unsigned)dwMinorVersion,
  16200. eol);
  16201. system_info_length += (int)strlen(block);
  16202. if (system_info_length < buflen) {
  16203. strcat0(buffer, block);
  16204. }
  16205. mg_snprintf(NULL,
  16206. NULL,
  16207. block,
  16208. sizeof(block),
  16209. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  16210. (unsigned)si.wProcessorArchitecture,
  16211. (unsigned)si.dwNumberOfProcessors,
  16212. (unsigned)si.dwActiveProcessorMask,
  16213. eol);
  16214. system_info_length += (int)strlen(block);
  16215. if (system_info_length < buflen) {
  16216. strcat0(buffer, block);
  16217. }
  16218. #else
  16219. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  16220. system_info_length += (int)strlen(block);
  16221. if (system_info_length < buflen) {
  16222. strcat0(buffer, block);
  16223. }
  16224. #endif
  16225. #else
  16226. struct utsname name;
  16227. memset(&name, 0, sizeof(name));
  16228. uname(&name);
  16229. mg_snprintf(NULL,
  16230. NULL,
  16231. block,
  16232. sizeof(block),
  16233. "\"os\" : \"%s %s (%s) - %s\",%s",
  16234. name.sysname,
  16235. name.version,
  16236. name.release,
  16237. name.machine,
  16238. eol);
  16239. system_info_length += (int)strlen(block);
  16240. if (system_info_length < buflen) {
  16241. strcat0(buffer, block);
  16242. }
  16243. #endif
  16244. }
  16245. /* Features */
  16246. {
  16247. mg_snprintf(NULL,
  16248. NULL,
  16249. block,
  16250. sizeof(block),
  16251. "\"features\" : %lu,%s"
  16252. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  16253. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16254. eol,
  16255. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16256. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16257. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16258. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16259. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16260. : "",
  16261. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16262. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16263. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16264. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  16265. eol);
  16266. system_info_length += (int)strlen(block);
  16267. if (system_info_length < buflen) {
  16268. strcat0(buffer, block);
  16269. }
  16270. #if defined(USE_LUA)
  16271. mg_snprintf(NULL,
  16272. NULL,
  16273. block,
  16274. sizeof(block),
  16275. "\"lua_version\" : \"%u (%s)\",%s",
  16276. (unsigned)LUA_VERSION_NUM,
  16277. LUA_RELEASE,
  16278. eol);
  16279. system_info_length += (int)strlen(block);
  16280. if (system_info_length < buflen) {
  16281. strcat0(buffer, block);
  16282. }
  16283. #endif
  16284. #if defined(USE_DUKTAPE)
  16285. mg_snprintf(NULL,
  16286. NULL,
  16287. block,
  16288. sizeof(block),
  16289. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  16290. (unsigned)DUK_VERSION / 10000,
  16291. ((unsigned)DUK_VERSION / 100) % 100,
  16292. (unsigned)DUK_VERSION % 100,
  16293. eol);
  16294. system_info_length += (int)strlen(block);
  16295. if (system_info_length < buflen) {
  16296. strcat0(buffer, block);
  16297. }
  16298. #endif
  16299. }
  16300. /* Build date */
  16301. {
  16302. #if defined(__GNUC__)
  16303. #pragma GCC diagnostic push
  16304. /* Disable bogus compiler warning -Wdate-time */
  16305. #pragma GCC diagnostic ignored "-Wdate-time"
  16306. #endif
  16307. mg_snprintf(NULL,
  16308. NULL,
  16309. block,
  16310. sizeof(block),
  16311. "\"build\" : \"%s\",%s",
  16312. __DATE__,
  16313. eol);
  16314. #if defined(__GNUC__)
  16315. #pragma GCC diagnostic pop
  16316. #endif
  16317. system_info_length += (int)strlen(block);
  16318. if (system_info_length < buflen) {
  16319. strcat0(buffer, block);
  16320. }
  16321. }
  16322. /* Compiler information */
  16323. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16324. {
  16325. #if defined(_MSC_VER)
  16326. mg_snprintf(NULL,
  16327. NULL,
  16328. block,
  16329. sizeof(block),
  16330. "\"compiler\" : \"MSC: %u (%u)\",%s",
  16331. (unsigned)_MSC_VER,
  16332. (unsigned)_MSC_FULL_VER,
  16333. eol);
  16334. system_info_length += (int)strlen(block);
  16335. if (system_info_length < buflen) {
  16336. strcat0(buffer, block);
  16337. }
  16338. #elif defined(__MINGW64__)
  16339. mg_snprintf(NULL,
  16340. NULL,
  16341. block,
  16342. sizeof(block),
  16343. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  16344. (unsigned)__MINGW64_VERSION_MAJOR,
  16345. (unsigned)__MINGW64_VERSION_MINOR,
  16346. eol);
  16347. system_info_length += (int)strlen(block);
  16348. if (system_info_length < buflen) {
  16349. strcat0(buffer, block);
  16350. }
  16351. mg_snprintf(NULL,
  16352. NULL,
  16353. block,
  16354. sizeof(block),
  16355. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16356. (unsigned)__MINGW32_MAJOR_VERSION,
  16357. (unsigned)__MINGW32_MINOR_VERSION,
  16358. eol);
  16359. system_info_length += (int)strlen(block);
  16360. if (system_info_length < buflen) {
  16361. strcat0(buffer, block);
  16362. }
  16363. #elif defined(__MINGW32__)
  16364. mg_snprintf(NULL,
  16365. NULL,
  16366. block,
  16367. sizeof(block),
  16368. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16369. (unsigned)__MINGW32_MAJOR_VERSION,
  16370. (unsigned)__MINGW32_MINOR_VERSION,
  16371. eol);
  16372. system_info_length += (int)strlen(block);
  16373. if (system_info_length < buflen) {
  16374. strcat0(buffer, block);
  16375. }
  16376. #elif defined(__clang__)
  16377. mg_snprintf(NULL,
  16378. NULL,
  16379. block,
  16380. sizeof(block),
  16381. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  16382. __clang_major__,
  16383. __clang_minor__,
  16384. __clang_patchlevel__,
  16385. __clang_version__,
  16386. eol);
  16387. system_info_length += (int)strlen(block);
  16388. if (system_info_length < buflen) {
  16389. strcat0(buffer, block);
  16390. }
  16391. #elif defined(__GNUC__)
  16392. mg_snprintf(NULL,
  16393. NULL,
  16394. block,
  16395. sizeof(block),
  16396. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  16397. (unsigned)__GNUC__,
  16398. (unsigned)__GNUC_MINOR__,
  16399. (unsigned)__GNUC_PATCHLEVEL__,
  16400. eol);
  16401. system_info_length += (int)strlen(block);
  16402. if (system_info_length < buflen) {
  16403. strcat0(buffer, block);
  16404. }
  16405. #elif defined(__INTEL_COMPILER)
  16406. mg_snprintf(NULL,
  16407. NULL,
  16408. block,
  16409. sizeof(block),
  16410. "\"compiler\" : \"Intel C/C++: %u\",%s",
  16411. (unsigned)__INTEL_COMPILER,
  16412. eol);
  16413. system_info_length += (int)strlen(block);
  16414. if (system_info_length < buflen) {
  16415. strcat0(buffer, block);
  16416. }
  16417. #elif defined(__BORLANDC__)
  16418. mg_snprintf(NULL,
  16419. NULL,
  16420. block,
  16421. sizeof(block),
  16422. "\"compiler\" : \"Borland C: 0x%x\",%s",
  16423. (unsigned)__BORLANDC__,
  16424. eol);
  16425. system_info_length += (int)strlen(block);
  16426. if (system_info_length < buflen) {
  16427. strcat0(buffer, block);
  16428. }
  16429. #elif defined(__SUNPRO_C)
  16430. mg_snprintf(NULL,
  16431. NULL,
  16432. block,
  16433. sizeof(block),
  16434. "\"compiler\" : \"Solaris: 0x%x\",%s",
  16435. (unsigned)__SUNPRO_C,
  16436. eol);
  16437. system_info_length += (int)strlen(block);
  16438. if (system_info_length < buflen) {
  16439. strcat0(buffer, block);
  16440. }
  16441. #else
  16442. mg_snprintf(NULL,
  16443. NULL,
  16444. block,
  16445. sizeof(block),
  16446. "\"compiler\" : \"other\",%s",
  16447. eol);
  16448. system_info_length += (int)strlen(block);
  16449. if (system_info_length < buflen) {
  16450. strcat0(buffer, block);
  16451. }
  16452. #endif
  16453. }
  16454. /* Determine 32/64 bit data mode.
  16455. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16456. {
  16457. mg_snprintf(NULL,
  16458. NULL,
  16459. block,
  16460. sizeof(block),
  16461. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16462. "char:%u/%u, "
  16463. "ptr:%u, size:%u, time:%u\"%s",
  16464. (unsigned)sizeof(short),
  16465. (unsigned)sizeof(int),
  16466. (unsigned)sizeof(long),
  16467. (unsigned)sizeof(long long),
  16468. (unsigned)sizeof(float),
  16469. (unsigned)sizeof(double),
  16470. (unsigned)sizeof(long double),
  16471. (unsigned)sizeof(char),
  16472. (unsigned)sizeof(wchar_t),
  16473. (unsigned)sizeof(void *),
  16474. (unsigned)sizeof(size_t),
  16475. (unsigned)sizeof(time_t),
  16476. eol);
  16477. system_info_length += (int)strlen(block);
  16478. if (system_info_length < buflen) {
  16479. strcat0(buffer, block);
  16480. }
  16481. }
  16482. /* Terminate string */
  16483. if ((buflen > 0) && buffer && buffer[0]) {
  16484. if (system_info_length < buflen) {
  16485. strcat0(buffer, eoobj);
  16486. strcat0(buffer, eol);
  16487. }
  16488. }
  16489. system_info_length += reserved_len;
  16490. return system_info_length;
  16491. }
  16492. #if defined(USE_SERVER_STATS)
  16493. /* Get context information. It can be printed or stored by the caller.
  16494. * Return the size of available information. */
  16495. static int
  16496. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  16497. {
  16498. char block[256];
  16499. int context_info_length = 0;
  16500. #if defined(_WIN32)
  16501. const char *eol = "\r\n";
  16502. #else
  16503. const char *eol = "\n";
  16504. #endif
  16505. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16506. const char *eoobj = "}";
  16507. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16508. if ((buffer == NULL) || (buflen < 1)) {
  16509. buflen = 0;
  16510. } else {
  16511. *buffer = 0;
  16512. }
  16513. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16514. context_info_length += (int)strlen(block);
  16515. if (context_info_length < buflen) {
  16516. strcat0(buffer, block);
  16517. }
  16518. if (ms) { /* <-- should be always true */
  16519. /* Memory information */
  16520. mg_snprintf(NULL,
  16521. NULL,
  16522. block,
  16523. sizeof(block),
  16524. "\"memory\" : {%s"
  16525. "\"blocks\" : %i,%s"
  16526. "\"used\" : %" INT64_FMT ",%s"
  16527. "\"maxUsed\" : %" INT64_FMT "%s"
  16528. "}%s%s",
  16529. eol,
  16530. ms->blockCount,
  16531. eol,
  16532. ms->totalMemUsed,
  16533. eol,
  16534. ms->maxMemUsed,
  16535. eol,
  16536. (ctx ? "," : ""),
  16537. eol);
  16538. context_info_length += (int)strlen(block);
  16539. if (context_info_length + reserved_len < buflen) {
  16540. strcat0(buffer, block);
  16541. }
  16542. }
  16543. if (ctx) {
  16544. /* Declare all variables at begin of the block, to comply
  16545. * with old C standards. */
  16546. char start_time_str[64] = {0};
  16547. char now_str[64] = {0};
  16548. time_t start_time = ctx->start_time;
  16549. time_t now = time(NULL);
  16550. /* Connections information */
  16551. mg_snprintf(NULL,
  16552. NULL,
  16553. block,
  16554. sizeof(block),
  16555. "\"connections\" : {%s"
  16556. "\"active\" : %i,%s"
  16557. "\"maxActive\" : %i,%s"
  16558. "\"total\" : %" INT64_FMT "%s"
  16559. "},%s",
  16560. eol,
  16561. ctx->active_connections,
  16562. eol,
  16563. ctx->max_connections,
  16564. eol,
  16565. ctx->total_connections,
  16566. eol,
  16567. eol);
  16568. context_info_length += (int)strlen(block);
  16569. if (context_info_length + reserved_len < buflen) {
  16570. strcat0(buffer, block);
  16571. }
  16572. /* Requests information */
  16573. mg_snprintf(NULL,
  16574. NULL,
  16575. block,
  16576. sizeof(block),
  16577. "\"requests\" : {%s"
  16578. "\"total\" : %" INT64_FMT "%s"
  16579. "},%s",
  16580. eol,
  16581. ctx->total_requests,
  16582. eol,
  16583. eol);
  16584. context_info_length += (int)strlen(block);
  16585. if (context_info_length + reserved_len < buflen) {
  16586. strcat0(buffer, block);
  16587. }
  16588. /* Data information */
  16589. mg_snprintf(NULL,
  16590. NULL,
  16591. block,
  16592. sizeof(block),
  16593. "\"data\" : {%s"
  16594. "\"read\" : %" INT64_FMT "%s,"
  16595. "\"written\" : %" INT64_FMT "%s"
  16596. "},%s",
  16597. eol,
  16598. ctx->total_data_read,
  16599. eol,
  16600. ctx->total_data_written,
  16601. eol,
  16602. eol);
  16603. context_info_length += (int)strlen(block);
  16604. if (context_info_length + reserved_len < buflen) {
  16605. strcat0(buffer, block);
  16606. }
  16607. /* Execution time information */
  16608. gmt_time_string(start_time_str,
  16609. sizeof(start_time_str) - 1,
  16610. &start_time);
  16611. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16612. mg_snprintf(NULL,
  16613. NULL,
  16614. block,
  16615. sizeof(block),
  16616. "\"time\" : {%s"
  16617. "\"uptime\" : %.0f,%s"
  16618. "\"start\" : \"%s\",%s"
  16619. "\"now\" : \"%s\"%s"
  16620. "}%s",
  16621. eol,
  16622. difftime(now, start_time),
  16623. eol,
  16624. start_time_str,
  16625. eol,
  16626. now_str,
  16627. eol,
  16628. eol);
  16629. context_info_length += (int)strlen(block);
  16630. if (context_info_length + reserved_len < buflen) {
  16631. strcat0(buffer, block);
  16632. }
  16633. }
  16634. /* Terminate string */
  16635. if ((buflen > 0) && buffer && buffer[0]) {
  16636. if (context_info_length < buflen) {
  16637. strcat0(buffer, eoobj);
  16638. strcat0(buffer, eol);
  16639. }
  16640. }
  16641. context_info_length += reserved_len;
  16642. return context_info_length;
  16643. }
  16644. #endif
  16645. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16646. /* Get connection information. It can be printed or stored by the caller.
  16647. * Return the size of available information. */
  16648. static int
  16649. mg_get_connection_info_impl(const struct mg_context *ctx,
  16650. int idx,
  16651. char *buffer,
  16652. int buflen)
  16653. {
  16654. const struct mg_connection *conn;
  16655. const struct mg_request_info *ri;
  16656. char block[256];
  16657. int connection_info_length = 0;
  16658. int state = 0;
  16659. const char *state_str = "unknown";
  16660. #if defined(_WIN32)
  16661. const char *eol = "\r\n";
  16662. #else
  16663. const char *eol = "\n";
  16664. #endif
  16665. const char *eoobj = "}";
  16666. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16667. if ((buffer == NULL) || (buflen < 1)) {
  16668. buflen = 0;
  16669. } else {
  16670. *buffer = 0;
  16671. }
  16672. if ((ctx == NULL) || (idx < 0)) {
  16673. /* Parameter error */
  16674. return 0;
  16675. }
  16676. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16677. /* Out of range */
  16678. return 0;
  16679. }
  16680. /* Take connection [idx]. This connection is not locked in
  16681. * any way, so some other thread might use it. */
  16682. conn = (ctx->worker_connections) + idx;
  16683. /* Initialize output string */
  16684. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16685. connection_info_length += (int)strlen(block);
  16686. if (connection_info_length < buflen) {
  16687. strcat0(buffer, block);
  16688. }
  16689. /* Init variables */
  16690. ri = &(conn->request_info);
  16691. #if defined(USE_SERVER_STATS)
  16692. state = conn->conn_state;
  16693. /* State as string */
  16694. switch (state) {
  16695. case 0:
  16696. state_str = "undefined";
  16697. break;
  16698. case 1:
  16699. state_str = "not used";
  16700. break;
  16701. case 2:
  16702. state_str = "init";
  16703. break;
  16704. case 3:
  16705. state_str = "ready";
  16706. break;
  16707. case 4:
  16708. state_str = "processing";
  16709. break;
  16710. case 5:
  16711. state_str = "processed";
  16712. break;
  16713. case 6:
  16714. state_str = "to close";
  16715. break;
  16716. case 7:
  16717. state_str = "closing";
  16718. break;
  16719. case 8:
  16720. state_str = "closed";
  16721. break;
  16722. case 9:
  16723. state_str = "done";
  16724. break;
  16725. }
  16726. #endif
  16727. /* Connection info */
  16728. if ((state >= 3) && (state < 9)) {
  16729. mg_snprintf(NULL,
  16730. NULL,
  16731. block,
  16732. sizeof(block),
  16733. "\"connection\" : {%s"
  16734. "\"remote\" : {%s"
  16735. "\"protocol\" : \"%s\",%s"
  16736. "\"addr\" : \"%s\",%s"
  16737. "\"port\" : %u%s"
  16738. "},%s"
  16739. "\"handled_requests\" : %u%s"
  16740. "},%s",
  16741. eol,
  16742. eol,
  16743. get_proto_name(conn),
  16744. eol,
  16745. ri->remote_addr,
  16746. eol,
  16747. ri->remote_port,
  16748. eol,
  16749. eol,
  16750. conn->handled_requests,
  16751. eol,
  16752. eol);
  16753. connection_info_length += (int)strlen(block);
  16754. if (connection_info_length + reserved_len < buflen) {
  16755. strcat0(buffer, block);
  16756. }
  16757. }
  16758. /* Request info */
  16759. if ((state >= 4) && (state < 6)) {
  16760. mg_snprintf(NULL,
  16761. NULL,
  16762. block,
  16763. sizeof(block),
  16764. "\"request_info\" : {%s"
  16765. "\"method\" : \"%s\",%s"
  16766. "\"uri\" : \"%s\",%s"
  16767. "\"query\" : %s%s%s%s"
  16768. "},%s",
  16769. eol,
  16770. ri->request_method,
  16771. eol,
  16772. ri->request_uri,
  16773. eol,
  16774. ri->query_string ? "\"" : "",
  16775. ri->query_string ? ri->query_string : "null",
  16776. ri->query_string ? "\"" : "",
  16777. eol,
  16778. eol);
  16779. connection_info_length += (int)strlen(block);
  16780. if (connection_info_length + reserved_len < buflen) {
  16781. strcat0(buffer, block);
  16782. }
  16783. }
  16784. /* Execution time information */
  16785. if ((state >= 2) && (state < 9)) {
  16786. char start_time_str[64] = {0};
  16787. char now_str[64] = {0};
  16788. time_t start_time = conn->conn_birth_time;
  16789. time_t now = time(NULL);
  16790. gmt_time_string(start_time_str,
  16791. sizeof(start_time_str) - 1,
  16792. &start_time);
  16793. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16794. mg_snprintf(NULL,
  16795. NULL,
  16796. block,
  16797. sizeof(block),
  16798. "\"time\" : {%s"
  16799. "\"uptime\" : %.0f,%s"
  16800. "\"start\" : \"%s\",%s"
  16801. "\"now\" : \"%s\"%s"
  16802. "},%s",
  16803. eol,
  16804. difftime(now, start_time),
  16805. eol,
  16806. start_time_str,
  16807. eol,
  16808. now_str,
  16809. eol,
  16810. eol);
  16811. connection_info_length += (int)strlen(block);
  16812. if (connection_info_length + reserved_len < buflen) {
  16813. strcat0(buffer, block);
  16814. }
  16815. }
  16816. /* Remote user name */
  16817. if ((ri->remote_user) && (state < 9)) {
  16818. mg_snprintf(NULL,
  16819. NULL,
  16820. block,
  16821. sizeof(block),
  16822. "\"user\" : {%s"
  16823. "\"name\" : \"%s\",%s"
  16824. "},%s",
  16825. eol,
  16826. ri->remote_user,
  16827. eol,
  16828. eol);
  16829. connection_info_length += (int)strlen(block);
  16830. if (connection_info_length + reserved_len < buflen) {
  16831. strcat0(buffer, block);
  16832. }
  16833. }
  16834. /* Data block */
  16835. if (state >= 3) {
  16836. mg_snprintf(NULL,
  16837. NULL,
  16838. block,
  16839. sizeof(block),
  16840. "\"data\" : {%s"
  16841. "\"read\" : %" INT64_FMT ",%s"
  16842. "\"written\" : %" INT64_FMT "%s"
  16843. "},%s",
  16844. eol,
  16845. conn->consumed_content,
  16846. eol,
  16847. conn->num_bytes_sent,
  16848. eol,
  16849. eol);
  16850. connection_info_length += (int)strlen(block);
  16851. if (connection_info_length + reserved_len < buflen) {
  16852. strcat0(buffer, block);
  16853. }
  16854. }
  16855. /* State */
  16856. mg_snprintf(NULL,
  16857. NULL,
  16858. block,
  16859. sizeof(block),
  16860. "\"state\" : \"%s\"%s",
  16861. state_str,
  16862. eol);
  16863. connection_info_length += (int)strlen(block);
  16864. if (connection_info_length + reserved_len < buflen) {
  16865. strcat0(buffer, block);
  16866. }
  16867. /* Terminate string */
  16868. if ((buflen > 0) && buffer && buffer[0]) {
  16869. if (connection_info_length < buflen) {
  16870. strcat0(buffer, eoobj);
  16871. strcat0(buffer, eol);
  16872. }
  16873. }
  16874. connection_info_length += reserved_len;
  16875. return connection_info_length;
  16876. }
  16877. #endif
  16878. /* Get system information. It can be printed or stored by the caller.
  16879. * Return the size of available information. */
  16880. int
  16881. mg_get_system_info(char *buffer, int buflen)
  16882. {
  16883. if ((buffer == NULL) || (buflen < 1)) {
  16884. return mg_get_system_info_impl(NULL, 0);
  16885. } else {
  16886. /* Reset buffer, so we can always use strcat. */
  16887. buffer[0] = 0;
  16888. return mg_get_system_info_impl(buffer, buflen);
  16889. }
  16890. }
  16891. /* Get context information. It can be printed or stored by the caller.
  16892. * Return the size of available information. */
  16893. int
  16894. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16895. {
  16896. #if defined(USE_SERVER_STATS)
  16897. if ((buffer == NULL) || (buflen < 1)) {
  16898. return mg_get_context_info_impl(ctx, NULL, 0);
  16899. } else {
  16900. /* Reset buffer, so we can always use strcat. */
  16901. buffer[0] = 0;
  16902. return mg_get_context_info_impl(ctx, buffer, buflen);
  16903. }
  16904. #else
  16905. (void)ctx;
  16906. if ((buffer != NULL) && (buflen > 0)) {
  16907. buffer[0] = 0;
  16908. }
  16909. return 0;
  16910. #endif
  16911. }
  16912. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16913. int
  16914. mg_get_connection_info(const struct mg_context *ctx,
  16915. int idx,
  16916. char *buffer,
  16917. int buflen)
  16918. {
  16919. if ((buffer == NULL) || (buflen < 1)) {
  16920. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  16921. } else {
  16922. /* Reset buffer, so we can always use strcat. */
  16923. buffer[0] = 0;
  16924. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  16925. }
  16926. }
  16927. #endif
  16928. /* Initialize this library. This function does not need to be thread safe.
  16929. */
  16930. unsigned
  16931. mg_init_library(unsigned features)
  16932. {
  16933. #if !defined(NO_SSL)
  16934. char ebuf[128];
  16935. #endif
  16936. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  16937. unsigned features_inited = features_to_init;
  16938. if (mg_init_library_called <= 0) {
  16939. /* Not initialized yet */
  16940. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  16941. return 0;
  16942. }
  16943. }
  16944. mg_global_lock();
  16945. if (mg_init_library_called <= 0) {
  16946. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  16947. /* Fatal error - abort start. However, this situation should
  16948. * never occur in practice. */
  16949. mg_global_unlock();
  16950. return 0;
  16951. }
  16952. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16953. InitializeCriticalSection(&global_log_file_lock);
  16954. #endif /* _WIN32 && !__SYMBIAN32__ */
  16955. #if !defined(_WIN32)
  16956. pthread_mutexattr_init(&pthread_mutex_attr);
  16957. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  16958. #endif
  16959. #if defined(USE_LUA)
  16960. lua_init_optional_libraries();
  16961. #endif
  16962. }
  16963. mg_global_unlock();
  16964. #if !defined(NO_SSL)
  16965. if (features_to_init & MG_FEATURES_SSL) {
  16966. if (!mg_ssl_initialized) {
  16967. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  16968. mg_ssl_initialized = 1;
  16969. } else {
  16970. (void)ebuf;
  16971. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16972. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  16973. }
  16974. } else {
  16975. /* ssl already initialized */
  16976. }
  16977. }
  16978. #endif
  16979. /* Start WinSock for Windows */
  16980. mg_global_lock();
  16981. if (mg_init_library_called <= 0) {
  16982. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16983. WSADATA data;
  16984. WSAStartup(MAKEWORD(2, 2), &data);
  16985. #endif /* _WIN32 && !__SYMBIAN32__ */
  16986. mg_init_library_called = 1;
  16987. } else {
  16988. mg_init_library_called++;
  16989. }
  16990. mg_global_unlock();
  16991. return features_inited;
  16992. }
  16993. /* Un-initialize this library. */
  16994. unsigned
  16995. mg_exit_library(void)
  16996. {
  16997. if (mg_init_library_called <= 0) {
  16998. return 0;
  16999. }
  17000. mg_global_lock();
  17001. mg_init_library_called--;
  17002. if (mg_init_library_called == 0) {
  17003. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  17004. (void)WSACleanup();
  17005. #endif /* _WIN32 && !__SYMBIAN32__ */
  17006. #if !defined(NO_SSL)
  17007. if (mg_ssl_initialized) {
  17008. uninitialize_ssl();
  17009. mg_ssl_initialized = 0;
  17010. }
  17011. #endif
  17012. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  17013. (void)DeleteCriticalSection(&global_log_file_lock);
  17014. #endif /* _WIN32 && !__SYMBIAN32__ */
  17015. #if !defined(_WIN32)
  17016. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17017. #endif
  17018. (void)pthread_key_delete(sTlsKey);
  17019. #if defined(USE_LUA)
  17020. lua_exit_optional_libraries();
  17021. #endif
  17022. mg_global_unlock();
  17023. (void)pthread_mutex_destroy(&global_lock_mutex);
  17024. return 1;
  17025. }
  17026. mg_global_unlock();
  17027. return 1;
  17028. }
  17029. /* End of civetweb.c */