civetweb.c 526 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730
  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. */
  128. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  129. #define NO_SSL /* SSL is not supported */
  130. #define NO_CGI /* CGI is not supported */
  131. #define PATH_MAX FILENAME_MAX
  132. #endif /* __SYMBIAN32__ */
  133. #if !defined(CIVETWEB_HEADER_INCLUDED)
  134. /* Include the header file here, so the CivetWeb interface is defined for the
  135. * entire implementation, including the following forward definitions. */
  136. #include "civetweb.h"
  137. #endif
  138. #if !defined(DEBUG_TRACE)
  139. #if defined(DEBUG)
  140. static void DEBUG_TRACE_FUNC(const char *func,
  141. unsigned line,
  142. PRINTF_FORMAT_STRING(const char *fmt),
  143. ...) PRINTF_ARGS(3, 4);
  144. #define DEBUG_TRACE(fmt, ...) \
  145. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  146. #define NEED_DEBUG_TRACE_FUNC
  147. #else
  148. #define DEBUG_TRACE(fmt, ...) \
  149. do { \
  150. } while (0)
  151. #endif /* DEBUG */
  152. #endif /* DEBUG_TRACE */
  153. #if !defined(DEBUG_ASSERT)
  154. #if defined(DEBUG)
  155. #define DEBUG_ASSERT(cond) \
  156. do { \
  157. if (!(cond)) { \
  158. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  159. exit(2); /* Exit with error */ \
  160. } \
  161. } while (0)
  162. #else
  163. #define DEBUG_ASSERT(cond)
  164. #endif /* DEBUG */
  165. #endif
  166. #if !defined(IGNORE_UNUSED_RESULT)
  167. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  168. #endif
  169. #if defined(__GNUC__) || defined(__MINGW32__)
  170. /* GCC unused function attribute seems fundamentally broken.
  171. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  172. * OR UNUSED" for individual functions failed.
  173. * Either the compiler creates an "unused-function" warning if a
  174. * function is not marked with __attribute__((unused)).
  175. * On the other hand, if the function is marked with this attribute,
  176. * but is used, the compiler raises a completely idiotic
  177. * "used-but-marked-unused" warning - and
  178. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  179. * raises error: unknown option after "#pragma GCC diagnostic".
  180. * Disable this warning completely, until the GCC guys sober up
  181. * again.
  182. */
  183. #pragma GCC diagnostic ignored "-Wunused-function"
  184. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  185. #else
  186. #define FUNCTION_MAY_BE_UNUSED
  187. #endif
  188. /* Some ANSI #includes are not available on Windows CE */
  189. #if !defined(_WIN32_WCE)
  190. #include <sys/types.h>
  191. #include <sys/stat.h>
  192. #include <errno.h>
  193. #include <signal.h>
  194. #include <fcntl.h>
  195. #endif /* !_WIN32_WCE */
  196. #if defined(__clang__)
  197. /* When using -Weverything, clang does not accept it's own headers
  198. * in a release build configuration. Disable what is too much in
  199. * -Weverything. */
  200. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  201. #endif
  202. #if defined(__GNUC__) || defined(__MINGW32__)
  203. /* Who on earth came to the conclusion, using __DATE__ should rise
  204. * an "expansion of date or time macro is not reproducible"
  205. * warning. That's exactly what was intended by using this macro.
  206. * Just disable this nonsense warning. */
  207. /* And disabling them does not work either:
  208. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  209. * #pragma clang diagnostic ignored "-Wdate-time"
  210. * So we just have to disable ALL warnings for some lines
  211. * of code.
  212. * This seems to be a known GCC bug, not resolved since 2012:
  213. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  214. */
  215. #endif
  216. #if defined(__MACH__) /* Apple OSX section */
  217. #if defined(__clang__)
  218. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  219. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  220. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  221. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  222. #endif
  223. #endif
  224. #define CLOCK_MONOTONIC (1)
  225. #define CLOCK_REALTIME (2)
  226. #include <sys/errno.h>
  227. #include <sys/time.h>
  228. #include <mach/clock.h>
  229. #include <mach/mach.h>
  230. #include <mach/mach_time.h>
  231. /* clock_gettime is not implemented on OSX prior to 10.12 */
  232. static int
  233. _civet_clock_gettime(int clk_id, struct timespec *t)
  234. {
  235. memset(t, 0, sizeof(*t));
  236. if (clk_id == CLOCK_REALTIME) {
  237. struct timeval now;
  238. int rv = gettimeofday(&now, NULL);
  239. if (rv) {
  240. return rv;
  241. }
  242. t->tv_sec = now.tv_sec;
  243. t->tv_nsec = now.tv_usec * 1000;
  244. return 0;
  245. } else if (clk_id == CLOCK_MONOTONIC) {
  246. static uint64_t clock_start_time = 0;
  247. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  248. uint64_t now = mach_absolute_time();
  249. if (clock_start_time == 0) {
  250. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  251. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  252. /* appease "unused variable" warning for release builds */
  253. (void)mach_status;
  254. clock_start_time = now;
  255. }
  256. now = (uint64_t)((double)(now - clock_start_time)
  257. * (double)timebase_ifo.numer
  258. / (double)timebase_ifo.denom);
  259. t->tv_sec = now / 1000000000;
  260. t->tv_nsec = now % 1000000000;
  261. return 0;
  262. }
  263. return -1; /* EINVAL - Clock ID is unknown */
  264. }
  265. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  266. #if defined(__CLOCK_AVAILABILITY)
  267. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  268. * declared but it may be NULL at runtime. So we need to check before using
  269. * it. */
  270. static int
  271. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  272. {
  273. if (clock_gettime) {
  274. return clock_gettime(clk_id, t);
  275. }
  276. return _civet_clock_gettime(clk_id, t);
  277. }
  278. #define clock_gettime _civet_safe_clock_gettime
  279. #else
  280. #define clock_gettime _civet_clock_gettime
  281. #endif
  282. #endif
  283. #include <time.h>
  284. #include <stdlib.h>
  285. #include <stdarg.h>
  286. #include <string.h>
  287. #include <ctype.h>
  288. #include <limits.h>
  289. #include <stddef.h>
  290. #include <stdio.h>
  291. #include <stdint.h>
  292. /********************************************************************/
  293. /* CivetWeb configuration defines */
  294. /********************************************************************/
  295. /* Maximum number of threads that can be configured.
  296. * The number of threads actually created depends on the "num_threads"
  297. * configuration parameter, but this is the upper limit. */
  298. #if !defined(MAX_WORKER_THREADS)
  299. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  300. #endif
  301. /* Timeout interval for select/poll calls.
  302. * The timeouts depend on "*_timeout_ms" configuration values, but long
  303. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  304. * This reduces the time required to stop the server. */
  305. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  306. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  307. #endif
  308. /* Do not try to compress files smaller than this limit. */
  309. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  310. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  311. #endif
  312. #if !defined(PASSWORDS_FILE_NAME)
  313. #define PASSWORDS_FILE_NAME ".htpasswd"
  314. #endif
  315. /* Initial buffer size for all CGI environment variables. In case there is
  316. * not enough space, another block is allocated. */
  317. #if !defined(CGI_ENVIRONMENT_SIZE)
  318. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  319. #endif
  320. /* Maximum number of environment variables. */
  321. #if !defined(MAX_CGI_ENVIR_VARS)
  322. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  323. #endif
  324. /* General purpose buffer size. */
  325. #if !defined(MG_BUF_LEN) /* in bytes */
  326. #define MG_BUF_LEN (1024 * 8)
  327. #endif
  328. /* Size of the accepted socket queue (in case the old queue implementation
  329. * is used). */
  330. #if !defined(MGSQLEN)
  331. #define MGSQLEN (20) /* count */
  332. #endif
  333. /********************************************************************/
  334. /* Helper makros */
  335. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  336. /* Standard defines */
  337. #if !defined(INT64_MAX)
  338. #define INT64_MAX (9223372036854775807)
  339. #endif
  340. #define SHUTDOWN_RD (0)
  341. #define SHUTDOWN_WR (1)
  342. #define SHUTDOWN_BOTH (2)
  343. mg_static_assert(MAX_WORKER_THREADS >= 1,
  344. "worker threads must be a positive number");
  345. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  346. "size_t data type size check");
  347. #if defined(_WIN32) /* WINDOWS include block */
  348. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  349. #include <ws2tcpip.h>
  350. #include <windows.h>
  351. typedef const char *SOCK_OPT_TYPE;
  352. #if !defined(PATH_MAX)
  353. #define W_PATH_MAX (MAX_PATH)
  354. /* at most three UTF-8 chars per wchar_t */
  355. #define PATH_MAX (W_PATH_MAX * 3)
  356. #else
  357. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  358. #endif
  359. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  360. #if !defined(_IN_PORT_T)
  361. #if !defined(in_port_t)
  362. #define in_port_t u_short
  363. #endif
  364. #endif
  365. #if !defined(_WIN32_WCE)
  366. #include <process.h>
  367. #include <direct.h>
  368. #include <io.h>
  369. #else /* _WIN32_WCE */
  370. #define NO_CGI /* WinCE has no pipes */
  371. #define NO_POPEN /* WinCE has no popen */
  372. typedef long off_t;
  373. #define errno ((int)(GetLastError()))
  374. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  375. #endif /* _WIN32_WCE */
  376. #define MAKEUQUAD(lo, hi) \
  377. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  378. #define RATE_DIFF (10000000) /* 100 nsecs */
  379. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  380. #define SYS2UNIX_TIME(lo, hi) \
  381. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  382. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  383. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  384. * Also use _strtoui64 on modern M$ compilers */
  385. #if defined(_MSC_VER)
  386. #if (_MSC_VER < 1300)
  387. #define STRX(x) #x
  388. #define STR(x) STRX(x)
  389. #define __func__ __FILE__ ":" STR(__LINE__)
  390. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  391. #define strtoll(x, y, z) (_atoi64(x))
  392. #else
  393. #define __func__ __FUNCTION__
  394. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  395. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  396. #endif
  397. #endif /* _MSC_VER */
  398. #define ERRNO ((int)(GetLastError()))
  399. #define NO_SOCKLEN_T
  400. #if defined(_WIN64) || defined(__MINGW64__)
  401. #if !defined(SSL_LIB)
  402. #define SSL_LIB "ssleay64.dll"
  403. #endif
  404. #if !defined(CRYPTO_LIB)
  405. #define CRYPTO_LIB "libeay64.dll"
  406. #endif
  407. #else
  408. #if !defined(SSL_LIB)
  409. #define SSL_LIB "ssleay32.dll"
  410. #endif
  411. #if !defined(CRYPTO_LIB)
  412. #define CRYPTO_LIB "libeay32.dll"
  413. #endif
  414. #endif
  415. #define O_NONBLOCK (0)
  416. #if !defined(W_OK)
  417. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  418. #endif
  419. #if !defined(EWOULDBLOCK)
  420. #define EWOULDBLOCK WSAEWOULDBLOCK
  421. #endif /* !EWOULDBLOCK */
  422. #define _POSIX_
  423. #define INT64_FMT "I64d"
  424. #define UINT64_FMT "I64u"
  425. #define WINCDECL __cdecl
  426. #define vsnprintf_impl _vsnprintf
  427. #define access _access
  428. #define mg_sleep(x) (Sleep(x))
  429. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  430. #if !defined(popen)
  431. #define popen(x, y) (_popen(x, y))
  432. #endif
  433. #if !defined(pclose)
  434. #define pclose(x) (_pclose(x))
  435. #endif
  436. #define close(x) (_close(x))
  437. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  438. #define RTLD_LAZY (0)
  439. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  440. #define fdopen(x, y) (_fdopen((x), (y)))
  441. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  442. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  443. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  444. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  445. #define sleep(x) (Sleep((x)*1000))
  446. #define rmdir(x) (_rmdir(x))
  447. #if defined(_WIN64) || !defined(__MINGW32__)
  448. /* Only MinGW 32 bit is missing this function */
  449. #define timegm(x) (_mkgmtime(x))
  450. #else
  451. time_t timegm(struct tm *tm);
  452. #define NEED_TIMEGM
  453. #endif
  454. #if !defined(fileno)
  455. #define fileno(x) (_fileno(x))
  456. #endif /* !fileno MINGW #defines fileno */
  457. typedef HANDLE pthread_mutex_t;
  458. typedef DWORD pthread_key_t;
  459. typedef HANDLE pthread_t;
  460. typedef struct {
  461. CRITICAL_SECTION threadIdSec;
  462. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  463. } pthread_cond_t;
  464. #if !defined(__clockid_t_defined)
  465. typedef DWORD clockid_t;
  466. #endif
  467. #if !defined(CLOCK_MONOTONIC)
  468. #define CLOCK_MONOTONIC (1)
  469. #endif
  470. #if !defined(CLOCK_REALTIME)
  471. #define CLOCK_REALTIME (2)
  472. #endif
  473. #if !defined(CLOCK_THREAD)
  474. #define CLOCK_THREAD (3)
  475. #endif
  476. #if !defined(CLOCK_PROCESS)
  477. #define CLOCK_PROCESS (4)
  478. #endif
  479. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  480. #define _TIMESPEC_DEFINED
  481. #endif
  482. #if !defined(_TIMESPEC_DEFINED)
  483. struct timespec {
  484. time_t tv_sec; /* seconds */
  485. long tv_nsec; /* nanoseconds */
  486. };
  487. #endif
  488. #if !defined(WIN_PTHREADS_TIME_H)
  489. #define MUST_IMPLEMENT_CLOCK_GETTIME
  490. #endif
  491. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  492. #define clock_gettime mg_clock_gettime
  493. static int
  494. clock_gettime(clockid_t clk_id, struct timespec *tp)
  495. {
  496. FILETIME ft;
  497. ULARGE_INTEGER li, li2;
  498. BOOL ok = FALSE;
  499. double d;
  500. static double perfcnt_per_sec = 0.0;
  501. static BOOL initialized = FALSE;
  502. if (!initialized) {
  503. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  504. perfcnt_per_sec = 1.0 / li.QuadPart;
  505. initialized = TRUE;
  506. }
  507. if (tp) {
  508. memset(tp, 0, sizeof(*tp));
  509. if (clk_id == CLOCK_REALTIME) {
  510. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  511. GetSystemTimeAsFileTime(&ft);
  512. li.LowPart = ft.dwLowDateTime;
  513. li.HighPart = ft.dwHighDateTime;
  514. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  515. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  516. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  517. ok = TRUE;
  518. /* END: CLOCK_REALTIME */
  519. } else if (clk_id == CLOCK_MONOTONIC) {
  520. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  521. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  522. d = li.QuadPart * perfcnt_per_sec;
  523. tp->tv_sec = (time_t)d;
  524. d -= (double)tp->tv_sec;
  525. tp->tv_nsec = (long)(d * 1.0E9);
  526. ok = TRUE;
  527. /* END: CLOCK_MONOTONIC */
  528. } else if (clk_id == CLOCK_THREAD) {
  529. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  530. FILETIME t_create, t_exit, t_kernel, t_user;
  531. if (GetThreadTimes(GetCurrentThread(),
  532. &t_create,
  533. &t_exit,
  534. &t_kernel,
  535. &t_user)) {
  536. li.LowPart = t_user.dwLowDateTime;
  537. li.HighPart = t_user.dwHighDateTime;
  538. li2.LowPart = t_kernel.dwLowDateTime;
  539. li2.HighPart = t_kernel.dwHighDateTime;
  540. li.QuadPart += li2.QuadPart;
  541. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  542. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  543. ok = TRUE;
  544. }
  545. /* END: CLOCK_THREAD */
  546. } else if (clk_id == CLOCK_PROCESS) {
  547. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  548. FILETIME t_create, t_exit, t_kernel, t_user;
  549. if (GetProcessTimes(GetCurrentProcess(),
  550. &t_create,
  551. &t_exit,
  552. &t_kernel,
  553. &t_user)) {
  554. li.LowPart = t_user.dwLowDateTime;
  555. li.HighPart = t_user.dwHighDateTime;
  556. li2.LowPart = t_kernel.dwLowDateTime;
  557. li2.HighPart = t_kernel.dwHighDateTime;
  558. li.QuadPart += li2.QuadPart;
  559. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  560. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  561. ok = TRUE;
  562. }
  563. /* END: CLOCK_PROCESS */
  564. } else {
  565. /* BEGIN: unknown clock */
  566. /* ok = FALSE; already set by init */
  567. /* END: unknown clock */
  568. }
  569. }
  570. return ok ? 0 : -1;
  571. }
  572. #endif
  573. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  574. static int pthread_mutex_lock(pthread_mutex_t *);
  575. static int pthread_mutex_unlock(pthread_mutex_t *);
  576. static void path_to_unicode(const struct mg_connection *conn,
  577. const char *path,
  578. wchar_t *wbuf,
  579. size_t wbuf_len);
  580. /* All file operations need to be rewritten to solve #246. */
  581. struct mg_file;
  582. static const char *
  583. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  584. /* POSIX dirent interface */
  585. struct dirent {
  586. char d_name[PATH_MAX];
  587. };
  588. typedef struct DIR {
  589. HANDLE handle;
  590. WIN32_FIND_DATAW info;
  591. struct dirent result;
  592. } DIR;
  593. #if defined(_WIN32)
  594. #if !defined(HAVE_POLL)
  595. struct pollfd {
  596. SOCKET fd;
  597. short events;
  598. short revents;
  599. };
  600. #endif
  601. #endif
  602. /* Mark required libraries */
  603. #if defined(_MSC_VER)
  604. #pragma comment(lib, "Ws2_32.lib")
  605. #endif
  606. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  607. #include <sys/wait.h>
  608. #include <sys/socket.h>
  609. #include <sys/poll.h>
  610. #include <netinet/in.h>
  611. #include <arpa/inet.h>
  612. #include <sys/time.h>
  613. #include <sys/utsname.h>
  614. #include <stdint.h>
  615. #include <inttypes.h>
  616. #include <netdb.h>
  617. #include <netinet/tcp.h>
  618. typedef const void *SOCK_OPT_TYPE;
  619. #if defined(ANDROID)
  620. typedef unsigned short int in_port_t;
  621. #endif
  622. #include <pwd.h>
  623. #include <unistd.h>
  624. #include <grp.h>
  625. #include <dirent.h>
  626. #define vsnprintf_impl vsnprintf
  627. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  628. #include <dlfcn.h>
  629. #endif
  630. #include <pthread.h>
  631. #if defined(__MACH__)
  632. #define SSL_LIB "libssl.dylib"
  633. #define CRYPTO_LIB "libcrypto.dylib"
  634. #else
  635. #if !defined(SSL_LIB)
  636. #define SSL_LIB "libssl.so"
  637. #endif
  638. #if !defined(CRYPTO_LIB)
  639. #define CRYPTO_LIB "libcrypto.so"
  640. #endif
  641. #endif
  642. #if !defined(O_BINARY)
  643. #define O_BINARY (0)
  644. #endif /* O_BINARY */
  645. #define closesocket(a) (close(a))
  646. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  647. #define mg_remove(conn, x) (remove(x))
  648. #define mg_sleep(x) (usleep((x)*1000))
  649. #define mg_opendir(conn, x) (opendir(x))
  650. #define mg_closedir(x) (closedir(x))
  651. #define mg_readdir(x) (readdir(x))
  652. #define ERRNO (errno)
  653. #define INVALID_SOCKET (-1)
  654. #define INT64_FMT PRId64
  655. #define UINT64_FMT PRIu64
  656. typedef int SOCKET;
  657. #define WINCDECL
  658. #if defined(__hpux)
  659. /* HPUX 11 does not have monotonic, fall back to realtime */
  660. #if !defined(CLOCK_MONOTONIC)
  661. #define CLOCK_MONOTONIC CLOCK_REALTIME
  662. #endif
  663. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  664. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  665. * the prototypes use int* rather than socklen_t* which matches the
  666. * actual library expectation. When called with the wrong size arg
  667. * accept() returns a zero client inet addr and check_acl() always
  668. * fails. Since socklen_t is widely used below, just force replace
  669. * their typedef with int. - DTL
  670. */
  671. #define socklen_t int
  672. #endif /* hpux */
  673. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  674. /* Maximum queue length for pending connections. This value is passed as
  675. * parameter to the "listen" socket call. */
  676. #if !defined(SOMAXCONN)
  677. /* This symbol may be defined in winsock2.h so this must after that include */
  678. #define SOMAXCONN (100) /* in pending connections (count) */
  679. #endif
  680. /* In case our C library is missing "timegm", provide an implementation */
  681. #if defined(NEED_TIMEGM)
  682. static inline int
  683. is_leap(int y)
  684. {
  685. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  686. }
  687. static inline int
  688. count_leap(int y)
  689. {
  690. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  691. }
  692. time_t
  693. timegm(struct tm *tm)
  694. {
  695. static const unsigned short ydays[] = {
  696. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  697. int year = tm->tm_year + 1900;
  698. int mon = tm->tm_mon;
  699. int mday = tm->tm_mday - 1;
  700. int hour = tm->tm_hour;
  701. int min = tm->tm_min;
  702. int sec = tm->tm_sec;
  703. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  704. || (mday >= ydays[mon + 1] - ydays[mon]
  705. + (mon == 1 && is_leap(year) ? 1 : 0)) || hour < 0
  706. || hour > 23
  707. || min < 0
  708. || min > 59
  709. || sec < 0
  710. || sec > 60)
  711. return -1;
  712. time_t res = year - 1970;
  713. res *= 365;
  714. res += mday;
  715. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  716. res += count_leap(year);
  717. res *= 24;
  718. res += hour;
  719. res *= 60;
  720. res += min;
  721. res *= 60;
  722. res += sec;
  723. return res;
  724. }
  725. #endif /* NEED_TIMEGM */
  726. /* va_copy should always be a macro, C99 and C++11 - DTL */
  727. #if !defined(va_copy)
  728. #define va_copy(x, y) ((x) = (y))
  729. #endif
  730. #if defined(_WIN32)
  731. /* Create substitutes for POSIX functions in Win32. */
  732. #if defined(__MINGW32__)
  733. /* Show no warning in case system functions are not used. */
  734. #pragma GCC diagnostic push
  735. #pragma GCC diagnostic ignored "-Wunused-function"
  736. #endif
  737. static CRITICAL_SECTION global_log_file_lock;
  738. FUNCTION_MAY_BE_UNUSED
  739. static DWORD
  740. pthread_self(void)
  741. {
  742. return GetCurrentThreadId();
  743. }
  744. FUNCTION_MAY_BE_UNUSED
  745. static int
  746. pthread_key_create(
  747. pthread_key_t *key,
  748. void (*_ignored)(void *) /* destructor not supported for Windows */
  749. )
  750. {
  751. (void)_ignored;
  752. if ((key != 0)) {
  753. *key = TlsAlloc();
  754. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  755. }
  756. return -2;
  757. }
  758. FUNCTION_MAY_BE_UNUSED
  759. static int
  760. pthread_key_delete(pthread_key_t key)
  761. {
  762. return TlsFree(key) ? 0 : 1;
  763. }
  764. FUNCTION_MAY_BE_UNUSED
  765. static int
  766. pthread_setspecific(pthread_key_t key, void *value)
  767. {
  768. return TlsSetValue(key, value) ? 0 : 1;
  769. }
  770. FUNCTION_MAY_BE_UNUSED
  771. static void *
  772. pthread_getspecific(pthread_key_t key)
  773. {
  774. return TlsGetValue(key);
  775. }
  776. #if defined(__MINGW32__)
  777. /* Enable unused function warning again */
  778. #pragma GCC diagnostic pop
  779. #endif
  780. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  781. #else
  782. static pthread_mutexattr_t pthread_mutex_attr;
  783. #endif /* _WIN32 */
  784. #if defined(_WIN32_WCE)
  785. /* Create substitutes for POSIX functions in Win32. */
  786. #if defined(__MINGW32__)
  787. /* Show no warning in case system functions are not used. */
  788. #pragma GCC diagnostic push
  789. #pragma GCC diagnostic ignored "-Wunused-function"
  790. #endif
  791. FUNCTION_MAY_BE_UNUSED
  792. static time_t
  793. time(time_t *ptime)
  794. {
  795. time_t t;
  796. SYSTEMTIME st;
  797. FILETIME ft;
  798. GetSystemTime(&st);
  799. SystemTimeToFileTime(&st, &ft);
  800. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  801. if (ptime != NULL) {
  802. *ptime = t;
  803. }
  804. return t;
  805. }
  806. FUNCTION_MAY_BE_UNUSED
  807. static struct tm *
  808. localtime_s(const time_t *ptime, struct tm *ptm)
  809. {
  810. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  811. FILETIME ft, lft;
  812. SYSTEMTIME st;
  813. TIME_ZONE_INFORMATION tzinfo;
  814. if (ptm == NULL) {
  815. return NULL;
  816. }
  817. *(int64_t *)&ft = t;
  818. FileTimeToLocalFileTime(&ft, &lft);
  819. FileTimeToSystemTime(&lft, &st);
  820. ptm->tm_year = st.wYear - 1900;
  821. ptm->tm_mon = st.wMonth - 1;
  822. ptm->tm_wday = st.wDayOfWeek;
  823. ptm->tm_mday = st.wDay;
  824. ptm->tm_hour = st.wHour;
  825. ptm->tm_min = st.wMinute;
  826. ptm->tm_sec = st.wSecond;
  827. ptm->tm_yday = 0; /* hope nobody uses this */
  828. ptm->tm_isdst =
  829. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  830. return ptm;
  831. }
  832. FUNCTION_MAY_BE_UNUSED
  833. static struct tm *
  834. gmtime_s(const time_t *ptime, struct tm *ptm)
  835. {
  836. /* FIXME(lsm): fix this. */
  837. return localtime_s(ptime, ptm);
  838. }
  839. static int mg_atomic_inc(volatile int *addr);
  840. static struct tm tm_array[MAX_WORKER_THREADS];
  841. static int tm_index = 0;
  842. FUNCTION_MAY_BE_UNUSED
  843. static struct tm *
  844. localtime(const time_t *ptime)
  845. {
  846. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  847. return localtime_s(ptime, tm_array + i);
  848. }
  849. FUNCTION_MAY_BE_UNUSED
  850. static struct tm *
  851. gmtime(const time_t *ptime)
  852. {
  853. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  854. return gmtime_s(ptime, tm_array + i);
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static size_t
  858. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  859. {
  860. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  861. * for WinCE"); */
  862. return 0;
  863. }
  864. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  865. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  866. #define remove(f) mg_remove(NULL, f)
  867. FUNCTION_MAY_BE_UNUSED
  868. static int
  869. rename(const char *a, const char *b)
  870. {
  871. wchar_t wa[W_PATH_MAX];
  872. wchar_t wb[W_PATH_MAX];
  873. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  874. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  875. return MoveFileW(wa, wb) ? 0 : -1;
  876. }
  877. struct stat {
  878. int64_t st_size;
  879. time_t st_mtime;
  880. };
  881. FUNCTION_MAY_BE_UNUSED
  882. static int
  883. stat(const char *name, struct stat *st)
  884. {
  885. wchar_t wbuf[W_PATH_MAX];
  886. WIN32_FILE_ATTRIBUTE_DATA attr;
  887. time_t creation_time, write_time;
  888. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  889. memset(&attr, 0, sizeof(attr));
  890. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  891. st->st_size =
  892. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  893. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  894. attr.ftLastWriteTime.dwHighDateTime);
  895. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  896. attr.ftCreationTime.dwHighDateTime);
  897. if (creation_time > write_time) {
  898. st->st_mtime = creation_time;
  899. } else {
  900. st->st_mtime = write_time;
  901. }
  902. return 0;
  903. }
  904. #define access(x, a) 1 /* not required anyway */
  905. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  906. /* Values from errno.h in Windows SDK (Visual Studio). */
  907. #define EEXIST 17
  908. #define EACCES 13
  909. #define ENOENT 2
  910. #if defined(__MINGW32__)
  911. /* Enable unused function warning again */
  912. #pragma GCC diagnostic pop
  913. #endif
  914. #endif /* defined(_WIN32_WCE) */
  915. #if defined(__GNUC__) || defined(__MINGW32__)
  916. /* Show no warning in case system functions are not used. */
  917. #define GCC_VERSION \
  918. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  919. #if GCC_VERSION >= 40500
  920. #pragma GCC diagnostic push
  921. #pragma GCC diagnostic ignored "-Wunused-function"
  922. #endif /* GCC_VERSION >= 40500 */
  923. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  924. #if defined(__clang__)
  925. /* Show no warning in case system functions are not used. */
  926. #pragma clang diagnostic push
  927. #pragma clang diagnostic ignored "-Wunused-function"
  928. #endif
  929. static pthread_mutex_t global_lock_mutex;
  930. #if defined(_WIN32)
  931. /* Forward declaration for Windows */
  932. FUNCTION_MAY_BE_UNUSED
  933. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  934. FUNCTION_MAY_BE_UNUSED
  935. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  936. #endif
  937. FUNCTION_MAY_BE_UNUSED
  938. static void
  939. mg_global_lock(void)
  940. {
  941. (void)pthread_mutex_lock(&global_lock_mutex);
  942. }
  943. FUNCTION_MAY_BE_UNUSED
  944. static void
  945. mg_global_unlock(void)
  946. {
  947. (void)pthread_mutex_unlock(&global_lock_mutex);
  948. }
  949. FUNCTION_MAY_BE_UNUSED
  950. static int
  951. mg_atomic_inc(volatile int *addr)
  952. {
  953. int ret;
  954. #if defined(_WIN32) && !defined(NO_ATOMICS)
  955. /* Depending on the SDK, this function uses either
  956. * (volatile unsigned int *) or (volatile LONG *),
  957. * so whatever you use, the other SDK is likely to raise a warning. */
  958. ret = InterlockedIncrement((volatile long *)addr);
  959. #elif defined(__GNUC__) \
  960. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  961. && !defined(NO_ATOMICS)
  962. ret = __sync_add_and_fetch(addr, 1);
  963. #else
  964. mg_global_lock();
  965. ret = (++(*addr));
  966. mg_global_unlock();
  967. #endif
  968. return ret;
  969. }
  970. FUNCTION_MAY_BE_UNUSED
  971. static int
  972. mg_atomic_dec(volatile int *addr)
  973. {
  974. int ret;
  975. #if defined(_WIN32) && !defined(NO_ATOMICS)
  976. /* Depending on the SDK, this function uses either
  977. * (volatile unsigned int *) or (volatile LONG *),
  978. * so whatever you use, the other SDK is likely to raise a warning. */
  979. ret = InterlockedDecrement((volatile long *)addr);
  980. #elif defined(__GNUC__) \
  981. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  982. && !defined(NO_ATOMICS)
  983. ret = __sync_sub_and_fetch(addr, 1);
  984. #else
  985. mg_global_lock();
  986. ret = (--(*addr));
  987. mg_global_unlock();
  988. #endif
  989. return ret;
  990. }
  991. #if defined(USE_SERVER_STATS)
  992. static int64_t
  993. mg_atomic_add(volatile int64_t *addr, int64_t value)
  994. {
  995. int64_t ret;
  996. #if defined(_WIN64) && !defined(NO_ATOMICS)
  997. ret = InterlockedAdd64(addr, value);
  998. #elif defined(__GNUC__) \
  999. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1000. && !defined(NO_ATOMICS)
  1001. ret = __sync_add_and_fetch(addr, value);
  1002. #else
  1003. mg_global_lock();
  1004. *addr += value;
  1005. ret = (*addr);
  1006. mg_global_unlock();
  1007. #endif
  1008. return ret;
  1009. }
  1010. #endif
  1011. #if defined(__GNUC__)
  1012. /* Show no warning in case system functions are not used. */
  1013. #if GCC_VERSION >= 40500
  1014. #pragma GCC diagnostic pop
  1015. #endif /* GCC_VERSION >= 40500 */
  1016. #endif /* defined(__GNUC__) */
  1017. #if defined(__clang__)
  1018. /* Show no warning in case system functions are not used. */
  1019. #pragma clang diagnostic pop
  1020. #endif
  1021. #if defined(USE_SERVER_STATS)
  1022. struct mg_memory_stat {
  1023. volatile int64_t totalMemUsed;
  1024. volatile int64_t maxMemUsed;
  1025. volatile int blockCount;
  1026. };
  1027. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1028. static void *
  1029. mg_malloc_ex(size_t size,
  1030. struct mg_context *ctx,
  1031. const char *file,
  1032. unsigned line)
  1033. {
  1034. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1035. void *memory = 0;
  1036. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1037. #if defined(MEMORY_DEBUGGING)
  1038. char mallocStr[256];
  1039. #else
  1040. (void)file;
  1041. (void)line;
  1042. #endif
  1043. if (data) {
  1044. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1045. if (mmem > mstat->maxMemUsed) {
  1046. /* could use atomic compare exchange, but this
  1047. * seems overkill for statistics data */
  1048. mstat->maxMemUsed = mmem;
  1049. }
  1050. mg_atomic_inc(&mstat->blockCount);
  1051. ((uintptr_t *)data)[0] = size;
  1052. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1053. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1054. }
  1055. #if defined(MEMORY_DEBUGGING)
  1056. sprintf(mallocStr,
  1057. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1058. memory,
  1059. (unsigned long)size,
  1060. (unsigned long)mstat->totalMemUsed,
  1061. (unsigned long)mstat->blockCount,
  1062. file,
  1063. line);
  1064. #if defined(_WIN32)
  1065. OutputDebugStringA(mallocStr);
  1066. #else
  1067. DEBUG_TRACE("%s", mallocStr);
  1068. #endif
  1069. #endif
  1070. return memory;
  1071. }
  1072. static void *
  1073. mg_calloc_ex(size_t count,
  1074. size_t size,
  1075. struct mg_context *ctx,
  1076. const char *file,
  1077. unsigned line)
  1078. {
  1079. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1080. if (data) {
  1081. memset(data, 0, size * count);
  1082. }
  1083. return data;
  1084. }
  1085. static void
  1086. mg_free_ex(void *memory, const char *file, unsigned line)
  1087. {
  1088. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1089. #if defined(MEMORY_DEBUGGING)
  1090. char mallocStr[256];
  1091. #else
  1092. (void)file;
  1093. (void)line;
  1094. #endif
  1095. if (memory) {
  1096. uintptr_t size = ((uintptr_t *)data)[0];
  1097. struct mg_memory_stat *mstat =
  1098. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1099. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1100. mg_atomic_dec(&mstat->blockCount);
  1101. #if defined(MEMORY_DEBUGGING)
  1102. sprintf(mallocStr,
  1103. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1104. memory,
  1105. (unsigned long)size,
  1106. (unsigned long)mstat->totalMemUsed,
  1107. (unsigned long)mstat->blockCount,
  1108. file,
  1109. line);
  1110. #if defined(_WIN32)
  1111. OutputDebugStringA(mallocStr);
  1112. #else
  1113. DEBUG_TRACE("%s", mallocStr);
  1114. #endif
  1115. #endif
  1116. free(data);
  1117. }
  1118. }
  1119. static void *
  1120. mg_realloc_ex(void *memory,
  1121. size_t newsize,
  1122. struct mg_context *ctx,
  1123. const char *file,
  1124. unsigned line)
  1125. {
  1126. void *data;
  1127. void *_realloc;
  1128. uintptr_t oldsize;
  1129. #if defined(MEMORY_DEBUGGING)
  1130. char mallocStr[256];
  1131. #else
  1132. (void)file;
  1133. (void)line;
  1134. #endif
  1135. if (newsize) {
  1136. if (memory) {
  1137. /* Reallocate existing block */
  1138. struct mg_memory_stat *mstat;
  1139. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1140. oldsize = ((uintptr_t *)data)[0];
  1141. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1142. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1143. if (_realloc) {
  1144. data = _realloc;
  1145. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1146. #if defined(MEMORY_DEBUGGING)
  1147. sprintf(mallocStr,
  1148. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1149. memory,
  1150. (unsigned long)oldsize,
  1151. (unsigned long)mstat->totalMemUsed,
  1152. (unsigned long)mstat->blockCount,
  1153. file,
  1154. line);
  1155. #if defined(_WIN32)
  1156. OutputDebugStringA(mallocStr);
  1157. #else
  1158. DEBUG_TRACE("%s", mallocStr);
  1159. #endif
  1160. #endif
  1161. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1162. #if defined(MEMORY_DEBUGGING)
  1163. sprintf(mallocStr,
  1164. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1165. memory,
  1166. (unsigned long)newsize,
  1167. (unsigned long)mstat->totalMemUsed,
  1168. (unsigned long)mstat->blockCount,
  1169. file,
  1170. line);
  1171. #if defined(_WIN32)
  1172. OutputDebugStringA(mallocStr);
  1173. #else
  1174. DEBUG_TRACE("%s", mallocStr);
  1175. #endif
  1176. #endif
  1177. *(uintptr_t *)data = newsize;
  1178. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1179. } else {
  1180. #if defined(MEMORY_DEBUGGING)
  1181. #if defined(_WIN32)
  1182. OutputDebugStringA("MEM: realloc failed\n");
  1183. #else
  1184. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1185. #endif
  1186. #endif
  1187. return _realloc;
  1188. }
  1189. } else {
  1190. /* Allocate new block */
  1191. data = mg_malloc_ex(newsize, ctx, file, line);
  1192. }
  1193. } else {
  1194. /* Free existing block */
  1195. data = 0;
  1196. mg_free_ex(memory, file, line);
  1197. }
  1198. return data;
  1199. }
  1200. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1201. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1202. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1203. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1204. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1205. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1206. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1207. #else /* USE_SERVER_STATS */
  1208. static __inline void *
  1209. mg_malloc(size_t a)
  1210. {
  1211. return malloc(a);
  1212. }
  1213. static __inline void *
  1214. mg_calloc(size_t a, size_t b)
  1215. {
  1216. return calloc(a, b);
  1217. }
  1218. static __inline void *
  1219. mg_realloc(void *a, size_t b)
  1220. {
  1221. return realloc(a, b);
  1222. }
  1223. static __inline void
  1224. mg_free(void *a)
  1225. {
  1226. free(a);
  1227. }
  1228. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1229. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1230. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1231. #define mg_free_ctx(a, c) mg_free(a)
  1232. #endif /* USE_SERVER_STATS */
  1233. static void mg_vsnprintf(const struct mg_connection *conn,
  1234. int *truncated,
  1235. char *buf,
  1236. size_t buflen,
  1237. const char *fmt,
  1238. va_list ap);
  1239. static void mg_snprintf(const struct mg_connection *conn,
  1240. int *truncated,
  1241. char *buf,
  1242. size_t buflen,
  1243. PRINTF_FORMAT_STRING(const char *fmt),
  1244. ...) PRINTF_ARGS(5, 6);
  1245. /* This following lines are just meant as a reminder to use the mg-functions
  1246. * for memory management */
  1247. #if defined(malloc)
  1248. #undef malloc
  1249. #endif
  1250. #if defined(calloc)
  1251. #undef calloc
  1252. #endif
  1253. #if defined(realloc)
  1254. #undef realloc
  1255. #endif
  1256. #if defined(free)
  1257. #undef free
  1258. #endif
  1259. #if defined(snprintf)
  1260. #undef snprintf
  1261. #endif
  1262. #if defined(vsnprintf)
  1263. #undef vsnprintf
  1264. #endif
  1265. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1266. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1267. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1268. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1269. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1270. #if defined(_WIN32)
  1271. /* vsnprintf must not be used in any system,
  1272. * but this define only works well for Windows. */
  1273. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1274. #endif
  1275. /* mg_init_library counter */
  1276. static int mg_init_library_called = 0;
  1277. #if !defined(NO_SSL)
  1278. static int mg_ssl_initialized = 0;
  1279. #endif
  1280. static pthread_key_t sTlsKey; /* Thread local storage index */
  1281. static int thread_idx_max = 0;
  1282. #if defined(MG_LEGACY_INTERFACE)
  1283. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1284. #endif
  1285. struct mg_workerTLS {
  1286. int is_master;
  1287. unsigned long thread_idx;
  1288. #if defined(_WIN32)
  1289. HANDLE pthread_cond_helper_mutex;
  1290. struct mg_workerTLS *next_waiting_thread;
  1291. #endif
  1292. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1293. char txtbuf[4];
  1294. #endif
  1295. };
  1296. #if defined(__GNUC__) || defined(__MINGW32__)
  1297. /* Show no warning in case system functions are not used. */
  1298. #if GCC_VERSION >= 40500
  1299. #pragma GCC diagnostic push
  1300. #pragma GCC diagnostic ignored "-Wunused-function"
  1301. #endif /* GCC_VERSION >= 40500 */
  1302. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1303. #if defined(__clang__)
  1304. /* Show no warning in case system functions are not used. */
  1305. #pragma clang diagnostic push
  1306. #pragma clang diagnostic ignored "-Wunused-function"
  1307. #endif
  1308. /* Get a unique thread ID as unsigned long, independent from the data type
  1309. * of thread IDs defined by the operating system API.
  1310. * If two calls to mg_current_thread_id return the same value, they calls
  1311. * are done from the same thread. If they return different values, they are
  1312. * done from different threads. (Provided this function is used in the same
  1313. * process context and threads are not repeatedly created and deleted, but
  1314. * CivetWeb does not do that).
  1315. * This function must match the signature required for SSL id callbacks:
  1316. * CRYPTO_set_id_callback
  1317. */
  1318. FUNCTION_MAY_BE_UNUSED
  1319. static unsigned long
  1320. mg_current_thread_id(void)
  1321. {
  1322. #if defined(_WIN32)
  1323. return GetCurrentThreadId();
  1324. #else
  1325. #if defined(__clang__)
  1326. #pragma clang diagnostic push
  1327. #pragma clang diagnostic ignored "-Wunreachable-code"
  1328. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1329. * or not, so one of the two conditions will be unreachable by construction.
  1330. * Unfortunately the C standard does not define a way to check this at
  1331. * compile time, since the #if preprocessor conditions can not use the sizeof
  1332. * operator as an argument. */
  1333. #endif
  1334. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1335. /* This is the problematic case for CRYPTO_set_id_callback:
  1336. * The OS pthread_t can not be cast to unsigned long. */
  1337. struct mg_workerTLS *tls =
  1338. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1339. if (tls == NULL) {
  1340. /* SSL called from an unknown thread: Create some thread index.
  1341. */
  1342. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1343. tls->is_master = -2; /* -2 means "3rd party thread" */
  1344. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1345. pthread_setspecific(sTlsKey, tls);
  1346. }
  1347. return tls->thread_idx;
  1348. } else {
  1349. /* pthread_t may be any data type, so a simple cast to unsigned long
  1350. * can rise a warning/error, depending on the platform.
  1351. * Here memcpy is used as an anything-to-anything cast. */
  1352. unsigned long ret = 0;
  1353. pthread_t t = pthread_self();
  1354. memcpy(&ret, &t, sizeof(pthread_t));
  1355. return ret;
  1356. }
  1357. #if defined(__clang__)
  1358. #pragma clang diagnostic pop
  1359. #endif
  1360. #endif
  1361. }
  1362. FUNCTION_MAY_BE_UNUSED
  1363. static uint64_t
  1364. mg_get_current_time_ns(void)
  1365. {
  1366. struct timespec tsnow;
  1367. clock_gettime(CLOCK_REALTIME, &tsnow);
  1368. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1369. }
  1370. #if defined(__GNUC__)
  1371. /* Show no warning in case system functions are not used. */
  1372. #if GCC_VERSION >= 40500
  1373. #pragma GCC diagnostic pop
  1374. #endif /* GCC_VERSION >= 40500 */
  1375. #endif /* defined(__GNUC__) */
  1376. #if defined(__clang__)
  1377. /* Show no warning in case system functions are not used. */
  1378. #pragma clang diagnostic pop
  1379. #endif
  1380. #if defined(NEED_DEBUG_TRACE_FUNC)
  1381. static void
  1382. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1383. {
  1384. va_list args;
  1385. uint64_t nsnow;
  1386. static uint64_t nslast;
  1387. struct timespec tsnow;
  1388. /* Get some operating system independent thread id */
  1389. unsigned long thread_id = mg_current_thread_id();
  1390. clock_gettime(CLOCK_REALTIME, &tsnow);
  1391. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1392. + ((uint64_t)tsnow.tv_nsec);
  1393. if (!nslast) {
  1394. nslast = nsnow;
  1395. }
  1396. flockfile(stdout);
  1397. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1398. (unsigned long)tsnow.tv_sec,
  1399. (unsigned long)tsnow.tv_nsec,
  1400. nsnow - nslast,
  1401. thread_id,
  1402. func,
  1403. line);
  1404. va_start(args, fmt);
  1405. vprintf(fmt, args);
  1406. va_end(args);
  1407. putchar('\n');
  1408. fflush(stdout);
  1409. funlockfile(stdout);
  1410. nslast = nsnow;
  1411. }
  1412. #endif /* NEED_DEBUG_TRACE_FUNC */
  1413. #define MD5_STATIC static
  1414. #include "md5.inl"
  1415. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1416. #if defined(NO_SOCKLEN_T)
  1417. typedef int socklen_t;
  1418. #endif /* NO_SOCKLEN_T */
  1419. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1420. #if !defined(MSG_NOSIGNAL)
  1421. #define MSG_NOSIGNAL (0)
  1422. #endif
  1423. #if defined(NO_SSL)
  1424. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1425. typedef struct SSL_CTX SSL_CTX;
  1426. #else
  1427. #if defined(NO_SSL_DL)
  1428. #include <openssl/ssl.h>
  1429. #include <openssl/err.h>
  1430. #include <openssl/crypto.h>
  1431. #include <openssl/x509.h>
  1432. #include <openssl/pem.h>
  1433. #include <openssl/engine.h>
  1434. #include <openssl/conf.h>
  1435. #include <openssl/dh.h>
  1436. #include <openssl/bn.h>
  1437. #include <openssl/opensslv.h>
  1438. #if defined(WOLFSSL_VERSION)
  1439. /* Additional defines for WolfSSL, see
  1440. * https://github.com/civetweb/civetweb/issues/583 */
  1441. #include "wolfssl_extras.inl"
  1442. #endif
  1443. #else
  1444. /* SSL loaded dynamically from DLL.
  1445. * I put the prototypes here to be independent from OpenSSL source
  1446. * installation. */
  1447. typedef struct ssl_st SSL;
  1448. typedef struct ssl_method_st SSL_METHOD;
  1449. typedef struct ssl_ctx_st SSL_CTX;
  1450. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1451. typedef struct x509_name X509_NAME;
  1452. typedef struct asn1_integer ASN1_INTEGER;
  1453. typedef struct bignum BIGNUM;
  1454. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1455. typedef struct evp_md EVP_MD;
  1456. typedef struct x509 X509;
  1457. #define SSL_CTRL_OPTIONS (32)
  1458. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1459. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1460. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1461. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1462. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1463. #define SSL_VERIFY_NONE (0)
  1464. #define SSL_VERIFY_PEER (1)
  1465. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1466. #define SSL_VERIFY_CLIENT_ONCE (4)
  1467. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1468. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1469. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1470. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1471. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1472. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1473. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1474. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1475. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1476. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1477. #define SSL_CB_HANDSHAKE_START (0x10)
  1478. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1479. #define SSL_ERROR_NONE (0)
  1480. #define SSL_ERROR_SSL (1)
  1481. #define SSL_ERROR_WANT_READ (2)
  1482. #define SSL_ERROR_WANT_WRITE (3)
  1483. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1484. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1485. #define SSL_ERROR_ZERO_RETURN (6)
  1486. #define SSL_ERROR_WANT_CONNECT (7)
  1487. #define SSL_ERROR_WANT_ACCEPT (8)
  1488. #define TLSEXT_TYPE_server_name (0)
  1489. #define TLSEXT_NAMETYPE_host_name (0)
  1490. #define SSL_TLSEXT_ERR_OK (0)
  1491. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1492. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1493. #define SSL_TLSEXT_ERR_NOACK (3)
  1494. struct ssl_func {
  1495. const char *name; /* SSL function name */
  1496. void (*ptr)(void); /* Function pointer */
  1497. };
  1498. #if defined(OPENSSL_API_1_1)
  1499. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1500. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1501. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1502. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1503. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1504. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1505. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1506. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1507. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1508. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1509. #define OPENSSL_init_ssl \
  1510. (*(int (*)(uint64_t opts, \
  1511. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1512. #define SSL_CTX_use_PrivateKey_file \
  1513. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1514. #define SSL_CTX_use_certificate_file \
  1515. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1516. #define SSL_CTX_set_default_passwd_cb \
  1517. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1518. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1519. #define SSL_CTX_use_certificate_chain_file \
  1520. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1521. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1522. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1523. #define SSL_CTX_set_verify \
  1524. (*(void (*)(SSL_CTX *, \
  1525. int, \
  1526. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1527. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1528. #define SSL_CTX_load_verify_locations \
  1529. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1530. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1531. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1532. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1533. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1534. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1535. #define SSL_CIPHER_get_name \
  1536. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1537. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1538. #define SSL_CTX_set_session_id_context \
  1539. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1540. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1541. #define SSL_CTX_set_cipher_list \
  1542. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1543. #define SSL_CTX_set_options \
  1544. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1545. #define SSL_CTX_set_info_callback \
  1546. (*(void (*)(SSL_CTX * ctx, \
  1547. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1548. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1549. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1550. #define SSL_CTX_callback_ctrl \
  1551. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1552. #define SSL_get_servername \
  1553. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1554. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1555. #define SSL_CTX_clear_options(ctx, op) \
  1556. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1557. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1558. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1559. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1560. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1561. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1562. SSL_CTX_callback_ctrl(ctx, \
  1563. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1564. (void (*)(void))cb)
  1565. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1566. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1567. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1568. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1569. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1570. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1571. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1572. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1573. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1574. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1575. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1576. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1577. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1578. #define X509_NAME_oneline \
  1579. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1580. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1581. #define EVP_get_digestbyname \
  1582. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1583. #define EVP_Digest \
  1584. (*(int (*)( \
  1585. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1586. crypto_sw[10].ptr)
  1587. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1588. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1589. #define ASN1_INTEGER_to_BN \
  1590. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1591. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1592. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1593. #define OPENSSL_free(a) CRYPTO_free(a)
  1594. /* init_ssl_ctx() function updates this array.
  1595. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1596. * of respective functions. The macros above (like SSL_connect()) are really
  1597. * just calling these functions indirectly via the pointer. */
  1598. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1599. {"SSL_accept", NULL},
  1600. {"SSL_connect", NULL},
  1601. {"SSL_read", NULL},
  1602. {"SSL_write", NULL},
  1603. {"SSL_get_error", NULL},
  1604. {"SSL_set_fd", NULL},
  1605. {"SSL_new", NULL},
  1606. {"SSL_CTX_new", NULL},
  1607. {"TLS_server_method", NULL},
  1608. {"OPENSSL_init_ssl", NULL},
  1609. {"SSL_CTX_use_PrivateKey_file", NULL},
  1610. {"SSL_CTX_use_certificate_file", NULL},
  1611. {"SSL_CTX_set_default_passwd_cb", NULL},
  1612. {"SSL_CTX_free", NULL},
  1613. {"SSL_CTX_use_certificate_chain_file", NULL},
  1614. {"TLS_client_method", NULL},
  1615. {"SSL_pending", NULL},
  1616. {"SSL_CTX_set_verify", NULL},
  1617. {"SSL_shutdown", NULL},
  1618. {"SSL_CTX_load_verify_locations", NULL},
  1619. {"SSL_CTX_set_default_verify_paths", NULL},
  1620. {"SSL_CTX_set_verify_depth", NULL},
  1621. {"SSL_get_peer_certificate", NULL},
  1622. {"SSL_get_version", NULL},
  1623. {"SSL_get_current_cipher", NULL},
  1624. {"SSL_CIPHER_get_name", NULL},
  1625. {"SSL_CTX_check_private_key", NULL},
  1626. {"SSL_CTX_set_session_id_context", NULL},
  1627. {"SSL_CTX_ctrl", NULL},
  1628. {"SSL_CTX_set_cipher_list", NULL},
  1629. {"SSL_CTX_set_options", NULL},
  1630. {"SSL_CTX_set_info_callback", NULL},
  1631. {"SSL_get_ex_data", NULL},
  1632. {"SSL_set_ex_data", NULL},
  1633. {"SSL_CTX_callback_ctrl", NULL},
  1634. {"SSL_get_servername", NULL},
  1635. {"SSL_set_SSL_CTX", NULL},
  1636. {NULL, NULL}};
  1637. /* Similar array as ssl_sw. These functions could be located in different
  1638. * lib. */
  1639. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1640. {"ERR_error_string", NULL},
  1641. {"ERR_remove_state", NULL},
  1642. {"CONF_modules_unload", NULL},
  1643. {"X509_free", NULL},
  1644. {"X509_get_subject_name", NULL},
  1645. {"X509_get_issuer_name", NULL},
  1646. {"X509_NAME_oneline", NULL},
  1647. {"X509_get_serialNumber", NULL},
  1648. {"EVP_get_digestbyname", NULL},
  1649. {"EVP_Digest", NULL},
  1650. {"i2d_X509", NULL},
  1651. {"BN_bn2hex", NULL},
  1652. {"ASN1_INTEGER_to_BN", NULL},
  1653. {"BN_free", NULL},
  1654. {"CRYPTO_free", NULL},
  1655. {NULL, NULL}};
  1656. #else
  1657. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1658. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1659. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1660. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1661. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1662. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1663. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1664. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1665. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1666. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1667. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1668. #define SSL_CTX_use_PrivateKey_file \
  1669. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1670. #define SSL_CTX_use_certificate_file \
  1671. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1672. #define SSL_CTX_set_default_passwd_cb \
  1673. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1674. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1675. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1676. #define SSL_CTX_use_certificate_chain_file \
  1677. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1678. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1679. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1680. #define SSL_CTX_set_verify \
  1681. (*(void (*)(SSL_CTX *, \
  1682. int, \
  1683. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1684. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1685. #define SSL_CTX_load_verify_locations \
  1686. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1687. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1688. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1689. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1690. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1691. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1692. #define SSL_CIPHER_get_name \
  1693. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1694. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1695. #define SSL_CTX_set_session_id_context \
  1696. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1697. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1698. #define SSL_CTX_set_cipher_list \
  1699. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1700. #define SSL_CTX_set_info_callback \
  1701. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1702. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1703. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1704. #define SSL_CTX_callback_ctrl \
  1705. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1706. #define SSL_get_servername \
  1707. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1708. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1709. #define SSL_CTX_set_options(ctx, op) \
  1710. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1711. #define SSL_CTX_clear_options(ctx, op) \
  1712. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1713. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1714. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1715. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1716. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1717. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1718. SSL_CTX_callback_ctrl(ctx, \
  1719. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1720. (void (*)(void))cb)
  1721. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1722. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1723. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1724. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1725. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1726. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1727. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1728. #define CRYPTO_set_locking_callback \
  1729. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1730. #define CRYPTO_set_id_callback \
  1731. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1732. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1733. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1734. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1735. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1736. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1737. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1738. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1739. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1740. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1741. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1742. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1743. #define X509_NAME_oneline \
  1744. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1745. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1746. #define i2c_ASN1_INTEGER \
  1747. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1748. #define EVP_get_digestbyname \
  1749. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1750. #define EVP_Digest \
  1751. (*(int (*)( \
  1752. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1753. crypto_sw[18].ptr)
  1754. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1755. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1756. #define ASN1_INTEGER_to_BN \
  1757. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1758. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1759. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1760. #define OPENSSL_free(a) CRYPTO_free(a)
  1761. /* init_ssl_ctx() function updates this array.
  1762. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1763. * of respective functions. The macros above (like SSL_connect()) are really
  1764. * just calling these functions indirectly via the pointer. */
  1765. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1766. {"SSL_accept", NULL},
  1767. {"SSL_connect", NULL},
  1768. {"SSL_read", NULL},
  1769. {"SSL_write", NULL},
  1770. {"SSL_get_error", NULL},
  1771. {"SSL_set_fd", NULL},
  1772. {"SSL_new", NULL},
  1773. {"SSL_CTX_new", NULL},
  1774. {"SSLv23_server_method", NULL},
  1775. {"SSL_library_init", NULL},
  1776. {"SSL_CTX_use_PrivateKey_file", NULL},
  1777. {"SSL_CTX_use_certificate_file", NULL},
  1778. {"SSL_CTX_set_default_passwd_cb", NULL},
  1779. {"SSL_CTX_free", NULL},
  1780. {"SSL_load_error_strings", NULL},
  1781. {"SSL_CTX_use_certificate_chain_file", NULL},
  1782. {"SSLv23_client_method", NULL},
  1783. {"SSL_pending", NULL},
  1784. {"SSL_CTX_set_verify", NULL},
  1785. {"SSL_shutdown", NULL},
  1786. {"SSL_CTX_load_verify_locations", NULL},
  1787. {"SSL_CTX_set_default_verify_paths", NULL},
  1788. {"SSL_CTX_set_verify_depth", NULL},
  1789. {"SSL_get_peer_certificate", NULL},
  1790. {"SSL_get_version", NULL},
  1791. {"SSL_get_current_cipher", NULL},
  1792. {"SSL_CIPHER_get_name", NULL},
  1793. {"SSL_CTX_check_private_key", NULL},
  1794. {"SSL_CTX_set_session_id_context", NULL},
  1795. {"SSL_CTX_ctrl", NULL},
  1796. {"SSL_CTX_set_cipher_list", NULL},
  1797. {"SSL_CTX_set_info_callback", NULL},
  1798. {"SSL_get_ex_data", NULL},
  1799. {"SSL_set_ex_data", NULL},
  1800. {"SSL_CTX_callback_ctrl", NULL},
  1801. {"SSL_get_servername", NULL},
  1802. {"SSL_set_SSL_CTX", NULL},
  1803. {NULL, NULL}};
  1804. /* Similar array as ssl_sw. These functions could be located in different
  1805. * lib. */
  1806. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1807. {"CRYPTO_set_locking_callback", NULL},
  1808. {"CRYPTO_set_id_callback", NULL},
  1809. {"ERR_get_error", NULL},
  1810. {"ERR_error_string", NULL},
  1811. {"ERR_remove_state", NULL},
  1812. {"ERR_free_strings", NULL},
  1813. {"ENGINE_cleanup", NULL},
  1814. {"CONF_modules_unload", NULL},
  1815. {"CRYPTO_cleanup_all_ex_data", NULL},
  1816. {"EVP_cleanup", NULL},
  1817. {"X509_free", NULL},
  1818. {"X509_get_subject_name", NULL},
  1819. {"X509_get_issuer_name", NULL},
  1820. {"X509_NAME_oneline", NULL},
  1821. {"X509_get_serialNumber", NULL},
  1822. {"i2c_ASN1_INTEGER", NULL},
  1823. {"EVP_get_digestbyname", NULL},
  1824. {"EVP_Digest", NULL},
  1825. {"i2d_X509", NULL},
  1826. {"BN_bn2hex", NULL},
  1827. {"ASN1_INTEGER_to_BN", NULL},
  1828. {"BN_free", NULL},
  1829. {"CRYPTO_free", NULL},
  1830. {NULL, NULL}};
  1831. #endif /* OPENSSL_API_1_1 */
  1832. #endif /* NO_SSL_DL */
  1833. #endif /* NO_SSL */
  1834. #if !defined(NO_CACHING)
  1835. static const char *month_names[] = {"Jan",
  1836. "Feb",
  1837. "Mar",
  1838. "Apr",
  1839. "May",
  1840. "Jun",
  1841. "Jul",
  1842. "Aug",
  1843. "Sep",
  1844. "Oct",
  1845. "Nov",
  1846. "Dec"};
  1847. #endif /* !NO_CACHING */
  1848. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1849. * the
  1850. * union u. */
  1851. union usa {
  1852. struct sockaddr sa;
  1853. struct sockaddr_in sin;
  1854. #if defined(USE_IPV6)
  1855. struct sockaddr_in6 sin6;
  1856. #endif
  1857. };
  1858. /* Describes a string (chunk of memory). */
  1859. struct vec {
  1860. const char *ptr;
  1861. size_t len;
  1862. };
  1863. struct mg_file_stat {
  1864. /* File properties filled by mg_stat: */
  1865. uint64_t size;
  1866. time_t last_modified;
  1867. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1868. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1869. * case we need a "Content-Eencoding: gzip" header */
  1870. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1871. };
  1872. struct mg_file_in_memory {
  1873. char *p;
  1874. uint32_t pos;
  1875. char mode;
  1876. };
  1877. struct mg_file_access {
  1878. /* File properties filled by mg_fopen: */
  1879. FILE *fp;
  1880. #if defined(MG_USE_OPEN_FILE)
  1881. /* TODO (low): Remove obsolete "file in memory" implementation.
  1882. * In an "early 2017" discussion at Google groups
  1883. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1884. * we decided to get rid of this feature (after some fade-out
  1885. * phase). */
  1886. const char *membuf;
  1887. #endif
  1888. };
  1889. struct mg_file {
  1890. struct mg_file_stat stat;
  1891. struct mg_file_access access;
  1892. };
  1893. #if defined(MG_USE_OPEN_FILE)
  1894. #define STRUCT_FILE_INITIALIZER \
  1895. { \
  1896. { \
  1897. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1898. } \
  1899. , \
  1900. { \
  1901. (FILE *) NULL, (const char *)NULL \
  1902. } \
  1903. }
  1904. #else
  1905. #define STRUCT_FILE_INITIALIZER \
  1906. { \
  1907. { \
  1908. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1909. } \
  1910. , \
  1911. { \
  1912. (FILE *) NULL \
  1913. } \
  1914. }
  1915. #endif
  1916. /* Describes listening socket, or socket which was accept()-ed by the master
  1917. * thread and queued for future handling by the worker thread. */
  1918. struct socket {
  1919. SOCKET sock; /* Listening socket */
  1920. union usa lsa; /* Local socket address */
  1921. union usa rsa; /* Remote socket address */
  1922. unsigned char is_ssl; /* Is port SSL-ed */
  1923. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1924. * port */
  1925. unsigned char in_use; /* Is valid */
  1926. };
  1927. /* Enum const for all options must be in sync with
  1928. * static struct mg_option config_options[]
  1929. * This is tested in the unit test (test/private.c)
  1930. * "Private Config Options"
  1931. */
  1932. enum {
  1933. LISTENING_PORTS,
  1934. NUM_THREADS,
  1935. RUN_AS_USER,
  1936. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1937. * socket option typedef TCP_NODELAY. */
  1938. MAX_REQUEST_SIZE,
  1939. LINGER_TIMEOUT,
  1940. #if defined(__linux__)
  1941. ALLOW_SENDFILE_CALL,
  1942. #endif
  1943. #if defined(_WIN32)
  1944. CASE_SENSITIVE_FILES,
  1945. #endif
  1946. THROTTLE,
  1947. ACCESS_LOG_FILE,
  1948. ERROR_LOG_FILE,
  1949. ENABLE_KEEP_ALIVE,
  1950. REQUEST_TIMEOUT,
  1951. KEEP_ALIVE_TIMEOUT,
  1952. #if defined(USE_WEBSOCKET)
  1953. WEBSOCKET_TIMEOUT,
  1954. ENABLE_WEBSOCKET_PING_PONG,
  1955. #endif
  1956. DECODE_URL,
  1957. #if defined(USE_LUA)
  1958. LUA_BACKGROUND_SCRIPT,
  1959. LUA_BACKGROUND_SCRIPT_PARAMS,
  1960. #endif
  1961. DOCUMENT_ROOT,
  1962. CGI_EXTENSIONS,
  1963. CGI_ENVIRONMENT,
  1964. PUT_DELETE_PASSWORDS_FILE,
  1965. CGI_INTERPRETER,
  1966. PROTECT_URI,
  1967. AUTHENTICATION_DOMAIN,
  1968. ENABLE_AUTH_DOMAIN_CHECK,
  1969. SSI_EXTENSIONS,
  1970. ENABLE_DIRECTORY_LISTING,
  1971. GLOBAL_PASSWORDS_FILE,
  1972. INDEX_FILES,
  1973. ACCESS_CONTROL_LIST,
  1974. EXTRA_MIME_TYPES,
  1975. SSL_CERTIFICATE,
  1976. SSL_CERTIFICATE_CHAIN,
  1977. URL_REWRITE_PATTERN,
  1978. HIDE_FILES,
  1979. SSL_DO_VERIFY_PEER,
  1980. SSL_CA_PATH,
  1981. SSL_CA_FILE,
  1982. SSL_VERIFY_DEPTH,
  1983. SSL_DEFAULT_VERIFY_PATHS,
  1984. SSL_CIPHER_LIST,
  1985. SSL_PROTOCOL_VERSION,
  1986. SSL_SHORT_TRUST,
  1987. #if defined(USE_LUA)
  1988. LUA_PRELOAD_FILE,
  1989. LUA_SCRIPT_EXTENSIONS,
  1990. LUA_SERVER_PAGE_EXTENSIONS,
  1991. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1992. LUA_DEBUG_PARAMS,
  1993. #endif
  1994. #endif
  1995. #if defined(USE_DUKTAPE)
  1996. DUKTAPE_SCRIPT_EXTENSIONS,
  1997. #endif
  1998. #if defined(USE_WEBSOCKET)
  1999. WEBSOCKET_ROOT,
  2000. #endif
  2001. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2002. LUA_WEBSOCKET_EXTENSIONS,
  2003. #endif
  2004. ACCESS_CONTROL_ALLOW_ORIGIN,
  2005. ACCESS_CONTROL_ALLOW_METHODS,
  2006. ACCESS_CONTROL_ALLOW_HEADERS,
  2007. ERROR_PAGES,
  2008. #if !defined(NO_CACHING)
  2009. STATIC_FILE_MAX_AGE,
  2010. #endif
  2011. #if !defined(NO_SSL)
  2012. STRICT_HTTPS_MAX_AGE,
  2013. #endif
  2014. ADDITIONAL_HEADER,
  2015. ALLOW_INDEX_SCRIPT_SUB_RES,
  2016. NUM_OPTIONS
  2017. };
  2018. /* Config option name, config types, default value.
  2019. * Must be in the same order as the enum const above.
  2020. */
  2021. static const struct mg_option config_options[] = {
  2022. /* Once for each server */
  2023. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2024. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2025. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2026. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2027. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2028. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2029. #if defined(__linux__)
  2030. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2031. #endif
  2032. #if defined(_WIN32)
  2033. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2034. #endif
  2035. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2036. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2037. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2038. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2039. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2040. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2041. #if defined(USE_WEBSOCKET)
  2042. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2043. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2044. #endif
  2045. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2046. #if defined(USE_LUA)
  2047. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2048. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2049. #endif
  2050. /* Once for each domain */
  2051. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2052. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2053. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2054. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2055. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2056. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2057. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2058. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2059. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2060. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2061. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2062. {"index_files",
  2063. MG_CONFIG_TYPE_STRING_LIST,
  2064. #if defined(USE_LUA)
  2065. "index.xhtml,index.html,index.htm,"
  2066. "index.lp,index.lsp,index.lua,index.cgi,"
  2067. "index.shtml,index.php"},
  2068. #else
  2069. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2070. #endif
  2071. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2072. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2073. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2074. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2075. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2076. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2077. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2078. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2079. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2080. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2081. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2082. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2083. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2084. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2085. #if defined(USE_LUA)
  2086. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2087. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2088. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2089. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2090. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2091. #endif
  2092. #endif
  2093. #if defined(USE_DUKTAPE)
  2094. /* The support for duktape is still in alpha version state.
  2095. * The name of this config option might change. */
  2096. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2097. #endif
  2098. #if defined(USE_WEBSOCKET)
  2099. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2100. #endif
  2101. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2102. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2103. #endif
  2104. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2105. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2106. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2107. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2108. #if !defined(NO_CACHING)
  2109. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2110. #endif
  2111. #if !defined(NO_SSL)
  2112. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2113. #endif
  2114. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2115. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2116. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2117. /* Check if the config_options and the corresponding enum have compatible
  2118. * sizes. */
  2119. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2120. == (NUM_OPTIONS + 1),
  2121. "config_options and enum not sync");
  2122. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2123. struct mg_handler_info {
  2124. /* Name/Pattern of the URI. */
  2125. char *uri;
  2126. size_t uri_len;
  2127. /* handler type */
  2128. int handler_type;
  2129. /* Handler for http/https or authorization requests. */
  2130. mg_request_handler handler;
  2131. unsigned int refcount;
  2132. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2133. pthread_cond_t
  2134. refcount_cond; /* Signaled when handler refcount is decremented */
  2135. /* Handler for ws/wss (websocket) requests. */
  2136. mg_websocket_connect_handler connect_handler;
  2137. mg_websocket_ready_handler ready_handler;
  2138. mg_websocket_data_handler data_handler;
  2139. mg_websocket_close_handler close_handler;
  2140. /* accepted subprotocols for ws/wss requests. */
  2141. struct mg_websocket_subprotocols *subprotocols;
  2142. /* Handler for authorization requests */
  2143. mg_authorization_handler auth_handler;
  2144. /* User supplied argument for the handler function. */
  2145. void *cbdata;
  2146. /* next handler in a linked list */
  2147. struct mg_handler_info *next;
  2148. };
  2149. enum {
  2150. CONTEXT_INVALID,
  2151. CONTEXT_SERVER,
  2152. CONTEXT_HTTP_CLIENT,
  2153. CONTEXT_WS_CLIENT
  2154. };
  2155. struct mg_domain_context {
  2156. SSL_CTX *ssl_ctx; /* SSL context */
  2157. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2158. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2159. /* Server nonce */
  2160. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2161. unsigned long nonce_count; /* Used nonces, used for authentication */
  2162. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2163. /* linked list of shared lua websockets */
  2164. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2165. #endif
  2166. /* Linked list of domains */
  2167. struct mg_domain_context *next;
  2168. };
  2169. struct mg_context {
  2170. /* Part 1 - Physical context:
  2171. * This holds threads, ports, timeouts, ...
  2172. * set for the entire server, independent from the
  2173. * addressed hostname.
  2174. */
  2175. /* Connection related */
  2176. int context_type; /* See CONTEXT_* above */
  2177. struct socket *listening_sockets;
  2178. struct pollfd *listening_socket_fds;
  2179. unsigned int num_listening_sockets;
  2180. struct mg_connection *worker_connections; /* The connection struct, pre-
  2181. * allocated for each worker */
  2182. #if defined(USE_SERVER_STATS)
  2183. int active_connections;
  2184. int max_connections;
  2185. int64_t total_connections;
  2186. int64_t total_requests;
  2187. int64_t total_data_read;
  2188. int64_t total_data_written;
  2189. #endif
  2190. /* Thread related */
  2191. volatile int stop_flag; /* Should we stop event loop */
  2192. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2193. pthread_t masterthreadid; /* The master thread ID */
  2194. unsigned int
  2195. cfg_worker_threads; /* The number of configured worker threads. */
  2196. pthread_t *worker_threadids; /* The worker thread IDs */
  2197. /* Connection to thread dispatching */
  2198. #if defined(ALTERNATIVE_QUEUE)
  2199. struct socket *client_socks;
  2200. void **client_wait_events;
  2201. #else
  2202. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2203. volatile int sq_head; /* Head of the socket queue */
  2204. volatile int sq_tail; /* Tail of the socket queue */
  2205. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2206. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2207. #endif
  2208. /* Memory related */
  2209. unsigned int max_request_size; /* The max request size */
  2210. #if defined(USE_SERVER_STATS)
  2211. struct mg_memory_stat ctx_memory;
  2212. #endif
  2213. /* Operating system related */
  2214. char *systemName; /* What operating system is running */
  2215. time_t start_time; /* Server start time, used for authentication
  2216. * and for diagnstics. */
  2217. #if defined(USE_TIMERS)
  2218. struct ttimers *timers;
  2219. #endif
  2220. /* Lua specific: Background operations and shared websockets */
  2221. #if defined(USE_LUA)
  2222. void *lua_background_state;
  2223. #endif
  2224. /* Server nonce */
  2225. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2226. /* Server callbacks */
  2227. struct mg_callbacks callbacks; /* User-defined callback function */
  2228. void *user_data; /* User-defined data */
  2229. /* Part 2 - Logical domain:
  2230. * This holds hostname, TLS certificate, document root, ...
  2231. * set for a domain hosted at the server.
  2232. * There may be multiple domains hosted at one physical server.
  2233. * The default domain "dd" is the first element of a list of
  2234. * domains.
  2235. */
  2236. struct mg_domain_context dd; /* default domain */
  2237. };
  2238. #if defined(USE_SERVER_STATS)
  2239. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2240. static struct mg_memory_stat *
  2241. get_memory_stat(struct mg_context *ctx)
  2242. {
  2243. if (ctx) {
  2244. return &(ctx->ctx_memory);
  2245. }
  2246. return &mg_common_memory;
  2247. }
  2248. #endif
  2249. enum {
  2250. CONNECTION_TYPE_INVALID,
  2251. CONNECTION_TYPE_REQUEST,
  2252. CONNECTION_TYPE_RESPONSE
  2253. };
  2254. struct mg_connection {
  2255. int connection_type; /* see CONNECTION_TYPE_* above */
  2256. struct mg_request_info request_info;
  2257. struct mg_response_info response_info;
  2258. struct mg_context *phys_ctx;
  2259. struct mg_domain_context *dom_ctx;
  2260. #if defined(USE_SERVER_STATS)
  2261. int conn_state; /* 0 = undef, numerical value may change in different
  2262. * versions. For the current definition, see
  2263. * mg_get_connection_info_impl */
  2264. #endif
  2265. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2266. SSL *ssl; /* SSL descriptor */
  2267. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2268. struct socket client; /* Connected client */
  2269. time_t conn_birth_time; /* Time (wall clock) when connection was
  2270. * established */
  2271. struct timespec req_time; /* Time (since system start) when the request
  2272. * was received */
  2273. int64_t num_bytes_sent; /* Total bytes sent to client */
  2274. int64_t content_len; /* Content-Length header value */
  2275. int64_t consumed_content; /* How many bytes of content have been read */
  2276. int is_chunked; /* Transfer-Encoding is chunked:
  2277. * 0 = not chunked,
  2278. * 1 = chunked, do data read yet,
  2279. * 2 = chunked, some data read,
  2280. * 3 = chunked, all data read
  2281. */
  2282. size_t chunk_remainder; /* Unread data from the last chunk */
  2283. char *buf; /* Buffer for received data */
  2284. char *path_info; /* PATH_INFO part of the URL */
  2285. int must_close; /* 1 if connection must be closed */
  2286. int accept_gzip; /* 1 if gzip encoding is accepted */
  2287. int in_error_handler; /* 1 if in handler for user defined error
  2288. * pages */
  2289. #if defined(USE_WEBSOCKET)
  2290. int in_websocket_handling; /* 1 if in read_websocket */
  2291. #endif
  2292. int handled_requests; /* Number of requests handled by this connection
  2293. */
  2294. int buf_size; /* Buffer size */
  2295. int request_len; /* Size of the request + headers in a buffer */
  2296. int data_len; /* Total size of data in a buffer */
  2297. int status_code; /* HTTP reply status code, e.g. 200 */
  2298. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2299. * throttle */
  2300. time_t last_throttle_time; /* Last time throttled data was sent */
  2301. int64_t last_throttle_bytes; /* Bytes sent this second */
  2302. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2303. * atomic transmissions for websockets */
  2304. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2305. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2306. #endif
  2307. int thread_index; /* Thread index within ctx */
  2308. };
  2309. /* Directory entry */
  2310. struct de {
  2311. struct mg_connection *conn;
  2312. char *file_name;
  2313. struct mg_file_stat file;
  2314. };
  2315. #if defined(USE_WEBSOCKET)
  2316. static int is_websocket_protocol(const struct mg_connection *conn);
  2317. #else
  2318. #define is_websocket_protocol(conn) (0)
  2319. #endif
  2320. #define mg_cry_internal(conn, fmt, ...) \
  2321. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2322. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2323. const char *func,
  2324. unsigned line,
  2325. const char *fmt,
  2326. ...) PRINTF_ARGS(4, 5);
  2327. #if !defined(NO_THREAD_NAME)
  2328. #if defined(_WIN32) && defined(_MSC_VER)
  2329. /* Set the thread name for debugging purposes in Visual Studio
  2330. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2331. */
  2332. #pragma pack(push, 8)
  2333. typedef struct tagTHREADNAME_INFO {
  2334. DWORD dwType; /* Must be 0x1000. */
  2335. LPCSTR szName; /* Pointer to name (in user addr space). */
  2336. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2337. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2338. } THREADNAME_INFO;
  2339. #pragma pack(pop)
  2340. #elif defined(__linux__)
  2341. #include <sys/prctl.h>
  2342. #include <sys/sendfile.h>
  2343. #if defined(ALTERNATIVE_QUEUE)
  2344. #include <sys/eventfd.h>
  2345. #endif /* ALTERNATIVE_QUEUE */
  2346. #if defined(ALTERNATIVE_QUEUE)
  2347. static void *
  2348. event_create(void)
  2349. {
  2350. int evhdl = eventfd(0, EFD_CLOEXEC);
  2351. int *ret;
  2352. if (evhdl == -1) {
  2353. /* Linux uses -1 on error, Windows NULL. */
  2354. /* However, Linux does not return 0 on success either. */
  2355. return 0;
  2356. }
  2357. ret = (int *)mg_malloc(sizeof(int));
  2358. if (ret) {
  2359. *ret = evhdl;
  2360. } else {
  2361. (void)close(evhdl);
  2362. }
  2363. return (void *)ret;
  2364. }
  2365. static int
  2366. event_wait(void *eventhdl)
  2367. {
  2368. uint64_t u;
  2369. int evhdl, s;
  2370. if (!eventhdl) {
  2371. /* error */
  2372. return 0;
  2373. }
  2374. evhdl = *(int *)eventhdl;
  2375. s = (int)read(evhdl, &u, sizeof(u));
  2376. if (s != sizeof(u)) {
  2377. /* error */
  2378. return 0;
  2379. }
  2380. (void)u; /* the value is not required */
  2381. return 1;
  2382. }
  2383. static int
  2384. event_signal(void *eventhdl)
  2385. {
  2386. uint64_t u = 1;
  2387. int evhdl, s;
  2388. if (!eventhdl) {
  2389. /* error */
  2390. return 0;
  2391. }
  2392. evhdl = *(int *)eventhdl;
  2393. s = (int)write(evhdl, &u, sizeof(u));
  2394. if (s != sizeof(u)) {
  2395. /* error */
  2396. return 0;
  2397. }
  2398. return 1;
  2399. }
  2400. static void
  2401. event_destroy(void *eventhdl)
  2402. {
  2403. int evhdl;
  2404. if (!eventhdl) {
  2405. /* error */
  2406. return;
  2407. }
  2408. evhdl = *(int *)eventhdl;
  2409. close(evhdl);
  2410. mg_free(eventhdl);
  2411. }
  2412. #endif
  2413. #endif
  2414. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2415. struct posix_event {
  2416. pthread_mutex_t mutex;
  2417. pthread_cond_t cond;
  2418. };
  2419. static void *
  2420. event_create(void)
  2421. {
  2422. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2423. if (ret == 0) {
  2424. /* out of memory */
  2425. return 0;
  2426. }
  2427. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2428. /* pthread mutex not available */
  2429. mg_free(ret);
  2430. return 0;
  2431. }
  2432. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2433. /* pthread cond not available */
  2434. pthread_mutex_destroy(&(ret->mutex));
  2435. mg_free(ret);
  2436. return 0;
  2437. }
  2438. return (void *)ret;
  2439. }
  2440. static int
  2441. event_wait(void *eventhdl)
  2442. {
  2443. struct posix_event *ev = (struct posix_event *)eventhdl;
  2444. pthread_mutex_lock(&(ev->mutex));
  2445. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2446. pthread_mutex_unlock(&(ev->mutex));
  2447. return 1;
  2448. }
  2449. static int
  2450. event_signal(void *eventhdl)
  2451. {
  2452. struct posix_event *ev = (struct posix_event *)eventhdl;
  2453. pthread_mutex_lock(&(ev->mutex));
  2454. pthread_cond_signal(&(ev->cond));
  2455. pthread_mutex_unlock(&(ev->mutex));
  2456. return 1;
  2457. }
  2458. static void
  2459. event_destroy(void *eventhdl)
  2460. {
  2461. struct posix_event *ev = (struct posix_event *)eventhdl;
  2462. pthread_cond_destroy(&(ev->cond));
  2463. pthread_mutex_destroy(&(ev->mutex));
  2464. mg_free(ev);
  2465. }
  2466. #endif
  2467. static void
  2468. mg_set_thread_name(const char *name)
  2469. {
  2470. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2471. mg_snprintf(
  2472. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2473. #if defined(_WIN32)
  2474. #if defined(_MSC_VER)
  2475. /* Windows and Visual Studio Compiler */
  2476. __try
  2477. {
  2478. THREADNAME_INFO info;
  2479. info.dwType = 0x1000;
  2480. info.szName = threadName;
  2481. info.dwThreadID = ~0U;
  2482. info.dwFlags = 0;
  2483. RaiseException(0x406D1388,
  2484. 0,
  2485. sizeof(info) / sizeof(ULONG_PTR),
  2486. (ULONG_PTR *)&info);
  2487. }
  2488. __except(EXCEPTION_EXECUTE_HANDLER)
  2489. {
  2490. }
  2491. #elif defined(__MINGW32__)
  2492. /* No option known to set thread name for MinGW */
  2493. #endif
  2494. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2495. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2496. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2497. (void)pthread_setname_np(pthread_self(), threadName);
  2498. #elif defined(__linux__)
  2499. /* on linux we can use the old prctl function */
  2500. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2501. #endif
  2502. }
  2503. #else /* !defined(NO_THREAD_NAME) */
  2504. void
  2505. mg_set_thread_name(const char *threadName)
  2506. {
  2507. }
  2508. #endif
  2509. #if defined(MG_LEGACY_INTERFACE)
  2510. const char **
  2511. mg_get_valid_option_names(void)
  2512. {
  2513. /* This function is deprecated. Use mg_get_valid_options instead. */
  2514. static const char *
  2515. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2516. int i;
  2517. for (i = 0; config_options[i].name != NULL; i++) {
  2518. data[i * 2] = config_options[i].name;
  2519. data[i * 2 + 1] = config_options[i].default_value;
  2520. }
  2521. return data;
  2522. }
  2523. #endif
  2524. const struct mg_option *
  2525. mg_get_valid_options(void)
  2526. {
  2527. return config_options;
  2528. }
  2529. /* Do not open file (used in is_file_in_memory) */
  2530. #define MG_FOPEN_MODE_NONE (0)
  2531. /* Open file for read only access */
  2532. #define MG_FOPEN_MODE_READ (1)
  2533. /* Open file for writing, create and overwrite */
  2534. #define MG_FOPEN_MODE_WRITE (2)
  2535. /* Open file for writing, create and append */
  2536. #define MG_FOPEN_MODE_APPEND (4)
  2537. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2538. * output filep and return 1, otherwise return 0 and don't modify anything.
  2539. */
  2540. static int
  2541. open_file_in_memory(const struct mg_connection *conn,
  2542. const char *path,
  2543. struct mg_file *filep,
  2544. int mode)
  2545. {
  2546. #if defined(MG_USE_OPEN_FILE)
  2547. size_t size = 0;
  2548. const char *buf = NULL;
  2549. if (!conn) {
  2550. return 0;
  2551. }
  2552. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2553. return 0;
  2554. }
  2555. if (conn->phys_ctx->callbacks.open_file) {
  2556. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2557. if (buf != NULL) {
  2558. if (filep == NULL) {
  2559. /* This is a file in memory, but we cannot store the
  2560. * properties
  2561. * now.
  2562. * Called from "is_file_in_memory" function. */
  2563. return 1;
  2564. }
  2565. /* NOTE: override filep->size only on success. Otherwise, it
  2566. * might
  2567. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2568. filep->access.membuf = buf;
  2569. filep->access.fp = NULL;
  2570. /* Size was set by the callback */
  2571. filep->stat.size = size;
  2572. /* Assume the data may change during runtime by setting
  2573. * last_modified = now */
  2574. filep->stat.last_modified = time(NULL);
  2575. filep->stat.is_directory = 0;
  2576. filep->stat.is_gzipped = 0;
  2577. }
  2578. }
  2579. return (buf != NULL);
  2580. #else
  2581. (void)conn;
  2582. (void)path;
  2583. (void)filep;
  2584. (void)mode;
  2585. return 0;
  2586. #endif
  2587. }
  2588. static int
  2589. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2590. {
  2591. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2592. }
  2593. static int
  2594. is_file_opened(const struct mg_file_access *fileacc)
  2595. {
  2596. if (!fileacc) {
  2597. return 0;
  2598. }
  2599. #if defined(MG_USE_OPEN_FILE)
  2600. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2601. #else
  2602. return (fileacc->fp != NULL);
  2603. #endif
  2604. }
  2605. static int mg_stat(const struct mg_connection *conn,
  2606. const char *path,
  2607. struct mg_file_stat *filep);
  2608. /* mg_fopen will open a file either in memory or on the disk.
  2609. * The input parameter path is a string in UTF-8 encoding.
  2610. * The input parameter mode is MG_FOPEN_MODE_*
  2611. * On success, either fp or membuf will be set in the output
  2612. * struct file. All status members will also be set.
  2613. * The function returns 1 on success, 0 on error. */
  2614. static int
  2615. mg_fopen(const struct mg_connection *conn,
  2616. const char *path,
  2617. int mode,
  2618. struct mg_file *filep)
  2619. {
  2620. int found;
  2621. if (!filep) {
  2622. return 0;
  2623. }
  2624. filep->access.fp = NULL;
  2625. #if defined(MG_USE_OPEN_FILE)
  2626. filep->access.membuf = NULL;
  2627. #endif
  2628. if (!is_file_in_memory(conn, path)) {
  2629. /* filep is initialized in mg_stat: all fields with memset to,
  2630. * some fields like size and modification date with values */
  2631. found = mg_stat(conn, path, &(filep->stat));
  2632. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2633. /* file does not exist and will not be created */
  2634. return 0;
  2635. }
  2636. #if defined(_WIN32)
  2637. {
  2638. wchar_t wbuf[W_PATH_MAX];
  2639. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2640. switch (mode) {
  2641. case MG_FOPEN_MODE_READ:
  2642. filep->access.fp = _wfopen(wbuf, L"rb");
  2643. break;
  2644. case MG_FOPEN_MODE_WRITE:
  2645. filep->access.fp = _wfopen(wbuf, L"wb");
  2646. break;
  2647. case MG_FOPEN_MODE_APPEND:
  2648. filep->access.fp = _wfopen(wbuf, L"ab");
  2649. break;
  2650. }
  2651. }
  2652. #else
  2653. /* Linux et al already use unicode. No need to convert. */
  2654. switch (mode) {
  2655. case MG_FOPEN_MODE_READ:
  2656. filep->access.fp = fopen(path, "r");
  2657. break;
  2658. case MG_FOPEN_MODE_WRITE:
  2659. filep->access.fp = fopen(path, "w");
  2660. break;
  2661. case MG_FOPEN_MODE_APPEND:
  2662. filep->access.fp = fopen(path, "a");
  2663. break;
  2664. }
  2665. #endif
  2666. if (!found) {
  2667. /* File did not exist before fopen was called.
  2668. * Maybe it has been created now. Get stat info
  2669. * like creation time now. */
  2670. found = mg_stat(conn, path, &(filep->stat));
  2671. (void)found;
  2672. }
  2673. /* file is on disk */
  2674. return (filep->access.fp != NULL);
  2675. } else {
  2676. #if defined(MG_USE_OPEN_FILE)
  2677. /* is_file_in_memory returned true */
  2678. if (open_file_in_memory(conn, path, filep, mode)) {
  2679. /* file is in memory */
  2680. return (filep->access.membuf != NULL);
  2681. }
  2682. #endif
  2683. }
  2684. /* Open failed */
  2685. return 0;
  2686. }
  2687. /* return 0 on success, just like fclose */
  2688. static int
  2689. mg_fclose(struct mg_file_access *fileacc)
  2690. {
  2691. int ret = -1;
  2692. if (fileacc != NULL) {
  2693. if (fileacc->fp != NULL) {
  2694. ret = fclose(fileacc->fp);
  2695. #if defined(MG_USE_OPEN_FILE)
  2696. } else if (fileacc->membuf != NULL) {
  2697. ret = 0;
  2698. #endif
  2699. }
  2700. /* reset all members of fileacc */
  2701. memset(fileacc, 0, sizeof(*fileacc));
  2702. }
  2703. return ret;
  2704. }
  2705. static void
  2706. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2707. {
  2708. for (; *src != '\0' && n > 1; n--) {
  2709. *dst++ = *src++;
  2710. }
  2711. *dst = '\0';
  2712. }
  2713. static int
  2714. lowercase(const char *s)
  2715. {
  2716. return tolower(*(const unsigned char *)s);
  2717. }
  2718. int
  2719. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2720. {
  2721. int diff = 0;
  2722. if (len > 0) {
  2723. do {
  2724. diff = lowercase(s1++) - lowercase(s2++);
  2725. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2726. }
  2727. return diff;
  2728. }
  2729. int
  2730. mg_strcasecmp(const char *s1, const char *s2)
  2731. {
  2732. int diff;
  2733. do {
  2734. diff = lowercase(s1++) - lowercase(s2++);
  2735. } while (diff == 0 && s1[-1] != '\0');
  2736. return diff;
  2737. }
  2738. static char *
  2739. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2740. {
  2741. char *p;
  2742. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2743. * defined */
  2744. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2745. mg_strlcpy(p, ptr, len + 1);
  2746. }
  2747. return p;
  2748. }
  2749. static char *
  2750. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2751. {
  2752. return mg_strndup_ctx(str, strlen(str), ctx);
  2753. }
  2754. static char *
  2755. mg_strdup(const char *str)
  2756. {
  2757. return mg_strndup_ctx(str, strlen(str), NULL);
  2758. }
  2759. static const char *
  2760. mg_strcasestr(const char *big_str, const char *small_str)
  2761. {
  2762. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2763. if (big_len >= small_len) {
  2764. for (i = 0; i <= (big_len - small_len); i++) {
  2765. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2766. return big_str + i;
  2767. }
  2768. }
  2769. }
  2770. return NULL;
  2771. }
  2772. /* Return null terminated string of given maximum length.
  2773. * Report errors if length is exceeded. */
  2774. static void
  2775. mg_vsnprintf(const struct mg_connection *conn,
  2776. int *truncated,
  2777. char *buf,
  2778. size_t buflen,
  2779. const char *fmt,
  2780. va_list ap)
  2781. {
  2782. int n, ok;
  2783. if (buflen == 0) {
  2784. if (truncated) {
  2785. *truncated = 1;
  2786. }
  2787. return;
  2788. }
  2789. #if defined(__clang__)
  2790. #pragma clang diagnostic push
  2791. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2792. /* Using fmt as a non-literal is intended here, since it is mostly called
  2793. * indirectly by mg_snprintf */
  2794. #endif
  2795. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2796. ok = (n >= 0) && ((size_t)n < buflen);
  2797. #if defined(__clang__)
  2798. #pragma clang diagnostic pop
  2799. #endif
  2800. if (ok) {
  2801. if (truncated) {
  2802. *truncated = 0;
  2803. }
  2804. } else {
  2805. if (truncated) {
  2806. *truncated = 1;
  2807. }
  2808. mg_cry_internal(conn,
  2809. "truncating vsnprintf buffer: [%.*s]",
  2810. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2811. buf);
  2812. n = (int)buflen - 1;
  2813. }
  2814. buf[n] = '\0';
  2815. }
  2816. static void
  2817. mg_snprintf(const struct mg_connection *conn,
  2818. int *truncated,
  2819. char *buf,
  2820. size_t buflen,
  2821. const char *fmt,
  2822. ...)
  2823. {
  2824. va_list ap;
  2825. va_start(ap, fmt);
  2826. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2827. va_end(ap);
  2828. }
  2829. static int
  2830. get_option_index(const char *name)
  2831. {
  2832. int i;
  2833. for (i = 0; config_options[i].name != NULL; i++) {
  2834. if (strcmp(config_options[i].name, name) == 0) {
  2835. return i;
  2836. }
  2837. }
  2838. return -1;
  2839. }
  2840. const char *
  2841. mg_get_option(const struct mg_context *ctx, const char *name)
  2842. {
  2843. int i;
  2844. if ((i = get_option_index(name)) == -1) {
  2845. return NULL;
  2846. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2847. return "";
  2848. } else {
  2849. return ctx->dd.config[i];
  2850. }
  2851. }
  2852. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2853. struct mg_context *
  2854. mg_get_context(const struct mg_connection *conn)
  2855. {
  2856. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2857. }
  2858. void *
  2859. mg_get_user_data(const struct mg_context *ctx)
  2860. {
  2861. return (ctx == NULL) ? NULL : ctx->user_data;
  2862. }
  2863. void
  2864. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2865. {
  2866. if (conn != NULL) {
  2867. conn->request_info.conn_data = data;
  2868. }
  2869. }
  2870. void *
  2871. mg_get_user_connection_data(const struct mg_connection *conn)
  2872. {
  2873. if (conn != NULL) {
  2874. return conn->request_info.conn_data;
  2875. }
  2876. return NULL;
  2877. }
  2878. #if defined(MG_LEGACY_INTERFACE)
  2879. /* Deprecated: Use mg_get_server_ports instead. */
  2880. size_t
  2881. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2882. {
  2883. size_t i;
  2884. if (!ctx) {
  2885. return 0;
  2886. }
  2887. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2888. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2889. ports[i] =
  2890. #if defined(USE_IPV6)
  2891. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2892. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2893. :
  2894. #endif
  2895. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2896. }
  2897. return i;
  2898. }
  2899. #endif
  2900. int
  2901. mg_get_server_ports(const struct mg_context *ctx,
  2902. int size,
  2903. struct mg_server_ports *ports)
  2904. {
  2905. int i, cnt = 0;
  2906. if (size <= 0) {
  2907. return -1;
  2908. }
  2909. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2910. if (!ctx) {
  2911. return -1;
  2912. }
  2913. if (!ctx->listening_sockets) {
  2914. return -1;
  2915. }
  2916. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2917. ports[cnt].port =
  2918. #if defined(USE_IPV6)
  2919. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2920. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2921. :
  2922. #endif
  2923. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2924. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2925. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2926. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2927. /* IPv4 */
  2928. ports[cnt].protocol = 1;
  2929. cnt++;
  2930. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2931. /* IPv6 */
  2932. ports[cnt].protocol = 3;
  2933. cnt++;
  2934. }
  2935. }
  2936. return cnt;
  2937. }
  2938. static void
  2939. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2940. {
  2941. buf[0] = '\0';
  2942. if (!usa) {
  2943. return;
  2944. }
  2945. if (usa->sa.sa_family == AF_INET) {
  2946. getnameinfo(&usa->sa,
  2947. sizeof(usa->sin),
  2948. buf,
  2949. (unsigned)len,
  2950. NULL,
  2951. 0,
  2952. NI_NUMERICHOST);
  2953. }
  2954. #if defined(USE_IPV6)
  2955. else if (usa->sa.sa_family == AF_INET6) {
  2956. getnameinfo(&usa->sa,
  2957. sizeof(usa->sin6),
  2958. buf,
  2959. (unsigned)len,
  2960. NULL,
  2961. 0,
  2962. NI_NUMERICHOST);
  2963. }
  2964. #endif
  2965. }
  2966. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2967. * included in all responses other than 100, 101, 5xx. */
  2968. static void
  2969. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2970. {
  2971. #if !defined(REENTRANT_TIME)
  2972. struct tm *tm;
  2973. tm = ((t != NULL) ? gmtime(t) : NULL);
  2974. if (tm != NULL) {
  2975. #else
  2976. struct tm _tm;
  2977. struct tm *tm = &_tm;
  2978. if (t != NULL) {
  2979. gmtime_r(t, tm);
  2980. #endif
  2981. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2982. } else {
  2983. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2984. buf[buf_len - 1] = '\0';
  2985. }
  2986. }
  2987. /* difftime for struct timespec. Return value is in seconds. */
  2988. static double
  2989. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2990. {
  2991. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2992. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2993. }
  2994. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2995. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2996. const char *func,
  2997. unsigned line,
  2998. const char *fmt,
  2999. va_list ap);
  3000. #include "external_mg_cry_internal_impl.inl"
  3001. #else
  3002. /* Print error message to the opened error log stream. */
  3003. static void
  3004. mg_cry_internal_impl(const struct mg_connection *conn,
  3005. const char *func,
  3006. unsigned line,
  3007. const char *fmt,
  3008. va_list ap)
  3009. {
  3010. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3011. struct mg_file fi;
  3012. time_t timestamp;
  3013. /* Unused, in the RELEASE build */
  3014. (void)func;
  3015. (void)line;
  3016. #if defined(__GNUC__) || defined(__MINGW32__)
  3017. #pragma GCC diagnostic push
  3018. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3019. #endif
  3020. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3021. #if defined(__GNUC__) || defined(__MINGW32__)
  3022. #pragma GCC diagnostic pop
  3023. #endif
  3024. buf[sizeof(buf) - 1] = 0;
  3025. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3026. if (!conn) {
  3027. puts(buf);
  3028. return;
  3029. }
  3030. /* Do not lock when getting the callback value, here and below.
  3031. * I suppose this is fine, since function cannot disappear in the
  3032. * same way string option can. */
  3033. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3034. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3035. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3036. if (mg_fopen(conn,
  3037. conn->dom_ctx->config[ERROR_LOG_FILE],
  3038. MG_FOPEN_MODE_APPEND,
  3039. &fi) == 0) {
  3040. fi.access.fp = NULL;
  3041. }
  3042. } else {
  3043. fi.access.fp = NULL;
  3044. }
  3045. if (fi.access.fp != NULL) {
  3046. flockfile(fi.access.fp);
  3047. timestamp = time(NULL);
  3048. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3049. fprintf(fi.access.fp,
  3050. "[%010lu] [error] [client %s] ",
  3051. (unsigned long)timestamp,
  3052. src_addr);
  3053. if (conn->request_info.request_method != NULL) {
  3054. fprintf(fi.access.fp,
  3055. "%s %s: ",
  3056. conn->request_info.request_method,
  3057. conn->request_info.request_uri
  3058. ? conn->request_info.request_uri
  3059. : "");
  3060. }
  3061. fprintf(fi.access.fp, "%s", buf);
  3062. fputc('\n', fi.access.fp);
  3063. fflush(fi.access.fp);
  3064. funlockfile(fi.access.fp);
  3065. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3066. * mg_cry here anyway ;-) */
  3067. }
  3068. }
  3069. }
  3070. #endif /* Externally provided function */
  3071. static void
  3072. mg_cry_internal_wrap(const struct mg_connection *conn,
  3073. const char *func,
  3074. unsigned line,
  3075. const char *fmt,
  3076. ...)
  3077. {
  3078. va_list ap;
  3079. va_start(ap, fmt);
  3080. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3081. va_end(ap);
  3082. }
  3083. void
  3084. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3085. {
  3086. va_list ap;
  3087. va_start(ap, fmt);
  3088. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3089. va_end(ap);
  3090. }
  3091. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3092. /* Return fake connection structure. Used for logging, if connection
  3093. * is not applicable at the moment of logging. */
  3094. static struct mg_connection *
  3095. fc(struct mg_context *ctx)
  3096. {
  3097. static struct mg_connection fake_connection;
  3098. fake_connection.phys_ctx = ctx;
  3099. fake_connection.dom_ctx = &(ctx->dd);
  3100. return &fake_connection;
  3101. }
  3102. const char *
  3103. mg_version(void)
  3104. {
  3105. return CIVETWEB_VERSION;
  3106. }
  3107. const struct mg_request_info *
  3108. mg_get_request_info(const struct mg_connection *conn)
  3109. {
  3110. if (!conn) {
  3111. return NULL;
  3112. }
  3113. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3114. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3115. char txt[16];
  3116. struct mg_workerTLS *tls =
  3117. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3118. sprintf(txt, "%03i", conn->response_info.status_code);
  3119. if (strlen(txt) == 3) {
  3120. memcpy(tls->txtbuf, txt, 4);
  3121. } else {
  3122. strcpy(tls->txtbuf, "ERR");
  3123. }
  3124. ((struct mg_connection *)conn)->request_info.local_uri =
  3125. ((struct mg_connection *)conn)->request_info.request_uri =
  3126. tls->txtbuf; /* use thread safe buffer */
  3127. ((struct mg_connection *)conn)->request_info.num_headers =
  3128. conn->response_info.num_headers;
  3129. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3130. conn->response_info.http_headers,
  3131. sizeof(conn->response_info.http_headers));
  3132. } else
  3133. #endif
  3134. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3135. return NULL;
  3136. }
  3137. return &conn->request_info;
  3138. }
  3139. const struct mg_response_info *
  3140. mg_get_response_info(const struct mg_connection *conn)
  3141. {
  3142. if (!conn) {
  3143. return NULL;
  3144. }
  3145. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3146. return NULL;
  3147. }
  3148. return &conn->response_info;
  3149. }
  3150. static const char *
  3151. get_proto_name(const struct mg_connection *conn)
  3152. {
  3153. #if defined(__clang__)
  3154. #pragma clang diagnostic push
  3155. #pragma clang diagnostic ignored "-Wunreachable-code"
  3156. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3157. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3158. * unreachable, but splitting into four different #ifdef clauses here is more
  3159. * complicated.
  3160. */
  3161. #endif
  3162. const struct mg_request_info *ri = &conn->request_info;
  3163. const char *proto =
  3164. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3165. : (ri->is_ssl ? "https" : "http"));
  3166. return proto;
  3167. #if defined(__clang__)
  3168. #pragma clang diagnostic pop
  3169. #endif
  3170. }
  3171. int
  3172. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3173. {
  3174. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3175. return -1;
  3176. } else {
  3177. int truncated = 0;
  3178. const struct mg_request_info *ri = &conn->request_info;
  3179. const char *proto = get_proto_name(conn);
  3180. if (ri->local_uri == NULL) {
  3181. return -1;
  3182. }
  3183. if ((ri->request_uri != NULL)
  3184. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3185. /* The request uri is different from the local uri.
  3186. * This is usually if an absolute URI, including server
  3187. * name has been provided. */
  3188. mg_snprintf(conn,
  3189. &truncated,
  3190. buf,
  3191. buflen,
  3192. "%s://%s",
  3193. proto,
  3194. ri->request_uri);
  3195. if (truncated) {
  3196. return -1;
  3197. }
  3198. return 0;
  3199. } else {
  3200. /* The common case is a relative URI, so we have to
  3201. * construct an absolute URI from server name and port */
  3202. #if defined(USE_IPV6)
  3203. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3204. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3205. : htons(conn->client.lsa.sin.sin_port);
  3206. #else
  3207. int port = htons(conn->client.lsa.sin.sin_port);
  3208. #endif
  3209. int def_port = ri->is_ssl ? 443 : 80;
  3210. int auth_domain_check_enabled =
  3211. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3212. && (!mg_strcasecmp(
  3213. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3214. "yes"));
  3215. const char *server_domain =
  3216. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3217. char portstr[16];
  3218. char server_ip[48];
  3219. if (port != def_port) {
  3220. sprintf(portstr, ":%u", (unsigned)port);
  3221. } else {
  3222. portstr[0] = 0;
  3223. }
  3224. if (!auth_domain_check_enabled || !server_domain) {
  3225. sockaddr_to_string(server_ip,
  3226. sizeof(server_ip),
  3227. &conn->client.lsa);
  3228. server_domain = server_ip;
  3229. }
  3230. mg_snprintf(conn,
  3231. &truncated,
  3232. buf,
  3233. buflen,
  3234. "%s://%s%s%s",
  3235. proto,
  3236. server_domain,
  3237. portstr,
  3238. ri->local_uri);
  3239. if (truncated) {
  3240. return -1;
  3241. }
  3242. return 0;
  3243. }
  3244. }
  3245. }
  3246. /* Skip the characters until one of the delimiters characters found.
  3247. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3248. * Advance pointer to buffer to the next word. Return found 0-terminated
  3249. * word.
  3250. * Delimiters can be quoted with quotechar. */
  3251. static char *
  3252. skip_quoted(char **buf,
  3253. const char *delimiters,
  3254. const char *whitespace,
  3255. char quotechar)
  3256. {
  3257. char *p, *begin_word, *end_word, *end_whitespace;
  3258. begin_word = *buf;
  3259. end_word = begin_word + strcspn(begin_word, delimiters);
  3260. /* Check for quotechar */
  3261. if (end_word > begin_word) {
  3262. p = end_word - 1;
  3263. while (*p == quotechar) {
  3264. /* While the delimiter is quoted, look for the next delimiter.
  3265. */
  3266. /* This happens, e.g., in calls from parse_auth_header,
  3267. * if the user name contains a " character. */
  3268. /* If there is anything beyond end_word, copy it. */
  3269. if (*end_word != '\0') {
  3270. size_t end_off = strcspn(end_word + 1, delimiters);
  3271. memmove(p, end_word, end_off + 1);
  3272. p += end_off; /* p must correspond to end_word - 1 */
  3273. end_word += end_off + 1;
  3274. } else {
  3275. *p = '\0';
  3276. break;
  3277. }
  3278. }
  3279. for (p++; p < end_word; p++) {
  3280. *p = '\0';
  3281. }
  3282. }
  3283. if (*end_word == '\0') {
  3284. *buf = end_word;
  3285. } else {
  3286. #if defined(__GNUC__) || defined(__MINGW32__)
  3287. /* Disable spurious conversion warning for GCC */
  3288. #if GCC_VERSION >= 40500
  3289. #pragma GCC diagnostic push
  3290. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3291. #endif /* GCC_VERSION >= 40500 */
  3292. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3293. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3294. #if defined(__GNUC__) || defined(__MINGW32__)
  3295. #if GCC_VERSION >= 40500
  3296. #pragma GCC diagnostic pop
  3297. #endif /* GCC_VERSION >= 40500 */
  3298. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3299. for (p = end_word; p < end_whitespace; p++) {
  3300. *p = '\0';
  3301. }
  3302. *buf = end_whitespace;
  3303. }
  3304. return begin_word;
  3305. }
  3306. /* Return HTTP header value, or NULL if not found. */
  3307. static const char *
  3308. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3309. {
  3310. int i;
  3311. for (i = 0; i < num_hdr; i++) {
  3312. if (!mg_strcasecmp(name, hdr[i].name)) {
  3313. return hdr[i].value;
  3314. }
  3315. }
  3316. return NULL;
  3317. }
  3318. #if defined(USE_WEBSOCKET)
  3319. /* Retrieve requested HTTP header multiple values, and return the number of
  3320. * found occurrences */
  3321. static int
  3322. get_req_headers(const struct mg_request_info *ri,
  3323. const char *name,
  3324. const char **output,
  3325. int output_max_size)
  3326. {
  3327. int i;
  3328. int cnt = 0;
  3329. if (ri) {
  3330. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3331. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3332. output[cnt++] = ri->http_headers[i].value;
  3333. }
  3334. }
  3335. }
  3336. return cnt;
  3337. }
  3338. #endif
  3339. const char *
  3340. mg_get_header(const struct mg_connection *conn, const char *name)
  3341. {
  3342. if (!conn) {
  3343. return NULL;
  3344. }
  3345. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3346. return get_header(conn->request_info.http_headers,
  3347. conn->request_info.num_headers,
  3348. name);
  3349. }
  3350. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3351. return get_header(conn->response_info.http_headers,
  3352. conn->response_info.num_headers,
  3353. name);
  3354. }
  3355. return NULL;
  3356. }
  3357. static const char *
  3358. get_http_version(const struct mg_connection *conn)
  3359. {
  3360. if (!conn) {
  3361. return NULL;
  3362. }
  3363. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3364. return conn->request_info.http_version;
  3365. }
  3366. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3367. return conn->response_info.http_version;
  3368. }
  3369. return NULL;
  3370. }
  3371. /* A helper function for traversing a comma separated list of values.
  3372. * It returns a list pointer shifted to the next value, or NULL if the end
  3373. * of the list found.
  3374. * Value is stored in val vector. If value has form "x=y", then eq_val
  3375. * vector is initialized to point to the "y" part, and val vector length
  3376. * is adjusted to point only to "x". */
  3377. static const char *
  3378. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3379. {
  3380. int end;
  3381. reparse:
  3382. if (val == NULL || list == NULL || *list == '\0') {
  3383. /* End of the list */
  3384. return NULL;
  3385. }
  3386. /* Skip over leading LWS */
  3387. while (*list == ' ' || *list == '\t')
  3388. list++;
  3389. val->ptr = list;
  3390. if ((list = strchr(val->ptr, ',')) != NULL) {
  3391. /* Comma found. Store length and shift the list ptr */
  3392. val->len = ((size_t)(list - val->ptr));
  3393. list++;
  3394. } else {
  3395. /* This value is the last one */
  3396. list = val->ptr + strlen(val->ptr);
  3397. val->len = ((size_t)(list - val->ptr));
  3398. }
  3399. /* Adjust length for trailing LWS */
  3400. end = (int)val->len - 1;
  3401. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3402. end--;
  3403. val->len = (size_t)(end + 1);
  3404. if (val->len == 0) {
  3405. /* Ignore any empty entries. */
  3406. goto reparse;
  3407. }
  3408. if (eq_val != NULL) {
  3409. /* Value has form "x=y", adjust pointers and lengths
  3410. * so that val points to "x", and eq_val points to "y". */
  3411. eq_val->len = 0;
  3412. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3413. if (eq_val->ptr != NULL) {
  3414. eq_val->ptr++; /* Skip over '=' character */
  3415. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3416. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3417. }
  3418. }
  3419. return list;
  3420. }
  3421. /* A helper function for checking if a comma separated list of values
  3422. * contains
  3423. * the given option (case insensitvely).
  3424. * 'header' can be NULL, in which case false is returned. */
  3425. static int
  3426. header_has_option(const char *header, const char *option)
  3427. {
  3428. struct vec opt_vec;
  3429. struct vec eq_vec;
  3430. DEBUG_ASSERT(option != NULL);
  3431. DEBUG_ASSERT(option[0] != '\0');
  3432. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3433. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3434. return 1;
  3435. }
  3436. return 0;
  3437. }
  3438. /* Perform case-insensitive match of string against pattern */
  3439. static ptrdiff_t
  3440. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3441. {
  3442. const char *or_str;
  3443. ptrdiff_t i, j, len, res;
  3444. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3445. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3446. return (res > 0) ? res : match_prefix(or_str + 1,
  3447. (size_t)((pattern + pattern_len)
  3448. - (or_str + 1)),
  3449. str);
  3450. }
  3451. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3452. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3453. continue;
  3454. } else if (pattern[i] == '$') {
  3455. return (str[j] == '\0') ? j : -1;
  3456. } else if (pattern[i] == '*') {
  3457. i++;
  3458. if (pattern[i] == '*') {
  3459. i++;
  3460. len = strlen(str + j);
  3461. } else {
  3462. len = strcspn(str + j, "/");
  3463. }
  3464. if (i == (ptrdiff_t)pattern_len) {
  3465. return j + len;
  3466. }
  3467. do {
  3468. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3469. } while (res == -1 && len-- > 0);
  3470. return (res == -1) ? -1 : j + res + len;
  3471. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3472. return -1;
  3473. }
  3474. }
  3475. return (ptrdiff_t)j;
  3476. }
  3477. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3478. * This function must tolerate situations when connection info is not
  3479. * set up, for example if request parsing failed. */
  3480. static int
  3481. should_keep_alive(const struct mg_connection *conn)
  3482. {
  3483. const char *http_version;
  3484. const char *header;
  3485. /* First satisfy needs of the server */
  3486. if ((conn == NULL) || conn->must_close) {
  3487. /* Close, if civetweb framework needs to close */
  3488. return 0;
  3489. }
  3490. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3491. /* Close, if keep alive is not enabled */
  3492. return 0;
  3493. }
  3494. /* Check explicit wish of the client */
  3495. header = mg_get_header(conn, "Connection");
  3496. if (header) {
  3497. /* If there is a connection header from the client, obey */
  3498. if (header_has_option(header, "keep-alive")) {
  3499. return 1;
  3500. }
  3501. return 0;
  3502. }
  3503. /* Use default of the standard */
  3504. http_version = get_http_version(conn);
  3505. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3506. /* HTTP 1.1 default is keep alive */
  3507. return 1;
  3508. }
  3509. /* HTTP 1.0 (and earlier) default is to close the connection */
  3510. return 0;
  3511. }
  3512. static int
  3513. should_decode_url(const struct mg_connection *conn)
  3514. {
  3515. if (!conn || !conn->dom_ctx) {
  3516. return 0;
  3517. }
  3518. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3519. }
  3520. static const char *
  3521. suggest_connection_header(const struct mg_connection *conn)
  3522. {
  3523. return should_keep_alive(conn) ? "keep-alive" : "close";
  3524. }
  3525. static int
  3526. send_no_cache_header(struct mg_connection *conn)
  3527. {
  3528. /* Send all current and obsolete cache opt-out directives. */
  3529. return mg_printf(conn,
  3530. "Cache-Control: no-cache, no-store, "
  3531. "must-revalidate, private, max-age=0\r\n"
  3532. "Pragma: no-cache\r\n"
  3533. "Expires: 0\r\n");
  3534. }
  3535. static int
  3536. send_static_cache_header(struct mg_connection *conn)
  3537. {
  3538. #if !defined(NO_CACHING)
  3539. /* Read the server config to check how long a file may be cached.
  3540. * The configuration is in seconds. */
  3541. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3542. if (max_age <= 0) {
  3543. /* 0 means "do not cache". All values <0 are reserved
  3544. * and may be used differently in the future. */
  3545. /* If a file should not be cached, do not only send
  3546. * max-age=0, but also pragmas and Expires headers. */
  3547. return send_no_cache_header(conn);
  3548. }
  3549. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3550. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3551. /* See also https://www.mnot.net/cache_docs/ */
  3552. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3553. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3554. * leap
  3555. * year to 31622400 seconds. For the moment, we just send whatever has
  3556. * been configured, still the behavior for >1 year should be considered
  3557. * as undefined. */
  3558. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3559. #else /* NO_CACHING */
  3560. return send_no_cache_header(conn);
  3561. #endif /* !NO_CACHING */
  3562. }
  3563. static int
  3564. send_additional_header(struct mg_connection *conn)
  3565. {
  3566. int i = 0;
  3567. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3568. #if !defined(NO_SSL)
  3569. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3570. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3571. if (max_age >= 0) {
  3572. i += mg_printf(conn,
  3573. "Strict-Transport-Security: max-age=%u\r\n",
  3574. (unsigned)max_age);
  3575. }
  3576. }
  3577. #endif
  3578. if (header && header[0]) {
  3579. i += mg_printf(conn, "%s\r\n", header);
  3580. }
  3581. return i;
  3582. }
  3583. static void handle_file_based_request(struct mg_connection *conn,
  3584. const char *path,
  3585. struct mg_file *filep);
  3586. const char *
  3587. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3588. {
  3589. /* See IANA HTTP status code assignment:
  3590. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3591. */
  3592. switch (response_code) {
  3593. /* RFC2616 Section 10.1 - Informational 1xx */
  3594. case 100:
  3595. return "Continue"; /* RFC2616 Section 10.1.1 */
  3596. case 101:
  3597. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3598. case 102:
  3599. return "Processing"; /* RFC2518 Section 10.1 */
  3600. /* RFC2616 Section 10.2 - Successful 2xx */
  3601. case 200:
  3602. return "OK"; /* RFC2616 Section 10.2.1 */
  3603. case 201:
  3604. return "Created"; /* RFC2616 Section 10.2.2 */
  3605. case 202:
  3606. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3607. case 203:
  3608. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3609. case 204:
  3610. return "No Content"; /* RFC2616 Section 10.2.5 */
  3611. case 205:
  3612. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3613. case 206:
  3614. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3615. case 207:
  3616. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3617. */
  3618. case 208:
  3619. return "Already Reported"; /* RFC5842 Section 7.1 */
  3620. case 226:
  3621. return "IM used"; /* RFC3229 Section 10.4.1 */
  3622. /* RFC2616 Section 10.3 - Redirection 3xx */
  3623. case 300:
  3624. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3625. case 301:
  3626. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3627. case 302:
  3628. return "Found"; /* RFC2616 Section 10.3.3 */
  3629. case 303:
  3630. return "See Other"; /* RFC2616 Section 10.3.4 */
  3631. case 304:
  3632. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3633. case 305:
  3634. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3635. case 307:
  3636. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3637. case 308:
  3638. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3639. /* RFC2616 Section 10.4 - Client Error 4xx */
  3640. case 400:
  3641. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3642. case 401:
  3643. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3644. case 402:
  3645. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3646. case 403:
  3647. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3648. case 404:
  3649. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3650. case 405:
  3651. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3652. case 406:
  3653. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3654. case 407:
  3655. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3656. case 408:
  3657. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3658. case 409:
  3659. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3660. case 410:
  3661. return "Gone"; /* RFC2616 Section 10.4.11 */
  3662. case 411:
  3663. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3664. case 412:
  3665. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3666. case 413:
  3667. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3668. case 414:
  3669. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3670. case 415:
  3671. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3672. case 416:
  3673. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3674. */
  3675. case 417:
  3676. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3677. case 421:
  3678. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3679. case 422:
  3680. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3681. * Section 11.2 */
  3682. case 423:
  3683. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3684. case 424:
  3685. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3686. * Section 11.4 */
  3687. case 426:
  3688. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3689. case 428:
  3690. return "Precondition Required"; /* RFC 6585, Section 3 */
  3691. case 429:
  3692. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3693. case 431:
  3694. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3695. case 451:
  3696. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3697. * Section 3 */
  3698. /* RFC2616 Section 10.5 - Server Error 5xx */
  3699. case 500:
  3700. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3701. case 501:
  3702. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3703. case 502:
  3704. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3705. case 503:
  3706. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3707. case 504:
  3708. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3709. case 505:
  3710. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3711. case 506:
  3712. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3713. case 507:
  3714. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3715. * Section 11.5 */
  3716. case 508:
  3717. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3718. case 510:
  3719. return "Not Extended"; /* RFC 2774, Section 7 */
  3720. case 511:
  3721. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3722. /* Other status codes, not shown in the IANA HTTP status code
  3723. * assignment.
  3724. * E.g., "de facto" standards due to common use, ... */
  3725. case 418:
  3726. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3727. case 419:
  3728. return "Authentication Timeout"; /* common use */
  3729. case 420:
  3730. return "Enhance Your Calm"; /* common use */
  3731. case 440:
  3732. return "Login Timeout"; /* common use */
  3733. case 509:
  3734. return "Bandwidth Limit Exceeded"; /* common use */
  3735. default:
  3736. /* This error code is unknown. This should not happen. */
  3737. if (conn) {
  3738. mg_cry_internal(conn,
  3739. "Unknown HTTP response code: %u",
  3740. response_code);
  3741. }
  3742. /* Return at least a category according to RFC 2616 Section 10. */
  3743. if (response_code >= 100 && response_code < 200) {
  3744. /* Unknown informational status code */
  3745. return "Information";
  3746. }
  3747. if (response_code >= 200 && response_code < 300) {
  3748. /* Unknown success code */
  3749. return "Success";
  3750. }
  3751. if (response_code >= 300 && response_code < 400) {
  3752. /* Unknown redirection code */
  3753. return "Redirection";
  3754. }
  3755. if (response_code >= 400 && response_code < 500) {
  3756. /* Unknown request error code */
  3757. return "Client Error";
  3758. }
  3759. if (response_code >= 500 && response_code < 600) {
  3760. /* Unknown server error code */
  3761. return "Server Error";
  3762. }
  3763. /* Response code not even within reasonable range */
  3764. return "";
  3765. }
  3766. }
  3767. static int
  3768. mg_send_http_error_impl(struct mg_connection *conn,
  3769. int status,
  3770. const char *fmt,
  3771. va_list args)
  3772. {
  3773. char errmsg_buf[MG_BUF_LEN];
  3774. char path_buf[PATH_MAX];
  3775. va_list ap;
  3776. int len, i, page_handler_found, scope, truncated, has_body;
  3777. char date[64];
  3778. time_t curtime = time(NULL);
  3779. const char *error_handler = NULL;
  3780. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3781. const char *error_page_file_ext, *tstr;
  3782. int handled_by_callback = 0;
  3783. const char *status_text = mg_get_response_code_text(conn, status);
  3784. if ((conn == NULL) || (fmt == NULL)) {
  3785. return -2;
  3786. }
  3787. /* Set status (for log) */
  3788. conn->status_code = status;
  3789. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3790. has_body = ((status > 199) && (status != 204) && (status != 304));
  3791. /* Prepare message in buf, if required */
  3792. if (has_body || (!conn->in_error_handler
  3793. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3794. /* Store error message in errmsg_buf */
  3795. va_copy(ap, args);
  3796. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3797. va_end(ap);
  3798. /* In a debug build, print all html errors */
  3799. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3800. }
  3801. /* If there is a http_error callback, call it.
  3802. * But don't do it recursively, if callback calls mg_send_http_error again.
  3803. */
  3804. if (!conn->in_error_handler
  3805. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3806. /* Mark in_error_handler to avoid recursion and call user callback. */
  3807. conn->in_error_handler = 1;
  3808. handled_by_callback =
  3809. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3810. == 0);
  3811. conn->in_error_handler = 0;
  3812. }
  3813. if (!handled_by_callback) {
  3814. /* Check for recursion */
  3815. if (conn->in_error_handler) {
  3816. DEBUG_TRACE(
  3817. "Recursion when handling error %u - fall back to default",
  3818. status);
  3819. } else {
  3820. /* Send user defined error pages, if defined */
  3821. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3822. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3823. page_handler_found = 0;
  3824. if (error_handler != NULL) {
  3825. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3826. switch (scope) {
  3827. case 1: /* Handler for specific error, e.g. 404 error */
  3828. mg_snprintf(conn,
  3829. &truncated,
  3830. path_buf,
  3831. sizeof(path_buf) - 32,
  3832. "%serror%03u.",
  3833. error_handler,
  3834. status);
  3835. break;
  3836. case 2: /* Handler for error group, e.g., 5xx error
  3837. * handler
  3838. * for all server errors (500-599) */
  3839. mg_snprintf(conn,
  3840. &truncated,
  3841. path_buf,
  3842. sizeof(path_buf) - 32,
  3843. "%serror%01uxx.",
  3844. error_handler,
  3845. status / 100);
  3846. break;
  3847. default: /* Handler for all errors */
  3848. mg_snprintf(conn,
  3849. &truncated,
  3850. path_buf,
  3851. sizeof(path_buf) - 32,
  3852. "%serror.",
  3853. error_handler);
  3854. break;
  3855. }
  3856. /* String truncation in buf may only occur if
  3857. * error_handler is too long. This string is
  3858. * from the config, not from a client. */
  3859. (void)truncated;
  3860. len = (int)strlen(path_buf);
  3861. tstr = strchr(error_page_file_ext, '.');
  3862. while (tstr) {
  3863. for (i = 1;
  3864. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3865. i++) {
  3866. /* buffer overrun is not possible here, since
  3867. * (i < 32) && (len < sizeof(path_buf) - 32)
  3868. * ==> (i + len) < sizeof(path_buf) */
  3869. path_buf[len + i - 1] = tstr[i];
  3870. }
  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] = 0;
  3875. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3876. DEBUG_TRACE("Check error page %s - found",
  3877. path_buf);
  3878. page_handler_found = 1;
  3879. break;
  3880. }
  3881. DEBUG_TRACE("Check error page %s - not found",
  3882. path_buf);
  3883. tstr = strchr(tstr + i, '.');
  3884. }
  3885. }
  3886. }
  3887. if (page_handler_found) {
  3888. conn->in_error_handler = 1;
  3889. handle_file_based_request(conn, path_buf, &error_page_file);
  3890. conn->in_error_handler = 0;
  3891. return 0;
  3892. }
  3893. }
  3894. /* No custom error page. Send default error page. */
  3895. gmt_time_string(date, sizeof(date), &curtime);
  3896. conn->must_close = 1;
  3897. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3898. send_no_cache_header(conn);
  3899. send_additional_header(conn);
  3900. if (has_body) {
  3901. mg_printf(conn,
  3902. "%s",
  3903. "Content-Type: text/plain; charset=utf-8\r\n");
  3904. }
  3905. mg_printf(conn,
  3906. "Date: %s\r\n"
  3907. "Connection: close\r\n\r\n",
  3908. date);
  3909. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3910. if (has_body) {
  3911. /* For other errors, send a generic error message. */
  3912. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3913. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3914. } else {
  3915. /* No body allowed. Close the connection. */
  3916. DEBUG_TRACE("Error %i", status);
  3917. }
  3918. }
  3919. return 0;
  3920. }
  3921. int
  3922. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3923. {
  3924. va_list ap;
  3925. int ret;
  3926. va_start(ap, fmt);
  3927. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3928. va_end(ap);
  3929. return ret;
  3930. }
  3931. int
  3932. mg_send_http_ok(struct mg_connection *conn,
  3933. const char *mime_type,
  3934. long long content_length)
  3935. {
  3936. char date[64];
  3937. time_t curtime = time(NULL);
  3938. if ((mime_type == NULL) || (*mime_type == 0)) {
  3939. /* Parameter error */
  3940. return -2;
  3941. }
  3942. gmt_time_string(date, sizeof(date), &curtime);
  3943. mg_printf(conn,
  3944. "HTTP/1.1 200 OK\r\n"
  3945. "Content-Type: %s\r\n"
  3946. "Date: %s\r\n"
  3947. "Connection: %s\r\n",
  3948. mime_type,
  3949. date,
  3950. suggest_connection_header(conn));
  3951. send_no_cache_header(conn);
  3952. send_additional_header(conn);
  3953. if (content_length < 0) {
  3954. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  3955. } else {
  3956. mg_printf(conn,
  3957. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  3958. (uint64_t)content_length);
  3959. }
  3960. return 0;
  3961. }
  3962. int
  3963. mg_send_http_redirect(struct mg_connection *conn,
  3964. const char *target_url,
  3965. int redirect_code)
  3966. {
  3967. /* Send a 30x redirect response.
  3968. *
  3969. * Redirect types (status codes):
  3970. *
  3971. * Status | Perm/Temp | Method | Version
  3972. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3973. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3974. * 303 | temporary | always use GET | HTTP/1.1
  3975. * 307 | temporary | always keep method | HTTP/1.1
  3976. * 308 | permanent | always keep method | HTTP/1.1
  3977. */
  3978. const char *redirect_text;
  3979. int ret;
  3980. size_t content_len = 0;
  3981. char reply[MG_BUF_LEN];
  3982. /* In case redirect_code=0, use 307. */
  3983. if (redirect_code == 0) {
  3984. redirect_code = 307;
  3985. }
  3986. /* In case redirect_code is none of the above, return error. */
  3987. if ((redirect_code != 301) && (redirect_code != 302)
  3988. && (redirect_code != 303) && (redirect_code != 307)
  3989. && (redirect_code != 308)) {
  3990. /* Parameter error */
  3991. return -2;
  3992. }
  3993. /* Get proper text for response code */
  3994. redirect_text = mg_get_response_code_text(conn, redirect_code);
  3995. /* If target_url is not defined, redirect to "/". */
  3996. if ((target_url == NULL) || (*target_url == 0)) {
  3997. target_url = "/";
  3998. }
  3999. #if defined(MG_SEND_REDIRECT_BODY)
  4000. /* TODO: condition name? */
  4001. /* Prepare a response body with a hyperlink.
  4002. *
  4003. * According to RFC2616 (and RFC1945 before):
  4004. * Unless the request method was HEAD, the entity of the
  4005. * response SHOULD contain a short hypertext note with a hyperlink to
  4006. * the new URI(s).
  4007. *
  4008. * However, this response body is not useful in M2M communication.
  4009. * Probably the original reason in the RFC was, clients not supporting
  4010. * a 30x HTTP redirect could still show the HTML page and let the user
  4011. * press the link. Since current browsers support 30x HTTP, the additional
  4012. * HTML body does not seem to make sense anymore.
  4013. *
  4014. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4015. * but it only notes:
  4016. * The server's response payload usually contains a short
  4017. * hypertext note with a hyperlink to the new URI(s).
  4018. *
  4019. * Deactivated by default. If you need the 30x body, set the define.
  4020. */
  4021. mg_snprintf(
  4022. conn,
  4023. NULL /* ignore truncation */,
  4024. reply,
  4025. sizeof(reply),
  4026. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4027. redirect_text,
  4028. target_url,
  4029. target_url);
  4030. content_len = strlen(reply);
  4031. #else
  4032. reply[0] = 0;
  4033. #endif
  4034. /* Do not send any additional header. For all other options,
  4035. * including caching, there are suitable defaults. */
  4036. ret = mg_printf(conn,
  4037. "HTTP/1.1 %i %s\r\n"
  4038. "Location: %s\r\n"
  4039. "Content-Length: %u\r\n"
  4040. "Connection: %s\r\n\r\n",
  4041. redirect_code,
  4042. redirect_text,
  4043. target_url,
  4044. (unsigned int)content_len,
  4045. suggest_connection_header(conn));
  4046. /* Send response body */
  4047. if (ret > 0) {
  4048. /* ... unless it is a HEAD request */
  4049. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4050. ret = mg_write(conn, reply, content_len);
  4051. }
  4052. }
  4053. return (ret > 0) ? ret : -1;
  4054. }
  4055. #if defined(_WIN32)
  4056. /* Create substitutes for POSIX functions in Win32. */
  4057. #if defined(__MINGW32__)
  4058. /* Show no warning in case system functions are not used. */
  4059. #pragma GCC diagnostic push
  4060. #pragma GCC diagnostic ignored "-Wunused-function"
  4061. #endif
  4062. FUNCTION_MAY_BE_UNUSED
  4063. static int
  4064. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4065. {
  4066. (void)unused;
  4067. *mutex = CreateMutex(NULL, FALSE, NULL);
  4068. return (*mutex == NULL) ? -1 : 0;
  4069. }
  4070. FUNCTION_MAY_BE_UNUSED
  4071. static int
  4072. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4073. {
  4074. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  4075. }
  4076. FUNCTION_MAY_BE_UNUSED
  4077. static int
  4078. pthread_mutex_lock(pthread_mutex_t *mutex)
  4079. {
  4080. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  4081. : -1;
  4082. }
  4083. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  4084. FUNCTION_MAY_BE_UNUSED
  4085. static int
  4086. pthread_mutex_trylock(pthread_mutex_t *mutex)
  4087. {
  4088. switch (WaitForSingleObject(*mutex, 0)) {
  4089. case WAIT_OBJECT_0:
  4090. return 0;
  4091. case WAIT_TIMEOUT:
  4092. return -2; /* EBUSY */
  4093. }
  4094. return -1;
  4095. }
  4096. #endif
  4097. FUNCTION_MAY_BE_UNUSED
  4098. static int
  4099. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4100. {
  4101. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  4102. }
  4103. FUNCTION_MAY_BE_UNUSED
  4104. static int
  4105. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4106. {
  4107. (void)unused;
  4108. InitializeCriticalSection(&cv->threadIdSec);
  4109. cv->waiting_thread = NULL;
  4110. return 0;
  4111. }
  4112. FUNCTION_MAY_BE_UNUSED
  4113. static int
  4114. pthread_cond_timedwait(pthread_cond_t *cv,
  4115. pthread_mutex_t *mutex,
  4116. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4117. {
  4118. struct mg_workerTLS **ptls,
  4119. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4120. int ok;
  4121. int64_t nsnow, nswaitabs, nswaitrel;
  4122. DWORD mswaitrel;
  4123. EnterCriticalSection(&cv->threadIdSec);
  4124. /* Add this thread to cv's waiting list */
  4125. ptls = &cv->waiting_thread;
  4126. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4127. ;
  4128. tls->next_waiting_thread = NULL;
  4129. *ptls = tls;
  4130. LeaveCriticalSection(&cv->threadIdSec);
  4131. if (abstime) {
  4132. nsnow = mg_get_current_time_ns();
  4133. nswaitabs =
  4134. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4135. nswaitrel = nswaitabs - nsnow;
  4136. if (nswaitrel < 0) {
  4137. nswaitrel = 0;
  4138. }
  4139. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4140. } else {
  4141. mswaitrel = (DWORD)INFINITE;
  4142. }
  4143. pthread_mutex_unlock(mutex);
  4144. ok = (WAIT_OBJECT_0
  4145. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4146. if (!ok) {
  4147. ok = 1;
  4148. EnterCriticalSection(&cv->threadIdSec);
  4149. ptls = &cv->waiting_thread;
  4150. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4151. if (*ptls == tls) {
  4152. *ptls = tls->next_waiting_thread;
  4153. ok = 0;
  4154. break;
  4155. }
  4156. }
  4157. LeaveCriticalSection(&cv->threadIdSec);
  4158. if (ok) {
  4159. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4160. (DWORD)INFINITE);
  4161. }
  4162. }
  4163. /* This thread has been removed from cv's waiting list */
  4164. pthread_mutex_lock(mutex);
  4165. return ok ? 0 : -1;
  4166. }
  4167. FUNCTION_MAY_BE_UNUSED
  4168. static int
  4169. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4170. {
  4171. return pthread_cond_timedwait(cv, mutex, NULL);
  4172. }
  4173. FUNCTION_MAY_BE_UNUSED
  4174. static int
  4175. pthread_cond_signal(pthread_cond_t *cv)
  4176. {
  4177. HANDLE wkup = NULL;
  4178. BOOL ok = FALSE;
  4179. EnterCriticalSection(&cv->threadIdSec);
  4180. if (cv->waiting_thread) {
  4181. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4182. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4183. ok = SetEvent(wkup);
  4184. DEBUG_ASSERT(ok);
  4185. }
  4186. LeaveCriticalSection(&cv->threadIdSec);
  4187. return ok ? 0 : 1;
  4188. }
  4189. FUNCTION_MAY_BE_UNUSED
  4190. static int
  4191. pthread_cond_broadcast(pthread_cond_t *cv)
  4192. {
  4193. EnterCriticalSection(&cv->threadIdSec);
  4194. while (cv->waiting_thread) {
  4195. pthread_cond_signal(cv);
  4196. }
  4197. LeaveCriticalSection(&cv->threadIdSec);
  4198. return 0;
  4199. }
  4200. FUNCTION_MAY_BE_UNUSED
  4201. static int
  4202. pthread_cond_destroy(pthread_cond_t *cv)
  4203. {
  4204. EnterCriticalSection(&cv->threadIdSec);
  4205. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4206. LeaveCriticalSection(&cv->threadIdSec);
  4207. DeleteCriticalSection(&cv->threadIdSec);
  4208. return 0;
  4209. }
  4210. #if defined(ALTERNATIVE_QUEUE)
  4211. FUNCTION_MAY_BE_UNUSED
  4212. static void *
  4213. event_create(void)
  4214. {
  4215. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4216. }
  4217. FUNCTION_MAY_BE_UNUSED
  4218. static int
  4219. event_wait(void *eventhdl)
  4220. {
  4221. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4222. return (res == WAIT_OBJECT_0);
  4223. }
  4224. FUNCTION_MAY_BE_UNUSED
  4225. static int
  4226. event_signal(void *eventhdl)
  4227. {
  4228. return (int)SetEvent((HANDLE)eventhdl);
  4229. }
  4230. FUNCTION_MAY_BE_UNUSED
  4231. static void
  4232. event_destroy(void *eventhdl)
  4233. {
  4234. CloseHandle((HANDLE)eventhdl);
  4235. }
  4236. #endif
  4237. #if defined(__MINGW32__)
  4238. /* Enable unused function warning again */
  4239. #pragma GCC diagnostic pop
  4240. #endif
  4241. /* For Windows, change all slashes to backslashes in path names. */
  4242. static void
  4243. change_slashes_to_backslashes(char *path)
  4244. {
  4245. int i;
  4246. for (i = 0; path[i] != '\0'; i++) {
  4247. if (path[i] == '/') {
  4248. path[i] = '\\';
  4249. }
  4250. /* remove double backslash (check i > 0 to preserve UNC paths,
  4251. * like \\server\file.txt) */
  4252. if ((path[i] == '\\') && (i > 0)) {
  4253. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4254. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4255. }
  4256. }
  4257. }
  4258. }
  4259. static int
  4260. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4261. {
  4262. int diff;
  4263. do {
  4264. diff = tolower(*s1) - tolower(*s2);
  4265. s1++;
  4266. s2++;
  4267. } while ((diff == 0) && (s1[-1] != '\0'));
  4268. return diff;
  4269. }
  4270. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4271. * wbuf and wbuf_len is a target buffer and its length. */
  4272. static void
  4273. path_to_unicode(const struct mg_connection *conn,
  4274. const char *path,
  4275. wchar_t *wbuf,
  4276. size_t wbuf_len)
  4277. {
  4278. char buf[PATH_MAX], buf2[PATH_MAX];
  4279. wchar_t wbuf2[W_PATH_MAX + 1];
  4280. DWORD long_len, err;
  4281. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4282. mg_strlcpy(buf, path, sizeof(buf));
  4283. change_slashes_to_backslashes(buf);
  4284. /* Convert to Unicode and back. If doubly-converted string does not
  4285. * match the original, something is fishy, reject. */
  4286. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4287. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4288. WideCharToMultiByte(
  4289. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4290. if (strcmp(buf, buf2) != 0) {
  4291. wbuf[0] = L'\0';
  4292. }
  4293. /* Windows file systems are not case sensitive, but you can still use
  4294. * uppercase and lowercase letters (on all modern file systems).
  4295. * The server can check if the URI uses the same upper/lowercase
  4296. * letters an the file system, effectively making Windows servers
  4297. * case sensitive (like Linux servers are). It is still not possible
  4298. * to use two files with the same name in different cases on Windows
  4299. * (like /a and /A) - this would be possible in Linux.
  4300. * As a default, Windows is not case sensitive, but the case sensitive
  4301. * file name check can be activated by an additional configuration. */
  4302. if (conn) {
  4303. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4304. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4305. "yes")) {
  4306. /* Use case sensitive compare function */
  4307. fcompare = wcscmp;
  4308. }
  4309. }
  4310. (void)conn; /* conn is currently unused */
  4311. #if !defined(_WIN32_WCE)
  4312. /* Only accept a full file path, not a Windows short (8.3) path. */
  4313. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4314. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4315. if (long_len == 0) {
  4316. err = GetLastError();
  4317. if (err == ERROR_FILE_NOT_FOUND) {
  4318. /* File does not exist. This is not always a problem here. */
  4319. return;
  4320. }
  4321. }
  4322. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4323. /* Short name is used. */
  4324. wbuf[0] = L'\0';
  4325. }
  4326. #else
  4327. (void)long_len;
  4328. (void)wbuf2;
  4329. (void)err;
  4330. if (strchr(path, '~')) {
  4331. wbuf[0] = L'\0';
  4332. }
  4333. #endif
  4334. }
  4335. /* Windows happily opens files with some garbage at the end of file name.
  4336. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4337. * "a.cgi", despite one would expect an error back.
  4338. * This function returns non-0 if path ends with some garbage. */
  4339. static int
  4340. path_cannot_disclose_cgi(const char *path)
  4341. {
  4342. static const char *allowed_last_characters = "_-";
  4343. int last = path[strlen(path) - 1];
  4344. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4345. }
  4346. static int
  4347. mg_stat(const struct mg_connection *conn,
  4348. const char *path,
  4349. struct mg_file_stat *filep)
  4350. {
  4351. wchar_t wbuf[W_PATH_MAX];
  4352. WIN32_FILE_ATTRIBUTE_DATA info;
  4353. time_t creation_time;
  4354. if (!filep) {
  4355. return 0;
  4356. }
  4357. memset(filep, 0, sizeof(*filep));
  4358. if (conn && is_file_in_memory(conn, path)) {
  4359. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4360. * memset */
  4361. /* Quick fix (for 1.9.x): */
  4362. /* mg_stat must fill all fields, also for files in memory */
  4363. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4364. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4365. filep->size = tmp_file.stat.size;
  4366. filep->location = 2;
  4367. /* TODO: for 1.10: restructure how files in memory are handled */
  4368. /* The "file in memory" feature is a candidate for deletion.
  4369. * Please join the discussion at
  4370. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4371. */
  4372. filep->last_modified = time(NULL); /* TODO */
  4373. /* last_modified = now ... assumes the file may change during
  4374. * runtime,
  4375. * so every mg_fopen call may return different data */
  4376. /* last_modified = conn->phys_ctx.start_time;
  4377. * May be used it the data does not change during runtime. This
  4378. * allows
  4379. * browser caching. Since we do not know, we have to assume the file
  4380. * in memory may change. */
  4381. return 1;
  4382. }
  4383. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4384. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4385. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4386. filep->last_modified =
  4387. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4388. info.ftLastWriteTime.dwHighDateTime);
  4389. /* On Windows, the file creation time can be higher than the
  4390. * modification time, e.g. when a file is copied.
  4391. * Since the Last-Modified timestamp is used for caching
  4392. * it should be based on the most recent timestamp. */
  4393. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4394. info.ftCreationTime.dwHighDateTime);
  4395. if (creation_time > filep->last_modified) {
  4396. filep->last_modified = creation_time;
  4397. }
  4398. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4399. /* If file name is fishy, reset the file structure and return
  4400. * error.
  4401. * Note it is important to reset, not just return the error, cause
  4402. * functions like is_file_opened() check the struct. */
  4403. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4404. memset(filep, 0, sizeof(*filep));
  4405. return 0;
  4406. }
  4407. return 1;
  4408. }
  4409. return 0;
  4410. }
  4411. static int
  4412. mg_remove(const struct mg_connection *conn, const char *path)
  4413. {
  4414. wchar_t wbuf[W_PATH_MAX];
  4415. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4416. return DeleteFileW(wbuf) ? 0 : -1;
  4417. }
  4418. static int
  4419. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4420. {
  4421. wchar_t wbuf[W_PATH_MAX];
  4422. (void)mode;
  4423. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4424. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4425. }
  4426. /* Create substitutes for POSIX functions in Win32. */
  4427. #if defined(__MINGW32__)
  4428. /* Show no warning in case system functions are not used. */
  4429. #pragma GCC diagnostic push
  4430. #pragma GCC diagnostic ignored "-Wunused-function"
  4431. #endif
  4432. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4433. FUNCTION_MAY_BE_UNUSED
  4434. static DIR *
  4435. mg_opendir(const struct mg_connection *conn, const char *name)
  4436. {
  4437. DIR *dir = NULL;
  4438. wchar_t wpath[W_PATH_MAX];
  4439. DWORD attrs;
  4440. if (name == NULL) {
  4441. SetLastError(ERROR_BAD_ARGUMENTS);
  4442. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4443. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4444. } else {
  4445. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4446. attrs = GetFileAttributesW(wpath);
  4447. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4448. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4449. (void)wcscat(wpath, L"\\*");
  4450. dir->handle = FindFirstFileW(wpath, &dir->info);
  4451. dir->result.d_name[0] = '\0';
  4452. } else {
  4453. mg_free(dir);
  4454. dir = NULL;
  4455. }
  4456. }
  4457. return dir;
  4458. }
  4459. FUNCTION_MAY_BE_UNUSED
  4460. static int
  4461. mg_closedir(DIR *dir)
  4462. {
  4463. int result = 0;
  4464. if (dir != NULL) {
  4465. if (dir->handle != INVALID_HANDLE_VALUE)
  4466. result = FindClose(dir->handle) ? 0 : -1;
  4467. mg_free(dir);
  4468. } else {
  4469. result = -1;
  4470. SetLastError(ERROR_BAD_ARGUMENTS);
  4471. }
  4472. return result;
  4473. }
  4474. FUNCTION_MAY_BE_UNUSED
  4475. static struct dirent *
  4476. mg_readdir(DIR *dir)
  4477. {
  4478. struct dirent *result = 0;
  4479. if (dir) {
  4480. if (dir->handle != INVALID_HANDLE_VALUE) {
  4481. result = &dir->result;
  4482. (void)WideCharToMultiByte(CP_UTF8,
  4483. 0,
  4484. dir->info.cFileName,
  4485. -1,
  4486. result->d_name,
  4487. sizeof(result->d_name),
  4488. NULL,
  4489. NULL);
  4490. if (!FindNextFileW(dir->handle, &dir->info)) {
  4491. (void)FindClose(dir->handle);
  4492. dir->handle = INVALID_HANDLE_VALUE;
  4493. }
  4494. } else {
  4495. SetLastError(ERROR_FILE_NOT_FOUND);
  4496. }
  4497. } else {
  4498. SetLastError(ERROR_BAD_ARGUMENTS);
  4499. }
  4500. return result;
  4501. }
  4502. #if !defined(HAVE_POLL)
  4503. #define POLLIN (1) /* Data ready - read will not block. */
  4504. #define POLLPRI (2) /* Priority data ready. */
  4505. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4506. FUNCTION_MAY_BE_UNUSED
  4507. static int
  4508. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4509. {
  4510. struct timeval tv;
  4511. fd_set rset;
  4512. fd_set wset;
  4513. unsigned int i;
  4514. int result;
  4515. SOCKET maxfd = 0;
  4516. memset(&tv, 0, sizeof(tv));
  4517. tv.tv_sec = milliseconds / 1000;
  4518. tv.tv_usec = (milliseconds % 1000) * 1000;
  4519. FD_ZERO(&rset);
  4520. FD_ZERO(&wset);
  4521. for (i = 0; i < n; i++) {
  4522. if (pfd[i].events & POLLIN) {
  4523. FD_SET((SOCKET)pfd[i].fd, &rset);
  4524. } else if (pfd[i].events & POLLOUT) {
  4525. FD_SET((SOCKET)pfd[i].fd, &wset);
  4526. }
  4527. pfd[i].revents = 0;
  4528. if (pfd[i].fd > maxfd) {
  4529. maxfd = pfd[i].fd;
  4530. }
  4531. }
  4532. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4533. for (i = 0; i < n; i++) {
  4534. if (FD_ISSET(pfd[i].fd, &rset)) {
  4535. pfd[i].revents |= POLLIN;
  4536. }
  4537. if (FD_ISSET(pfd[i].fd, &wset)) {
  4538. pfd[i].revents |= POLLOUT;
  4539. }
  4540. }
  4541. }
  4542. /* We should subtract the time used in select from remaining
  4543. * "milliseconds", in particular if called from mg_poll with a
  4544. * timeout quantum.
  4545. * Unfortunately, the remaining time is not stored in "tv" in all
  4546. * implementations, so the result in "tv" must be considered undefined.
  4547. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4548. return result;
  4549. }
  4550. #endif /* HAVE_POLL */
  4551. #if defined(__MINGW32__)
  4552. /* Enable unused function warning again */
  4553. #pragma GCC diagnostic pop
  4554. #endif
  4555. static void
  4556. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4557. {
  4558. (void)conn; /* Unused. */
  4559. #if defined(_WIN32_WCE)
  4560. (void)sock;
  4561. #else
  4562. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4563. #endif
  4564. }
  4565. int
  4566. mg_start_thread(mg_thread_func_t f, void *p)
  4567. {
  4568. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4569. /* Compile-time option to control stack size, e.g.
  4570. * -DUSE_STACK_SIZE=16384
  4571. */
  4572. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4573. == ((uintptr_t)(-1L)))
  4574. ? -1
  4575. : 0);
  4576. #else
  4577. return (
  4578. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4579. ? -1
  4580. : 0);
  4581. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4582. }
  4583. /* Start a thread storing the thread context. */
  4584. static int
  4585. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4586. void *p,
  4587. pthread_t *threadidptr)
  4588. {
  4589. uintptr_t uip;
  4590. HANDLE threadhandle;
  4591. int result = -1;
  4592. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4593. threadhandle = (HANDLE)uip;
  4594. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4595. *threadidptr = threadhandle;
  4596. result = 0;
  4597. }
  4598. return result;
  4599. }
  4600. /* Wait for a thread to finish. */
  4601. static int
  4602. mg_join_thread(pthread_t threadid)
  4603. {
  4604. int result;
  4605. DWORD dwevent;
  4606. result = -1;
  4607. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4608. if (dwevent == WAIT_FAILED) {
  4609. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4610. } else {
  4611. if (dwevent == WAIT_OBJECT_0) {
  4612. CloseHandle(threadid);
  4613. result = 0;
  4614. }
  4615. }
  4616. return result;
  4617. }
  4618. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4619. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4620. /* Create substitutes for POSIX functions in Win32. */
  4621. #if defined(__MINGW32__)
  4622. /* Show no warning in case system functions are not used. */
  4623. #pragma GCC diagnostic push
  4624. #pragma GCC diagnostic ignored "-Wunused-function"
  4625. #endif
  4626. FUNCTION_MAY_BE_UNUSED
  4627. static HANDLE
  4628. dlopen(const char *dll_name, int flags)
  4629. {
  4630. wchar_t wbuf[W_PATH_MAX];
  4631. (void)flags;
  4632. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4633. return LoadLibraryW(wbuf);
  4634. }
  4635. FUNCTION_MAY_BE_UNUSED
  4636. static int
  4637. dlclose(void *handle)
  4638. {
  4639. int result;
  4640. if (FreeLibrary((HMODULE)handle) != 0) {
  4641. result = 0;
  4642. } else {
  4643. result = -1;
  4644. }
  4645. return result;
  4646. }
  4647. #if defined(__MINGW32__)
  4648. /* Enable unused function warning again */
  4649. #pragma GCC diagnostic pop
  4650. #endif
  4651. #endif
  4652. #if !defined(NO_CGI)
  4653. #define SIGKILL (0)
  4654. static int
  4655. kill(pid_t pid, int sig_num)
  4656. {
  4657. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4658. (void)CloseHandle((HANDLE)pid);
  4659. return 0;
  4660. }
  4661. #ifndef WNOHANG
  4662. #define WNOHANG (1)
  4663. #endif
  4664. static pid_t
  4665. waitpid(pid_t pid, int *status, int flags)
  4666. {
  4667. DWORD timeout = INFINITE;
  4668. DWORD waitres;
  4669. (void)status; /* Currently not used by any client here */
  4670. if ((flags | WNOHANG) == WNOHANG) {
  4671. timeout = 0;
  4672. }
  4673. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4674. if (waitres == WAIT_OBJECT_0) {
  4675. return pid;
  4676. }
  4677. if (waitres == WAIT_TIMEOUT) {
  4678. return 0;
  4679. }
  4680. return (pid_t)-1;
  4681. }
  4682. static void
  4683. trim_trailing_whitespaces(char *s)
  4684. {
  4685. char *e = s + strlen(s) - 1;
  4686. while ((e > s) && isspace(*(unsigned char *)e)) {
  4687. *e-- = '\0';
  4688. }
  4689. }
  4690. static pid_t
  4691. spawn_process(struct mg_connection *conn,
  4692. const char *prog,
  4693. char *envblk,
  4694. char *envp[],
  4695. int fdin[2],
  4696. int fdout[2],
  4697. int fderr[2],
  4698. const char *dir)
  4699. {
  4700. HANDLE me;
  4701. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4702. cmdline[PATH_MAX], buf[PATH_MAX];
  4703. int truncated;
  4704. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4705. STARTUPINFOA si;
  4706. PROCESS_INFORMATION pi = {0};
  4707. (void)envp;
  4708. memset(&si, 0, sizeof(si));
  4709. si.cb = sizeof(si);
  4710. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4711. si.wShowWindow = SW_HIDE;
  4712. me = GetCurrentProcess();
  4713. DuplicateHandle(me,
  4714. (HANDLE)_get_osfhandle(fdin[0]),
  4715. me,
  4716. &si.hStdInput,
  4717. 0,
  4718. TRUE,
  4719. DUPLICATE_SAME_ACCESS);
  4720. DuplicateHandle(me,
  4721. (HANDLE)_get_osfhandle(fdout[1]),
  4722. me,
  4723. &si.hStdOutput,
  4724. 0,
  4725. TRUE,
  4726. DUPLICATE_SAME_ACCESS);
  4727. DuplicateHandle(me,
  4728. (HANDLE)_get_osfhandle(fderr[1]),
  4729. me,
  4730. &si.hStdError,
  4731. 0,
  4732. TRUE,
  4733. DUPLICATE_SAME_ACCESS);
  4734. /* Mark handles that should not be inherited. See
  4735. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4736. */
  4737. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4738. HANDLE_FLAG_INHERIT,
  4739. 0);
  4740. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4741. HANDLE_FLAG_INHERIT,
  4742. 0);
  4743. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4744. HANDLE_FLAG_INHERIT,
  4745. 0);
  4746. /* If CGI file is a script, try to read the interpreter line */
  4747. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4748. if (interp == NULL) {
  4749. buf[0] = buf[1] = '\0';
  4750. /* Read the first line of the script into the buffer */
  4751. mg_snprintf(
  4752. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4753. if (truncated) {
  4754. pi.hProcess = (pid_t)-1;
  4755. goto spawn_cleanup;
  4756. }
  4757. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4758. #if defined(MG_USE_OPEN_FILE)
  4759. p = (char *)file.access.membuf;
  4760. #else
  4761. p = (char *)NULL;
  4762. #endif
  4763. mg_fgets(buf, sizeof(buf), &file, &p);
  4764. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4765. buf[sizeof(buf) - 1] = '\0';
  4766. }
  4767. if ((buf[0] == '#') && (buf[1] == '!')) {
  4768. trim_trailing_whitespaces(buf + 2);
  4769. } else {
  4770. buf[2] = '\0';
  4771. }
  4772. interp = buf + 2;
  4773. }
  4774. if (interp[0] != '\0') {
  4775. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4776. interp = full_interp;
  4777. }
  4778. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4779. if (interp[0] != '\0') {
  4780. mg_snprintf(conn,
  4781. &truncated,
  4782. cmdline,
  4783. sizeof(cmdline),
  4784. "\"%s\" \"%s\\%s\"",
  4785. interp,
  4786. full_dir,
  4787. prog);
  4788. } else {
  4789. mg_snprintf(conn,
  4790. &truncated,
  4791. cmdline,
  4792. sizeof(cmdline),
  4793. "\"%s\\%s\"",
  4794. full_dir,
  4795. prog);
  4796. }
  4797. if (truncated) {
  4798. pi.hProcess = (pid_t)-1;
  4799. goto spawn_cleanup;
  4800. }
  4801. DEBUG_TRACE("Running [%s]", cmdline);
  4802. if (CreateProcessA(NULL,
  4803. cmdline,
  4804. NULL,
  4805. NULL,
  4806. TRUE,
  4807. CREATE_NEW_PROCESS_GROUP,
  4808. envblk,
  4809. NULL,
  4810. &si,
  4811. &pi) == 0) {
  4812. mg_cry_internal(
  4813. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4814. pi.hProcess = (pid_t)-1;
  4815. /* goto spawn_cleanup; */
  4816. }
  4817. spawn_cleanup:
  4818. (void)CloseHandle(si.hStdOutput);
  4819. (void)CloseHandle(si.hStdError);
  4820. (void)CloseHandle(si.hStdInput);
  4821. if (pi.hThread != NULL) {
  4822. (void)CloseHandle(pi.hThread);
  4823. }
  4824. return (pid_t)pi.hProcess;
  4825. }
  4826. #endif /* !NO_CGI */
  4827. static int
  4828. set_blocking_mode(SOCKET sock)
  4829. {
  4830. unsigned long non_blocking = 0;
  4831. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4832. }
  4833. static int
  4834. set_non_blocking_mode(SOCKET sock)
  4835. {
  4836. unsigned long non_blocking = 1;
  4837. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4838. }
  4839. #else
  4840. static int
  4841. mg_stat(const struct mg_connection *conn,
  4842. const char *path,
  4843. struct mg_file_stat *filep)
  4844. {
  4845. struct stat st;
  4846. if (!filep) {
  4847. return 0;
  4848. }
  4849. memset(filep, 0, sizeof(*filep));
  4850. if (conn && is_file_in_memory(conn, path)) {
  4851. /* Quick fix (for 1.9.x): */
  4852. /* mg_stat must fill all fields, also for files in memory */
  4853. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4854. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4855. filep->size = tmp_file.stat.size;
  4856. filep->last_modified = time(NULL);
  4857. filep->location = 2;
  4858. /* TODO: remove legacy "files in memory" feature */
  4859. return 1;
  4860. }
  4861. if (0 == stat(path, &st)) {
  4862. filep->size = (uint64_t)(st.st_size);
  4863. filep->last_modified = st.st_mtime;
  4864. filep->is_directory = S_ISDIR(st.st_mode);
  4865. return 1;
  4866. }
  4867. return 0;
  4868. }
  4869. static void
  4870. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4871. {
  4872. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4873. if (conn) {
  4874. mg_cry_internal(conn,
  4875. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4876. __func__,
  4877. strerror(ERRNO));
  4878. }
  4879. }
  4880. }
  4881. int
  4882. mg_start_thread(mg_thread_func_t func, void *param)
  4883. {
  4884. pthread_t thread_id;
  4885. pthread_attr_t attr;
  4886. int result;
  4887. (void)pthread_attr_init(&attr);
  4888. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4889. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4890. /* Compile-time option to control stack size,
  4891. * e.g. -DUSE_STACK_SIZE=16384 */
  4892. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4893. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4894. result = pthread_create(&thread_id, &attr, func, param);
  4895. pthread_attr_destroy(&attr);
  4896. return result;
  4897. }
  4898. /* Start a thread storing the thread context. */
  4899. static int
  4900. mg_start_thread_with_id(mg_thread_func_t func,
  4901. void *param,
  4902. pthread_t *threadidptr)
  4903. {
  4904. pthread_t thread_id;
  4905. pthread_attr_t attr;
  4906. int result;
  4907. (void)pthread_attr_init(&attr);
  4908. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4909. /* Compile-time option to control stack size,
  4910. * e.g. -DUSE_STACK_SIZE=16384 */
  4911. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4912. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4913. result = pthread_create(&thread_id, &attr, func, param);
  4914. pthread_attr_destroy(&attr);
  4915. if ((result == 0) && (threadidptr != NULL)) {
  4916. *threadidptr = thread_id;
  4917. }
  4918. return result;
  4919. }
  4920. /* Wait for a thread to finish. */
  4921. static int
  4922. mg_join_thread(pthread_t threadid)
  4923. {
  4924. int result;
  4925. result = pthread_join(threadid, NULL);
  4926. return result;
  4927. }
  4928. #if !defined(NO_CGI)
  4929. static pid_t
  4930. spawn_process(struct mg_connection *conn,
  4931. const char *prog,
  4932. char *envblk,
  4933. char *envp[],
  4934. int fdin[2],
  4935. int fdout[2],
  4936. int fderr[2],
  4937. const char *dir)
  4938. {
  4939. pid_t pid;
  4940. const char *interp;
  4941. (void)envblk;
  4942. if (conn == NULL) {
  4943. return 0;
  4944. }
  4945. if ((pid = fork()) == -1) {
  4946. /* Parent */
  4947. mg_send_http_error(conn,
  4948. 500,
  4949. "Error: Creating CGI process\nfork(): %s",
  4950. strerror(ERRNO));
  4951. } else if (pid == 0) {
  4952. /* Child */
  4953. if (chdir(dir) != 0) {
  4954. mg_cry_internal(
  4955. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4956. } else if (dup2(fdin[0], 0) == -1) {
  4957. mg_cry_internal(conn,
  4958. "%s: dup2(%d, 0): %s",
  4959. __func__,
  4960. fdin[0],
  4961. strerror(ERRNO));
  4962. } else if (dup2(fdout[1], 1) == -1) {
  4963. mg_cry_internal(conn,
  4964. "%s: dup2(%d, 1): %s",
  4965. __func__,
  4966. fdout[1],
  4967. strerror(ERRNO));
  4968. } else if (dup2(fderr[1], 2) == -1) {
  4969. mg_cry_internal(conn,
  4970. "%s: dup2(%d, 2): %s",
  4971. __func__,
  4972. fderr[1],
  4973. strerror(ERRNO));
  4974. } else {
  4975. /* Keep stderr and stdout in two different pipes.
  4976. * Stdout will be sent back to the client,
  4977. * stderr should go into a server error log. */
  4978. (void)close(fdin[0]);
  4979. (void)close(fdout[1]);
  4980. (void)close(fderr[1]);
  4981. /* Close write end fdin and read end fdout and fderr */
  4982. (void)close(fdin[1]);
  4983. (void)close(fdout[0]);
  4984. (void)close(fderr[0]);
  4985. /* After exec, all signal handlers are restored to their default
  4986. * values, with one exception of SIGCHLD. According to
  4987. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4988. * will leave unchanged after exec if it was set to be ignored.
  4989. * Restore it to default action. */
  4990. signal(SIGCHLD, SIG_DFL);
  4991. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4992. if (interp == NULL) {
  4993. (void)execle(prog, prog, NULL, envp);
  4994. mg_cry_internal(conn,
  4995. "%s: execle(%s): %s",
  4996. __func__,
  4997. prog,
  4998. strerror(ERRNO));
  4999. } else {
  5000. (void)execle(interp, interp, prog, NULL, envp);
  5001. mg_cry_internal(conn,
  5002. "%s: execle(%s %s): %s",
  5003. __func__,
  5004. interp,
  5005. prog,
  5006. strerror(ERRNO));
  5007. }
  5008. }
  5009. exit(EXIT_FAILURE);
  5010. }
  5011. return pid;
  5012. }
  5013. #endif /* !NO_CGI */
  5014. static int
  5015. set_non_blocking_mode(SOCKET sock)
  5016. {
  5017. int flags = fcntl(sock, F_GETFL, 0);
  5018. if (flags < 0) {
  5019. return -1;
  5020. }
  5021. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5022. return -1;
  5023. }
  5024. return 0;
  5025. }
  5026. static int
  5027. set_blocking_mode(SOCKET sock)
  5028. {
  5029. int flags = fcntl(sock, F_GETFL, 0);
  5030. if (flags < 0) {
  5031. return -1;
  5032. }
  5033. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5034. return -1;
  5035. }
  5036. return 0;
  5037. }
  5038. #endif /* _WIN32 / else */
  5039. /* End of initial operating system specific define block. */
  5040. /* Get a random number (independent of C rand function) */
  5041. static uint64_t
  5042. get_random(void)
  5043. {
  5044. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5045. static uint64_t lcg = 0; /* Linear congruential generator */
  5046. uint64_t now = mg_get_current_time_ns();
  5047. if (lfsr == 0) {
  5048. /* lfsr will be only 0 if has not been initialized,
  5049. * so this code is called only once. */
  5050. lfsr = mg_get_current_time_ns();
  5051. lcg = mg_get_current_time_ns();
  5052. } else {
  5053. /* Get the next step of both random number generators. */
  5054. lfsr = (lfsr >> 1)
  5055. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5056. << 63);
  5057. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5058. }
  5059. /* Combining two pseudo-random number generators and a high resolution
  5060. * part
  5061. * of the current server time will make it hard (impossible?) to guess
  5062. * the
  5063. * next number. */
  5064. return (lfsr ^ lcg ^ now);
  5065. }
  5066. static int
  5067. mg_poll(struct pollfd *pfd,
  5068. unsigned int n,
  5069. int milliseconds,
  5070. volatile int *stop_server)
  5071. {
  5072. /* Call poll, but only for a maximum time of a few seconds.
  5073. * This will allow to stop the server after some seconds, instead
  5074. * of having to wait for a long socket timeout. */
  5075. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5076. do {
  5077. int result;
  5078. if (*stop_server) {
  5079. /* Shut down signal */
  5080. return -2;
  5081. }
  5082. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5083. ms_now = milliseconds;
  5084. }
  5085. result = poll(pfd, n, ms_now);
  5086. if (result != 0) {
  5087. /* Poll returned either success (1) or error (-1).
  5088. * Forward both to the caller. */
  5089. return result;
  5090. }
  5091. /* Poll returned timeout (0). */
  5092. if (milliseconds > 0) {
  5093. milliseconds -= ms_now;
  5094. }
  5095. } while (milliseconds != 0);
  5096. /* timeout: return 0 */
  5097. return 0;
  5098. }
  5099. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5100. * descriptor.
  5101. * Return value:
  5102. * >=0 .. number of bytes successfully written
  5103. * -1 .. timeout
  5104. * -2 .. error
  5105. */
  5106. static int
  5107. push_inner(struct mg_context *ctx,
  5108. FILE *fp,
  5109. SOCKET sock,
  5110. SSL *ssl,
  5111. const char *buf,
  5112. int len,
  5113. double timeout)
  5114. {
  5115. uint64_t start = 0, now = 0, timeout_ns = 0;
  5116. int n, err;
  5117. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5118. #if defined(_WIN32)
  5119. typedef int len_t;
  5120. #else
  5121. typedef size_t len_t;
  5122. #endif
  5123. if (timeout > 0) {
  5124. now = mg_get_current_time_ns();
  5125. start = now;
  5126. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5127. }
  5128. if (ctx == NULL) {
  5129. return -2;
  5130. }
  5131. #if defined(NO_SSL)
  5132. if (ssl) {
  5133. return -2;
  5134. }
  5135. #endif
  5136. /* Try to read until it succeeds, fails, times out, or the server
  5137. * shuts down. */
  5138. for (;;) {
  5139. #if !defined(NO_SSL)
  5140. if (ssl != NULL) {
  5141. n = SSL_write(ssl, buf, len);
  5142. if (n <= 0) {
  5143. err = SSL_get_error(ssl, n);
  5144. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5145. err = ERRNO;
  5146. } else if ((err == SSL_ERROR_WANT_READ)
  5147. || (err == SSL_ERROR_WANT_WRITE)) {
  5148. n = 0;
  5149. } else {
  5150. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5151. return -2;
  5152. }
  5153. } else {
  5154. err = 0;
  5155. }
  5156. } else
  5157. #endif
  5158. if (fp != NULL) {
  5159. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5160. if (ferror(fp)) {
  5161. n = -1;
  5162. err = ERRNO;
  5163. } else {
  5164. err = 0;
  5165. }
  5166. } else {
  5167. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5168. err = (n < 0) ? ERRNO : 0;
  5169. #if defined(_WIN32)
  5170. if (err == WSAEWOULDBLOCK) {
  5171. err = 0;
  5172. n = 0;
  5173. }
  5174. #else
  5175. if (err == EWOULDBLOCK) {
  5176. err = 0;
  5177. n = 0;
  5178. }
  5179. #endif
  5180. if (n < 0) {
  5181. /* shutdown of the socket at client side */
  5182. return -2;
  5183. }
  5184. }
  5185. if (ctx->stop_flag) {
  5186. return -2;
  5187. }
  5188. if ((n > 0) || ((n == 0) && (len == 0))) {
  5189. /* some data has been read, or no data was requested */
  5190. return n;
  5191. }
  5192. if (n < 0) {
  5193. /* socket error - check errno */
  5194. DEBUG_TRACE("send() failed, error %d", err);
  5195. /* TODO (mid): error handling depending on the error code.
  5196. * These codes are different between Windows and Linux.
  5197. * Currently there is no problem with failing send calls,
  5198. * if there is a reproducible situation, it should be
  5199. * investigated in detail.
  5200. */
  5201. return -2;
  5202. }
  5203. /* Only in case n=0 (timeout), repeat calling the write function */
  5204. /* If send failed, wait before retry */
  5205. if (fp != NULL) {
  5206. /* For files, just wait a fixed time.
  5207. * Maybe it helps, maybe not. */
  5208. mg_sleep(5);
  5209. } else {
  5210. /* For sockets, wait for the socket using poll */
  5211. struct pollfd pfd[1];
  5212. int pollres;
  5213. pfd[0].fd = sock;
  5214. pfd[0].events = POLLOUT;
  5215. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5216. if (ctx->stop_flag) {
  5217. return -2;
  5218. }
  5219. if (pollres > 0) {
  5220. continue;
  5221. }
  5222. }
  5223. if (timeout > 0) {
  5224. now = mg_get_current_time_ns();
  5225. if ((now - start) > timeout_ns) {
  5226. /* Timeout */
  5227. break;
  5228. }
  5229. }
  5230. }
  5231. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5232. used */
  5233. return -1;
  5234. }
  5235. static int64_t
  5236. push_all(struct mg_context *ctx,
  5237. FILE *fp,
  5238. SOCKET sock,
  5239. SSL *ssl,
  5240. const char *buf,
  5241. int64_t len)
  5242. {
  5243. double timeout = -1.0;
  5244. int64_t n, nwritten = 0;
  5245. if (ctx == NULL) {
  5246. return -1;
  5247. }
  5248. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5249. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5250. }
  5251. while ((len > 0) && (ctx->stop_flag == 0)) {
  5252. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  5253. if (n < 0) {
  5254. if (nwritten == 0) {
  5255. nwritten = n; /* Propagate the error */
  5256. }
  5257. break;
  5258. } else if (n == 0) {
  5259. break; /* No more data to write */
  5260. } else {
  5261. nwritten += n;
  5262. len -= n;
  5263. }
  5264. }
  5265. return nwritten;
  5266. }
  5267. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5268. * Return value:
  5269. * >=0 .. number of bytes successfully read
  5270. * -1 .. timeout
  5271. * -2 .. error
  5272. */
  5273. static int
  5274. pull_inner(FILE *fp,
  5275. struct mg_connection *conn,
  5276. char *buf,
  5277. int len,
  5278. double timeout)
  5279. {
  5280. int nread, err = 0;
  5281. #if defined(_WIN32)
  5282. typedef int len_t;
  5283. #else
  5284. typedef size_t len_t;
  5285. #endif
  5286. #if !defined(NO_SSL)
  5287. int ssl_pending;
  5288. #endif
  5289. /* We need an additional wait loop around this, because in some cases
  5290. * with TLSwe may get data from the socket but not from SSL_read.
  5291. * In this case we need to repeat at least once.
  5292. */
  5293. if (fp != NULL) {
  5294. #if !defined(_WIN32_WCE)
  5295. /* Use read() instead of fread(), because if we're reading from the
  5296. * CGI pipe, fread() may block until IO buffer is filled up. We
  5297. * cannot afford to block and must pass all read bytes immediately
  5298. * to the client. */
  5299. nread = (int)read(fileno(fp), buf, (size_t)len);
  5300. #else
  5301. /* WinCE does not support CGI pipes */
  5302. nread = (int)fread(buf, 1, (size_t)len, fp);
  5303. #endif
  5304. err = (nread < 0) ? ERRNO : 0;
  5305. if ((nread == 0) && (len > 0)) {
  5306. /* Should get data, but got EOL */
  5307. return -2;
  5308. }
  5309. #if !defined(NO_SSL)
  5310. } else if ((conn->ssl != NULL)
  5311. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5312. /* We already know there is no more data buffered in conn->buf
  5313. * but there is more available in the SSL layer. So don't poll
  5314. * conn->client.sock yet. */
  5315. if (ssl_pending > len) {
  5316. ssl_pending = len;
  5317. }
  5318. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5319. if (nread <= 0) {
  5320. err = SSL_get_error(conn->ssl, nread);
  5321. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5322. err = ERRNO;
  5323. } else if ((err == SSL_ERROR_WANT_READ)
  5324. || (err == SSL_ERROR_WANT_WRITE)) {
  5325. nread = 0;
  5326. } else {
  5327. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5328. return -1;
  5329. }
  5330. } else {
  5331. err = 0;
  5332. }
  5333. } else if (conn->ssl != NULL) {
  5334. struct pollfd pfd[1];
  5335. int pollres;
  5336. pfd[0].fd = conn->client.sock;
  5337. pfd[0].events = POLLIN;
  5338. pollres = mg_poll(pfd,
  5339. 1,
  5340. (int)(timeout * 1000.0),
  5341. &(conn->phys_ctx->stop_flag));
  5342. if (conn->phys_ctx->stop_flag) {
  5343. return -2;
  5344. }
  5345. if (pollres > 0) {
  5346. nread = SSL_read(conn->ssl, buf, len);
  5347. if (nread <= 0) {
  5348. err = SSL_get_error(conn->ssl, nread);
  5349. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5350. err = ERRNO;
  5351. } else if ((err == SSL_ERROR_WANT_READ)
  5352. || (err == SSL_ERROR_WANT_WRITE)) {
  5353. nread = 0;
  5354. } else {
  5355. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5356. return -2;
  5357. }
  5358. } else {
  5359. err = 0;
  5360. }
  5361. } else if (pollres < 0) {
  5362. /* Error */
  5363. return -2;
  5364. } else {
  5365. /* pollres = 0 means timeout */
  5366. nread = 0;
  5367. }
  5368. #endif
  5369. } else {
  5370. struct pollfd pfd[1];
  5371. int pollres;
  5372. pfd[0].fd = conn->client.sock;
  5373. pfd[0].events = POLLIN;
  5374. pollres = mg_poll(pfd,
  5375. 1,
  5376. (int)(timeout * 1000.0),
  5377. &(conn->phys_ctx->stop_flag));
  5378. if (conn->phys_ctx->stop_flag) {
  5379. return -2;
  5380. }
  5381. if (pollres > 0) {
  5382. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5383. err = (nread < 0) ? ERRNO : 0;
  5384. if (nread <= 0) {
  5385. /* shutdown of the socket at client side */
  5386. return -2;
  5387. }
  5388. } else if (pollres < 0) {
  5389. /* error callint poll */
  5390. return -2;
  5391. } else {
  5392. /* pollres = 0 means timeout */
  5393. nread = 0;
  5394. }
  5395. }
  5396. if (conn->phys_ctx->stop_flag) {
  5397. return -2;
  5398. }
  5399. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5400. /* some data has been read, or no data was requested */
  5401. return nread;
  5402. }
  5403. if (nread < 0) {
  5404. /* socket error - check errno */
  5405. #if defined(_WIN32)
  5406. if (err == WSAEWOULDBLOCK) {
  5407. /* TODO (low): check if this is still required */
  5408. /* standard case if called from close_socket_gracefully */
  5409. return -2;
  5410. } else if (err == WSAETIMEDOUT) {
  5411. /* TODO (low): check if this is still required */
  5412. /* timeout is handled by the while loop */
  5413. return 0;
  5414. } else if (err == WSAECONNABORTED) {
  5415. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5416. return -2;
  5417. } else {
  5418. DEBUG_TRACE("recv() failed, error %d", err);
  5419. return -2;
  5420. }
  5421. #else
  5422. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5423. * if the timeout is reached and if the socket was set to non-
  5424. * blocking in close_socket_gracefully, so we can not distinguish
  5425. * here. We have to wait for the timeout in both cases for now.
  5426. */
  5427. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5428. /* TODO (low): check if this is still required */
  5429. /* EAGAIN/EWOULDBLOCK:
  5430. * standard case if called from close_socket_gracefully
  5431. * => should return -1 */
  5432. /* or timeout occurred
  5433. * => the code must stay in the while loop */
  5434. /* EINTR can be generated on a socket with a timeout set even
  5435. * when SA_RESTART is effective for all relevant signals
  5436. * (see signal(7)).
  5437. * => stay in the while loop */
  5438. } else {
  5439. DEBUG_TRACE("recv() failed, error %d", err);
  5440. return -2;
  5441. }
  5442. #endif
  5443. }
  5444. /* Timeout occurred, but no data available. */
  5445. return -1;
  5446. }
  5447. static int
  5448. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5449. {
  5450. int n, nread = 0;
  5451. double timeout = -1.0;
  5452. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5453. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5454. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5455. }
  5456. if (timeout >= 0.0) {
  5457. start_time = mg_get_current_time_ns();
  5458. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5459. }
  5460. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5461. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5462. if (n == -2) {
  5463. if (nread == 0) {
  5464. nread = -1; /* Propagate the error */
  5465. }
  5466. break;
  5467. } else if (n == -1) {
  5468. /* timeout */
  5469. if (timeout >= 0.0) {
  5470. now = mg_get_current_time_ns();
  5471. if ((now - start_time) <= timeout_ns) {
  5472. continue;
  5473. }
  5474. }
  5475. break;
  5476. } else if (n == 0) {
  5477. break; /* No more data to read */
  5478. } else {
  5479. conn->consumed_content += n;
  5480. nread += n;
  5481. len -= n;
  5482. }
  5483. }
  5484. return nread;
  5485. }
  5486. static void
  5487. discard_unread_request_data(struct mg_connection *conn)
  5488. {
  5489. char buf[MG_BUF_LEN];
  5490. size_t to_read;
  5491. int nread;
  5492. if (conn == NULL) {
  5493. return;
  5494. }
  5495. to_read = sizeof(buf);
  5496. if (conn->is_chunked) {
  5497. /* Chunked encoding: 3=chunk read completely
  5498. * completely */
  5499. while (conn->is_chunked != 3) {
  5500. nread = mg_read(conn, buf, to_read);
  5501. if (nread <= 0) {
  5502. break;
  5503. }
  5504. }
  5505. } else {
  5506. /* Not chunked: content length is known */
  5507. while (conn->consumed_content < conn->content_len) {
  5508. if (to_read
  5509. > (size_t)(conn->content_len - conn->consumed_content)) {
  5510. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5511. }
  5512. nread = mg_read(conn, buf, to_read);
  5513. if (nread <= 0) {
  5514. break;
  5515. }
  5516. }
  5517. }
  5518. }
  5519. static int
  5520. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5521. {
  5522. int64_t n, buffered_len, nread;
  5523. int64_t len64 =
  5524. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5525. * int, we may not read more
  5526. * bytes */
  5527. const char *body;
  5528. if (conn == NULL) {
  5529. return 0;
  5530. }
  5531. /* If Content-Length is not set for a request with body data
  5532. * (e.g., a PUT or POST request), we do not know in advance
  5533. * how much data should be read. */
  5534. if (conn->consumed_content == 0) {
  5535. if (conn->is_chunked == 1) {
  5536. conn->content_len = len64;
  5537. conn->is_chunked = 2;
  5538. } else if (conn->content_len == -1) {
  5539. /* The body data is completed when the connection
  5540. * is closed. */
  5541. conn->content_len = INT64_MAX;
  5542. conn->must_close = 1;
  5543. }
  5544. }
  5545. nread = 0;
  5546. if (conn->consumed_content < conn->content_len) {
  5547. /* Adjust number of bytes to read. */
  5548. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5549. if (left_to_read < len64) {
  5550. /* Do not read more than the total content length of the
  5551. * request.
  5552. */
  5553. len64 = left_to_read;
  5554. }
  5555. /* Return buffered data */
  5556. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5557. - conn->consumed_content;
  5558. if (buffered_len > 0) {
  5559. if (len64 < buffered_len) {
  5560. buffered_len = len64;
  5561. }
  5562. body = conn->buf + conn->request_len + conn->consumed_content;
  5563. memcpy(buf, body, (size_t)buffered_len);
  5564. len64 -= buffered_len;
  5565. conn->consumed_content += buffered_len;
  5566. nread += buffered_len;
  5567. buf = (char *)buf + buffered_len;
  5568. }
  5569. /* We have returned all buffered data. Read new data from the remote
  5570. * socket.
  5571. */
  5572. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5573. nread += n;
  5574. } else {
  5575. nread = ((nread > 0) ? nread : n);
  5576. }
  5577. }
  5578. return (int)nread;
  5579. }
  5580. static char
  5581. mg_getc(struct mg_connection *conn)
  5582. {
  5583. char c;
  5584. if (conn == NULL) {
  5585. return 0;
  5586. }
  5587. if (mg_read_inner(conn, &c, 1) <= 0) {
  5588. return (char)0;
  5589. }
  5590. return c;
  5591. }
  5592. int
  5593. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5594. {
  5595. if (len > INT_MAX) {
  5596. len = INT_MAX;
  5597. }
  5598. if (conn == NULL) {
  5599. return 0;
  5600. }
  5601. if (conn->is_chunked) {
  5602. size_t all_read = 0;
  5603. while (len > 0) {
  5604. if (conn->is_chunked == 3) {
  5605. /* No more data left to read */
  5606. return 0;
  5607. }
  5608. if (conn->chunk_remainder) {
  5609. /* copy from the remainder of the last received chunk */
  5610. long read_ret;
  5611. size_t read_now =
  5612. ((conn->chunk_remainder > len) ? (len)
  5613. : (conn->chunk_remainder));
  5614. conn->content_len += (int)read_now;
  5615. read_ret =
  5616. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5617. if (read_ret < 1) {
  5618. /* read error */
  5619. return -1;
  5620. }
  5621. all_read += (size_t)read_ret;
  5622. conn->chunk_remainder -= (size_t)read_ret;
  5623. len -= (size_t)read_ret;
  5624. if (conn->chunk_remainder == 0) {
  5625. /* Add data bytes in the current chunk have been read,
  5626. * so we are expecting \r\n now. */
  5627. char x1, x2;
  5628. conn->content_len += 2;
  5629. x1 = mg_getc(conn);
  5630. x2 = mg_getc(conn);
  5631. if ((x1 != '\r') || (x2 != '\n')) {
  5632. /* Protocol violation */
  5633. return -1;
  5634. }
  5635. }
  5636. } else {
  5637. /* fetch a new chunk */
  5638. int i = 0;
  5639. char lenbuf[64];
  5640. char *end = 0;
  5641. unsigned long chunkSize = 0;
  5642. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5643. conn->content_len++;
  5644. lenbuf[i] = mg_getc(conn);
  5645. if ((i > 0) && (lenbuf[i] == '\r')
  5646. && (lenbuf[i - 1] != '\r')) {
  5647. continue;
  5648. }
  5649. if ((i > 1) && (lenbuf[i] == '\n')
  5650. && (lenbuf[i - 1] == '\r')) {
  5651. lenbuf[i + 1] = 0;
  5652. chunkSize = strtoul(lenbuf, &end, 16);
  5653. if (chunkSize == 0) {
  5654. /* regular end of content */
  5655. conn->is_chunked = 3;
  5656. }
  5657. break;
  5658. }
  5659. if (!isxdigit(lenbuf[i])) {
  5660. /* illegal character for chunk length */
  5661. return -1;
  5662. }
  5663. }
  5664. if ((end == NULL) || (*end != '\r')) {
  5665. /* chunksize not set correctly */
  5666. return -1;
  5667. }
  5668. if (chunkSize == 0) {
  5669. break;
  5670. }
  5671. conn->chunk_remainder = chunkSize;
  5672. }
  5673. }
  5674. return (int)all_read;
  5675. }
  5676. return mg_read_inner(conn, buf, len);
  5677. }
  5678. int
  5679. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5680. {
  5681. time_t now;
  5682. int64_t n, total, allowed;
  5683. if (conn == NULL) {
  5684. return 0;
  5685. }
  5686. if (conn->throttle > 0) {
  5687. if ((now = time(NULL)) != conn->last_throttle_time) {
  5688. conn->last_throttle_time = now;
  5689. conn->last_throttle_bytes = 0;
  5690. }
  5691. allowed = conn->throttle - conn->last_throttle_bytes;
  5692. if (allowed > (int64_t)len) {
  5693. allowed = (int64_t)len;
  5694. }
  5695. if ((total = push_all(conn->phys_ctx,
  5696. NULL,
  5697. conn->client.sock,
  5698. conn->ssl,
  5699. (const char *)buf,
  5700. (int64_t)allowed)) == allowed) {
  5701. buf = (const char *)buf + total;
  5702. conn->last_throttle_bytes += total;
  5703. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5704. allowed = (conn->throttle > ((int64_t)len - total))
  5705. ? (int64_t)len - total
  5706. : conn->throttle;
  5707. if ((n = push_all(conn->phys_ctx,
  5708. NULL,
  5709. conn->client.sock,
  5710. conn->ssl,
  5711. (const char *)buf,
  5712. (int64_t)allowed)) != allowed) {
  5713. break;
  5714. }
  5715. sleep(1);
  5716. conn->last_throttle_bytes = allowed;
  5717. conn->last_throttle_time = time(NULL);
  5718. buf = (const char *)buf + n;
  5719. total += n;
  5720. }
  5721. }
  5722. } else {
  5723. total = push_all(conn->phys_ctx,
  5724. NULL,
  5725. conn->client.sock,
  5726. conn->ssl,
  5727. (const char *)buf,
  5728. (int64_t)len);
  5729. }
  5730. if (total > 0) {
  5731. conn->num_bytes_sent += total;
  5732. }
  5733. return (int)total;
  5734. }
  5735. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5736. int
  5737. mg_send_chunk(struct mg_connection *conn,
  5738. const char *chunk,
  5739. unsigned int chunk_len)
  5740. {
  5741. char lenbuf[16];
  5742. size_t lenbuf_len;
  5743. int ret;
  5744. int t;
  5745. /* First store the length information in a text buffer. */
  5746. sprintf(lenbuf, "%x\r\n", chunk_len);
  5747. lenbuf_len = strlen(lenbuf);
  5748. /* Then send length information, chunk and terminating \r\n. */
  5749. ret = mg_write(conn, lenbuf, lenbuf_len);
  5750. if (ret != (int)lenbuf_len) {
  5751. return -1;
  5752. }
  5753. t = ret;
  5754. ret = mg_write(conn, chunk, chunk_len);
  5755. if (ret != (int)chunk_len) {
  5756. return -1;
  5757. }
  5758. t += ret;
  5759. ret = mg_write(conn, "\r\n", 2);
  5760. if (ret != 2) {
  5761. return -1;
  5762. }
  5763. t += ret;
  5764. return t;
  5765. }
  5766. #if defined(__GNUC__) || defined(__MINGW32__)
  5767. /* This block forwards format strings to printf implementations,
  5768. * so we need to disable the format-nonliteral warning. */
  5769. #pragma GCC diagnostic push
  5770. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5771. #endif
  5772. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5773. static int
  5774. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5775. {
  5776. va_list ap_copy;
  5777. size_t size = MG_BUF_LEN / 4;
  5778. int len = -1;
  5779. *buf = NULL;
  5780. while (len < 0) {
  5781. if (*buf) {
  5782. mg_free(*buf);
  5783. }
  5784. size *= 4;
  5785. *buf = (char *)mg_malloc(size);
  5786. if (!*buf) {
  5787. break;
  5788. }
  5789. va_copy(ap_copy, ap);
  5790. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5791. va_end(ap_copy);
  5792. (*buf)[size - 1] = 0;
  5793. }
  5794. return len;
  5795. }
  5796. /* Print message to buffer. If buffer is large enough to hold the message,
  5797. * return buffer. If buffer is to small, allocate large enough buffer on
  5798. * heap,
  5799. * and return allocated buffer. */
  5800. static int
  5801. alloc_vprintf(char **out_buf,
  5802. char *prealloc_buf,
  5803. size_t prealloc_size,
  5804. const char *fmt,
  5805. va_list ap)
  5806. {
  5807. va_list ap_copy;
  5808. int len;
  5809. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5810. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5811. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5812. * Therefore, we make two passes: on first pass, get required message
  5813. * length.
  5814. * On second pass, actually print the message. */
  5815. va_copy(ap_copy, ap);
  5816. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5817. va_end(ap_copy);
  5818. if (len < 0) {
  5819. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5820. * Switch to alternative code path that uses incremental
  5821. * allocations.
  5822. */
  5823. va_copy(ap_copy, ap);
  5824. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5825. va_end(ap_copy);
  5826. } else if ((size_t)(len) >= prealloc_size) {
  5827. /* The pre-allocated buffer not large enough. */
  5828. /* Allocate a new buffer. */
  5829. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5830. if (!*out_buf) {
  5831. /* Allocation failed. Return -1 as "out of memory" error. */
  5832. return -1;
  5833. }
  5834. /* Buffer allocation successful. Store the string there. */
  5835. va_copy(ap_copy, ap);
  5836. IGNORE_UNUSED_RESULT(
  5837. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5838. va_end(ap_copy);
  5839. } else {
  5840. /* The pre-allocated buffer is large enough.
  5841. * Use it to store the string and return the address. */
  5842. va_copy(ap_copy, ap);
  5843. IGNORE_UNUSED_RESULT(
  5844. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5845. va_end(ap_copy);
  5846. *out_buf = prealloc_buf;
  5847. }
  5848. return len;
  5849. }
  5850. #if defined(__GNUC__) || defined(__MINGW32__)
  5851. /* Enable format-nonliteral warning again. */
  5852. #pragma GCC diagnostic pop
  5853. #endif
  5854. static int
  5855. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5856. {
  5857. char mem[MG_BUF_LEN];
  5858. char *buf = NULL;
  5859. int len;
  5860. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5861. len = mg_write(conn, buf, (size_t)len);
  5862. }
  5863. if ((buf != mem) && (buf != NULL)) {
  5864. mg_free(buf);
  5865. }
  5866. return len;
  5867. }
  5868. int
  5869. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5870. {
  5871. va_list ap;
  5872. int result;
  5873. va_start(ap, fmt);
  5874. result = mg_vprintf(conn, fmt, ap);
  5875. va_end(ap);
  5876. return result;
  5877. }
  5878. int
  5879. mg_url_decode(const char *src,
  5880. int src_len,
  5881. char *dst,
  5882. int dst_len,
  5883. int is_form_url_encoded)
  5884. {
  5885. int i, j, a, b;
  5886. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5887. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5888. if ((i < src_len - 2) && (src[i] == '%')
  5889. && isxdigit(*(const unsigned char *)(src + i + 1))
  5890. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5891. a = tolower(*(const unsigned char *)(src + i + 1));
  5892. b = tolower(*(const unsigned char *)(src + i + 2));
  5893. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5894. i += 2;
  5895. } else if (is_form_url_encoded && (src[i] == '+')) {
  5896. dst[j] = ' ';
  5897. } else {
  5898. dst[j] = src[i];
  5899. }
  5900. }
  5901. dst[j] = '\0'; /* Null-terminate the destination */
  5902. return (i >= src_len) ? j : -1;
  5903. }
  5904. int
  5905. mg_get_var(const char *data,
  5906. size_t data_len,
  5907. const char *name,
  5908. char *dst,
  5909. size_t dst_len)
  5910. {
  5911. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5912. }
  5913. int
  5914. mg_get_var2(const char *data,
  5915. size_t data_len,
  5916. const char *name,
  5917. char *dst,
  5918. size_t dst_len,
  5919. size_t occurrence)
  5920. {
  5921. const char *p, *e, *s;
  5922. size_t name_len;
  5923. int len;
  5924. if ((dst == NULL) || (dst_len == 0)) {
  5925. len = -2;
  5926. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5927. len = -1;
  5928. dst[0] = '\0';
  5929. } else {
  5930. name_len = strlen(name);
  5931. e = data + data_len;
  5932. len = -1;
  5933. dst[0] = '\0';
  5934. /* data is "var1=val1&var2=val2...". Find variable first */
  5935. for (p = data; p + name_len < e; p++) {
  5936. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5937. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5938. /* Point p to variable value */
  5939. p += name_len + 1;
  5940. /* Point s to the end of the value */
  5941. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5942. if (s == NULL) {
  5943. s = e;
  5944. }
  5945. DEBUG_ASSERT(s >= p);
  5946. if (s < p) {
  5947. return -3;
  5948. }
  5949. /* Decode variable into destination buffer */
  5950. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5951. /* Redirect error code from -1 to -2 (destination buffer too
  5952. * small). */
  5953. if (len == -1) {
  5954. len = -2;
  5955. }
  5956. break;
  5957. }
  5958. }
  5959. }
  5960. return len;
  5961. }
  5962. /* HCP24: some changes to compare hole var_name */
  5963. int
  5964. mg_get_cookie(const char *cookie_header,
  5965. const char *var_name,
  5966. char *dst,
  5967. size_t dst_size)
  5968. {
  5969. const char *s, *p, *end;
  5970. int name_len, len = -1;
  5971. if ((dst == NULL) || (dst_size == 0)) {
  5972. return -2;
  5973. }
  5974. dst[0] = '\0';
  5975. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5976. return -1;
  5977. }
  5978. name_len = (int)strlen(var_name);
  5979. end = s + strlen(s);
  5980. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5981. if (s[name_len] == '=') {
  5982. /* HCP24: now check is it a substring or a full cookie name */
  5983. if ((s == cookie_header) || (s[-1] == ' ')) {
  5984. s += name_len + 1;
  5985. if ((p = strchr(s, ' ')) == NULL) {
  5986. p = end;
  5987. }
  5988. if (p[-1] == ';') {
  5989. p--;
  5990. }
  5991. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5992. s++;
  5993. p--;
  5994. }
  5995. if ((size_t)(p - s) < dst_size) {
  5996. len = (int)(p - s);
  5997. mg_strlcpy(dst, s, (size_t)len + 1);
  5998. } else {
  5999. len = -3;
  6000. }
  6001. break;
  6002. }
  6003. }
  6004. }
  6005. return len;
  6006. }
  6007. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6008. static void
  6009. base64_encode(const unsigned char *src, int src_len, char *dst)
  6010. {
  6011. static const char *b64 =
  6012. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6013. int i, j, a, b, c;
  6014. for (i = j = 0; i < src_len; i += 3) {
  6015. a = src[i];
  6016. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6017. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6018. dst[j++] = b64[a >> 2];
  6019. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6020. if (i + 1 < src_len) {
  6021. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6022. }
  6023. if (i + 2 < src_len) {
  6024. dst[j++] = b64[c & 63];
  6025. }
  6026. }
  6027. while (j % 4 != 0) {
  6028. dst[j++] = '=';
  6029. }
  6030. dst[j++] = '\0';
  6031. }
  6032. #endif
  6033. #if defined(USE_LUA)
  6034. static unsigned char
  6035. b64reverse(char letter)
  6036. {
  6037. if ((letter >= 'A') && (letter <= 'Z')) {
  6038. return letter - 'A';
  6039. }
  6040. if ((letter >= 'a') && (letter <= 'z')) {
  6041. return letter - 'a' + 26;
  6042. }
  6043. if ((letter >= '0') && (letter <= '9')) {
  6044. return letter - '0' + 52;
  6045. }
  6046. if (letter == '+') {
  6047. return 62;
  6048. }
  6049. if (letter == '/') {
  6050. return 63;
  6051. }
  6052. if (letter == '=') {
  6053. return 255; /* normal end */
  6054. }
  6055. return 254; /* error */
  6056. }
  6057. static int
  6058. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6059. {
  6060. int i;
  6061. unsigned char a, b, c, d;
  6062. *dst_len = 0;
  6063. for (i = 0; i < src_len; i += 4) {
  6064. a = b64reverse(src[i]);
  6065. if (a >= 254) {
  6066. return i;
  6067. }
  6068. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6069. if (b >= 254) {
  6070. return i + 1;
  6071. }
  6072. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6073. if (c == 254) {
  6074. return i + 2;
  6075. }
  6076. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6077. if (d == 254) {
  6078. return i + 3;
  6079. }
  6080. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6081. if (c != 255) {
  6082. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6083. if (d != 255) {
  6084. dst[(*dst_len)++] = (c << 6) + d;
  6085. }
  6086. }
  6087. }
  6088. return -1;
  6089. }
  6090. #endif
  6091. static int
  6092. is_put_or_delete_method(const struct mg_connection *conn)
  6093. {
  6094. if (conn) {
  6095. const char *s = conn->request_info.request_method;
  6096. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6097. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6098. }
  6099. return 0;
  6100. }
  6101. #if !defined(NO_FILES)
  6102. static int
  6103. extention_matches_script(
  6104. struct mg_connection *conn, /* in: request (must be valid) */
  6105. const char *filename /* in: filename (must be valid) */
  6106. )
  6107. {
  6108. #if !defined(NO_CGI)
  6109. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6110. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6111. filename) > 0) {
  6112. return 1;
  6113. }
  6114. #endif
  6115. #if defined(USE_LUA)
  6116. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6117. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6118. filename) > 0) {
  6119. return 1;
  6120. }
  6121. #endif
  6122. #if defined(USE_DUKTAPE)
  6123. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6124. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6125. filename) > 0) {
  6126. return 1;
  6127. }
  6128. #endif
  6129. /* filename and conn could be unused, if all preocessor conditions
  6130. * are false (no script language supported). */
  6131. (void)filename;
  6132. (void)conn;
  6133. return 0;
  6134. }
  6135. /* For given directory path, substitute it to valid index file.
  6136. * Return 1 if index file has been found, 0 if not found.
  6137. * If the file is found, it's stats is returned in stp. */
  6138. static int
  6139. substitute_index_file(struct mg_connection *conn,
  6140. char *path,
  6141. size_t path_len,
  6142. struct mg_file_stat *filestat)
  6143. {
  6144. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6145. struct vec filename_vec;
  6146. size_t n = strlen(path);
  6147. int found = 0;
  6148. /* The 'path' given to us points to the directory. Remove all trailing
  6149. * directory separator characters from the end of the path, and
  6150. * then append single directory separator character. */
  6151. while ((n > 0) && (path[n - 1] == '/')) {
  6152. n--;
  6153. }
  6154. path[n] = '/';
  6155. /* Traverse index files list. For each entry, append it to the given
  6156. * path and see if the file exists. If it exists, break the loop */
  6157. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6158. /* Ignore too long entries that may overflow path buffer */
  6159. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6160. continue;
  6161. }
  6162. /* Prepare full path to the index file */
  6163. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6164. /* Does it exist? */
  6165. if (mg_stat(conn, path, filestat)) {
  6166. /* Yes it does, break the loop */
  6167. found = 1;
  6168. break;
  6169. }
  6170. }
  6171. /* If no index file exists, restore directory path */
  6172. if (!found) {
  6173. path[n] = '\0';
  6174. }
  6175. return found;
  6176. }
  6177. #endif
  6178. static void
  6179. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6180. char *filename, /* out: filename */
  6181. size_t filename_buf_len, /* in: size of filename buffer */
  6182. struct mg_file_stat *filestat, /* out: file status structure */
  6183. int *is_found, /* out: file found (directly) */
  6184. int *is_script_resource, /* out: handled by a script? */
  6185. int *is_websocket_request, /* out: websocket connetion? */
  6186. int *is_put_or_delete_request /* out: put/delete a file? */
  6187. )
  6188. {
  6189. char const *accept_encoding;
  6190. #if !defined(NO_FILES)
  6191. const char *uri = conn->request_info.local_uri;
  6192. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6193. const char *rewrite;
  6194. struct vec a, b;
  6195. ptrdiff_t match_len;
  6196. char gz_path[PATH_MAX];
  6197. int truncated;
  6198. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6199. char *tmp_str;
  6200. size_t tmp_str_len, sep_pos;
  6201. int allow_substitute_script_subresources;
  6202. #endif
  6203. #else
  6204. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6205. #endif
  6206. /* Step 1: Set all initially unknown outputs to zero */
  6207. memset(filestat, 0, sizeof(*filestat));
  6208. *filename = 0;
  6209. *is_found = 0;
  6210. *is_script_resource = 0;
  6211. /* Step 2: Check if the request attempts to modify the file system */
  6212. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6213. /* Step 3: Check if it is a websocket request, and modify the document
  6214. * root if required */
  6215. #if defined(USE_WEBSOCKET)
  6216. *is_websocket_request = is_websocket_protocol(conn);
  6217. #if !defined(NO_FILES)
  6218. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6219. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6220. }
  6221. #endif /* !NO_FILES */
  6222. #else /* USE_WEBSOCKET */
  6223. *is_websocket_request = 0;
  6224. #endif /* USE_WEBSOCKET */
  6225. /* Step 4: Check if gzip encoded response is allowed */
  6226. conn->accept_gzip = 0;
  6227. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6228. if (strstr(accept_encoding, "gzip") != NULL) {
  6229. conn->accept_gzip = 1;
  6230. }
  6231. }
  6232. #if !defined(NO_FILES)
  6233. /* Step 5: If there is no root directory, don't look for files. */
  6234. /* Note that root == NULL is a regular use case here. This occurs,
  6235. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6236. * config is not required. */
  6237. if (root == NULL) {
  6238. /* all file related outputs have already been set to 0, just return
  6239. */
  6240. return;
  6241. }
  6242. /* Step 6: Determine the local file path from the root path and the
  6243. * request uri. */
  6244. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6245. * part of the path one byte on the right. */
  6246. mg_snprintf(
  6247. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6248. if (truncated) {
  6249. goto interpret_cleanup;
  6250. }
  6251. /* Step 7: URI rewriting */
  6252. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6253. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6254. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6255. mg_snprintf(conn,
  6256. &truncated,
  6257. filename,
  6258. filename_buf_len - 1,
  6259. "%.*s%s",
  6260. (int)b.len,
  6261. b.ptr,
  6262. uri + match_len);
  6263. break;
  6264. }
  6265. }
  6266. if (truncated) {
  6267. goto interpret_cleanup;
  6268. }
  6269. /* Step 8: Check if the file exists at the server */
  6270. /* Local file path and name, corresponding to requested URI
  6271. * is now stored in "filename" variable. */
  6272. if (mg_stat(conn, filename, filestat)) {
  6273. int uri_len = (int)strlen(uri);
  6274. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6275. /* 8.1: File exists. */
  6276. *is_found = 1;
  6277. /* 8.2: Check if it is a script type. */
  6278. if (extention_matches_script(conn, filename)) {
  6279. /* The request addresses a CGI resource, Lua script or
  6280. * server-side javascript.
  6281. * The URI corresponds to the script itself (like
  6282. * /path/script.cgi), and there is no additional resource
  6283. * path (like /path/script.cgi/something).
  6284. * Requests that modify (replace or delete) a resource, like
  6285. * PUT and DELETE requests, should replace/delete the script
  6286. * file.
  6287. * Requests that read or write from/to a resource, like GET and
  6288. * POST requests, should call the script and return the
  6289. * generated response. */
  6290. *is_script_resource = (!*is_put_or_delete_request);
  6291. }
  6292. /* 8.3: If the request target is a directory, there could be
  6293. * a substitute file (index.html, index.cgi, ...). */
  6294. if (filestat->is_directory && is_uri_end_slash) {
  6295. /* Use a local copy here, since substitute_index_file will
  6296. * change the content of the file status */
  6297. struct mg_file_stat tmp_filestat;
  6298. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6299. if (substitute_index_file(
  6300. conn, filename, filename_buf_len, &tmp_filestat)) {
  6301. /* Substitute file found. Copy stat to the output, then
  6302. * check if the file is a script file */
  6303. *filestat = tmp_filestat;
  6304. if (extention_matches_script(conn, filename)) {
  6305. /* Substitute file is a script file */
  6306. *is_script_resource = 1;
  6307. } else {
  6308. /* Substitute file is a regular file */
  6309. *is_script_resource = 0;
  6310. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6311. }
  6312. }
  6313. /* If there is no substitute file, the server could return
  6314. * a directory listing in a later step */
  6315. }
  6316. return;
  6317. }
  6318. /* Step 9: Check for zipped files: */
  6319. /* If we can't find the actual file, look for the file
  6320. * with the same name but a .gz extension. If we find it,
  6321. * use that and set the gzipped flag in the file struct
  6322. * to indicate that the response need to have the content-
  6323. * encoding: gzip header.
  6324. * We can only do this if the browser declares support. */
  6325. if (conn->accept_gzip) {
  6326. mg_snprintf(
  6327. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6328. if (truncated) {
  6329. goto interpret_cleanup;
  6330. }
  6331. if (mg_stat(conn, gz_path, filestat)) {
  6332. if (filestat) {
  6333. filestat->is_gzipped = 1;
  6334. *is_found = 1;
  6335. }
  6336. /* Currently gz files can not be scripts. */
  6337. return;
  6338. }
  6339. }
  6340. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6341. /* Step 10: Script resources may handle sub-resources */
  6342. /* Support PATH_INFO for CGI scripts. */
  6343. tmp_str_len = strlen(filename);
  6344. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6345. if (!tmp_str) {
  6346. /* Out of memory */
  6347. goto interpret_cleanup;
  6348. }
  6349. memcpy(tmp_str, filename, tmp_str_len + 1);
  6350. /* Check config, if index scripts may have sub-resources */
  6351. allow_substitute_script_subresources =
  6352. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6353. "yes");
  6354. sep_pos = tmp_str_len;
  6355. while (sep_pos > 0) {
  6356. sep_pos--;
  6357. if (tmp_str[sep_pos] == '/') {
  6358. int is_script = 0, does_exist = 0;
  6359. tmp_str[sep_pos] = 0;
  6360. if (tmp_str[0]) {
  6361. is_script = extention_matches_script(conn, tmp_str);
  6362. does_exist = mg_stat(conn, tmp_str, filestat);
  6363. }
  6364. if (does_exist && is_script) {
  6365. filename[sep_pos] = 0;
  6366. memmove(filename + sep_pos + 2,
  6367. filename + sep_pos + 1,
  6368. strlen(filename + sep_pos + 1) + 1);
  6369. conn->path_info = filename + sep_pos + 1;
  6370. filename[sep_pos + 1] = '/';
  6371. *is_script_resource = 1;
  6372. *is_found = 1;
  6373. break;
  6374. }
  6375. if (allow_substitute_script_subresources) {
  6376. if (substitute_index_file(
  6377. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6378. /* some intermediate directory has an index file */
  6379. if (extention_matches_script(conn, tmp_str)) {
  6380. char *tmp_str2;
  6381. DEBUG_TRACE("Substitute script %s serving path %s",
  6382. tmp_str,
  6383. filename);
  6384. /* this index file is a script */
  6385. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6386. conn->phys_ctx);
  6387. mg_snprintf(conn,
  6388. &truncated,
  6389. filename,
  6390. filename_buf_len,
  6391. "%s//%s",
  6392. tmp_str,
  6393. tmp_str2);
  6394. mg_free(tmp_str2);
  6395. if (truncated) {
  6396. mg_free(tmp_str);
  6397. goto interpret_cleanup;
  6398. }
  6399. sep_pos = strlen(tmp_str);
  6400. filename[sep_pos] = 0;
  6401. conn->path_info = filename + sep_pos + 1;
  6402. *is_script_resource = 1;
  6403. *is_found = 1;
  6404. break;
  6405. } else {
  6406. DEBUG_TRACE("Substitute file %s serving path %s",
  6407. tmp_str,
  6408. filename);
  6409. /* non-script files will not have sub-resources */
  6410. filename[sep_pos] = 0;
  6411. conn->path_info = 0;
  6412. *is_script_resource = 0;
  6413. *is_found = 0;
  6414. break;
  6415. }
  6416. }
  6417. }
  6418. tmp_str[sep_pos] = '/';
  6419. }
  6420. }
  6421. mg_free(tmp_str);
  6422. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6423. #endif /* !defined(NO_FILES) */
  6424. return;
  6425. #if !defined(NO_FILES)
  6426. /* Reset all outputs */
  6427. interpret_cleanup:
  6428. memset(filestat, 0, sizeof(*filestat));
  6429. *filename = 0;
  6430. *is_found = 0;
  6431. *is_script_resource = 0;
  6432. *is_websocket_request = 0;
  6433. *is_put_or_delete_request = 0;
  6434. #endif /* !defined(NO_FILES) */
  6435. }
  6436. /* Check whether full request is buffered. Return:
  6437. * -1 if request or response is malformed
  6438. * 0 if request or response is not yet fully buffered
  6439. * >0 actual request length, including last \r\n\r\n */
  6440. static int
  6441. get_http_header_len(const char *buf, int buflen)
  6442. {
  6443. int i;
  6444. for (i = 0; i < buflen; i++) {
  6445. /* Do an unsigned comparison in some conditions below */
  6446. const unsigned char c = ((const unsigned char *)buf)[i];
  6447. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6448. && !isprint(c)) {
  6449. /* abort scan as soon as one malformed character is found */
  6450. return -1;
  6451. }
  6452. if (i < buflen - 1) {
  6453. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6454. /* Two newline, no carriage return - not standard compliant,
  6455. * but
  6456. * it
  6457. * should be accepted */
  6458. return i + 2;
  6459. }
  6460. }
  6461. if (i < buflen - 3) {
  6462. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6463. && (buf[i + 3] == '\n')) {
  6464. /* Two \r\n - standard compliant */
  6465. return i + 4;
  6466. }
  6467. }
  6468. }
  6469. return 0;
  6470. }
  6471. #if !defined(NO_CACHING)
  6472. /* Convert month to the month number. Return -1 on error, or month number */
  6473. static int
  6474. get_month_index(const char *s)
  6475. {
  6476. size_t i;
  6477. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6478. if (!strcmp(s, month_names[i])) {
  6479. return (int)i;
  6480. }
  6481. }
  6482. return -1;
  6483. }
  6484. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6485. static time_t
  6486. parse_date_string(const char *datetime)
  6487. {
  6488. char month_str[32] = {0};
  6489. int second, minute, hour, day, month, year;
  6490. time_t result = (time_t)0;
  6491. struct tm tm;
  6492. if ((sscanf(datetime,
  6493. "%d/%3s/%d %d:%d:%d",
  6494. &day,
  6495. month_str,
  6496. &year,
  6497. &hour,
  6498. &minute,
  6499. &second) == 6) || (sscanf(datetime,
  6500. "%d %3s %d %d:%d:%d",
  6501. &day,
  6502. month_str,
  6503. &year,
  6504. &hour,
  6505. &minute,
  6506. &second) == 6)
  6507. || (sscanf(datetime,
  6508. "%*3s, %d %3s %d %d:%d:%d",
  6509. &day,
  6510. month_str,
  6511. &year,
  6512. &hour,
  6513. &minute,
  6514. &second) == 6) || (sscanf(datetime,
  6515. "%d-%3s-%d %d:%d:%d",
  6516. &day,
  6517. month_str,
  6518. &year,
  6519. &hour,
  6520. &minute,
  6521. &second) == 6)) {
  6522. month = get_month_index(month_str);
  6523. if ((month >= 0) && (year >= 1970)) {
  6524. memset(&tm, 0, sizeof(tm));
  6525. tm.tm_year = year - 1900;
  6526. tm.tm_mon = month;
  6527. tm.tm_mday = day;
  6528. tm.tm_hour = hour;
  6529. tm.tm_min = minute;
  6530. tm.tm_sec = second;
  6531. result = timegm(&tm);
  6532. }
  6533. }
  6534. return result;
  6535. }
  6536. #endif /* !NO_CACHING */
  6537. /* Protect against directory disclosure attack by removing '..',
  6538. * excessive '/' and '\' characters */
  6539. static void
  6540. remove_double_dots_and_double_slashes(char *s)
  6541. {
  6542. char *p = s;
  6543. while ((s[0] == '.') && (s[1] == '.')) {
  6544. s++;
  6545. }
  6546. while (*s != '\0') {
  6547. *p++ = *s++;
  6548. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6549. /* Skip all following slashes, backslashes and double-dots */
  6550. while (s[0] != '\0') {
  6551. if ((s[0] == '/') || (s[0] == '\\')) {
  6552. s++;
  6553. } else if ((s[0] == '.') && (s[1] == '.')) {
  6554. s += 2;
  6555. } else {
  6556. break;
  6557. }
  6558. }
  6559. }
  6560. }
  6561. *p = '\0';
  6562. }
  6563. static const struct {
  6564. const char *extension;
  6565. size_t ext_len;
  6566. const char *mime_type;
  6567. } builtin_mime_types[] = {
  6568. /* IANA registered MIME types
  6569. * (http://www.iana.org/assignments/media-types)
  6570. * application types */
  6571. {".doc", 4, "application/msword"},
  6572. {".eps", 4, "application/postscript"},
  6573. {".exe", 4, "application/octet-stream"},
  6574. {".js", 3, "application/javascript"},
  6575. {".json", 5, "application/json"},
  6576. {".pdf", 4, "application/pdf"},
  6577. {".ps", 3, "application/postscript"},
  6578. {".rtf", 4, "application/rtf"},
  6579. {".xhtml", 6, "application/xhtml+xml"},
  6580. {".xsl", 4, "application/xml"},
  6581. {".xslt", 5, "application/xml"},
  6582. /* fonts */
  6583. {".ttf", 4, "application/font-sfnt"},
  6584. {".cff", 4, "application/font-sfnt"},
  6585. {".otf", 4, "application/font-sfnt"},
  6586. {".aat", 4, "application/font-sfnt"},
  6587. {".sil", 4, "application/font-sfnt"},
  6588. {".pfr", 4, "application/font-tdpfr"},
  6589. {".woff", 5, "application/font-woff"},
  6590. /* audio */
  6591. {".mp3", 4, "audio/mpeg"},
  6592. {".oga", 4, "audio/ogg"},
  6593. {".ogg", 4, "audio/ogg"},
  6594. /* image */
  6595. {".gif", 4, "image/gif"},
  6596. {".ief", 4, "image/ief"},
  6597. {".jpeg", 5, "image/jpeg"},
  6598. {".jpg", 4, "image/jpeg"},
  6599. {".jpm", 4, "image/jpm"},
  6600. {".jpx", 4, "image/jpx"},
  6601. {".png", 4, "image/png"},
  6602. {".svg", 4, "image/svg+xml"},
  6603. {".tif", 4, "image/tiff"},
  6604. {".tiff", 5, "image/tiff"},
  6605. /* model */
  6606. {".wrl", 4, "model/vrml"},
  6607. /* text */
  6608. {".css", 4, "text/css"},
  6609. {".csv", 4, "text/csv"},
  6610. {".htm", 4, "text/html"},
  6611. {".html", 5, "text/html"},
  6612. {".sgm", 4, "text/sgml"},
  6613. {".shtm", 5, "text/html"},
  6614. {".shtml", 6, "text/html"},
  6615. {".txt", 4, "text/plain"},
  6616. {".xml", 4, "text/xml"},
  6617. /* video */
  6618. {".mov", 4, "video/quicktime"},
  6619. {".mp4", 4, "video/mp4"},
  6620. {".mpeg", 5, "video/mpeg"},
  6621. {".mpg", 4, "video/mpeg"},
  6622. {".ogv", 4, "video/ogg"},
  6623. {".qt", 3, "video/quicktime"},
  6624. /* not registered types
  6625. * (http://reference.sitepoint.com/html/mime-types-full,
  6626. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6627. {".arj", 4, "application/x-arj-compressed"},
  6628. {".gz", 3, "application/x-gunzip"},
  6629. {".rar", 4, "application/x-arj-compressed"},
  6630. {".swf", 4, "application/x-shockwave-flash"},
  6631. {".tar", 4, "application/x-tar"},
  6632. {".tgz", 4, "application/x-tar-gz"},
  6633. {".torrent", 8, "application/x-bittorrent"},
  6634. {".ppt", 4, "application/x-mspowerpoint"},
  6635. {".xls", 4, "application/x-msexcel"},
  6636. {".zip", 4, "application/x-zip-compressed"},
  6637. {".aac",
  6638. 4,
  6639. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6640. {".aif", 4, "audio/x-aif"},
  6641. {".m3u", 4, "audio/x-mpegurl"},
  6642. {".mid", 4, "audio/x-midi"},
  6643. {".ra", 3, "audio/x-pn-realaudio"},
  6644. {".ram", 4, "audio/x-pn-realaudio"},
  6645. {".wav", 4, "audio/x-wav"},
  6646. {".bmp", 4, "image/bmp"},
  6647. {".ico", 4, "image/x-icon"},
  6648. {".pct", 4, "image/x-pct"},
  6649. {".pict", 5, "image/pict"},
  6650. {".rgb", 4, "image/x-rgb"},
  6651. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6652. {".asf", 4, "video/x-ms-asf"},
  6653. {".avi", 4, "video/x-msvideo"},
  6654. {".m4v", 4, "video/x-m4v"},
  6655. {NULL, 0, NULL}};
  6656. const char *
  6657. mg_get_builtin_mime_type(const char *path)
  6658. {
  6659. const char *ext;
  6660. size_t i, path_len;
  6661. path_len = strlen(path);
  6662. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6663. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6664. if ((path_len > builtin_mime_types[i].ext_len)
  6665. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6666. return builtin_mime_types[i].mime_type;
  6667. }
  6668. }
  6669. return "text/plain";
  6670. }
  6671. /* Look at the "path" extension and figure what mime type it has.
  6672. * Store mime type in the vector. */
  6673. static void
  6674. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6675. {
  6676. struct vec ext_vec, mime_vec;
  6677. const char *list, *ext;
  6678. size_t path_len;
  6679. path_len = strlen(path);
  6680. if ((conn == NULL) || (vec == NULL)) {
  6681. if (vec != NULL) {
  6682. memset(vec, '\0', sizeof(struct vec));
  6683. }
  6684. return;
  6685. }
  6686. /* Scan user-defined mime types first, in case user wants to
  6687. * override default mime types. */
  6688. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6689. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6690. /* ext now points to the path suffix */
  6691. ext = path + path_len - ext_vec.len;
  6692. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6693. *vec = mime_vec;
  6694. return;
  6695. }
  6696. }
  6697. vec->ptr = mg_get_builtin_mime_type(path);
  6698. vec->len = strlen(vec->ptr);
  6699. }
  6700. /* Stringify binary data. Output buffer must be twice as big as input,
  6701. * because each byte takes 2 bytes in string representation */
  6702. static void
  6703. bin2str(char *to, const unsigned char *p, size_t len)
  6704. {
  6705. static const char *hex = "0123456789abcdef";
  6706. for (; len--; p++) {
  6707. *to++ = hex[p[0] >> 4];
  6708. *to++ = hex[p[0] & 0x0f];
  6709. }
  6710. *to = '\0';
  6711. }
  6712. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6713. */
  6714. char *
  6715. mg_md5(char buf[33], ...)
  6716. {
  6717. md5_byte_t hash[16];
  6718. const char *p;
  6719. va_list ap;
  6720. md5_state_t ctx;
  6721. md5_init(&ctx);
  6722. va_start(ap, buf);
  6723. while ((p = va_arg(ap, const char *)) != NULL) {
  6724. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6725. }
  6726. va_end(ap);
  6727. md5_finish(&ctx, hash);
  6728. bin2str(buf, hash, sizeof(hash));
  6729. return buf;
  6730. }
  6731. /* Check the user's password, return 1 if OK */
  6732. static int
  6733. check_password(const char *method,
  6734. const char *ha1,
  6735. const char *uri,
  6736. const char *nonce,
  6737. const char *nc,
  6738. const char *cnonce,
  6739. const char *qop,
  6740. const char *response)
  6741. {
  6742. char ha2[32 + 1], expected_response[32 + 1];
  6743. /* Some of the parameters may be NULL */
  6744. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6745. || (qop == NULL) || (response == NULL)) {
  6746. return 0;
  6747. }
  6748. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6749. if (strlen(response) != 32) {
  6750. return 0;
  6751. }
  6752. mg_md5(ha2, method, ":", uri, NULL);
  6753. mg_md5(expected_response,
  6754. ha1,
  6755. ":",
  6756. nonce,
  6757. ":",
  6758. nc,
  6759. ":",
  6760. cnonce,
  6761. ":",
  6762. qop,
  6763. ":",
  6764. ha2,
  6765. NULL);
  6766. return mg_strcasecmp(response, expected_response) == 0;
  6767. }
  6768. /* Use the global passwords file, if specified by auth_gpass option,
  6769. * or search for .htpasswd in the requested directory. */
  6770. static void
  6771. open_auth_file(struct mg_connection *conn,
  6772. const char *path,
  6773. struct mg_file *filep)
  6774. {
  6775. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6776. char name[PATH_MAX];
  6777. const char *p, *e,
  6778. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6779. int truncated;
  6780. if (gpass != NULL) {
  6781. /* Use global passwords file */
  6782. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6783. #if defined(DEBUG)
  6784. /* Use mg_cry_internal here, since gpass has been configured. */
  6785. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6786. #endif
  6787. }
  6788. /* Important: using local struct mg_file to test path for
  6789. * is_directory flag. If filep is used, mg_stat() makes it
  6790. * appear as if auth file was opened.
  6791. * TODO(mid): Check if this is still required after rewriting
  6792. * mg_stat */
  6793. } else if (mg_stat(conn, path, &filep->stat)
  6794. && filep->stat.is_directory) {
  6795. mg_snprintf(conn,
  6796. &truncated,
  6797. name,
  6798. sizeof(name),
  6799. "%s/%s",
  6800. path,
  6801. PASSWORDS_FILE_NAME);
  6802. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6803. #if defined(DEBUG)
  6804. /* Don't use mg_cry_internal here, but only a trace, since this
  6805. * is
  6806. * a typical case. It will occur for every directory
  6807. * without a password file. */
  6808. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6809. #endif
  6810. }
  6811. } else {
  6812. /* Try to find .htpasswd in requested directory. */
  6813. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6814. if (e[0] == '/') {
  6815. break;
  6816. }
  6817. }
  6818. mg_snprintf(conn,
  6819. &truncated,
  6820. name,
  6821. sizeof(name),
  6822. "%.*s/%s",
  6823. (int)(e - p),
  6824. p,
  6825. PASSWORDS_FILE_NAME);
  6826. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6827. #if defined(DEBUG)
  6828. /* Don't use mg_cry_internal here, but only a trace, since this
  6829. * is
  6830. * a typical case. It will occur for every directory
  6831. * without a password file. */
  6832. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6833. #endif
  6834. }
  6835. }
  6836. }
  6837. }
  6838. /* Parsed Authorization header */
  6839. struct ah {
  6840. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6841. };
  6842. /* Return 1 on success. Always initializes the ah structure. */
  6843. static int
  6844. parse_auth_header(struct mg_connection *conn,
  6845. char *buf,
  6846. size_t buf_size,
  6847. struct ah *ah)
  6848. {
  6849. char *name, *value, *s;
  6850. const char *auth_header;
  6851. uint64_t nonce;
  6852. if (!ah || !conn) {
  6853. return 0;
  6854. }
  6855. (void)memset(ah, 0, sizeof(*ah));
  6856. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6857. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6858. return 0;
  6859. }
  6860. /* Make modifiable copy of the auth header */
  6861. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6862. s = buf;
  6863. /* Parse authorization header */
  6864. for (;;) {
  6865. /* Gobble initial spaces */
  6866. while (isspace(*(unsigned char *)s)) {
  6867. s++;
  6868. }
  6869. name = skip_quoted(&s, "=", " ", 0);
  6870. /* Value is either quote-delimited, or ends at first comma or space.
  6871. */
  6872. if (s[0] == '\"') {
  6873. s++;
  6874. value = skip_quoted(&s, "\"", " ", '\\');
  6875. if (s[0] == ',') {
  6876. s++;
  6877. }
  6878. } else {
  6879. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6880. * spaces */
  6881. }
  6882. if (*name == '\0') {
  6883. break;
  6884. }
  6885. if (!strcmp(name, "username")) {
  6886. ah->user = value;
  6887. } else if (!strcmp(name, "cnonce")) {
  6888. ah->cnonce = value;
  6889. } else if (!strcmp(name, "response")) {
  6890. ah->response = value;
  6891. } else if (!strcmp(name, "uri")) {
  6892. ah->uri = value;
  6893. } else if (!strcmp(name, "qop")) {
  6894. ah->qop = value;
  6895. } else if (!strcmp(name, "nc")) {
  6896. ah->nc = value;
  6897. } else if (!strcmp(name, "nonce")) {
  6898. ah->nonce = value;
  6899. }
  6900. }
  6901. #if !defined(NO_NONCE_CHECK)
  6902. /* Read the nonce from the response. */
  6903. if (ah->nonce == NULL) {
  6904. return 0;
  6905. }
  6906. s = NULL;
  6907. nonce = strtoull(ah->nonce, &s, 10);
  6908. if ((s == NULL) || (*s != 0)) {
  6909. return 0;
  6910. }
  6911. /* Convert the nonce from the client to a number. */
  6912. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6913. /* The converted number corresponds to the time the nounce has been
  6914. * created. This should not be earlier than the server start. */
  6915. /* Server side nonce check is valuable in all situations but one:
  6916. * if the server restarts frequently, but the client should not see
  6917. * that, so the server should accept nonces from previous starts. */
  6918. /* However, the reasonable default is to not accept a nonce from a
  6919. * previous start, so if anyone changed the access rights between
  6920. * two restarts, a new login is required. */
  6921. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6922. /* nonce is from a previous start of the server and no longer valid
  6923. * (replay attack?) */
  6924. return 0;
  6925. }
  6926. /* Check if the nonce is too high, so it has not (yet) been used by the
  6927. * server. */
  6928. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6929. + conn->dom_ctx->nonce_count)) {
  6930. return 0;
  6931. }
  6932. #else
  6933. (void)nonce;
  6934. #endif
  6935. /* CGI needs it as REMOTE_USER */
  6936. if (ah->user != NULL) {
  6937. conn->request_info.remote_user =
  6938. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6939. } else {
  6940. return 0;
  6941. }
  6942. return 1;
  6943. }
  6944. static const char *
  6945. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6946. {
  6947. #if defined(MG_USE_OPEN_FILE)
  6948. const char *eof;
  6949. size_t len;
  6950. const char *memend;
  6951. #else
  6952. (void)p; /* parameter is unused */
  6953. #endif
  6954. if (!filep) {
  6955. return NULL;
  6956. }
  6957. #if defined(MG_USE_OPEN_FILE)
  6958. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6959. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6960. /* Search for \n from p till the end of stream */
  6961. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6962. if (eof != NULL) {
  6963. eof += 1; /* Include \n */
  6964. } else {
  6965. eof = memend; /* Copy remaining data */
  6966. }
  6967. len =
  6968. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6969. memcpy(buf, *p, len);
  6970. buf[len] = '\0';
  6971. *p += len;
  6972. return len ? eof : NULL;
  6973. } else /* filep->access.fp block below */
  6974. #endif
  6975. if (filep->access.fp != NULL) {
  6976. return fgets(buf, (int)size, filep->access.fp);
  6977. } else {
  6978. return NULL;
  6979. }
  6980. }
  6981. /* Define the initial recursion depth for procesesing htpasswd files that
  6982. * include other htpasswd
  6983. * (or even the same) files. It is not difficult to provide a file or files
  6984. * s.t. they force civetweb
  6985. * to infinitely recurse and then crash.
  6986. */
  6987. #define INITIAL_DEPTH 9
  6988. #if INITIAL_DEPTH <= 0
  6989. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6990. #endif
  6991. struct read_auth_file_struct {
  6992. struct mg_connection *conn;
  6993. struct ah ah;
  6994. const char *domain;
  6995. char buf[256 + 256 + 40];
  6996. const char *f_user;
  6997. const char *f_domain;
  6998. const char *f_ha1;
  6999. };
  7000. static int
  7001. read_auth_file(struct mg_file *filep,
  7002. struct read_auth_file_struct *workdata,
  7003. int depth)
  7004. {
  7005. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7006. int is_authorized = 0;
  7007. struct mg_file fp;
  7008. size_t l;
  7009. if (!filep || !workdata || (0 == depth)) {
  7010. return 0;
  7011. }
  7012. /* Loop over passwords file */
  7013. #if defined(MG_USE_OPEN_FILE)
  7014. p = (char *)filep->access.membuf;
  7015. #endif
  7016. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7017. l = strlen(workdata->buf);
  7018. while (l > 0) {
  7019. if (isspace(workdata->buf[l - 1])
  7020. || iscntrl(workdata->buf[l - 1])) {
  7021. l--;
  7022. workdata->buf[l] = 0;
  7023. } else
  7024. break;
  7025. }
  7026. if (l < 1) {
  7027. continue;
  7028. }
  7029. workdata->f_user = workdata->buf;
  7030. if (workdata->f_user[0] == ':') {
  7031. /* user names may not contain a ':' and may not be empty,
  7032. * so lines starting with ':' may be used for a special purpose
  7033. */
  7034. if (workdata->f_user[1] == '#') {
  7035. /* :# is a comment */
  7036. continue;
  7037. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7038. if (mg_fopen(workdata->conn,
  7039. workdata->f_user + 9,
  7040. MG_FOPEN_MODE_READ,
  7041. &fp)) {
  7042. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7043. (void)mg_fclose(
  7044. &fp.access); /* ignore error on read only file */
  7045. /* No need to continue processing files once we have a
  7046. * match, since nothing will reset it back
  7047. * to 0.
  7048. */
  7049. if (is_authorized) {
  7050. return is_authorized;
  7051. }
  7052. } else {
  7053. mg_cry_internal(workdata->conn,
  7054. "%s: cannot open authorization file: %s",
  7055. __func__,
  7056. workdata->buf);
  7057. }
  7058. continue;
  7059. }
  7060. /* everything is invalid for the moment (might change in the
  7061. * future) */
  7062. mg_cry_internal(workdata->conn,
  7063. "%s: syntax error in authorization file: %s",
  7064. __func__,
  7065. workdata->buf);
  7066. continue;
  7067. }
  7068. workdata->f_domain = strchr(workdata->f_user, ':');
  7069. if (workdata->f_domain == NULL) {
  7070. mg_cry_internal(workdata->conn,
  7071. "%s: syntax error in authorization file: %s",
  7072. __func__,
  7073. workdata->buf);
  7074. continue;
  7075. }
  7076. *(char *)(workdata->f_domain) = 0;
  7077. (workdata->f_domain)++;
  7078. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7079. if (workdata->f_ha1 == NULL) {
  7080. mg_cry_internal(workdata->conn,
  7081. "%s: syntax error in authorization file: %s",
  7082. __func__,
  7083. workdata->buf);
  7084. continue;
  7085. }
  7086. *(char *)(workdata->f_ha1) = 0;
  7087. (workdata->f_ha1)++;
  7088. if (!strcmp(workdata->ah.user, workdata->f_user)
  7089. && !strcmp(workdata->domain, workdata->f_domain)) {
  7090. return check_password(workdata->conn->request_info.request_method,
  7091. workdata->f_ha1,
  7092. workdata->ah.uri,
  7093. workdata->ah.nonce,
  7094. workdata->ah.nc,
  7095. workdata->ah.cnonce,
  7096. workdata->ah.qop,
  7097. workdata->ah.response);
  7098. }
  7099. }
  7100. return is_authorized;
  7101. }
  7102. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7103. static int
  7104. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7105. {
  7106. struct read_auth_file_struct workdata;
  7107. char buf[MG_BUF_LEN];
  7108. if (!conn || !conn->dom_ctx) {
  7109. return 0;
  7110. }
  7111. memset(&workdata, 0, sizeof(workdata));
  7112. workdata.conn = conn;
  7113. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7114. return 0;
  7115. }
  7116. if (realm) {
  7117. workdata.domain = realm;
  7118. } else {
  7119. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7120. }
  7121. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7122. }
  7123. /* Public function to check http digest authentication header */
  7124. int
  7125. mg_check_digest_access_authentication(struct mg_connection *conn,
  7126. const char *realm,
  7127. const char *filename)
  7128. {
  7129. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7130. int auth;
  7131. if (!conn || !filename) {
  7132. return -1;
  7133. }
  7134. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7135. return -2;
  7136. }
  7137. auth = authorize(conn, &file, realm);
  7138. mg_fclose(&file.access);
  7139. return auth;
  7140. }
  7141. /* Return 1 if request is authorised, 0 otherwise. */
  7142. static int
  7143. check_authorization(struct mg_connection *conn, const char *path)
  7144. {
  7145. char fname[PATH_MAX];
  7146. struct vec uri_vec, filename_vec;
  7147. const char *list;
  7148. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7149. int authorized = 1, truncated;
  7150. if (!conn || !conn->dom_ctx) {
  7151. return 0;
  7152. }
  7153. list = conn->dom_ctx->config[PROTECT_URI];
  7154. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7155. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7156. mg_snprintf(conn,
  7157. &truncated,
  7158. fname,
  7159. sizeof(fname),
  7160. "%.*s",
  7161. (int)filename_vec.len,
  7162. filename_vec.ptr);
  7163. if (truncated
  7164. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7165. mg_cry_internal(conn,
  7166. "%s: cannot open %s: %s",
  7167. __func__,
  7168. fname,
  7169. strerror(errno));
  7170. }
  7171. break;
  7172. }
  7173. }
  7174. if (!is_file_opened(&file.access)) {
  7175. open_auth_file(conn, path, &file);
  7176. }
  7177. if (is_file_opened(&file.access)) {
  7178. authorized = authorize(conn, &file, NULL);
  7179. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7180. }
  7181. return authorized;
  7182. }
  7183. /* Internal function. Assumes conn is valid */
  7184. static void
  7185. send_authorization_request(struct mg_connection *conn, const char *realm)
  7186. {
  7187. char date[64];
  7188. time_t curtime = time(NULL);
  7189. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7190. if (!realm) {
  7191. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7192. }
  7193. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7194. nonce += conn->dom_ctx->nonce_count;
  7195. ++conn->dom_ctx->nonce_count;
  7196. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7197. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7198. conn->status_code = 401;
  7199. conn->must_close = 1;
  7200. gmt_time_string(date, sizeof(date), &curtime);
  7201. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7202. send_no_cache_header(conn);
  7203. send_additional_header(conn);
  7204. mg_printf(conn,
  7205. "Date: %s\r\n"
  7206. "Connection: %s\r\n"
  7207. "Content-Length: 0\r\n"
  7208. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7209. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7210. date,
  7211. suggest_connection_header(conn),
  7212. realm,
  7213. nonce);
  7214. }
  7215. /* Interface function. Parameters are provided by the user, so do
  7216. * at least some basic checks.
  7217. */
  7218. int
  7219. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7220. const char *realm)
  7221. {
  7222. if (conn && conn->dom_ctx) {
  7223. send_authorization_request(conn, realm);
  7224. return 0;
  7225. }
  7226. return -1;
  7227. }
  7228. #if !defined(NO_FILES)
  7229. static int
  7230. is_authorized_for_put(struct mg_connection *conn)
  7231. {
  7232. if (conn) {
  7233. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7234. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7235. int ret = 0;
  7236. if (passfile != NULL
  7237. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7238. ret = authorize(conn, &file, NULL);
  7239. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7240. }
  7241. return ret;
  7242. }
  7243. return 0;
  7244. }
  7245. #endif
  7246. int
  7247. mg_modify_passwords_file(const char *fname,
  7248. const char *domain,
  7249. const char *user,
  7250. const char *pass)
  7251. {
  7252. int found, i;
  7253. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7254. FILE *fp, *fp2;
  7255. found = 0;
  7256. fp = fp2 = NULL;
  7257. /* Regard empty password as no password - remove user record. */
  7258. if ((pass != NULL) && (pass[0] == '\0')) {
  7259. pass = NULL;
  7260. }
  7261. /* Other arguments must not be empty */
  7262. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7263. return 0;
  7264. }
  7265. /* Using the given file format, user name and domain must not contain
  7266. * ':'
  7267. */
  7268. if (strchr(user, ':') != NULL) {
  7269. return 0;
  7270. }
  7271. if (strchr(domain, ':') != NULL) {
  7272. return 0;
  7273. }
  7274. /* Do not allow control characters like newline in user name and domain.
  7275. * Do not allow excessively long names either. */
  7276. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7277. if (iscntrl(user[i])) {
  7278. return 0;
  7279. }
  7280. }
  7281. if (user[i]) {
  7282. return 0;
  7283. }
  7284. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7285. if (iscntrl(domain[i])) {
  7286. return 0;
  7287. }
  7288. }
  7289. if (domain[i]) {
  7290. return 0;
  7291. }
  7292. /* The maximum length of the path to the password file is limited */
  7293. if ((strlen(fname) + 4) >= PATH_MAX) {
  7294. return 0;
  7295. }
  7296. /* Create a temporary file name. Length has been checked before. */
  7297. strcpy(tmp, fname);
  7298. strcat(tmp, ".tmp");
  7299. /* Create the file if does not exist */
  7300. /* Use of fopen here is OK, since fname is only ASCII */
  7301. if ((fp = fopen(fname, "a+")) != NULL) {
  7302. (void)fclose(fp);
  7303. }
  7304. /* Open the given file and temporary file */
  7305. if ((fp = fopen(fname, "r")) == NULL) {
  7306. return 0;
  7307. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7308. fclose(fp);
  7309. return 0;
  7310. }
  7311. /* Copy the stuff to temporary file */
  7312. while (fgets(line, sizeof(line), fp) != NULL) {
  7313. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7314. continue;
  7315. }
  7316. u[255] = 0;
  7317. d[255] = 0;
  7318. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7319. found++;
  7320. if (pass != NULL) {
  7321. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7322. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7323. }
  7324. } else {
  7325. fprintf(fp2, "%s", line);
  7326. }
  7327. }
  7328. /* If new user, just add it */
  7329. if (!found && (pass != NULL)) {
  7330. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7331. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7332. }
  7333. /* Close files */
  7334. fclose(fp);
  7335. fclose(fp2);
  7336. /* Put the temp file in place of real file */
  7337. IGNORE_UNUSED_RESULT(remove(fname));
  7338. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7339. return 1;
  7340. }
  7341. static int
  7342. is_valid_port(unsigned long port)
  7343. {
  7344. return (port <= 0xffff);
  7345. }
  7346. static int
  7347. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7348. {
  7349. struct addrinfo hints, *res, *ressave;
  7350. int func_ret = 0;
  7351. int gai_ret;
  7352. memset(&hints, 0, sizeof(struct addrinfo));
  7353. hints.ai_family = af;
  7354. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7355. if (gai_ret != 0) {
  7356. /* gai_strerror could be used to convert gai_ret to a string */
  7357. /* POSIX return values: see
  7358. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7359. */
  7360. /* Windows return values: see
  7361. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7362. */
  7363. return 0;
  7364. }
  7365. ressave = res;
  7366. while (res) {
  7367. if (dstlen >= (size_t)res->ai_addrlen) {
  7368. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7369. func_ret = 1;
  7370. }
  7371. res = res->ai_next;
  7372. }
  7373. freeaddrinfo(ressave);
  7374. return func_ret;
  7375. }
  7376. static int
  7377. connect_socket(struct mg_context *ctx /* may be NULL */,
  7378. const char *host,
  7379. int port,
  7380. int use_ssl,
  7381. char *ebuf,
  7382. size_t ebuf_len,
  7383. SOCKET *sock /* output: socket, must not be NULL */,
  7384. union usa *sa /* output: socket address, must not be NULL */
  7385. )
  7386. {
  7387. int ip_ver = 0;
  7388. int conn_ret = -1;
  7389. *sock = INVALID_SOCKET;
  7390. memset(sa, 0, sizeof(*sa));
  7391. if (ebuf_len > 0) {
  7392. *ebuf = 0;
  7393. }
  7394. if (host == NULL) {
  7395. mg_snprintf(NULL,
  7396. NULL, /* No truncation check for ebuf */
  7397. ebuf,
  7398. ebuf_len,
  7399. "%s",
  7400. "NULL host");
  7401. return 0;
  7402. }
  7403. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7404. mg_snprintf(NULL,
  7405. NULL, /* No truncation check for ebuf */
  7406. ebuf,
  7407. ebuf_len,
  7408. "%s",
  7409. "invalid port");
  7410. return 0;
  7411. }
  7412. #if !defined(NO_SSL)
  7413. #if !defined(NO_SSL_DL)
  7414. #if defined(OPENSSL_API_1_1)
  7415. if (use_ssl && (TLS_client_method == NULL)) {
  7416. mg_snprintf(NULL,
  7417. NULL, /* No truncation check for ebuf */
  7418. ebuf,
  7419. ebuf_len,
  7420. "%s",
  7421. "SSL is not initialized");
  7422. return 0;
  7423. }
  7424. #else
  7425. if (use_ssl && (SSLv23_client_method == NULL)) {
  7426. mg_snprintf(NULL,
  7427. NULL, /* No truncation check for ebuf */
  7428. ebuf,
  7429. ebuf_len,
  7430. "%s",
  7431. "SSL is not initialized");
  7432. return 0;
  7433. }
  7434. #endif /* OPENSSL_API_1_1 */
  7435. #else
  7436. (void)use_ssl;
  7437. #endif /* NO_SSL_DL */
  7438. #else
  7439. (void)use_ssl;
  7440. #endif /* !defined(NO_SSL) */
  7441. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7442. sa->sin.sin_family = AF_INET;
  7443. sa->sin.sin_port = htons((uint16_t)port);
  7444. ip_ver = 4;
  7445. #if defined(USE_IPV6)
  7446. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7447. sa->sin6.sin6_family = AF_INET6;
  7448. sa->sin6.sin6_port = htons((uint16_t)port);
  7449. ip_ver = 6;
  7450. } else if (host[0] == '[') {
  7451. /* While getaddrinfo on Windows will work with [::1],
  7452. * getaddrinfo on Linux only works with ::1 (without []). */
  7453. size_t l = strlen(host + 1);
  7454. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7455. if (h) {
  7456. h[l - 1] = 0;
  7457. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7458. sa->sin6.sin6_family = AF_INET6;
  7459. sa->sin6.sin6_port = htons((uint16_t)port);
  7460. ip_ver = 6;
  7461. }
  7462. mg_free(h);
  7463. }
  7464. #endif
  7465. }
  7466. if (ip_ver == 0) {
  7467. mg_snprintf(NULL,
  7468. NULL, /* No truncation check for ebuf */
  7469. ebuf,
  7470. ebuf_len,
  7471. "%s",
  7472. "host not found");
  7473. return 0;
  7474. }
  7475. if (ip_ver == 4) {
  7476. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7477. }
  7478. #if defined(USE_IPV6)
  7479. else if (ip_ver == 6) {
  7480. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7481. }
  7482. #endif
  7483. if (*sock == INVALID_SOCKET) {
  7484. mg_snprintf(NULL,
  7485. NULL, /* No truncation check for ebuf */
  7486. ebuf,
  7487. ebuf_len,
  7488. "socket(): %s",
  7489. strerror(ERRNO));
  7490. return 0;
  7491. }
  7492. if (0 != set_non_blocking_mode(*sock)) {
  7493. mg_snprintf(NULL,
  7494. NULL, /* No truncation check for ebuf */
  7495. ebuf,
  7496. ebuf_len,
  7497. "Cannot set socket to non-blocking: %s",
  7498. strerror(ERRNO));
  7499. closesocket(*sock);
  7500. *sock = INVALID_SOCKET;
  7501. return 0;
  7502. }
  7503. set_close_on_exec(*sock, fc(ctx));
  7504. if (ip_ver == 4) {
  7505. /* connected with IPv4 */
  7506. conn_ret = connect(*sock,
  7507. (struct sockaddr *)((void *)&sa->sin),
  7508. sizeof(sa->sin));
  7509. }
  7510. #if defined(USE_IPV6)
  7511. else if (ip_ver == 6) {
  7512. /* connected with IPv6 */
  7513. conn_ret = connect(*sock,
  7514. (struct sockaddr *)((void *)&sa->sin6),
  7515. sizeof(sa->sin6));
  7516. }
  7517. #endif
  7518. #if defined(_WIN32)
  7519. if (conn_ret != 0) {
  7520. DWORD err = WSAGetLastError(); /* could return WSAEWOULDBLOCK */
  7521. conn_ret = (int)err;
  7522. #if !defined(EINPROGRESS)
  7523. #define EINPROGRESS (WSAEWOULDBLOCK) /* Winsock equivalent */
  7524. #endif /* if !defined(EINPROGRESS) */
  7525. }
  7526. #endif
  7527. if ((conn_ret != 0) && (conn_ret != EINPROGRESS)) {
  7528. /* Data for getsockopt */
  7529. int sockerr = -1;
  7530. void *psockerr = &sockerr;
  7531. #if defined(_WIN32)
  7532. int len = (int)sizeof(sockerr);
  7533. #else
  7534. socklen_t len = (socklen_t)sizeof(sockerr);
  7535. #endif
  7536. /* Data for poll */
  7537. struct pollfd pfd[1];
  7538. int pollres;
  7539. int ms_wait = 10000; /* 10 second timeout */
  7540. /* For a non-blocking socket, the connect sequence is:
  7541. * 1) call connect (will not block)
  7542. * 2) wait until the socket is ready for writing (select or poll)
  7543. * 3) check connection state with getsockopt
  7544. */
  7545. pfd[0].fd = *sock;
  7546. pfd[0].events = POLLOUT;
  7547. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  7548. if (pollres != 1) {
  7549. /* Not connected */
  7550. mg_snprintf(NULL,
  7551. NULL, /* No truncation check for ebuf */
  7552. ebuf,
  7553. ebuf_len,
  7554. "connect(%s:%d): timeout",
  7555. host,
  7556. port);
  7557. closesocket(*sock);
  7558. *sock = INVALID_SOCKET;
  7559. return 0;
  7560. }
  7561. #if defined(_WIN32)
  7562. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7563. #else
  7564. getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7565. #endif
  7566. if (sockerr != 0) {
  7567. /* Not connected */
  7568. mg_snprintf(NULL,
  7569. NULL, /* No truncation check for ebuf */
  7570. ebuf,
  7571. ebuf_len,
  7572. "connect(%s:%d): error %s",
  7573. host,
  7574. port,
  7575. strerror(sockerr));
  7576. closesocket(*sock);
  7577. *sock = INVALID_SOCKET;
  7578. return 0;
  7579. }
  7580. }
  7581. return 1;
  7582. }
  7583. int
  7584. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7585. {
  7586. static const char *dont_escape = "._-$,;~()";
  7587. static const char *hex = "0123456789abcdef";
  7588. char *pos = dst;
  7589. const char *end = dst + dst_len - 1;
  7590. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7591. if (isalnum(*(const unsigned char *)src)
  7592. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7593. *pos = *src;
  7594. } else if (pos + 2 < end) {
  7595. pos[0] = '%';
  7596. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7597. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7598. pos += 2;
  7599. } else {
  7600. break;
  7601. }
  7602. }
  7603. *pos = '\0';
  7604. return (*src == '\0') ? (int)(pos - dst) : -1;
  7605. }
  7606. /* Return 0 on success, non-zero if an error occurs. */
  7607. static int
  7608. print_dir_entry(struct de *de)
  7609. {
  7610. size_t hrefsize;
  7611. char *href;
  7612. char size[64], mod[64];
  7613. #if defined(REENTRANT_TIME)
  7614. struct tm _tm;
  7615. struct tm *tm = &_tm;
  7616. #else
  7617. struct tm *tm;
  7618. #endif
  7619. hrefsize = PATH_MAX * 3; /* worst case */
  7620. href = (char *)mg_malloc(hrefsize);
  7621. if (href == NULL) {
  7622. return -1;
  7623. }
  7624. if (de->file.is_directory) {
  7625. mg_snprintf(de->conn,
  7626. NULL, /* Buffer is big enough */
  7627. size,
  7628. sizeof(size),
  7629. "%s",
  7630. "[DIRECTORY]");
  7631. } else {
  7632. /* We use (signed) cast below because MSVC 6 compiler cannot
  7633. * convert unsigned __int64 to double. Sigh. */
  7634. if (de->file.size < 1024) {
  7635. mg_snprintf(de->conn,
  7636. NULL, /* Buffer is big enough */
  7637. size,
  7638. sizeof(size),
  7639. "%d",
  7640. (int)de->file.size);
  7641. } else if (de->file.size < 0x100000) {
  7642. mg_snprintf(de->conn,
  7643. NULL, /* Buffer is big enough */
  7644. size,
  7645. sizeof(size),
  7646. "%.1fk",
  7647. (double)de->file.size / 1024.0);
  7648. } else if (de->file.size < 0x40000000) {
  7649. mg_snprintf(de->conn,
  7650. NULL, /* Buffer is big enough */
  7651. size,
  7652. sizeof(size),
  7653. "%.1fM",
  7654. (double)de->file.size / 1048576);
  7655. } else {
  7656. mg_snprintf(de->conn,
  7657. NULL, /* Buffer is big enough */
  7658. size,
  7659. sizeof(size),
  7660. "%.1fG",
  7661. (double)de->file.size / 1073741824);
  7662. }
  7663. }
  7664. /* Note: mg_snprintf will not cause a buffer overflow above.
  7665. * So, string truncation checks are not required here. */
  7666. #if defined(REENTRANT_TIME)
  7667. localtime_r(&de->file.last_modified, tm);
  7668. #else
  7669. tm = localtime(&de->file.last_modified);
  7670. #endif
  7671. if (tm != NULL) {
  7672. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7673. } else {
  7674. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7675. mod[sizeof(mod) - 1] = '\0';
  7676. }
  7677. mg_url_encode(de->file_name, href, hrefsize);
  7678. mg_printf(de->conn,
  7679. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7680. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7681. de->conn->request_info.local_uri,
  7682. href,
  7683. de->file.is_directory ? "/" : "",
  7684. de->file_name,
  7685. de->file.is_directory ? "/" : "",
  7686. mod,
  7687. size);
  7688. mg_free(href);
  7689. return 0;
  7690. }
  7691. /* This function is called from send_directory() and used for
  7692. * sorting directory entries by size, or name, or modification time.
  7693. * On windows, __cdecl specification is needed in case if project is built
  7694. * with __stdcall convention. qsort always requires __cdels callback. */
  7695. static int WINCDECL
  7696. compare_dir_entries(const void *p1, const void *p2)
  7697. {
  7698. if (p1 && p2) {
  7699. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7700. const char *query_string = a->conn->request_info.query_string;
  7701. int cmp_result = 0;
  7702. if (query_string == NULL) {
  7703. query_string = "na";
  7704. }
  7705. if (a->file.is_directory && !b->file.is_directory) {
  7706. return -1; /* Always put directories on top */
  7707. } else if (!a->file.is_directory && b->file.is_directory) {
  7708. return 1; /* Always put directories on top */
  7709. } else if (*query_string == 'n') {
  7710. cmp_result = strcmp(a->file_name, b->file_name);
  7711. } else if (*query_string == 's') {
  7712. cmp_result = (a->file.size == b->file.size)
  7713. ? 0
  7714. : ((a->file.size > b->file.size) ? 1 : -1);
  7715. } else if (*query_string == 'd') {
  7716. cmp_result =
  7717. (a->file.last_modified == b->file.last_modified)
  7718. ? 0
  7719. : ((a->file.last_modified > b->file.last_modified) ? 1
  7720. : -1);
  7721. }
  7722. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7723. }
  7724. return 0;
  7725. }
  7726. static int
  7727. must_hide_file(struct mg_connection *conn, const char *path)
  7728. {
  7729. if (conn && conn->dom_ctx) {
  7730. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7731. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7732. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7733. || ((pattern != NULL)
  7734. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7735. }
  7736. return 0;
  7737. }
  7738. static int
  7739. scan_directory(struct mg_connection *conn,
  7740. const char *dir,
  7741. void *data,
  7742. int (*cb)(struct de *, void *))
  7743. {
  7744. char path[PATH_MAX];
  7745. struct dirent *dp;
  7746. DIR *dirp;
  7747. struct de de;
  7748. int truncated;
  7749. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7750. return 0;
  7751. } else {
  7752. de.conn = conn;
  7753. while ((dp = mg_readdir(dirp)) != NULL) {
  7754. /* Do not show current dir and hidden files */
  7755. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7756. || must_hide_file(conn, dp->d_name)) {
  7757. continue;
  7758. }
  7759. mg_snprintf(
  7760. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7761. /* If we don't memset stat structure to zero, mtime will have
  7762. * garbage and strftime() will segfault later on in
  7763. * print_dir_entry(). memset is required only if mg_stat()
  7764. * fails. For more details, see
  7765. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7766. memset(&de.file, 0, sizeof(de.file));
  7767. if (truncated) {
  7768. /* If the path is not complete, skip processing. */
  7769. continue;
  7770. }
  7771. if (!mg_stat(conn, path, &de.file)) {
  7772. mg_cry_internal(conn,
  7773. "%s: mg_stat(%s) failed: %s",
  7774. __func__,
  7775. path,
  7776. strerror(ERRNO));
  7777. }
  7778. de.file_name = dp->d_name;
  7779. cb(&de, data);
  7780. }
  7781. (void)mg_closedir(dirp);
  7782. }
  7783. return 1;
  7784. }
  7785. #if !defined(NO_FILES)
  7786. static int
  7787. remove_directory(struct mg_connection *conn, const char *dir)
  7788. {
  7789. char path[PATH_MAX];
  7790. struct dirent *dp;
  7791. DIR *dirp;
  7792. struct de de;
  7793. int truncated;
  7794. int ok = 1;
  7795. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7796. return 0;
  7797. } else {
  7798. de.conn = conn;
  7799. while ((dp = mg_readdir(dirp)) != NULL) {
  7800. /* Do not show current dir (but show hidden files as they will
  7801. * also be removed) */
  7802. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7803. continue;
  7804. }
  7805. mg_snprintf(
  7806. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7807. /* If we don't memset stat structure to zero, mtime will have
  7808. * garbage and strftime() will segfault later on in
  7809. * print_dir_entry(). memset is required only if mg_stat()
  7810. * fails. For more details, see
  7811. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7812. memset(&de.file, 0, sizeof(de.file));
  7813. if (truncated) {
  7814. /* Do not delete anything shorter */
  7815. ok = 0;
  7816. continue;
  7817. }
  7818. if (!mg_stat(conn, path, &de.file)) {
  7819. mg_cry_internal(conn,
  7820. "%s: mg_stat(%s) failed: %s",
  7821. __func__,
  7822. path,
  7823. strerror(ERRNO));
  7824. ok = 0;
  7825. }
  7826. if (de.file.is_directory) {
  7827. if (remove_directory(conn, path) == 0) {
  7828. ok = 0;
  7829. }
  7830. } else {
  7831. /* This will fail file is the file is in memory */
  7832. if (mg_remove(conn, path) == 0) {
  7833. ok = 0;
  7834. }
  7835. }
  7836. }
  7837. (void)mg_closedir(dirp);
  7838. IGNORE_UNUSED_RESULT(rmdir(dir));
  7839. }
  7840. return ok;
  7841. }
  7842. #endif
  7843. struct dir_scan_data {
  7844. struct de *entries;
  7845. unsigned int num_entries;
  7846. unsigned int arr_size;
  7847. };
  7848. /* Behaves like realloc(), but frees original pointer on failure */
  7849. static void *
  7850. realloc2(void *ptr, size_t size)
  7851. {
  7852. void *new_ptr = mg_realloc(ptr, size);
  7853. if (new_ptr == NULL) {
  7854. mg_free(ptr);
  7855. }
  7856. return new_ptr;
  7857. }
  7858. static int
  7859. dir_scan_callback(struct de *de, void *data)
  7860. {
  7861. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7862. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7863. dsd->arr_size *= 2;
  7864. dsd->entries =
  7865. (struct de *)realloc2(dsd->entries,
  7866. dsd->arr_size * sizeof(dsd->entries[0]));
  7867. }
  7868. if (dsd->entries == NULL) {
  7869. /* TODO(lsm, low): propagate an error to the caller */
  7870. dsd->num_entries = 0;
  7871. } else {
  7872. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7873. dsd->entries[dsd->num_entries].file = de->file;
  7874. dsd->entries[dsd->num_entries].conn = de->conn;
  7875. dsd->num_entries++;
  7876. }
  7877. return 0;
  7878. }
  7879. static void
  7880. handle_directory_request(struct mg_connection *conn, const char *dir)
  7881. {
  7882. unsigned int i;
  7883. int sort_direction;
  7884. struct dir_scan_data data = {NULL, 0, 128};
  7885. char date[64];
  7886. time_t curtime = time(NULL);
  7887. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7888. mg_send_http_error(conn,
  7889. 500,
  7890. "Error: Cannot open directory\nopendir(%s): %s",
  7891. dir,
  7892. strerror(ERRNO));
  7893. return;
  7894. }
  7895. gmt_time_string(date, sizeof(date), &curtime);
  7896. if (!conn) {
  7897. return;
  7898. }
  7899. sort_direction = ((conn->request_info.query_string != NULL)
  7900. && (conn->request_info.query_string[1] == 'd'))
  7901. ? 'a'
  7902. : 'd';
  7903. conn->must_close = 1;
  7904. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7905. send_static_cache_header(conn);
  7906. send_additional_header(conn);
  7907. mg_printf(conn,
  7908. "Date: %s\r\n"
  7909. "Connection: close\r\n"
  7910. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7911. date);
  7912. mg_printf(conn,
  7913. "<html><head><title>Index of %s</title>"
  7914. "<style>th {text-align: left;}</style></head>"
  7915. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7916. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7917. "<th><a href=\"?d%c\">Modified</a></th>"
  7918. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7919. "<tr><td colspan=\"3\"><hr></td></tr>",
  7920. conn->request_info.local_uri,
  7921. conn->request_info.local_uri,
  7922. sort_direction,
  7923. sort_direction,
  7924. sort_direction);
  7925. /* Print first entry - link to a parent directory */
  7926. mg_printf(conn,
  7927. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7928. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7929. conn->request_info.local_uri,
  7930. "..",
  7931. "Parent directory",
  7932. "-",
  7933. "-");
  7934. /* Sort and print directory entries */
  7935. if (data.entries != NULL) {
  7936. qsort(data.entries,
  7937. (size_t)data.num_entries,
  7938. sizeof(data.entries[0]),
  7939. compare_dir_entries);
  7940. for (i = 0; i < data.num_entries; i++) {
  7941. print_dir_entry(&data.entries[i]);
  7942. mg_free(data.entries[i].file_name);
  7943. }
  7944. mg_free(data.entries);
  7945. }
  7946. mg_printf(conn, "%s", "</table></body></html>");
  7947. conn->status_code = 200;
  7948. }
  7949. /* Send len bytes from the opened file to the client. */
  7950. static void
  7951. send_file_data(struct mg_connection *conn,
  7952. struct mg_file *filep,
  7953. int64_t offset,
  7954. int64_t len)
  7955. {
  7956. char buf[MG_BUF_LEN];
  7957. int to_read, num_read, num_written;
  7958. int64_t size;
  7959. if (!filep || !conn) {
  7960. return;
  7961. }
  7962. /* Sanity check the offset */
  7963. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7964. : (int64_t)(filep->stat.size);
  7965. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7966. #if defined(MG_USE_OPEN_FILE)
  7967. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7968. /* file stored in memory */
  7969. if (len > size - offset) {
  7970. len = size - offset;
  7971. }
  7972. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7973. } else /* else block below */
  7974. #endif
  7975. if (len > 0 && filep->access.fp != NULL) {
  7976. /* file stored on disk */
  7977. #if defined(__linux__)
  7978. /* sendfile is only available for Linux */
  7979. if ((conn->ssl == 0) && (conn->throttle == 0)
  7980. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7981. "yes"))) {
  7982. off_t sf_offs = (off_t)offset;
  7983. ssize_t sf_sent;
  7984. int sf_file = fileno(filep->access.fp);
  7985. int loop_cnt = 0;
  7986. do {
  7987. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7988. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7989. size_t sf_tosend =
  7990. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7991. sf_sent =
  7992. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7993. if (sf_sent > 0) {
  7994. len -= sf_sent;
  7995. offset += sf_sent;
  7996. } else if (loop_cnt == 0) {
  7997. /* This file can not be sent using sendfile.
  7998. * This might be the case for pseudo-files in the
  7999. * /sys/ and /proc/ file system.
  8000. * Use the regular user mode copy code instead. */
  8001. break;
  8002. } else if (sf_sent == 0) {
  8003. /* No error, but 0 bytes sent. May be EOF? */
  8004. return;
  8005. }
  8006. loop_cnt++;
  8007. } while ((len > 0) && (sf_sent >= 0));
  8008. if (sf_sent > 0) {
  8009. return; /* OK */
  8010. }
  8011. /* sf_sent<0 means error, thus fall back to the classic way */
  8012. /* This is always the case, if sf_file is not a "normal" file,
  8013. * e.g., for sending data from the output of a CGI process. */
  8014. offset = (int64_t)sf_offs;
  8015. }
  8016. #endif
  8017. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8018. mg_cry_internal(conn,
  8019. "%s: fseeko() failed: %s",
  8020. __func__,
  8021. strerror(ERRNO));
  8022. mg_send_http_error(
  8023. conn,
  8024. 500,
  8025. "%s",
  8026. "Error: Unable to access file at requested position.");
  8027. } else {
  8028. while (len > 0) {
  8029. /* Calculate how much to read from the file in the buffer */
  8030. to_read = sizeof(buf);
  8031. if ((int64_t)to_read > len) {
  8032. to_read = (int)len;
  8033. }
  8034. /* Read from file, exit the loop on error */
  8035. if ((num_read =
  8036. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8037. <= 0) {
  8038. break;
  8039. }
  8040. /* Send read bytes to the client, exit the loop on error */
  8041. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8042. != num_read) {
  8043. break;
  8044. }
  8045. /* Both read and were successful, adjust counters */
  8046. len -= num_written;
  8047. }
  8048. }
  8049. }
  8050. }
  8051. static int
  8052. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8053. {
  8054. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8055. }
  8056. static void
  8057. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8058. {
  8059. if ((filestat != NULL) && (buf != NULL)) {
  8060. mg_snprintf(NULL,
  8061. NULL, /* All calls to construct_etag use 64 byte buffer */
  8062. buf,
  8063. buf_len,
  8064. "\"%lx.%" INT64_FMT "\"",
  8065. (unsigned long)filestat->last_modified,
  8066. filestat->size);
  8067. }
  8068. }
  8069. static void
  8070. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8071. {
  8072. if (filep != NULL && filep->fp != NULL) {
  8073. #if defined(_WIN32)
  8074. (void)conn; /* Unused. */
  8075. #else
  8076. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8077. mg_cry_internal(conn,
  8078. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8079. __func__,
  8080. strerror(ERRNO));
  8081. }
  8082. #endif
  8083. }
  8084. }
  8085. #if defined(USE_ZLIB)
  8086. #include "mod_zlib.inl"
  8087. #endif
  8088. static void
  8089. handle_static_file_request(struct mg_connection *conn,
  8090. const char *path,
  8091. struct mg_file *filep,
  8092. const char *mime_type,
  8093. const char *additional_headers)
  8094. {
  8095. char date[64], lm[64], etag[64];
  8096. char range[128]; /* large enough, so there will be no overflow */
  8097. const char *msg = "OK", *hdr;
  8098. time_t curtime = time(NULL);
  8099. int64_t cl, r1, r2;
  8100. struct vec mime_vec;
  8101. int n, truncated;
  8102. char gz_path[PATH_MAX];
  8103. const char *encoding = "";
  8104. const char *cors1, *cors2, *cors3;
  8105. int is_head_request;
  8106. #if defined(USE_ZLIB)
  8107. /* Compression is allowed, unless there is a reason not to use compression.
  8108. * If the file is already compressed, too small or a "range" request was
  8109. * made, on the fly compression is not possible. */
  8110. int allow_on_the_fly_compression = 1;
  8111. #endif
  8112. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8113. return;
  8114. }
  8115. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8116. if (mime_type == NULL) {
  8117. get_mime_type(conn, path, &mime_vec);
  8118. } else {
  8119. mime_vec.ptr = mime_type;
  8120. mime_vec.len = strlen(mime_type);
  8121. }
  8122. if (filep->stat.size > INT64_MAX) {
  8123. mg_send_http_error(conn,
  8124. 500,
  8125. "Error: File size is too large to send\n%" INT64_FMT,
  8126. filep->stat.size);
  8127. return;
  8128. }
  8129. cl = (int64_t)filep->stat.size;
  8130. conn->status_code = 200;
  8131. range[0] = '\0';
  8132. #if defined(USE_ZLIB)
  8133. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8134. * it's important to rewrite the filename after resolving
  8135. * the mime type from it, to preserve the actual file's type */
  8136. if (!conn->accept_gzip) {
  8137. allow_on_the_fly_compression = 0;
  8138. }
  8139. #endif
  8140. if (filep->stat.is_gzipped) {
  8141. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8142. if (truncated) {
  8143. mg_send_http_error(conn,
  8144. 500,
  8145. "Error: Path of zipped file too long (%s)",
  8146. path);
  8147. return;
  8148. }
  8149. path = gz_path;
  8150. encoding = "Content-Encoding: gzip\r\n";
  8151. #if defined(USE_ZLIB)
  8152. /* File is already compressed. No "on the fly" compression. */
  8153. allow_on_the_fly_compression = 0;
  8154. #endif
  8155. }
  8156. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8157. mg_send_http_error(conn,
  8158. 500,
  8159. "Error: Cannot open file\nfopen(%s): %s",
  8160. path,
  8161. strerror(ERRNO));
  8162. return;
  8163. }
  8164. fclose_on_exec(&filep->access, conn);
  8165. /* If "Range" request was made: parse header, send only selected part
  8166. * of the file. */
  8167. r1 = r2 = 0;
  8168. hdr = mg_get_header(conn, "Range");
  8169. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  8170. && (r1 >= 0) && (r2 >= 0)) {
  8171. /* actually, range requests don't play well with a pre-gzipped
  8172. * file (since the range is specified in the uncompressed space) */
  8173. if (filep->stat.is_gzipped) {
  8174. mg_send_http_error(
  8175. conn,
  8176. 416, /* 416 = Range Not Satisfiable */
  8177. "%s",
  8178. "Error: Range requests in gzipped files are not supported");
  8179. (void)mg_fclose(
  8180. &filep->access); /* ignore error on read only file */
  8181. return;
  8182. }
  8183. conn->status_code = 206;
  8184. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8185. mg_snprintf(conn,
  8186. NULL, /* range buffer is big enough */
  8187. range,
  8188. sizeof(range),
  8189. "Content-Range: bytes "
  8190. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8191. r1,
  8192. r1 + cl - 1,
  8193. filep->stat.size);
  8194. msg = "Partial Content";
  8195. #if defined(USE_ZLIB)
  8196. /* Do not compress ranges. */
  8197. allow_on_the_fly_compression = 0;
  8198. #endif
  8199. }
  8200. /* Do not compress small files. Small files do not benefit from file
  8201. * compression, but there is still some overhead. */
  8202. #if defined(USE_ZLIB)
  8203. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8204. /* File is below the size limit. */
  8205. allow_on_the_fly_compression = 0;
  8206. }
  8207. #endif
  8208. /* Standard CORS header */
  8209. hdr = mg_get_header(conn, "Origin");
  8210. if (hdr) {
  8211. /* Cross-origin resource sharing (CORS), see
  8212. * http://www.html5rocks.com/en/tutorials/cors/,
  8213. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8214. * -
  8215. * preflight is not supported for files. */
  8216. cors1 = "Access-Control-Allow-Origin: ";
  8217. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8218. cors3 = "\r\n";
  8219. } else {
  8220. cors1 = cors2 = cors3 = "";
  8221. }
  8222. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8223. * according to
  8224. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8225. gmt_time_string(date, sizeof(date), &curtime);
  8226. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8227. construct_etag(etag, sizeof(etag), &filep->stat);
  8228. /* Send header */
  8229. (void)mg_printf(conn,
  8230. "HTTP/1.1 %d %s\r\n"
  8231. "%s%s%s" /* CORS */
  8232. "Date: %s\r\n"
  8233. "Last-Modified: %s\r\n"
  8234. "Etag: %s\r\n"
  8235. "Content-Type: %.*s\r\n"
  8236. "Connection: %s\r\n",
  8237. conn->status_code,
  8238. msg,
  8239. cors1,
  8240. cors2,
  8241. cors3,
  8242. date,
  8243. lm,
  8244. etag,
  8245. (int)mime_vec.len,
  8246. mime_vec.ptr,
  8247. suggest_connection_header(conn));
  8248. send_static_cache_header(conn);
  8249. send_additional_header(conn);
  8250. #if defined(USE_ZLIB)
  8251. /* On the fly compression allowed */
  8252. if (allow_on_the_fly_compression) {
  8253. /* For on the fly compression, we don't know the content size in
  8254. * advance, so we have to use chunked encoding */
  8255. (void)mg_printf(conn,
  8256. "Content-Encoding: gzip\r\n"
  8257. "Transfer-Encoding: chunked\r\n");
  8258. } else
  8259. #endif
  8260. {
  8261. /* Without on-the-fly compression, we know the content-length
  8262. * and we can use ranges (with on-the-fly compression we cannot).
  8263. * So we send these response headers only in this case. */
  8264. (void)mg_printf(conn,
  8265. "Content-Length: %" INT64_FMT "\r\n"
  8266. "Accept-Ranges: bytes\r\n"
  8267. "%s" /* range */
  8268. "%s" /* encoding */,
  8269. cl,
  8270. range,
  8271. encoding);
  8272. }
  8273. /* The previous code must not add any header starting with X- to make
  8274. * sure no one of the additional_headers is included twice */
  8275. if (additional_headers != NULL) {
  8276. (void)mg_printf(conn,
  8277. "%.*s\r\n\r\n",
  8278. (int)strlen(additional_headers),
  8279. additional_headers);
  8280. } else {
  8281. (void)mg_printf(conn, "\r\n");
  8282. }
  8283. if (!is_head_request) {
  8284. #if defined(USE_ZLIB)
  8285. if (allow_on_the_fly_compression) {
  8286. /* Compress and send */
  8287. send_compressed_data(conn, filep);
  8288. } else
  8289. #endif
  8290. {
  8291. /* Send file directly */
  8292. send_file_data(conn, filep, r1, cl);
  8293. }
  8294. }
  8295. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8296. }
  8297. #if !defined(NO_CACHING)
  8298. /* Return True if we should reply 304 Not Modified. */
  8299. static int
  8300. is_not_modified(const struct mg_connection *conn,
  8301. const struct mg_file_stat *filestat)
  8302. {
  8303. char etag[64];
  8304. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8305. const char *inm = mg_get_header(conn, "If-None-Match");
  8306. construct_etag(etag, sizeof(etag), filestat);
  8307. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8308. || ((ims != NULL)
  8309. && (filestat->last_modified <= parse_date_string(ims)));
  8310. }
  8311. static void
  8312. handle_not_modified_static_file_request(struct mg_connection *conn,
  8313. struct mg_file *filep)
  8314. {
  8315. char date[64], lm[64], etag[64];
  8316. time_t curtime = time(NULL);
  8317. if ((conn == NULL) || (filep == NULL)) {
  8318. return;
  8319. }
  8320. conn->status_code = 304;
  8321. gmt_time_string(date, sizeof(date), &curtime);
  8322. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8323. construct_etag(etag, sizeof(etag), &filep->stat);
  8324. (void)mg_printf(conn,
  8325. "HTTP/1.1 %d %s\r\n"
  8326. "Date: %s\r\n",
  8327. conn->status_code,
  8328. mg_get_response_code_text(conn, conn->status_code),
  8329. date);
  8330. send_static_cache_header(conn);
  8331. send_additional_header(conn);
  8332. (void)mg_printf(conn,
  8333. "Last-Modified: %s\r\n"
  8334. "Etag: %s\r\n"
  8335. "Connection: %s\r\n"
  8336. "\r\n",
  8337. lm,
  8338. etag,
  8339. suggest_connection_header(conn));
  8340. }
  8341. #endif
  8342. void
  8343. mg_send_file(struct mg_connection *conn, const char *path)
  8344. {
  8345. mg_send_mime_file(conn, path, NULL);
  8346. }
  8347. void
  8348. mg_send_mime_file(struct mg_connection *conn,
  8349. const char *path,
  8350. const char *mime_type)
  8351. {
  8352. mg_send_mime_file2(conn, path, mime_type, NULL);
  8353. }
  8354. void
  8355. mg_send_mime_file2(struct mg_connection *conn,
  8356. const char *path,
  8357. const char *mime_type,
  8358. const char *additional_headers)
  8359. {
  8360. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8361. if (!conn) {
  8362. /* No conn */
  8363. return;
  8364. }
  8365. if (mg_stat(conn, path, &file.stat)) {
  8366. #if !defined(NO_CACHING)
  8367. if (is_not_modified(conn, &file.stat)) {
  8368. /* Send 304 "Not Modified" - this must not send any body data */
  8369. handle_not_modified_static_file_request(conn, &file);
  8370. } else
  8371. #endif /* NO_CACHING */
  8372. if (file.stat.is_directory) {
  8373. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8374. "yes")) {
  8375. handle_directory_request(conn, path);
  8376. } else {
  8377. mg_send_http_error(conn,
  8378. 403,
  8379. "%s",
  8380. "Error: Directory listing denied");
  8381. }
  8382. } else {
  8383. handle_static_file_request(
  8384. conn, path, &file, mime_type, additional_headers);
  8385. }
  8386. } else {
  8387. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8388. }
  8389. }
  8390. /* For a given PUT path, create all intermediate subdirectories.
  8391. * Return 0 if the path itself is a directory.
  8392. * Return 1 if the path leads to a file.
  8393. * Return -1 for if the path is too long.
  8394. * Return -2 if path can not be created.
  8395. */
  8396. static int
  8397. put_dir(struct mg_connection *conn, const char *path)
  8398. {
  8399. char buf[PATH_MAX];
  8400. const char *s, *p;
  8401. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8402. size_t len;
  8403. int res = 1;
  8404. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8405. len = (size_t)(p - path);
  8406. if (len >= sizeof(buf)) {
  8407. /* path too long */
  8408. res = -1;
  8409. break;
  8410. }
  8411. memcpy(buf, path, len);
  8412. buf[len] = '\0';
  8413. /* Try to create intermediate directory */
  8414. DEBUG_TRACE("mkdir(%s)", buf);
  8415. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8416. /* path does not exixt and can not be created */
  8417. res = -2;
  8418. break;
  8419. }
  8420. /* Is path itself a directory? */
  8421. if (p[1] == '\0') {
  8422. res = 0;
  8423. }
  8424. }
  8425. return res;
  8426. }
  8427. static void
  8428. remove_bad_file(const struct mg_connection *conn, const char *path)
  8429. {
  8430. int r = mg_remove(conn, path);
  8431. if (r != 0) {
  8432. mg_cry_internal(conn,
  8433. "%s: Cannot remove invalid file %s",
  8434. __func__,
  8435. path);
  8436. }
  8437. }
  8438. long long
  8439. mg_store_body(struct mg_connection *conn, const char *path)
  8440. {
  8441. char buf[MG_BUF_LEN];
  8442. long long len = 0;
  8443. int ret, n;
  8444. struct mg_file fi;
  8445. if (conn->consumed_content != 0) {
  8446. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8447. return -11;
  8448. }
  8449. ret = put_dir(conn, path);
  8450. if (ret < 0) {
  8451. /* -1 for path too long,
  8452. * -2 for path can not be created. */
  8453. return ret;
  8454. }
  8455. if (ret != 1) {
  8456. /* Return 0 means, path itself is a directory. */
  8457. return 0;
  8458. }
  8459. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8460. return -12;
  8461. }
  8462. ret = mg_read(conn, buf, sizeof(buf));
  8463. while (ret > 0) {
  8464. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8465. if (n != ret) {
  8466. (void)mg_fclose(
  8467. &fi.access); /* File is bad and will be removed anyway. */
  8468. remove_bad_file(conn, path);
  8469. return -13;
  8470. }
  8471. len += ret;
  8472. ret = mg_read(conn, buf, sizeof(buf));
  8473. }
  8474. /* File is open for writing. If fclose fails, there was probably an
  8475. * error flushing the buffer to disk, so the file on disk might be
  8476. * broken. Delete it and return an error to the caller. */
  8477. if (mg_fclose(&fi.access) != 0) {
  8478. remove_bad_file(conn, path);
  8479. return -14;
  8480. }
  8481. return len;
  8482. }
  8483. /* Parse a buffer:
  8484. * Forward the string pointer till the end of a word, then
  8485. * terminate it and forward till the begin of the next word.
  8486. */
  8487. static int
  8488. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8489. {
  8490. /* Forward until a space is found - use isgraph here */
  8491. /* See http://www.cplusplus.com/reference/cctype/ */
  8492. while (isgraph(**ppw)) {
  8493. (*ppw)++;
  8494. }
  8495. /* Check end of word */
  8496. if (eol) {
  8497. /* must be a end of line */
  8498. if ((**ppw != '\r') && (**ppw != '\n')) {
  8499. return -1;
  8500. }
  8501. } else {
  8502. /* must be a end of a word, but not a line */
  8503. if (**ppw != ' ') {
  8504. return -1;
  8505. }
  8506. }
  8507. /* Terminate and forward to the next word */
  8508. do {
  8509. **ppw = 0;
  8510. (*ppw)++;
  8511. } while ((**ppw) && isspace(**ppw));
  8512. /* Check after term */
  8513. if (!eol) {
  8514. /* if it's not the end of line, there must be a next word */
  8515. if (!isgraph(**ppw)) {
  8516. return -1;
  8517. }
  8518. }
  8519. /* ok */
  8520. return 1;
  8521. }
  8522. /* Parse HTTP headers from the given buffer, advance buf pointer
  8523. * to the point where parsing stopped.
  8524. * All parameters must be valid pointers (not NULL).
  8525. * Return <0 on error. */
  8526. static int
  8527. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8528. {
  8529. int i;
  8530. int num_headers = 0;
  8531. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8532. char *dp = *buf;
  8533. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8534. dp++;
  8535. }
  8536. if (dp == *buf) {
  8537. /* End of headers reached. */
  8538. break;
  8539. }
  8540. if (*dp != ':') {
  8541. /* This is not a valid field. */
  8542. return -1;
  8543. }
  8544. /* End of header key (*dp == ':') */
  8545. /* Truncate here and set the key name */
  8546. *dp = 0;
  8547. hdr[i].name = *buf;
  8548. do {
  8549. dp++;
  8550. } while (*dp == ' ');
  8551. /* The rest of the line is the value */
  8552. hdr[i].value = dp;
  8553. *buf = dp + strcspn(dp, "\r\n");
  8554. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8555. *buf = NULL;
  8556. }
  8557. num_headers = i + 1;
  8558. if (*buf) {
  8559. (*buf)[0] = 0;
  8560. (*buf)[1] = 0;
  8561. *buf += 2;
  8562. } else {
  8563. *buf = dp;
  8564. break;
  8565. }
  8566. if ((*buf)[0] == '\r') {
  8567. /* This is the end of the header */
  8568. break;
  8569. }
  8570. }
  8571. return num_headers;
  8572. }
  8573. struct mg_http_method_info {
  8574. const char *name;
  8575. int request_has_body;
  8576. int response_has_body;
  8577. int is_safe;
  8578. int is_idempotent;
  8579. int is_cacheable;
  8580. };
  8581. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8582. static struct mg_http_method_info http_methods[] = {
  8583. /* HTTP (RFC 2616) */
  8584. {"GET", 0, 1, 1, 1, 1},
  8585. {"POST", 1, 1, 0, 0, 0},
  8586. {"PUT", 1, 0, 0, 1, 0},
  8587. {"DELETE", 0, 0, 0, 1, 0},
  8588. {"HEAD", 0, 0, 1, 1, 1},
  8589. {"OPTIONS", 0, 0, 1, 1, 0},
  8590. {"CONNECT", 1, 1, 0, 0, 0},
  8591. /* TRACE method (RFC 2616) is not supported for security reasons */
  8592. /* PATCH method (RFC 5789) */
  8593. {"PATCH", 1, 0, 0, 0, 0},
  8594. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8595. /* WEBDAV (RFC 2518) */
  8596. {"PROPFIND", 0, 1, 1, 1, 0},
  8597. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8598. * Some PROPFIND results MAY be cached, with care,
  8599. * as there is no cache validation mechanism for
  8600. * most properties. This method is both safe and
  8601. * idempotent (see Section 9.1 of [RFC2616]). */
  8602. {"MKCOL", 0, 0, 0, 1, 0},
  8603. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8604. * When MKCOL is invoked without a request body,
  8605. * the newly created collection SHOULD have no
  8606. * members. A MKCOL request message may contain
  8607. * a message body. The precise behavior of a MKCOL
  8608. * request when the body is present is undefined,
  8609. * ... ==> We do not support MKCOL with body data.
  8610. * This method is idempotent, but not safe (see
  8611. * Section 9.1 of [RFC2616]). Responses to this
  8612. * method MUST NOT be cached. */
  8613. /* Unsupported WEBDAV Methods: */
  8614. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8615. /* + 11 methods from RFC 3253 */
  8616. /* ORDERPATCH (RFC 3648) */
  8617. /* ACL (RFC 3744) */
  8618. /* SEARCH (RFC 5323) */
  8619. /* + MicroSoft extensions
  8620. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8621. /* REPORT method (RFC 3253) */
  8622. {"REPORT", 1, 1, 1, 1, 1},
  8623. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8624. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8625. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8626. * to be useful for REST in case a "GET request with body" is
  8627. * required. */
  8628. {NULL, 0, 0, 0, 0, 0}
  8629. /* end of list */
  8630. };
  8631. static const struct mg_http_method_info *
  8632. get_http_method_info(const char *method)
  8633. {
  8634. /* Check if the method is known to the server. The list of all known
  8635. * HTTP methods can be found here at
  8636. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8637. */
  8638. const struct mg_http_method_info *m = http_methods;
  8639. while (m->name) {
  8640. if (!strcmp(m->name, method)) {
  8641. return m;
  8642. }
  8643. m++;
  8644. }
  8645. return NULL;
  8646. }
  8647. static int
  8648. is_valid_http_method(const char *method)
  8649. {
  8650. return (get_http_method_info(method) != NULL);
  8651. }
  8652. /* Parse HTTP request, fill in mg_request_info structure.
  8653. * This function modifies the buffer by NUL-terminating
  8654. * HTTP request components, header names and header values.
  8655. * Parameters:
  8656. * buf (in/out): pointer to the HTTP header to parse and split
  8657. * len (in): length of HTTP header buffer
  8658. * re (out): parsed header as mg_request_info
  8659. * buf and ri must be valid pointers (not NULL), len>0.
  8660. * Returns <0 on error. */
  8661. static int
  8662. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8663. {
  8664. int request_length;
  8665. int init_skip = 0;
  8666. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8667. * remote_port */
  8668. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8669. NULL;
  8670. ri->num_headers = 0;
  8671. /* RFC says that all initial whitespaces should be ingored */
  8672. /* This included all leading \r and \n (isspace) */
  8673. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8674. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8675. buf++;
  8676. len--;
  8677. init_skip++;
  8678. }
  8679. if (len == 0) {
  8680. /* Incomplete request */
  8681. return 0;
  8682. }
  8683. /* Control characters are not allowed, including zero */
  8684. if (iscntrl(*(unsigned char *)buf)) {
  8685. return -1;
  8686. }
  8687. /* Find end of HTTP header */
  8688. request_length = get_http_header_len(buf, len);
  8689. if (request_length <= 0) {
  8690. return request_length;
  8691. }
  8692. buf[request_length - 1] = '\0';
  8693. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8694. return -1;
  8695. }
  8696. /* The first word has to be the HTTP method */
  8697. ri->request_method = buf;
  8698. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8699. return -1;
  8700. }
  8701. /* Check for a valid http method */
  8702. if (!is_valid_http_method(ri->request_method)) {
  8703. return -1;
  8704. }
  8705. /* The second word is the URI */
  8706. ri->request_uri = buf;
  8707. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8708. return -1;
  8709. }
  8710. /* Next would be the HTTP version */
  8711. ri->http_version = buf;
  8712. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8713. return -1;
  8714. }
  8715. /* Check for a valid HTTP version key */
  8716. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8717. /* Invalid request */
  8718. return -1;
  8719. }
  8720. ri->http_version += 5;
  8721. /* Parse all HTTP headers */
  8722. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8723. if (ri->num_headers < 0) {
  8724. /* Error while parsing headers */
  8725. return -1;
  8726. }
  8727. return request_length + init_skip;
  8728. }
  8729. static int
  8730. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8731. {
  8732. int response_length;
  8733. int init_skip = 0;
  8734. char *tmp, *tmp2;
  8735. long l;
  8736. /* Initialize elements. */
  8737. ri->http_version = ri->status_text = NULL;
  8738. ri->num_headers = ri->status_code = 0;
  8739. /* RFC says that all initial whitespaces should be ingored */
  8740. /* This included all leading \r and \n (isspace) */
  8741. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8742. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8743. buf++;
  8744. len--;
  8745. init_skip++;
  8746. }
  8747. if (len == 0) {
  8748. /* Incomplete request */
  8749. return 0;
  8750. }
  8751. /* Control characters are not allowed, including zero */
  8752. if (iscntrl(*(unsigned char *)buf)) {
  8753. return -1;
  8754. }
  8755. /* Find end of HTTP header */
  8756. response_length = get_http_header_len(buf, len);
  8757. if (response_length <= 0) {
  8758. return response_length;
  8759. }
  8760. buf[response_length - 1] = '\0';
  8761. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8762. return -1;
  8763. }
  8764. /* The first word is the HTTP version */
  8765. /* Check for a valid HTTP version key */
  8766. if (strncmp(buf, "HTTP/", 5) != 0) {
  8767. /* Invalid request */
  8768. return -1;
  8769. }
  8770. buf += 5;
  8771. if (!isgraph(buf[0])) {
  8772. /* Invalid request */
  8773. return -1;
  8774. }
  8775. ri->http_version = buf;
  8776. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8777. return -1;
  8778. }
  8779. /* The second word is the status as a number */
  8780. tmp = buf;
  8781. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8782. return -1;
  8783. }
  8784. l = strtol(tmp, &tmp2, 10);
  8785. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8786. /* Everything else but a 3 digit code is invalid */
  8787. return -1;
  8788. }
  8789. ri->status_code = (int)l;
  8790. /* The rest of the line is the status text */
  8791. ri->status_text = buf;
  8792. /* Find end of status text */
  8793. /* isgraph or isspace = isprint */
  8794. while (isprint(*buf)) {
  8795. buf++;
  8796. }
  8797. if ((*buf != '\r') && (*buf != '\n')) {
  8798. return -1;
  8799. }
  8800. /* Terminate string and forward buf to next line */
  8801. do {
  8802. *buf = 0;
  8803. buf++;
  8804. } while ((*buf) && isspace(*buf));
  8805. /* Parse all HTTP headers */
  8806. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8807. if (ri->num_headers < 0) {
  8808. /* Error while parsing headers */
  8809. return -1;
  8810. }
  8811. return response_length + init_skip;
  8812. }
  8813. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8814. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8815. * buffer (which marks the end of HTTP request). Buffer buf may already
  8816. * have some data. The length of the data is stored in nread.
  8817. * Upon every read operation, increase nread by the number of bytes read. */
  8818. static int
  8819. read_message(FILE *fp,
  8820. struct mg_connection *conn,
  8821. char *buf,
  8822. int bufsiz,
  8823. int *nread)
  8824. {
  8825. int request_len, n = 0;
  8826. struct timespec last_action_time;
  8827. double request_timeout;
  8828. if (!conn) {
  8829. return 0;
  8830. }
  8831. memset(&last_action_time, 0, sizeof(last_action_time));
  8832. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8833. /* value of request_timeout is in seconds, config in milliseconds */
  8834. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8835. } else {
  8836. request_timeout = -1.0;
  8837. }
  8838. if (conn->handled_requests > 0) {
  8839. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8840. request_timeout =
  8841. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8842. }
  8843. }
  8844. request_len = get_http_header_len(buf, *nread);
  8845. /* first time reading from this connection */
  8846. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8847. while (request_len == 0) {
  8848. /* Full request not yet received */
  8849. if (conn->phys_ctx->stop_flag != 0) {
  8850. /* Server is to be stopped. */
  8851. return -1;
  8852. }
  8853. if (*nread >= bufsiz) {
  8854. /* Request too long */
  8855. return -2;
  8856. }
  8857. n = pull_inner(
  8858. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8859. if (n == -2) {
  8860. /* Receive error */
  8861. return -1;
  8862. }
  8863. if (n > 0) {
  8864. *nread += n;
  8865. request_len = get_http_header_len(buf, *nread);
  8866. } else {
  8867. request_len = 0;
  8868. }
  8869. if ((request_len == 0) && (request_timeout >= 0)) {
  8870. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8871. > request_timeout) {
  8872. /* Timeout */
  8873. return -1;
  8874. }
  8875. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8876. }
  8877. }
  8878. return request_len;
  8879. }
  8880. #if !defined(NO_CGI) || !defined(NO_FILES)
  8881. static int
  8882. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8883. {
  8884. const char *expect, *body;
  8885. char buf[MG_BUF_LEN];
  8886. int to_read, nread, success = 0;
  8887. int64_t buffered_len;
  8888. double timeout = -1.0;
  8889. if (!conn) {
  8890. return 0;
  8891. }
  8892. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8893. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8894. }
  8895. expect = mg_get_header(conn, "Expect");
  8896. DEBUG_ASSERT(fp != NULL);
  8897. if (!fp) {
  8898. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8899. return 0;
  8900. }
  8901. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8902. /* Content length is not specified by the client. */
  8903. mg_send_http_error(conn,
  8904. 411,
  8905. "%s",
  8906. "Error: Client did not specify content length");
  8907. } else if ((expect != NULL)
  8908. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8909. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8910. */
  8911. mg_send_http_error(conn,
  8912. 417,
  8913. "Error: Can not fulfill expectation %s",
  8914. expect);
  8915. } else {
  8916. if (expect != NULL) {
  8917. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8918. conn->status_code = 100;
  8919. } else {
  8920. conn->status_code = 200;
  8921. }
  8922. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8923. - conn->consumed_content;
  8924. DEBUG_ASSERT(buffered_len >= 0);
  8925. DEBUG_ASSERT(conn->consumed_content == 0);
  8926. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8927. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8928. return 0;
  8929. }
  8930. if (buffered_len > 0) {
  8931. if ((int64_t)buffered_len > conn->content_len) {
  8932. buffered_len = (int)conn->content_len;
  8933. }
  8934. body = conn->buf + conn->request_len + conn->consumed_content;
  8935. push_all(
  8936. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8937. conn->consumed_content += buffered_len;
  8938. }
  8939. nread = 0;
  8940. while (conn->consumed_content < conn->content_len) {
  8941. to_read = sizeof(buf);
  8942. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8943. to_read = (int)(conn->content_len - conn->consumed_content);
  8944. }
  8945. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8946. if (nread == -2) {
  8947. /* error */
  8948. break;
  8949. }
  8950. if (nread > 0) {
  8951. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8952. != nread) {
  8953. break;
  8954. }
  8955. }
  8956. conn->consumed_content += nread;
  8957. }
  8958. if (conn->consumed_content == conn->content_len) {
  8959. success = (nread >= 0);
  8960. }
  8961. /* Each error code path in this function must send an error */
  8962. if (!success) {
  8963. /* NOTE: Maybe some data has already been sent. */
  8964. /* TODO (low): If some data has been sent, a correct error
  8965. * reply can no longer be sent, so just close the connection */
  8966. mg_send_http_error(conn, 500, "%s", "");
  8967. }
  8968. }
  8969. return success;
  8970. }
  8971. #endif
  8972. #if defined(USE_TIMERS)
  8973. #define TIMER_API static
  8974. #include "timer.inl"
  8975. #endif /* USE_TIMERS */
  8976. #if !defined(NO_CGI)
  8977. /* This structure helps to create an environment for the spawned CGI
  8978. * program.
  8979. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8980. * last element must be NULL.
  8981. * However, on Windows there is a requirement that all these
  8982. * VARIABLE=VALUE\0
  8983. * strings must reside in a contiguous buffer. The end of the buffer is
  8984. * marked by two '\0' characters.
  8985. * We satisfy both worlds: we create an envp array (which is vars), all
  8986. * entries are actually pointers inside buf. */
  8987. struct cgi_environment {
  8988. struct mg_connection *conn;
  8989. /* Data block */
  8990. char *buf; /* Environment buffer */
  8991. size_t buflen; /* Space available in buf */
  8992. size_t bufused; /* Space taken in buf */
  8993. /* Index block */
  8994. char **var; /* char **envp */
  8995. size_t varlen; /* Number of variables available in var */
  8996. size_t varused; /* Number of variables stored in var */
  8997. };
  8998. static void addenv(struct cgi_environment *env,
  8999. PRINTF_FORMAT_STRING(const char *fmt),
  9000. ...) PRINTF_ARGS(2, 3);
  9001. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9002. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9003. static void
  9004. addenv(struct cgi_environment *env, const char *fmt, ...)
  9005. {
  9006. size_t n, space;
  9007. int truncated = 0;
  9008. char *added;
  9009. va_list ap;
  9010. /* Calculate how much space is left in the buffer */
  9011. space = (env->buflen - env->bufused);
  9012. /* Calculate an estimate for the required space */
  9013. n = strlen(fmt) + 2 + 128;
  9014. do {
  9015. if (space <= n) {
  9016. /* Allocate new buffer */
  9017. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9018. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9019. if (!added) {
  9020. /* Out of memory */
  9021. mg_cry_internal(
  9022. env->conn,
  9023. "%s: Cannot allocate memory for CGI variable [%s]",
  9024. __func__,
  9025. fmt);
  9026. return;
  9027. }
  9028. env->buf = added;
  9029. env->buflen = n;
  9030. space = (env->buflen - env->bufused);
  9031. }
  9032. /* Make a pointer to the free space int the buffer */
  9033. added = env->buf + env->bufused;
  9034. /* Copy VARIABLE=VALUE\0 string into the free space */
  9035. va_start(ap, fmt);
  9036. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  9037. va_end(ap);
  9038. /* Do not add truncated strings to the environment */
  9039. if (truncated) {
  9040. /* Reallocate the buffer */
  9041. space = 0;
  9042. n = 1;
  9043. }
  9044. } while (truncated);
  9045. /* Calculate number of bytes added to the environment */
  9046. n = strlen(added) + 1;
  9047. env->bufused += n;
  9048. /* Now update the variable index */
  9049. space = (env->varlen - env->varused);
  9050. if (space < 2) {
  9051. mg_cry_internal(env->conn,
  9052. "%s: Cannot register CGI variable [%s]",
  9053. __func__,
  9054. fmt);
  9055. return;
  9056. }
  9057. /* Append a pointer to the added string into the envp array */
  9058. env->var[env->varused] = added;
  9059. env->varused++;
  9060. }
  9061. /* Return 0 on success, non-zero if an error occurs. */
  9062. static int
  9063. prepare_cgi_environment(struct mg_connection *conn,
  9064. const char *prog,
  9065. struct cgi_environment *env)
  9066. {
  9067. const char *s;
  9068. struct vec var_vec;
  9069. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9070. int i, truncated, uri_len;
  9071. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9072. return -1;
  9073. }
  9074. env->conn = conn;
  9075. env->buflen = CGI_ENVIRONMENT_SIZE;
  9076. env->bufused = 0;
  9077. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9078. if (env->buf == NULL) {
  9079. mg_cry_internal(conn,
  9080. "%s: Not enough memory for environmental buffer",
  9081. __func__);
  9082. return -1;
  9083. }
  9084. env->varlen = MAX_CGI_ENVIR_VARS;
  9085. env->varused = 0;
  9086. env->var =
  9087. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  9088. if (env->var == NULL) {
  9089. mg_cry_internal(conn,
  9090. "%s: Not enough memory for environmental variables",
  9091. __func__);
  9092. mg_free(env->buf);
  9093. return -1;
  9094. }
  9095. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9096. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9097. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9098. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9099. /* Prepare the environment block */
  9100. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9101. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9102. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9103. #if defined(USE_IPV6)
  9104. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9105. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9106. } else
  9107. #endif
  9108. {
  9109. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9110. }
  9111. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9112. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9113. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9114. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9115. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9116. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9117. /* SCRIPT_NAME */
  9118. uri_len = (int)strlen(conn->request_info.local_uri);
  9119. if (conn->path_info == NULL) {
  9120. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9121. /* URI: /path_to_script/script.cgi */
  9122. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9123. } else {
  9124. /* URI: /path_to_script/ ... using index.cgi */
  9125. const char *index_file = strrchr(prog, '/');
  9126. if (index_file) {
  9127. addenv(env,
  9128. "SCRIPT_NAME=%s%s",
  9129. conn->request_info.local_uri,
  9130. index_file + 1);
  9131. }
  9132. }
  9133. } else {
  9134. /* URI: /path_to_script/script.cgi/path_info */
  9135. addenv(env,
  9136. "SCRIPT_NAME=%.*s",
  9137. uri_len - (int)strlen(conn->path_info),
  9138. conn->request_info.local_uri);
  9139. }
  9140. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9141. if (conn->path_info == NULL) {
  9142. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9143. } else {
  9144. addenv(env,
  9145. "PATH_TRANSLATED=%s%s",
  9146. conn->dom_ctx->config[DOCUMENT_ROOT],
  9147. conn->path_info);
  9148. }
  9149. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9150. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9151. addenv(env, "CONTENT_TYPE=%s", s);
  9152. }
  9153. if (conn->request_info.query_string != NULL) {
  9154. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9155. }
  9156. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9157. addenv(env, "CONTENT_LENGTH=%s", s);
  9158. }
  9159. if ((s = getenv("PATH")) != NULL) {
  9160. addenv(env, "PATH=%s", s);
  9161. }
  9162. if (conn->path_info != NULL) {
  9163. addenv(env, "PATH_INFO=%s", conn->path_info);
  9164. }
  9165. if (conn->status_code > 0) {
  9166. /* CGI error handler should show the status code */
  9167. addenv(env, "STATUS=%d", conn->status_code);
  9168. }
  9169. #if defined(_WIN32)
  9170. if ((s = getenv("COMSPEC")) != NULL) {
  9171. addenv(env, "COMSPEC=%s", s);
  9172. }
  9173. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9174. addenv(env, "SYSTEMROOT=%s", s);
  9175. }
  9176. if ((s = getenv("SystemDrive")) != NULL) {
  9177. addenv(env, "SystemDrive=%s", s);
  9178. }
  9179. if ((s = getenv("ProgramFiles")) != NULL) {
  9180. addenv(env, "ProgramFiles=%s", s);
  9181. }
  9182. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9183. addenv(env, "ProgramFiles(x86)=%s", s);
  9184. }
  9185. #else
  9186. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9187. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9188. }
  9189. #endif /* _WIN32 */
  9190. if ((s = getenv("PERLLIB")) != NULL) {
  9191. addenv(env, "PERLLIB=%s", s);
  9192. }
  9193. if (conn->request_info.remote_user != NULL) {
  9194. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9195. addenv(env, "%s", "AUTH_TYPE=Digest");
  9196. }
  9197. /* Add all headers as HTTP_* variables */
  9198. for (i = 0; i < conn->request_info.num_headers; i++) {
  9199. (void)mg_snprintf(conn,
  9200. &truncated,
  9201. http_var_name,
  9202. sizeof(http_var_name),
  9203. "HTTP_%s",
  9204. conn->request_info.http_headers[i].name);
  9205. if (truncated) {
  9206. mg_cry_internal(conn,
  9207. "%s: HTTP header variable too long [%s]",
  9208. __func__,
  9209. conn->request_info.http_headers[i].name);
  9210. continue;
  9211. }
  9212. /* Convert variable name into uppercase, and change - to _ */
  9213. for (p = http_var_name; *p != '\0'; p++) {
  9214. if (*p == '-') {
  9215. *p = '_';
  9216. }
  9217. *p = (char)toupper(*(unsigned char *)p);
  9218. }
  9219. addenv(env,
  9220. "%s=%s",
  9221. http_var_name,
  9222. conn->request_info.http_headers[i].value);
  9223. }
  9224. /* Add user-specified variables */
  9225. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9226. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9227. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9228. }
  9229. env->var[env->varused] = NULL;
  9230. env->buf[env->bufused] = '\0';
  9231. return 0;
  9232. }
  9233. static int
  9234. abort_process(void *data)
  9235. {
  9236. /* Waitpid checks for child status and won't work for a pid that does not
  9237. * identify a child of the current process. Thus, if the pid is reused,
  9238. * we will not affect a different process. */
  9239. pid_t pid = (pid_t)data;
  9240. int status = 0;
  9241. pid_t rpid = waitpid(pid, &status, WNOHANG);
  9242. if ((rpid != (pid_t)-1) && (status == 0)) {
  9243. /* Stop child process */
  9244. DEBUG_TRACE("CGI timer: Stop child process %p\n", pid);
  9245. kill(pid, SIGABRT);
  9246. /* Wait until process is terminated (don't leave zombies) */
  9247. while (waitpid(pid, &status, 0) != (pid_t)-1) /* nop */
  9248. ;
  9249. } else {
  9250. DEBUG_TRACE("CGI timer: Child process %p already stopped in time\n",
  9251. pid);
  9252. }
  9253. return 0;
  9254. }
  9255. static void
  9256. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9257. {
  9258. char *buf;
  9259. size_t buflen;
  9260. int headers_len, data_len, i, truncated;
  9261. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9262. const char *status, *status_text, *connection_state;
  9263. char *pbuf, dir[PATH_MAX], *p;
  9264. struct mg_request_info ri;
  9265. struct cgi_environment blk;
  9266. FILE *in = NULL, *out = NULL, *err = NULL;
  9267. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9268. pid_t pid = (pid_t)-1;
  9269. if (conn == NULL) {
  9270. return;
  9271. }
  9272. buf = NULL;
  9273. buflen = conn->phys_ctx->max_request_size;
  9274. i = prepare_cgi_environment(conn, prog, &blk);
  9275. if (i != 0) {
  9276. blk.buf = NULL;
  9277. blk.var = NULL;
  9278. goto done;
  9279. }
  9280. /* CGI must be executed in its own directory. 'dir' must point to the
  9281. * directory containing executable program, 'p' must point to the
  9282. * executable program name relative to 'dir'. */
  9283. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9284. if (truncated) {
  9285. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9286. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9287. goto done;
  9288. }
  9289. if ((p = strrchr(dir, '/')) != NULL) {
  9290. *p++ = '\0';
  9291. } else {
  9292. dir[0] = '.';
  9293. dir[1] = '\0';
  9294. p = (char *)prog;
  9295. }
  9296. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9297. status = strerror(ERRNO);
  9298. mg_cry_internal(
  9299. conn,
  9300. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9301. prog,
  9302. status);
  9303. mg_send_http_error(conn,
  9304. 500,
  9305. "Error: Cannot create CGI pipe: %s",
  9306. status);
  9307. goto done;
  9308. }
  9309. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9310. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9311. if (pid == (pid_t)-1) {
  9312. status = strerror(ERRNO);
  9313. mg_cry_internal(
  9314. conn,
  9315. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9316. prog,
  9317. status);
  9318. mg_send_http_error(conn,
  9319. 500,
  9320. "Error: Cannot spawn CGI process [%s]: %s",
  9321. prog,
  9322. status);
  9323. goto done;
  9324. }
  9325. #if defined(USE_TIMERS)
  9326. // TODO (#618): set a timeout
  9327. timer_add(conn->phys_ctx,
  9328. /* one minute */ 60.0,
  9329. 0.0,
  9330. 1,
  9331. abort_process,
  9332. (void *)pid);
  9333. #endif
  9334. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  9335. */
  9336. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9337. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9338. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9339. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9340. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9341. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9342. /* Parent closes only one side of the pipes.
  9343. * If we don't mark them as closed, close() attempt before
  9344. * return from this function throws an exception on Windows.
  9345. * Windows does not like when closed descriptor is closed again. */
  9346. (void)close(fdin[0]);
  9347. (void)close(fdout[1]);
  9348. (void)close(fderr[1]);
  9349. fdin[0] = fdout[1] = fderr[1] = -1;
  9350. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9351. status = strerror(ERRNO);
  9352. mg_cry_internal(conn,
  9353. "Error: CGI program \"%s\": Can not open stdin: %s",
  9354. prog,
  9355. status);
  9356. mg_send_http_error(conn,
  9357. 500,
  9358. "Error: CGI can not open fdin\nfopen: %s",
  9359. status);
  9360. goto done;
  9361. }
  9362. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9363. status = strerror(ERRNO);
  9364. mg_cry_internal(conn,
  9365. "Error: CGI program \"%s\": Can not open stdout: %s",
  9366. prog,
  9367. status);
  9368. mg_send_http_error(conn,
  9369. 500,
  9370. "Error: CGI can not open fdout\nfopen: %s",
  9371. status);
  9372. goto done;
  9373. }
  9374. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9375. status = strerror(ERRNO);
  9376. mg_cry_internal(conn,
  9377. "Error: CGI program \"%s\": Can not open stderr: %s",
  9378. prog,
  9379. status);
  9380. mg_send_http_error(conn,
  9381. 500,
  9382. "Error: CGI can not open fderr\nfopen: %s",
  9383. status);
  9384. goto done;
  9385. }
  9386. setbuf(in, NULL);
  9387. setbuf(out, NULL);
  9388. setbuf(err, NULL);
  9389. fout.access.fp = out;
  9390. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9391. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9392. (signed long long)conn->request_info.content_length);
  9393. /* This is a POST/PUT request, or another request with body data. */
  9394. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9395. /* Error sending the body data */
  9396. mg_cry_internal(
  9397. conn,
  9398. "Error: CGI program \"%s\": Forward body data failed",
  9399. prog);
  9400. goto done;
  9401. }
  9402. }
  9403. /* Close so child gets an EOF. */
  9404. fclose(in);
  9405. in = NULL;
  9406. fdin[1] = -1;
  9407. /* Now read CGI reply into a buffer. We need to set correct
  9408. * status code, thus we need to see all HTTP headers first.
  9409. * Do not send anything back to client, until we buffer in all
  9410. * HTTP headers. */
  9411. data_len = 0;
  9412. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9413. if (buf == NULL) {
  9414. mg_send_http_error(conn,
  9415. 500,
  9416. "Error: Not enough memory for CGI buffer (%u bytes)",
  9417. (unsigned int)buflen);
  9418. mg_cry_internal(
  9419. conn,
  9420. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9421. "bytes)",
  9422. prog,
  9423. (unsigned int)buflen);
  9424. goto done;
  9425. }
  9426. DEBUG_TRACE("CGI: %s", "wait for response");
  9427. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9428. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9429. if (headers_len <= 0) {
  9430. /* Could not parse the CGI response. Check if some error message on
  9431. * stderr. */
  9432. i = pull_all(err, conn, buf, (int)buflen);
  9433. if (i > 0) {
  9434. /* CGI program explicitly sent an error */
  9435. /* Write the error message to the internal log */
  9436. mg_cry_internal(conn,
  9437. "Error: CGI program \"%s\" sent error "
  9438. "message: [%.*s]",
  9439. prog,
  9440. i,
  9441. buf);
  9442. /* Don't send the error message back to the client */
  9443. mg_send_http_error(conn,
  9444. 500,
  9445. "Error: CGI program \"%s\" failed.",
  9446. prog);
  9447. } else {
  9448. /* CGI program did not explicitly send an error, but a broken
  9449. * respon header */
  9450. mg_cry_internal(conn,
  9451. "Error: CGI program sent malformed or too big "
  9452. "(>%u bytes) HTTP headers: [%.*s]",
  9453. (unsigned)buflen,
  9454. data_len,
  9455. buf);
  9456. mg_send_http_error(conn,
  9457. 500,
  9458. "Error: CGI program sent malformed or too big "
  9459. "(>%u bytes) HTTP headers: [%.*s]",
  9460. (unsigned)buflen,
  9461. data_len,
  9462. buf);
  9463. }
  9464. /* in both cases, abort processing CGI */
  9465. goto done;
  9466. }
  9467. pbuf = buf;
  9468. buf[headers_len - 1] = '\0';
  9469. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9470. /* Make up and send the status line */
  9471. status_text = "OK";
  9472. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9473. != NULL) {
  9474. conn->status_code = atoi(status);
  9475. status_text = status;
  9476. while (isdigit(*(const unsigned char *)status_text)
  9477. || *status_text == ' ') {
  9478. status_text++;
  9479. }
  9480. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9481. != NULL) {
  9482. conn->status_code = 307;
  9483. } else {
  9484. conn->status_code = 200;
  9485. }
  9486. connection_state =
  9487. get_header(ri.http_headers, ri.num_headers, "Connection");
  9488. if (!header_has_option(connection_state, "keep-alive")) {
  9489. conn->must_close = 1;
  9490. }
  9491. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9492. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9493. /* Send headers */
  9494. for (i = 0; i < ri.num_headers; i++) {
  9495. mg_printf(conn,
  9496. "%s: %s\r\n",
  9497. ri.http_headers[i].name,
  9498. ri.http_headers[i].value);
  9499. }
  9500. mg_write(conn, "\r\n", 2);
  9501. /* Send chunk of data that may have been read after the headers */
  9502. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9503. /* Read the rest of CGI output and send to the client */
  9504. DEBUG_TRACE("CGI: %s", "forward all data");
  9505. send_file_data(conn, &fout, 0, INT64_MAX);
  9506. DEBUG_TRACE("CGI: %s", "all data sent");
  9507. done:
  9508. mg_free(blk.var);
  9509. mg_free(blk.buf);
  9510. if (pid != (pid_t)-1) {
  9511. abort_process((void *)pid);
  9512. }
  9513. if (fdin[0] != -1) {
  9514. close(fdin[0]);
  9515. }
  9516. if (fdout[1] != -1) {
  9517. close(fdout[1]);
  9518. }
  9519. if (in != NULL) {
  9520. fclose(in);
  9521. } else if (fdin[1] != -1) {
  9522. close(fdin[1]);
  9523. }
  9524. if (out != NULL) {
  9525. fclose(out);
  9526. } else if (fdout[0] != -1) {
  9527. close(fdout[0]);
  9528. }
  9529. if (err != NULL) {
  9530. fclose(err);
  9531. } else if (fderr[0] != -1) {
  9532. close(fderr[0]);
  9533. }
  9534. if (buf != NULL) {
  9535. mg_free(buf);
  9536. }
  9537. }
  9538. #endif /* !NO_CGI */
  9539. #if !defined(NO_FILES)
  9540. static void
  9541. mkcol(struct mg_connection *conn, const char *path)
  9542. {
  9543. int rc, body_len;
  9544. struct de de;
  9545. char date[64];
  9546. time_t curtime = time(NULL);
  9547. if (conn == NULL) {
  9548. return;
  9549. }
  9550. /* TODO (mid): Check the mg_send_http_error situations in this function
  9551. */
  9552. memset(&de.file, 0, sizeof(de.file));
  9553. if (!mg_stat(conn, path, &de.file)) {
  9554. mg_cry_internal(conn,
  9555. "%s: mg_stat(%s) failed: %s",
  9556. __func__,
  9557. path,
  9558. strerror(ERRNO));
  9559. }
  9560. if (de.file.last_modified) {
  9561. /* TODO (mid): This check does not seem to make any sense ! */
  9562. /* TODO (mid): Add a webdav unit test first, before changing
  9563. * anything here. */
  9564. mg_send_http_error(
  9565. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9566. return;
  9567. }
  9568. body_len = conn->data_len - conn->request_len;
  9569. if (body_len > 0) {
  9570. mg_send_http_error(
  9571. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9572. return;
  9573. }
  9574. rc = mg_mkdir(conn, path, 0755);
  9575. if (rc == 0) {
  9576. conn->status_code = 201;
  9577. gmt_time_string(date, sizeof(date), &curtime);
  9578. mg_printf(conn,
  9579. "HTTP/1.1 %d Created\r\n"
  9580. "Date: %s\r\n",
  9581. conn->status_code,
  9582. date);
  9583. send_static_cache_header(conn);
  9584. send_additional_header(conn);
  9585. mg_printf(conn,
  9586. "Content-Length: 0\r\n"
  9587. "Connection: %s\r\n\r\n",
  9588. suggest_connection_header(conn));
  9589. } else {
  9590. if (errno == EEXIST) {
  9591. mg_send_http_error(
  9592. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9593. } else if (errno == EACCES) {
  9594. mg_send_http_error(
  9595. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9596. } else if (errno == ENOENT) {
  9597. mg_send_http_error(
  9598. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9599. } else {
  9600. mg_send_http_error(
  9601. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9602. }
  9603. }
  9604. }
  9605. static void
  9606. put_file(struct mg_connection *conn, const char *path)
  9607. {
  9608. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9609. const char *range;
  9610. int64_t r1, r2;
  9611. int rc;
  9612. char date[64];
  9613. time_t curtime = time(NULL);
  9614. if (conn == NULL) {
  9615. return;
  9616. }
  9617. if (mg_stat(conn, path, &file.stat)) {
  9618. /* File already exists */
  9619. conn->status_code = 200;
  9620. if (file.stat.is_directory) {
  9621. /* This is an already existing directory,
  9622. * so there is nothing to do for the server. */
  9623. rc = 0;
  9624. } else {
  9625. /* File exists and is not a directory. */
  9626. /* Can it be replaced? */
  9627. #if defined(MG_USE_OPEN_FILE)
  9628. if (file.access.membuf != NULL) {
  9629. /* This is an "in-memory" file, that can not be replaced */
  9630. mg_send_http_error(conn,
  9631. 405,
  9632. "Error: Put not possible\nReplacing %s "
  9633. "is not supported",
  9634. path);
  9635. return;
  9636. }
  9637. #endif
  9638. /* Check if the server may write this file */
  9639. if (access(path, W_OK) == 0) {
  9640. /* Access granted */
  9641. conn->status_code = 200;
  9642. rc = 1;
  9643. } else {
  9644. mg_send_http_error(
  9645. conn,
  9646. 403,
  9647. "Error: Put not possible\nReplacing %s is not allowed",
  9648. path);
  9649. return;
  9650. }
  9651. }
  9652. } else {
  9653. /* File should be created */
  9654. conn->status_code = 201;
  9655. rc = put_dir(conn, path);
  9656. }
  9657. if (rc == 0) {
  9658. /* put_dir returns 0 if path is a directory */
  9659. gmt_time_string(date, sizeof(date), &curtime);
  9660. mg_printf(conn,
  9661. "HTTP/1.1 %d %s\r\n",
  9662. conn->status_code,
  9663. mg_get_response_code_text(NULL, conn->status_code));
  9664. send_no_cache_header(conn);
  9665. send_additional_header(conn);
  9666. mg_printf(conn,
  9667. "Date: %s\r\n"
  9668. "Content-Length: 0\r\n"
  9669. "Connection: %s\r\n\r\n",
  9670. date,
  9671. suggest_connection_header(conn));
  9672. /* Request to create a directory has been fulfilled successfully.
  9673. * No need to put a file. */
  9674. return;
  9675. }
  9676. if (rc == -1) {
  9677. /* put_dir returns -1 if the path is too long */
  9678. mg_send_http_error(conn,
  9679. 414,
  9680. "Error: Path too long\nput_dir(%s): %s",
  9681. path,
  9682. strerror(ERRNO));
  9683. return;
  9684. }
  9685. if (rc == -2) {
  9686. /* put_dir returns -2 if the directory can not be created */
  9687. mg_send_http_error(conn,
  9688. 500,
  9689. "Error: Can not create directory\nput_dir(%s): %s",
  9690. path,
  9691. strerror(ERRNO));
  9692. return;
  9693. }
  9694. /* A file should be created or overwritten. */
  9695. /* Currently CivetWeb does not nead read+write access. */
  9696. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9697. || file.access.fp == NULL) {
  9698. (void)mg_fclose(&file.access);
  9699. mg_send_http_error(conn,
  9700. 500,
  9701. "Error: Can not create file\nfopen(%s): %s",
  9702. path,
  9703. strerror(ERRNO));
  9704. return;
  9705. }
  9706. fclose_on_exec(&file.access, conn);
  9707. range = mg_get_header(conn, "Content-Range");
  9708. r1 = r2 = 0;
  9709. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9710. conn->status_code = 206; /* Partial content */
  9711. fseeko(file.access.fp, r1, SEEK_SET);
  9712. }
  9713. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9714. /* forward_body_data failed.
  9715. * The error code has already been sent to the client,
  9716. * and conn->status_code is already set. */
  9717. (void)mg_fclose(&file.access);
  9718. return;
  9719. }
  9720. if (mg_fclose(&file.access) != 0) {
  9721. /* fclose failed. This might have different reasons, but a likely
  9722. * one is "no space on disk", http 507. */
  9723. conn->status_code = 507;
  9724. }
  9725. gmt_time_string(date, sizeof(date), &curtime);
  9726. mg_printf(conn,
  9727. "HTTP/1.1 %d %s\r\n",
  9728. conn->status_code,
  9729. mg_get_response_code_text(NULL, conn->status_code));
  9730. send_no_cache_header(conn);
  9731. send_additional_header(conn);
  9732. mg_printf(conn,
  9733. "Date: %s\r\n"
  9734. "Content-Length: 0\r\n"
  9735. "Connection: %s\r\n\r\n",
  9736. date,
  9737. suggest_connection_header(conn));
  9738. }
  9739. static void
  9740. delete_file(struct mg_connection *conn, const char *path)
  9741. {
  9742. struct de de;
  9743. memset(&de.file, 0, sizeof(de.file));
  9744. if (!mg_stat(conn, path, &de.file)) {
  9745. /* mg_stat returns 0 if the file does not exist */
  9746. mg_send_http_error(conn,
  9747. 404,
  9748. "Error: Cannot delete file\nFile %s not found",
  9749. path);
  9750. return;
  9751. }
  9752. #if 0 /* Ignore if a file in memory is inside a folder */
  9753. if (de.access.membuf != NULL) {
  9754. /* the file is cached in memory */
  9755. mg_send_http_error(
  9756. conn,
  9757. 405,
  9758. "Error: Delete not possible\nDeleting %s is not supported",
  9759. path);
  9760. return;
  9761. }
  9762. #endif
  9763. if (de.file.is_directory) {
  9764. if (remove_directory(conn, path)) {
  9765. /* Delete is successful: Return 204 without content. */
  9766. mg_send_http_error(conn, 204, "%s", "");
  9767. } else {
  9768. /* Delete is not successful: Return 500 (Server error). */
  9769. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9770. }
  9771. return;
  9772. }
  9773. /* This is an existing file (not a directory).
  9774. * Check if write permission is granted. */
  9775. if (access(path, W_OK) != 0) {
  9776. /* File is read only */
  9777. mg_send_http_error(
  9778. conn,
  9779. 403,
  9780. "Error: Delete not possible\nDeleting %s is not allowed",
  9781. path);
  9782. return;
  9783. }
  9784. /* Try to delete it. */
  9785. if (mg_remove(conn, path) == 0) {
  9786. /* Delete was successful: Return 204 without content. */
  9787. mg_send_http_error(conn, 204, "%s", "");
  9788. } else {
  9789. /* Delete not successful (file locked). */
  9790. mg_send_http_error(conn,
  9791. 423,
  9792. "Error: Cannot delete file\nremove(%s): %s",
  9793. path,
  9794. strerror(ERRNO));
  9795. }
  9796. }
  9797. #endif /* !NO_FILES */
  9798. static void
  9799. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9800. static void
  9801. do_ssi_include(struct mg_connection *conn,
  9802. const char *ssi,
  9803. char *tag,
  9804. int include_level)
  9805. {
  9806. char file_name[MG_BUF_LEN], path[512], *p;
  9807. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9808. size_t len;
  9809. int truncated = 0;
  9810. if (conn == NULL) {
  9811. return;
  9812. }
  9813. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9814. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9815. * always < MG_BUF_LEN. */
  9816. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9817. /* File name is relative to the webserver root */
  9818. file_name[511] = 0;
  9819. (void)mg_snprintf(conn,
  9820. &truncated,
  9821. path,
  9822. sizeof(path),
  9823. "%s/%s",
  9824. conn->dom_ctx->config[DOCUMENT_ROOT],
  9825. file_name);
  9826. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9827. /* File name is relative to the webserver working directory
  9828. * or it is absolute system path */
  9829. file_name[511] = 0;
  9830. (void)
  9831. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9832. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9833. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9834. /* File name is relative to the currect document */
  9835. file_name[511] = 0;
  9836. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9837. if (!truncated) {
  9838. if ((p = strrchr(path, '/')) != NULL) {
  9839. p[1] = '\0';
  9840. }
  9841. len = strlen(path);
  9842. (void)mg_snprintf(conn,
  9843. &truncated,
  9844. path + len,
  9845. sizeof(path) - len,
  9846. "%s",
  9847. file_name);
  9848. }
  9849. } else {
  9850. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9851. return;
  9852. }
  9853. if (truncated) {
  9854. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9855. return;
  9856. }
  9857. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9858. mg_cry_internal(conn,
  9859. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9860. tag,
  9861. path,
  9862. strerror(ERRNO));
  9863. } else {
  9864. fclose_on_exec(&file.access, conn);
  9865. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9866. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9867. path) > 0) {
  9868. send_ssi_file(conn, path, &file, include_level + 1);
  9869. } else {
  9870. send_file_data(conn, &file, 0, INT64_MAX);
  9871. }
  9872. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9873. }
  9874. }
  9875. #if !defined(NO_POPEN)
  9876. static void
  9877. do_ssi_exec(struct mg_connection *conn, char *tag)
  9878. {
  9879. char cmd[1024] = "";
  9880. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9881. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9882. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9883. } else {
  9884. cmd[1023] = 0;
  9885. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9886. mg_cry_internal(conn,
  9887. "Cannot SSI #exec: [%s]: %s",
  9888. cmd,
  9889. strerror(ERRNO));
  9890. } else {
  9891. send_file_data(conn, &file, 0, INT64_MAX);
  9892. pclose(file.access.fp);
  9893. }
  9894. }
  9895. }
  9896. #endif /* !NO_POPEN */
  9897. static int
  9898. mg_fgetc(struct mg_file *filep, int offset)
  9899. {
  9900. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  9901. if (filep == NULL) {
  9902. return EOF;
  9903. }
  9904. #if defined(MG_USE_OPEN_FILE)
  9905. if ((filep->access.membuf != NULL) && (offset >= 0)
  9906. && (((unsigned int)(offset)) < filep->stat.size)) {
  9907. return ((const unsigned char *)filep->access.membuf)[offset];
  9908. } else /* else block below */
  9909. #endif
  9910. if (filep->access.fp != NULL) {
  9911. return fgetc(filep->access.fp);
  9912. } else {
  9913. return EOF;
  9914. }
  9915. }
  9916. static void
  9917. send_ssi_file(struct mg_connection *conn,
  9918. const char *path,
  9919. struct mg_file *filep,
  9920. int include_level)
  9921. {
  9922. char buf[MG_BUF_LEN];
  9923. int ch, offset, len, in_tag, in_ssi_tag;
  9924. if (include_level > 10) {
  9925. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  9926. return;
  9927. }
  9928. in_tag = in_ssi_tag = len = offset = 0;
  9929. /* Read file, byte by byte, and look for SSI include tags */
  9930. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9931. if (in_tag) {
  9932. /* We are in a tag, either SSI tag or html tag */
  9933. if (ch == '>') {
  9934. /* Tag is closing */
  9935. buf[len++] = '>';
  9936. if (in_ssi_tag) {
  9937. /* Handle SSI tag */
  9938. buf[len] = 0;
  9939. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  9940. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9941. #if !defined(NO_POPEN)
  9942. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  9943. do_ssi_exec(conn, buf + 9);
  9944. #endif /* !NO_POPEN */
  9945. } else {
  9946. mg_cry_internal(conn,
  9947. "%s: unknown SSI "
  9948. "command: \"%s\"",
  9949. path,
  9950. buf);
  9951. }
  9952. len = 0;
  9953. in_ssi_tag = in_tag = 0;
  9954. } else {
  9955. /* Not an SSI tag */
  9956. /* Flush buffer */
  9957. (void)mg_write(conn, buf, (size_t)len);
  9958. len = 0;
  9959. in_tag = 0;
  9960. }
  9961. } else {
  9962. /* Tag is still open */
  9963. buf[len++] = (char)(ch & 0xff);
  9964. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9965. /* All SSI tags start with <!--# */
  9966. in_ssi_tag = 1;
  9967. }
  9968. if ((len + 2) > (int)sizeof(buf)) {
  9969. /* Tag to long for buffer */
  9970. mg_cry_internal(conn, "%s: tag is too large", path);
  9971. return;
  9972. }
  9973. }
  9974. } else {
  9975. /* We are not in a tag yet. */
  9976. if (ch == '<') {
  9977. /* Tag is opening */
  9978. in_tag = 1;
  9979. if (len > 0) {
  9980. /* Flush current buffer.
  9981. * Buffer is filled with "len" bytes. */
  9982. (void)mg_write(conn, buf, (size_t)len);
  9983. }
  9984. /* Store the < */
  9985. len = 1;
  9986. buf[0] = '<';
  9987. } else {
  9988. /* No Tag */
  9989. /* Add data to buffer */
  9990. buf[len++] = (char)(ch & 0xff);
  9991. /* Flush if buffer is full */
  9992. if (len == (int)sizeof(buf)) {
  9993. mg_write(conn, buf, (size_t)len);
  9994. len = 0;
  9995. }
  9996. }
  9997. }
  9998. }
  9999. /* Send the rest of buffered data */
  10000. if (len > 0) {
  10001. mg_write(conn, buf, (size_t)len);
  10002. }
  10003. }
  10004. static void
  10005. handle_ssi_file_request(struct mg_connection *conn,
  10006. const char *path,
  10007. struct mg_file *filep)
  10008. {
  10009. char date[64];
  10010. time_t curtime = time(NULL);
  10011. const char *cors1, *cors2, *cors3;
  10012. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10013. return;
  10014. }
  10015. if (mg_get_header(conn, "Origin")) {
  10016. /* Cross-origin resource sharing (CORS). */
  10017. cors1 = "Access-Control-Allow-Origin: ";
  10018. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10019. cors3 = "\r\n";
  10020. } else {
  10021. cors1 = cors2 = cors3 = "";
  10022. }
  10023. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10024. /* File exists (precondition for calling this function),
  10025. * but can not be opened by the server. */
  10026. mg_send_http_error(conn,
  10027. 500,
  10028. "Error: Cannot read file\nfopen(%s): %s",
  10029. path,
  10030. strerror(ERRNO));
  10031. } else {
  10032. conn->must_close = 1;
  10033. gmt_time_string(date, sizeof(date), &curtime);
  10034. fclose_on_exec(&filep->access, conn);
  10035. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10036. send_no_cache_header(conn);
  10037. send_additional_header(conn);
  10038. mg_printf(conn,
  10039. "%s%s%s"
  10040. "Date: %s\r\n"
  10041. "Content-Type: text/html\r\n"
  10042. "Connection: %s\r\n\r\n",
  10043. cors1,
  10044. cors2,
  10045. cors3,
  10046. date,
  10047. suggest_connection_header(conn));
  10048. send_ssi_file(conn, path, filep, 0);
  10049. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10050. }
  10051. }
  10052. #if !defined(NO_FILES)
  10053. static void
  10054. send_options(struct mg_connection *conn)
  10055. {
  10056. char date[64];
  10057. time_t curtime = time(NULL);
  10058. if (!conn) {
  10059. return;
  10060. }
  10061. conn->status_code = 200;
  10062. conn->must_close = 1;
  10063. gmt_time_string(date, sizeof(date), &curtime);
  10064. /* We do not set a "Cache-Control" header here, but leave the default.
  10065. * Since browsers do not send an OPTIONS request, we can not test the
  10066. * effect anyway. */
  10067. mg_printf(conn,
  10068. "HTTP/1.1 200 OK\r\n"
  10069. "Date: %s\r\n"
  10070. "Connection: %s\r\n"
  10071. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10072. "PROPFIND, MKCOL\r\n"
  10073. "DAV: 1\r\n",
  10074. date,
  10075. suggest_connection_header(conn));
  10076. send_additional_header(conn);
  10077. mg_printf(conn, "\r\n");
  10078. }
  10079. /* Writes PROPFIND properties for a collection element */
  10080. static void
  10081. print_props(struct mg_connection *conn,
  10082. const char *uri,
  10083. struct mg_file_stat *filep)
  10084. {
  10085. char mtime[64];
  10086. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  10087. return;
  10088. }
  10089. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10090. mg_printf(conn,
  10091. "<d:response>"
  10092. "<d:href>%s</d:href>"
  10093. "<d:propstat>"
  10094. "<d:prop>"
  10095. "<d:resourcetype>%s</d:resourcetype>"
  10096. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10097. "<d:getlastmodified>%s</d:getlastmodified>"
  10098. "</d:prop>"
  10099. "<d:status>HTTP/1.1 200 OK</d:status>"
  10100. "</d:propstat>"
  10101. "</d:response>\n",
  10102. uri,
  10103. filep->is_directory ? "<d:collection/>" : "",
  10104. filep->size,
  10105. mtime);
  10106. }
  10107. static int
  10108. print_dav_dir_entry(struct de *de, void *data)
  10109. {
  10110. char href[PATH_MAX];
  10111. int truncated;
  10112. struct mg_connection *conn = (struct mg_connection *)data;
  10113. if (!de || !conn) {
  10114. return -1;
  10115. }
  10116. mg_snprintf(conn,
  10117. &truncated,
  10118. href,
  10119. sizeof(href),
  10120. "%s%s",
  10121. conn->request_info.local_uri,
  10122. de->file_name);
  10123. if (!truncated) {
  10124. size_t href_encoded_size;
  10125. char *href_encoded;
  10126. href_encoded_size = PATH_MAX * 3; /* worst case */
  10127. href_encoded = (char *)mg_malloc(href_encoded_size);
  10128. if (href_encoded == NULL) {
  10129. return -1;
  10130. }
  10131. mg_url_encode(href, href_encoded, href_encoded_size);
  10132. print_props(conn, href_encoded, &de->file);
  10133. mg_free(href_encoded);
  10134. }
  10135. return 0;
  10136. }
  10137. static void
  10138. handle_propfind(struct mg_connection *conn,
  10139. const char *path,
  10140. struct mg_file_stat *filep)
  10141. {
  10142. const char *depth = mg_get_header(conn, "Depth");
  10143. char date[64];
  10144. time_t curtime = time(NULL);
  10145. gmt_time_string(date, sizeof(date), &curtime);
  10146. if (!conn || !path || !filep || !conn->dom_ctx) {
  10147. return;
  10148. }
  10149. conn->must_close = 1;
  10150. conn->status_code = 207;
  10151. mg_printf(conn,
  10152. "HTTP/1.1 207 Multi-Status\r\n"
  10153. "Date: %s\r\n",
  10154. date);
  10155. send_static_cache_header(conn);
  10156. send_additional_header(conn);
  10157. mg_printf(conn,
  10158. "Connection: %s\r\n"
  10159. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10160. suggest_connection_header(conn));
  10161. mg_printf(conn,
  10162. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10163. "<d:multistatus xmlns:d='DAV:'>\n");
  10164. /* Print properties for the requested resource itself */
  10165. print_props(conn, conn->request_info.local_uri, filep);
  10166. /* If it is a directory, print directory entries too if Depth is not 0
  10167. */
  10168. if (filep->is_directory
  10169. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10170. "yes")
  10171. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10172. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10173. }
  10174. mg_printf(conn, "%s\n", "</d:multistatus>");
  10175. }
  10176. #endif
  10177. void
  10178. mg_lock_connection(struct mg_connection *conn)
  10179. {
  10180. if (conn) {
  10181. (void)pthread_mutex_lock(&conn->mutex);
  10182. }
  10183. }
  10184. void
  10185. mg_unlock_connection(struct mg_connection *conn)
  10186. {
  10187. if (conn) {
  10188. (void)pthread_mutex_unlock(&conn->mutex);
  10189. }
  10190. }
  10191. void
  10192. mg_lock_context(struct mg_context *ctx)
  10193. {
  10194. if (ctx) {
  10195. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10196. }
  10197. }
  10198. void
  10199. mg_unlock_context(struct mg_context *ctx)
  10200. {
  10201. if (ctx) {
  10202. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10203. }
  10204. }
  10205. #if defined(USE_LUA)
  10206. #include "mod_lua.inl"
  10207. #endif /* USE_LUA */
  10208. #if defined(USE_DUKTAPE)
  10209. #include "mod_duktape.inl"
  10210. #endif /* USE_DUKTAPE */
  10211. #if defined(USE_WEBSOCKET)
  10212. #if !defined(NO_SSL_DL)
  10213. #define SHA_API static
  10214. #include "sha1.inl"
  10215. #endif
  10216. static int
  10217. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10218. {
  10219. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10220. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10221. SHA_CTX sha_ctx;
  10222. int truncated;
  10223. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10224. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10225. if (truncated) {
  10226. conn->must_close = 1;
  10227. return 0;
  10228. }
  10229. DEBUG_TRACE("%s", "Send websocket handshake");
  10230. SHA1_Init(&sha_ctx);
  10231. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10232. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10233. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10234. mg_printf(conn,
  10235. "HTTP/1.1 101 Switching Protocols\r\n"
  10236. "Upgrade: websocket\r\n"
  10237. "Connection: Upgrade\r\n"
  10238. "Sec-WebSocket-Accept: %s\r\n",
  10239. b64_sha);
  10240. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10241. mg_printf(conn,
  10242. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10243. conn->request_info.acceptedWebSocketSubprotocol);
  10244. } else {
  10245. mg_printf(conn, "%s", "\r\n");
  10246. }
  10247. return 1;
  10248. }
  10249. #if !defined(MG_MAX_UNANSWERED_PING)
  10250. /* Configuration of the maximum number of websocket PINGs that might
  10251. * stay unanswered before the connection is considered broken.
  10252. * Note: The name of this define may still change (until it is
  10253. * defined as a compile parameter in a documentation).
  10254. */
  10255. #define MG_MAX_UNANSWERED_PING (5)
  10256. #endif
  10257. static void
  10258. read_websocket(struct mg_connection *conn,
  10259. mg_websocket_data_handler ws_data_handler,
  10260. void *callback_data)
  10261. {
  10262. /* Pointer to the beginning of the portion of the incoming websocket
  10263. * message queue.
  10264. * The original websocket upgrade request is never removed, so the queue
  10265. * begins after it. */
  10266. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10267. int n, error, exit_by_callback;
  10268. int ret;
  10269. /* body_len is the length of the entire queue in bytes
  10270. * len is the length of the current message
  10271. * data_len is the length of the current message's data payload
  10272. * header_len is the length of the current message's header */
  10273. size_t i, len, mask_len = 0, header_len, body_len;
  10274. uint64_t data_len = 0;
  10275. /* "The masking key is a 32-bit value chosen at random by the client."
  10276. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10277. */
  10278. unsigned char mask[4];
  10279. /* data points to the place where the message is stored when passed to
  10280. * the websocket_data callback. This is either mem on the stack, or a
  10281. * dynamically allocated buffer if it is too large. */
  10282. unsigned char mem[4096];
  10283. unsigned char mop; /* mask flag and opcode */
  10284. /* Variables used for connection monitoring */
  10285. double timeout = -1.0;
  10286. int enable_ping_pong = 0;
  10287. int ping_count = 0;
  10288. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10289. enable_ping_pong =
  10290. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10291. "yes");
  10292. }
  10293. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10294. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10295. }
  10296. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10297. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10298. }
  10299. /* Enter data processing loop */
  10300. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10301. conn->request_info.remote_addr,
  10302. conn->request_info.remote_port);
  10303. conn->in_websocket_handling = 1;
  10304. mg_set_thread_name("wsock");
  10305. /* Loop continuously, reading messages from the socket, invoking the
  10306. * callback, and waiting repeatedly until an error occurs. */
  10307. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10308. header_len = 0;
  10309. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10310. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10311. len = buf[1] & 127;
  10312. mask_len = (buf[1] & 128) ? 4 : 0;
  10313. if ((len < 126) && (body_len >= mask_len)) {
  10314. /* inline 7-bit length field */
  10315. data_len = len;
  10316. header_len = 2 + mask_len;
  10317. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10318. /* 16-bit length field */
  10319. header_len = 4 + mask_len;
  10320. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10321. } else if (body_len >= (10 + mask_len)) {
  10322. /* 64-bit length field */
  10323. uint32_t l1, l2;
  10324. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10325. memcpy(&l2, &buf[6], 4);
  10326. header_len = 10 + mask_len;
  10327. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10328. if (data_len > (uint64_t)0x7FFF0000ul) {
  10329. /* no can do */
  10330. mg_cry_internal(
  10331. conn,
  10332. "%s",
  10333. "websocket out of memory; closing connection");
  10334. break;
  10335. }
  10336. }
  10337. }
  10338. if ((header_len > 0) && (body_len >= header_len)) {
  10339. /* Allocate space to hold websocket payload */
  10340. unsigned char *data = mem;
  10341. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10342. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10343. conn->phys_ctx);
  10344. if (data == NULL) {
  10345. /* Allocation failed, exit the loop and then close the
  10346. * connection */
  10347. mg_cry_internal(
  10348. conn,
  10349. "%s",
  10350. "websocket out of memory; closing connection");
  10351. break;
  10352. }
  10353. }
  10354. /* Copy the mask before we shift the queue and destroy it */
  10355. if (mask_len > 0) {
  10356. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10357. } else {
  10358. memset(mask, 0, sizeof(mask));
  10359. }
  10360. /* Read frame payload from the first message in the queue into
  10361. * data and advance the queue by moving the memory in place. */
  10362. DEBUG_ASSERT(body_len >= header_len);
  10363. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10364. mop = buf[0]; /* current mask and opcode */
  10365. /* Overflow case */
  10366. len = body_len - header_len;
  10367. memcpy(data, buf + header_len, len);
  10368. error = 0;
  10369. while ((uint64_t)len < data_len) {
  10370. n = pull_inner(NULL,
  10371. conn,
  10372. (char *)(data + len),
  10373. (int)(data_len - len),
  10374. timeout);
  10375. if (n <= -2) {
  10376. error = 1;
  10377. break;
  10378. } else if (n > 0) {
  10379. len += (size_t)n;
  10380. } else {
  10381. /* Timeout: should retry */
  10382. /* TODO: retry condition */
  10383. }
  10384. }
  10385. if (error) {
  10386. mg_cry_internal(
  10387. conn,
  10388. "%s",
  10389. "Websocket pull failed; closing connection");
  10390. if (data != mem) {
  10391. mg_free(data);
  10392. }
  10393. break;
  10394. }
  10395. conn->data_len = conn->request_len;
  10396. } else {
  10397. mop = buf[0]; /* current mask and opcode, overwritten by
  10398. * memmove() */
  10399. /* Length of the message being read at the front of the
  10400. * queue. Cast to 31 bit is OK, since we limited
  10401. * data_len before. */
  10402. len = (size_t)data_len + header_len;
  10403. /* Copy the data payload into the data pointer for the
  10404. * callback. Cast to 31 bit is OK, since we
  10405. * limited data_len */
  10406. memcpy(data, buf + header_len, (size_t)data_len);
  10407. /* Move the queue forward len bytes */
  10408. memmove(buf, buf + len, body_len - len);
  10409. /* Mark the queue as advanced */
  10410. conn->data_len -= (int)len;
  10411. }
  10412. /* Apply mask if necessary */
  10413. if (mask_len > 0) {
  10414. for (i = 0; i < (size_t)data_len; i++) {
  10415. data[i] ^= mask[i & 3];
  10416. }
  10417. }
  10418. exit_by_callback = 0;
  10419. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10420. /* filter PONG messages */
  10421. DEBUG_TRACE("PONG from %s:%u",
  10422. conn->request_info.remote_addr,
  10423. conn->request_info.remote_port);
  10424. /* No unanwered PINGs left */
  10425. ping_count = 0;
  10426. } else if (enable_ping_pong
  10427. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10428. /* reply PING messages */
  10429. DEBUG_TRACE("Reply PING from %s:%u",
  10430. conn->request_info.remote_addr,
  10431. conn->request_info.remote_port);
  10432. ret = mg_websocket_write(conn,
  10433. MG_WEBSOCKET_OPCODE_PONG,
  10434. (char *)data,
  10435. (size_t)data_len);
  10436. if (ret <= 0) {
  10437. /* Error: send failed */
  10438. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10439. break;
  10440. }
  10441. } else {
  10442. /* Exit the loop if callback signals to exit (server side),
  10443. * or "connection close" opcode received (client side). */
  10444. if ((ws_data_handler != NULL)
  10445. && !ws_data_handler(conn,
  10446. mop,
  10447. (char *)data,
  10448. (size_t)data_len,
  10449. callback_data)) {
  10450. exit_by_callback = 1;
  10451. }
  10452. }
  10453. /* It a buffer has been allocated, free it again */
  10454. if (data != mem) {
  10455. mg_free(data);
  10456. }
  10457. if (exit_by_callback) {
  10458. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10459. conn->request_info.remote_addr,
  10460. conn->request_info.remote_port);
  10461. break;
  10462. }
  10463. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10464. /* Opcode == 8, connection close */
  10465. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10466. conn->request_info.remote_addr,
  10467. conn->request_info.remote_port);
  10468. break;
  10469. }
  10470. /* Not breaking the loop, process next websocket frame. */
  10471. } else {
  10472. /* Read from the socket into the next available location in the
  10473. * message queue. */
  10474. n = pull_inner(NULL,
  10475. conn,
  10476. conn->buf + conn->data_len,
  10477. conn->buf_size - conn->data_len,
  10478. timeout);
  10479. if (n <= -2) {
  10480. /* Error, no bytes read */
  10481. DEBUG_TRACE("PULL from %s:%u failed",
  10482. conn->request_info.remote_addr,
  10483. conn->request_info.remote_port);
  10484. break;
  10485. }
  10486. if (n > 0) {
  10487. conn->data_len += n;
  10488. /* Reset open PING count */
  10489. ping_count = 0;
  10490. } else {
  10491. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10492. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10493. /* Stop sending PING */
  10494. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10495. "- closing connection",
  10496. ping_count,
  10497. conn->request_info.remote_addr,
  10498. conn->request_info.remote_port);
  10499. break;
  10500. }
  10501. if (enable_ping_pong) {
  10502. /* Send Websocket PING message */
  10503. DEBUG_TRACE("PING to %s:%u",
  10504. conn->request_info.remote_addr,
  10505. conn->request_info.remote_port);
  10506. ret = mg_websocket_write(conn,
  10507. MG_WEBSOCKET_OPCODE_PING,
  10508. NULL,
  10509. 0);
  10510. if (ret <= 0) {
  10511. /* Error: send failed */
  10512. DEBUG_TRACE("Send PING failed (%i)", ret);
  10513. break;
  10514. }
  10515. ping_count++;
  10516. }
  10517. }
  10518. /* Timeout: should retry */
  10519. /* TODO: get timeout def */
  10520. }
  10521. }
  10522. }
  10523. /* Leave data processing loop */
  10524. mg_set_thread_name("worker");
  10525. conn->in_websocket_handling = 0;
  10526. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10527. conn->request_info.remote_addr,
  10528. conn->request_info.remote_port);
  10529. }
  10530. static int
  10531. mg_websocket_write_exec(struct mg_connection *conn,
  10532. int opcode,
  10533. const char *data,
  10534. size_t dataLen,
  10535. uint32_t masking_key)
  10536. {
  10537. unsigned char header[14];
  10538. size_t headerLen;
  10539. int retval;
  10540. #if defined(__GNUC__) || defined(__MINGW32__)
  10541. /* Disable spurious conversion warning for GCC */
  10542. #pragma GCC diagnostic push
  10543. #pragma GCC diagnostic ignored "-Wconversion"
  10544. #endif
  10545. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10546. #if defined(__GNUC__) || defined(__MINGW32__)
  10547. #pragma GCC diagnostic pop
  10548. #endif
  10549. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10550. if (dataLen < 126) {
  10551. /* inline 7-bit length field */
  10552. header[1] = (unsigned char)dataLen;
  10553. headerLen = 2;
  10554. } else if (dataLen <= 0xFFFF) {
  10555. /* 16-bit length field */
  10556. uint16_t len = htons((uint16_t)dataLen);
  10557. header[1] = 126;
  10558. memcpy(header + 2, &len, 2);
  10559. headerLen = 4;
  10560. } else {
  10561. /* 64-bit length field */
  10562. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10563. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10564. header[1] = 127;
  10565. memcpy(header + 2, &len1, 4);
  10566. memcpy(header + 6, &len2, 4);
  10567. headerLen = 10;
  10568. }
  10569. if (masking_key) {
  10570. /* add mask */
  10571. header[1] |= 0x80;
  10572. memcpy(header + headerLen, &masking_key, 4);
  10573. headerLen += 4;
  10574. }
  10575. /* Note that POSIX/Winsock's send() is threadsafe
  10576. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10577. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10578. * push(), although that is only a problem if the packet is large or
  10579. * outgoing buffer is full). */
  10580. /* TODO: Check if this lock should be moved to user land.
  10581. * Currently the server sets this lock for websockets, but
  10582. * not for any other connection. It must be set for every
  10583. * conn read/written by more than one thread, no matter if
  10584. * it is a websocket or regular connection. */
  10585. (void)mg_lock_connection(conn);
  10586. retval = mg_write(conn, header, headerLen);
  10587. if (retval != (int)headerLen) {
  10588. /* Did not send complete header */
  10589. retval = -1;
  10590. } else {
  10591. if (dataLen > 0) {
  10592. retval = mg_write(conn, data, dataLen);
  10593. }
  10594. /* if dataLen == 0, the header length (2) is returned */
  10595. }
  10596. /* TODO: Remove this unlock as well, when lock is removed. */
  10597. mg_unlock_connection(conn);
  10598. return retval;
  10599. }
  10600. int
  10601. mg_websocket_write(struct mg_connection *conn,
  10602. int opcode,
  10603. const char *data,
  10604. size_t dataLen)
  10605. {
  10606. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10607. }
  10608. static void
  10609. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10610. {
  10611. size_t i = 0;
  10612. i = 0;
  10613. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10614. /* Convert in 32 bit words, if data is 4 byte aligned */
  10615. while (i < (in_len - 3)) {
  10616. *(uint32_t *)(void *)(out + i) =
  10617. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10618. i += 4;
  10619. }
  10620. }
  10621. if (i != in_len) {
  10622. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10623. while (i < in_len) {
  10624. *(uint8_t *)(void *)(out + i) =
  10625. *(uint8_t *)(void *)(in + i)
  10626. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10627. i++;
  10628. }
  10629. }
  10630. }
  10631. int
  10632. mg_websocket_client_write(struct mg_connection *conn,
  10633. int opcode,
  10634. const char *data,
  10635. size_t dataLen)
  10636. {
  10637. int retval = -1;
  10638. char *masked_data =
  10639. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10640. uint32_t masking_key = 0;
  10641. if (masked_data == NULL) {
  10642. /* Return -1 in an error case */
  10643. mg_cry_internal(conn,
  10644. "%s",
  10645. "Cannot allocate buffer for masked websocket response: "
  10646. "Out of memory");
  10647. return -1;
  10648. }
  10649. do {
  10650. /* Get a masking key - but not 0 */
  10651. masking_key = (uint32_t)get_random();
  10652. } while (masking_key == 0);
  10653. mask_data(data, dataLen, masking_key, masked_data);
  10654. retval = mg_websocket_write_exec(
  10655. conn, opcode, masked_data, dataLen, masking_key);
  10656. mg_free(masked_data);
  10657. return retval;
  10658. }
  10659. static void
  10660. handle_websocket_request(struct mg_connection *conn,
  10661. const char *path,
  10662. int is_callback_resource,
  10663. struct mg_websocket_subprotocols *subprotocols,
  10664. mg_websocket_connect_handler ws_connect_handler,
  10665. mg_websocket_ready_handler ws_ready_handler,
  10666. mg_websocket_data_handler ws_data_handler,
  10667. mg_websocket_close_handler ws_close_handler,
  10668. void *cbData)
  10669. {
  10670. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10671. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10672. ptrdiff_t lua_websock = 0;
  10673. #if !defined(USE_LUA)
  10674. (void)path;
  10675. #endif
  10676. /* Step 1: Check websocket protocol version. */
  10677. /* Step 1.1: Check Sec-WebSocket-Key. */
  10678. if (!websock_key) {
  10679. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10680. * requires a Sec-WebSocket-Key header.
  10681. */
  10682. /* It could be the hixie draft version
  10683. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10684. */
  10685. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10686. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10687. char key3[8];
  10688. if ((key1 != NULL) && (key2 != NULL)) {
  10689. /* This version uses 8 byte body data in a GET request */
  10690. conn->content_len = 8;
  10691. if (8 == mg_read(conn, key3, 8)) {
  10692. /* This is the hixie version */
  10693. mg_send_http_error(conn,
  10694. 426,
  10695. "%s",
  10696. "Protocol upgrade to RFC 6455 required");
  10697. return;
  10698. }
  10699. }
  10700. /* This is an unknown version */
  10701. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10702. return;
  10703. }
  10704. /* Step 1.2: Check websocket protocol version. */
  10705. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10706. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10707. /* Reject wrong versions */
  10708. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10709. return;
  10710. }
  10711. /* Step 1.3: Could check for "Host", but we do not really nead this
  10712. * value for anything, so just ignore it. */
  10713. /* Step 2: If a callback is responsible, call it. */
  10714. if (is_callback_resource) {
  10715. /* Step 2.1 check and select subprotocol */
  10716. const char *protocols[64]; // max 64 headers
  10717. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10718. "Sec-WebSocket-Protocol",
  10719. protocols,
  10720. 64);
  10721. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10722. int cnt = 0;
  10723. int idx;
  10724. unsigned long len;
  10725. const char *sep, *curSubProtocol,
  10726. *acceptedWebSocketSubprotocol = NULL;
  10727. /* look for matching subprotocol */
  10728. do {
  10729. const char *protocol = protocols[cnt];
  10730. do {
  10731. sep = strchr(protocol, ',');
  10732. curSubProtocol = protocol;
  10733. len = sep ? (unsigned long)(sep - protocol)
  10734. : (unsigned long)strlen(protocol);
  10735. while (sep && isspace(*++sep))
  10736. ; // ignore leading whitespaces
  10737. protocol = sep;
  10738. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10739. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10740. && (strncmp(curSubProtocol,
  10741. subprotocols->subprotocols[idx],
  10742. len) == 0)) {
  10743. acceptedWebSocketSubprotocol =
  10744. subprotocols->subprotocols[idx];
  10745. break;
  10746. }
  10747. }
  10748. } while (sep && !acceptedWebSocketSubprotocol);
  10749. } while (++cnt < nbSubprotocolHeader
  10750. && !acceptedWebSocketSubprotocol);
  10751. conn->request_info.acceptedWebSocketSubprotocol =
  10752. acceptedWebSocketSubprotocol;
  10753. } else if (nbSubprotocolHeader > 0) {
  10754. /* keep legacy behavior */
  10755. const char *protocol = protocols[0];
  10756. /* The protocol is a comma separated list of names. */
  10757. /* The server must only return one value from this list. */
  10758. /* First check if it is a list or just a single value. */
  10759. const char *sep = strrchr(protocol, ',');
  10760. if (sep == NULL) {
  10761. /* Just a single protocol -> accept it. */
  10762. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10763. } else {
  10764. /* Multiple protocols -> accept the last one. */
  10765. /* This is just a quick fix if the client offers multiple
  10766. * protocols. The handler should have a list of accepted
  10767. * protocols on his own
  10768. * and use it to select one protocol among those the client
  10769. * has
  10770. * offered.
  10771. */
  10772. while (isspace(*++sep)) {
  10773. ; /* ignore leading whitespaces */
  10774. }
  10775. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10776. }
  10777. }
  10778. if ((ws_connect_handler != NULL)
  10779. && (ws_connect_handler(conn, cbData) != 0)) {
  10780. /* C callback has returned non-zero, do not proceed with
  10781. * handshake.
  10782. */
  10783. /* Note that C callbacks are no longer called when Lua is
  10784. * responsible, so C can no longer filter callbacks for Lua. */
  10785. return;
  10786. }
  10787. }
  10788. #if defined(USE_LUA)
  10789. /* Step 3: No callback. Check if Lua is responsible. */
  10790. else {
  10791. /* Step 3.1: Check if Lua is responsible. */
  10792. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10793. lua_websock = match_prefix(
  10794. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10795. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10796. path);
  10797. }
  10798. if (lua_websock) {
  10799. /* Step 3.2: Lua is responsible: call it. */
  10800. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10801. if (!conn->lua_websocket_state) {
  10802. /* Lua rejected the new client */
  10803. return;
  10804. }
  10805. }
  10806. }
  10807. #endif
  10808. /* Step 4: Check if there is a responsible websocket handler. */
  10809. if (!is_callback_resource && !lua_websock) {
  10810. /* There is no callback, and Lua is not responsible either. */
  10811. /* Reply with a 404 Not Found. We are still at a standard
  10812. * HTTP request here, before the websocket handshake, so
  10813. * we can still send standard HTTP error replies. */
  10814. mg_send_http_error(conn, 404, "%s", "Not found");
  10815. return;
  10816. }
  10817. /* Step 5: The websocket connection has been accepted */
  10818. if (!send_websocket_handshake(conn, websock_key)) {
  10819. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10820. return;
  10821. }
  10822. /* Step 6: Call the ready handler */
  10823. if (is_callback_resource) {
  10824. if (ws_ready_handler != NULL) {
  10825. ws_ready_handler(conn, cbData);
  10826. }
  10827. #if defined(USE_LUA)
  10828. } else if (lua_websock) {
  10829. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10830. /* the ready handler returned false */
  10831. return;
  10832. }
  10833. #endif
  10834. }
  10835. /* Step 7: Enter the read loop */
  10836. if (is_callback_resource) {
  10837. read_websocket(conn, ws_data_handler, cbData);
  10838. #if defined(USE_LUA)
  10839. } else if (lua_websock) {
  10840. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10841. #endif
  10842. }
  10843. /* Step 8: Call the close handler */
  10844. if (ws_close_handler) {
  10845. ws_close_handler(conn, cbData);
  10846. }
  10847. }
  10848. static int
  10849. is_websocket_protocol(const struct mg_connection *conn)
  10850. {
  10851. const char *upgrade, *connection;
  10852. /* A websocket protocoll has the following HTTP headers:
  10853. *
  10854. * Connection: Upgrade
  10855. * Upgrade: Websocket
  10856. */
  10857. upgrade = mg_get_header(conn, "Upgrade");
  10858. if (upgrade == NULL) {
  10859. return 0; /* fail early, don't waste time checking other header
  10860. * fields
  10861. */
  10862. }
  10863. if (!mg_strcasestr(upgrade, "websocket")) {
  10864. return 0;
  10865. }
  10866. connection = mg_get_header(conn, "Connection");
  10867. if (connection == NULL) {
  10868. return 0;
  10869. }
  10870. if (!mg_strcasestr(connection, "upgrade")) {
  10871. return 0;
  10872. }
  10873. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10874. * "Sec-WebSocket-Version" are also required.
  10875. * Don't check them here, since even an unsupported websocket protocol
  10876. * request still IS a websocket request (in contrast to a standard HTTP
  10877. * request). It will fail later in handle_websocket_request.
  10878. */
  10879. return 1;
  10880. }
  10881. #endif /* !USE_WEBSOCKET */
  10882. static int
  10883. isbyte(int n)
  10884. {
  10885. return (n >= 0) && (n <= 255);
  10886. }
  10887. static int
  10888. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10889. {
  10890. int n, a, b, c, d, slash = 32, len = 0;
  10891. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10892. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10893. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10894. && (slash < 33)) {
  10895. len = n;
  10896. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10897. | (uint32_t)d;
  10898. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10899. }
  10900. return len;
  10901. }
  10902. static int
  10903. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10904. {
  10905. int throttle = 0;
  10906. struct vec vec, val;
  10907. uint32_t net, mask;
  10908. char mult;
  10909. double v;
  10910. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10911. mult = ',';
  10912. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10913. || (v < 0) || ((lowercase(&mult) != 'k')
  10914. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10915. continue;
  10916. }
  10917. v *= (lowercase(&mult) == 'k')
  10918. ? 1024
  10919. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10920. if (vec.len == 1 && vec.ptr[0] == '*') {
  10921. throttle = (int)v;
  10922. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10923. if ((remote_ip & mask) == net) {
  10924. throttle = (int)v;
  10925. }
  10926. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10927. throttle = (int)v;
  10928. }
  10929. }
  10930. return throttle;
  10931. }
  10932. static uint32_t
  10933. get_remote_ip(const struct mg_connection *conn)
  10934. {
  10935. if (!conn) {
  10936. return 0;
  10937. }
  10938. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10939. }
  10940. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10941. #include "handle_form.inl"
  10942. #if defined(MG_LEGACY_INTERFACE)
  10943. /* Implement the deprecated mg_upload function by calling the new
  10944. * mg_handle_form_request function. While mg_upload could only handle
  10945. * HTML forms sent as POST request in multipart/form-data format
  10946. * containing only file input elements, mg_handle_form_request can
  10947. * handle all form input elements and all standard request methods. */
  10948. struct mg_upload_user_data {
  10949. struct mg_connection *conn;
  10950. const char *destination_dir;
  10951. int num_uploaded_files;
  10952. };
  10953. /* Helper function for deprecated mg_upload. */
  10954. static int
  10955. mg_upload_field_found(const char *key,
  10956. const char *filename,
  10957. char *path,
  10958. size_t pathlen,
  10959. void *user_data)
  10960. {
  10961. int truncated = 0;
  10962. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10963. (void)key;
  10964. if (!filename) {
  10965. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  10966. return FORM_FIELD_STORAGE_ABORT;
  10967. }
  10968. mg_snprintf(fud->conn,
  10969. &truncated,
  10970. path,
  10971. pathlen - 1,
  10972. "%s/%s",
  10973. fud->destination_dir,
  10974. filename);
  10975. if (truncated) {
  10976. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  10977. return FORM_FIELD_STORAGE_ABORT;
  10978. }
  10979. return FORM_FIELD_STORAGE_STORE;
  10980. }
  10981. /* Helper function for deprecated mg_upload. */
  10982. static int
  10983. mg_upload_field_get(const char *key,
  10984. const char *value,
  10985. size_t value_size,
  10986. void *user_data)
  10987. {
  10988. /* Function should never be called */
  10989. (void)key;
  10990. (void)value;
  10991. (void)value_size;
  10992. (void)user_data;
  10993. return 0;
  10994. }
  10995. /* Helper function for deprecated mg_upload. */
  10996. static int
  10997. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10998. {
  10999. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11000. (void)file_size;
  11001. fud->num_uploaded_files++;
  11002. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11003. return 0;
  11004. }
  11005. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11006. int
  11007. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11008. {
  11009. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11010. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11011. mg_upload_field_get,
  11012. mg_upload_field_stored,
  11013. 0};
  11014. int ret;
  11015. fdh.user_data = (void *)&fud;
  11016. ret = mg_handle_form_request(conn, &fdh);
  11017. if (ret < 0) {
  11018. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11019. }
  11020. return fud.num_uploaded_files;
  11021. }
  11022. #endif
  11023. static int
  11024. get_first_ssl_listener_index(const struct mg_context *ctx)
  11025. {
  11026. unsigned int i;
  11027. int idx = -1;
  11028. if (ctx) {
  11029. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11030. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11031. }
  11032. }
  11033. return idx;
  11034. }
  11035. /* Return host (without port) */
  11036. /* Use mg_free to free the result */
  11037. static const char *
  11038. alloc_get_host(struct mg_connection *conn)
  11039. {
  11040. char buf[1025];
  11041. size_t buflen = sizeof(buf);
  11042. const char *host_header = get_header(conn->request_info.http_headers,
  11043. conn->request_info.num_headers,
  11044. "Host");
  11045. char *host;
  11046. if (host_header != NULL) {
  11047. char *pos;
  11048. /* Create a local copy of the "Host" header, since it might be
  11049. * modified here. */
  11050. mg_strlcpy(buf, host_header, buflen);
  11051. buf[buflen - 1] = '\0';
  11052. host = buf;
  11053. while (isspace(*host)) {
  11054. host++;
  11055. }
  11056. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11057. * is found. */
  11058. if (*host == '[') {
  11059. pos = strchr(host, ']');
  11060. if (!pos) {
  11061. /* Malformed hostname starts with '[', but no ']' found */
  11062. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11063. return NULL;
  11064. }
  11065. /* terminate after ']' */
  11066. pos[1] = 0;
  11067. } else {
  11068. /* Otherwise, a ':' separates hostname and port number */
  11069. pos = strchr(host, ':');
  11070. if (pos != NULL) {
  11071. *pos = '\0';
  11072. }
  11073. }
  11074. if (conn->ssl) {
  11075. /* This is a HTTPS connection, maybe we have a hostname
  11076. * from SNI (set in ssl_servername_callback). */
  11077. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11078. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11079. /* We are not using the default domain */
  11080. if (mg_strcasecmp(host, sslhost)) {
  11081. /* Mismatch between SNI domain and HTTP domain */
  11082. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11083. sslhost,
  11084. host);
  11085. return NULL;
  11086. }
  11087. }
  11088. DEBUG_TRACE("HTTPS Host: %s", host);
  11089. } else {
  11090. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11091. while (dom) {
  11092. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11093. /* Found matching domain */
  11094. DEBUG_TRACE("HTTP domain %s found",
  11095. dom->config[AUTHENTICATION_DOMAIN]);
  11096. /* TODO: Check if this is a HTTP or HTTPS domain */
  11097. conn->dom_ctx = dom;
  11098. break;
  11099. }
  11100. dom = dom->next;
  11101. }
  11102. DEBUG_TRACE("HTTP Host: %s", host);
  11103. }
  11104. } else {
  11105. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11106. host = buf;
  11107. DEBUG_TRACE("IP: %s", host);
  11108. }
  11109. return mg_strdup_ctx(host, conn->phys_ctx);
  11110. }
  11111. static void
  11112. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11113. {
  11114. char target_url[MG_BUF_LEN];
  11115. int truncated = 0;
  11116. conn->must_close = 1;
  11117. /* Send host, port, uri and (if it exists) ?query_string */
  11118. if (conn->host) {
  11119. /* Use "308 Permanent Redirect" */
  11120. int redirect_code = 308;
  11121. /* Create target URL */
  11122. mg_snprintf(
  11123. conn,
  11124. &truncated,
  11125. target_url,
  11126. sizeof(target_url),
  11127. "Location: https://%s:%d%s%s%s",
  11128. conn->host,
  11129. #if defined(USE_IPV6)
  11130. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11131. == AF_INET6)
  11132. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11133. .lsa.sin6.sin6_port)
  11134. :
  11135. #endif
  11136. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11137. .lsa.sin.sin_port),
  11138. conn->request_info.local_uri,
  11139. (conn->request_info.query_string == NULL) ? "" : "?",
  11140. (conn->request_info.query_string == NULL)
  11141. ? ""
  11142. : conn->request_info.query_string);
  11143. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11144. * is used as buffer size) */
  11145. if (truncated) {
  11146. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11147. return;
  11148. }
  11149. /* Use redirect helper function */
  11150. mg_send_http_redirect(conn, target_url, redirect_code);
  11151. }
  11152. }
  11153. static void
  11154. handler_info_acquire(struct mg_handler_info *handler_info)
  11155. {
  11156. pthread_mutex_lock(&handler_info->refcount_mutex);
  11157. handler_info->refcount++;
  11158. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11159. }
  11160. static void
  11161. handler_info_release(struct mg_handler_info *handler_info)
  11162. {
  11163. pthread_mutex_lock(&handler_info->refcount_mutex);
  11164. handler_info->refcount--;
  11165. pthread_cond_signal(&handler_info->refcount_cond);
  11166. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11167. }
  11168. static void
  11169. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11170. {
  11171. pthread_mutex_lock(&handler_info->refcount_mutex);
  11172. while (handler_info->refcount) {
  11173. pthread_cond_wait(&handler_info->refcount_cond,
  11174. &handler_info->refcount_mutex);
  11175. }
  11176. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11177. }
  11178. static void
  11179. mg_set_handler_type(struct mg_context *phys_ctx,
  11180. struct mg_domain_context *dom_ctx,
  11181. const char *uri,
  11182. int handler_type,
  11183. int is_delete_request,
  11184. mg_request_handler handler,
  11185. struct mg_websocket_subprotocols *subprotocols,
  11186. mg_websocket_connect_handler connect_handler,
  11187. mg_websocket_ready_handler ready_handler,
  11188. mg_websocket_data_handler data_handler,
  11189. mg_websocket_close_handler close_handler,
  11190. mg_authorization_handler auth_handler,
  11191. void *cbdata)
  11192. {
  11193. struct mg_handler_info *tmp_rh, **lastref;
  11194. size_t urilen = strlen(uri);
  11195. if (handler_type == WEBSOCKET_HANDLER) {
  11196. DEBUG_ASSERT(handler == NULL);
  11197. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11198. || ready_handler != NULL
  11199. || data_handler != NULL
  11200. || close_handler != NULL);
  11201. DEBUG_ASSERT(auth_handler == NULL);
  11202. if (handler != NULL) {
  11203. return;
  11204. }
  11205. if (!is_delete_request && (connect_handler == NULL)
  11206. && (ready_handler == NULL) && (data_handler == NULL)
  11207. && (close_handler == NULL)) {
  11208. return;
  11209. }
  11210. if (auth_handler != NULL) {
  11211. return;
  11212. }
  11213. } else if (handler_type == REQUEST_HANDLER) {
  11214. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11215. && data_handler == NULL
  11216. && close_handler == NULL);
  11217. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11218. DEBUG_ASSERT(auth_handler == NULL);
  11219. if ((connect_handler != NULL) || (ready_handler != NULL)
  11220. || (data_handler != NULL) || (close_handler != NULL)) {
  11221. return;
  11222. }
  11223. if (!is_delete_request && (handler == NULL)) {
  11224. return;
  11225. }
  11226. if (auth_handler != NULL) {
  11227. return;
  11228. }
  11229. } else { /* AUTH_HANDLER */
  11230. DEBUG_ASSERT(handler == NULL);
  11231. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11232. && data_handler == NULL
  11233. && close_handler == NULL);
  11234. DEBUG_ASSERT(auth_handler != NULL);
  11235. if (handler != NULL) {
  11236. return;
  11237. }
  11238. if ((connect_handler != NULL) || (ready_handler != NULL)
  11239. || (data_handler != NULL) || (close_handler != NULL)) {
  11240. return;
  11241. }
  11242. if (!is_delete_request && (auth_handler == NULL)) {
  11243. return;
  11244. }
  11245. }
  11246. if (!phys_ctx || !dom_ctx) {
  11247. return;
  11248. }
  11249. mg_lock_context(phys_ctx);
  11250. /* first try to find an existing handler */
  11251. lastref = &(dom_ctx->handlers);
  11252. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11253. if (tmp_rh->handler_type == handler_type) {
  11254. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11255. if (!is_delete_request) {
  11256. /* update existing handler */
  11257. if (handler_type == REQUEST_HANDLER) {
  11258. /* Wait for end of use before updating */
  11259. handler_info_wait_unused(tmp_rh);
  11260. /* Ok, the handler is no more use -> Update it */
  11261. tmp_rh->handler = handler;
  11262. } else if (handler_type == WEBSOCKET_HANDLER) {
  11263. tmp_rh->subprotocols = subprotocols;
  11264. tmp_rh->connect_handler = connect_handler;
  11265. tmp_rh->ready_handler = ready_handler;
  11266. tmp_rh->data_handler = data_handler;
  11267. tmp_rh->close_handler = close_handler;
  11268. } else { /* AUTH_HANDLER */
  11269. tmp_rh->auth_handler = auth_handler;
  11270. }
  11271. tmp_rh->cbdata = cbdata;
  11272. } else {
  11273. /* remove existing handler */
  11274. if (handler_type == REQUEST_HANDLER) {
  11275. /* Wait for end of use before removing */
  11276. handler_info_wait_unused(tmp_rh);
  11277. /* Ok, the handler is no more used -> Destroy resources
  11278. */
  11279. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11280. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11281. }
  11282. *lastref = tmp_rh->next;
  11283. mg_free(tmp_rh->uri);
  11284. mg_free(tmp_rh);
  11285. }
  11286. mg_unlock_context(phys_ctx);
  11287. return;
  11288. }
  11289. }
  11290. lastref = &(tmp_rh->next);
  11291. }
  11292. if (is_delete_request) {
  11293. /* no handler to set, this was a remove request to a non-existing
  11294. * handler */
  11295. mg_unlock_context(phys_ctx);
  11296. return;
  11297. }
  11298. tmp_rh =
  11299. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11300. 1,
  11301. phys_ctx);
  11302. if (tmp_rh == NULL) {
  11303. mg_unlock_context(phys_ctx);
  11304. mg_cry_internal(fc(phys_ctx),
  11305. "%s",
  11306. "Cannot create new request handler struct, OOM");
  11307. return;
  11308. }
  11309. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11310. if (!tmp_rh->uri) {
  11311. mg_unlock_context(phys_ctx);
  11312. mg_free(tmp_rh);
  11313. mg_cry_internal(fc(phys_ctx),
  11314. "%s",
  11315. "Cannot create new request handler struct, OOM");
  11316. return;
  11317. }
  11318. tmp_rh->uri_len = urilen;
  11319. if (handler_type == REQUEST_HANDLER) {
  11320. /* Init refcount mutex and condition */
  11321. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11322. mg_unlock_context(phys_ctx);
  11323. mg_free(tmp_rh);
  11324. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11325. return;
  11326. }
  11327. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11328. mg_unlock_context(phys_ctx);
  11329. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11330. mg_free(tmp_rh);
  11331. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11332. return;
  11333. }
  11334. tmp_rh->refcount = 0;
  11335. tmp_rh->handler = handler;
  11336. } else if (handler_type == WEBSOCKET_HANDLER) {
  11337. tmp_rh->subprotocols = subprotocols;
  11338. tmp_rh->connect_handler = connect_handler;
  11339. tmp_rh->ready_handler = ready_handler;
  11340. tmp_rh->data_handler = data_handler;
  11341. tmp_rh->close_handler = close_handler;
  11342. } else { /* AUTH_HANDLER */
  11343. tmp_rh->auth_handler = auth_handler;
  11344. }
  11345. tmp_rh->cbdata = cbdata;
  11346. tmp_rh->handler_type = handler_type;
  11347. tmp_rh->next = NULL;
  11348. *lastref = tmp_rh;
  11349. mg_unlock_context(phys_ctx);
  11350. }
  11351. void
  11352. mg_set_request_handler(struct mg_context *ctx,
  11353. const char *uri,
  11354. mg_request_handler handler,
  11355. void *cbdata)
  11356. {
  11357. mg_set_handler_type(ctx,
  11358. &(ctx->dd),
  11359. uri,
  11360. REQUEST_HANDLER,
  11361. handler == NULL,
  11362. handler,
  11363. NULL,
  11364. NULL,
  11365. NULL,
  11366. NULL,
  11367. NULL,
  11368. NULL,
  11369. cbdata);
  11370. }
  11371. void
  11372. mg_set_websocket_handler(struct mg_context *ctx,
  11373. const char *uri,
  11374. mg_websocket_connect_handler connect_handler,
  11375. mg_websocket_ready_handler ready_handler,
  11376. mg_websocket_data_handler data_handler,
  11377. mg_websocket_close_handler close_handler,
  11378. void *cbdata)
  11379. {
  11380. mg_set_websocket_handler_with_subprotocols(ctx,
  11381. uri,
  11382. NULL,
  11383. connect_handler,
  11384. ready_handler,
  11385. data_handler,
  11386. close_handler,
  11387. cbdata);
  11388. }
  11389. void
  11390. mg_set_websocket_handler_with_subprotocols(
  11391. struct mg_context *ctx,
  11392. const char *uri,
  11393. struct mg_websocket_subprotocols *subprotocols,
  11394. mg_websocket_connect_handler connect_handler,
  11395. mg_websocket_ready_handler ready_handler,
  11396. mg_websocket_data_handler data_handler,
  11397. mg_websocket_close_handler close_handler,
  11398. void *cbdata)
  11399. {
  11400. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11401. && (data_handler == NULL)
  11402. && (close_handler == NULL);
  11403. mg_set_handler_type(ctx,
  11404. &(ctx->dd),
  11405. uri,
  11406. WEBSOCKET_HANDLER,
  11407. is_delete_request,
  11408. NULL,
  11409. subprotocols,
  11410. connect_handler,
  11411. ready_handler,
  11412. data_handler,
  11413. close_handler,
  11414. NULL,
  11415. cbdata);
  11416. }
  11417. void
  11418. mg_set_auth_handler(struct mg_context *ctx,
  11419. const char *uri,
  11420. mg_request_handler handler,
  11421. void *cbdata)
  11422. {
  11423. mg_set_handler_type(ctx,
  11424. &(ctx->dd),
  11425. uri,
  11426. AUTH_HANDLER,
  11427. handler == NULL,
  11428. NULL,
  11429. NULL,
  11430. NULL,
  11431. NULL,
  11432. NULL,
  11433. NULL,
  11434. handler,
  11435. cbdata);
  11436. }
  11437. static int
  11438. get_request_handler(struct mg_connection *conn,
  11439. int handler_type,
  11440. mg_request_handler *handler,
  11441. struct mg_websocket_subprotocols **subprotocols,
  11442. mg_websocket_connect_handler *connect_handler,
  11443. mg_websocket_ready_handler *ready_handler,
  11444. mg_websocket_data_handler *data_handler,
  11445. mg_websocket_close_handler *close_handler,
  11446. mg_authorization_handler *auth_handler,
  11447. void **cbdata,
  11448. struct mg_handler_info **handler_info)
  11449. {
  11450. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11451. if (request_info) {
  11452. const char *uri = request_info->local_uri;
  11453. size_t urilen = strlen(uri);
  11454. struct mg_handler_info *tmp_rh;
  11455. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11456. return 0;
  11457. }
  11458. mg_lock_context(conn->phys_ctx);
  11459. /* first try for an exact match */
  11460. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11461. tmp_rh = tmp_rh->next) {
  11462. if (tmp_rh->handler_type == handler_type) {
  11463. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11464. if (handler_type == WEBSOCKET_HANDLER) {
  11465. *subprotocols = tmp_rh->subprotocols;
  11466. *connect_handler = tmp_rh->connect_handler;
  11467. *ready_handler = tmp_rh->ready_handler;
  11468. *data_handler = tmp_rh->data_handler;
  11469. *close_handler = tmp_rh->close_handler;
  11470. } else if (handler_type == REQUEST_HANDLER) {
  11471. *handler = tmp_rh->handler;
  11472. /* Acquire handler and give it back */
  11473. handler_info_acquire(tmp_rh);
  11474. *handler_info = tmp_rh;
  11475. } else { /* AUTH_HANDLER */
  11476. *auth_handler = tmp_rh->auth_handler;
  11477. }
  11478. *cbdata = tmp_rh->cbdata;
  11479. mg_unlock_context(conn->phys_ctx);
  11480. return 1;
  11481. }
  11482. }
  11483. }
  11484. /* next try for a partial match, we will accept uri/something */
  11485. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11486. tmp_rh = tmp_rh->next) {
  11487. if (tmp_rh->handler_type == handler_type) {
  11488. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11489. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11490. if (handler_type == WEBSOCKET_HANDLER) {
  11491. *subprotocols = tmp_rh->subprotocols;
  11492. *connect_handler = tmp_rh->connect_handler;
  11493. *ready_handler = tmp_rh->ready_handler;
  11494. *data_handler = tmp_rh->data_handler;
  11495. *close_handler = tmp_rh->close_handler;
  11496. } else if (handler_type == REQUEST_HANDLER) {
  11497. *handler = tmp_rh->handler;
  11498. /* Acquire handler and give it back */
  11499. handler_info_acquire(tmp_rh);
  11500. *handler_info = tmp_rh;
  11501. } else { /* AUTH_HANDLER */
  11502. *auth_handler = tmp_rh->auth_handler;
  11503. }
  11504. *cbdata = tmp_rh->cbdata;
  11505. mg_unlock_context(conn->phys_ctx);
  11506. return 1;
  11507. }
  11508. }
  11509. }
  11510. /* finally try for pattern match */
  11511. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11512. tmp_rh = tmp_rh->next) {
  11513. if (tmp_rh->handler_type == handler_type) {
  11514. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11515. if (handler_type == WEBSOCKET_HANDLER) {
  11516. *subprotocols = tmp_rh->subprotocols;
  11517. *connect_handler = tmp_rh->connect_handler;
  11518. *ready_handler = tmp_rh->ready_handler;
  11519. *data_handler = tmp_rh->data_handler;
  11520. *close_handler = tmp_rh->close_handler;
  11521. } else if (handler_type == REQUEST_HANDLER) {
  11522. *handler = tmp_rh->handler;
  11523. /* Acquire handler and give it back */
  11524. handler_info_acquire(tmp_rh);
  11525. *handler_info = tmp_rh;
  11526. } else { /* AUTH_HANDLER */
  11527. *auth_handler = tmp_rh->auth_handler;
  11528. }
  11529. *cbdata = tmp_rh->cbdata;
  11530. mg_unlock_context(conn->phys_ctx);
  11531. return 1;
  11532. }
  11533. }
  11534. }
  11535. mg_unlock_context(conn->phys_ctx);
  11536. }
  11537. return 0; /* none found */
  11538. }
  11539. /* Check if the script file is in a path, allowed for script files.
  11540. * This can be used if uploading files is possible not only for the server
  11541. * admin, and the upload mechanism does not check the file extension.
  11542. */
  11543. static int
  11544. is_in_script_path(const struct mg_connection *conn, const char *path)
  11545. {
  11546. /* TODO (Feature): Add config value for allowed script path.
  11547. * Default: All allowed. */
  11548. (void)conn;
  11549. (void)path;
  11550. return 1;
  11551. }
  11552. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11553. static int
  11554. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11555. void *cbdata)
  11556. {
  11557. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11558. if (pcallbacks->websocket_connect) {
  11559. return pcallbacks->websocket_connect(conn);
  11560. }
  11561. /* No handler set - assume "OK" */
  11562. return 0;
  11563. }
  11564. static void
  11565. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11566. {
  11567. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11568. if (pcallbacks->websocket_ready) {
  11569. pcallbacks->websocket_ready(conn);
  11570. }
  11571. }
  11572. static int
  11573. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11574. int bits,
  11575. char *data,
  11576. size_t len,
  11577. void *cbdata)
  11578. {
  11579. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11580. if (pcallbacks->websocket_data) {
  11581. return pcallbacks->websocket_data(conn, bits, data, len);
  11582. }
  11583. /* No handler set - assume "OK" */
  11584. return 1;
  11585. }
  11586. #endif
  11587. /* This is the heart of the Civetweb's logic.
  11588. * This function is called when the request is read, parsed and validated,
  11589. * and Civetweb must decide what action to take: serve a file, or
  11590. * a directory, or call embedded function, etcetera. */
  11591. static void
  11592. handle_request(struct mg_connection *conn)
  11593. {
  11594. struct mg_request_info *ri = &conn->request_info;
  11595. char path[PATH_MAX];
  11596. int uri_len, ssl_index;
  11597. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11598. is_put_or_delete_request = 0, is_callback_resource = 0;
  11599. int i;
  11600. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11601. mg_request_handler callback_handler = NULL;
  11602. struct mg_handler_info *handler_info = NULL;
  11603. struct mg_websocket_subprotocols *subprotocols;
  11604. mg_websocket_connect_handler ws_connect_handler = NULL;
  11605. mg_websocket_ready_handler ws_ready_handler = NULL;
  11606. mg_websocket_data_handler ws_data_handler = NULL;
  11607. mg_websocket_close_handler ws_close_handler = NULL;
  11608. void *callback_data = NULL;
  11609. mg_authorization_handler auth_handler = NULL;
  11610. void *auth_callback_data = NULL;
  11611. int handler_type;
  11612. time_t curtime = time(NULL);
  11613. char date[64];
  11614. path[0] = 0;
  11615. /* 1. get the request url */
  11616. /* 1.1. split into url and query string */
  11617. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11618. != NULL) {
  11619. *((char *)conn->request_info.query_string++) = '\0';
  11620. }
  11621. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11622. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11623. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11624. if (ssl_index >= 0) {
  11625. redirect_to_https_port(conn, ssl_index);
  11626. } else {
  11627. /* A http to https forward port has been specified,
  11628. * but no https port to forward to. */
  11629. mg_send_http_error(conn,
  11630. 503,
  11631. "%s",
  11632. "Error: SSL forward not configured properly");
  11633. mg_cry_internal(conn,
  11634. "%s",
  11635. "Can not redirect to SSL, no SSL port available");
  11636. }
  11637. return;
  11638. }
  11639. uri_len = (int)strlen(ri->local_uri);
  11640. /* 1.3. decode url (if config says so) */
  11641. if (should_decode_url(conn)) {
  11642. mg_url_decode(
  11643. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11644. }
  11645. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11646. * not possible */
  11647. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11648. /* step 1. completed, the url is known now */
  11649. uri_len = (int)strlen(ri->local_uri);
  11650. DEBUG_TRACE("URL: %s", ri->local_uri);
  11651. /* 2. if this ip has limited speed, set it for this connection */
  11652. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11653. get_remote_ip(conn),
  11654. ri->local_uri);
  11655. /* 3. call a "handle everything" callback, if registered */
  11656. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11657. /* Note that since V1.7 the "begin_request" function is called
  11658. * before an authorization check. If an authorization check is
  11659. * required, use a request_handler instead. */
  11660. i = conn->phys_ctx->callbacks.begin_request(conn);
  11661. if (i > 0) {
  11662. /* callback already processed the request. Store the
  11663. return value as a status code for the access log. */
  11664. conn->status_code = i;
  11665. discard_unread_request_data(conn);
  11666. return;
  11667. } else if (i == 0) {
  11668. /* civetweb should process the request */
  11669. } else {
  11670. /* unspecified - may change with the next version */
  11671. return;
  11672. }
  11673. }
  11674. /* request not yet handled by a handler or redirect, so the request
  11675. * is processed here */
  11676. /* 4. Check for CORS preflight requests and handle them (if configured).
  11677. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11678. */
  11679. if (!strcmp(ri->request_method, "OPTIONS")) {
  11680. /* Send a response to CORS preflights only if
  11681. * access_control_allow_methods is not NULL and not an empty string.
  11682. * In this case, scripts can still handle CORS. */
  11683. const char *cors_meth_cfg =
  11684. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11685. const char *cors_orig_cfg =
  11686. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11687. const char *cors_origin =
  11688. get_header(ri->http_headers, ri->num_headers, "Origin");
  11689. const char *cors_acrm = get_header(ri->http_headers,
  11690. ri->num_headers,
  11691. "Access-Control-Request-Method");
  11692. /* Todo: check if cors_origin is in cors_orig_cfg.
  11693. * Or, let the client check this. */
  11694. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11695. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11696. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11697. /* This is a valid CORS preflight, and the server is configured
  11698. * to
  11699. * handle it automatically. */
  11700. const char *cors_acrh =
  11701. get_header(ri->http_headers,
  11702. ri->num_headers,
  11703. "Access-Control-Request-Headers");
  11704. gmt_time_string(date, sizeof(date), &curtime);
  11705. mg_printf(conn,
  11706. "HTTP/1.1 200 OK\r\n"
  11707. "Date: %s\r\n"
  11708. "Access-Control-Allow-Origin: %s\r\n"
  11709. "Access-Control-Allow-Methods: %s\r\n"
  11710. "Content-Length: 0\r\n"
  11711. "Connection: %s\r\n",
  11712. date,
  11713. cors_orig_cfg,
  11714. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11715. suggest_connection_header(conn));
  11716. if (cors_acrh != NULL) {
  11717. /* CORS request is asking for additional headers */
  11718. const char *cors_hdr_cfg =
  11719. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11720. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11721. /* Allow only if access_control_allow_headers is
  11722. * not NULL and not an empty string. If this
  11723. * configuration is set to *, allow everything.
  11724. * Otherwise this configuration must be a list
  11725. * of allowed HTTP header names. */
  11726. mg_printf(conn,
  11727. "Access-Control-Allow-Headers: %s\r\n",
  11728. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11729. : cors_hdr_cfg));
  11730. }
  11731. }
  11732. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11733. mg_printf(conn, "\r\n");
  11734. return;
  11735. }
  11736. }
  11737. /* 5. interpret the url to find out how the request must be handled
  11738. */
  11739. /* 5.1. first test, if the request targets the regular http(s)://
  11740. * protocol namespace or the websocket ws(s):// protocol namespace.
  11741. */
  11742. is_websocket_request = is_websocket_protocol(conn);
  11743. #if defined(USE_WEBSOCKET)
  11744. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11745. #else
  11746. handler_type = REQUEST_HANDLER;
  11747. #endif /* defined(USE_WEBSOCKET) */
  11748. /* 5.2. check if the request will be handled by a callback */
  11749. if (get_request_handler(conn,
  11750. handler_type,
  11751. &callback_handler,
  11752. &subprotocols,
  11753. &ws_connect_handler,
  11754. &ws_ready_handler,
  11755. &ws_data_handler,
  11756. &ws_close_handler,
  11757. NULL,
  11758. &callback_data,
  11759. &handler_info)) {
  11760. /* 5.2.1. A callback will handle this request. All requests
  11761. * handled
  11762. * by a callback have to be considered as requests to a script
  11763. * resource. */
  11764. is_callback_resource = 1;
  11765. is_script_resource = 1;
  11766. is_put_or_delete_request = is_put_or_delete_method(conn);
  11767. } else {
  11768. no_callback_resource:
  11769. /* 5.2.2. No callback is responsible for this request. The URI
  11770. * addresses a file based resource (static content or Lua/cgi
  11771. * scripts in the file system). */
  11772. is_callback_resource = 0;
  11773. interpret_uri(conn,
  11774. path,
  11775. sizeof(path),
  11776. &file.stat,
  11777. &is_found,
  11778. &is_script_resource,
  11779. &is_websocket_request,
  11780. &is_put_or_delete_request);
  11781. }
  11782. /* 6. authorization check */
  11783. /* 6.1. a custom authorization handler is installed */
  11784. if (get_request_handler(conn,
  11785. AUTH_HANDLER,
  11786. NULL,
  11787. NULL,
  11788. NULL,
  11789. NULL,
  11790. NULL,
  11791. NULL,
  11792. &auth_handler,
  11793. &auth_callback_data,
  11794. NULL)) {
  11795. if (!auth_handler(conn, auth_callback_data)) {
  11796. return;
  11797. }
  11798. } else if (is_put_or_delete_request && !is_script_resource
  11799. && !is_callback_resource) {
  11800. /* 6.2. this request is a PUT/DELETE to a real file */
  11801. /* 6.2.1. thus, the server must have real files */
  11802. #if defined(NO_FILES)
  11803. if (1) {
  11804. #else
  11805. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11806. #endif
  11807. /* This server does not have any real files, thus the
  11808. * PUT/DELETE methods are not valid. */
  11809. mg_send_http_error(conn,
  11810. 405,
  11811. "%s method not allowed",
  11812. conn->request_info.request_method);
  11813. return;
  11814. }
  11815. #if !defined(NO_FILES)
  11816. /* 6.2.2. Check if put authorization for static files is
  11817. * available.
  11818. */
  11819. if (!is_authorized_for_put(conn)) {
  11820. send_authorization_request(conn, NULL);
  11821. return;
  11822. }
  11823. #endif
  11824. } else {
  11825. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11826. * or it is a PUT or DELETE request to a resource that does not
  11827. * correspond to a file. Check authorization. */
  11828. if (!check_authorization(conn, path)) {
  11829. send_authorization_request(conn, NULL);
  11830. return;
  11831. }
  11832. }
  11833. /* request is authorized or does not need authorization */
  11834. /* 7. check if there are request handlers for this uri */
  11835. if (is_callback_resource) {
  11836. if (!is_websocket_request) {
  11837. i = callback_handler(conn, callback_data);
  11838. /* Callback handler will not be used anymore. Release it */
  11839. handler_info_release(handler_info);
  11840. if (i > 0) {
  11841. /* Do nothing, callback has served the request. Store
  11842. * then return value as status code for the log and discard
  11843. * all data from the client not used by the callback. */
  11844. conn->status_code = i;
  11845. discard_unread_request_data(conn);
  11846. } else {
  11847. /* The handler did NOT handle the request. */
  11848. /* Some proper reactions would be:
  11849. * a) close the connections without sending anything
  11850. * b) send a 404 not found
  11851. * c) try if there is a file matching the URI
  11852. * It would be possible to do a, b or c in the callback
  11853. * implementation, and return 1 - we cannot do anything
  11854. * here, that is not possible in the callback.
  11855. *
  11856. * TODO: What would be the best reaction here?
  11857. * (Note: The reaction may change, if there is a better
  11858. *idea.)
  11859. */
  11860. /* For the moment, use option c: We look for a proper file,
  11861. * but since a file request is not always a script resource,
  11862. * the authorization check might be different. */
  11863. interpret_uri(conn,
  11864. path,
  11865. sizeof(path),
  11866. &file.stat,
  11867. &is_found,
  11868. &is_script_resource,
  11869. &is_websocket_request,
  11870. &is_put_or_delete_request);
  11871. callback_handler = NULL;
  11872. /* Here we are at a dead end:
  11873. * According to URI matching, a callback should be
  11874. * responsible for handling the request,
  11875. * we called it, but the callback declared itself
  11876. * not responsible.
  11877. * We use a goto here, to get out of this dead end,
  11878. * and continue with the default handling.
  11879. * A goto here is simpler and better to understand
  11880. * than some curious loop. */
  11881. goto no_callback_resource;
  11882. }
  11883. } else {
  11884. #if defined(USE_WEBSOCKET)
  11885. handle_websocket_request(conn,
  11886. path,
  11887. is_callback_resource,
  11888. subprotocols,
  11889. ws_connect_handler,
  11890. ws_ready_handler,
  11891. ws_data_handler,
  11892. ws_close_handler,
  11893. callback_data);
  11894. #endif
  11895. }
  11896. return;
  11897. }
  11898. /* 8. handle websocket requests */
  11899. #if defined(USE_WEBSOCKET)
  11900. if (is_websocket_request) {
  11901. if (is_script_resource) {
  11902. if (is_in_script_path(conn, path)) {
  11903. /* Websocket Lua script */
  11904. handle_websocket_request(conn,
  11905. path,
  11906. 0 /* Lua Script */,
  11907. NULL,
  11908. NULL,
  11909. NULL,
  11910. NULL,
  11911. NULL,
  11912. conn->phys_ctx->user_data);
  11913. } else {
  11914. /* Script was in an illegal path */
  11915. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11916. }
  11917. } else {
  11918. #if defined(MG_LEGACY_INTERFACE)
  11919. handle_websocket_request(
  11920. conn,
  11921. path,
  11922. !is_script_resource /* could be deprecated global callback */,
  11923. NULL,
  11924. deprecated_websocket_connect_wrapper,
  11925. deprecated_websocket_ready_wrapper,
  11926. deprecated_websocket_data_wrapper,
  11927. NULL,
  11928. conn->phys_ctx->user_data);
  11929. #else
  11930. mg_send_http_error(conn, 404, "%s", "Not found");
  11931. #endif
  11932. }
  11933. return;
  11934. } else
  11935. #endif
  11936. #if defined(NO_FILES)
  11937. /* 9a. In case the server uses only callbacks, this uri is
  11938. * unknown.
  11939. * Then, all request handling ends here. */
  11940. mg_send_http_error(conn, 404, "%s", "Not Found");
  11941. #else
  11942. /* 9b. This request is either for a static file or resource handled
  11943. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11944. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11945. mg_send_http_error(conn, 404, "%s", "Not Found");
  11946. return;
  11947. }
  11948. /* 10. Request is handled by a script */
  11949. if (is_script_resource) {
  11950. handle_file_based_request(conn, path, &file);
  11951. return;
  11952. }
  11953. /* 11. Handle put/delete/mkcol requests */
  11954. if (is_put_or_delete_request) {
  11955. /* 11.1. PUT method */
  11956. if (!strcmp(ri->request_method, "PUT")) {
  11957. put_file(conn, path);
  11958. return;
  11959. }
  11960. /* 11.2. DELETE method */
  11961. if (!strcmp(ri->request_method, "DELETE")) {
  11962. delete_file(conn, path);
  11963. return;
  11964. }
  11965. /* 11.3. MKCOL method */
  11966. if (!strcmp(ri->request_method, "MKCOL")) {
  11967. mkcol(conn, path);
  11968. return;
  11969. }
  11970. /* 11.4. PATCH method
  11971. * This method is not supported for static resources,
  11972. * only for scripts (Lua, CGI) and callbacks. */
  11973. mg_send_http_error(conn,
  11974. 405,
  11975. "%s method not allowed",
  11976. conn->request_info.request_method);
  11977. return;
  11978. }
  11979. /* 11. File does not exist, or it was configured that it should be
  11980. * hidden */
  11981. if (!is_found || (must_hide_file(conn, path))) {
  11982. mg_send_http_error(conn, 404, "%s", "Not found");
  11983. return;
  11984. }
  11985. /* 12. Directory uris should end with a slash */
  11986. if (file.stat.is_directory && (uri_len > 0)
  11987. && (ri->local_uri[uri_len - 1] != '/')) {
  11988. gmt_time_string(date, sizeof(date), &curtime);
  11989. mg_printf(conn,
  11990. "HTTP/1.1 301 Moved Permanently\r\n"
  11991. "Location: %s/\r\n"
  11992. "Date: %s\r\n"
  11993. /* "Cache-Control: private\r\n" (= default) */
  11994. "Content-Length: 0\r\n"
  11995. "Connection: %s\r\n",
  11996. ri->request_uri,
  11997. date,
  11998. suggest_connection_header(conn));
  11999. send_additional_header(conn);
  12000. mg_printf(conn, "\r\n");
  12001. return;
  12002. }
  12003. /* 13. Handle other methods than GET/HEAD */
  12004. /* 13.1. Handle PROPFIND */
  12005. if (!strcmp(ri->request_method, "PROPFIND")) {
  12006. handle_propfind(conn, path, &file.stat);
  12007. return;
  12008. }
  12009. /* 13.2. Handle OPTIONS for files */
  12010. if (!strcmp(ri->request_method, "OPTIONS")) {
  12011. /* This standard handler is only used for real files.
  12012. * Scripts should support the OPTIONS method themselves, to allow a
  12013. * maximum flexibility.
  12014. * Lua and CGI scripts may fully support CORS this way (including
  12015. * preflights). */
  12016. send_options(conn);
  12017. return;
  12018. }
  12019. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12020. if ((0 != strcmp(ri->request_method, "GET"))
  12021. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12022. mg_send_http_error(conn,
  12023. 405,
  12024. "%s method not allowed",
  12025. conn->request_info.request_method);
  12026. return;
  12027. }
  12028. /* 14. directories */
  12029. if (file.stat.is_directory) {
  12030. /* Substitute files have already been handled above. */
  12031. /* Here we can either generate and send a directory listing,
  12032. * or send an "access denied" error. */
  12033. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12034. "yes")) {
  12035. handle_directory_request(conn, path);
  12036. } else {
  12037. mg_send_http_error(conn,
  12038. 403,
  12039. "%s",
  12040. "Error: Directory listing denied");
  12041. }
  12042. return;
  12043. }
  12044. /* 15. read a normal file with GET or HEAD */
  12045. handle_file_based_request(conn, path, &file);
  12046. #endif /* !defined(NO_FILES) */
  12047. }
  12048. static void
  12049. handle_file_based_request(struct mg_connection *conn,
  12050. const char *path,
  12051. struct mg_file *file)
  12052. {
  12053. if (!conn || !conn->dom_ctx) {
  12054. return;
  12055. }
  12056. if (0) {
  12057. #if defined(USE_LUA)
  12058. } else if (match_prefix(
  12059. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12060. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12061. path) > 0) {
  12062. if (is_in_script_path(conn, path)) {
  12063. /* Lua server page: an SSI like page containing mostly plain
  12064. * html
  12065. * code
  12066. * plus some tags with server generated contents. */
  12067. handle_lsp_request(conn, path, file, NULL);
  12068. } else {
  12069. /* Script was in an illegal path */
  12070. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12071. }
  12072. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12073. strlen(
  12074. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12075. path) > 0) {
  12076. if (is_in_script_path(conn, path)) {
  12077. /* Lua in-server module script: a CGI like script used to
  12078. * generate
  12079. * the
  12080. * entire reply. */
  12081. mg_exec_lua_script(conn, path, NULL);
  12082. } else {
  12083. /* Script was in an illegal path */
  12084. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12085. }
  12086. #endif
  12087. #if defined(USE_DUKTAPE)
  12088. } else if (match_prefix(
  12089. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12090. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12091. path) > 0) {
  12092. if (is_in_script_path(conn, path)) {
  12093. /* Call duktape to generate the page */
  12094. mg_exec_duktape_script(conn, path);
  12095. } else {
  12096. /* Script was in an illegal path */
  12097. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12098. }
  12099. #endif
  12100. #if !defined(NO_CGI)
  12101. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12102. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12103. path) > 0) {
  12104. if (is_in_script_path(conn, path)) {
  12105. /* CGI scripts may support all HTTP methods */
  12106. handle_cgi_request(conn, path);
  12107. } else {
  12108. /* Script was in an illegal path */
  12109. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12110. }
  12111. #endif /* !NO_CGI */
  12112. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12113. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12114. path) > 0) {
  12115. if (is_in_script_path(conn, path)) {
  12116. handle_ssi_file_request(conn, path, file);
  12117. } else {
  12118. /* Script was in an illegal path */
  12119. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12120. }
  12121. #if !defined(NO_CACHING)
  12122. } else if ((!conn->in_error_handler)
  12123. && is_not_modified(conn, &file->stat)) {
  12124. /* Send 304 "Not Modified" - this must not send any body data */
  12125. handle_not_modified_static_file_request(conn, file);
  12126. #endif /* !NO_CACHING */
  12127. } else {
  12128. handle_static_file_request(conn, path, file, NULL, NULL);
  12129. }
  12130. }
  12131. static void
  12132. close_all_listening_sockets(struct mg_context *ctx)
  12133. {
  12134. unsigned int i;
  12135. if (!ctx) {
  12136. return;
  12137. }
  12138. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12139. closesocket(ctx->listening_sockets[i].sock);
  12140. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12141. }
  12142. mg_free(ctx->listening_sockets);
  12143. ctx->listening_sockets = NULL;
  12144. mg_free(ctx->listening_socket_fds);
  12145. ctx->listening_socket_fds = NULL;
  12146. }
  12147. /* Valid listening port specification is: [ip_address:]port[s]
  12148. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12149. * Examples for IPv6: [::]:80, [::1]:80,
  12150. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12151. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12152. * In order to bind to both, IPv4 and IPv6, you can either add
  12153. * both ports using 8080,[::]:8080, or the short form +8080.
  12154. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12155. * one only accepting IPv4 the other only IPv6. +8080 creates
  12156. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12157. * environment, they might work differently, or might not work
  12158. * at all - it must be tested what options work best in the
  12159. * relevant network environment.
  12160. */
  12161. static int
  12162. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12163. {
  12164. unsigned int a, b, c, d, port;
  12165. int ch, len;
  12166. const char *cb;
  12167. #if defined(USE_IPV6)
  12168. char buf[100] = {0};
  12169. #endif
  12170. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12171. * Also, all-zeroes in the socket address means binding to all addresses
  12172. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12173. memset(so, 0, sizeof(*so));
  12174. so->lsa.sin.sin_family = AF_INET;
  12175. *ip_version = 0;
  12176. /* Initialize port and len as invalid. */
  12177. port = 0;
  12178. len = 0;
  12179. /* Test for different ways to format this string */
  12180. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12181. == 5) {
  12182. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12183. so->lsa.sin.sin_addr.s_addr =
  12184. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12185. so->lsa.sin.sin_port = htons((uint16_t)port);
  12186. *ip_version = 4;
  12187. #if defined(USE_IPV6)
  12188. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12189. && mg_inet_pton(
  12190. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12191. /* IPv6 address, examples: see above */
  12192. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12193. */
  12194. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12195. *ip_version = 6;
  12196. #endif
  12197. } else if ((vec->ptr[0] == '+')
  12198. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12199. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12200. /* Add 1 to len for the + character we skipped before */
  12201. len++;
  12202. #if defined(USE_IPV6)
  12203. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12204. so->lsa.sin6.sin6_family = AF_INET6;
  12205. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12206. *ip_version = 4 + 6;
  12207. #else
  12208. /* Bind to IPv4 only, since IPv6 is not built in. */
  12209. so->lsa.sin.sin_port = htons((uint16_t)port);
  12210. *ip_version = 4;
  12211. #endif
  12212. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12213. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12214. so->lsa.sin.sin_port = htons((uint16_t)port);
  12215. *ip_version = 4;
  12216. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12217. /* String could be a hostname. This check algotithm
  12218. * will only work for RFC 952 compliant hostnames,
  12219. * starting with a letter, containing only letters,
  12220. * digits and hyphen ('-'). Newer specs may allow
  12221. * more, but this is not guaranteed here, since it
  12222. * may interfere with rules for port option lists. */
  12223. /* According to RFC 1035, hostnames are restricted to 255 characters
  12224. * in total (63 between two dots). */
  12225. char hostname[256];
  12226. size_t hostnlen = (size_t)(cb - vec->ptr);
  12227. if (hostnlen >= sizeof(hostname)) {
  12228. /* This would be invalid in any case */
  12229. *ip_version = 0;
  12230. return 0;
  12231. }
  12232. memcpy(hostname, vec->ptr, hostnlen);
  12233. hostname[hostnlen] = 0;
  12234. if (mg_inet_pton(
  12235. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12236. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12237. *ip_version = 4;
  12238. so->lsa.sin.sin_family = AF_INET;
  12239. so->lsa.sin.sin_port = htons((uint16_t)port);
  12240. len += (int)(hostnlen + 1);
  12241. } else {
  12242. port = 0;
  12243. len = 0;
  12244. }
  12245. #if defined(USE_IPV6)
  12246. } else if (mg_inet_pton(AF_INET6,
  12247. vec->ptr,
  12248. &so->lsa.sin6,
  12249. sizeof(so->lsa.sin6))) {
  12250. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12251. *ip_version = 6;
  12252. so->lsa.sin6.sin6_family = AF_INET6;
  12253. so->lsa.sin.sin_port = htons((uint16_t)port);
  12254. len += (int)(hostnlen + 1);
  12255. } else {
  12256. port = 0;
  12257. len = 0;
  12258. }
  12259. #endif
  12260. }
  12261. } else {
  12262. /* Parsing failure. */
  12263. }
  12264. /* sscanf and the option splitting code ensure the following condition
  12265. */
  12266. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12267. *ip_version = 0;
  12268. return 0;
  12269. }
  12270. ch = vec->ptr[len]; /* Next character after the port number */
  12271. so->is_ssl = (ch == 's');
  12272. so->ssl_redir = (ch == 'r');
  12273. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12274. if (is_valid_port(port)
  12275. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12276. return 1;
  12277. }
  12278. /* Reset ip_version to 0 if there is an error */
  12279. *ip_version = 0;
  12280. return 0;
  12281. }
  12282. /* Is there any SSL port in use? */
  12283. static int
  12284. is_ssl_port_used(const char *ports)
  12285. {
  12286. if (ports) {
  12287. /* There are several different allowed syntax variants:
  12288. * - "80" for a single port using every network interface
  12289. * - "localhost:80" for a single port using only localhost
  12290. * - "80,localhost:8080" for two ports, one bound to localhost
  12291. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12292. * to IPv4 localhost, one to IPv6 localhost
  12293. * - "+80" use port 80 for IPv4 and IPv6
  12294. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12295. * for both: IPv4 and IPv4
  12296. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12297. * additionally port 8080 bound to localhost connections
  12298. *
  12299. * If we just look for 's' anywhere in the string, "localhost:80"
  12300. * will be detected as SSL (false positive).
  12301. * Looking for 's' after a digit may cause false positives in
  12302. * "my24service:8080".
  12303. * Looking from 's' backward if there are only ':' and numbers
  12304. * before will not work for "24service:8080" (non SSL, port 8080)
  12305. * or "24s" (SSL, port 24).
  12306. *
  12307. * Remark: Initially hostnames were not allowed to start with a
  12308. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12309. * Section 2.1).
  12310. *
  12311. * To get this correct, the entire string must be parsed as a whole,
  12312. * reading it as a list element for element and parsing with an
  12313. * algorithm equivalent to parse_port_string.
  12314. *
  12315. * In fact, we use local interface names here, not arbitrary hostnames,
  12316. * so in most cases the only name will be "localhost".
  12317. *
  12318. * So, for now, we use this simple algorithm, that may still return
  12319. * a false positive in bizarre cases.
  12320. */
  12321. int i;
  12322. int portslen = (int)strlen(ports);
  12323. char prevIsNumber = 0;
  12324. for (i = 0; i < portslen; i++) {
  12325. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12326. return 1;
  12327. }
  12328. if (ports[i] >= '0' && ports[i] <= '9') {
  12329. prevIsNumber = 1;
  12330. } else {
  12331. prevIsNumber = 0;
  12332. }
  12333. }
  12334. }
  12335. return 0;
  12336. }
  12337. static int
  12338. set_ports_option(struct mg_context *phys_ctx)
  12339. {
  12340. const char *list;
  12341. int on = 1;
  12342. #if defined(USE_IPV6)
  12343. int off = 0;
  12344. #endif
  12345. struct vec vec;
  12346. struct socket so, *ptr;
  12347. struct pollfd *pfd;
  12348. union usa usa;
  12349. socklen_t len;
  12350. int ip_version;
  12351. int portsTotal = 0;
  12352. int portsOk = 0;
  12353. if (!phys_ctx) {
  12354. return 0;
  12355. }
  12356. memset(&so, 0, sizeof(so));
  12357. memset(&usa, 0, sizeof(usa));
  12358. len = sizeof(usa);
  12359. list = phys_ctx->dd.config[LISTENING_PORTS];
  12360. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12361. portsTotal++;
  12362. if (!parse_port_string(&vec, &so, &ip_version)) {
  12363. mg_cry_internal(
  12364. fc(phys_ctx),
  12365. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12366. (int)vec.len,
  12367. vec.ptr,
  12368. portsTotal,
  12369. "[IP_ADDRESS:]PORT[s|r]");
  12370. continue;
  12371. }
  12372. #if !defined(NO_SSL)
  12373. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12374. mg_cry_internal(fc(phys_ctx),
  12375. "Cannot add SSL socket (entry %i)",
  12376. portsTotal);
  12377. continue;
  12378. }
  12379. #endif
  12380. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12381. == INVALID_SOCKET) {
  12382. mg_cry_internal(fc(phys_ctx),
  12383. "cannot create socket (entry %i)",
  12384. portsTotal);
  12385. continue;
  12386. }
  12387. #if defined(_WIN32)
  12388. /* Windows SO_REUSEADDR lets many procs binds to a
  12389. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12390. * if someone already has the socket -- DTL */
  12391. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12392. * Windows might need a few seconds before
  12393. * the same port can be used again in the
  12394. * same process, so a short Sleep may be
  12395. * required between mg_stop and mg_start.
  12396. */
  12397. if (setsockopt(so.sock,
  12398. SOL_SOCKET,
  12399. SO_EXCLUSIVEADDRUSE,
  12400. (SOCK_OPT_TYPE)&on,
  12401. sizeof(on)) != 0) {
  12402. /* Set reuse option, but don't abort on errors. */
  12403. mg_cry_internal(
  12404. fc(phys_ctx),
  12405. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12406. portsTotal);
  12407. }
  12408. #else
  12409. if (setsockopt(so.sock,
  12410. SOL_SOCKET,
  12411. SO_REUSEADDR,
  12412. (SOCK_OPT_TYPE)&on,
  12413. sizeof(on)) != 0) {
  12414. /* Set reuse option, but don't abort on errors. */
  12415. mg_cry_internal(fc(phys_ctx),
  12416. "cannot set socket option SO_REUSEADDR (entry %i)",
  12417. portsTotal);
  12418. }
  12419. #endif
  12420. if (ip_version > 4) {
  12421. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12422. #if defined(USE_IPV6)
  12423. if (ip_version > 6) {
  12424. if (so.lsa.sa.sa_family == AF_INET6
  12425. && setsockopt(so.sock,
  12426. IPPROTO_IPV6,
  12427. IPV6_V6ONLY,
  12428. (void *)&off,
  12429. sizeof(off)) != 0) {
  12430. /* Set IPv6 only option, but don't abort on errors. */
  12431. mg_cry_internal(
  12432. fc(phys_ctx),
  12433. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12434. portsTotal);
  12435. }
  12436. } else {
  12437. if (so.lsa.sa.sa_family == AF_INET6
  12438. && setsockopt(so.sock,
  12439. IPPROTO_IPV6,
  12440. IPV6_V6ONLY,
  12441. (void *)&on,
  12442. sizeof(on)) != 0) {
  12443. /* Set IPv6 only option, but don't abort on errors. */
  12444. mg_cry_internal(
  12445. fc(phys_ctx),
  12446. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12447. portsTotal);
  12448. }
  12449. }
  12450. #else
  12451. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12452. closesocket(so.sock);
  12453. so.sock = INVALID_SOCKET;
  12454. continue;
  12455. #endif
  12456. }
  12457. if (so.lsa.sa.sa_family == AF_INET) {
  12458. len = sizeof(so.lsa.sin);
  12459. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12460. mg_cry_internal(fc(phys_ctx),
  12461. "cannot bind to %.*s: %d (%s)",
  12462. (int)vec.len,
  12463. vec.ptr,
  12464. (int)ERRNO,
  12465. strerror(errno));
  12466. closesocket(so.sock);
  12467. so.sock = INVALID_SOCKET;
  12468. continue;
  12469. }
  12470. }
  12471. #if defined(USE_IPV6)
  12472. else if (so.lsa.sa.sa_family == AF_INET6) {
  12473. len = sizeof(so.lsa.sin6);
  12474. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12475. mg_cry_internal(fc(phys_ctx),
  12476. "cannot bind to IPv6 %.*s: %d (%s)",
  12477. (int)vec.len,
  12478. vec.ptr,
  12479. (int)ERRNO,
  12480. strerror(errno));
  12481. closesocket(so.sock);
  12482. so.sock = INVALID_SOCKET;
  12483. continue;
  12484. }
  12485. }
  12486. #endif
  12487. else {
  12488. mg_cry_internal(
  12489. fc(phys_ctx),
  12490. "cannot bind: address family not supported (entry %i)",
  12491. portsTotal);
  12492. closesocket(so.sock);
  12493. so.sock = INVALID_SOCKET;
  12494. continue;
  12495. }
  12496. if (listen(so.sock, SOMAXCONN) != 0) {
  12497. mg_cry_internal(fc(phys_ctx),
  12498. "cannot listen to %.*s: %d (%s)",
  12499. (int)vec.len,
  12500. vec.ptr,
  12501. (int)ERRNO,
  12502. strerror(errno));
  12503. closesocket(so.sock);
  12504. so.sock = INVALID_SOCKET;
  12505. continue;
  12506. }
  12507. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12508. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12509. int err = (int)ERRNO;
  12510. mg_cry_internal(fc(phys_ctx),
  12511. "call to getsockname failed %.*s: %d (%s)",
  12512. (int)vec.len,
  12513. vec.ptr,
  12514. err,
  12515. strerror(errno));
  12516. closesocket(so.sock);
  12517. so.sock = INVALID_SOCKET;
  12518. continue;
  12519. }
  12520. /* Update lsa port in case of random free ports */
  12521. #if defined(USE_IPV6)
  12522. if (so.lsa.sa.sa_family == AF_INET6) {
  12523. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12524. } else
  12525. #endif
  12526. {
  12527. so.lsa.sin.sin_port = usa.sin.sin_port;
  12528. }
  12529. if ((ptr = (struct socket *)
  12530. mg_realloc_ctx(phys_ctx->listening_sockets,
  12531. (phys_ctx->num_listening_sockets + 1)
  12532. * sizeof(phys_ctx->listening_sockets[0]),
  12533. phys_ctx)) == NULL) {
  12534. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12535. closesocket(so.sock);
  12536. so.sock = INVALID_SOCKET;
  12537. continue;
  12538. }
  12539. if ((pfd = (struct pollfd *)
  12540. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12541. (phys_ctx->num_listening_sockets + 1)
  12542. * sizeof(phys_ctx->listening_socket_fds[0]),
  12543. phys_ctx)) == NULL) {
  12544. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12545. closesocket(so.sock);
  12546. so.sock = INVALID_SOCKET;
  12547. mg_free(ptr);
  12548. continue;
  12549. }
  12550. set_close_on_exec(so.sock, fc(phys_ctx));
  12551. phys_ctx->listening_sockets = ptr;
  12552. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12553. phys_ctx->listening_socket_fds = pfd;
  12554. phys_ctx->num_listening_sockets++;
  12555. portsOk++;
  12556. }
  12557. if (portsOk != portsTotal) {
  12558. close_all_listening_sockets(phys_ctx);
  12559. portsOk = 0;
  12560. }
  12561. return portsOk;
  12562. }
  12563. static const char *
  12564. header_val(const struct mg_connection *conn, const char *header)
  12565. {
  12566. const char *header_value;
  12567. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12568. return "-";
  12569. } else {
  12570. return header_value;
  12571. }
  12572. }
  12573. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12574. static void log_access(const struct mg_connection *conn);
  12575. #include "external_log_access.inl"
  12576. #else
  12577. static void
  12578. log_access(const struct mg_connection *conn)
  12579. {
  12580. const struct mg_request_info *ri;
  12581. struct mg_file fi;
  12582. char date[64], src_addr[IP_ADDR_STR_LEN];
  12583. struct tm *tm;
  12584. const char *referer;
  12585. const char *user_agent;
  12586. char buf[4096];
  12587. if (!conn || !conn->dom_ctx) {
  12588. return;
  12589. }
  12590. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12591. if (mg_fopen(conn,
  12592. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12593. MG_FOPEN_MODE_APPEND,
  12594. &fi) == 0) {
  12595. fi.access.fp = NULL;
  12596. }
  12597. } else {
  12598. fi.access.fp = NULL;
  12599. }
  12600. /* Log is written to a file and/or a callback. If both are not set,
  12601. * executing the rest of the function is pointless. */
  12602. if ((fi.access.fp == NULL)
  12603. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12604. return;
  12605. }
  12606. tm = localtime(&conn->conn_birth_time);
  12607. if (tm != NULL) {
  12608. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12609. } else {
  12610. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12611. date[sizeof(date) - 1] = '\0';
  12612. }
  12613. ri = &conn->request_info;
  12614. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12615. referer = header_val(conn, "Referer");
  12616. user_agent = header_val(conn, "User-Agent");
  12617. mg_snprintf(conn,
  12618. NULL, /* Ignore truncation in access log */
  12619. buf,
  12620. sizeof(buf),
  12621. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12622. src_addr,
  12623. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12624. date,
  12625. ri->request_method ? ri->request_method : "-",
  12626. ri->request_uri ? ri->request_uri : "-",
  12627. ri->query_string ? "?" : "",
  12628. ri->query_string ? ri->query_string : "",
  12629. ri->http_version,
  12630. conn->status_code,
  12631. conn->num_bytes_sent,
  12632. referer,
  12633. user_agent);
  12634. if (conn->phys_ctx->callbacks.log_access) {
  12635. conn->phys_ctx->callbacks.log_access(conn, buf);
  12636. }
  12637. if (fi.access.fp) {
  12638. int ok = 1;
  12639. flockfile(fi.access.fp);
  12640. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12641. ok = 0;
  12642. }
  12643. if (fflush(fi.access.fp) != 0) {
  12644. ok = 0;
  12645. }
  12646. funlockfile(fi.access.fp);
  12647. if (mg_fclose(&fi.access) != 0) {
  12648. ok = 0;
  12649. }
  12650. if (!ok) {
  12651. mg_cry_internal(conn,
  12652. "Error writing log file %s",
  12653. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12654. }
  12655. }
  12656. }
  12657. #endif /* Externally provided function */
  12658. /* Verify given socket address against the ACL.
  12659. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12660. */
  12661. static int
  12662. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12663. {
  12664. int allowed, flag;
  12665. uint32_t net, mask;
  12666. struct vec vec;
  12667. if (phys_ctx) {
  12668. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12669. /* If any ACL is set, deny by default */
  12670. allowed = (list == NULL) ? '+' : '-';
  12671. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12672. flag = vec.ptr[0];
  12673. if ((flag != '+' && flag != '-')
  12674. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12675. mg_cry_internal(fc(phys_ctx),
  12676. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12677. __func__);
  12678. return -1;
  12679. }
  12680. if (net == (remote_ip & mask)) {
  12681. allowed = flag;
  12682. }
  12683. }
  12684. return allowed == '+';
  12685. }
  12686. return -1;
  12687. }
  12688. #if !defined(_WIN32)
  12689. static int
  12690. set_uid_option(struct mg_context *phys_ctx)
  12691. {
  12692. int success = 0;
  12693. if (phys_ctx) {
  12694. /* We are currently running as curr_uid. */
  12695. const uid_t curr_uid = getuid();
  12696. /* If set, we want to run as run_as_user. */
  12697. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12698. const struct passwd *to_pw = NULL;
  12699. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12700. /* run_as_user does not exist on the system. We can't proceed
  12701. * further. */
  12702. mg_cry_internal(fc(phys_ctx),
  12703. "%s: unknown user [%s]",
  12704. __func__,
  12705. run_as_user);
  12706. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12707. /* There was either no request to change user, or we're already
  12708. * running as run_as_user. Nothing else to do.
  12709. */
  12710. success = 1;
  12711. } else {
  12712. /* Valid change request. */
  12713. if (setgid(to_pw->pw_gid) == -1) {
  12714. mg_cry_internal(fc(phys_ctx),
  12715. "%s: setgid(%s): %s",
  12716. __func__,
  12717. run_as_user,
  12718. strerror(errno));
  12719. } else if (setgroups(0, NULL) == -1) {
  12720. mg_cry_internal(fc(phys_ctx),
  12721. "%s: setgroups(): %s",
  12722. __func__,
  12723. strerror(errno));
  12724. } else if (setuid(to_pw->pw_uid) == -1) {
  12725. mg_cry_internal(fc(phys_ctx),
  12726. "%s: setuid(%s): %s",
  12727. __func__,
  12728. run_as_user,
  12729. strerror(errno));
  12730. } else {
  12731. success = 1;
  12732. }
  12733. }
  12734. }
  12735. return success;
  12736. }
  12737. #endif /* !_WIN32 */
  12738. static void
  12739. tls_dtor(void *key)
  12740. {
  12741. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12742. /* key == pthread_getspecific(sTlsKey); */
  12743. if (tls) {
  12744. if (tls->is_master == 2) {
  12745. tls->is_master = -3; /* Mark memory as dead */
  12746. mg_free(tls);
  12747. }
  12748. }
  12749. pthread_setspecific(sTlsKey, NULL);
  12750. }
  12751. #if !defined(NO_SSL)
  12752. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12753. struct mg_domain_context *dom_ctx,
  12754. const char *pem,
  12755. const char *chain);
  12756. static const char *ssl_error(void);
  12757. static int
  12758. refresh_trust(struct mg_connection *conn)
  12759. {
  12760. static int reload_lock = 0;
  12761. static long int data_check = 0;
  12762. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12763. struct stat cert_buf;
  12764. long int t;
  12765. const char *pem;
  12766. const char *chain;
  12767. int should_verify_peer;
  12768. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12769. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12770. * refresh_trust still can not work. */
  12771. return 0;
  12772. }
  12773. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12774. if (chain == NULL) {
  12775. /* pem is not NULL here */
  12776. chain = pem;
  12777. }
  12778. if (*chain == 0) {
  12779. chain = NULL;
  12780. }
  12781. t = data_check;
  12782. if (stat(pem, &cert_buf) != -1) {
  12783. t = (long int)cert_buf.st_mtime;
  12784. }
  12785. if (data_check != t) {
  12786. data_check = t;
  12787. should_verify_peer = 0;
  12788. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12789. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12790. == 0) {
  12791. should_verify_peer = 1;
  12792. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12793. "optional") == 0) {
  12794. should_verify_peer = 1;
  12795. }
  12796. }
  12797. if (should_verify_peer) {
  12798. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12799. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12800. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12801. ca_file,
  12802. ca_path) != 1) {
  12803. mg_cry_internal(
  12804. fc(conn->phys_ctx),
  12805. "SSL_CTX_load_verify_locations error: %s "
  12806. "ssl_verify_peer requires setting "
  12807. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12808. "present in "
  12809. "the .conf file?",
  12810. ssl_error());
  12811. return 0;
  12812. }
  12813. }
  12814. if (1 == mg_atomic_inc(p_reload_lock)) {
  12815. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12816. == 0) {
  12817. return 0;
  12818. }
  12819. *p_reload_lock = 0;
  12820. }
  12821. }
  12822. /* lock while cert is reloading */
  12823. while (*p_reload_lock) {
  12824. sleep(1);
  12825. }
  12826. return 1;
  12827. }
  12828. #if defined(OPENSSL_API_1_1)
  12829. #else
  12830. static pthread_mutex_t *ssl_mutexes;
  12831. #endif /* OPENSSL_API_1_1 */
  12832. static int
  12833. sslize(struct mg_connection *conn,
  12834. SSL_CTX *s,
  12835. int (*func)(SSL *),
  12836. volatile int *stop_server)
  12837. {
  12838. int ret, err;
  12839. int short_trust;
  12840. unsigned i;
  12841. if (!conn) {
  12842. return 0;
  12843. }
  12844. short_trust =
  12845. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12846. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12847. if (short_trust) {
  12848. int trust_ret = refresh_trust(conn);
  12849. if (!trust_ret) {
  12850. return trust_ret;
  12851. }
  12852. }
  12853. conn->ssl = SSL_new(s);
  12854. if (conn->ssl == NULL) {
  12855. return 0;
  12856. }
  12857. SSL_set_app_data(conn->ssl, (char *)conn);
  12858. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12859. if (ret != 1) {
  12860. err = SSL_get_error(conn->ssl, ret);
  12861. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  12862. SSL_free(conn->ssl);
  12863. conn->ssl = NULL;
  12864. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12865. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12866. #if !defined(OPENSSL_API_1_1)
  12867. ERR_remove_state(0);
  12868. #endif
  12869. return 0;
  12870. }
  12871. /* SSL functions may fail and require to be called again:
  12872. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  12873. * Here "func" could be SSL_connect or SSL_accept. */
  12874. for (i = 16; i <= 1024; i *= 2) {
  12875. ret = func(conn->ssl);
  12876. if (ret != 1) {
  12877. err = SSL_get_error(conn->ssl, ret);
  12878. if ((err == SSL_ERROR_WANT_CONNECT)
  12879. || (err == SSL_ERROR_WANT_ACCEPT)
  12880. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  12881. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  12882. /* Need to retry the function call "later".
  12883. * See https://linux.die.net/man/3/ssl_get_error
  12884. * This is typical for non-blocking sockets. */
  12885. if (*stop_server) {
  12886. /* Don't wait if the server is going to be stopped. */
  12887. break;
  12888. }
  12889. mg_sleep(i);
  12890. } else if (err == SSL_ERROR_SYSCALL) {
  12891. /* This is an IO error. Look at errno. */
  12892. err = errno;
  12893. mg_cry_internal(conn, "SSL syscall error %i", err);
  12894. break;
  12895. } else {
  12896. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  12897. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  12898. break;
  12899. }
  12900. } else {
  12901. /* success */
  12902. break;
  12903. }
  12904. }
  12905. if (ret != 1) {
  12906. SSL_free(conn->ssl);
  12907. conn->ssl = NULL;
  12908. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12909. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12910. #if !defined(OPENSSL_API_1_1)
  12911. ERR_remove_state(0);
  12912. #endif
  12913. return 0;
  12914. }
  12915. return 1;
  12916. }
  12917. /* Return OpenSSL error message (from CRYPTO lib) */
  12918. static const char *
  12919. ssl_error(void)
  12920. {
  12921. unsigned long err;
  12922. err = ERR_get_error();
  12923. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  12924. }
  12925. static int
  12926. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  12927. {
  12928. int i;
  12929. const char hexdigit[] = "0123456789abcdef";
  12930. if ((memlen <= 0) || (buflen <= 0)) {
  12931. return 0;
  12932. }
  12933. if (buflen < (3 * memlen)) {
  12934. return 0;
  12935. }
  12936. for (i = 0; i < memlen; i++) {
  12937. if (i > 0) {
  12938. buf[3 * i - 1] = ' ';
  12939. }
  12940. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12941. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12942. }
  12943. buf[3 * memlen - 1] = 0;
  12944. return 1;
  12945. }
  12946. static void
  12947. ssl_get_client_cert_info(struct mg_connection *conn)
  12948. {
  12949. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12950. if (cert) {
  12951. char str_subject[1024];
  12952. char str_issuer[1024];
  12953. char str_finger[1024];
  12954. unsigned char buf[256];
  12955. char *str_serial = NULL;
  12956. unsigned int ulen;
  12957. int ilen;
  12958. unsigned char *tmp_buf;
  12959. unsigned char *tmp_p;
  12960. /* Handle to algorithm used for fingerprint */
  12961. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12962. /* Get Subject and issuer */
  12963. X509_NAME *subj = X509_get_subject_name(cert);
  12964. X509_NAME *iss = X509_get_issuer_name(cert);
  12965. /* Get serial number */
  12966. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12967. /* Translate serial number to a hex string */
  12968. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12969. str_serial = BN_bn2hex(serial_bn);
  12970. BN_free(serial_bn);
  12971. /* Translate subject and issuer to a string */
  12972. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12973. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12974. /* Calculate SHA1 fingerprint and store as a hex string */
  12975. ulen = 0;
  12976. /* ASN1_digest is deprecated. Do the calculation manually,
  12977. * using EVP_Digest. */
  12978. ilen = i2d_X509(cert, NULL);
  12979. tmp_buf = (ilen > 0)
  12980. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  12981. conn->phys_ctx)
  12982. : NULL;
  12983. if (tmp_buf) {
  12984. tmp_p = tmp_buf;
  12985. (void)i2d_X509(cert, &tmp_p);
  12986. if (!EVP_Digest(
  12987. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12988. ulen = 0;
  12989. }
  12990. mg_free(tmp_buf);
  12991. }
  12992. if (!hexdump2string(
  12993. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12994. *str_finger = 0;
  12995. }
  12996. conn->request_info.client_cert = (struct mg_client_cert *)
  12997. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  12998. if (conn->request_info.client_cert) {
  12999. conn->request_info.client_cert->peer_cert = (void *)cert;
  13000. conn->request_info.client_cert->subject =
  13001. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13002. conn->request_info.client_cert->issuer =
  13003. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13004. conn->request_info.client_cert->serial =
  13005. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13006. conn->request_info.client_cert->finger =
  13007. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13008. } else {
  13009. mg_cry_internal(conn,
  13010. "%s",
  13011. "Out of memory: Cannot allocate memory for client "
  13012. "certificate");
  13013. }
  13014. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13015. * see https://linux.die.net/man/3/bn_bn2hex */
  13016. OPENSSL_free(str_serial);
  13017. }
  13018. }
  13019. #if defined(OPENSSL_API_1_1)
  13020. #else
  13021. static void
  13022. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13023. {
  13024. (void)line;
  13025. (void)file;
  13026. if (mode & 1) {
  13027. /* 1 is CRYPTO_LOCK */
  13028. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13029. } else {
  13030. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13031. }
  13032. }
  13033. #endif /* OPENSSL_API_1_1 */
  13034. #if !defined(NO_SSL_DL)
  13035. static void *
  13036. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13037. {
  13038. union {
  13039. void *p;
  13040. void (*fp)(void);
  13041. } u;
  13042. void *dll_handle;
  13043. struct ssl_func *fp;
  13044. int ok;
  13045. int truncated = 0;
  13046. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13047. mg_snprintf(NULL,
  13048. NULL, /* No truncation check for ebuf */
  13049. ebuf,
  13050. ebuf_len,
  13051. "%s: cannot load %s",
  13052. __func__,
  13053. dll_name);
  13054. return NULL;
  13055. }
  13056. ok = 1;
  13057. for (fp = sw; fp->name != NULL; fp++) {
  13058. #if defined(_WIN32)
  13059. /* GetProcAddress() returns pointer to function */
  13060. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13061. #else
  13062. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13063. * pointers to function pointers. We need to use a union to make a
  13064. * cast. */
  13065. u.p = dlsym(dll_handle, fp->name);
  13066. #endif /* _WIN32 */
  13067. if (u.fp == NULL) {
  13068. if (ok) {
  13069. mg_snprintf(NULL,
  13070. &truncated,
  13071. ebuf,
  13072. ebuf_len,
  13073. "%s: %s: cannot find %s",
  13074. __func__,
  13075. dll_name,
  13076. fp->name);
  13077. ok = 0;
  13078. } else {
  13079. size_t cur_len = strlen(ebuf);
  13080. if (!truncated) {
  13081. mg_snprintf(NULL,
  13082. &truncated,
  13083. ebuf + cur_len,
  13084. ebuf_len - cur_len - 3,
  13085. ", %s",
  13086. fp->name);
  13087. if (truncated) {
  13088. /* If truncated, add "..." */
  13089. strcat(ebuf, "...");
  13090. }
  13091. }
  13092. }
  13093. /* Debug:
  13094. * printf("Missing function: %s\n", fp->name); */
  13095. } else {
  13096. fp->ptr = u.fp;
  13097. }
  13098. }
  13099. if (!ok) {
  13100. (void)dlclose(dll_handle);
  13101. return NULL;
  13102. }
  13103. return dll_handle;
  13104. }
  13105. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13106. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13107. #endif /* NO_SSL_DL */
  13108. #if defined(SSL_ALREADY_INITIALIZED)
  13109. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13110. #else
  13111. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13112. #endif
  13113. static int
  13114. initialize_ssl(char *ebuf, size_t ebuf_len)
  13115. {
  13116. #if defined(OPENSSL_API_1_1)
  13117. if (ebuf_len > 0) {
  13118. ebuf[0] = 0;
  13119. }
  13120. #if !defined(NO_SSL_DL)
  13121. if (!cryptolib_dll_handle) {
  13122. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13123. if (!cryptolib_dll_handle) {
  13124. mg_snprintf(NULL,
  13125. NULL, /* No truncation check for ebuf */
  13126. ebuf,
  13127. ebuf_len,
  13128. "%s: error loading library %s",
  13129. __func__,
  13130. CRYPTO_LIB);
  13131. DEBUG_TRACE("%s", ebuf);
  13132. return 0;
  13133. }
  13134. }
  13135. #endif /* NO_SSL_DL */
  13136. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13137. return 1;
  13138. }
  13139. #else /* not OPENSSL_API_1_1 */
  13140. int i, num_locks;
  13141. size_t size;
  13142. if (ebuf_len > 0) {
  13143. ebuf[0] = 0;
  13144. }
  13145. #if !defined(NO_SSL_DL)
  13146. if (!cryptolib_dll_handle) {
  13147. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13148. if (!cryptolib_dll_handle) {
  13149. mg_snprintf(NULL,
  13150. NULL, /* No truncation check for ebuf */
  13151. ebuf,
  13152. ebuf_len,
  13153. "%s: error loading library %s",
  13154. __func__,
  13155. CRYPTO_LIB);
  13156. DEBUG_TRACE("%s", ebuf);
  13157. return 0;
  13158. }
  13159. }
  13160. #endif /* NO_SSL_DL */
  13161. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13162. return 1;
  13163. }
  13164. /* Initialize locking callbacks, needed for thread safety.
  13165. * http://www.openssl.org/support/faq.html#PROG1
  13166. */
  13167. num_locks = CRYPTO_num_locks();
  13168. if (num_locks < 0) {
  13169. num_locks = 0;
  13170. }
  13171. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13172. /* allocate mutex array, if required */
  13173. if (num_locks == 0) {
  13174. /* No mutex array required */
  13175. ssl_mutexes = NULL;
  13176. } else {
  13177. /* Mutex array required - allocate it */
  13178. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13179. /* Check OOM */
  13180. if (ssl_mutexes == NULL) {
  13181. mg_snprintf(NULL,
  13182. NULL, /* No truncation check for ebuf */
  13183. ebuf,
  13184. ebuf_len,
  13185. "%s: cannot allocate mutexes: %s",
  13186. __func__,
  13187. ssl_error());
  13188. DEBUG_TRACE("%s", ebuf);
  13189. return 0;
  13190. }
  13191. /* initialize mutex array */
  13192. for (i = 0; i < num_locks; i++) {
  13193. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13194. mg_snprintf(NULL,
  13195. NULL, /* No truncation check for ebuf */
  13196. ebuf,
  13197. ebuf_len,
  13198. "%s: error initializing mutex %i of %i",
  13199. __func__,
  13200. i,
  13201. num_locks);
  13202. DEBUG_TRACE("%s", ebuf);
  13203. mg_free(ssl_mutexes);
  13204. return 0;
  13205. }
  13206. }
  13207. }
  13208. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13209. CRYPTO_set_id_callback(&mg_current_thread_id);
  13210. #endif /* OPENSSL_API_1_1 */
  13211. #if !defined(NO_SSL_DL)
  13212. if (!ssllib_dll_handle) {
  13213. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13214. if (!ssllib_dll_handle) {
  13215. #if !defined(OPENSSL_API_1_1)
  13216. mg_free(ssl_mutexes);
  13217. #endif
  13218. DEBUG_TRACE("%s", ebuf);
  13219. return 0;
  13220. }
  13221. }
  13222. #endif /* NO_SSL_DL */
  13223. #if defined(OPENSSL_API_1_1)
  13224. /* Initialize SSL library */
  13225. OPENSSL_init_ssl(0, NULL);
  13226. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13227. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13228. NULL);
  13229. #else
  13230. /* Initialize SSL library */
  13231. SSL_library_init();
  13232. SSL_load_error_strings();
  13233. #endif
  13234. return 1;
  13235. }
  13236. static int
  13237. ssl_use_pem_file(struct mg_context *phys_ctx,
  13238. struct mg_domain_context *dom_ctx,
  13239. const char *pem,
  13240. const char *chain)
  13241. {
  13242. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13243. mg_cry_internal(fc(phys_ctx),
  13244. "%s: cannot open certificate file %s: %s",
  13245. __func__,
  13246. pem,
  13247. ssl_error());
  13248. return 0;
  13249. }
  13250. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13251. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13252. mg_cry_internal(fc(phys_ctx),
  13253. "%s: cannot open private key file %s: %s",
  13254. __func__,
  13255. pem,
  13256. ssl_error());
  13257. return 0;
  13258. }
  13259. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13260. mg_cry_internal(fc(phys_ctx),
  13261. "%s: certificate and private key do not match: %s",
  13262. __func__,
  13263. pem);
  13264. return 0;
  13265. }
  13266. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13267. * chain files that contain private keys and certificates in
  13268. * SSL_CTX_use_certificate_chain_file.
  13269. * The CivetWeb-Server used pem-Files that contained both information.
  13270. * In order to make wolfSSL work, it is split in two files.
  13271. * One file that contains key and certificate used by the server and
  13272. * an optional chain file for the ssl stack.
  13273. */
  13274. if (chain) {
  13275. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13276. mg_cry_internal(fc(phys_ctx),
  13277. "%s: cannot use certificate chain file %s: %s",
  13278. __func__,
  13279. pem,
  13280. ssl_error());
  13281. return 0;
  13282. }
  13283. }
  13284. return 1;
  13285. }
  13286. #if defined(OPENSSL_API_1_1)
  13287. static unsigned long
  13288. ssl_get_protocol(int version_id)
  13289. {
  13290. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13291. if (version_id > 0)
  13292. ret |= SSL_OP_NO_SSLv2;
  13293. if (version_id > 1)
  13294. ret |= SSL_OP_NO_SSLv3;
  13295. if (version_id > 2)
  13296. ret |= SSL_OP_NO_TLSv1;
  13297. if (version_id > 3)
  13298. ret |= SSL_OP_NO_TLSv1_1;
  13299. return ret;
  13300. }
  13301. #else
  13302. static long
  13303. ssl_get_protocol(int version_id)
  13304. {
  13305. long ret = (long)SSL_OP_ALL;
  13306. if (version_id > 0)
  13307. ret |= SSL_OP_NO_SSLv2;
  13308. if (version_id > 1)
  13309. ret |= SSL_OP_NO_SSLv3;
  13310. if (version_id > 2)
  13311. ret |= SSL_OP_NO_TLSv1;
  13312. if (version_id > 3)
  13313. ret |= SSL_OP_NO_TLSv1_1;
  13314. return ret;
  13315. }
  13316. #endif /* OPENSSL_API_1_1 */
  13317. /* SSL callback documentation:
  13318. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13319. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13320. * https://linux.die.net/man/3/ssl_set_info_callback */
  13321. /* Note: There is no "const" for the first argument in the documentation,
  13322. * however some (maybe most, but not all) headers of OpenSSL versions /
  13323. * OpenSSL compatibility layers have it. Having a different definition
  13324. * will cause a warning in C and an error in C++. With inconsitent
  13325. * definitions of this function, having a warning in one version or
  13326. * another is unavoidable. */
  13327. static void
  13328. ssl_info_callback(SSL *ssl, int what, int ret)
  13329. {
  13330. (void)ret;
  13331. if (what & SSL_CB_HANDSHAKE_START) {
  13332. SSL_get_app_data(ssl);
  13333. }
  13334. if (what & SSL_CB_HANDSHAKE_DONE) {
  13335. /* TODO: check for openSSL 1.1 */
  13336. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13337. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13338. }
  13339. }
  13340. static int
  13341. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13342. {
  13343. struct mg_context *ctx = (struct mg_context *)arg;
  13344. struct mg_domain_context *dom =
  13345. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13346. #if defined(__GNUC__) || defined(__MINGW32__)
  13347. #pragma GCC diagnostic push
  13348. #pragma GCC diagnostic ignored "-Wcast-align"
  13349. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13350. /* We used an aligned pointer in SSL_set_app_data */
  13351. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13352. #if defined(__GNUC__) || defined(__MINGW32__)
  13353. #pragma GCC diagnostic pop
  13354. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13355. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13356. (void)ad;
  13357. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13358. DEBUG_TRACE("%s", "internal error - assertion failed");
  13359. return SSL_TLSEXT_ERR_NOACK;
  13360. }
  13361. /* Old clients (Win XP) will not support SNI. Then, there
  13362. * is no server name available in the request - we can
  13363. * only work with the default certificate.
  13364. * Multiple HTTPS hosts on one IP+port are only possible
  13365. * with a certificate containing all alternative names.
  13366. */
  13367. if ((servername == NULL) || (*servername == 0)) {
  13368. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13369. conn->dom_ctx = &(ctx->dd);
  13370. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13371. return SSL_TLSEXT_ERR_NOACK;
  13372. }
  13373. DEBUG_TRACE("TLS connection to host %s", servername);
  13374. while (dom) {
  13375. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13376. /* Found matching domain */
  13377. DEBUG_TRACE("TLS domain %s found",
  13378. dom->config[AUTHENTICATION_DOMAIN]);
  13379. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13380. conn->dom_ctx = dom;
  13381. return SSL_TLSEXT_ERR_OK;
  13382. }
  13383. dom = dom->next;
  13384. }
  13385. /* Default domain */
  13386. DEBUG_TRACE("TLS default domain %s used",
  13387. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13388. conn->dom_ctx = &(ctx->dd);
  13389. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13390. return SSL_TLSEXT_ERR_OK;
  13391. }
  13392. /* Setup SSL CTX as required by CivetWeb */
  13393. static int
  13394. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13395. struct mg_domain_context *dom_ctx,
  13396. const char *pem,
  13397. const char *chain)
  13398. {
  13399. int callback_ret;
  13400. int should_verify_peer;
  13401. int peer_certificate_optional;
  13402. const char *ca_path;
  13403. const char *ca_file;
  13404. int use_default_verify_paths;
  13405. int verify_depth;
  13406. struct timespec now_mt;
  13407. md5_byte_t ssl_context_id[16];
  13408. md5_state_t md5state;
  13409. int protocol_ver;
  13410. #if defined(OPENSSL_API_1_1)
  13411. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13412. mg_cry_internal(fc(phys_ctx),
  13413. "SSL_CTX_new (server) error: %s",
  13414. ssl_error());
  13415. return 0;
  13416. }
  13417. #else
  13418. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13419. mg_cry_internal(fc(phys_ctx),
  13420. "SSL_CTX_new (server) error: %s",
  13421. ssl_error());
  13422. return 0;
  13423. }
  13424. #endif /* OPENSSL_API_1_1 */
  13425. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13426. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13427. | SSL_OP_NO_TLSv1_1);
  13428. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13429. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13430. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13431. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13432. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13433. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13434. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13435. #if !defined(NO_SSL_DL)
  13436. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13437. #endif /* NO_SSL_DL */
  13438. #if defined(__clang__)
  13439. #pragma clang diagnostic push
  13440. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  13441. #endif
  13442. #if defined(__GNUC__) || defined(__MINGW32__)
  13443. #pragma GCC diagnostic push
  13444. #pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
  13445. #endif
  13446. /* Depending on the OpenSSL version, the callback may be
  13447. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  13448. * yielding in an "incompatible-pointer-type" warning for the other
  13449. * version. It seems to be "unclear" what is correct:
  13450. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13451. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13452. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13453. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13454. * Disable this warning here.
  13455. * Alternative would be a version dependent ssl_info_callback and
  13456. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  13457. */
  13458. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13459. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13460. ssl_servername_callback);
  13461. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13462. #if defined(__GNUC__) || defined(__MINGW32__)
  13463. #pragma GCC diagnostic pop
  13464. #endif
  13465. #if defined(__clang__)
  13466. #pragma clang diagnostic pop
  13467. #endif
  13468. /* If a callback has been specified, call it. */
  13469. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13470. ? 0
  13471. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13472. phys_ctx->user_data));
  13473. /* If callback returns 0, civetweb sets up the SSL certificate.
  13474. * If it returns 1, civetweb assumes the calback already did this.
  13475. * If it returns -1, initializing ssl fails. */
  13476. if (callback_ret < 0) {
  13477. mg_cry_internal(fc(phys_ctx),
  13478. "SSL callback returned error: %i",
  13479. callback_ret);
  13480. return 0;
  13481. }
  13482. if (callback_ret > 0) {
  13483. /* Callback did everything. */
  13484. return 1;
  13485. }
  13486. /* Use some combination of start time, domain and port as a SSL
  13487. * context ID. This should be unique on the current machine. */
  13488. md5_init(&md5state);
  13489. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13490. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13491. md5_append(&md5state,
  13492. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13493. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13494. md5_append(&md5state,
  13495. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13496. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13497. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13498. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13499. md5_finish(&md5state, ssl_context_id);
  13500. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13501. (unsigned char *)ssl_context_id,
  13502. sizeof(ssl_context_id));
  13503. if (pem != NULL) {
  13504. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13505. return 0;
  13506. }
  13507. }
  13508. /* Should we support client certificates? */
  13509. /* Default is "no". */
  13510. should_verify_peer = 0;
  13511. peer_certificate_optional = 0;
  13512. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13513. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13514. /* Yes, they are mandatory */
  13515. should_verify_peer = 1;
  13516. peer_certificate_optional = 0;
  13517. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13518. "optional") == 0) {
  13519. /* Yes, they are optional */
  13520. should_verify_peer = 1;
  13521. peer_certificate_optional = 1;
  13522. }
  13523. }
  13524. use_default_verify_paths =
  13525. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13526. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13527. == 0);
  13528. if (should_verify_peer) {
  13529. ca_path = dom_ctx->config[SSL_CA_PATH];
  13530. ca_file = dom_ctx->config[SSL_CA_FILE];
  13531. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13532. != 1) {
  13533. mg_cry_internal(fc(phys_ctx),
  13534. "SSL_CTX_load_verify_locations error: %s "
  13535. "ssl_verify_peer requires setting "
  13536. "either ssl_ca_path or ssl_ca_file. "
  13537. "Is any of them present in the "
  13538. ".conf file?",
  13539. ssl_error());
  13540. return 0;
  13541. }
  13542. if (peer_certificate_optional) {
  13543. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13544. } else {
  13545. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13546. SSL_VERIFY_PEER
  13547. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13548. NULL);
  13549. }
  13550. if (use_default_verify_paths
  13551. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13552. mg_cry_internal(fc(phys_ctx),
  13553. "SSL_CTX_set_default_verify_paths error: %s",
  13554. ssl_error());
  13555. return 0;
  13556. }
  13557. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13558. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13559. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13560. }
  13561. }
  13562. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13563. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13564. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  13565. mg_cry_internal(fc(phys_ctx),
  13566. "SSL_CTX_set_cipher_list error: %s",
  13567. ssl_error());
  13568. }
  13569. }
  13570. return 1;
  13571. }
  13572. /* Check if SSL is required.
  13573. * If so, dynamically load SSL library
  13574. * and set up ctx->ssl_ctx pointer. */
  13575. static int
  13576. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13577. {
  13578. void *ssl_ctx = 0;
  13579. int callback_ret;
  13580. const char *pem;
  13581. const char *chain;
  13582. char ebuf[128];
  13583. if (!phys_ctx) {
  13584. return 0;
  13585. }
  13586. if (!dom_ctx) {
  13587. dom_ctx = &(phys_ctx->dd);
  13588. }
  13589. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13590. /* No SSL port is set. No need to setup SSL. */
  13591. return 1;
  13592. }
  13593. /* Check for external SSL_CTX */
  13594. callback_ret =
  13595. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13596. ? 0
  13597. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13598. phys_ctx->user_data));
  13599. if (callback_ret < 0) {
  13600. mg_cry_internal(fc(phys_ctx),
  13601. "external_ssl_ctx callback returned error: %i",
  13602. callback_ret);
  13603. return 0;
  13604. } else if (callback_ret > 0) {
  13605. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13606. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13607. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13608. return 0;
  13609. }
  13610. return 1;
  13611. }
  13612. /* else: external_ssl_ctx does not exist or returns 0,
  13613. * CivetWeb should continue initializing SSL */
  13614. /* If PEM file is not specified and the init_ssl callback
  13615. * is not specified, setup will fail. */
  13616. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13617. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13618. /* No certificate and no callback:
  13619. * Essential data to set up TLS is missing.
  13620. */
  13621. mg_cry_internal(fc(phys_ctx),
  13622. "Initializing SSL failed: -%s is not set",
  13623. config_options[SSL_CERTIFICATE].name);
  13624. return 0;
  13625. }
  13626. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13627. if (chain == NULL) {
  13628. chain = pem;
  13629. }
  13630. if ((chain != NULL) && (*chain == 0)) {
  13631. chain = NULL;
  13632. }
  13633. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13634. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13635. return 0;
  13636. }
  13637. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13638. }
  13639. static void
  13640. uninitialize_ssl(void)
  13641. {
  13642. #if defined(OPENSSL_API_1_1)
  13643. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13644. /* Shutdown according to
  13645. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13646. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13647. */
  13648. CONF_modules_unload(1);
  13649. #else
  13650. int i;
  13651. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13652. /* Shutdown according to
  13653. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13654. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13655. */
  13656. CRYPTO_set_locking_callback(NULL);
  13657. CRYPTO_set_id_callback(NULL);
  13658. ENGINE_cleanup();
  13659. CONF_modules_unload(1);
  13660. ERR_free_strings();
  13661. EVP_cleanup();
  13662. CRYPTO_cleanup_all_ex_data();
  13663. ERR_remove_state(0);
  13664. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13665. pthread_mutex_destroy(&ssl_mutexes[i]);
  13666. }
  13667. mg_free(ssl_mutexes);
  13668. ssl_mutexes = NULL;
  13669. #endif /* OPENSSL_API_1_1 */
  13670. }
  13671. }
  13672. #endif /* !NO_SSL */
  13673. static int
  13674. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13675. {
  13676. if (phys_ctx) {
  13677. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13678. const char *path;
  13679. if (!dom_ctx) {
  13680. dom_ctx = &(phys_ctx->dd);
  13681. }
  13682. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13683. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13684. mg_cry_internal(fc(phys_ctx),
  13685. "Cannot open %s: %s",
  13686. path,
  13687. strerror(ERRNO));
  13688. return 0;
  13689. }
  13690. return 1;
  13691. }
  13692. return 0;
  13693. }
  13694. static int
  13695. set_acl_option(struct mg_context *phys_ctx)
  13696. {
  13697. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13698. }
  13699. static void
  13700. reset_per_request_attributes(struct mg_connection *conn)
  13701. {
  13702. if (!conn) {
  13703. return;
  13704. }
  13705. conn->connection_type =
  13706. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13707. conn->num_bytes_sent = conn->consumed_content = 0;
  13708. conn->path_info = NULL;
  13709. conn->status_code = -1;
  13710. conn->content_len = -1;
  13711. conn->is_chunked = 0;
  13712. conn->must_close = 0;
  13713. conn->request_len = 0;
  13714. conn->throttle = 0;
  13715. conn->data_len = 0;
  13716. conn->chunk_remainder = 0;
  13717. conn->accept_gzip = 0;
  13718. conn->response_info.content_length = conn->request_info.content_length = -1;
  13719. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13720. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13721. conn->response_info.status_text = NULL;
  13722. conn->response_info.status_code = 0;
  13723. conn->request_info.remote_user = NULL;
  13724. conn->request_info.request_method = NULL;
  13725. conn->request_info.request_uri = NULL;
  13726. conn->request_info.local_uri = NULL;
  13727. #if defined(MG_LEGACY_INTERFACE)
  13728. /* Legacy before split into local_uri and request_uri */
  13729. conn->request_info.uri = NULL;
  13730. #endif
  13731. }
  13732. #if 0
  13733. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13734. * Leave this function here (commented out) for reference until
  13735. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13736. * no longer required.
  13737. */
  13738. static int
  13739. set_sock_timeout(SOCKET sock, int milliseconds)
  13740. {
  13741. int r0 = 0, r1, r2;
  13742. #if defined(_WIN32)
  13743. /* Windows specific */
  13744. DWORD tv = (DWORD)milliseconds;
  13745. #else
  13746. /* Linux, ... (not Windows) */
  13747. struct timeval tv;
  13748. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13749. * max. time waiting for the acknowledged of TCP data before the connection
  13750. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13751. * If this option is not set, the default timeout of 20-30 minutes is used.
  13752. */
  13753. /* #define TCP_USER_TIMEOUT (18) */
  13754. #if defined(TCP_USER_TIMEOUT)
  13755. unsigned int uto = (unsigned int)milliseconds;
  13756. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13757. #endif
  13758. memset(&tv, 0, sizeof(tv));
  13759. tv.tv_sec = milliseconds / 1000;
  13760. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13761. #endif /* _WIN32 */
  13762. r1 = setsockopt(
  13763. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13764. r2 = setsockopt(
  13765. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13766. return r0 || r1 || r2;
  13767. }
  13768. #endif
  13769. static int
  13770. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13771. {
  13772. if (setsockopt(sock,
  13773. IPPROTO_TCP,
  13774. TCP_NODELAY,
  13775. (SOCK_OPT_TYPE)&nodelay_on,
  13776. sizeof(nodelay_on)) != 0) {
  13777. /* Error */
  13778. return 1;
  13779. }
  13780. /* OK */
  13781. return 0;
  13782. }
  13783. static void
  13784. close_socket_gracefully(struct mg_connection *conn)
  13785. {
  13786. #if defined(_WIN32)
  13787. char buf[MG_BUF_LEN];
  13788. int n;
  13789. #endif
  13790. struct linger linger;
  13791. int error_code = 0;
  13792. int linger_timeout = -2;
  13793. socklen_t opt_len = sizeof(error_code);
  13794. if (!conn) {
  13795. return;
  13796. }
  13797. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13798. * "Note that enabling a nonzero timeout on a nonblocking socket
  13799. * is not recommended.", so set it to blocking now */
  13800. set_blocking_mode(conn->client.sock);
  13801. /* Send FIN to the client */
  13802. shutdown(conn->client.sock, SHUTDOWN_WR);
  13803. #if defined(_WIN32)
  13804. /* Read and discard pending incoming data. If we do not do that and
  13805. * close
  13806. * the socket, the data in the send buffer may be discarded. This
  13807. * behaviour is seen on Windows, when client keeps sending data
  13808. * when server decides to close the connection; then when client
  13809. * does recv() it gets no data back. */
  13810. do {
  13811. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13812. } while (n > 0);
  13813. #endif
  13814. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13815. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13816. }
  13817. /* Set linger option according to configuration */
  13818. if (linger_timeout >= 0) {
  13819. /* Set linger option to avoid socket hanging out after close. This
  13820. * prevent ephemeral port exhaust problem under high QPS. */
  13821. linger.l_onoff = 1;
  13822. #if defined(_MSC_VER)
  13823. #pragma warning(push)
  13824. #pragma warning(disable : 4244)
  13825. #endif
  13826. #if defined(__GNUC__) || defined(__MINGW32__)
  13827. #pragma GCC diagnostic push
  13828. #pragma GCC diagnostic ignored "-Wconversion"
  13829. #endif
  13830. /* Data type of linger structure elements may differ,
  13831. * so we don't know what cast we need here.
  13832. * Disable type conversion warnings. */
  13833. linger.l_linger = (linger_timeout + 999) / 1000;
  13834. #if defined(__GNUC__) || defined(__MINGW32__)
  13835. #pragma GCC diagnostic pop
  13836. #endif
  13837. #if defined(_MSC_VER)
  13838. #pragma warning(pop)
  13839. #endif
  13840. } else {
  13841. linger.l_onoff = 0;
  13842. linger.l_linger = 0;
  13843. }
  13844. if (linger_timeout < -1) {
  13845. /* Default: don't configure any linger */
  13846. } else if (getsockopt(conn->client.sock,
  13847. SOL_SOCKET,
  13848. SO_ERROR,
  13849. #if defined(_WIN32) /* WinSock uses different data type here */
  13850. (char *)&error_code,
  13851. #else
  13852. &error_code,
  13853. #endif
  13854. &opt_len) != 0) {
  13855. /* Cannot determine if socket is already closed. This should
  13856. * not occur and never did in a test. Log an error message
  13857. * and continue. */
  13858. mg_cry_internal(conn,
  13859. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13860. __func__,
  13861. strerror(ERRNO));
  13862. } else if (error_code == ECONNRESET) {
  13863. /* Socket already closed by client/peer, close socket without linger
  13864. */
  13865. } else {
  13866. /* Set linger timeout */
  13867. if (setsockopt(conn->client.sock,
  13868. SOL_SOCKET,
  13869. SO_LINGER,
  13870. (char *)&linger,
  13871. sizeof(linger)) != 0) {
  13872. mg_cry_internal(
  13873. conn,
  13874. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13875. __func__,
  13876. linger.l_onoff,
  13877. linger.l_linger,
  13878. strerror(ERRNO));
  13879. }
  13880. }
  13881. /* Now we know that our FIN is ACK-ed, safe to close */
  13882. closesocket(conn->client.sock);
  13883. conn->client.sock = INVALID_SOCKET;
  13884. }
  13885. static void
  13886. close_connection(struct mg_connection *conn)
  13887. {
  13888. #if defined(USE_SERVER_STATS)
  13889. conn->conn_state = 6; /* to close */
  13890. #endif
  13891. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13892. if (conn->lua_websocket_state) {
  13893. lua_websocket_close(conn, conn->lua_websocket_state);
  13894. conn->lua_websocket_state = NULL;
  13895. }
  13896. #endif
  13897. mg_lock_connection(conn);
  13898. /* Set close flag, so keep-alive loops will stop */
  13899. conn->must_close = 1;
  13900. /* call the connection_close callback if assigned */
  13901. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13902. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13903. conn->phys_ctx->callbacks.connection_close(conn);
  13904. }
  13905. }
  13906. /* Reset user data, after close callback is called.
  13907. * Do not reuse it. If the user needs a destructor,
  13908. * it must be done in the connection_close callback. */
  13909. mg_set_user_connection_data(conn, NULL);
  13910. #if defined(USE_SERVER_STATS)
  13911. conn->conn_state = 7; /* closing */
  13912. #endif
  13913. #if !defined(NO_SSL)
  13914. if (conn->ssl != NULL) {
  13915. /* Run SSL_shutdown twice to ensure completely close SSL connection
  13916. */
  13917. SSL_shutdown(conn->ssl);
  13918. SSL_free(conn->ssl);
  13919. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13920. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13921. #if !defined(OPENSSL_API_1_1)
  13922. ERR_remove_state(0);
  13923. #endif
  13924. conn->ssl = NULL;
  13925. }
  13926. #endif
  13927. if (conn->client.sock != INVALID_SOCKET) {
  13928. close_socket_gracefully(conn);
  13929. conn->client.sock = INVALID_SOCKET;
  13930. }
  13931. if (conn->host) {
  13932. mg_free((void *)conn->host);
  13933. conn->host = NULL;
  13934. }
  13935. mg_unlock_connection(conn);
  13936. #if defined(USE_SERVER_STATS)
  13937. conn->conn_state = 8; /* closed */
  13938. #endif
  13939. }
  13940. void
  13941. mg_close_connection(struct mg_connection *conn)
  13942. {
  13943. #if defined(USE_WEBSOCKET)
  13944. struct mg_context *client_ctx = NULL;
  13945. #endif /* defined(USE_WEBSOCKET) */
  13946. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13947. return;
  13948. }
  13949. #if defined(USE_WEBSOCKET)
  13950. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13951. if (conn->in_websocket_handling) {
  13952. /* Set close flag, so the server thread can exit. */
  13953. conn->must_close = 1;
  13954. return;
  13955. }
  13956. }
  13957. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  13958. unsigned int i;
  13959. /* ws/wss client */
  13960. client_ctx = conn->phys_ctx;
  13961. /* client context: loops must end */
  13962. client_ctx->stop_flag = 1;
  13963. conn->must_close = 1;
  13964. /* We need to get the client thread out of the select/recv call
  13965. * here. */
  13966. /* Since we use a sleep quantum of some seconds to check for recv
  13967. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13968. /* join worker thread */
  13969. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13970. if (client_ctx->worker_threadids[i] != 0) {
  13971. mg_join_thread(client_ctx->worker_threadids[i]);
  13972. }
  13973. }
  13974. }
  13975. #endif /* defined(USE_WEBSOCKET) */
  13976. close_connection(conn);
  13977. #if !defined(NO_SSL)
  13978. if (conn->client_ssl_ctx != NULL) {
  13979. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13980. }
  13981. #endif
  13982. #if defined(USE_WEBSOCKET)
  13983. if (client_ctx != NULL) {
  13984. /* free context */
  13985. mg_free(client_ctx->worker_threadids);
  13986. mg_free(client_ctx);
  13987. (void)pthread_mutex_destroy(&conn->mutex);
  13988. mg_free(conn);
  13989. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13990. mg_free(conn);
  13991. }
  13992. #else
  13993. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13994. mg_free(conn);
  13995. }
  13996. #endif /* defined(USE_WEBSOCKET) */
  13997. }
  13998. /* Only for memory statistics */
  13999. static struct mg_context common_client_context;
  14000. static struct mg_connection *
  14001. mg_connect_client_impl(const struct mg_client_options *client_options,
  14002. int use_ssl,
  14003. char *ebuf,
  14004. size_t ebuf_len)
  14005. {
  14006. struct mg_connection *conn = NULL;
  14007. SOCKET sock;
  14008. union usa sa;
  14009. struct sockaddr *psa;
  14010. socklen_t len;
  14011. unsigned max_req_size =
  14012. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14013. /* Size of structures, aligned to 8 bytes */
  14014. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14015. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14016. conn = (struct mg_connection *)mg_calloc_ctx(1,
  14017. conn_size + ctx_size
  14018. + max_req_size,
  14019. &common_client_context);
  14020. if (conn == NULL) {
  14021. mg_snprintf(NULL,
  14022. NULL, /* No truncation check for ebuf */
  14023. ebuf,
  14024. ebuf_len,
  14025. "calloc(): %s",
  14026. strerror(ERRNO));
  14027. return NULL;
  14028. }
  14029. #if defined(__GNUC__) || defined(__MINGW32__)
  14030. #pragma GCC diagnostic push
  14031. #pragma GCC diagnostic ignored "-Wcast-align"
  14032. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  14033. /* conn_size is aligned to 8 bytes */
  14034. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14035. #if defined(__GNUC__) || defined(__MINGW32__)
  14036. #pragma GCC diagnostic pop
  14037. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  14038. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14039. conn->buf_size = (int)max_req_size;
  14040. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14041. conn->dom_ctx = &(conn->phys_ctx->dd);
  14042. if (!connect_socket(&common_client_context,
  14043. client_options->host,
  14044. client_options->port,
  14045. use_ssl,
  14046. ebuf,
  14047. ebuf_len,
  14048. &sock,
  14049. &sa)) {
  14050. /* ebuf is set by connect_socket,
  14051. * free all memory and return NULL; */
  14052. mg_free(conn);
  14053. return NULL;
  14054. }
  14055. #if !defined(NO_SSL)
  14056. #if defined(OPENSSL_API_1_1)
  14057. if (use_ssl
  14058. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  14059. mg_snprintf(NULL,
  14060. NULL, /* No truncation check for ebuf */
  14061. ebuf,
  14062. ebuf_len,
  14063. "SSL_CTX_new error");
  14064. closesocket(sock);
  14065. mg_free(conn);
  14066. return NULL;
  14067. }
  14068. #else
  14069. if (use_ssl
  14070. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14071. == NULL) {
  14072. mg_snprintf(NULL,
  14073. NULL, /* No truncation check for ebuf */
  14074. ebuf,
  14075. ebuf_len,
  14076. "SSL_CTX_new error");
  14077. closesocket(sock);
  14078. mg_free(conn);
  14079. return NULL;
  14080. }
  14081. #endif /* OPENSSL_API_1_1 */
  14082. #endif /* NO_SSL */
  14083. #if defined(USE_IPV6)
  14084. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14085. : sizeof(conn->client.rsa.sin6);
  14086. psa = (sa.sa.sa_family == AF_INET)
  14087. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14088. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14089. #else
  14090. len = sizeof(conn->client.rsa.sin);
  14091. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14092. #endif
  14093. conn->client.sock = sock;
  14094. conn->client.lsa = sa;
  14095. if (getsockname(sock, psa, &len) != 0) {
  14096. mg_cry_internal(conn,
  14097. "%s: getsockname() failed: %s",
  14098. __func__,
  14099. strerror(ERRNO));
  14100. }
  14101. conn->client.is_ssl = use_ssl ? 1 : 0;
  14102. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14103. mg_snprintf(NULL,
  14104. NULL, /* No truncation check for ebuf */
  14105. ebuf,
  14106. ebuf_len,
  14107. "Can not create mutex");
  14108. #if !defined(NO_SSL)
  14109. SSL_CTX_free(conn->client_ssl_ctx);
  14110. #endif
  14111. closesocket(sock);
  14112. mg_free(conn);
  14113. return NULL;
  14114. }
  14115. #if !defined(NO_SSL)
  14116. if (use_ssl) {
  14117. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  14118. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14119. * SSL_CTX_set_verify call is needed to switch off server
  14120. * certificate checking, which is off by default in OpenSSL and
  14121. * on in yaSSL. */
  14122. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  14123. * SSL_VERIFY_PEER, verify_ssl_server); */
  14124. if (client_options->client_cert) {
  14125. if (!ssl_use_pem_file(&common_client_context,
  14126. &(common_client_context.dd),
  14127. client_options->client_cert,
  14128. NULL)) {
  14129. mg_snprintf(NULL,
  14130. NULL, /* No truncation check for ebuf */
  14131. ebuf,
  14132. ebuf_len,
  14133. "Can not use SSL client certificate");
  14134. SSL_CTX_free(conn->client_ssl_ctx);
  14135. closesocket(sock);
  14136. mg_free(conn);
  14137. return NULL;
  14138. }
  14139. }
  14140. if (client_options->server_cert) {
  14141. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  14142. client_options->server_cert,
  14143. NULL);
  14144. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  14145. } else {
  14146. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  14147. }
  14148. if (!sslize(conn,
  14149. conn->client_ssl_ctx,
  14150. SSL_connect,
  14151. &(conn->phys_ctx->stop_flag))) {
  14152. mg_snprintf(NULL,
  14153. NULL, /* No truncation check for ebuf */
  14154. ebuf,
  14155. ebuf_len,
  14156. "SSL connection error");
  14157. SSL_CTX_free(conn->client_ssl_ctx);
  14158. closesocket(sock);
  14159. mg_free(conn);
  14160. return NULL;
  14161. }
  14162. }
  14163. #endif
  14164. if (0 != set_non_blocking_mode(sock)) {
  14165. mg_cry_internal(conn,
  14166. "Cannot set non-blocking mode for client %s:%i",
  14167. client_options->host,
  14168. client_options->port);
  14169. }
  14170. return conn;
  14171. }
  14172. CIVETWEB_API struct mg_connection *
  14173. mg_connect_client_secure(const struct mg_client_options *client_options,
  14174. char *error_buffer,
  14175. size_t error_buffer_size)
  14176. {
  14177. return mg_connect_client_impl(client_options,
  14178. 1,
  14179. error_buffer,
  14180. error_buffer_size);
  14181. }
  14182. struct mg_connection *
  14183. mg_connect_client(const char *host,
  14184. int port,
  14185. int use_ssl,
  14186. char *error_buffer,
  14187. size_t error_buffer_size)
  14188. {
  14189. struct mg_client_options opts;
  14190. memset(&opts, 0, sizeof(opts));
  14191. opts.host = host;
  14192. opts.port = port;
  14193. return mg_connect_client_impl(&opts,
  14194. use_ssl,
  14195. error_buffer,
  14196. error_buffer_size);
  14197. }
  14198. static const struct {
  14199. const char *proto;
  14200. size_t proto_len;
  14201. unsigned default_port;
  14202. } abs_uri_protocols[] = {{"http://", 7, 80},
  14203. {"https://", 8, 443},
  14204. {"ws://", 5, 80},
  14205. {"wss://", 6, 443},
  14206. {NULL, 0, 0}};
  14207. /* Check if the uri is valid.
  14208. * return 0 for invalid uri,
  14209. * return 1 for *,
  14210. * return 2 for relative uri,
  14211. * return 3 for absolute uri without port,
  14212. * return 4 for absolute uri with port */
  14213. static int
  14214. get_uri_type(const char *uri)
  14215. {
  14216. int i;
  14217. const char *hostend, *portbegin;
  14218. char *portend;
  14219. unsigned long port;
  14220. /* According to the HTTP standard
  14221. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14222. * URI can be an asterisk (*) or should start with slash (relative uri),
  14223. * or it should start with the protocol (absolute uri). */
  14224. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14225. /* asterisk */
  14226. return 1;
  14227. }
  14228. /* Valid URIs according to RFC 3986
  14229. * (https://www.ietf.org/rfc/rfc3986.txt)
  14230. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14231. * and unreserved characters A-Z a-z 0-9 and -._~
  14232. * and % encoded symbols.
  14233. */
  14234. for (i = 0; uri[i] != 0; i++) {
  14235. if (uri[i] < 33) {
  14236. /* control characters and spaces are invalid */
  14237. return 0;
  14238. }
  14239. if (uri[i] > 126) {
  14240. /* non-ascii characters must be % encoded */
  14241. return 0;
  14242. } else {
  14243. switch (uri[i]) {
  14244. case '"': /* 34 */
  14245. case '<': /* 60 */
  14246. case '>': /* 62 */
  14247. case '\\': /* 92 */
  14248. case '^': /* 94 */
  14249. case '`': /* 96 */
  14250. case '{': /* 123 */
  14251. case '|': /* 124 */
  14252. case '}': /* 125 */
  14253. return 0;
  14254. default:
  14255. /* character is ok */
  14256. break;
  14257. }
  14258. }
  14259. }
  14260. /* A relative uri starts with a / character */
  14261. if (uri[0] == '/') {
  14262. /* relative uri */
  14263. return 2;
  14264. }
  14265. /* It could be an absolute uri: */
  14266. /* This function only checks if the uri is valid, not if it is
  14267. * addressing the current server. So civetweb can also be used
  14268. * as a proxy server. */
  14269. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14270. if (mg_strncasecmp(uri,
  14271. abs_uri_protocols[i].proto,
  14272. abs_uri_protocols[i].proto_len) == 0) {
  14273. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14274. if (!hostend) {
  14275. return 0;
  14276. }
  14277. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14278. if (!portbegin) {
  14279. return 3;
  14280. }
  14281. port = strtoul(portbegin + 1, &portend, 10);
  14282. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14283. return 0;
  14284. }
  14285. return 4;
  14286. }
  14287. }
  14288. return 0;
  14289. }
  14290. /* Return NULL or the relative uri at the current server */
  14291. static const char *
  14292. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14293. {
  14294. const char *server_domain;
  14295. size_t server_domain_len;
  14296. size_t request_domain_len = 0;
  14297. unsigned long port = 0;
  14298. int i, auth_domain_check_enabled;
  14299. const char *hostbegin = NULL;
  14300. const char *hostend = NULL;
  14301. const char *portbegin;
  14302. char *portend;
  14303. auth_domain_check_enabled =
  14304. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14305. /* DNS is case insensitive, so use case insensitive string compare here
  14306. */
  14307. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14308. if (mg_strncasecmp(uri,
  14309. abs_uri_protocols[i].proto,
  14310. abs_uri_protocols[i].proto_len) == 0) {
  14311. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14312. hostend = strchr(hostbegin, '/');
  14313. if (!hostend) {
  14314. return 0;
  14315. }
  14316. portbegin = strchr(hostbegin, ':');
  14317. if ((!portbegin) || (portbegin > hostend)) {
  14318. port = abs_uri_protocols[i].default_port;
  14319. request_domain_len = (size_t)(hostend - hostbegin);
  14320. } else {
  14321. port = strtoul(portbegin + 1, &portend, 10);
  14322. if ((portend != hostend) || (port <= 0)
  14323. || !is_valid_port(port)) {
  14324. return 0;
  14325. }
  14326. request_domain_len = (size_t)(portbegin - hostbegin);
  14327. }
  14328. /* protocol found, port set */
  14329. break;
  14330. }
  14331. }
  14332. if (!port) {
  14333. /* port remains 0 if the protocol is not found */
  14334. return 0;
  14335. }
  14336. /* Check if the request is directed to a different server. */
  14337. /* First check if the port is the same (IPv4 and IPv6). */
  14338. #if defined(USE_IPV6)
  14339. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14340. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14341. /* Request is directed to a different port */
  14342. return 0;
  14343. }
  14344. } else
  14345. #endif
  14346. {
  14347. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14348. /* Request is directed to a different port */
  14349. return 0;
  14350. }
  14351. }
  14352. /* Finally check if the server corresponds to the authentication
  14353. * domain of the server (the server domain).
  14354. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14355. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14356. * but do not allow substrings (like
  14357. * http://notmydomain.com/path/file.ext
  14358. * or http://mydomain.com.fake/path/file.ext).
  14359. */
  14360. if (auth_domain_check_enabled) {
  14361. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14362. server_domain_len = strlen(server_domain);
  14363. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14364. return 0;
  14365. }
  14366. if ((request_domain_len == server_domain_len)
  14367. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14368. /* Request is directed to this server - full name match. */
  14369. } else {
  14370. if (request_domain_len < (server_domain_len + 2)) {
  14371. /* Request is directed to another server: The server name
  14372. * is longer than the request name.
  14373. * Drop this case here to avoid overflows in the
  14374. * following checks. */
  14375. return 0;
  14376. }
  14377. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14378. /* Request is directed to another server: It could be a
  14379. * substring
  14380. * like notmyserver.com */
  14381. return 0;
  14382. }
  14383. if (0 != memcmp(server_domain,
  14384. hostbegin + request_domain_len - server_domain_len,
  14385. server_domain_len)) {
  14386. /* Request is directed to another server:
  14387. * The server name is different. */
  14388. return 0;
  14389. }
  14390. }
  14391. }
  14392. return hostend;
  14393. }
  14394. static int
  14395. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14396. {
  14397. if (ebuf_len > 0) {
  14398. ebuf[0] = '\0';
  14399. }
  14400. *err = 0;
  14401. reset_per_request_attributes(conn);
  14402. if (!conn) {
  14403. mg_snprintf(conn,
  14404. NULL, /* No truncation check for ebuf */
  14405. ebuf,
  14406. ebuf_len,
  14407. "%s",
  14408. "Internal error");
  14409. *err = 500;
  14410. return 0;
  14411. }
  14412. /* Set the time the request was received. This value should be used for
  14413. * timeouts. */
  14414. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14415. conn->request_len =
  14416. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14417. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14418. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14419. mg_snprintf(conn,
  14420. NULL, /* No truncation check for ebuf */
  14421. ebuf,
  14422. ebuf_len,
  14423. "%s",
  14424. "Invalid message size");
  14425. *err = 500;
  14426. return 0;
  14427. }
  14428. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14429. mg_snprintf(conn,
  14430. NULL, /* No truncation check for ebuf */
  14431. ebuf,
  14432. ebuf_len,
  14433. "%s",
  14434. "Message too large");
  14435. *err = 413;
  14436. return 0;
  14437. }
  14438. if (conn->request_len <= 0) {
  14439. if (conn->data_len > 0) {
  14440. mg_snprintf(conn,
  14441. NULL, /* No truncation check for ebuf */
  14442. ebuf,
  14443. ebuf_len,
  14444. "%s",
  14445. "Malformed message");
  14446. *err = 400;
  14447. } else {
  14448. /* Server did not recv anything -> just close the connection */
  14449. conn->must_close = 1;
  14450. mg_snprintf(conn,
  14451. NULL, /* No truncation check for ebuf */
  14452. ebuf,
  14453. ebuf_len,
  14454. "%s",
  14455. "No data received");
  14456. *err = 0;
  14457. }
  14458. return 0;
  14459. }
  14460. return 1;
  14461. }
  14462. static int
  14463. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14464. {
  14465. const char *cl;
  14466. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14467. return 0;
  14468. }
  14469. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14470. <= 0) {
  14471. mg_snprintf(conn,
  14472. NULL, /* No truncation check for ebuf */
  14473. ebuf,
  14474. ebuf_len,
  14475. "%s",
  14476. "Bad request");
  14477. *err = 400;
  14478. return 0;
  14479. }
  14480. /* Message is a valid request */
  14481. /* Is there a "host" ? */
  14482. conn->host = alloc_get_host(conn);
  14483. if (!conn->host) {
  14484. mg_snprintf(conn,
  14485. NULL, /* No truncation check for ebuf */
  14486. ebuf,
  14487. ebuf_len,
  14488. "%s",
  14489. "Bad request: Host mismatch");
  14490. *err = 400;
  14491. return 0;
  14492. }
  14493. /* Do we know the content length? */
  14494. if ((cl = get_header(conn->request_info.http_headers,
  14495. conn->request_info.num_headers,
  14496. "Content-Length")) != NULL) {
  14497. /* Request/response has content length set */
  14498. char *endptr = NULL;
  14499. conn->content_len = strtoll(cl, &endptr, 10);
  14500. if (endptr == cl) {
  14501. mg_snprintf(conn,
  14502. NULL, /* No truncation check for ebuf */
  14503. ebuf,
  14504. ebuf_len,
  14505. "%s",
  14506. "Bad request");
  14507. *err = 411;
  14508. return 0;
  14509. }
  14510. /* Publish the content length back to the request info. */
  14511. conn->request_info.content_length = conn->content_len;
  14512. } else if ((cl = get_header(conn->request_info.http_headers,
  14513. conn->request_info.num_headers,
  14514. "Transfer-Encoding")) != NULL
  14515. && !mg_strcasecmp(cl, "chunked")) {
  14516. conn->is_chunked = 1;
  14517. conn->content_len = -1; /* unknown content length */
  14518. } else {
  14519. const struct mg_http_method_info *meth =
  14520. get_http_method_info(conn->request_info.request_method);
  14521. if (!meth) {
  14522. /* No valid HTTP method */
  14523. mg_snprintf(conn,
  14524. NULL, /* No truncation check for ebuf */
  14525. ebuf,
  14526. ebuf_len,
  14527. "%s",
  14528. "Bad request");
  14529. *err = 411;
  14530. return 0;
  14531. }
  14532. if (meth->request_has_body) {
  14533. /* POST or PUT request without content length set */
  14534. conn->content_len = -1; /* unknown content length */
  14535. } else {
  14536. /* Other request */
  14537. conn->content_len = 0; /* No content */
  14538. }
  14539. }
  14540. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14541. return 1;
  14542. }
  14543. /* conn is assumed to be valid in this internal function */
  14544. static int
  14545. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14546. {
  14547. const char *cl;
  14548. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14549. return 0;
  14550. }
  14551. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14552. <= 0) {
  14553. mg_snprintf(conn,
  14554. NULL, /* No truncation check for ebuf */
  14555. ebuf,
  14556. ebuf_len,
  14557. "%s",
  14558. "Bad response");
  14559. *err = 400;
  14560. return 0;
  14561. }
  14562. /* Message is a valid response */
  14563. /* Do we know the content length? */
  14564. if ((cl = get_header(conn->response_info.http_headers,
  14565. conn->response_info.num_headers,
  14566. "Content-Length")) != NULL) {
  14567. /* Request/response has content length set */
  14568. char *endptr = NULL;
  14569. conn->content_len = strtoll(cl, &endptr, 10);
  14570. if (endptr == cl) {
  14571. mg_snprintf(conn,
  14572. NULL, /* No truncation check for ebuf */
  14573. ebuf,
  14574. ebuf_len,
  14575. "%s",
  14576. "Bad request");
  14577. *err = 411;
  14578. return 0;
  14579. }
  14580. /* Publish the content length back to the response info. */
  14581. conn->response_info.content_length = conn->content_len;
  14582. /* TODO: check if it is still used in response_info */
  14583. conn->request_info.content_length = conn->content_len;
  14584. } else if ((cl = get_header(conn->response_info.http_headers,
  14585. conn->response_info.num_headers,
  14586. "Transfer-Encoding")) != NULL
  14587. && !mg_strcasecmp(cl, "chunked")) {
  14588. conn->is_chunked = 1;
  14589. conn->content_len = -1; /* unknown content length */
  14590. } else {
  14591. conn->content_len = -1; /* unknown content length */
  14592. }
  14593. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14594. return 1;
  14595. }
  14596. int
  14597. mg_get_response(struct mg_connection *conn,
  14598. char *ebuf,
  14599. size_t ebuf_len,
  14600. int timeout)
  14601. {
  14602. int err, ret;
  14603. char txt[32]; /* will not overflow */
  14604. char *save_timeout;
  14605. char *new_timeout;
  14606. if (ebuf_len > 0) {
  14607. ebuf[0] = '\0';
  14608. }
  14609. if (!conn) {
  14610. mg_snprintf(conn,
  14611. NULL, /* No truncation check for ebuf */
  14612. ebuf,
  14613. ebuf_len,
  14614. "%s",
  14615. "Parameter error");
  14616. return -1;
  14617. }
  14618. /* Implementation of API function for HTTP clients */
  14619. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14620. if (timeout >= 0) {
  14621. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14622. new_timeout = txt;
  14623. /* Not required for non-blocking sockets.
  14624. set_sock_timeout(conn->client.sock, timeout);
  14625. */
  14626. } else {
  14627. new_timeout = NULL;
  14628. }
  14629. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14630. ret = get_response(conn, ebuf, ebuf_len, &err);
  14631. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14632. #if defined(MG_LEGACY_INTERFACE)
  14633. /* TODO: 1) uri is deprecated;
  14634. * 2) here, ri.uri is the http response code */
  14635. conn->request_info.uri = conn->request_info.request_uri;
  14636. #endif
  14637. conn->request_info.local_uri = conn->request_info.request_uri;
  14638. /* TODO (mid): Define proper return values - maybe return length?
  14639. * For the first test use <0 for error and >0 for OK */
  14640. return (ret == 0) ? -1 : +1;
  14641. }
  14642. struct mg_connection *
  14643. mg_download(const char *host,
  14644. int port,
  14645. int use_ssl,
  14646. char *ebuf,
  14647. size_t ebuf_len,
  14648. const char *fmt,
  14649. ...)
  14650. {
  14651. struct mg_connection *conn;
  14652. va_list ap;
  14653. int i;
  14654. int reqerr;
  14655. if (ebuf_len > 0) {
  14656. ebuf[0] = '\0';
  14657. }
  14658. va_start(ap, fmt);
  14659. /* open a connection */
  14660. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14661. if (conn != NULL) {
  14662. i = mg_vprintf(conn, fmt, ap);
  14663. if (i <= 0) {
  14664. mg_snprintf(conn,
  14665. NULL, /* No truncation check for ebuf */
  14666. ebuf,
  14667. ebuf_len,
  14668. "%s",
  14669. "Error sending request");
  14670. } else {
  14671. get_response(conn, ebuf, ebuf_len, &reqerr);
  14672. #if defined(MG_LEGACY_INTERFACE)
  14673. /* TODO: 1) uri is deprecated;
  14674. * 2) here, ri.uri is the http response code */
  14675. conn->request_info.uri = conn->request_info.request_uri;
  14676. #endif
  14677. conn->request_info.local_uri = conn->request_info.request_uri;
  14678. }
  14679. }
  14680. /* if an error occurred, close the connection */
  14681. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14682. mg_close_connection(conn);
  14683. conn = NULL;
  14684. }
  14685. va_end(ap);
  14686. return conn;
  14687. }
  14688. struct websocket_client_thread_data {
  14689. struct mg_connection *conn;
  14690. mg_websocket_data_handler data_handler;
  14691. mg_websocket_close_handler close_handler;
  14692. void *callback_data;
  14693. };
  14694. #if defined(USE_WEBSOCKET)
  14695. #if defined(_WIN32)
  14696. static unsigned __stdcall websocket_client_thread(void *data)
  14697. #else
  14698. static void *
  14699. websocket_client_thread(void *data)
  14700. #endif
  14701. {
  14702. struct websocket_client_thread_data *cdata =
  14703. (struct websocket_client_thread_data *)data;
  14704. #if !defined(_WIN32)
  14705. struct sigaction sa;
  14706. /* Ignore SIGPIPE */
  14707. memset(&sa, 0, sizeof(sa));
  14708. sa.sa_handler = SIG_IGN;
  14709. sigaction(SIGPIPE, &sa, NULL);
  14710. #endif
  14711. mg_set_thread_name("ws-clnt");
  14712. if (cdata->conn->phys_ctx) {
  14713. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14714. /* 3 indicates a websocket client thread */
  14715. /* TODO: check if conn->phys_ctx can be set */
  14716. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14717. 3);
  14718. }
  14719. }
  14720. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14721. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14722. if (cdata->close_handler != NULL) {
  14723. cdata->close_handler(cdata->conn, cdata->callback_data);
  14724. }
  14725. /* The websocket_client context has only this thread. If it runs out,
  14726. set the stop_flag to 2 (= "stopped"). */
  14727. cdata->conn->phys_ctx->stop_flag = 2;
  14728. mg_free((void *)cdata);
  14729. #if defined(_WIN32)
  14730. return 0;
  14731. #else
  14732. return NULL;
  14733. #endif
  14734. }
  14735. #endif
  14736. struct mg_connection *
  14737. mg_connect_websocket_client(const char *host,
  14738. int port,
  14739. int use_ssl,
  14740. char *error_buffer,
  14741. size_t error_buffer_size,
  14742. const char *path,
  14743. const char *origin,
  14744. mg_websocket_data_handler data_func,
  14745. mg_websocket_close_handler close_func,
  14746. void *user_data)
  14747. {
  14748. struct mg_connection *conn = NULL;
  14749. #if defined(USE_WEBSOCKET)
  14750. struct mg_context *newctx = NULL;
  14751. struct websocket_client_thread_data *thread_data;
  14752. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14753. static const char *handshake_req;
  14754. if (origin != NULL) {
  14755. handshake_req = "GET %s HTTP/1.1\r\n"
  14756. "Host: %s\r\n"
  14757. "Upgrade: websocket\r\n"
  14758. "Connection: Upgrade\r\n"
  14759. "Sec-WebSocket-Key: %s\r\n"
  14760. "Sec-WebSocket-Version: 13\r\n"
  14761. "Origin: %s\r\n"
  14762. "\r\n";
  14763. } else {
  14764. handshake_req = "GET %s HTTP/1.1\r\n"
  14765. "Host: %s\r\n"
  14766. "Upgrade: websocket\r\n"
  14767. "Connection: Upgrade\r\n"
  14768. "Sec-WebSocket-Key: %s\r\n"
  14769. "Sec-WebSocket-Version: 13\r\n"
  14770. "\r\n";
  14771. }
  14772. #if defined(__clang__)
  14773. #pragma clang diagnostic push
  14774. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14775. #endif
  14776. /* Establish the client connection and request upgrade */
  14777. conn = mg_download(host,
  14778. port,
  14779. use_ssl,
  14780. error_buffer,
  14781. error_buffer_size,
  14782. handshake_req,
  14783. path,
  14784. host,
  14785. magic,
  14786. origin);
  14787. #if defined(__clang__)
  14788. #pragma clang diagnostic pop
  14789. #endif
  14790. /* Connection object will be null if something goes wrong */
  14791. if (conn == NULL) {
  14792. if (!*error_buffer) {
  14793. /* There should be already an error message */
  14794. mg_snprintf(conn,
  14795. NULL, /* No truncation check for ebuf */
  14796. error_buffer,
  14797. error_buffer_size,
  14798. "Unexpected error");
  14799. }
  14800. return NULL;
  14801. }
  14802. if (conn->response_info.status_code != 101) {
  14803. /* We sent an "upgrade" request. For a correct websocket
  14804. * protocol handshake, we expect a "101 Continue" response.
  14805. * Otherwise it is a protocol violation. Maybe the HTTP
  14806. * Server does not know websockets. */
  14807. if (!*error_buffer) {
  14808. /* set an error, if not yet set */
  14809. mg_snprintf(conn,
  14810. NULL, /* No truncation check for ebuf */
  14811. error_buffer,
  14812. error_buffer_size,
  14813. "Unexpected server reply");
  14814. }
  14815. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14816. mg_free(conn);
  14817. return NULL;
  14818. }
  14819. /* For client connections, mg_context is fake. Since we need to set a
  14820. * callback function, we need to create a copy and modify it. */
  14821. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14822. if (!newctx) {
  14823. DEBUG_TRACE("%s\r\n", "Out of memory");
  14824. mg_free(conn);
  14825. return NULL;
  14826. }
  14827. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14828. newctx->user_data = user_data;
  14829. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14830. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14831. newctx->worker_threadids =
  14832. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14833. sizeof(pthread_t),
  14834. newctx);
  14835. conn->phys_ctx = newctx;
  14836. conn->dom_ctx = &(newctx->dd);
  14837. thread_data = (struct websocket_client_thread_data *)
  14838. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14839. if (!thread_data) {
  14840. DEBUG_TRACE("%s\r\n", "Out of memory");
  14841. mg_free(newctx);
  14842. mg_free(conn);
  14843. return NULL;
  14844. }
  14845. thread_data->conn = conn;
  14846. thread_data->data_handler = data_func;
  14847. thread_data->close_handler = close_func;
  14848. thread_data->callback_data = user_data;
  14849. /* Start a thread to read the websocket client connection
  14850. * This thread will automatically stop when mg_disconnect is
  14851. * called on the client connection */
  14852. if (mg_start_thread_with_id(websocket_client_thread,
  14853. (void *)thread_data,
  14854. newctx->worker_threadids) != 0) {
  14855. mg_free((void *)thread_data);
  14856. mg_free((void *)newctx->worker_threadids);
  14857. mg_free((void *)newctx);
  14858. mg_free((void *)conn);
  14859. conn = NULL;
  14860. DEBUG_TRACE("%s",
  14861. "Websocket client connect thread could not be started\r\n");
  14862. }
  14863. #else
  14864. /* Appease "unused parameter" warnings */
  14865. (void)host;
  14866. (void)port;
  14867. (void)use_ssl;
  14868. (void)error_buffer;
  14869. (void)error_buffer_size;
  14870. (void)path;
  14871. (void)origin;
  14872. (void)user_data;
  14873. (void)data_func;
  14874. (void)close_func;
  14875. #endif
  14876. return conn;
  14877. }
  14878. /* Prepare connection data structure */
  14879. static void
  14880. init_connection(struct mg_connection *conn)
  14881. {
  14882. /* Is keep alive allowed by the server */
  14883. int keep_alive_enabled =
  14884. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  14885. if (!keep_alive_enabled) {
  14886. conn->must_close = 1;
  14887. }
  14888. /* Important: on new connection, reset the receiving buffer. Credit
  14889. * goes to crule42. */
  14890. conn->data_len = 0;
  14891. conn->handled_requests = 0;
  14892. mg_set_user_connection_data(conn, NULL);
  14893. #if defined(USE_SERVER_STATS)
  14894. conn->conn_state = 2; /* init */
  14895. #endif
  14896. /* call the init_connection callback if assigned */
  14897. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  14898. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14899. void *conn_data = NULL;
  14900. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  14901. mg_set_user_connection_data(conn, conn_data);
  14902. }
  14903. }
  14904. }
  14905. /* Process a connection - may handle multiple requests
  14906. * using the same connection.
  14907. * Must be called with a valid connection (conn and
  14908. * conn->phys_ctx must be valid).
  14909. */
  14910. static void
  14911. process_new_connection(struct mg_connection *conn)
  14912. {
  14913. struct mg_request_info *ri = &conn->request_info;
  14914. int keep_alive, discard_len;
  14915. char ebuf[100];
  14916. const char *hostend;
  14917. int reqerr, uri_type;
  14918. #if defined(USE_SERVER_STATS)
  14919. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  14920. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  14921. if (mcon > (conn->phys_ctx->max_connections)) {
  14922. /* could use atomic compare exchange, but this
  14923. * seems overkill for statistics data */
  14924. conn->phys_ctx->max_connections = mcon;
  14925. }
  14926. #endif
  14927. init_connection(conn);
  14928. DEBUG_TRACE("Start processing connection from %s",
  14929. conn->request_info.remote_addr);
  14930. /* Loop over multiple requests sent using the same connection
  14931. * (while "keep alive"). */
  14932. do {
  14933. DEBUG_TRACE("calling get_request (%i times for this connection)",
  14934. conn->handled_requests + 1);
  14935. #if defined(USE_SERVER_STATS)
  14936. conn->conn_state = 3; /* ready */
  14937. #endif
  14938. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  14939. /* The request sent by the client could not be understood by
  14940. * the server, or it was incomplete or a timeout. Send an
  14941. * error message and close the connection. */
  14942. if (reqerr > 0) {
  14943. DEBUG_ASSERT(ebuf[0] != '\0');
  14944. mg_send_http_error(conn, reqerr, "%s", ebuf);
  14945. }
  14946. } else if (strcmp(ri->http_version, "1.0")
  14947. && strcmp(ri->http_version, "1.1")) {
  14948. mg_snprintf(conn,
  14949. NULL, /* No truncation check for ebuf */
  14950. ebuf,
  14951. sizeof(ebuf),
  14952. "Bad HTTP version: [%s]",
  14953. ri->http_version);
  14954. mg_send_http_error(conn, 505, "%s", ebuf);
  14955. }
  14956. if (ebuf[0] == '\0') {
  14957. uri_type = get_uri_type(conn->request_info.request_uri);
  14958. switch (uri_type) {
  14959. case 1:
  14960. /* Asterisk */
  14961. conn->request_info.local_uri = NULL;
  14962. break;
  14963. case 2:
  14964. /* relative uri */
  14965. conn->request_info.local_uri = conn->request_info.request_uri;
  14966. break;
  14967. case 3:
  14968. case 4:
  14969. /* absolute uri (with/without port) */
  14970. hostend = get_rel_url_at_current_server(
  14971. conn->request_info.request_uri, conn);
  14972. if (hostend) {
  14973. conn->request_info.local_uri = hostend;
  14974. } else {
  14975. conn->request_info.local_uri = NULL;
  14976. }
  14977. break;
  14978. default:
  14979. mg_snprintf(conn,
  14980. NULL, /* No truncation check for ebuf */
  14981. ebuf,
  14982. sizeof(ebuf),
  14983. "Invalid URI");
  14984. mg_send_http_error(conn, 400, "%s", ebuf);
  14985. conn->request_info.local_uri = NULL;
  14986. break;
  14987. }
  14988. #if defined(MG_LEGACY_INTERFACE)
  14989. /* Legacy before split into local_uri and request_uri */
  14990. conn->request_info.uri = conn->request_info.local_uri;
  14991. #endif
  14992. }
  14993. DEBUG_TRACE("http: %s, error: %s",
  14994. (ri->http_version ? ri->http_version : "none"),
  14995. (ebuf[0] ? ebuf : "none"));
  14996. if (ebuf[0] == '\0') {
  14997. if (conn->request_info.local_uri) {
  14998. /* handle request to local server */
  14999. #if defined(USE_SERVER_STATS)
  15000. conn->conn_state = 4; /* processing */
  15001. #endif
  15002. handle_request(conn);
  15003. #if defined(USE_SERVER_STATS)
  15004. conn->conn_state = 5; /* processed */
  15005. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15006. conn->consumed_content);
  15007. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15008. conn->num_bytes_sent);
  15009. #endif
  15010. DEBUG_TRACE("%s", "handle_request done");
  15011. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15012. conn->phys_ctx->callbacks.end_request(conn,
  15013. conn->status_code);
  15014. DEBUG_TRACE("%s", "end_request callback done");
  15015. }
  15016. log_access(conn);
  15017. } else {
  15018. /* TODO: handle non-local request (PROXY) */
  15019. conn->must_close = 1;
  15020. }
  15021. } else {
  15022. conn->must_close = 1;
  15023. }
  15024. if (ri->remote_user != NULL) {
  15025. mg_free((void *)ri->remote_user);
  15026. /* Important! When having connections with and without auth
  15027. * would cause double free and then crash */
  15028. ri->remote_user = NULL;
  15029. }
  15030. /* NOTE(lsm): order is important here. should_keep_alive() call
  15031. * is using parsed request, which will be invalid after
  15032. * memmove's below.
  15033. * Therefore, memorize should_keep_alive() result now for later
  15034. * use in loop exit condition. */
  15035. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15036. && (conn->content_len >= 0);
  15037. /* Discard all buffered data for this request */
  15038. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  15039. && ((conn->request_len + conn->content_len)
  15040. < (int64_t)conn->data_len))
  15041. ? (int)(conn->request_len + conn->content_len)
  15042. : conn->data_len;
  15043. DEBUG_ASSERT(discard_len >= 0);
  15044. if (discard_len < 0) {
  15045. DEBUG_TRACE("internal error: discard_len = %li",
  15046. (long int)discard_len);
  15047. break;
  15048. }
  15049. conn->data_len -= discard_len;
  15050. if (conn->data_len > 0) {
  15051. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  15052. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  15053. }
  15054. DEBUG_ASSERT(conn->data_len >= 0);
  15055. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15056. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15057. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15058. (long int)conn->data_len,
  15059. (long int)conn->buf_size);
  15060. break;
  15061. }
  15062. conn->handled_requests++;
  15063. } while (keep_alive);
  15064. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15065. conn->request_info.remote_addr,
  15066. difftime(time(NULL), conn->conn_birth_time));
  15067. close_connection(conn);
  15068. #if defined(USE_SERVER_STATS)
  15069. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15070. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15071. #endif
  15072. }
  15073. #if defined(ALTERNATIVE_QUEUE)
  15074. static void
  15075. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15076. {
  15077. unsigned int i;
  15078. while (!ctx->stop_flag) {
  15079. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15080. /* find a free worker slot and signal it */
  15081. if (ctx->client_socks[i].in_use == 0) {
  15082. ctx->client_socks[i] = *sp;
  15083. ctx->client_socks[i].in_use = 1;
  15084. event_signal(ctx->client_wait_events[i]);
  15085. return;
  15086. }
  15087. }
  15088. /* queue is full */
  15089. mg_sleep(1);
  15090. }
  15091. }
  15092. static int
  15093. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15094. {
  15095. DEBUG_TRACE("%s", "going idle");
  15096. ctx->client_socks[thread_index].in_use = 0;
  15097. event_wait(ctx->client_wait_events[thread_index]);
  15098. *sp = ctx->client_socks[thread_index];
  15099. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15100. return !ctx->stop_flag;
  15101. }
  15102. #else /* ALTERNATIVE_QUEUE */
  15103. /* Worker threads take accepted socket from the queue */
  15104. static int
  15105. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15106. {
  15107. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15108. (void)thread_index;
  15109. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15110. DEBUG_TRACE("%s", "going idle");
  15111. /* If the queue is empty, wait. We're idle at this point. */
  15112. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15113. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15114. }
  15115. /* If we're stopping, sq_head may be equal to sq_tail. */
  15116. if (ctx->sq_head > ctx->sq_tail) {
  15117. /* Copy socket from the queue and increment tail */
  15118. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15119. ctx->sq_tail++;
  15120. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15121. /* Wrap pointers if needed */
  15122. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15123. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15124. ctx->sq_head -= QUEUE_SIZE(ctx);
  15125. }
  15126. }
  15127. (void)pthread_cond_signal(&ctx->sq_empty);
  15128. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15129. return !ctx->stop_flag;
  15130. #undef QUEUE_SIZE
  15131. }
  15132. /* Master thread adds accepted socket to a queue */
  15133. static void
  15134. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15135. {
  15136. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15137. if (!ctx) {
  15138. return;
  15139. }
  15140. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15141. /* If the queue is full, wait */
  15142. while ((ctx->stop_flag == 0)
  15143. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15144. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15145. }
  15146. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15147. /* Copy socket to the queue and increment head */
  15148. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15149. ctx->sq_head++;
  15150. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15151. }
  15152. (void)pthread_cond_signal(&ctx->sq_full);
  15153. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15154. #undef QUEUE_SIZE
  15155. }
  15156. #endif /* ALTERNATIVE_QUEUE */
  15157. struct worker_thread_args {
  15158. struct mg_context *ctx;
  15159. int index;
  15160. };
  15161. static void *
  15162. worker_thread_run(struct worker_thread_args *thread_args)
  15163. {
  15164. struct mg_context *ctx = thread_args->ctx;
  15165. struct mg_connection *conn;
  15166. struct mg_workerTLS tls;
  15167. #if defined(MG_LEGACY_INTERFACE)
  15168. uint32_t addr;
  15169. #endif
  15170. mg_set_thread_name("worker");
  15171. tls.is_master = 0;
  15172. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15173. #if defined(_WIN32)
  15174. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15175. #endif
  15176. /* Initialize thread local storage before calling any callback */
  15177. pthread_setspecific(sTlsKey, &tls);
  15178. if (ctx->callbacks.init_thread) {
  15179. /* call init_thread for a worker thread (type 1) */
  15180. ctx->callbacks.init_thread(ctx, 1);
  15181. }
  15182. /* Connection structure has been pre-allocated */
  15183. if (((int)thread_args->index < 0)
  15184. || ((unsigned)thread_args->index
  15185. >= (unsigned)ctx->cfg_worker_threads)) {
  15186. mg_cry_internal(fc(ctx),
  15187. "Internal error: Invalid worker index %i",
  15188. (int)thread_args->index);
  15189. return NULL;
  15190. }
  15191. conn = ctx->worker_connections + thread_args->index;
  15192. /* Request buffers are not pre-allocated. They are private to the
  15193. * request and do not contain any state information that might be
  15194. * of interest to anyone observing a server status. */
  15195. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15196. if (conn->buf == NULL) {
  15197. mg_cry_internal(fc(ctx),
  15198. "Out of memory: Cannot allocate buffer for worker %i",
  15199. (int)thread_args->index);
  15200. return NULL;
  15201. }
  15202. conn->buf_size = (int)ctx->max_request_size;
  15203. conn->phys_ctx = ctx;
  15204. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15205. conn->host = NULL; /* until we have more information. */
  15206. conn->thread_index = thread_args->index;
  15207. conn->request_info.user_data = ctx->user_data;
  15208. /* Allocate a mutex for this connection to allow communication both
  15209. * within the request handler and from elsewhere in the application
  15210. */
  15211. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15212. mg_free(conn->buf);
  15213. mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
  15214. return NULL;
  15215. }
  15216. #if defined(USE_SERVER_STATS)
  15217. conn->conn_state = 1; /* not consumed */
  15218. #endif
  15219. #if defined(ALTERNATIVE_QUEUE)
  15220. while ((ctx->stop_flag == 0)
  15221. && consume_socket(ctx, &conn->client, conn->thread_index)) {
  15222. #else
  15223. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15224. * signal sq_empty condvar to wake up the master waiting in
  15225. * produce_socket() */
  15226. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  15227. #endif
  15228. conn->conn_birth_time = time(NULL);
  15229. /* Fill in IP, port info early so even if SSL setup below fails,
  15230. * error handler would have the corresponding info.
  15231. * Thanks to Johannes Winkelmann for the patch.
  15232. */
  15233. #if defined(USE_IPV6)
  15234. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15235. conn->request_info.remote_port =
  15236. ntohs(conn->client.rsa.sin6.sin6_port);
  15237. } else
  15238. #endif
  15239. {
  15240. conn->request_info.remote_port =
  15241. ntohs(conn->client.rsa.sin.sin_port);
  15242. }
  15243. sockaddr_to_string(conn->request_info.remote_addr,
  15244. sizeof(conn->request_info.remote_addr),
  15245. &conn->client.rsa);
  15246. DEBUG_TRACE("Start processing connection from %s",
  15247. conn->request_info.remote_addr);
  15248. conn->request_info.is_ssl = conn->client.is_ssl;
  15249. if (conn->client.is_ssl) {
  15250. #if !defined(NO_SSL)
  15251. /* HTTPS connection */
  15252. if (sslize(conn,
  15253. conn->dom_ctx->ssl_ctx,
  15254. SSL_accept,
  15255. &(conn->phys_ctx->stop_flag))) {
  15256. /* conn->dom_ctx is set in get_request */
  15257. /* Get SSL client certificate information (if set) */
  15258. ssl_get_client_cert_info(conn);
  15259. /* process HTTPS connection */
  15260. process_new_connection(conn);
  15261. /* Free client certificate info */
  15262. if (conn->request_info.client_cert) {
  15263. mg_free((void *)(conn->request_info.client_cert->subject));
  15264. mg_free((void *)(conn->request_info.client_cert->issuer));
  15265. mg_free((void *)(conn->request_info.client_cert->serial));
  15266. mg_free((void *)(conn->request_info.client_cert->finger));
  15267. /* Free certificate memory */
  15268. X509_free(
  15269. (X509 *)conn->request_info.client_cert->peer_cert);
  15270. conn->request_info.client_cert->peer_cert = 0;
  15271. conn->request_info.client_cert->subject = 0;
  15272. conn->request_info.client_cert->issuer = 0;
  15273. conn->request_info.client_cert->serial = 0;
  15274. conn->request_info.client_cert->finger = 0;
  15275. mg_free(conn->request_info.client_cert);
  15276. conn->request_info.client_cert = 0;
  15277. }
  15278. } else {
  15279. /* make sure the connection is cleaned up on SSL failure */
  15280. close_connection(conn);
  15281. }
  15282. #endif
  15283. } else {
  15284. /* process HTTP connection */
  15285. process_new_connection(conn);
  15286. }
  15287. DEBUG_TRACE("%s", "Connection closed");
  15288. }
  15289. pthread_setspecific(sTlsKey, NULL);
  15290. #if defined(_WIN32)
  15291. CloseHandle(tls.pthread_cond_helper_mutex);
  15292. #endif
  15293. pthread_mutex_destroy(&conn->mutex);
  15294. /* Free the request buffer. */
  15295. conn->buf_size = 0;
  15296. mg_free(conn->buf);
  15297. conn->buf = NULL;
  15298. #if defined(USE_SERVER_STATS)
  15299. conn->conn_state = 9; /* done */
  15300. #endif
  15301. DEBUG_TRACE("%s", "exiting");
  15302. return NULL;
  15303. }
  15304. /* Threads have different return types on Windows and Unix. */
  15305. #if defined(_WIN32)
  15306. static unsigned __stdcall worker_thread(void *thread_func_param)
  15307. {
  15308. struct worker_thread_args *pwta =
  15309. (struct worker_thread_args *)thread_func_param;
  15310. worker_thread_run(pwta);
  15311. mg_free(thread_func_param);
  15312. return 0;
  15313. }
  15314. #else
  15315. static void *
  15316. worker_thread(void *thread_func_param)
  15317. {
  15318. struct worker_thread_args *pwta =
  15319. (struct worker_thread_args *)thread_func_param;
  15320. struct sigaction sa;
  15321. /* Ignore SIGPIPE */
  15322. memset(&sa, 0, sizeof(sa));
  15323. sa.sa_handler = SIG_IGN;
  15324. sigaction(SIGPIPE, &sa, NULL);
  15325. worker_thread_run(pwta);
  15326. mg_free(thread_func_param);
  15327. return NULL;
  15328. }
  15329. #endif /* _WIN32 */
  15330. /* This is an internal function, thus all arguments are expected to be
  15331. * valid - a NULL check is not required. */
  15332. static void
  15333. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15334. {
  15335. struct socket so;
  15336. char src_addr[IP_ADDR_STR_LEN];
  15337. socklen_t len = sizeof(so.rsa);
  15338. int on = 1;
  15339. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15340. == INVALID_SOCKET) {
  15341. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15342. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15343. mg_cry_internal(fc(ctx),
  15344. "%s: %s is not allowed to connect",
  15345. __func__,
  15346. src_addr);
  15347. closesocket(so.sock);
  15348. } else {
  15349. /* Put so socket structure into the queue */
  15350. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15351. set_close_on_exec(so.sock, fc(ctx));
  15352. so.is_ssl = listener->is_ssl;
  15353. so.ssl_redir = listener->ssl_redir;
  15354. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15355. mg_cry_internal(fc(ctx),
  15356. "%s: getsockname() failed: %s",
  15357. __func__,
  15358. strerror(ERRNO));
  15359. }
  15360. /* Set TCP keep-alive. This is needed because if HTTP-level
  15361. * keep-alive
  15362. * is enabled, and client resets the connection, server won't get
  15363. * TCP FIN or RST and will keep the connection open forever. With
  15364. * TCP keep-alive, next keep-alive handshake will figure out that
  15365. * the client is down and will close the server end.
  15366. * Thanks to Igor Klopov who suggested the patch. */
  15367. if (setsockopt(so.sock,
  15368. SOL_SOCKET,
  15369. SO_KEEPALIVE,
  15370. (SOCK_OPT_TYPE)&on,
  15371. sizeof(on)) != 0) {
  15372. mg_cry_internal(
  15373. fc(ctx),
  15374. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15375. __func__,
  15376. strerror(ERRNO));
  15377. }
  15378. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15379. * to effectively fill up the underlying IP packet payload and
  15380. * reduce the overhead of sending lots of small buffers. However
  15381. * this hurts the server's throughput (ie. operations per second)
  15382. * when HTTP 1.1 persistent connections are used and the responses
  15383. * are relatively small (eg. less than 1400 bytes).
  15384. */
  15385. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15386. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15387. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15388. mg_cry_internal(
  15389. fc(ctx),
  15390. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15391. __func__,
  15392. strerror(ERRNO));
  15393. }
  15394. }
  15395. /* We are using non-blocking sockets. Thus, the
  15396. * set_sock_timeout(so.sock, timeout);
  15397. * call is no longer required. */
  15398. /* The "non blocking" property should already be
  15399. * inherited from the parent socket. Set it for
  15400. * non-compliant socket implementations. */
  15401. set_non_blocking_mode(so.sock);
  15402. so.in_use = 0;
  15403. produce_socket(ctx, &so);
  15404. }
  15405. }
  15406. static void
  15407. master_thread_run(void *thread_func_param)
  15408. {
  15409. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  15410. struct mg_workerTLS tls;
  15411. struct pollfd *pfd;
  15412. unsigned int i;
  15413. unsigned int workerthreadcount;
  15414. if (!ctx) {
  15415. return;
  15416. }
  15417. mg_set_thread_name("master");
  15418. /* Increase priority of the master thread */
  15419. #if defined(_WIN32)
  15420. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15421. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15422. int min_prio = sched_get_priority_min(SCHED_RR);
  15423. int max_prio = sched_get_priority_max(SCHED_RR);
  15424. if ((min_prio >= 0) && (max_prio >= 0)
  15425. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15426. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15427. struct sched_param sched_param = {0};
  15428. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15429. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15430. }
  15431. #endif
  15432. /* Initialize thread local storage */
  15433. #if defined(_WIN32)
  15434. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15435. #endif
  15436. tls.is_master = 1;
  15437. pthread_setspecific(sTlsKey, &tls);
  15438. if (ctx->callbacks.init_thread) {
  15439. /* Callback for the master thread (type 0) */
  15440. ctx->callbacks.init_thread(ctx, 0);
  15441. }
  15442. /* Server starts *now* */
  15443. ctx->start_time = time(NULL);
  15444. /* Start the server */
  15445. pfd = ctx->listening_socket_fds;
  15446. while (ctx->stop_flag == 0) {
  15447. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15448. pfd[i].fd = ctx->listening_sockets[i].sock;
  15449. pfd[i].events = POLLIN;
  15450. }
  15451. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15452. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15453. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15454. * successful poll, and POLLIN is defined as
  15455. * (POLLRDNORM | POLLRDBAND)
  15456. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15457. * pfd[i].revents == POLLIN. */
  15458. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15459. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15460. }
  15461. }
  15462. }
  15463. }
  15464. /* Here stop_flag is 1 - Initiate shutdown. */
  15465. DEBUG_TRACE("%s", "stopping workers");
  15466. /* Stop signal received: somebody called mg_stop. Quit. */
  15467. close_all_listening_sockets(ctx);
  15468. /* Wakeup workers that are waiting for connections to handle. */
  15469. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15470. #if defined(ALTERNATIVE_QUEUE)
  15471. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15472. event_signal(ctx->client_wait_events[i]);
  15473. /* Since we know all sockets, we can shutdown the connections. */
  15474. if (ctx->client_socks[i].in_use) {
  15475. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  15476. }
  15477. }
  15478. #else
  15479. pthread_cond_broadcast(&ctx->sq_full);
  15480. #endif
  15481. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15482. /* Join all worker threads to avoid leaking threads. */
  15483. workerthreadcount = ctx->cfg_worker_threads;
  15484. for (i = 0; i < workerthreadcount; i++) {
  15485. if (ctx->worker_threadids[i] != 0) {
  15486. mg_join_thread(ctx->worker_threadids[i]);
  15487. }
  15488. }
  15489. #if defined(USE_LUA)
  15490. /* Free Lua state of lua background task */
  15491. if (ctx->lua_background_state) {
  15492. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15493. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15494. if (lua_istable(lstate, -1)) {
  15495. reg_boolean(lstate, "shutdown", 1);
  15496. lua_pop(lstate, 1);
  15497. mg_sleep(2);
  15498. }
  15499. lua_close(lstate);
  15500. ctx->lua_background_state = 0;
  15501. }
  15502. #endif
  15503. DEBUG_TRACE("%s", "exiting");
  15504. #if defined(_WIN32)
  15505. CloseHandle(tls.pthread_cond_helper_mutex);
  15506. #endif
  15507. pthread_setspecific(sTlsKey, NULL);
  15508. /* Signal mg_stop() that we're done.
  15509. * WARNING: This must be the very last thing this
  15510. * thread does, as ctx becomes invalid after this line. */
  15511. ctx->stop_flag = 2;
  15512. }
  15513. /* Threads have different return types on Windows and Unix. */
  15514. #if defined(_WIN32)
  15515. static unsigned __stdcall master_thread(void *thread_func_param)
  15516. {
  15517. master_thread_run(thread_func_param);
  15518. return 0;
  15519. }
  15520. #else
  15521. static void *
  15522. master_thread(void *thread_func_param)
  15523. {
  15524. struct sigaction sa;
  15525. /* Ignore SIGPIPE */
  15526. memset(&sa, 0, sizeof(sa));
  15527. sa.sa_handler = SIG_IGN;
  15528. sigaction(SIGPIPE, &sa, NULL);
  15529. master_thread_run(thread_func_param);
  15530. return NULL;
  15531. }
  15532. #endif /* _WIN32 */
  15533. static void
  15534. free_context(struct mg_context *ctx)
  15535. {
  15536. int i;
  15537. struct mg_handler_info *tmp_rh;
  15538. if (ctx == NULL) {
  15539. return;
  15540. }
  15541. if (ctx->callbacks.exit_context) {
  15542. ctx->callbacks.exit_context(ctx);
  15543. }
  15544. /* All threads exited, no sync is needed. Destroy thread mutex and
  15545. * condvars
  15546. */
  15547. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15548. #if defined(ALTERNATIVE_QUEUE)
  15549. mg_free(ctx->client_socks);
  15550. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15551. event_destroy(ctx->client_wait_events[i]);
  15552. }
  15553. mg_free(ctx->client_wait_events);
  15554. #else
  15555. (void)pthread_cond_destroy(&ctx->sq_empty);
  15556. (void)pthread_cond_destroy(&ctx->sq_full);
  15557. #endif
  15558. /* Destroy other context global data structures mutex */
  15559. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15560. #if defined(USE_TIMERS)
  15561. timers_exit(ctx);
  15562. #endif
  15563. /* Deallocate config parameters */
  15564. for (i = 0; i < NUM_OPTIONS; i++) {
  15565. if (ctx->dd.config[i] != NULL) {
  15566. #if defined(_MSC_VER)
  15567. #pragma warning(suppress : 6001)
  15568. #endif
  15569. mg_free(ctx->dd.config[i]);
  15570. }
  15571. }
  15572. /* Deallocate request handlers */
  15573. while (ctx->dd.handlers) {
  15574. tmp_rh = ctx->dd.handlers;
  15575. ctx->dd.handlers = tmp_rh->next;
  15576. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15577. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15578. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15579. }
  15580. mg_free(tmp_rh->uri);
  15581. mg_free(tmp_rh);
  15582. }
  15583. #if !defined(NO_SSL)
  15584. /* Deallocate SSL context */
  15585. if (ctx->dd.ssl_ctx != NULL) {
  15586. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15587. int callback_ret =
  15588. (ctx->callbacks.external_ssl_ctx == NULL)
  15589. ? 0
  15590. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15591. if (callback_ret == 0) {
  15592. SSL_CTX_free(ctx->dd.ssl_ctx);
  15593. }
  15594. /* else: ignore error and ommit SSL_CTX_free in case
  15595. * callback_ret is 1 */
  15596. }
  15597. #endif /* !NO_SSL */
  15598. /* Deallocate worker thread ID array */
  15599. if (ctx->worker_threadids != NULL) {
  15600. mg_free(ctx->worker_threadids);
  15601. }
  15602. /* Deallocate worker thread ID array */
  15603. if (ctx->worker_connections != NULL) {
  15604. mg_free(ctx->worker_connections);
  15605. }
  15606. /* deallocate system name string */
  15607. mg_free(ctx->systemName);
  15608. /* Deallocate context itself */
  15609. mg_free(ctx);
  15610. }
  15611. void
  15612. mg_stop(struct mg_context *ctx)
  15613. {
  15614. pthread_t mt;
  15615. if (!ctx) {
  15616. return;
  15617. }
  15618. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15619. * two threads is not allowed. */
  15620. mt = ctx->masterthreadid;
  15621. if (mt == 0) {
  15622. return;
  15623. }
  15624. ctx->masterthreadid = 0;
  15625. /* Set stop flag, so all threads know they have to exit. */
  15626. ctx->stop_flag = 1;
  15627. /* Wait until everything has stopped. */
  15628. while (ctx->stop_flag != 2) {
  15629. (void)mg_sleep(10);
  15630. }
  15631. mg_join_thread(mt);
  15632. free_context(ctx);
  15633. #if defined(_WIN32)
  15634. (void)WSACleanup();
  15635. #endif /* _WIN32 */
  15636. }
  15637. static void
  15638. get_system_name(char **sysName)
  15639. {
  15640. #if defined(_WIN32)
  15641. #if !defined(__SYMBIAN32__)
  15642. #if defined(_WIN32_WCE)
  15643. *sysName = mg_strdup("WinCE");
  15644. #else
  15645. char name[128];
  15646. DWORD dwVersion = 0;
  15647. DWORD dwMajorVersion = 0;
  15648. DWORD dwMinorVersion = 0;
  15649. DWORD dwBuild = 0;
  15650. BOOL wowRet, isWoW = FALSE;
  15651. #if defined(_MSC_VER)
  15652. #pragma warning(push)
  15653. /* GetVersion was declared deprecated */
  15654. #pragma warning(disable : 4996)
  15655. #endif
  15656. dwVersion = GetVersion();
  15657. #if defined(_MSC_VER)
  15658. #pragma warning(pop)
  15659. #endif
  15660. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15661. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15662. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15663. (void)dwBuild;
  15664. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15665. sprintf(name,
  15666. "Windows %u.%u%s",
  15667. (unsigned)dwMajorVersion,
  15668. (unsigned)dwMinorVersion,
  15669. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15670. *sysName = mg_strdup(name);
  15671. #endif
  15672. #else
  15673. *sysName = mg_strdup("Symbian");
  15674. #endif
  15675. #else
  15676. struct utsname name;
  15677. memset(&name, 0, sizeof(name));
  15678. uname(&name);
  15679. *sysName = mg_strdup(name.sysname);
  15680. #endif
  15681. }
  15682. struct mg_context *
  15683. mg_start(const struct mg_callbacks *callbacks,
  15684. void *user_data,
  15685. const char **options)
  15686. {
  15687. struct mg_context *ctx;
  15688. const char *name, *value, *default_value;
  15689. int idx, ok, workerthreadcount;
  15690. unsigned int i;
  15691. int itmp;
  15692. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15693. struct mg_workerTLS tls;
  15694. #if defined(_WIN32)
  15695. WSADATA data;
  15696. WSAStartup(MAKEWORD(2, 2), &data);
  15697. #endif /* _WIN32 */
  15698. /* Allocate context and initialize reasonable general case defaults. */
  15699. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15700. return NULL;
  15701. }
  15702. /* Random number generator will initialize at the first call */
  15703. ctx->dd.auth_nonce_mask =
  15704. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15705. if (mg_init_library_called == 0) {
  15706. /* Legacy INIT, if mg_start is called without mg_init_library.
  15707. * Note: This may cause a memory leak */
  15708. const char *ports_option =
  15709. config_options[LISTENING_PORTS].default_value;
  15710. if (options) {
  15711. const char **run_options = options;
  15712. const char *optname = config_options[LISTENING_PORTS].name;
  15713. /* Try to find the "listening_ports" option */
  15714. while (*run_options) {
  15715. if (!strcmp(*run_options, optname)) {
  15716. ports_option = run_options[1];
  15717. }
  15718. run_options += 2;
  15719. }
  15720. }
  15721. if (is_ssl_port_used(ports_option)) {
  15722. /* Initialize with SSL support */
  15723. mg_init_library(MG_FEATURES_TLS);
  15724. } else {
  15725. /* Initialize without SSL support */
  15726. mg_init_library(MG_FEATURES_DEFAULT);
  15727. }
  15728. }
  15729. tls.is_master = -1;
  15730. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15731. #if defined(_WIN32)
  15732. tls.pthread_cond_helper_mutex = NULL;
  15733. #endif
  15734. pthread_setspecific(sTlsKey, &tls);
  15735. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15736. #if !defined(ALTERNATIVE_QUEUE)
  15737. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15738. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15739. #endif
  15740. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15741. if (!ok) {
  15742. /* Fatal error - abort start. However, this situation should never
  15743. * occur in practice. */
  15744. mg_cry_internal(fc(ctx),
  15745. "%s",
  15746. "Cannot initialize thread synchronization objects");
  15747. mg_free(ctx);
  15748. pthread_setspecific(sTlsKey, NULL);
  15749. return NULL;
  15750. }
  15751. if (callbacks) {
  15752. ctx->callbacks = *callbacks;
  15753. exit_callback = callbacks->exit_context;
  15754. ctx->callbacks.exit_context = 0;
  15755. }
  15756. ctx->user_data = user_data;
  15757. ctx->dd.handlers = NULL;
  15758. ctx->dd.next = NULL;
  15759. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15760. ctx->dd.shared_lua_websockets = NULL;
  15761. #endif
  15762. /* Store options */
  15763. while (options && (name = *options++) != NULL) {
  15764. if ((idx = get_option_index(name)) == -1) {
  15765. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15766. free_context(ctx);
  15767. pthread_setspecific(sTlsKey, NULL);
  15768. return NULL;
  15769. } else if ((value = *options++) == NULL) {
  15770. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15771. free_context(ctx);
  15772. pthread_setspecific(sTlsKey, NULL);
  15773. return NULL;
  15774. }
  15775. if (ctx->dd.config[idx] != NULL) {
  15776. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15777. mg_free(ctx->dd.config[idx]);
  15778. }
  15779. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15780. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15781. }
  15782. /* Set default value if needed */
  15783. for (i = 0; config_options[i].name != NULL; i++) {
  15784. default_value = config_options[i].default_value;
  15785. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15786. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15787. }
  15788. }
  15789. /* Request size option */
  15790. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15791. if (itmp < 1024) {
  15792. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15793. free_context(ctx);
  15794. pthread_setspecific(sTlsKey, NULL);
  15795. return NULL;
  15796. }
  15797. ctx->max_request_size = (unsigned)itmp;
  15798. /* Worker thread count option */
  15799. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15800. if (workerthreadcount > MAX_WORKER_THREADS) {
  15801. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15802. free_context(ctx);
  15803. pthread_setspecific(sTlsKey, NULL);
  15804. return NULL;
  15805. }
  15806. if (workerthreadcount <= 0) {
  15807. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15808. free_context(ctx);
  15809. pthread_setspecific(sTlsKey, NULL);
  15810. return NULL;
  15811. }
  15812. /* Document root */
  15813. #if defined(NO_FILES)
  15814. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15815. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15816. free_context(ctx);
  15817. pthread_setspecific(sTlsKey, NULL);
  15818. return NULL;
  15819. }
  15820. #endif
  15821. get_system_name(&ctx->systemName);
  15822. #if defined(USE_LUA)
  15823. /* If a Lua background script has been configured, start it. */
  15824. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15825. char ebuf[256];
  15826. struct vec opt_vec;
  15827. struct vec eq_vec;
  15828. const char *sparams;
  15829. lua_State *state = mg_prepare_lua_context_script(
  15830. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15831. if (!state) {
  15832. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15833. free_context(ctx);
  15834. pthread_setspecific(sTlsKey, NULL);
  15835. return NULL;
  15836. }
  15837. ctx->lua_background_state = (void *)state;
  15838. lua_newtable(state);
  15839. reg_boolean(state, "shutdown", 0);
  15840. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15841. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15842. reg_llstring(
  15843. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15844. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15845. break;
  15846. }
  15847. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15848. } else {
  15849. ctx->lua_background_state = 0;
  15850. }
  15851. #endif
  15852. /* NOTE(lsm): order is important here. SSL certificates must
  15853. * be initialized before listening ports. UID must be set last. */
  15854. if (!set_gpass_option(ctx, NULL) ||
  15855. #if !defined(NO_SSL)
  15856. !init_ssl_ctx(ctx, NULL) ||
  15857. #endif
  15858. !set_ports_option(ctx) ||
  15859. #if !defined(_WIN32)
  15860. !set_uid_option(ctx) ||
  15861. #endif
  15862. !set_acl_option(ctx)) {
  15863. free_context(ctx);
  15864. pthread_setspecific(sTlsKey, NULL);
  15865. return NULL;
  15866. }
  15867. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  15868. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15869. sizeof(pthread_t),
  15870. ctx);
  15871. if (ctx->worker_threadids == NULL) {
  15872. mg_cry_internal(fc(ctx),
  15873. "%s",
  15874. "Not enough memory for worker thread ID array");
  15875. free_context(ctx);
  15876. pthread_setspecific(sTlsKey, NULL);
  15877. return NULL;
  15878. }
  15879. ctx->worker_connections =
  15880. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15881. sizeof(struct mg_connection),
  15882. ctx);
  15883. if (ctx->worker_connections == NULL) {
  15884. mg_cry_internal(fc(ctx),
  15885. "%s",
  15886. "Not enough memory for worker thread connection array");
  15887. free_context(ctx);
  15888. pthread_setspecific(sTlsKey, NULL);
  15889. return NULL;
  15890. }
  15891. #if defined(ALTERNATIVE_QUEUE)
  15892. ctx->client_wait_events =
  15893. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  15894. ctx->cfg_worker_threads,
  15895. ctx);
  15896. if (ctx->client_wait_events == NULL) {
  15897. mg_cry_internal(fc(ctx),
  15898. "%s",
  15899. "Not enough memory for worker event array");
  15900. mg_free(ctx->worker_threadids);
  15901. free_context(ctx);
  15902. pthread_setspecific(sTlsKey, NULL);
  15903. return NULL;
  15904. }
  15905. ctx->client_socks =
  15906. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  15907. ctx->cfg_worker_threads,
  15908. ctx);
  15909. if (ctx->client_socks == NULL) {
  15910. mg_cry_internal(fc(ctx),
  15911. "%s",
  15912. "Not enough memory for worker socket array");
  15913. mg_free(ctx->client_wait_events);
  15914. mg_free(ctx->worker_threadids);
  15915. free_context(ctx);
  15916. pthread_setspecific(sTlsKey, NULL);
  15917. return NULL;
  15918. }
  15919. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15920. ctx->client_wait_events[i] = event_create();
  15921. if (ctx->client_wait_events[i] == 0) {
  15922. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  15923. while (i > 0) {
  15924. i--;
  15925. event_destroy(ctx->client_wait_events[i]);
  15926. }
  15927. mg_free(ctx->client_socks);
  15928. mg_free(ctx->client_wait_events);
  15929. mg_free(ctx->worker_threadids);
  15930. free_context(ctx);
  15931. pthread_setspecific(sTlsKey, NULL);
  15932. return NULL;
  15933. }
  15934. }
  15935. #endif
  15936. #if defined(USE_TIMERS)
  15937. if (timers_init(ctx) != 0) {
  15938. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  15939. free_context(ctx);
  15940. pthread_setspecific(sTlsKey, NULL);
  15941. return NULL;
  15942. }
  15943. #endif
  15944. /* Context has been created - init user libraries */
  15945. if (ctx->callbacks.init_context) {
  15946. ctx->callbacks.init_context(ctx);
  15947. }
  15948. ctx->callbacks.exit_context = exit_callback;
  15949. ctx->context_type = CONTEXT_SERVER; /* server context */
  15950. /* Start master (listening) thread */
  15951. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  15952. /* Start worker threads */
  15953. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15954. struct worker_thread_args *wta = (struct worker_thread_args *)
  15955. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  15956. if (wta) {
  15957. wta->ctx = ctx;
  15958. wta->index = (int)i;
  15959. }
  15960. if ((wta == NULL)
  15961. || (mg_start_thread_with_id(worker_thread,
  15962. wta,
  15963. &ctx->worker_threadids[i]) != 0)) {
  15964. /* thread was not created */
  15965. if (wta != NULL) {
  15966. mg_free(wta);
  15967. }
  15968. if (i > 0) {
  15969. mg_cry_internal(fc(ctx),
  15970. "Cannot start worker thread %i: error %ld",
  15971. i + 1,
  15972. (long)ERRNO);
  15973. } else {
  15974. mg_cry_internal(fc(ctx),
  15975. "Cannot create threads: error %ld",
  15976. (long)ERRNO);
  15977. free_context(ctx);
  15978. pthread_setspecific(sTlsKey, NULL);
  15979. return NULL;
  15980. }
  15981. break;
  15982. }
  15983. }
  15984. pthread_setspecific(sTlsKey, NULL);
  15985. return ctx;
  15986. }
  15987. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15988. /* Add an additional domain to an already running web server. */
  15989. int
  15990. mg_start_domain(struct mg_context *ctx, const char **options)
  15991. {
  15992. const char *name;
  15993. const char *value;
  15994. const char *default_value;
  15995. struct mg_domain_context *new_dom;
  15996. struct mg_domain_context *dom;
  15997. int idx, i;
  15998. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  15999. return -1;
  16000. }
  16001. new_dom = (struct mg_domain_context *)
  16002. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16003. if (!new_dom) {
  16004. /* Out of memory */
  16005. return -6;
  16006. }
  16007. /* Store options - TODO: unite duplicate code */
  16008. while (options && (name = *options++) != NULL) {
  16009. if ((idx = get_option_index(name)) == -1) {
  16010. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  16011. mg_free(new_dom);
  16012. return -2;
  16013. } else if ((value = *options++) == NULL) {
  16014. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16015. mg_free(new_dom);
  16016. return -2;
  16017. }
  16018. if (new_dom->config[idx] != NULL) {
  16019. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16020. mg_free(new_dom->config[idx]);
  16021. }
  16022. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16023. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16024. }
  16025. /* Authentication domain is mandatory */
  16026. /* TODO: Maybe use a new option hostname? */
  16027. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16028. mg_cry_internal(fc(ctx), "%s", "authentication domain required");
  16029. mg_free(new_dom);
  16030. return -4;
  16031. }
  16032. /* Set default value if needed. Take the config value from
  16033. * ctx as a default value. */
  16034. for (i = 0; config_options[i].name != NULL; i++) {
  16035. default_value = ctx->dd.config[i];
  16036. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16037. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16038. }
  16039. }
  16040. new_dom->handlers = NULL;
  16041. new_dom->next = NULL;
  16042. new_dom->nonce_count = 0;
  16043. new_dom->auth_nonce_mask =
  16044. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16045. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16046. new_dom->shared_lua_websockets = NULL;
  16047. #endif
  16048. if (!init_ssl_ctx(ctx, new_dom)) {
  16049. /* Init SSL failed */
  16050. mg_free(new_dom);
  16051. return -3;
  16052. }
  16053. /* Add element to linked list. */
  16054. mg_lock_context(ctx);
  16055. idx = 0;
  16056. dom = &(ctx->dd);
  16057. for (;;) {
  16058. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16059. dom->config[AUTHENTICATION_DOMAIN])) {
  16060. /* Domain collision */
  16061. mg_cry_internal(fc(ctx),
  16062. "domain %s already in use",
  16063. new_dom->config[AUTHENTICATION_DOMAIN]);
  16064. mg_free(new_dom);
  16065. return -5;
  16066. }
  16067. /* Count number of domains */
  16068. idx++;
  16069. if (dom->next == NULL) {
  16070. dom->next = new_dom;
  16071. break;
  16072. }
  16073. dom = dom->next;
  16074. }
  16075. mg_unlock_context(ctx);
  16076. /* Return domain number */
  16077. return idx;
  16078. }
  16079. #endif
  16080. /* Feature check API function */
  16081. unsigned
  16082. mg_check_feature(unsigned feature)
  16083. {
  16084. static const unsigned feature_set = 0
  16085. /* Set bits for available features according to API documentation.
  16086. * This bit mask is created at compile time, according to the active
  16087. * preprocessor defines. It is a single const value at runtime. */
  16088. #if !defined(NO_FILES)
  16089. | MG_FEATURES_FILES
  16090. #endif
  16091. #if !defined(NO_SSL)
  16092. | MG_FEATURES_SSL
  16093. #endif
  16094. #if !defined(NO_CGI)
  16095. | MG_FEATURES_CGI
  16096. #endif
  16097. #if defined(USE_IPV6)
  16098. | MG_FEATURES_IPV6
  16099. #endif
  16100. #if defined(USE_WEBSOCKET)
  16101. | MG_FEATURES_WEBSOCKET
  16102. #endif
  16103. #if defined(USE_LUA)
  16104. | MG_FEATURES_LUA
  16105. #endif
  16106. #if defined(USE_DUKTAPE)
  16107. | MG_FEATURES_SSJS
  16108. #endif
  16109. #if !defined(NO_CACHING)
  16110. | MG_FEATURES_CACHE
  16111. #endif
  16112. #if defined(USE_SERVER_STATS)
  16113. | MG_FEATURES_STATS
  16114. #endif
  16115. #if defined(USE_ZLIB)
  16116. | MG_FEATURES_COMPRESSION
  16117. #endif
  16118. /* Set some extra bits not defined in the API documentation.
  16119. * These bits may change without further notice. */
  16120. #if defined(MG_LEGACY_INTERFACE)
  16121. | 0x00008000u
  16122. #endif
  16123. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16124. | 0x00004000u
  16125. #endif
  16126. #if defined(MEMORY_DEBUGGING)
  16127. | 0x00001000u
  16128. #endif
  16129. #if defined(USE_TIMERS)
  16130. | 0x00020000u
  16131. #endif
  16132. #if !defined(NO_NONCE_CHECK)
  16133. | 0x00040000u
  16134. #endif
  16135. #if !defined(NO_POPEN)
  16136. | 0x00080000u
  16137. #endif
  16138. ;
  16139. return (feature & feature_set);
  16140. }
  16141. /* strcat with additional NULL check to avoid clang scan-build warning. */
  16142. #define strcat0(a, b) \
  16143. { \
  16144. if ((a != NULL) && (b != NULL)) { \
  16145. strcat(a, b); \
  16146. } \
  16147. }
  16148. /* Get system information. It can be printed or stored by the caller.
  16149. * Return the size of available information. */
  16150. static int
  16151. mg_get_system_info_impl(char *buffer, int buflen)
  16152. {
  16153. char block[256];
  16154. int system_info_length = 0;
  16155. #if defined(_WIN32)
  16156. const char *eol = "\r\n";
  16157. #else
  16158. const char *eol = "\n";
  16159. #endif
  16160. const char *eoobj = "}";
  16161. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16162. if ((buffer == NULL) || (buflen < 1)) {
  16163. buflen = 0;
  16164. } else {
  16165. *buffer = 0;
  16166. }
  16167. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16168. system_info_length += (int)strlen(block);
  16169. if (system_info_length < buflen) {
  16170. strcat0(buffer, block);
  16171. }
  16172. /* Server version */
  16173. {
  16174. const char *version = mg_version();
  16175. mg_snprintf(NULL,
  16176. NULL,
  16177. block,
  16178. sizeof(block),
  16179. "\"version\" : \"%s\",%s",
  16180. version,
  16181. eol);
  16182. system_info_length += (int)strlen(block);
  16183. if (system_info_length < buflen) {
  16184. strcat0(buffer, block);
  16185. }
  16186. }
  16187. /* System info */
  16188. {
  16189. #if defined(_WIN32)
  16190. DWORD dwVersion = 0;
  16191. DWORD dwMajorVersion = 0;
  16192. DWORD dwMinorVersion = 0;
  16193. SYSTEM_INFO si;
  16194. GetSystemInfo(&si);
  16195. #if defined(_MSC_VER)
  16196. #pragma warning(push)
  16197. /* GetVersion was declared deprecated */
  16198. #pragma warning(disable : 4996)
  16199. #endif
  16200. dwVersion = GetVersion();
  16201. #if defined(_MSC_VER)
  16202. #pragma warning(pop)
  16203. #endif
  16204. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16205. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16206. mg_snprintf(NULL,
  16207. NULL,
  16208. block,
  16209. sizeof(block),
  16210. "\"os\" : \"Windows %u.%u\",%s",
  16211. (unsigned)dwMajorVersion,
  16212. (unsigned)dwMinorVersion,
  16213. eol);
  16214. system_info_length += (int)strlen(block);
  16215. if (system_info_length < buflen) {
  16216. strcat0(buffer, block);
  16217. }
  16218. mg_snprintf(NULL,
  16219. NULL,
  16220. block,
  16221. sizeof(block),
  16222. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  16223. (unsigned)si.wProcessorArchitecture,
  16224. (unsigned)si.dwNumberOfProcessors,
  16225. (unsigned)si.dwActiveProcessorMask,
  16226. eol);
  16227. system_info_length += (int)strlen(block);
  16228. if (system_info_length < buflen) {
  16229. strcat0(buffer, block);
  16230. }
  16231. #else
  16232. struct utsname name;
  16233. memset(&name, 0, sizeof(name));
  16234. uname(&name);
  16235. mg_snprintf(NULL,
  16236. NULL,
  16237. block,
  16238. sizeof(block),
  16239. "\"os\" : \"%s %s (%s) - %s\",%s",
  16240. name.sysname,
  16241. name.version,
  16242. name.release,
  16243. name.machine,
  16244. eol);
  16245. system_info_length += (int)strlen(block);
  16246. if (system_info_length < buflen) {
  16247. strcat0(buffer, block);
  16248. }
  16249. #endif
  16250. }
  16251. /* Features */
  16252. {
  16253. mg_snprintf(NULL,
  16254. NULL,
  16255. block,
  16256. sizeof(block),
  16257. "\"features\" : %lu,%s"
  16258. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  16259. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16260. eol,
  16261. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16262. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16263. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16264. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16265. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16266. : "",
  16267. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16268. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16269. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16270. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  16271. eol);
  16272. system_info_length += (int)strlen(block);
  16273. if (system_info_length < buflen) {
  16274. strcat0(buffer, block);
  16275. }
  16276. #if defined(USE_LUA)
  16277. mg_snprintf(NULL,
  16278. NULL,
  16279. block,
  16280. sizeof(block),
  16281. "\"lua_version\" : \"%u (%s)\",%s",
  16282. (unsigned)LUA_VERSION_NUM,
  16283. LUA_RELEASE,
  16284. eol);
  16285. system_info_length += (int)strlen(block);
  16286. if (system_info_length < buflen) {
  16287. strcat0(buffer, block);
  16288. }
  16289. #endif
  16290. #if defined(USE_DUKTAPE)
  16291. mg_snprintf(NULL,
  16292. NULL,
  16293. block,
  16294. sizeof(block),
  16295. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  16296. (unsigned)DUK_VERSION / 10000,
  16297. ((unsigned)DUK_VERSION / 100) % 100,
  16298. (unsigned)DUK_VERSION % 100,
  16299. eol);
  16300. system_info_length += (int)strlen(block);
  16301. if (system_info_length < buflen) {
  16302. strcat0(buffer, block);
  16303. }
  16304. #endif
  16305. }
  16306. /* Build date */
  16307. {
  16308. #if defined(__GNUC__)
  16309. #pragma GCC diagnostic push
  16310. /* Disable bogus compiler warning -Wdate-time */
  16311. #pragma GCC diagnostic ignored "-Wdate-time"
  16312. #endif
  16313. mg_snprintf(NULL,
  16314. NULL,
  16315. block,
  16316. sizeof(block),
  16317. "\"build\" : \"%s\",%s",
  16318. __DATE__,
  16319. eol);
  16320. #if defined(__GNUC__)
  16321. #pragma GCC diagnostic pop
  16322. #endif
  16323. system_info_length += (int)strlen(block);
  16324. if (system_info_length < buflen) {
  16325. strcat0(buffer, block);
  16326. }
  16327. }
  16328. /* Compiler information */
  16329. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16330. {
  16331. #if defined(_MSC_VER)
  16332. mg_snprintf(NULL,
  16333. NULL,
  16334. block,
  16335. sizeof(block),
  16336. "\"compiler\" : \"MSC: %u (%u)\",%s",
  16337. (unsigned)_MSC_VER,
  16338. (unsigned)_MSC_FULL_VER,
  16339. eol);
  16340. system_info_length += (int)strlen(block);
  16341. if (system_info_length < buflen) {
  16342. strcat0(buffer, block);
  16343. }
  16344. #elif defined(__MINGW64__)
  16345. mg_snprintf(NULL,
  16346. NULL,
  16347. block,
  16348. sizeof(block),
  16349. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  16350. (unsigned)__MINGW64_VERSION_MAJOR,
  16351. (unsigned)__MINGW64_VERSION_MINOR,
  16352. eol);
  16353. system_info_length += (int)strlen(block);
  16354. if (system_info_length < buflen) {
  16355. strcat0(buffer, block);
  16356. }
  16357. mg_snprintf(NULL,
  16358. NULL,
  16359. block,
  16360. sizeof(block),
  16361. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16362. (unsigned)__MINGW32_MAJOR_VERSION,
  16363. (unsigned)__MINGW32_MINOR_VERSION,
  16364. eol);
  16365. system_info_length += (int)strlen(block);
  16366. if (system_info_length < buflen) {
  16367. strcat0(buffer, block);
  16368. }
  16369. #elif defined(__MINGW32__)
  16370. mg_snprintf(NULL,
  16371. NULL,
  16372. block,
  16373. sizeof(block),
  16374. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16375. (unsigned)__MINGW32_MAJOR_VERSION,
  16376. (unsigned)__MINGW32_MINOR_VERSION,
  16377. eol);
  16378. system_info_length += (int)strlen(block);
  16379. if (system_info_length < buflen) {
  16380. strcat0(buffer, block);
  16381. }
  16382. #elif defined(__clang__)
  16383. mg_snprintf(NULL,
  16384. NULL,
  16385. block,
  16386. sizeof(block),
  16387. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  16388. __clang_major__,
  16389. __clang_minor__,
  16390. __clang_patchlevel__,
  16391. __clang_version__,
  16392. eol);
  16393. system_info_length += (int)strlen(block);
  16394. if (system_info_length < buflen) {
  16395. strcat0(buffer, block);
  16396. }
  16397. #elif defined(__GNUC__)
  16398. mg_snprintf(NULL,
  16399. NULL,
  16400. block,
  16401. sizeof(block),
  16402. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  16403. (unsigned)__GNUC__,
  16404. (unsigned)__GNUC_MINOR__,
  16405. (unsigned)__GNUC_PATCHLEVEL__,
  16406. eol);
  16407. system_info_length += (int)strlen(block);
  16408. if (system_info_length < buflen) {
  16409. strcat0(buffer, block);
  16410. }
  16411. #elif defined(__INTEL_COMPILER)
  16412. mg_snprintf(NULL,
  16413. NULL,
  16414. block,
  16415. sizeof(block),
  16416. "\"compiler\" : \"Intel C/C++: %u\",%s",
  16417. (unsigned)__INTEL_COMPILER,
  16418. eol);
  16419. system_info_length += (int)strlen(block);
  16420. if (system_info_length < buflen) {
  16421. strcat0(buffer, block);
  16422. }
  16423. #elif defined(__BORLANDC__)
  16424. mg_snprintf(NULL,
  16425. NULL,
  16426. block,
  16427. sizeof(block),
  16428. "\"compiler\" : \"Borland C: 0x%x\",%s",
  16429. (unsigned)__BORLANDC__,
  16430. eol);
  16431. system_info_length += (int)strlen(block);
  16432. if (system_info_length < buflen) {
  16433. strcat0(buffer, block);
  16434. }
  16435. #elif defined(__SUNPRO_C)
  16436. mg_snprintf(NULL,
  16437. NULL,
  16438. block,
  16439. sizeof(block),
  16440. "\"compiler\" : \"Solaris: 0x%x\",%s",
  16441. (unsigned)__SUNPRO_C,
  16442. eol);
  16443. system_info_length += (int)strlen(block);
  16444. if (system_info_length < buflen) {
  16445. strcat0(buffer, block);
  16446. }
  16447. #else
  16448. mg_snprintf(NULL,
  16449. NULL,
  16450. block,
  16451. sizeof(block),
  16452. "\"compiler\" : \"other\",%s",
  16453. eol);
  16454. system_info_length += (int)strlen(block);
  16455. if (system_info_length < buflen) {
  16456. strcat0(buffer, block);
  16457. }
  16458. #endif
  16459. }
  16460. /* Determine 32/64 bit data mode.
  16461. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16462. {
  16463. mg_snprintf(NULL,
  16464. NULL,
  16465. block,
  16466. sizeof(block),
  16467. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16468. "char:%u/%u, "
  16469. "ptr:%u, size:%u, time:%u\"%s",
  16470. (unsigned)sizeof(short),
  16471. (unsigned)sizeof(int),
  16472. (unsigned)sizeof(long),
  16473. (unsigned)sizeof(long long),
  16474. (unsigned)sizeof(float),
  16475. (unsigned)sizeof(double),
  16476. (unsigned)sizeof(long double),
  16477. (unsigned)sizeof(char),
  16478. (unsigned)sizeof(wchar_t),
  16479. (unsigned)sizeof(void *),
  16480. (unsigned)sizeof(size_t),
  16481. (unsigned)sizeof(time_t),
  16482. eol);
  16483. system_info_length += (int)strlen(block);
  16484. if (system_info_length < buflen) {
  16485. strcat0(buffer, block);
  16486. }
  16487. }
  16488. /* Terminate string */
  16489. if ((buflen > 0) && buffer && buffer[0]) {
  16490. if (system_info_length < buflen) {
  16491. strcat0(buffer, eoobj);
  16492. strcat0(buffer, eol);
  16493. }
  16494. }
  16495. system_info_length += reserved_len;
  16496. return system_info_length;
  16497. }
  16498. #if defined(USE_SERVER_STATS)
  16499. /* Get context information. It can be printed or stored by the caller.
  16500. * Return the size of available information. */
  16501. static int
  16502. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  16503. {
  16504. char block[256];
  16505. int context_info_length = 0;
  16506. #if defined(_WIN32)
  16507. const char *eol = "\r\n";
  16508. #else
  16509. const char *eol = "\n";
  16510. #endif
  16511. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16512. const char *eoobj = "}";
  16513. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16514. if ((buffer == NULL) || (buflen < 1)) {
  16515. buflen = 0;
  16516. } else {
  16517. *buffer = 0;
  16518. }
  16519. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16520. context_info_length += (int)strlen(block);
  16521. if (context_info_length < buflen) {
  16522. strcat0(buffer, block);
  16523. }
  16524. if (ms) { /* <-- should be always true */
  16525. /* Memory information */
  16526. mg_snprintf(NULL,
  16527. NULL,
  16528. block,
  16529. sizeof(block),
  16530. "\"memory\" : {%s"
  16531. "\"blocks\" : %i,%s"
  16532. "\"used\" : %" INT64_FMT ",%s"
  16533. "\"maxUsed\" : %" INT64_FMT "%s"
  16534. "}%s%s",
  16535. eol,
  16536. ms->blockCount,
  16537. eol,
  16538. ms->totalMemUsed,
  16539. eol,
  16540. ms->maxMemUsed,
  16541. eol,
  16542. (ctx ? "," : ""),
  16543. eol);
  16544. context_info_length += (int)strlen(block);
  16545. if (context_info_length + reserved_len < buflen) {
  16546. strcat0(buffer, block);
  16547. }
  16548. }
  16549. if (ctx) {
  16550. /* Declare all variables at begin of the block, to comply
  16551. * with old C standards. */
  16552. char start_time_str[64] = {0};
  16553. char now_str[64] = {0};
  16554. time_t start_time = ctx->start_time;
  16555. time_t now = time(NULL);
  16556. /* Connections information */
  16557. mg_snprintf(NULL,
  16558. NULL,
  16559. block,
  16560. sizeof(block),
  16561. "\"connections\" : {%s"
  16562. "\"active\" : %i,%s"
  16563. "\"maxActive\" : %i,%s"
  16564. "\"total\" : %" INT64_FMT "%s"
  16565. "},%s",
  16566. eol,
  16567. ctx->active_connections,
  16568. eol,
  16569. ctx->max_connections,
  16570. eol,
  16571. ctx->total_connections,
  16572. eol,
  16573. eol);
  16574. context_info_length += (int)strlen(block);
  16575. if (context_info_length + reserved_len < buflen) {
  16576. strcat0(buffer, block);
  16577. }
  16578. /* Requests information */
  16579. mg_snprintf(NULL,
  16580. NULL,
  16581. block,
  16582. sizeof(block),
  16583. "\"requests\" : {%s"
  16584. "\"total\" : %" INT64_FMT "%s"
  16585. "},%s",
  16586. eol,
  16587. ctx->total_requests,
  16588. eol,
  16589. eol);
  16590. context_info_length += (int)strlen(block);
  16591. if (context_info_length + reserved_len < buflen) {
  16592. strcat0(buffer, block);
  16593. }
  16594. /* Data information */
  16595. mg_snprintf(NULL,
  16596. NULL,
  16597. block,
  16598. sizeof(block),
  16599. "\"data\" : {%s"
  16600. "\"read\" : %" INT64_FMT "%s,"
  16601. "\"written\" : %" INT64_FMT "%s"
  16602. "},%s",
  16603. eol,
  16604. ctx->total_data_read,
  16605. eol,
  16606. ctx->total_data_written,
  16607. eol,
  16608. eol);
  16609. context_info_length += (int)strlen(block);
  16610. if (context_info_length + reserved_len < buflen) {
  16611. strcat0(buffer, block);
  16612. }
  16613. /* Execution time information */
  16614. gmt_time_string(start_time_str,
  16615. sizeof(start_time_str) - 1,
  16616. &start_time);
  16617. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16618. mg_snprintf(NULL,
  16619. NULL,
  16620. block,
  16621. sizeof(block),
  16622. "\"time\" : {%s"
  16623. "\"uptime\" : %.0f,%s"
  16624. "\"start\" : \"%s\",%s"
  16625. "\"now\" : \"%s\"%s"
  16626. "}%s",
  16627. eol,
  16628. difftime(now, start_time),
  16629. eol,
  16630. start_time_str,
  16631. eol,
  16632. now_str,
  16633. eol,
  16634. eol);
  16635. context_info_length += (int)strlen(block);
  16636. if (context_info_length + reserved_len < buflen) {
  16637. strcat0(buffer, block);
  16638. }
  16639. }
  16640. /* Terminate string */
  16641. if ((buflen > 0) && buffer && buffer[0]) {
  16642. if (context_info_length < buflen) {
  16643. strcat0(buffer, eoobj);
  16644. strcat0(buffer, eol);
  16645. }
  16646. }
  16647. context_info_length += reserved_len;
  16648. return context_info_length;
  16649. }
  16650. #endif
  16651. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16652. /* Get connection information. It can be printed or stored by the caller.
  16653. * Return the size of available information. */
  16654. static int
  16655. mg_get_connection_info_impl(const struct mg_context *ctx,
  16656. int idx,
  16657. char *buffer,
  16658. int buflen)
  16659. {
  16660. const struct mg_connection *conn;
  16661. const struct mg_request_info *ri;
  16662. char block[256];
  16663. int connection_info_length = 0;
  16664. int state = 0;
  16665. const char *state_str = "unknown";
  16666. #if defined(_WIN32)
  16667. const char *eol = "\r\n";
  16668. #else
  16669. const char *eol = "\n";
  16670. #endif
  16671. const char *eoobj = "}";
  16672. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16673. if ((buffer == NULL) || (buflen < 1)) {
  16674. buflen = 0;
  16675. } else {
  16676. *buffer = 0;
  16677. }
  16678. if ((ctx == NULL) || (idx < 0)) {
  16679. /* Parameter error */
  16680. return 0;
  16681. }
  16682. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16683. /* Out of range */
  16684. return 0;
  16685. }
  16686. /* Take connection [idx]. This connection is not locked in
  16687. * any way, so some other thread might use it. */
  16688. conn = (ctx->worker_connections) + idx;
  16689. /* Initialize output string */
  16690. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16691. connection_info_length += (int)strlen(block);
  16692. if (connection_info_length < buflen) {
  16693. strcat0(buffer, block);
  16694. }
  16695. /* Init variables */
  16696. ri = &(conn->request_info);
  16697. #if defined(USE_SERVER_STATS)
  16698. state = conn->conn_state;
  16699. /* State as string */
  16700. switch (state) {
  16701. case 0:
  16702. state_str = "undefined";
  16703. break;
  16704. case 1:
  16705. state_str = "not used";
  16706. break;
  16707. case 2:
  16708. state_str = "init";
  16709. break;
  16710. case 3:
  16711. state_str = "ready";
  16712. break;
  16713. case 4:
  16714. state_str = "processing";
  16715. break;
  16716. case 5:
  16717. state_str = "processed";
  16718. break;
  16719. case 6:
  16720. state_str = "to close";
  16721. break;
  16722. case 7:
  16723. state_str = "closing";
  16724. break;
  16725. case 8:
  16726. state_str = "closed";
  16727. break;
  16728. case 9:
  16729. state_str = "done";
  16730. break;
  16731. }
  16732. #endif
  16733. /* Connection info */
  16734. if ((state >= 3) && (state < 9)) {
  16735. mg_snprintf(NULL,
  16736. NULL,
  16737. block,
  16738. sizeof(block),
  16739. "\"connection\" : {%s"
  16740. "\"remote\" : {%s"
  16741. "\"protocol\" : \"%s\",%s"
  16742. "\"addr\" : \"%s\",%s"
  16743. "\"port\" : %u%s"
  16744. "},%s"
  16745. "\"handled_requests\" : %u%s"
  16746. "},%s",
  16747. eol,
  16748. eol,
  16749. get_proto_name(conn),
  16750. eol,
  16751. ri->remote_addr,
  16752. eol,
  16753. ri->remote_port,
  16754. eol,
  16755. eol,
  16756. conn->handled_requests,
  16757. eol,
  16758. eol);
  16759. connection_info_length += (int)strlen(block);
  16760. if (connection_info_length + reserved_len < buflen) {
  16761. strcat0(buffer, block);
  16762. }
  16763. }
  16764. /* Request info */
  16765. if ((state >= 4) && (state < 6)) {
  16766. mg_snprintf(NULL,
  16767. NULL,
  16768. block,
  16769. sizeof(block),
  16770. "\"request_info\" : {%s"
  16771. "\"method\" : \"%s\",%s"
  16772. "\"uri\" : \"%s\",%s"
  16773. "\"query\" : %s%s%s%s"
  16774. "},%s",
  16775. eol,
  16776. ri->request_method,
  16777. eol,
  16778. ri->request_uri,
  16779. eol,
  16780. ri->query_string ? "\"" : "",
  16781. ri->query_string ? ri->query_string : "null",
  16782. ri->query_string ? "\"" : "",
  16783. eol,
  16784. eol);
  16785. connection_info_length += (int)strlen(block);
  16786. if (connection_info_length + reserved_len < buflen) {
  16787. strcat0(buffer, block);
  16788. }
  16789. }
  16790. /* Execution time information */
  16791. if ((state >= 2) && (state < 9)) {
  16792. char start_time_str[64] = {0};
  16793. char now_str[64] = {0};
  16794. time_t start_time = conn->conn_birth_time;
  16795. time_t now = time(NULL);
  16796. gmt_time_string(start_time_str,
  16797. sizeof(start_time_str) - 1,
  16798. &start_time);
  16799. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16800. mg_snprintf(NULL,
  16801. NULL,
  16802. block,
  16803. sizeof(block),
  16804. "\"time\" : {%s"
  16805. "\"uptime\" : %.0f,%s"
  16806. "\"start\" : \"%s\",%s"
  16807. "\"now\" : \"%s\"%s"
  16808. "},%s",
  16809. eol,
  16810. difftime(now, start_time),
  16811. eol,
  16812. start_time_str,
  16813. eol,
  16814. now_str,
  16815. eol,
  16816. eol);
  16817. connection_info_length += (int)strlen(block);
  16818. if (connection_info_length + reserved_len < buflen) {
  16819. strcat0(buffer, block);
  16820. }
  16821. }
  16822. /* Remote user name */
  16823. if ((ri->remote_user) && (state < 9)) {
  16824. mg_snprintf(NULL,
  16825. NULL,
  16826. block,
  16827. sizeof(block),
  16828. "\"user\" : {%s"
  16829. "\"name\" : \"%s\",%s"
  16830. "},%s",
  16831. eol,
  16832. ri->remote_user,
  16833. eol,
  16834. eol);
  16835. connection_info_length += (int)strlen(block);
  16836. if (connection_info_length + reserved_len < buflen) {
  16837. strcat0(buffer, block);
  16838. }
  16839. }
  16840. /* Data block */
  16841. if (state >= 3) {
  16842. mg_snprintf(NULL,
  16843. NULL,
  16844. block,
  16845. sizeof(block),
  16846. "\"data\" : {%s"
  16847. "\"read\" : %" INT64_FMT ",%s"
  16848. "\"written\" : %" INT64_FMT "%s"
  16849. "},%s",
  16850. eol,
  16851. conn->consumed_content,
  16852. eol,
  16853. conn->num_bytes_sent,
  16854. eol,
  16855. eol);
  16856. connection_info_length += (int)strlen(block);
  16857. if (connection_info_length + reserved_len < buflen) {
  16858. strcat0(buffer, block);
  16859. }
  16860. }
  16861. /* State */
  16862. mg_snprintf(NULL,
  16863. NULL,
  16864. block,
  16865. sizeof(block),
  16866. "\"state\" : \"%s\"%s",
  16867. state_str,
  16868. eol);
  16869. connection_info_length += (int)strlen(block);
  16870. if (connection_info_length + reserved_len < buflen) {
  16871. strcat0(buffer, block);
  16872. }
  16873. /* Terminate string */
  16874. if ((buflen > 0) && buffer && buffer[0]) {
  16875. if (connection_info_length < buflen) {
  16876. strcat0(buffer, eoobj);
  16877. strcat0(buffer, eol);
  16878. }
  16879. }
  16880. connection_info_length += reserved_len;
  16881. return connection_info_length;
  16882. }
  16883. #endif
  16884. /* Get system information. It can be printed or stored by the caller.
  16885. * Return the size of available information. */
  16886. int
  16887. mg_get_system_info(char *buffer, int buflen)
  16888. {
  16889. if ((buffer == NULL) || (buflen < 1)) {
  16890. return mg_get_system_info_impl(NULL, 0);
  16891. } else {
  16892. /* Reset buffer, so we can always use strcat. */
  16893. buffer[0] = 0;
  16894. return mg_get_system_info_impl(buffer, buflen);
  16895. }
  16896. }
  16897. /* Get context information. It can be printed or stored by the caller.
  16898. * Return the size of available information. */
  16899. int
  16900. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16901. {
  16902. #if defined(USE_SERVER_STATS)
  16903. if ((buffer == NULL) || (buflen < 1)) {
  16904. return mg_get_context_info_impl(ctx, NULL, 0);
  16905. } else {
  16906. /* Reset buffer, so we can always use strcat. */
  16907. buffer[0] = 0;
  16908. return mg_get_context_info_impl(ctx, buffer, buflen);
  16909. }
  16910. #else
  16911. (void)ctx;
  16912. if ((buffer != NULL) && (buflen > 0)) {
  16913. buffer[0] = 0;
  16914. }
  16915. return 0;
  16916. #endif
  16917. }
  16918. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16919. int
  16920. mg_get_connection_info(const struct mg_context *ctx,
  16921. int idx,
  16922. char *buffer,
  16923. int buflen)
  16924. {
  16925. if ((buffer == NULL) || (buflen < 1)) {
  16926. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  16927. } else {
  16928. /* Reset buffer, so we can always use strcat. */
  16929. buffer[0] = 0;
  16930. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  16931. }
  16932. }
  16933. #endif
  16934. /* Initialize this library. This function does not need to be thread safe.
  16935. */
  16936. unsigned
  16937. mg_init_library(unsigned features)
  16938. {
  16939. #if !defined(NO_SSL)
  16940. char ebuf[128];
  16941. #endif
  16942. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  16943. unsigned features_inited = features_to_init;
  16944. if (mg_init_library_called <= 0) {
  16945. /* Not initialized yet */
  16946. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  16947. return 0;
  16948. }
  16949. }
  16950. mg_global_lock();
  16951. if (mg_init_library_called <= 0) {
  16952. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  16953. /* Fatal error - abort start. However, this situation should
  16954. * never occur in practice. */
  16955. mg_global_unlock();
  16956. return 0;
  16957. }
  16958. #if defined(_WIN32)
  16959. InitializeCriticalSection(&global_log_file_lock);
  16960. #endif
  16961. #if !defined(_WIN32)
  16962. pthread_mutexattr_init(&pthread_mutex_attr);
  16963. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  16964. #endif
  16965. #if defined(USE_LUA)
  16966. lua_init_optional_libraries();
  16967. #endif
  16968. }
  16969. mg_global_unlock();
  16970. #if !defined(NO_SSL)
  16971. if (features_to_init & MG_FEATURES_SSL) {
  16972. if (!mg_ssl_initialized) {
  16973. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  16974. mg_ssl_initialized = 1;
  16975. } else {
  16976. (void)ebuf;
  16977. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16978. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  16979. }
  16980. } else {
  16981. /* ssl already initialized */
  16982. }
  16983. }
  16984. #endif
  16985. /* Start WinSock for Windows */
  16986. mg_global_lock();
  16987. if (mg_init_library_called <= 0) {
  16988. #if defined(_WIN32)
  16989. WSADATA data;
  16990. WSAStartup(MAKEWORD(2, 2), &data);
  16991. #endif /* _WIN32 */
  16992. mg_init_library_called = 1;
  16993. } else {
  16994. mg_init_library_called++;
  16995. }
  16996. mg_global_unlock();
  16997. return features_inited;
  16998. }
  16999. /* Un-initialize this library. */
  17000. unsigned
  17001. mg_exit_library(void)
  17002. {
  17003. if (mg_init_library_called <= 0) {
  17004. return 0;
  17005. }
  17006. mg_global_lock();
  17007. mg_init_library_called--;
  17008. if (mg_init_library_called == 0) {
  17009. #if defined(_WIN32)
  17010. (void)WSACleanup();
  17011. #endif /* _WIN32 */
  17012. #if !defined(NO_SSL)
  17013. if (mg_ssl_initialized) {
  17014. uninitialize_ssl();
  17015. mg_ssl_initialized = 0;
  17016. }
  17017. #endif
  17018. #if defined(_WIN32)
  17019. (void)DeleteCriticalSection(&global_log_file_lock);
  17020. #endif /* _WIN32 */
  17021. #if !defined(_WIN32)
  17022. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17023. #endif
  17024. (void)pthread_key_delete(sTlsKey);
  17025. #if defined(USE_LUA)
  17026. lua_exit_optional_libraries();
  17027. #endif
  17028. mg_global_unlock();
  17029. (void)pthread_mutex_destroy(&global_lock_mutex);
  17030. return 1;
  17031. }
  17032. mg_global_unlock();
  17033. return 1;
  17034. }
  17035. /* End of civetweb.c */