civetweb.c 526 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716
  1. /* Copyright (c) 2013-2018 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. /* Disable unused macros warnings - not all defines are required
  24. * for all systems and all compilers. */
  25. #pragma GCC diagnostic ignored "-Wunused-macros"
  26. /* A padding warning is just plain useless */
  27. #pragma GCC diagnostic ignored "-Wpadded"
  28. #endif
  29. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  30. /* We must set some flags for the headers we include. These flags
  31. * are reserved ids according to C99, so we need to disable a
  32. * warning for that. */
  33. #pragma GCC diagnostic push
  34. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  35. #endif
  36. #if defined(_WIN32)
  37. #if !defined(_CRT_SECURE_NO_WARNINGS)
  38. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  39. #endif
  40. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  41. #define _WIN32_WINNT 0x0501
  42. #endif
  43. #else
  44. #if !defined(_GNU_SOURCE)
  45. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  46. #endif
  47. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  48. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  49. #endif
  50. #if !defined(_LARGEFILE_SOURCE)
  51. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  52. #endif
  53. #if !defined(_FILE_OFFSET_BITS)
  54. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  55. #endif
  56. #if !defined(__STDC_FORMAT_MACROS)
  57. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  58. #endif
  59. #if !defined(__STDC_LIMIT_MACROS)
  60. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  61. #endif
  62. #if !defined(_DARWIN_UNLIMITED_SELECT)
  63. #define _DARWIN_UNLIMITED_SELECT
  64. #endif
  65. #if defined(__sun)
  66. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  67. #define __inline inline /* not recognized on older compiler versions */
  68. #endif
  69. #endif
  70. #if defined(__clang__)
  71. /* Enable reserved-id-macro warning again. */
  72. #pragma GCC diagnostic pop
  73. #endif
  74. #if defined(USE_LUA)
  75. #define USE_TIMERS
  76. #endif
  77. #if defined(_MSC_VER)
  78. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  79. #pragma warning(disable : 4306)
  80. /* conditional expression is constant: introduced by FD_SET(..) */
  81. #pragma warning(disable : 4127)
  82. /* non-constant aggregate initializer: issued due to missing C99 support */
  83. #pragma warning(disable : 4204)
  84. /* padding added after data member */
  85. #pragma warning(disable : 4820)
  86. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  87. #pragma warning(disable : 4668)
  88. /* no function prototype given: converting '()' to '(void)' */
  89. #pragma warning(disable : 4255)
  90. /* function has been selected for automatic inline expansion */
  91. #pragma warning(disable : 4711)
  92. #endif
  93. /* This code uses static_assert to check some conditions.
  94. * Unfortunately some compilers still do not support it, so we have a
  95. * replacement function here. */
  96. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  97. #define mg_static_assert _Static_assert
  98. #elif defined(__cplusplus) && __cplusplus >= 201103L
  99. #define mg_static_assert static_assert
  100. #else
  101. char static_assert_replacement[1];
  102. #define mg_static_assert(cond, txt) \
  103. extern char static_assert_replacement[(cond) ? 1 : -1]
  104. #endif
  105. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  106. "int data type size check");
  107. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  108. "pointer data type size check");
  109. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  110. /* Alternative queue is well tested and should be the new default */
  111. #if defined(NO_ALTERNATIVE_QUEUE)
  112. #if defined(ALTERNATIVE_QUEUE)
  113. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  114. #endif
  115. #else
  116. #define ALTERNATIVE_QUEUE
  117. #endif
  118. /* DTL -- including winsock2.h works better if lean and mean */
  119. #if !defined(WIN32_LEAN_AND_MEAN)
  120. #define WIN32_LEAN_AND_MEAN
  121. #endif
  122. #if defined(__SYMBIAN32__)
  123. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  124. * Symbian is no longer maintained since 2014-01-01.
  125. * Recent versions of CivetWeb are no longer tested for Symbian.
  126. * It makes no sense, to support an abandoned operating system.
  127. * All remaining "#ifdef __SYMBIAN__" cases will be dropped from
  128. * the code sooner or later.
  129. */
  130. #pragma message \
  131. "Symbian is no longer maintained. CivetWeb will drop Symbian support."
  132. #define NO_SSL /* SSL is not supported */
  133. #define NO_CGI /* CGI is not supported */
  134. #define PATH_MAX FILENAME_MAX
  135. #endif /* __SYMBIAN32__ */
  136. #if !defined(CIVETWEB_HEADER_INCLUDED)
  137. /* Include the header file here, so the CivetWeb interface is defined for the
  138. * entire implementation, including the following forward definitions. */
  139. #include "civetweb.h"
  140. #endif
  141. #if !defined(DEBUG_TRACE)
  142. #if defined(DEBUG)
  143. static void DEBUG_TRACE_FUNC(const char *func,
  144. unsigned line,
  145. PRINTF_FORMAT_STRING(const char *fmt),
  146. ...) PRINTF_ARGS(3, 4);
  147. #define DEBUG_TRACE(fmt, ...) \
  148. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  149. #define NEED_DEBUG_TRACE_FUNC
  150. #else
  151. #define DEBUG_TRACE(fmt, ...) \
  152. do { \
  153. } while (0)
  154. #endif /* DEBUG */
  155. #endif /* DEBUG_TRACE */
  156. #if !defined(DEBUG_ASSERT)
  157. #if defined(DEBUG)
  158. #define DEBUG_ASSERT(cond) \
  159. do { \
  160. if (!(cond)) { \
  161. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  162. exit(2); /* Exit with error */ \
  163. } \
  164. } while (0)
  165. #else
  166. #define DEBUG_ASSERT(cond)
  167. #endif /* DEBUG */
  168. #endif
  169. #if !defined(IGNORE_UNUSED_RESULT)
  170. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  171. #endif
  172. #if defined(__GNUC__) || defined(__MINGW32__)
  173. /* GCC unused function attribute seems fundamentally broken.
  174. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  175. * OR UNUSED" for individual functions failed.
  176. * Either the compiler creates an "unused-function" warning if a
  177. * function is not marked with __attribute__((unused)).
  178. * On the other hand, if the function is marked with this attribute,
  179. * but is used, the compiler raises a completely idiotic
  180. * "used-but-marked-unused" warning - and
  181. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  182. * raises error: unknown option after "#pragma GCC diagnostic".
  183. * Disable this warning completely, until the GCC guys sober up
  184. * again.
  185. */
  186. #pragma GCC diagnostic ignored "-Wunused-function"
  187. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  188. #else
  189. #define FUNCTION_MAY_BE_UNUSED
  190. #endif
  191. /* Some ANSI #includes are not available on Windows CE */
  192. #if !defined(_WIN32_WCE)
  193. #include <sys/types.h>
  194. #include <sys/stat.h>
  195. #include <errno.h>
  196. #include <signal.h>
  197. #include <fcntl.h>
  198. #endif /* !_WIN32_WCE */
  199. #if defined(__clang__)
  200. /* When using -Weverything, clang does not accept it's own headers
  201. * in a release build configuration. Disable what is too much in
  202. * -Weverything. */
  203. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  204. #endif
  205. #if defined(__GNUC__) || defined(__MINGW32__)
  206. /* Who on earth came to the conclusion, using __DATE__ should rise
  207. * an "expansion of date or time macro is not reproducible"
  208. * warning. That's exactly what was intended by using this macro.
  209. * Just disable this nonsense warning. */
  210. /* And disabling them does not work either:
  211. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  212. * #pragma clang diagnostic ignored "-Wdate-time"
  213. * So we just have to disable ALL warnings for some lines
  214. * of code.
  215. * This seems to be a known GCC bug, not resolved since 2012:
  216. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  217. */
  218. #endif
  219. #if defined(__MACH__) /* Apple OSX section */
  220. #if defined(__clang__)
  221. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  222. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  223. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  224. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  225. #endif
  226. #endif
  227. #define CLOCK_MONOTONIC (1)
  228. #define CLOCK_REALTIME (2)
  229. #include <sys/errno.h>
  230. #include <sys/time.h>
  231. #include <mach/clock.h>
  232. #include <mach/mach.h>
  233. #include <mach/mach_time.h>
  234. /* clock_gettime is not implemented on OSX prior to 10.12 */
  235. static int
  236. _civet_clock_gettime(int clk_id, struct timespec *t)
  237. {
  238. memset(t, 0, sizeof(*t));
  239. if (clk_id == CLOCK_REALTIME) {
  240. struct timeval now;
  241. int rv = gettimeofday(&now, NULL);
  242. if (rv) {
  243. return rv;
  244. }
  245. t->tv_sec = now.tv_sec;
  246. t->tv_nsec = now.tv_usec * 1000;
  247. return 0;
  248. } else if (clk_id == CLOCK_MONOTONIC) {
  249. static uint64_t clock_start_time = 0;
  250. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  251. uint64_t now = mach_absolute_time();
  252. if (clock_start_time == 0) {
  253. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  254. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  255. /* appease "unused variable" warning for release builds */
  256. (void)mach_status;
  257. clock_start_time = now;
  258. }
  259. now = (uint64_t)((double)(now - clock_start_time)
  260. * (double)timebase_ifo.numer
  261. / (double)timebase_ifo.denom);
  262. t->tv_sec = now / 1000000000;
  263. t->tv_nsec = now % 1000000000;
  264. return 0;
  265. }
  266. return -1; /* EINVAL - Clock ID is unknown */
  267. }
  268. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  269. #if defined(__CLOCK_AVAILABILITY)
  270. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  271. * declared but it may be NULL at runtime. So we need to check before using
  272. * it. */
  273. static int
  274. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  275. {
  276. if (clock_gettime) {
  277. return clock_gettime(clk_id, t);
  278. }
  279. return _civet_clock_gettime(clk_id, t);
  280. }
  281. #define clock_gettime _civet_safe_clock_gettime
  282. #else
  283. #define clock_gettime _civet_clock_gettime
  284. #endif
  285. #endif
  286. #include <time.h>
  287. #include <stdlib.h>
  288. #include <stdarg.h>
  289. #include <string.h>
  290. #include <ctype.h>
  291. #include <limits.h>
  292. #include <stddef.h>
  293. #include <stdio.h>
  294. #include <stdint.h>
  295. /********************************************************************/
  296. /* CivetWeb configuration defines */
  297. /********************************************************************/
  298. /* Maximum number of threads that can be configured.
  299. * The number of threads actually created depends on the "num_threads"
  300. * configuration parameter, but this is the upper limit. */
  301. #if !defined(MAX_WORKER_THREADS)
  302. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  303. #endif
  304. /* Timeout interval for select/poll calls.
  305. * The timeouts depend on "*_timeout_ms" configuration values, but long
  306. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  307. * This reduces the time required to stop the server. */
  308. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  309. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  310. #endif
  311. /* Do not try to compress files smaller than this limit. */
  312. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  313. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  314. #endif
  315. #if !defined(PASSWORDS_FILE_NAME)
  316. #define PASSWORDS_FILE_NAME ".htpasswd"
  317. #endif
  318. /* Initial buffer size for all CGI environment variables. In case there is
  319. * not enough space, another block is allocated. */
  320. #if !defined(CGI_ENVIRONMENT_SIZE)
  321. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  322. #endif
  323. /* Maximum number of environment variables. */
  324. #if !defined(MAX_CGI_ENVIR_VARS)
  325. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  326. #endif
  327. /* General purpose buffer size. */
  328. #if !defined(MG_BUF_LEN) /* in bytes */
  329. #define MG_BUF_LEN (1024 * 8)
  330. #endif
  331. /* Maximum queue length for pending connections. This value is passed as
  332. * parameter to the "listen" socket call. */
  333. #if !defined(SOMAXCONN)
  334. #define SOMAXCONN (100) /* in pending connections (count) */
  335. #endif
  336. /* Size of the accepted socket queue (in case the old queue implementation
  337. * is used). */
  338. #if !defined(MGSQLEN)
  339. #define MGSQLEN (20) /* count */
  340. #endif
  341. /********************************************************************/
  342. /* Helper makros */
  343. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  344. /* Standard defines */
  345. #if !defined(INT64_MAX)
  346. #define INT64_MAX (9223372036854775807)
  347. #endif
  348. #define SHUTDOWN_RD (0)
  349. #define SHUTDOWN_WR (1)
  350. #define SHUTDOWN_BOTH (2)
  351. mg_static_assert(MAX_WORKER_THREADS >= 1,
  352. "worker threads must be a positive number");
  353. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  354. "size_t data type size check");
  355. #if defined(_WIN32) && !defined(__SYMBIAN32__) /* WINDOWS include block */
  356. #include <windows.h>
  357. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  358. #include <ws2tcpip.h>
  359. typedef const char *SOCK_OPT_TYPE;
  360. #if !defined(PATH_MAX)
  361. #define W_PATH_MAX (MAX_PATH)
  362. /* at most three UTF-8 chars per wchar_t */
  363. #define PATH_MAX (W_PATH_MAX * 3)
  364. #else
  365. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  366. #endif
  367. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  368. #if !defined(_IN_PORT_T)
  369. #if !defined(in_port_t)
  370. #define in_port_t u_short
  371. #endif
  372. #endif
  373. #if !defined(_WIN32_WCE)
  374. #include <process.h>
  375. #include <direct.h>
  376. #include <io.h>
  377. #else /* _WIN32_WCE */
  378. #define NO_CGI /* WinCE has no pipes */
  379. #define NO_POPEN /* WinCE has no popen */
  380. typedef long off_t;
  381. #define errno ((int)(GetLastError()))
  382. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  383. #endif /* _WIN32_WCE */
  384. #define MAKEUQUAD(lo, hi) \
  385. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  386. #define RATE_DIFF (10000000) /* 100 nsecs */
  387. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  388. #define SYS2UNIX_TIME(lo, hi) \
  389. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  390. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  391. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  392. * Also use _strtoui64 on modern M$ compilers */
  393. #if defined(_MSC_VER)
  394. #if (_MSC_VER < 1300)
  395. #define STRX(x) #x
  396. #define STR(x) STRX(x)
  397. #define __func__ __FILE__ ":" STR(__LINE__)
  398. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  399. #define strtoll(x, y, z) (_atoi64(x))
  400. #else
  401. #define __func__ __FUNCTION__
  402. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  403. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  404. #endif
  405. #endif /* _MSC_VER */
  406. #define ERRNO ((int)(GetLastError()))
  407. #define NO_SOCKLEN_T
  408. #if defined(_WIN64) || defined(__MINGW64__)
  409. #if !defined(SSL_LIB)
  410. #define SSL_LIB "ssleay64.dll"
  411. #endif
  412. #if !defined(CRYPTO_LIB)
  413. #define CRYPTO_LIB "libeay64.dll"
  414. #endif
  415. #else
  416. #if !defined(SSL_LIB)
  417. #define SSL_LIB "ssleay32.dll"
  418. #endif
  419. #if !defined(CRYPTO_LIB)
  420. #define CRYPTO_LIB "libeay32.dll"
  421. #endif
  422. #endif
  423. #define O_NONBLOCK (0)
  424. #if !defined(W_OK)
  425. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  426. #endif
  427. #if !defined(EWOULDBLOCK)
  428. #define EWOULDBLOCK WSAEWOULDBLOCK
  429. #endif /* !EWOULDBLOCK */
  430. #define _POSIX_
  431. #define INT64_FMT "I64d"
  432. #define UINT64_FMT "I64u"
  433. #define WINCDECL __cdecl
  434. #define vsnprintf_impl _vsnprintf
  435. #define access _access
  436. #define mg_sleep(x) (Sleep(x))
  437. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  438. #if !defined(popen)
  439. #define popen(x, y) (_popen(x, y))
  440. #endif
  441. #if !defined(pclose)
  442. #define pclose(x) (_pclose(x))
  443. #endif
  444. #define close(x) (_close(x))
  445. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  446. #define RTLD_LAZY (0)
  447. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  448. #define fdopen(x, y) (_fdopen((x), (y)))
  449. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  450. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  451. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  452. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  453. #define sleep(x) (Sleep((x)*1000))
  454. #define rmdir(x) (_rmdir(x))
  455. #if defined(_WIN64) || !defined(__MINGW32__)
  456. /* Only MinGW 32 bit is missing this function */
  457. #define timegm(x) (_mkgmtime(x))
  458. #else
  459. time_t timegm(struct tm *tm);
  460. #define NEED_TIMEGM
  461. #endif
  462. #if !defined(fileno)
  463. #define fileno(x) (_fileno(x))
  464. #endif /* !fileno MINGW #defines fileno */
  465. typedef HANDLE pthread_mutex_t;
  466. typedef DWORD pthread_key_t;
  467. typedef HANDLE pthread_t;
  468. typedef struct {
  469. CRITICAL_SECTION threadIdSec;
  470. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  471. } pthread_cond_t;
  472. #if !defined(__clockid_t_defined)
  473. typedef DWORD clockid_t;
  474. #endif
  475. #if !defined(CLOCK_MONOTONIC)
  476. #define CLOCK_MONOTONIC (1)
  477. #endif
  478. #if !defined(CLOCK_REALTIME)
  479. #define CLOCK_REALTIME (2)
  480. #endif
  481. #if !defined(CLOCK_THREAD)
  482. #define CLOCK_THREAD (3)
  483. #endif
  484. #if !defined(CLOCK_PROCESS)
  485. #define CLOCK_PROCESS (4)
  486. #endif
  487. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  488. #define _TIMESPEC_DEFINED
  489. #endif
  490. #if !defined(_TIMESPEC_DEFINED)
  491. struct timespec {
  492. time_t tv_sec; /* seconds */
  493. long tv_nsec; /* nanoseconds */
  494. };
  495. #endif
  496. #if !defined(WIN_PTHREADS_TIME_H)
  497. #define MUST_IMPLEMENT_CLOCK_GETTIME
  498. #endif
  499. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  500. #define clock_gettime mg_clock_gettime
  501. static int
  502. clock_gettime(clockid_t clk_id, struct timespec *tp)
  503. {
  504. FILETIME ft;
  505. ULARGE_INTEGER li, li2;
  506. BOOL ok = FALSE;
  507. double d;
  508. static double perfcnt_per_sec = 0.0;
  509. static BOOL initialized = FALSE;
  510. if (!initialized) {
  511. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  512. perfcnt_per_sec = 1.0 / li.QuadPart;
  513. initialized = TRUE;
  514. }
  515. if (tp) {
  516. memset(tp, 0, sizeof(*tp));
  517. if (clk_id == CLOCK_REALTIME) {
  518. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  519. GetSystemTimeAsFileTime(&ft);
  520. li.LowPart = ft.dwLowDateTime;
  521. li.HighPart = ft.dwHighDateTime;
  522. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  523. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  524. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  525. ok = TRUE;
  526. /* END: CLOCK_REALTIME */
  527. } else if (clk_id == CLOCK_MONOTONIC) {
  528. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  529. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  530. d = li.QuadPart * perfcnt_per_sec;
  531. tp->tv_sec = (time_t)d;
  532. d -= (double)tp->tv_sec;
  533. tp->tv_nsec = (long)(d * 1.0E9);
  534. ok = TRUE;
  535. /* END: CLOCK_MONOTONIC */
  536. } else if (clk_id == CLOCK_THREAD) {
  537. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  538. FILETIME t_create, t_exit, t_kernel, t_user;
  539. if (GetThreadTimes(GetCurrentThread(),
  540. &t_create,
  541. &t_exit,
  542. &t_kernel,
  543. &t_user)) {
  544. li.LowPart = t_user.dwLowDateTime;
  545. li.HighPart = t_user.dwHighDateTime;
  546. li2.LowPart = t_kernel.dwLowDateTime;
  547. li2.HighPart = t_kernel.dwHighDateTime;
  548. li.QuadPart += li2.QuadPart;
  549. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  550. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  551. ok = TRUE;
  552. }
  553. /* END: CLOCK_THREAD */
  554. } else if (clk_id == CLOCK_PROCESS) {
  555. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  556. FILETIME t_create, t_exit, t_kernel, t_user;
  557. if (GetProcessTimes(GetCurrentProcess(),
  558. &t_create,
  559. &t_exit,
  560. &t_kernel,
  561. &t_user)) {
  562. li.LowPart = t_user.dwLowDateTime;
  563. li.HighPart = t_user.dwHighDateTime;
  564. li2.LowPart = t_kernel.dwLowDateTime;
  565. li2.HighPart = t_kernel.dwHighDateTime;
  566. li.QuadPart += li2.QuadPart;
  567. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  568. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  569. ok = TRUE;
  570. }
  571. /* END: CLOCK_PROCESS */
  572. } else {
  573. /* BEGIN: unknown clock */
  574. /* ok = FALSE; already set by init */
  575. /* END: unknown clock */
  576. }
  577. }
  578. return ok ? 0 : -1;
  579. }
  580. #endif
  581. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  582. static int pthread_mutex_lock(pthread_mutex_t *);
  583. static int pthread_mutex_unlock(pthread_mutex_t *);
  584. static void path_to_unicode(const struct mg_connection *conn,
  585. const char *path,
  586. wchar_t *wbuf,
  587. size_t wbuf_len);
  588. /* All file operations need to be rewritten to solve #246. */
  589. struct mg_file;
  590. static const char *
  591. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  592. /* POSIX dirent interface */
  593. struct dirent {
  594. char d_name[PATH_MAX];
  595. };
  596. typedef struct DIR {
  597. HANDLE handle;
  598. WIN32_FIND_DATAW info;
  599. struct dirent result;
  600. } DIR;
  601. #if defined(_WIN32) && !defined(POLLIN)
  602. #if !defined(HAVE_POLL)
  603. struct pollfd {
  604. SOCKET fd;
  605. short events;
  606. short revents;
  607. };
  608. #define POLLIN (0x0300)
  609. #endif
  610. #endif
  611. /* Mark required libraries */
  612. #if defined(_MSC_VER)
  613. #pragma comment(lib, "Ws2_32.lib")
  614. #endif
  615. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  616. WINDOWS / UNIX include block */
  617. #include <sys/wait.h>
  618. #include <sys/socket.h>
  619. #include <sys/poll.h>
  620. #include <netinet/in.h>
  621. #include <arpa/inet.h>
  622. #include <sys/time.h>
  623. #include <sys/utsname.h>
  624. #include <stdint.h>
  625. #include <inttypes.h>
  626. #include <netdb.h>
  627. #include <netinet/tcp.h>
  628. typedef const void *SOCK_OPT_TYPE;
  629. #if defined(ANDROID)
  630. typedef unsigned short int in_port_t;
  631. #endif
  632. #include <pwd.h>
  633. #include <unistd.h>
  634. #include <grp.h>
  635. #include <dirent.h>
  636. #define vsnprintf_impl vsnprintf
  637. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  638. #include <dlfcn.h>
  639. #endif
  640. #include <pthread.h>
  641. #if defined(__MACH__)
  642. #define SSL_LIB "libssl.dylib"
  643. #define CRYPTO_LIB "libcrypto.dylib"
  644. #else
  645. #if !defined(SSL_LIB)
  646. #define SSL_LIB "libssl.so"
  647. #endif
  648. #if !defined(CRYPTO_LIB)
  649. #define CRYPTO_LIB "libcrypto.so"
  650. #endif
  651. #endif
  652. #if !defined(O_BINARY)
  653. #define O_BINARY (0)
  654. #endif /* O_BINARY */
  655. #define closesocket(a) (close(a))
  656. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  657. #define mg_remove(conn, x) (remove(x))
  658. #define mg_sleep(x) (usleep((x)*1000))
  659. #define mg_opendir(conn, x) (opendir(x))
  660. #define mg_closedir(x) (closedir(x))
  661. #define mg_readdir(x) (readdir(x))
  662. #define ERRNO (errno)
  663. #define INVALID_SOCKET (-1)
  664. #define INT64_FMT PRId64
  665. #define UINT64_FMT PRIu64
  666. typedef int SOCKET;
  667. #define WINCDECL
  668. #if defined(__hpux)
  669. /* HPUX 11 does not have monotonic, fall back to realtime */
  670. #if !defined(CLOCK_MONOTONIC)
  671. #define CLOCK_MONOTONIC CLOCK_REALTIME
  672. #endif
  673. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  674. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  675. * the prototypes use int* rather than socklen_t* which matches the
  676. * actual library expectation. When called with the wrong size arg
  677. * accept() returns a zero client inet addr and check_acl() always
  678. * fails. Since socklen_t is widely used below, just force replace
  679. * their typedef with int. - DTL
  680. */
  681. #define socklen_t int
  682. #endif /* hpux */
  683. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  684. WINDOWS / UNIX include block */
  685. /* In case our C library is missing "timegm", provide an implementation */
  686. #if defined(NEED_TIMEGM)
  687. static inline int
  688. is_leap(int y)
  689. {
  690. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  691. }
  692. static inline int
  693. count_leap(int y)
  694. {
  695. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  696. }
  697. time_t
  698. timegm(struct tm *tm)
  699. {
  700. static const unsigned short ydays[] = {
  701. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  702. int year = tm->tm_year + 1900;
  703. int mon = tm->tm_mon;
  704. int mday = tm->tm_mday - 1;
  705. int hour = tm->tm_hour;
  706. int min = tm->tm_min;
  707. int sec = tm->tm_sec;
  708. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  709. || (mday >= ydays[mon + 1] - ydays[mon]
  710. + (mon == 1 && is_leap(year) ? 1 : 0)) || hour < 0
  711. || hour > 23
  712. || min < 0
  713. || min > 59
  714. || sec < 0
  715. || sec > 60)
  716. return -1;
  717. time_t res = year - 1970;
  718. res *= 365;
  719. res += mday;
  720. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  721. res += count_leap(year);
  722. res *= 24;
  723. res += hour;
  724. res *= 60;
  725. res += min;
  726. res *= 60;
  727. res += sec;
  728. return res;
  729. }
  730. #endif /* NEED_TIMEGM */
  731. /* va_copy should always be a macro, C99 and C++11 - DTL */
  732. #if !defined(va_copy)
  733. #define va_copy(x, y) ((x) = (y))
  734. #endif
  735. #if defined(_WIN32)
  736. /* Create substitutes for POSIX functions in Win32. */
  737. #if defined(__MINGW32__)
  738. /* Show no warning in case system functions are not used. */
  739. #pragma GCC diagnostic push
  740. #pragma GCC diagnostic ignored "-Wunused-function"
  741. #endif
  742. static CRITICAL_SECTION global_log_file_lock;
  743. FUNCTION_MAY_BE_UNUSED
  744. static DWORD
  745. pthread_self(void)
  746. {
  747. return GetCurrentThreadId();
  748. }
  749. FUNCTION_MAY_BE_UNUSED
  750. static int
  751. pthread_key_create(
  752. pthread_key_t *key,
  753. void (*_ignored)(void *) /* destructor not supported for Windows */
  754. )
  755. {
  756. (void)_ignored;
  757. if ((key != 0)) {
  758. *key = TlsAlloc();
  759. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  760. }
  761. return -2;
  762. }
  763. FUNCTION_MAY_BE_UNUSED
  764. static int
  765. pthread_key_delete(pthread_key_t key)
  766. {
  767. return TlsFree(key) ? 0 : 1;
  768. }
  769. FUNCTION_MAY_BE_UNUSED
  770. static int
  771. pthread_setspecific(pthread_key_t key, void *value)
  772. {
  773. return TlsSetValue(key, value) ? 0 : 1;
  774. }
  775. FUNCTION_MAY_BE_UNUSED
  776. static void *
  777. pthread_getspecific(pthread_key_t key)
  778. {
  779. return TlsGetValue(key);
  780. }
  781. #if defined(__MINGW32__)
  782. /* Enable unused function warning again */
  783. #pragma GCC diagnostic pop
  784. #endif
  785. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  786. #else
  787. static pthread_mutexattr_t pthread_mutex_attr;
  788. #endif /* _WIN32 */
  789. #if defined(_WIN32_WCE)
  790. /* Create substitutes for POSIX functions in Win32. */
  791. #if defined(__MINGW32__)
  792. /* Show no warning in case system functions are not used. */
  793. #pragma GCC diagnostic push
  794. #pragma GCC diagnostic ignored "-Wunused-function"
  795. #endif
  796. FUNCTION_MAY_BE_UNUSED
  797. static time_t
  798. time(time_t *ptime)
  799. {
  800. time_t t;
  801. SYSTEMTIME st;
  802. FILETIME ft;
  803. GetSystemTime(&st);
  804. SystemTimeToFileTime(&st, &ft);
  805. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  806. if (ptime != NULL) {
  807. *ptime = t;
  808. }
  809. return t;
  810. }
  811. FUNCTION_MAY_BE_UNUSED
  812. static struct tm *
  813. localtime_s(const time_t *ptime, struct tm *ptm)
  814. {
  815. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  816. FILETIME ft, lft;
  817. SYSTEMTIME st;
  818. TIME_ZONE_INFORMATION tzinfo;
  819. if (ptm == NULL) {
  820. return NULL;
  821. }
  822. *(int64_t *)&ft = t;
  823. FileTimeToLocalFileTime(&ft, &lft);
  824. FileTimeToSystemTime(&lft, &st);
  825. ptm->tm_year = st.wYear - 1900;
  826. ptm->tm_mon = st.wMonth - 1;
  827. ptm->tm_wday = st.wDayOfWeek;
  828. ptm->tm_mday = st.wDay;
  829. ptm->tm_hour = st.wHour;
  830. ptm->tm_min = st.wMinute;
  831. ptm->tm_sec = st.wSecond;
  832. ptm->tm_yday = 0; /* hope nobody uses this */
  833. ptm->tm_isdst =
  834. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  835. return ptm;
  836. }
  837. FUNCTION_MAY_BE_UNUSED
  838. static struct tm *
  839. gmtime_s(const time_t *ptime, struct tm *ptm)
  840. {
  841. /* FIXME(lsm): fix this. */
  842. return localtime_s(ptime, ptm);
  843. }
  844. static int mg_atomic_inc(volatile int *addr);
  845. static struct tm tm_array[MAX_WORKER_THREADS];
  846. static int tm_index = 0;
  847. FUNCTION_MAY_BE_UNUSED
  848. static struct tm *
  849. localtime(const time_t *ptime)
  850. {
  851. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  852. return localtime_s(ptime, tm_array + i);
  853. }
  854. FUNCTION_MAY_BE_UNUSED
  855. static struct tm *
  856. gmtime(const time_t *ptime)
  857. {
  858. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  859. return gmtime_s(ptime, tm_array + i);
  860. }
  861. FUNCTION_MAY_BE_UNUSED
  862. static size_t
  863. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  864. {
  865. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  866. * for WinCE"); */
  867. return 0;
  868. }
  869. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  870. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  871. #define remove(f) mg_remove(NULL, f)
  872. FUNCTION_MAY_BE_UNUSED
  873. static int
  874. rename(const char *a, const char *b)
  875. {
  876. wchar_t wa[W_PATH_MAX];
  877. wchar_t wb[W_PATH_MAX];
  878. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  879. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  880. return MoveFileW(wa, wb) ? 0 : -1;
  881. }
  882. struct stat {
  883. int64_t st_size;
  884. time_t st_mtime;
  885. };
  886. FUNCTION_MAY_BE_UNUSED
  887. static int
  888. stat(const char *name, struct stat *st)
  889. {
  890. wchar_t wbuf[W_PATH_MAX];
  891. WIN32_FILE_ATTRIBUTE_DATA attr;
  892. time_t creation_time, write_time;
  893. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  894. memset(&attr, 0, sizeof(attr));
  895. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  896. st->st_size =
  897. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  898. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  899. attr.ftLastWriteTime.dwHighDateTime);
  900. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  901. attr.ftCreationTime.dwHighDateTime);
  902. if (creation_time > write_time) {
  903. st->st_mtime = creation_time;
  904. } else {
  905. st->st_mtime = write_time;
  906. }
  907. return 0;
  908. }
  909. #define access(x, a) 1 /* not required anyway */
  910. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  911. /* Values from errno.h in Windows SDK (Visual Studio). */
  912. #define EEXIST 17
  913. #define EACCES 13
  914. #define ENOENT 2
  915. #if defined(__MINGW32__)
  916. /* Enable unused function warning again */
  917. #pragma GCC diagnostic pop
  918. #endif
  919. #endif /* defined(_WIN32_WCE) */
  920. #if defined(__GNUC__) || defined(__MINGW32__)
  921. /* Show no warning in case system functions are not used. */
  922. #define GCC_VERSION \
  923. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  924. #if GCC_VERSION >= 40500
  925. #pragma GCC diagnostic push
  926. #pragma GCC diagnostic ignored "-Wunused-function"
  927. #endif /* GCC_VERSION >= 40500 */
  928. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  929. #if defined(__clang__)
  930. /* Show no warning in case system functions are not used. */
  931. #pragma clang diagnostic push
  932. #pragma clang diagnostic ignored "-Wunused-function"
  933. #endif
  934. static pthread_mutex_t global_lock_mutex;
  935. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  936. /* Forward declaration for Windows */
  937. FUNCTION_MAY_BE_UNUSED
  938. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  939. FUNCTION_MAY_BE_UNUSED
  940. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  941. #endif
  942. FUNCTION_MAY_BE_UNUSED
  943. static void
  944. mg_global_lock(void)
  945. {
  946. (void)pthread_mutex_lock(&global_lock_mutex);
  947. }
  948. FUNCTION_MAY_BE_UNUSED
  949. static void
  950. mg_global_unlock(void)
  951. {
  952. (void)pthread_mutex_unlock(&global_lock_mutex);
  953. }
  954. FUNCTION_MAY_BE_UNUSED
  955. static int
  956. mg_atomic_inc(volatile int *addr)
  957. {
  958. int ret;
  959. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  960. /* Depending on the SDK, this function uses either
  961. * (volatile unsigned int *) or (volatile LONG *),
  962. * so whatever you use, the other SDK is likely to raise a warning. */
  963. ret = InterlockedIncrement((volatile long *)addr);
  964. #elif defined(__GNUC__) \
  965. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  966. && !defined(NO_ATOMICS)
  967. ret = __sync_add_and_fetch(addr, 1);
  968. #else
  969. mg_global_lock();
  970. ret = (++(*addr));
  971. mg_global_unlock();
  972. #endif
  973. return ret;
  974. }
  975. FUNCTION_MAY_BE_UNUSED
  976. static int
  977. mg_atomic_dec(volatile int *addr)
  978. {
  979. int ret;
  980. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  981. /* Depending on the SDK, this function uses either
  982. * (volatile unsigned int *) or (volatile LONG *),
  983. * so whatever you use, the other SDK is likely to raise a warning. */
  984. ret = InterlockedDecrement((volatile long *)addr);
  985. #elif defined(__GNUC__) \
  986. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  987. && !defined(NO_ATOMICS)
  988. ret = __sync_sub_and_fetch(addr, 1);
  989. #else
  990. mg_global_lock();
  991. ret = (--(*addr));
  992. mg_global_unlock();
  993. #endif
  994. return ret;
  995. }
  996. #if defined(USE_SERVER_STATS)
  997. static int64_t
  998. mg_atomic_add(volatile int64_t *addr, int64_t value)
  999. {
  1000. int64_t ret;
  1001. #if defined(_WIN64) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  1002. ret = InterlockedAdd64(addr, value);
  1003. #elif defined(__GNUC__) \
  1004. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1005. && !defined(NO_ATOMICS)
  1006. ret = __sync_add_and_fetch(addr, value);
  1007. #else
  1008. mg_global_lock();
  1009. *addr += value;
  1010. ret = (*addr);
  1011. mg_global_unlock();
  1012. #endif
  1013. return ret;
  1014. }
  1015. #endif
  1016. #if defined(__GNUC__)
  1017. /* Show no warning in case system functions are not used. */
  1018. #if GCC_VERSION >= 40500
  1019. #pragma GCC diagnostic pop
  1020. #endif /* GCC_VERSION >= 40500 */
  1021. #endif /* defined(__GNUC__) */
  1022. #if defined(__clang__)
  1023. /* Show no warning in case system functions are not used. */
  1024. #pragma clang diagnostic pop
  1025. #endif
  1026. #if defined(USE_SERVER_STATS)
  1027. struct mg_memory_stat {
  1028. volatile int64_t totalMemUsed;
  1029. volatile int64_t maxMemUsed;
  1030. volatile int blockCount;
  1031. };
  1032. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1033. static void *
  1034. mg_malloc_ex(size_t size,
  1035. struct mg_context *ctx,
  1036. const char *file,
  1037. unsigned line)
  1038. {
  1039. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1040. void *memory = 0;
  1041. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1042. #if defined(MEMORY_DEBUGGING)
  1043. char mallocStr[256];
  1044. #else
  1045. (void)file;
  1046. (void)line;
  1047. #endif
  1048. if (data) {
  1049. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1050. if (mmem > mstat->maxMemUsed) {
  1051. /* could use atomic compare exchange, but this
  1052. * seems overkill for statistics data */
  1053. mstat->maxMemUsed = mmem;
  1054. }
  1055. mg_atomic_inc(&mstat->blockCount);
  1056. ((uintptr_t *)data)[0] = size;
  1057. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1058. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1059. }
  1060. #if defined(MEMORY_DEBUGGING)
  1061. sprintf(mallocStr,
  1062. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1063. memory,
  1064. (unsigned long)size,
  1065. (unsigned long)mstat->totalMemUsed,
  1066. (unsigned long)mstat->blockCount,
  1067. file,
  1068. line);
  1069. #if defined(_WIN32)
  1070. OutputDebugStringA(mallocStr);
  1071. #else
  1072. DEBUG_TRACE("%s", mallocStr);
  1073. #endif
  1074. #endif
  1075. return memory;
  1076. }
  1077. static void *
  1078. mg_calloc_ex(size_t count,
  1079. size_t size,
  1080. struct mg_context *ctx,
  1081. const char *file,
  1082. unsigned line)
  1083. {
  1084. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1085. if (data) {
  1086. memset(data, 0, size * count);
  1087. }
  1088. return data;
  1089. }
  1090. static void
  1091. mg_free_ex(void *memory, const char *file, unsigned line)
  1092. {
  1093. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1094. #if defined(MEMORY_DEBUGGING)
  1095. char mallocStr[256];
  1096. #else
  1097. (void)file;
  1098. (void)line;
  1099. #endif
  1100. if (memory) {
  1101. uintptr_t size = ((uintptr_t *)data)[0];
  1102. struct mg_memory_stat *mstat =
  1103. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1104. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1105. mg_atomic_dec(&mstat->blockCount);
  1106. #if defined(MEMORY_DEBUGGING)
  1107. sprintf(mallocStr,
  1108. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1109. memory,
  1110. (unsigned long)size,
  1111. (unsigned long)mstat->totalMemUsed,
  1112. (unsigned long)mstat->blockCount,
  1113. file,
  1114. line);
  1115. #if defined(_WIN32)
  1116. OutputDebugStringA(mallocStr);
  1117. #else
  1118. DEBUG_TRACE("%s", mallocStr);
  1119. #endif
  1120. #endif
  1121. free(data);
  1122. }
  1123. }
  1124. static void *
  1125. mg_realloc_ex(void *memory,
  1126. size_t newsize,
  1127. struct mg_context *ctx,
  1128. const char *file,
  1129. unsigned line)
  1130. {
  1131. void *data;
  1132. void *_realloc;
  1133. uintptr_t oldsize;
  1134. #if defined(MEMORY_DEBUGGING)
  1135. char mallocStr[256];
  1136. #else
  1137. (void)file;
  1138. (void)line;
  1139. #endif
  1140. if (newsize) {
  1141. if (memory) {
  1142. /* Reallocate existing block */
  1143. struct mg_memory_stat *mstat;
  1144. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1145. oldsize = ((uintptr_t *)data)[0];
  1146. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1147. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1148. if (_realloc) {
  1149. data = _realloc;
  1150. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1151. #if defined(MEMORY_DEBUGGING)
  1152. sprintf(mallocStr,
  1153. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1154. memory,
  1155. (unsigned long)oldsize,
  1156. (unsigned long)mstat->totalMemUsed,
  1157. (unsigned long)mstat->blockCount,
  1158. file,
  1159. line);
  1160. #if defined(_WIN32)
  1161. OutputDebugStringA(mallocStr);
  1162. #else
  1163. DEBUG_TRACE("%s", mallocStr);
  1164. #endif
  1165. #endif
  1166. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1167. #if defined(MEMORY_DEBUGGING)
  1168. sprintf(mallocStr,
  1169. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1170. memory,
  1171. (unsigned long)newsize,
  1172. (unsigned long)mstat->totalMemUsed,
  1173. (unsigned long)mstat->blockCount,
  1174. file,
  1175. line);
  1176. #if defined(_WIN32)
  1177. OutputDebugStringA(mallocStr);
  1178. #else
  1179. DEBUG_TRACE("%s", mallocStr);
  1180. #endif
  1181. #endif
  1182. *(uintptr_t *)data = newsize;
  1183. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1184. } else {
  1185. #if defined(MEMORY_DEBUGGING)
  1186. #if defined(_WIN32)
  1187. OutputDebugStringA("MEM: realloc failed\n");
  1188. #else
  1189. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1190. #endif
  1191. #endif
  1192. return _realloc;
  1193. }
  1194. } else {
  1195. /* Allocate new block */
  1196. data = mg_malloc_ex(newsize, ctx, file, line);
  1197. }
  1198. } else {
  1199. /* Free existing block */
  1200. data = 0;
  1201. mg_free_ex(memory, file, line);
  1202. }
  1203. return data;
  1204. }
  1205. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1206. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1207. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1208. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1209. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1210. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1211. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1212. #else /* USE_SERVER_STATS */
  1213. static __inline void *
  1214. mg_malloc(size_t a)
  1215. {
  1216. return malloc(a);
  1217. }
  1218. static __inline void *
  1219. mg_calloc(size_t a, size_t b)
  1220. {
  1221. return calloc(a, b);
  1222. }
  1223. static __inline void *
  1224. mg_realloc(void *a, size_t b)
  1225. {
  1226. return realloc(a, b);
  1227. }
  1228. static __inline void
  1229. mg_free(void *a)
  1230. {
  1231. free(a);
  1232. }
  1233. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1234. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1235. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1236. #define mg_free_ctx(a, c) mg_free(a)
  1237. #endif /* USE_SERVER_STATS */
  1238. static void mg_vsnprintf(const struct mg_connection *conn,
  1239. int *truncated,
  1240. char *buf,
  1241. size_t buflen,
  1242. const char *fmt,
  1243. va_list ap);
  1244. static void mg_snprintf(const struct mg_connection *conn,
  1245. int *truncated,
  1246. char *buf,
  1247. size_t buflen,
  1248. PRINTF_FORMAT_STRING(const char *fmt),
  1249. ...) PRINTF_ARGS(5, 6);
  1250. /* This following lines are just meant as a reminder to use the mg-functions
  1251. * for memory management */
  1252. #if defined(malloc)
  1253. #undef malloc
  1254. #endif
  1255. #if defined(calloc)
  1256. #undef calloc
  1257. #endif
  1258. #if defined(realloc)
  1259. #undef realloc
  1260. #endif
  1261. #if defined(free)
  1262. #undef free
  1263. #endif
  1264. #if defined(snprintf)
  1265. #undef snprintf
  1266. #endif
  1267. #if defined(vsnprintf)
  1268. #undef vsnprintf
  1269. #endif
  1270. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1271. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1272. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1273. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1274. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1275. #if defined(_WIN32)
  1276. /* vsnprintf must not be used in any system,
  1277. * but this define only works well for Windows. */
  1278. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1279. #endif
  1280. /* mg_init_library counter */
  1281. static int mg_init_library_called = 0;
  1282. #if !defined(NO_SSL)
  1283. static int mg_ssl_initialized = 0;
  1284. #endif
  1285. static pthread_key_t sTlsKey; /* Thread local storage index */
  1286. static int thread_idx_max = 0;
  1287. #if defined(MG_LEGACY_INTERFACE)
  1288. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1289. #endif
  1290. struct mg_workerTLS {
  1291. int is_master;
  1292. unsigned long thread_idx;
  1293. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1294. HANDLE pthread_cond_helper_mutex;
  1295. struct mg_workerTLS *next_waiting_thread;
  1296. #endif
  1297. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1298. char txtbuf[4];
  1299. #endif
  1300. };
  1301. #if defined(__GNUC__) || defined(__MINGW32__)
  1302. /* Show no warning in case system functions are not used. */
  1303. #if GCC_VERSION >= 40500
  1304. #pragma GCC diagnostic push
  1305. #pragma GCC diagnostic ignored "-Wunused-function"
  1306. #endif /* GCC_VERSION >= 40500 */
  1307. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1308. #if defined(__clang__)
  1309. /* Show no warning in case system functions are not used. */
  1310. #pragma clang diagnostic push
  1311. #pragma clang diagnostic ignored "-Wunused-function"
  1312. #endif
  1313. /* Get a unique thread ID as unsigned long, independent from the data type
  1314. * of thread IDs defined by the operating system API.
  1315. * If two calls to mg_current_thread_id return the same value, they calls
  1316. * are done from the same thread. If they return different values, they are
  1317. * done from different threads. (Provided this function is used in the same
  1318. * process context and threads are not repeatedly created and deleted, but
  1319. * CivetWeb does not do that).
  1320. * This function must match the signature required for SSL id callbacks:
  1321. * CRYPTO_set_id_callback
  1322. */
  1323. FUNCTION_MAY_BE_UNUSED
  1324. static unsigned long
  1325. mg_current_thread_id(void)
  1326. {
  1327. #if defined(_WIN32)
  1328. return GetCurrentThreadId();
  1329. #else
  1330. #if defined(__clang__)
  1331. #pragma clang diagnostic push
  1332. #pragma clang diagnostic ignored "-Wunreachable-code"
  1333. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1334. * or not, so one of the two conditions will be unreachable by construction.
  1335. * Unfortunately the C standard does not define a way to check this at
  1336. * compile time, since the #if preprocessor conditions can not use the sizeof
  1337. * operator as an argument. */
  1338. #endif
  1339. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1340. /* This is the problematic case for CRYPTO_set_id_callback:
  1341. * The OS pthread_t can not be cast to unsigned long. */
  1342. struct mg_workerTLS *tls =
  1343. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1344. if (tls == NULL) {
  1345. /* SSL called from an unknown thread: Create some thread index.
  1346. */
  1347. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1348. tls->is_master = -2; /* -2 means "3rd party thread" */
  1349. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1350. pthread_setspecific(sTlsKey, tls);
  1351. }
  1352. return tls->thread_idx;
  1353. } else {
  1354. /* pthread_t may be any data type, so a simple cast to unsigned long
  1355. * can rise a warning/error, depending on the platform.
  1356. * Here memcpy is used as an anything-to-anything cast. */
  1357. unsigned long ret = 0;
  1358. pthread_t t = pthread_self();
  1359. memcpy(&ret, &t, sizeof(pthread_t));
  1360. return ret;
  1361. }
  1362. #if defined(__clang__)
  1363. #pragma clang diagnostic pop
  1364. #endif
  1365. #endif
  1366. }
  1367. FUNCTION_MAY_BE_UNUSED
  1368. static uint64_t
  1369. mg_get_current_time_ns(void)
  1370. {
  1371. struct timespec tsnow;
  1372. clock_gettime(CLOCK_REALTIME, &tsnow);
  1373. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1374. }
  1375. #if defined(__GNUC__)
  1376. /* Show no warning in case system functions are not used. */
  1377. #if GCC_VERSION >= 40500
  1378. #pragma GCC diagnostic pop
  1379. #endif /* GCC_VERSION >= 40500 */
  1380. #endif /* defined(__GNUC__) */
  1381. #if defined(__clang__)
  1382. /* Show no warning in case system functions are not used. */
  1383. #pragma clang diagnostic pop
  1384. #endif
  1385. #if defined(NEED_DEBUG_TRACE_FUNC)
  1386. static void
  1387. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1388. {
  1389. va_list args;
  1390. uint64_t nsnow;
  1391. static uint64_t nslast;
  1392. struct timespec tsnow;
  1393. /* Get some operating system independent thread id */
  1394. unsigned long thread_id = mg_current_thread_id();
  1395. clock_gettime(CLOCK_REALTIME, &tsnow);
  1396. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1397. + ((uint64_t)tsnow.tv_nsec);
  1398. if (!nslast) {
  1399. nslast = nsnow;
  1400. }
  1401. flockfile(stdout);
  1402. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1403. (unsigned long)tsnow.tv_sec,
  1404. (unsigned long)tsnow.tv_nsec,
  1405. nsnow - nslast,
  1406. thread_id,
  1407. func,
  1408. line);
  1409. va_start(args, fmt);
  1410. vprintf(fmt, args);
  1411. va_end(args);
  1412. putchar('\n');
  1413. fflush(stdout);
  1414. funlockfile(stdout);
  1415. nslast = nsnow;
  1416. }
  1417. #endif /* NEED_DEBUG_TRACE_FUNC */
  1418. #define MD5_STATIC static
  1419. #include "md5.inl"
  1420. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1421. #if defined(NO_SOCKLEN_T)
  1422. typedef int socklen_t;
  1423. #endif /* NO_SOCKLEN_T */
  1424. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1425. #if !defined(MSG_NOSIGNAL)
  1426. #define MSG_NOSIGNAL (0)
  1427. #endif
  1428. #if defined(NO_SSL)
  1429. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1430. typedef struct SSL_CTX SSL_CTX;
  1431. #else
  1432. #if defined(NO_SSL_DL)
  1433. #include <openssl/ssl.h>
  1434. #include <openssl/err.h>
  1435. #include <openssl/crypto.h>
  1436. #include <openssl/x509.h>
  1437. #include <openssl/pem.h>
  1438. #include <openssl/engine.h>
  1439. #include <openssl/conf.h>
  1440. #include <openssl/dh.h>
  1441. #include <openssl/bn.h>
  1442. #include <openssl/opensslv.h>
  1443. #if defined(WOLFSSL_VERSION)
  1444. /* Additional defines for WolfSSL, see
  1445. * https://github.com/civetweb/civetweb/issues/583 */
  1446. #include "wolfssl_extras.inl"
  1447. #endif
  1448. #else
  1449. /* SSL loaded dynamically from DLL.
  1450. * I put the prototypes here to be independent from OpenSSL source
  1451. * installation. */
  1452. typedef struct ssl_st SSL;
  1453. typedef struct ssl_method_st SSL_METHOD;
  1454. typedef struct ssl_ctx_st SSL_CTX;
  1455. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1456. typedef struct x509_name X509_NAME;
  1457. typedef struct asn1_integer ASN1_INTEGER;
  1458. typedef struct bignum BIGNUM;
  1459. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1460. typedef struct evp_md EVP_MD;
  1461. typedef struct x509 X509;
  1462. #define SSL_CTRL_OPTIONS (32)
  1463. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1464. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1465. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1466. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1467. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1468. #define SSL_VERIFY_NONE (0)
  1469. #define SSL_VERIFY_PEER (1)
  1470. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1471. #define SSL_VERIFY_CLIENT_ONCE (4)
  1472. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1473. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1474. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1475. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1476. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1477. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1478. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1479. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1480. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1481. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1482. #define SSL_CB_HANDSHAKE_START (0x10)
  1483. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1484. #define SSL_ERROR_NONE (0)
  1485. #define SSL_ERROR_SSL (1)
  1486. #define SSL_ERROR_WANT_READ (2)
  1487. #define SSL_ERROR_WANT_WRITE (3)
  1488. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1489. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1490. #define SSL_ERROR_ZERO_RETURN (6)
  1491. #define SSL_ERROR_WANT_CONNECT (7)
  1492. #define SSL_ERROR_WANT_ACCEPT (8)
  1493. #define TLSEXT_TYPE_server_name (0)
  1494. #define TLSEXT_NAMETYPE_host_name (0)
  1495. #define SSL_TLSEXT_ERR_OK (0)
  1496. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1497. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1498. #define SSL_TLSEXT_ERR_NOACK (3)
  1499. struct ssl_func {
  1500. const char *name; /* SSL function name */
  1501. void (*ptr)(void); /* Function pointer */
  1502. };
  1503. #if defined(OPENSSL_API_1_1)
  1504. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1505. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1506. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1507. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1508. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1509. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1510. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1511. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1512. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1513. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1514. #define OPENSSL_init_ssl \
  1515. (*(int (*)(uint64_t opts, \
  1516. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1517. #define SSL_CTX_use_PrivateKey_file \
  1518. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1519. #define SSL_CTX_use_certificate_file \
  1520. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1521. #define SSL_CTX_set_default_passwd_cb \
  1522. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1523. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1524. #define SSL_CTX_use_certificate_chain_file \
  1525. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1526. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1527. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1528. #define SSL_CTX_set_verify \
  1529. (*(void (*)(SSL_CTX *, \
  1530. int, \
  1531. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1532. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1533. #define SSL_CTX_load_verify_locations \
  1534. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1535. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1536. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1537. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1538. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1539. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1540. #define SSL_CIPHER_get_name \
  1541. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1542. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1543. #define SSL_CTX_set_session_id_context \
  1544. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1545. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1546. #define SSL_CTX_set_cipher_list \
  1547. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1548. #define SSL_CTX_set_options \
  1549. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1550. #define SSL_CTX_set_info_callback \
  1551. (*(void (*)(SSL_CTX * ctx, \
  1552. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1553. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1554. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1555. #define SSL_CTX_callback_ctrl \
  1556. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1557. #define SSL_get_servername \
  1558. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1559. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1560. #define SSL_CTX_clear_options(ctx, op) \
  1561. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1562. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1563. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1564. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1565. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1566. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1567. SSL_CTX_callback_ctrl(ctx, \
  1568. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1569. (void (*)(void))cb)
  1570. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1571. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1572. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1573. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1574. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1575. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1576. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1577. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1578. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1579. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1580. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1581. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1582. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1583. #define X509_NAME_oneline \
  1584. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1585. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1586. #define EVP_get_digestbyname \
  1587. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1588. #define EVP_Digest \
  1589. (*(int (*)( \
  1590. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1591. crypto_sw[10].ptr)
  1592. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1593. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1594. #define ASN1_INTEGER_to_BN \
  1595. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1596. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1597. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1598. #define OPENSSL_free(a) CRYPTO_free(a)
  1599. /* init_ssl_ctx() function updates this array.
  1600. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1601. * of respective functions. The macros above (like SSL_connect()) are really
  1602. * just calling these functions indirectly via the pointer. */
  1603. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1604. {"SSL_accept", NULL},
  1605. {"SSL_connect", NULL},
  1606. {"SSL_read", NULL},
  1607. {"SSL_write", NULL},
  1608. {"SSL_get_error", NULL},
  1609. {"SSL_set_fd", NULL},
  1610. {"SSL_new", NULL},
  1611. {"SSL_CTX_new", NULL},
  1612. {"TLS_server_method", NULL},
  1613. {"OPENSSL_init_ssl", NULL},
  1614. {"SSL_CTX_use_PrivateKey_file", NULL},
  1615. {"SSL_CTX_use_certificate_file", NULL},
  1616. {"SSL_CTX_set_default_passwd_cb", NULL},
  1617. {"SSL_CTX_free", NULL},
  1618. {"SSL_CTX_use_certificate_chain_file", NULL},
  1619. {"TLS_client_method", NULL},
  1620. {"SSL_pending", NULL},
  1621. {"SSL_CTX_set_verify", NULL},
  1622. {"SSL_shutdown", NULL},
  1623. {"SSL_CTX_load_verify_locations", NULL},
  1624. {"SSL_CTX_set_default_verify_paths", NULL},
  1625. {"SSL_CTX_set_verify_depth", NULL},
  1626. {"SSL_get_peer_certificate", NULL},
  1627. {"SSL_get_version", NULL},
  1628. {"SSL_get_current_cipher", NULL},
  1629. {"SSL_CIPHER_get_name", NULL},
  1630. {"SSL_CTX_check_private_key", NULL},
  1631. {"SSL_CTX_set_session_id_context", NULL},
  1632. {"SSL_CTX_ctrl", NULL},
  1633. {"SSL_CTX_set_cipher_list", NULL},
  1634. {"SSL_CTX_set_options", NULL},
  1635. {"SSL_CTX_set_info_callback", NULL},
  1636. {"SSL_get_ex_data", NULL},
  1637. {"SSL_set_ex_data", NULL},
  1638. {"SSL_CTX_callback_ctrl", NULL},
  1639. {"SSL_get_servername", NULL},
  1640. {"SSL_set_SSL_CTX", NULL},
  1641. {NULL, NULL}};
  1642. /* Similar array as ssl_sw. These functions could be located in different
  1643. * lib. */
  1644. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1645. {"ERR_error_string", NULL},
  1646. {"ERR_remove_state", NULL},
  1647. {"CONF_modules_unload", NULL},
  1648. {"X509_free", NULL},
  1649. {"X509_get_subject_name", NULL},
  1650. {"X509_get_issuer_name", NULL},
  1651. {"X509_NAME_oneline", NULL},
  1652. {"X509_get_serialNumber", NULL},
  1653. {"EVP_get_digestbyname", NULL},
  1654. {"EVP_Digest", NULL},
  1655. {"i2d_X509", NULL},
  1656. {"BN_bn2hex", NULL},
  1657. {"ASN1_INTEGER_to_BN", NULL},
  1658. {"BN_free", NULL},
  1659. {"CRYPTO_free", NULL},
  1660. {NULL, NULL}};
  1661. #else
  1662. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1663. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1664. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1665. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1666. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1667. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1668. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1669. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1670. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1671. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1672. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1673. #define SSL_CTX_use_PrivateKey_file \
  1674. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1675. #define SSL_CTX_use_certificate_file \
  1676. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1677. #define SSL_CTX_set_default_passwd_cb \
  1678. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1679. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1680. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1681. #define SSL_CTX_use_certificate_chain_file \
  1682. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1683. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1684. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1685. #define SSL_CTX_set_verify \
  1686. (*(void (*)(SSL_CTX *, \
  1687. int, \
  1688. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1689. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1690. #define SSL_CTX_load_verify_locations \
  1691. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1692. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1693. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1694. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1695. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1696. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1697. #define SSL_CIPHER_get_name \
  1698. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1699. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1700. #define SSL_CTX_set_session_id_context \
  1701. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1702. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1703. #define SSL_CTX_set_cipher_list \
  1704. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1705. #define SSL_CTX_set_info_callback \
  1706. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1707. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1708. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1709. #define SSL_CTX_callback_ctrl \
  1710. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1711. #define SSL_get_servername \
  1712. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1713. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1714. #define SSL_CTX_set_options(ctx, op) \
  1715. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1716. #define SSL_CTX_clear_options(ctx, op) \
  1717. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1718. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1719. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1720. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1721. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1722. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1723. SSL_CTX_callback_ctrl(ctx, \
  1724. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1725. (void (*)(void))cb)
  1726. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1727. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1728. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1729. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1730. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1731. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1732. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1733. #define CRYPTO_set_locking_callback \
  1734. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1735. #define CRYPTO_set_id_callback \
  1736. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1737. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1738. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1739. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1740. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1741. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1742. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1743. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1744. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1745. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1746. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1747. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1748. #define X509_NAME_oneline \
  1749. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1750. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1751. #define i2c_ASN1_INTEGER \
  1752. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1753. #define EVP_get_digestbyname \
  1754. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1755. #define EVP_Digest \
  1756. (*(int (*)( \
  1757. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1758. crypto_sw[18].ptr)
  1759. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1760. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1761. #define ASN1_INTEGER_to_BN \
  1762. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1763. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1764. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1765. #define OPENSSL_free(a) CRYPTO_free(a)
  1766. /* init_ssl_ctx() function updates this array.
  1767. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1768. * of respective functions. The macros above (like SSL_connect()) are really
  1769. * just calling these functions indirectly via the pointer. */
  1770. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1771. {"SSL_accept", NULL},
  1772. {"SSL_connect", NULL},
  1773. {"SSL_read", NULL},
  1774. {"SSL_write", NULL},
  1775. {"SSL_get_error", NULL},
  1776. {"SSL_set_fd", NULL},
  1777. {"SSL_new", NULL},
  1778. {"SSL_CTX_new", NULL},
  1779. {"SSLv23_server_method", NULL},
  1780. {"SSL_library_init", NULL},
  1781. {"SSL_CTX_use_PrivateKey_file", NULL},
  1782. {"SSL_CTX_use_certificate_file", NULL},
  1783. {"SSL_CTX_set_default_passwd_cb", NULL},
  1784. {"SSL_CTX_free", NULL},
  1785. {"SSL_load_error_strings", NULL},
  1786. {"SSL_CTX_use_certificate_chain_file", NULL},
  1787. {"SSLv23_client_method", NULL},
  1788. {"SSL_pending", NULL},
  1789. {"SSL_CTX_set_verify", NULL},
  1790. {"SSL_shutdown", NULL},
  1791. {"SSL_CTX_load_verify_locations", NULL},
  1792. {"SSL_CTX_set_default_verify_paths", NULL},
  1793. {"SSL_CTX_set_verify_depth", NULL},
  1794. {"SSL_get_peer_certificate", NULL},
  1795. {"SSL_get_version", NULL},
  1796. {"SSL_get_current_cipher", NULL},
  1797. {"SSL_CIPHER_get_name", NULL},
  1798. {"SSL_CTX_check_private_key", NULL},
  1799. {"SSL_CTX_set_session_id_context", NULL},
  1800. {"SSL_CTX_ctrl", NULL},
  1801. {"SSL_CTX_set_cipher_list", NULL},
  1802. {"SSL_CTX_set_info_callback", NULL},
  1803. {"SSL_get_ex_data", NULL},
  1804. {"SSL_set_ex_data", NULL},
  1805. {"SSL_CTX_callback_ctrl", NULL},
  1806. {"SSL_get_servername", NULL},
  1807. {"SSL_set_SSL_CTX", NULL},
  1808. {NULL, NULL}};
  1809. /* Similar array as ssl_sw. These functions could be located in different
  1810. * lib. */
  1811. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1812. {"CRYPTO_set_locking_callback", NULL},
  1813. {"CRYPTO_set_id_callback", NULL},
  1814. {"ERR_get_error", NULL},
  1815. {"ERR_error_string", NULL},
  1816. {"ERR_remove_state", NULL},
  1817. {"ERR_free_strings", NULL},
  1818. {"ENGINE_cleanup", NULL},
  1819. {"CONF_modules_unload", NULL},
  1820. {"CRYPTO_cleanup_all_ex_data", NULL},
  1821. {"EVP_cleanup", NULL},
  1822. {"X509_free", NULL},
  1823. {"X509_get_subject_name", NULL},
  1824. {"X509_get_issuer_name", NULL},
  1825. {"X509_NAME_oneline", NULL},
  1826. {"X509_get_serialNumber", NULL},
  1827. {"i2c_ASN1_INTEGER", NULL},
  1828. {"EVP_get_digestbyname", NULL},
  1829. {"EVP_Digest", NULL},
  1830. {"i2d_X509", NULL},
  1831. {"BN_bn2hex", NULL},
  1832. {"ASN1_INTEGER_to_BN", NULL},
  1833. {"BN_free", NULL},
  1834. {"CRYPTO_free", NULL},
  1835. {NULL, NULL}};
  1836. #endif /* OPENSSL_API_1_1 */
  1837. #endif /* NO_SSL_DL */
  1838. #endif /* NO_SSL */
  1839. #if !defined(NO_CACHING)
  1840. static const char *month_names[] = {"Jan",
  1841. "Feb",
  1842. "Mar",
  1843. "Apr",
  1844. "May",
  1845. "Jun",
  1846. "Jul",
  1847. "Aug",
  1848. "Sep",
  1849. "Oct",
  1850. "Nov",
  1851. "Dec"};
  1852. #endif /* !NO_CACHING */
  1853. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1854. * the
  1855. * union u. */
  1856. union usa {
  1857. struct sockaddr sa;
  1858. struct sockaddr_in sin;
  1859. #if defined(USE_IPV6)
  1860. struct sockaddr_in6 sin6;
  1861. #endif
  1862. };
  1863. /* Describes a string (chunk of memory). */
  1864. struct vec {
  1865. const char *ptr;
  1866. size_t len;
  1867. };
  1868. struct mg_file_stat {
  1869. /* File properties filled by mg_stat: */
  1870. uint64_t size;
  1871. time_t last_modified;
  1872. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1873. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1874. * case we need a "Content-Eencoding: gzip" header */
  1875. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1876. };
  1877. struct mg_file_in_memory {
  1878. char *p;
  1879. uint32_t pos;
  1880. char mode;
  1881. };
  1882. struct mg_file_access {
  1883. /* File properties filled by mg_fopen: */
  1884. FILE *fp;
  1885. #if defined(MG_USE_OPEN_FILE)
  1886. /* TODO (low): Remove obsolete "file in memory" implementation.
  1887. * In an "early 2017" discussion at Google groups
  1888. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1889. * we decided to get rid of this feature (after some fade-out
  1890. * phase). */
  1891. const char *membuf;
  1892. #endif
  1893. };
  1894. struct mg_file {
  1895. struct mg_file_stat stat;
  1896. struct mg_file_access access;
  1897. };
  1898. #if defined(MG_USE_OPEN_FILE)
  1899. #define STRUCT_FILE_INITIALIZER \
  1900. { \
  1901. { \
  1902. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1903. } \
  1904. , \
  1905. { \
  1906. (FILE *) NULL, (const char *)NULL \
  1907. } \
  1908. }
  1909. #else
  1910. #define STRUCT_FILE_INITIALIZER \
  1911. { \
  1912. { \
  1913. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1914. } \
  1915. , \
  1916. { \
  1917. (FILE *) NULL \
  1918. } \
  1919. }
  1920. #endif
  1921. /* Describes listening socket, or socket which was accept()-ed by the master
  1922. * thread and queued for future handling by the worker thread. */
  1923. struct socket {
  1924. SOCKET sock; /* Listening socket */
  1925. union usa lsa; /* Local socket address */
  1926. union usa rsa; /* Remote socket address */
  1927. unsigned char is_ssl; /* Is port SSL-ed */
  1928. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1929. * port */
  1930. unsigned char in_use; /* Is valid */
  1931. };
  1932. /* Enum const for all options must be in sync with
  1933. * static struct mg_option config_options[]
  1934. * This is tested in the unit test (test/private.c)
  1935. * "Private Config Options"
  1936. */
  1937. enum {
  1938. LISTENING_PORTS,
  1939. NUM_THREADS,
  1940. RUN_AS_USER,
  1941. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1942. * socket option typedef TCP_NODELAY. */
  1943. MAX_REQUEST_SIZE,
  1944. LINGER_TIMEOUT,
  1945. #if defined(__linux__)
  1946. ALLOW_SENDFILE_CALL,
  1947. #endif
  1948. #if defined(_WIN32)
  1949. CASE_SENSITIVE_FILES,
  1950. #endif
  1951. THROTTLE,
  1952. ACCESS_LOG_FILE,
  1953. ERROR_LOG_FILE,
  1954. ENABLE_KEEP_ALIVE,
  1955. REQUEST_TIMEOUT,
  1956. KEEP_ALIVE_TIMEOUT,
  1957. #if defined(USE_WEBSOCKET)
  1958. WEBSOCKET_TIMEOUT,
  1959. ENABLE_WEBSOCKET_PING_PONG,
  1960. #endif
  1961. DECODE_URL,
  1962. #if defined(USE_LUA)
  1963. LUA_BACKGROUND_SCRIPT,
  1964. LUA_BACKGROUND_SCRIPT_PARAMS,
  1965. #endif
  1966. DOCUMENT_ROOT,
  1967. CGI_EXTENSIONS,
  1968. CGI_ENVIRONMENT,
  1969. PUT_DELETE_PASSWORDS_FILE,
  1970. CGI_INTERPRETER,
  1971. PROTECT_URI,
  1972. AUTHENTICATION_DOMAIN,
  1973. ENABLE_AUTH_DOMAIN_CHECK,
  1974. SSI_EXTENSIONS,
  1975. ENABLE_DIRECTORY_LISTING,
  1976. GLOBAL_PASSWORDS_FILE,
  1977. INDEX_FILES,
  1978. ACCESS_CONTROL_LIST,
  1979. EXTRA_MIME_TYPES,
  1980. SSL_CERTIFICATE,
  1981. SSL_CERTIFICATE_CHAIN,
  1982. URL_REWRITE_PATTERN,
  1983. HIDE_FILES,
  1984. SSL_DO_VERIFY_PEER,
  1985. SSL_CA_PATH,
  1986. SSL_CA_FILE,
  1987. SSL_VERIFY_DEPTH,
  1988. SSL_DEFAULT_VERIFY_PATHS,
  1989. SSL_CIPHER_LIST,
  1990. SSL_PROTOCOL_VERSION,
  1991. SSL_SHORT_TRUST,
  1992. #if defined(USE_LUA)
  1993. LUA_PRELOAD_FILE,
  1994. LUA_SCRIPT_EXTENSIONS,
  1995. LUA_SERVER_PAGE_EXTENSIONS,
  1996. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1997. LUA_DEBUG_PARAMS,
  1998. #endif
  1999. #endif
  2000. #if defined(USE_DUKTAPE)
  2001. DUKTAPE_SCRIPT_EXTENSIONS,
  2002. #endif
  2003. #if defined(USE_WEBSOCKET)
  2004. WEBSOCKET_ROOT,
  2005. #endif
  2006. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2007. LUA_WEBSOCKET_EXTENSIONS,
  2008. #endif
  2009. ACCESS_CONTROL_ALLOW_ORIGIN,
  2010. ACCESS_CONTROL_ALLOW_METHODS,
  2011. ACCESS_CONTROL_ALLOW_HEADERS,
  2012. ERROR_PAGES,
  2013. #if !defined(NO_CACHING)
  2014. STATIC_FILE_MAX_AGE,
  2015. #endif
  2016. #if !defined(NO_SSL)
  2017. STRICT_HTTPS_MAX_AGE,
  2018. #endif
  2019. ADDITIONAL_HEADER,
  2020. ALLOW_INDEX_SCRIPT_SUB_RES,
  2021. NUM_OPTIONS
  2022. };
  2023. /* Config option name, config types, default value.
  2024. * Must be in the same order as the enum const above.
  2025. */
  2026. static const struct mg_option config_options[] = {
  2027. /* Once for each server */
  2028. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2029. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2030. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2031. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2032. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2033. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2034. #if defined(__linux__)
  2035. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2036. #endif
  2037. #if defined(_WIN32)
  2038. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2039. #endif
  2040. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2041. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2042. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2043. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2044. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2045. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2046. #if defined(USE_WEBSOCKET)
  2047. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2048. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2049. #endif
  2050. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2051. #if defined(USE_LUA)
  2052. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2053. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2054. #endif
  2055. /* Once for each domain */
  2056. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2057. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2058. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2059. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2060. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2061. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2062. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2063. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2064. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2065. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2066. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2067. {"index_files",
  2068. MG_CONFIG_TYPE_STRING_LIST,
  2069. #if defined(USE_LUA)
  2070. "index.xhtml,index.html,index.htm,"
  2071. "index.lp,index.lsp,index.lua,index.cgi,"
  2072. "index.shtml,index.php"},
  2073. #else
  2074. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2075. #endif
  2076. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2077. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2078. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2079. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2080. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2081. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2082. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2083. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2084. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2085. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2086. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2087. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2088. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2089. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2090. #if defined(USE_LUA)
  2091. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2092. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2093. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2094. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2095. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2096. #endif
  2097. #endif
  2098. #if defined(USE_DUKTAPE)
  2099. /* The support for duktape is still in alpha version state.
  2100. * The name of this config option might change. */
  2101. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2102. #endif
  2103. #if defined(USE_WEBSOCKET)
  2104. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2105. #endif
  2106. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2107. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2108. #endif
  2109. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2110. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2111. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2112. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2113. #if !defined(NO_CACHING)
  2114. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2115. #endif
  2116. #if !defined(NO_SSL)
  2117. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2118. #endif
  2119. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2120. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2121. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2122. /* Check if the config_options and the corresponding enum have compatible
  2123. * sizes. */
  2124. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2125. == (NUM_OPTIONS + 1),
  2126. "config_options and enum not sync");
  2127. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2128. struct mg_handler_info {
  2129. /* Name/Pattern of the URI. */
  2130. char *uri;
  2131. size_t uri_len;
  2132. /* handler type */
  2133. int handler_type;
  2134. /* Handler for http/https or authorization requests. */
  2135. mg_request_handler handler;
  2136. unsigned int refcount;
  2137. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2138. pthread_cond_t
  2139. refcount_cond; /* Signaled when handler refcount is decremented */
  2140. /* Handler for ws/wss (websocket) requests. */
  2141. mg_websocket_connect_handler connect_handler;
  2142. mg_websocket_ready_handler ready_handler;
  2143. mg_websocket_data_handler data_handler;
  2144. mg_websocket_close_handler close_handler;
  2145. /* accepted subprotocols for ws/wss requests. */
  2146. struct mg_websocket_subprotocols *subprotocols;
  2147. /* Handler for authorization requests */
  2148. mg_authorization_handler auth_handler;
  2149. /* User supplied argument for the handler function. */
  2150. void *cbdata;
  2151. /* next handler in a linked list */
  2152. struct mg_handler_info *next;
  2153. };
  2154. enum {
  2155. CONTEXT_INVALID,
  2156. CONTEXT_SERVER,
  2157. CONTEXT_HTTP_CLIENT,
  2158. CONTEXT_WS_CLIENT
  2159. };
  2160. struct mg_domain_context {
  2161. SSL_CTX *ssl_ctx; /* SSL context */
  2162. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2163. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2164. /* Server nonce */
  2165. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2166. unsigned long nonce_count; /* Used nonces, used for authentication */
  2167. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2168. /* linked list of shared lua websockets */
  2169. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2170. #endif
  2171. /* Linked list of domains */
  2172. struct mg_domain_context *next;
  2173. };
  2174. struct mg_context {
  2175. /* Part 1 - Physical context:
  2176. * This holds threads, ports, timeouts, ...
  2177. * set for the entire server, independent from the
  2178. * addressed hostname.
  2179. */
  2180. /* Connection related */
  2181. int context_type; /* See CONTEXT_* above */
  2182. struct socket *listening_sockets;
  2183. struct pollfd *listening_socket_fds;
  2184. unsigned int num_listening_sockets;
  2185. struct mg_connection *worker_connections; /* The connection struct, pre-
  2186. * allocated for each worker */
  2187. #if defined(USE_SERVER_STATS)
  2188. int active_connections;
  2189. int max_connections;
  2190. int64_t total_connections;
  2191. int64_t total_requests;
  2192. int64_t total_data_read;
  2193. int64_t total_data_written;
  2194. #endif
  2195. /* Thread related */
  2196. volatile int stop_flag; /* Should we stop event loop */
  2197. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2198. pthread_t masterthreadid; /* The master thread ID */
  2199. unsigned int
  2200. cfg_worker_threads; /* The number of configured worker threads. */
  2201. pthread_t *worker_threadids; /* The worker thread IDs */
  2202. /* Connection to thread dispatching */
  2203. #if defined(ALTERNATIVE_QUEUE)
  2204. struct socket *client_socks;
  2205. void **client_wait_events;
  2206. #else
  2207. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2208. volatile int sq_head; /* Head of the socket queue */
  2209. volatile int sq_tail; /* Tail of the socket queue */
  2210. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2211. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2212. #endif
  2213. /* Memory related */
  2214. unsigned int max_request_size; /* The max request size */
  2215. #if defined(USE_SERVER_STATS)
  2216. struct mg_memory_stat ctx_memory;
  2217. #endif
  2218. /* Operating system related */
  2219. char *systemName; /* What operating system is running */
  2220. time_t start_time; /* Server start time, used for authentication
  2221. * and for diagnstics. */
  2222. #if defined(USE_TIMERS)
  2223. struct ttimers *timers;
  2224. #endif
  2225. /* Lua specific: Background operations and shared websockets */
  2226. #if defined(USE_LUA)
  2227. void *lua_background_state;
  2228. #endif
  2229. /* Server nonce */
  2230. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2231. /* Server callbacks */
  2232. struct mg_callbacks callbacks; /* User-defined callback function */
  2233. void *user_data; /* User-defined data */
  2234. /* Part 2 - Logical domain:
  2235. * This holds hostname, TLS certificate, document root, ...
  2236. * set for a domain hosted at the server.
  2237. * There may be multiple domains hosted at one physical server.
  2238. * The default domain "dd" is the first element of a list of
  2239. * domains.
  2240. */
  2241. struct mg_domain_context dd; /* default domain */
  2242. };
  2243. #if defined(USE_SERVER_STATS)
  2244. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2245. static struct mg_memory_stat *
  2246. get_memory_stat(struct mg_context *ctx)
  2247. {
  2248. if (ctx) {
  2249. return &(ctx->ctx_memory);
  2250. }
  2251. return &mg_common_memory;
  2252. }
  2253. #endif
  2254. enum {
  2255. CONNECTION_TYPE_INVALID,
  2256. CONNECTION_TYPE_REQUEST,
  2257. CONNECTION_TYPE_RESPONSE
  2258. };
  2259. struct mg_connection {
  2260. int connection_type; /* see CONNECTION_TYPE_* above */
  2261. struct mg_request_info request_info;
  2262. struct mg_response_info response_info;
  2263. struct mg_context *phys_ctx;
  2264. struct mg_domain_context *dom_ctx;
  2265. #if defined(USE_SERVER_STATS)
  2266. int conn_state; /* 0 = undef, numerical value may change in different
  2267. * versions. For the current definition, see
  2268. * mg_get_connection_info_impl */
  2269. #endif
  2270. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2271. SSL *ssl; /* SSL descriptor */
  2272. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2273. struct socket client; /* Connected client */
  2274. time_t conn_birth_time; /* Time (wall clock) when connection was
  2275. * established */
  2276. struct timespec req_time; /* Time (since system start) when the request
  2277. * was received */
  2278. int64_t num_bytes_sent; /* Total bytes sent to client */
  2279. int64_t content_len; /* Content-Length header value */
  2280. int64_t consumed_content; /* How many bytes of content have been read */
  2281. int is_chunked; /* Transfer-Encoding is chunked:
  2282. * 0 = not chunked,
  2283. * 1 = chunked, do data read yet,
  2284. * 2 = chunked, some data read,
  2285. * 3 = chunked, all data read
  2286. */
  2287. size_t chunk_remainder; /* Unread data from the last chunk */
  2288. char *buf; /* Buffer for received data */
  2289. char *path_info; /* PATH_INFO part of the URL */
  2290. int must_close; /* 1 if connection must be closed */
  2291. int accept_gzip; /* 1 if gzip encoding is accepted */
  2292. int in_error_handler; /* 1 if in handler for user defined error
  2293. * pages */
  2294. #if defined(USE_WEBSOCKET)
  2295. int in_websocket_handling; /* 1 if in read_websocket */
  2296. #endif
  2297. int handled_requests; /* Number of requests handled by this connection
  2298. */
  2299. int buf_size; /* Buffer size */
  2300. int request_len; /* Size of the request + headers in a buffer */
  2301. int data_len; /* Total size of data in a buffer */
  2302. int status_code; /* HTTP reply status code, e.g. 200 */
  2303. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2304. * throttle */
  2305. time_t last_throttle_time; /* Last time throttled data was sent */
  2306. int64_t last_throttle_bytes; /* Bytes sent this second */
  2307. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2308. * atomic transmissions for websockets */
  2309. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2310. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2311. #endif
  2312. int thread_index; /* Thread index within ctx */
  2313. };
  2314. /* Directory entry */
  2315. struct de {
  2316. struct mg_connection *conn;
  2317. char *file_name;
  2318. struct mg_file_stat file;
  2319. };
  2320. #if defined(USE_WEBSOCKET)
  2321. static int is_websocket_protocol(const struct mg_connection *conn);
  2322. #else
  2323. #define is_websocket_protocol(conn) (0)
  2324. #endif
  2325. #define mg_cry_internal(conn, fmt, ...) \
  2326. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2327. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2328. const char *func,
  2329. unsigned line,
  2330. const char *fmt,
  2331. ...) PRINTF_ARGS(4, 5);
  2332. #if !defined(NO_THREAD_NAME)
  2333. #if defined(_WIN32) && defined(_MSC_VER)
  2334. /* Set the thread name for debugging purposes in Visual Studio
  2335. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2336. */
  2337. #pragma pack(push, 8)
  2338. typedef struct tagTHREADNAME_INFO {
  2339. DWORD dwType; /* Must be 0x1000. */
  2340. LPCSTR szName; /* Pointer to name (in user addr space). */
  2341. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2342. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2343. } THREADNAME_INFO;
  2344. #pragma pack(pop)
  2345. #elif defined(__linux__)
  2346. #include <sys/prctl.h>
  2347. #include <sys/sendfile.h>
  2348. #if defined(ALTERNATIVE_QUEUE)
  2349. #include <sys/eventfd.h>
  2350. #endif /* ALTERNATIVE_QUEUE */
  2351. #if defined(ALTERNATIVE_QUEUE)
  2352. static void *
  2353. event_create(void)
  2354. {
  2355. int evhdl = eventfd(0, EFD_CLOEXEC);
  2356. int *ret;
  2357. if (evhdl == -1) {
  2358. /* Linux uses -1 on error, Windows NULL. */
  2359. /* However, Linux does not return 0 on success either. */
  2360. return 0;
  2361. }
  2362. ret = (int *)mg_malloc(sizeof(int));
  2363. if (ret) {
  2364. *ret = evhdl;
  2365. } else {
  2366. (void)close(evhdl);
  2367. }
  2368. return (void *)ret;
  2369. }
  2370. static int
  2371. event_wait(void *eventhdl)
  2372. {
  2373. uint64_t u;
  2374. int evhdl, s;
  2375. if (!eventhdl) {
  2376. /* error */
  2377. return 0;
  2378. }
  2379. evhdl = *(int *)eventhdl;
  2380. s = (int)read(evhdl, &u, sizeof(u));
  2381. if (s != sizeof(u)) {
  2382. /* error */
  2383. return 0;
  2384. }
  2385. (void)u; /* the value is not required */
  2386. return 1;
  2387. }
  2388. static int
  2389. event_signal(void *eventhdl)
  2390. {
  2391. uint64_t u = 1;
  2392. int evhdl, s;
  2393. if (!eventhdl) {
  2394. /* error */
  2395. return 0;
  2396. }
  2397. evhdl = *(int *)eventhdl;
  2398. s = (int)write(evhdl, &u, sizeof(u));
  2399. if (s != sizeof(u)) {
  2400. /* error */
  2401. return 0;
  2402. }
  2403. return 1;
  2404. }
  2405. static void
  2406. event_destroy(void *eventhdl)
  2407. {
  2408. int evhdl;
  2409. if (!eventhdl) {
  2410. /* error */
  2411. return;
  2412. }
  2413. evhdl = *(int *)eventhdl;
  2414. close(evhdl);
  2415. mg_free(eventhdl);
  2416. }
  2417. #endif
  2418. #endif
  2419. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2420. struct posix_event {
  2421. pthread_mutex_t mutex;
  2422. pthread_cond_t cond;
  2423. };
  2424. static void *
  2425. event_create(void)
  2426. {
  2427. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2428. if (ret == 0) {
  2429. /* out of memory */
  2430. return 0;
  2431. }
  2432. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2433. /* pthread mutex not available */
  2434. mg_free(ret);
  2435. return 0;
  2436. }
  2437. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2438. /* pthread cond not available */
  2439. pthread_mutex_destroy(&(ret->mutex));
  2440. mg_free(ret);
  2441. return 0;
  2442. }
  2443. return (void *)ret;
  2444. }
  2445. static int
  2446. event_wait(void *eventhdl)
  2447. {
  2448. struct posix_event *ev = (struct posix_event *)eventhdl;
  2449. pthread_mutex_lock(&(ev->mutex));
  2450. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2451. pthread_mutex_unlock(&(ev->mutex));
  2452. return 1;
  2453. }
  2454. static int
  2455. event_signal(void *eventhdl)
  2456. {
  2457. struct posix_event *ev = (struct posix_event *)eventhdl;
  2458. pthread_mutex_lock(&(ev->mutex));
  2459. pthread_cond_signal(&(ev->cond));
  2460. pthread_mutex_unlock(&(ev->mutex));
  2461. return 1;
  2462. }
  2463. static void
  2464. event_destroy(void *eventhdl)
  2465. {
  2466. struct posix_event *ev = (struct posix_event *)eventhdl;
  2467. pthread_cond_destroy(&(ev->cond));
  2468. pthread_mutex_destroy(&(ev->mutex));
  2469. mg_free(ev);
  2470. }
  2471. #endif
  2472. static void
  2473. mg_set_thread_name(const char *name)
  2474. {
  2475. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2476. mg_snprintf(
  2477. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2478. #if defined(_WIN32)
  2479. #if defined(_MSC_VER)
  2480. /* Windows and Visual Studio Compiler */
  2481. __try
  2482. {
  2483. THREADNAME_INFO info;
  2484. info.dwType = 0x1000;
  2485. info.szName = threadName;
  2486. info.dwThreadID = ~0U;
  2487. info.dwFlags = 0;
  2488. RaiseException(0x406D1388,
  2489. 0,
  2490. sizeof(info) / sizeof(ULONG_PTR),
  2491. (ULONG_PTR *)&info);
  2492. }
  2493. __except(EXCEPTION_EXECUTE_HANDLER)
  2494. {
  2495. }
  2496. #elif defined(__MINGW32__)
  2497. /* No option known to set thread name for MinGW */
  2498. #endif
  2499. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2500. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2501. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2502. (void)pthread_setname_np(pthread_self(), threadName);
  2503. #elif defined(__linux__)
  2504. /* on linux we can use the old prctl function */
  2505. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2506. #endif
  2507. }
  2508. #else /* !defined(NO_THREAD_NAME) */
  2509. void
  2510. mg_set_thread_name(const char *threadName)
  2511. {
  2512. }
  2513. #endif
  2514. #if defined(MG_LEGACY_INTERFACE)
  2515. const char **
  2516. mg_get_valid_option_names(void)
  2517. {
  2518. /* This function is deprecated. Use mg_get_valid_options instead. */
  2519. static const char *
  2520. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2521. int i;
  2522. for (i = 0; config_options[i].name != NULL; i++) {
  2523. data[i * 2] = config_options[i].name;
  2524. data[i * 2 + 1] = config_options[i].default_value;
  2525. }
  2526. return data;
  2527. }
  2528. #endif
  2529. const struct mg_option *
  2530. mg_get_valid_options(void)
  2531. {
  2532. return config_options;
  2533. }
  2534. /* Do not open file (used in is_file_in_memory) */
  2535. #define MG_FOPEN_MODE_NONE (0)
  2536. /* Open file for read only access */
  2537. #define MG_FOPEN_MODE_READ (1)
  2538. /* Open file for writing, create and overwrite */
  2539. #define MG_FOPEN_MODE_WRITE (2)
  2540. /* Open file for writing, create and append */
  2541. #define MG_FOPEN_MODE_APPEND (4)
  2542. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2543. * output filep and return 1, otherwise return 0 and don't modify anything.
  2544. */
  2545. static int
  2546. open_file_in_memory(const struct mg_connection *conn,
  2547. const char *path,
  2548. struct mg_file *filep,
  2549. int mode)
  2550. {
  2551. #if defined(MG_USE_OPEN_FILE)
  2552. size_t size = 0;
  2553. const char *buf = NULL;
  2554. if (!conn) {
  2555. return 0;
  2556. }
  2557. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2558. return 0;
  2559. }
  2560. if (conn->phys_ctx->callbacks.open_file) {
  2561. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2562. if (buf != NULL) {
  2563. if (filep == NULL) {
  2564. /* This is a file in memory, but we cannot store the
  2565. * properties
  2566. * now.
  2567. * Called from "is_file_in_memory" function. */
  2568. return 1;
  2569. }
  2570. /* NOTE: override filep->size only on success. Otherwise, it
  2571. * might
  2572. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2573. filep->access.membuf = buf;
  2574. filep->access.fp = NULL;
  2575. /* Size was set by the callback */
  2576. filep->stat.size = size;
  2577. /* Assume the data may change during runtime by setting
  2578. * last_modified = now */
  2579. filep->stat.last_modified = time(NULL);
  2580. filep->stat.is_directory = 0;
  2581. filep->stat.is_gzipped = 0;
  2582. }
  2583. }
  2584. return (buf != NULL);
  2585. #else
  2586. (void)conn;
  2587. (void)path;
  2588. (void)filep;
  2589. (void)mode;
  2590. return 0;
  2591. #endif
  2592. }
  2593. static int
  2594. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2595. {
  2596. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2597. }
  2598. static int
  2599. is_file_opened(const struct mg_file_access *fileacc)
  2600. {
  2601. if (!fileacc) {
  2602. return 0;
  2603. }
  2604. #if defined(MG_USE_OPEN_FILE)
  2605. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2606. #else
  2607. return (fileacc->fp != NULL);
  2608. #endif
  2609. }
  2610. static int mg_stat(const struct mg_connection *conn,
  2611. const char *path,
  2612. struct mg_file_stat *filep);
  2613. /* mg_fopen will open a file either in memory or on the disk.
  2614. * The input parameter path is a string in UTF-8 encoding.
  2615. * The input parameter mode is MG_FOPEN_MODE_*
  2616. * On success, either fp or membuf will be set in the output
  2617. * struct file. All status members will also be set.
  2618. * The function returns 1 on success, 0 on error. */
  2619. static int
  2620. mg_fopen(const struct mg_connection *conn,
  2621. const char *path,
  2622. int mode,
  2623. struct mg_file *filep)
  2624. {
  2625. int found;
  2626. if (!filep) {
  2627. return 0;
  2628. }
  2629. filep->access.fp = NULL;
  2630. #if defined(MG_USE_OPEN_FILE)
  2631. filep->access.membuf = NULL;
  2632. #endif
  2633. if (!is_file_in_memory(conn, path)) {
  2634. /* filep is initialized in mg_stat: all fields with memset to,
  2635. * some fields like size and modification date with values */
  2636. found = mg_stat(conn, path, &(filep->stat));
  2637. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2638. /* file does not exist and will not be created */
  2639. return 0;
  2640. }
  2641. #if defined(_WIN32)
  2642. {
  2643. wchar_t wbuf[W_PATH_MAX];
  2644. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2645. switch (mode) {
  2646. case MG_FOPEN_MODE_READ:
  2647. filep->access.fp = _wfopen(wbuf, L"rb");
  2648. break;
  2649. case MG_FOPEN_MODE_WRITE:
  2650. filep->access.fp = _wfopen(wbuf, L"wb");
  2651. break;
  2652. case MG_FOPEN_MODE_APPEND:
  2653. filep->access.fp = _wfopen(wbuf, L"ab");
  2654. break;
  2655. }
  2656. }
  2657. #else
  2658. /* Linux et al already use unicode. No need to convert. */
  2659. switch (mode) {
  2660. case MG_FOPEN_MODE_READ:
  2661. filep->access.fp = fopen(path, "r");
  2662. break;
  2663. case MG_FOPEN_MODE_WRITE:
  2664. filep->access.fp = fopen(path, "w");
  2665. break;
  2666. case MG_FOPEN_MODE_APPEND:
  2667. filep->access.fp = fopen(path, "a");
  2668. break;
  2669. }
  2670. #endif
  2671. if (!found) {
  2672. /* File did not exist before fopen was called.
  2673. * Maybe it has been created now. Get stat info
  2674. * like creation time now. */
  2675. found = mg_stat(conn, path, &(filep->stat));
  2676. (void)found;
  2677. }
  2678. /* file is on disk */
  2679. return (filep->access.fp != NULL);
  2680. } else {
  2681. #if defined(MG_USE_OPEN_FILE)
  2682. /* is_file_in_memory returned true */
  2683. if (open_file_in_memory(conn, path, filep, mode)) {
  2684. /* file is in memory */
  2685. return (filep->access.membuf != NULL);
  2686. }
  2687. #endif
  2688. }
  2689. /* Open failed */
  2690. return 0;
  2691. }
  2692. /* return 0 on success, just like fclose */
  2693. static int
  2694. mg_fclose(struct mg_file_access *fileacc)
  2695. {
  2696. int ret = -1;
  2697. if (fileacc != NULL) {
  2698. if (fileacc->fp != NULL) {
  2699. ret = fclose(fileacc->fp);
  2700. #if defined(MG_USE_OPEN_FILE)
  2701. } else if (fileacc->membuf != NULL) {
  2702. ret = 0;
  2703. #endif
  2704. }
  2705. /* reset all members of fileacc */
  2706. memset(fileacc, 0, sizeof(*fileacc));
  2707. }
  2708. return ret;
  2709. }
  2710. static void
  2711. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2712. {
  2713. for (; *src != '\0' && n > 1; n--) {
  2714. *dst++ = *src++;
  2715. }
  2716. *dst = '\0';
  2717. }
  2718. static int
  2719. lowercase(const char *s)
  2720. {
  2721. return tolower(*(const unsigned char *)s);
  2722. }
  2723. int
  2724. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2725. {
  2726. int diff = 0;
  2727. if (len > 0) {
  2728. do {
  2729. diff = lowercase(s1++) - lowercase(s2++);
  2730. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2731. }
  2732. return diff;
  2733. }
  2734. int
  2735. mg_strcasecmp(const char *s1, const char *s2)
  2736. {
  2737. int diff;
  2738. do {
  2739. diff = lowercase(s1++) - lowercase(s2++);
  2740. } while (diff == 0 && s1[-1] != '\0');
  2741. return diff;
  2742. }
  2743. static char *
  2744. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2745. {
  2746. char *p;
  2747. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2748. * defined */
  2749. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2750. mg_strlcpy(p, ptr, len + 1);
  2751. }
  2752. return p;
  2753. }
  2754. static char *
  2755. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2756. {
  2757. return mg_strndup_ctx(str, strlen(str), ctx);
  2758. }
  2759. static char *
  2760. mg_strdup(const char *str)
  2761. {
  2762. return mg_strndup_ctx(str, strlen(str), NULL);
  2763. }
  2764. static const char *
  2765. mg_strcasestr(const char *big_str, const char *small_str)
  2766. {
  2767. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2768. if (big_len >= small_len) {
  2769. for (i = 0; i <= (big_len - small_len); i++) {
  2770. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2771. return big_str + i;
  2772. }
  2773. }
  2774. }
  2775. return NULL;
  2776. }
  2777. /* Return null terminated string of given maximum length.
  2778. * Report errors if length is exceeded. */
  2779. static void
  2780. mg_vsnprintf(const struct mg_connection *conn,
  2781. int *truncated,
  2782. char *buf,
  2783. size_t buflen,
  2784. const char *fmt,
  2785. va_list ap)
  2786. {
  2787. int n, ok;
  2788. if (buflen == 0) {
  2789. if (truncated) {
  2790. *truncated = 1;
  2791. }
  2792. return;
  2793. }
  2794. #if defined(__clang__)
  2795. #pragma clang diagnostic push
  2796. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2797. /* Using fmt as a non-literal is intended here, since it is mostly called
  2798. * indirectly by mg_snprintf */
  2799. #endif
  2800. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2801. ok = (n >= 0) && ((size_t)n < buflen);
  2802. #if defined(__clang__)
  2803. #pragma clang diagnostic pop
  2804. #endif
  2805. if (ok) {
  2806. if (truncated) {
  2807. *truncated = 0;
  2808. }
  2809. } else {
  2810. if (truncated) {
  2811. *truncated = 1;
  2812. }
  2813. mg_cry_internal(conn,
  2814. "truncating vsnprintf buffer: [%.*s]",
  2815. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2816. buf);
  2817. n = (int)buflen - 1;
  2818. }
  2819. buf[n] = '\0';
  2820. }
  2821. static void
  2822. mg_snprintf(const struct mg_connection *conn,
  2823. int *truncated,
  2824. char *buf,
  2825. size_t buflen,
  2826. const char *fmt,
  2827. ...)
  2828. {
  2829. va_list ap;
  2830. va_start(ap, fmt);
  2831. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2832. va_end(ap);
  2833. }
  2834. static int
  2835. get_option_index(const char *name)
  2836. {
  2837. int i;
  2838. for (i = 0; config_options[i].name != NULL; i++) {
  2839. if (strcmp(config_options[i].name, name) == 0) {
  2840. return i;
  2841. }
  2842. }
  2843. return -1;
  2844. }
  2845. const char *
  2846. mg_get_option(const struct mg_context *ctx, const char *name)
  2847. {
  2848. int i;
  2849. if ((i = get_option_index(name)) == -1) {
  2850. return NULL;
  2851. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2852. return "";
  2853. } else {
  2854. return ctx->dd.config[i];
  2855. }
  2856. }
  2857. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2858. struct mg_context *
  2859. mg_get_context(const struct mg_connection *conn)
  2860. {
  2861. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2862. }
  2863. void *
  2864. mg_get_user_data(const struct mg_context *ctx)
  2865. {
  2866. return (ctx == NULL) ? NULL : ctx->user_data;
  2867. }
  2868. void
  2869. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2870. {
  2871. if (conn != NULL) {
  2872. conn->request_info.conn_data = data;
  2873. }
  2874. }
  2875. void *
  2876. mg_get_user_connection_data(const struct mg_connection *conn)
  2877. {
  2878. if (conn != NULL) {
  2879. return conn->request_info.conn_data;
  2880. }
  2881. return NULL;
  2882. }
  2883. #if defined(MG_LEGACY_INTERFACE)
  2884. /* Deprecated: Use mg_get_server_ports instead. */
  2885. size_t
  2886. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2887. {
  2888. size_t i;
  2889. if (!ctx) {
  2890. return 0;
  2891. }
  2892. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2893. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2894. ports[i] =
  2895. #if defined(USE_IPV6)
  2896. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2897. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2898. :
  2899. #endif
  2900. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2901. }
  2902. return i;
  2903. }
  2904. #endif
  2905. int
  2906. mg_get_server_ports(const struct mg_context *ctx,
  2907. int size,
  2908. struct mg_server_ports *ports)
  2909. {
  2910. int i, cnt = 0;
  2911. if (size <= 0) {
  2912. return -1;
  2913. }
  2914. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2915. if (!ctx) {
  2916. return -1;
  2917. }
  2918. if (!ctx->listening_sockets) {
  2919. return -1;
  2920. }
  2921. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2922. ports[cnt].port =
  2923. #if defined(USE_IPV6)
  2924. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2925. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2926. :
  2927. #endif
  2928. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2929. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2930. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2931. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2932. /* IPv4 */
  2933. ports[cnt].protocol = 1;
  2934. cnt++;
  2935. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2936. /* IPv6 */
  2937. ports[cnt].protocol = 3;
  2938. cnt++;
  2939. }
  2940. }
  2941. return cnt;
  2942. }
  2943. static void
  2944. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2945. {
  2946. buf[0] = '\0';
  2947. if (!usa) {
  2948. return;
  2949. }
  2950. if (usa->sa.sa_family == AF_INET) {
  2951. getnameinfo(&usa->sa,
  2952. sizeof(usa->sin),
  2953. buf,
  2954. (unsigned)len,
  2955. NULL,
  2956. 0,
  2957. NI_NUMERICHOST);
  2958. }
  2959. #if defined(USE_IPV6)
  2960. else if (usa->sa.sa_family == AF_INET6) {
  2961. getnameinfo(&usa->sa,
  2962. sizeof(usa->sin6),
  2963. buf,
  2964. (unsigned)len,
  2965. NULL,
  2966. 0,
  2967. NI_NUMERICHOST);
  2968. }
  2969. #endif
  2970. }
  2971. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2972. * included in all responses other than 100, 101, 5xx. */
  2973. static void
  2974. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2975. {
  2976. #if !defined(REENTRANT_TIME)
  2977. struct tm *tm;
  2978. tm = ((t != NULL) ? gmtime(t) : NULL);
  2979. if (tm != NULL) {
  2980. #else
  2981. struct tm _tm;
  2982. struct tm *tm = &_tm;
  2983. if (t != NULL) {
  2984. gmtime_r(t, tm);
  2985. #endif
  2986. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2987. } else {
  2988. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2989. buf[buf_len - 1] = '\0';
  2990. }
  2991. }
  2992. /* difftime for struct timespec. Return value is in seconds. */
  2993. static double
  2994. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2995. {
  2996. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2997. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2998. }
  2999. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3000. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3001. const char *func,
  3002. unsigned line,
  3003. const char *fmt,
  3004. va_list ap);
  3005. #include "external_mg_cry_internal_impl.inl"
  3006. #else
  3007. /* Print error message to the opened error log stream. */
  3008. static void
  3009. mg_cry_internal_impl(const struct mg_connection *conn,
  3010. const char *func,
  3011. unsigned line,
  3012. const char *fmt,
  3013. va_list ap)
  3014. {
  3015. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3016. struct mg_file fi;
  3017. time_t timestamp;
  3018. /* Unused, in the RELEASE build */
  3019. (void)func;
  3020. (void)line;
  3021. #if defined(__GNUC__) || defined(__MINGW32__)
  3022. #pragma GCC diagnostic push
  3023. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3024. #endif
  3025. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3026. #if defined(__GNUC__) || defined(__MINGW32__)
  3027. #pragma GCC diagnostic pop
  3028. #endif
  3029. buf[sizeof(buf) - 1] = 0;
  3030. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3031. if (!conn) {
  3032. puts(buf);
  3033. return;
  3034. }
  3035. /* Do not lock when getting the callback value, here and below.
  3036. * I suppose this is fine, since function cannot disappear in the
  3037. * same way string option can. */
  3038. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3039. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3040. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3041. if (mg_fopen(conn,
  3042. conn->dom_ctx->config[ERROR_LOG_FILE],
  3043. MG_FOPEN_MODE_APPEND,
  3044. &fi) == 0) {
  3045. fi.access.fp = NULL;
  3046. }
  3047. } else {
  3048. fi.access.fp = NULL;
  3049. }
  3050. if (fi.access.fp != NULL) {
  3051. flockfile(fi.access.fp);
  3052. timestamp = time(NULL);
  3053. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3054. fprintf(fi.access.fp,
  3055. "[%010lu] [error] [client %s] ",
  3056. (unsigned long)timestamp,
  3057. src_addr);
  3058. if (conn->request_info.request_method != NULL) {
  3059. fprintf(fi.access.fp,
  3060. "%s %s: ",
  3061. conn->request_info.request_method,
  3062. conn->request_info.request_uri
  3063. ? conn->request_info.request_uri
  3064. : "");
  3065. }
  3066. fprintf(fi.access.fp, "%s", buf);
  3067. fputc('\n', fi.access.fp);
  3068. fflush(fi.access.fp);
  3069. funlockfile(fi.access.fp);
  3070. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3071. * mg_cry here anyway ;-) */
  3072. }
  3073. }
  3074. }
  3075. #endif /* Externally provided function */
  3076. static void
  3077. mg_cry_internal_wrap(const struct mg_connection *conn,
  3078. const char *func,
  3079. unsigned line,
  3080. const char *fmt,
  3081. ...)
  3082. {
  3083. va_list ap;
  3084. va_start(ap, fmt);
  3085. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3086. va_end(ap);
  3087. }
  3088. void
  3089. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3090. {
  3091. va_list ap;
  3092. va_start(ap, fmt);
  3093. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3094. va_end(ap);
  3095. }
  3096. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3097. /* Return fake connection structure. Used for logging, if connection
  3098. * is not applicable at the moment of logging. */
  3099. static struct mg_connection *
  3100. fc(struct mg_context *ctx)
  3101. {
  3102. static struct mg_connection fake_connection;
  3103. fake_connection.phys_ctx = ctx;
  3104. fake_connection.dom_ctx = &(ctx->dd);
  3105. return &fake_connection;
  3106. }
  3107. const char *
  3108. mg_version(void)
  3109. {
  3110. return CIVETWEB_VERSION;
  3111. }
  3112. const struct mg_request_info *
  3113. mg_get_request_info(const struct mg_connection *conn)
  3114. {
  3115. if (!conn) {
  3116. return NULL;
  3117. }
  3118. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3119. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3120. char txt[16];
  3121. struct mg_workerTLS *tls =
  3122. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3123. sprintf(txt, "%03i", conn->response_info.status_code);
  3124. if (strlen(txt) == 3) {
  3125. memcpy(tls->txtbuf, txt, 4);
  3126. } else {
  3127. strcpy(tls->txtbuf, "ERR");
  3128. }
  3129. ((struct mg_connection *)conn)->request_info.local_uri =
  3130. ((struct mg_connection *)conn)->request_info.request_uri =
  3131. tls->txtbuf; /* use thread safe buffer */
  3132. ((struct mg_connection *)conn)->request_info.num_headers =
  3133. conn->response_info.num_headers;
  3134. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3135. conn->response_info.http_headers,
  3136. sizeof(conn->response_info.http_headers));
  3137. } else
  3138. #endif
  3139. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3140. return NULL;
  3141. }
  3142. return &conn->request_info;
  3143. }
  3144. const struct mg_response_info *
  3145. mg_get_response_info(const struct mg_connection *conn)
  3146. {
  3147. if (!conn) {
  3148. return NULL;
  3149. }
  3150. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3151. return NULL;
  3152. }
  3153. return &conn->response_info;
  3154. }
  3155. static const char *
  3156. get_proto_name(const struct mg_connection *conn)
  3157. {
  3158. #if defined(__clang__)
  3159. #pragma clang diagnostic push
  3160. #pragma clang diagnostic ignored "-Wunreachable-code"
  3161. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3162. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3163. * unreachable, but splitting into four different #ifdef clauses here is more
  3164. * complicated.
  3165. */
  3166. #endif
  3167. const struct mg_request_info *ri = &conn->request_info;
  3168. const char *proto =
  3169. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3170. : (ri->is_ssl ? "https" : "http"));
  3171. return proto;
  3172. #if defined(__clang__)
  3173. #pragma clang diagnostic pop
  3174. #endif
  3175. }
  3176. int
  3177. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3178. {
  3179. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3180. return -1;
  3181. } else {
  3182. int truncated = 0;
  3183. const struct mg_request_info *ri = &conn->request_info;
  3184. const char *proto = get_proto_name(conn);
  3185. if (ri->local_uri == NULL) {
  3186. return -1;
  3187. }
  3188. if ((ri->request_uri != NULL)
  3189. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3190. /* The request uri is different from the local uri.
  3191. * This is usually if an absolute URI, including server
  3192. * name has been provided. */
  3193. mg_snprintf(conn,
  3194. &truncated,
  3195. buf,
  3196. buflen,
  3197. "%s://%s",
  3198. proto,
  3199. ri->request_uri);
  3200. if (truncated) {
  3201. return -1;
  3202. }
  3203. return 0;
  3204. } else {
  3205. /* The common case is a relative URI, so we have to
  3206. * construct an absolute URI from server name and port */
  3207. #if defined(USE_IPV6)
  3208. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3209. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3210. : htons(conn->client.lsa.sin.sin_port);
  3211. #else
  3212. int port = htons(conn->client.lsa.sin.sin_port);
  3213. #endif
  3214. int def_port = ri->is_ssl ? 443 : 80;
  3215. int auth_domain_check_enabled =
  3216. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3217. && (!mg_strcasecmp(
  3218. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3219. "yes"));
  3220. const char *server_domain =
  3221. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3222. char portstr[16];
  3223. char server_ip[48];
  3224. if (port != def_port) {
  3225. sprintf(portstr, ":%u", (unsigned)port);
  3226. } else {
  3227. portstr[0] = 0;
  3228. }
  3229. if (!auth_domain_check_enabled || !server_domain) {
  3230. sockaddr_to_string(server_ip,
  3231. sizeof(server_ip),
  3232. &conn->client.lsa);
  3233. server_domain = server_ip;
  3234. }
  3235. mg_snprintf(conn,
  3236. &truncated,
  3237. buf,
  3238. buflen,
  3239. "%s://%s%s%s",
  3240. proto,
  3241. server_domain,
  3242. portstr,
  3243. ri->local_uri);
  3244. if (truncated) {
  3245. return -1;
  3246. }
  3247. return 0;
  3248. }
  3249. }
  3250. }
  3251. /* Skip the characters until one of the delimiters characters found.
  3252. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3253. * Advance pointer to buffer to the next word. Return found 0-terminated
  3254. * word.
  3255. * Delimiters can be quoted with quotechar. */
  3256. static char *
  3257. skip_quoted(char **buf,
  3258. const char *delimiters,
  3259. const char *whitespace,
  3260. char quotechar)
  3261. {
  3262. char *p, *begin_word, *end_word, *end_whitespace;
  3263. begin_word = *buf;
  3264. end_word = begin_word + strcspn(begin_word, delimiters);
  3265. /* Check for quotechar */
  3266. if (end_word > begin_word) {
  3267. p = end_word - 1;
  3268. while (*p == quotechar) {
  3269. /* While the delimiter is quoted, look for the next delimiter.
  3270. */
  3271. /* This happens, e.g., in calls from parse_auth_header,
  3272. * if the user name contains a " character. */
  3273. /* If there is anything beyond end_word, copy it. */
  3274. if (*end_word != '\0') {
  3275. size_t end_off = strcspn(end_word + 1, delimiters);
  3276. memmove(p, end_word, end_off + 1);
  3277. p += end_off; /* p must correspond to end_word - 1 */
  3278. end_word += end_off + 1;
  3279. } else {
  3280. *p = '\0';
  3281. break;
  3282. }
  3283. }
  3284. for (p++; p < end_word; p++) {
  3285. *p = '\0';
  3286. }
  3287. }
  3288. if (*end_word == '\0') {
  3289. *buf = end_word;
  3290. } else {
  3291. #if defined(__GNUC__) || defined(__MINGW32__)
  3292. /* Disable spurious conversion warning for GCC */
  3293. #if GCC_VERSION >= 40500
  3294. #pragma GCC diagnostic push
  3295. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3296. #endif /* GCC_VERSION >= 40500 */
  3297. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3298. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3299. #if defined(__GNUC__) || defined(__MINGW32__)
  3300. #if GCC_VERSION >= 40500
  3301. #pragma GCC diagnostic pop
  3302. #endif /* GCC_VERSION >= 40500 */
  3303. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3304. for (p = end_word; p < end_whitespace; p++) {
  3305. *p = '\0';
  3306. }
  3307. *buf = end_whitespace;
  3308. }
  3309. return begin_word;
  3310. }
  3311. /* Return HTTP header value, or NULL if not found. */
  3312. static const char *
  3313. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3314. {
  3315. int i;
  3316. for (i = 0; i < num_hdr; i++) {
  3317. if (!mg_strcasecmp(name, hdr[i].name)) {
  3318. return hdr[i].value;
  3319. }
  3320. }
  3321. return NULL;
  3322. }
  3323. #if defined(USE_WEBSOCKET)
  3324. /* Retrieve requested HTTP header multiple values, and return the number of
  3325. * found occurrences */
  3326. static int
  3327. get_req_headers(const struct mg_request_info *ri,
  3328. const char *name,
  3329. const char **output,
  3330. int output_max_size)
  3331. {
  3332. int i;
  3333. int cnt = 0;
  3334. if (ri) {
  3335. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3336. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3337. output[cnt++] = ri->http_headers[i].value;
  3338. }
  3339. }
  3340. }
  3341. return cnt;
  3342. }
  3343. #endif
  3344. const char *
  3345. mg_get_header(const struct mg_connection *conn, const char *name)
  3346. {
  3347. if (!conn) {
  3348. return NULL;
  3349. }
  3350. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3351. return get_header(conn->request_info.http_headers,
  3352. conn->request_info.num_headers,
  3353. name);
  3354. }
  3355. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3356. return get_header(conn->response_info.http_headers,
  3357. conn->response_info.num_headers,
  3358. name);
  3359. }
  3360. return NULL;
  3361. }
  3362. static const char *
  3363. get_http_version(const struct mg_connection *conn)
  3364. {
  3365. if (!conn) {
  3366. return NULL;
  3367. }
  3368. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3369. return conn->request_info.http_version;
  3370. }
  3371. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3372. return conn->response_info.http_version;
  3373. }
  3374. return NULL;
  3375. }
  3376. /* A helper function for traversing a comma separated list of values.
  3377. * It returns a list pointer shifted to the next value, or NULL if the end
  3378. * of the list found.
  3379. * Value is stored in val vector. If value has form "x=y", then eq_val
  3380. * vector is initialized to point to the "y" part, and val vector length
  3381. * is adjusted to point only to "x". */
  3382. static const char *
  3383. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3384. {
  3385. int end;
  3386. reparse:
  3387. if (val == NULL || list == NULL || *list == '\0') {
  3388. /* End of the list */
  3389. return NULL;
  3390. }
  3391. /* Skip over leading LWS */
  3392. while (*list == ' ' || *list == '\t')
  3393. list++;
  3394. val->ptr = list;
  3395. if ((list = strchr(val->ptr, ',')) != NULL) {
  3396. /* Comma found. Store length and shift the list ptr */
  3397. val->len = ((size_t)(list - val->ptr));
  3398. list++;
  3399. } else {
  3400. /* This value is the last one */
  3401. list = val->ptr + strlen(val->ptr);
  3402. val->len = ((size_t)(list - val->ptr));
  3403. }
  3404. /* Adjust length for trailing LWS */
  3405. end = (int)val->len - 1;
  3406. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3407. end--;
  3408. val->len = (size_t)(end + 1);
  3409. if (val->len == 0) {
  3410. /* Ignore any empty entries. */
  3411. goto reparse;
  3412. }
  3413. if (eq_val != NULL) {
  3414. /* Value has form "x=y", adjust pointers and lengths
  3415. * so that val points to "x", and eq_val points to "y". */
  3416. eq_val->len = 0;
  3417. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3418. if (eq_val->ptr != NULL) {
  3419. eq_val->ptr++; /* Skip over '=' character */
  3420. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3421. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3422. }
  3423. }
  3424. return list;
  3425. }
  3426. /* A helper function for checking if a comma separated list of values
  3427. * contains
  3428. * the given option (case insensitvely).
  3429. * 'header' can be NULL, in which case false is returned. */
  3430. static int
  3431. header_has_option(const char *header, const char *option)
  3432. {
  3433. struct vec opt_vec;
  3434. struct vec eq_vec;
  3435. DEBUG_ASSERT(option != NULL);
  3436. DEBUG_ASSERT(option[0] != '\0');
  3437. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3438. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3439. return 1;
  3440. }
  3441. return 0;
  3442. }
  3443. /* Perform case-insensitive match of string against pattern */
  3444. static ptrdiff_t
  3445. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3446. {
  3447. const char *or_str;
  3448. ptrdiff_t i, j, len, res;
  3449. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3450. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3451. return (res > 0) ? res : match_prefix(or_str + 1,
  3452. (size_t)((pattern + pattern_len)
  3453. - (or_str + 1)),
  3454. str);
  3455. }
  3456. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3457. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3458. continue;
  3459. } else if (pattern[i] == '$') {
  3460. return (str[j] == '\0') ? j : -1;
  3461. } else if (pattern[i] == '*') {
  3462. i++;
  3463. if (pattern[i] == '*') {
  3464. i++;
  3465. len = strlen(str + j);
  3466. } else {
  3467. len = strcspn(str + j, "/");
  3468. }
  3469. if (i == (ptrdiff_t)pattern_len) {
  3470. return j + len;
  3471. }
  3472. do {
  3473. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3474. } while (res == -1 && len-- > 0);
  3475. return (res == -1) ? -1 : j + res + len;
  3476. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3477. return -1;
  3478. }
  3479. }
  3480. return (ptrdiff_t)j;
  3481. }
  3482. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3483. * This function must tolerate situations when connection info is not
  3484. * set up, for example if request parsing failed. */
  3485. static int
  3486. should_keep_alive(const struct mg_connection *conn)
  3487. {
  3488. const char *http_version;
  3489. const char *header;
  3490. /* First satisfy needs of the server */
  3491. if ((conn == NULL) || conn->must_close) {
  3492. /* Close, if civetweb framework needs to close */
  3493. return 0;
  3494. }
  3495. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3496. /* Close, if keep alive is not enabled */
  3497. return 0;
  3498. }
  3499. /* Check explicit wish of the client */
  3500. header = mg_get_header(conn, "Connection");
  3501. if (header) {
  3502. /* If there is a connection header from the client, obey */
  3503. if (header_has_option(header, "keep-alive")) {
  3504. return 1;
  3505. }
  3506. return 0;
  3507. }
  3508. /* Use default of the standard */
  3509. http_version = get_http_version(conn);
  3510. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3511. /* HTTP 1.1 default is keep alive */
  3512. return 1;
  3513. }
  3514. /* HTTP 1.0 (and earlier) default is to close the connection */
  3515. return 0;
  3516. }
  3517. static int
  3518. should_decode_url(const struct mg_connection *conn)
  3519. {
  3520. if (!conn || !conn->dom_ctx) {
  3521. return 0;
  3522. }
  3523. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3524. }
  3525. static const char *
  3526. suggest_connection_header(const struct mg_connection *conn)
  3527. {
  3528. return should_keep_alive(conn) ? "keep-alive" : "close";
  3529. }
  3530. static int
  3531. send_no_cache_header(struct mg_connection *conn)
  3532. {
  3533. /* Send all current and obsolete cache opt-out directives. */
  3534. return mg_printf(conn,
  3535. "Cache-Control: no-cache, no-store, "
  3536. "must-revalidate, private, max-age=0\r\n"
  3537. "Pragma: no-cache\r\n"
  3538. "Expires: 0\r\n");
  3539. }
  3540. static int
  3541. send_static_cache_header(struct mg_connection *conn)
  3542. {
  3543. #if !defined(NO_CACHING)
  3544. /* Read the server config to check how long a file may be cached.
  3545. * The configuration is in seconds. */
  3546. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3547. if (max_age <= 0) {
  3548. /* 0 means "do not cache". All values <0 are reserved
  3549. * and may be used differently in the future. */
  3550. /* If a file should not be cached, do not only send
  3551. * max-age=0, but also pragmas and Expires headers. */
  3552. return send_no_cache_header(conn);
  3553. }
  3554. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3555. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3556. /* See also https://www.mnot.net/cache_docs/ */
  3557. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3558. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3559. * leap
  3560. * year to 31622400 seconds. For the moment, we just send whatever has
  3561. * been configured, still the behavior for >1 year should be considered
  3562. * as undefined. */
  3563. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3564. #else /* NO_CACHING */
  3565. return send_no_cache_header(conn);
  3566. #endif /* !NO_CACHING */
  3567. }
  3568. static int
  3569. send_additional_header(struct mg_connection *conn)
  3570. {
  3571. int i = 0;
  3572. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3573. #if !defined(NO_SSL)
  3574. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3575. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3576. if (max_age >= 0) {
  3577. i += mg_printf(conn,
  3578. "Strict-Transport-Security: max-age=%u\r\n",
  3579. (unsigned)max_age);
  3580. }
  3581. }
  3582. #endif
  3583. if (header && header[0]) {
  3584. i += mg_printf(conn, "%s\r\n", header);
  3585. }
  3586. return i;
  3587. }
  3588. static void handle_file_based_request(struct mg_connection *conn,
  3589. const char *path,
  3590. struct mg_file *filep);
  3591. const char *
  3592. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3593. {
  3594. /* See IANA HTTP status code assignment:
  3595. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3596. */
  3597. switch (response_code) {
  3598. /* RFC2616 Section 10.1 - Informational 1xx */
  3599. case 100:
  3600. return "Continue"; /* RFC2616 Section 10.1.1 */
  3601. case 101:
  3602. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3603. case 102:
  3604. return "Processing"; /* RFC2518 Section 10.1 */
  3605. /* RFC2616 Section 10.2 - Successful 2xx */
  3606. case 200:
  3607. return "OK"; /* RFC2616 Section 10.2.1 */
  3608. case 201:
  3609. return "Created"; /* RFC2616 Section 10.2.2 */
  3610. case 202:
  3611. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3612. case 203:
  3613. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3614. case 204:
  3615. return "No Content"; /* RFC2616 Section 10.2.5 */
  3616. case 205:
  3617. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3618. case 206:
  3619. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3620. case 207:
  3621. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3622. */
  3623. case 208:
  3624. return "Already Reported"; /* RFC5842 Section 7.1 */
  3625. case 226:
  3626. return "IM used"; /* RFC3229 Section 10.4.1 */
  3627. /* RFC2616 Section 10.3 - Redirection 3xx */
  3628. case 300:
  3629. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3630. case 301:
  3631. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3632. case 302:
  3633. return "Found"; /* RFC2616 Section 10.3.3 */
  3634. case 303:
  3635. return "See Other"; /* RFC2616 Section 10.3.4 */
  3636. case 304:
  3637. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3638. case 305:
  3639. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3640. case 307:
  3641. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3642. case 308:
  3643. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3644. /* RFC2616 Section 10.4 - Client Error 4xx */
  3645. case 400:
  3646. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3647. case 401:
  3648. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3649. case 402:
  3650. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3651. case 403:
  3652. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3653. case 404:
  3654. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3655. case 405:
  3656. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3657. case 406:
  3658. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3659. case 407:
  3660. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3661. case 408:
  3662. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3663. case 409:
  3664. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3665. case 410:
  3666. return "Gone"; /* RFC2616 Section 10.4.11 */
  3667. case 411:
  3668. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3669. case 412:
  3670. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3671. case 413:
  3672. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3673. case 414:
  3674. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3675. case 415:
  3676. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3677. case 416:
  3678. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3679. */
  3680. case 417:
  3681. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3682. case 421:
  3683. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3684. case 422:
  3685. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3686. * Section 11.2 */
  3687. case 423:
  3688. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3689. case 424:
  3690. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3691. * Section 11.4 */
  3692. case 426:
  3693. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3694. case 428:
  3695. return "Precondition Required"; /* RFC 6585, Section 3 */
  3696. case 429:
  3697. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3698. case 431:
  3699. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3700. case 451:
  3701. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3702. * Section 3 */
  3703. /* RFC2616 Section 10.5 - Server Error 5xx */
  3704. case 500:
  3705. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3706. case 501:
  3707. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3708. case 502:
  3709. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3710. case 503:
  3711. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3712. case 504:
  3713. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3714. case 505:
  3715. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3716. case 506:
  3717. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3718. case 507:
  3719. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3720. * Section 11.5 */
  3721. case 508:
  3722. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3723. case 510:
  3724. return "Not Extended"; /* RFC 2774, Section 7 */
  3725. case 511:
  3726. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3727. /* Other status codes, not shown in the IANA HTTP status code
  3728. * assignment.
  3729. * E.g., "de facto" standards due to common use, ... */
  3730. case 418:
  3731. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3732. case 419:
  3733. return "Authentication Timeout"; /* common use */
  3734. case 420:
  3735. return "Enhance Your Calm"; /* common use */
  3736. case 440:
  3737. return "Login Timeout"; /* common use */
  3738. case 509:
  3739. return "Bandwidth Limit Exceeded"; /* common use */
  3740. default:
  3741. /* This error code is unknown. This should not happen. */
  3742. if (conn) {
  3743. mg_cry_internal(conn,
  3744. "Unknown HTTP response code: %u",
  3745. response_code);
  3746. }
  3747. /* Return at least a category according to RFC 2616 Section 10. */
  3748. if (response_code >= 100 && response_code < 200) {
  3749. /* Unknown informational status code */
  3750. return "Information";
  3751. }
  3752. if (response_code >= 200 && response_code < 300) {
  3753. /* Unknown success code */
  3754. return "Success";
  3755. }
  3756. if (response_code >= 300 && response_code < 400) {
  3757. /* Unknown redirection code */
  3758. return "Redirection";
  3759. }
  3760. if (response_code >= 400 && response_code < 500) {
  3761. /* Unknown request error code */
  3762. return "Client Error";
  3763. }
  3764. if (response_code >= 500 && response_code < 600) {
  3765. /* Unknown server error code */
  3766. return "Server Error";
  3767. }
  3768. /* Response code not even within reasonable range */
  3769. return "";
  3770. }
  3771. }
  3772. static int
  3773. mg_send_http_error_impl(struct mg_connection *conn,
  3774. int status,
  3775. const char *fmt,
  3776. va_list args)
  3777. {
  3778. char errmsg_buf[MG_BUF_LEN];
  3779. char path_buf[PATH_MAX];
  3780. va_list ap;
  3781. int len, i, page_handler_found, scope, truncated, has_body;
  3782. char date[64];
  3783. time_t curtime = time(NULL);
  3784. const char *error_handler = NULL;
  3785. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3786. const char *error_page_file_ext, *tstr;
  3787. int handled_by_callback = 0;
  3788. const char *status_text = mg_get_response_code_text(conn, status);
  3789. if ((conn == NULL) || (fmt == NULL)) {
  3790. return -2;
  3791. }
  3792. /* Set status (for log) */
  3793. conn->status_code = status;
  3794. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3795. has_body = ((status > 199) && (status != 204) && (status != 304));
  3796. /* Prepare message in buf, if required */
  3797. if (has_body || (!conn->in_error_handler
  3798. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3799. /* Store error message in errmsg_buf */
  3800. va_copy(ap, args);
  3801. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3802. va_end(ap);
  3803. /* In a debug build, print all html errors */
  3804. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3805. }
  3806. /* If there is a http_error callback, call it.
  3807. * But don't do it recursively, if callback calls mg_send_http_error again.
  3808. */
  3809. if (!conn->in_error_handler
  3810. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3811. /* Mark in_error_handler to avoid recursion and call user callback. */
  3812. conn->in_error_handler = 1;
  3813. handled_by_callback =
  3814. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3815. == 0);
  3816. conn->in_error_handler = 0;
  3817. }
  3818. if (!handled_by_callback) {
  3819. /* Check for recursion */
  3820. if (conn->in_error_handler) {
  3821. DEBUG_TRACE(
  3822. "Recursion when handling error %u - fall back to default",
  3823. status);
  3824. } else {
  3825. /* Send user defined error pages, if defined */
  3826. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3827. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3828. page_handler_found = 0;
  3829. if (error_handler != NULL) {
  3830. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3831. switch (scope) {
  3832. case 1: /* Handler for specific error, e.g. 404 error */
  3833. mg_snprintf(conn,
  3834. &truncated,
  3835. path_buf,
  3836. sizeof(path_buf) - 32,
  3837. "%serror%03u.",
  3838. error_handler,
  3839. status);
  3840. break;
  3841. case 2: /* Handler for error group, e.g., 5xx error
  3842. * handler
  3843. * for all server errors (500-599) */
  3844. mg_snprintf(conn,
  3845. &truncated,
  3846. path_buf,
  3847. sizeof(path_buf) - 32,
  3848. "%serror%01uxx.",
  3849. error_handler,
  3850. status / 100);
  3851. break;
  3852. default: /* Handler for all errors */
  3853. mg_snprintf(conn,
  3854. &truncated,
  3855. path_buf,
  3856. sizeof(path_buf) - 32,
  3857. "%serror.",
  3858. error_handler);
  3859. break;
  3860. }
  3861. /* String truncation in buf may only occur if
  3862. * error_handler is too long. This string is
  3863. * from the config, not from a client. */
  3864. (void)truncated;
  3865. len = (int)strlen(path_buf);
  3866. tstr = strchr(error_page_file_ext, '.');
  3867. while (tstr) {
  3868. for (i = 1;
  3869. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3870. i++) {
  3871. /* buffer overrun is not possible here, since
  3872. * (i < 32) && (len < sizeof(path_buf) - 32)
  3873. * ==> (i + len) < sizeof(path_buf) */
  3874. path_buf[len + i - 1] = tstr[i];
  3875. }
  3876. /* buffer overrun is not possible here, since
  3877. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3878. * ==> (i + len) <= sizeof(path_buf) */
  3879. path_buf[len + i - 1] = 0;
  3880. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3881. DEBUG_TRACE("Check error page %s - found",
  3882. path_buf);
  3883. page_handler_found = 1;
  3884. break;
  3885. }
  3886. DEBUG_TRACE("Check error page %s - not found",
  3887. path_buf);
  3888. tstr = strchr(tstr + i, '.');
  3889. }
  3890. }
  3891. }
  3892. if (page_handler_found) {
  3893. conn->in_error_handler = 1;
  3894. handle_file_based_request(conn, path_buf, &error_page_file);
  3895. conn->in_error_handler = 0;
  3896. return 0;
  3897. }
  3898. }
  3899. /* No custom error page. Send default error page. */
  3900. gmt_time_string(date, sizeof(date), &curtime);
  3901. conn->must_close = 1;
  3902. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3903. send_no_cache_header(conn);
  3904. send_additional_header(conn);
  3905. if (has_body) {
  3906. mg_printf(conn,
  3907. "%s",
  3908. "Content-Type: text/plain; charset=utf-8\r\n");
  3909. }
  3910. mg_printf(conn,
  3911. "Date: %s\r\n"
  3912. "Connection: close\r\n\r\n",
  3913. date);
  3914. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3915. if (has_body) {
  3916. /* For other errors, send a generic error message. */
  3917. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3918. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3919. } else {
  3920. /* No body allowed. Close the connection. */
  3921. DEBUG_TRACE("Error %i", status);
  3922. }
  3923. }
  3924. return 0;
  3925. }
  3926. int
  3927. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3928. {
  3929. va_list ap;
  3930. int ret;
  3931. va_start(ap, fmt);
  3932. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3933. va_end(ap);
  3934. return ret;
  3935. }
  3936. int
  3937. mg_send_http_ok(struct mg_connection *conn,
  3938. const char *mime_type,
  3939. long long content_length)
  3940. {
  3941. char date[64];
  3942. time_t curtime = time(NULL);
  3943. if ((mime_type == NULL) || (*mime_type == 0)) {
  3944. /* Parameter error */
  3945. return -2;
  3946. }
  3947. gmt_time_string(date, sizeof(date), &curtime);
  3948. mg_printf(conn,
  3949. "HTTP/1.1 200 OK\r\n"
  3950. "Content-Type: %s\r\n"
  3951. "Date: %s\r\n"
  3952. "Connection: %s\r\n",
  3953. mime_type,
  3954. date,
  3955. suggest_connection_header(conn));
  3956. send_no_cache_header(conn);
  3957. send_additional_header(conn);
  3958. if (content_length < 0) {
  3959. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  3960. } else {
  3961. mg_printf(conn,
  3962. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  3963. (uint64_t)content_length);
  3964. }
  3965. return 0;
  3966. }
  3967. int
  3968. mg_send_http_redirect(struct mg_connection *conn,
  3969. const char *target_url,
  3970. int redirect_code)
  3971. {
  3972. /* Send a 30x redirect response.
  3973. *
  3974. * Redirect types (status codes):
  3975. *
  3976. * Status | Perm/Temp | Method | Version
  3977. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3978. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3979. * 303 | temporary | always use GET | HTTP/1.1
  3980. * 307 | temporary | always keep method | HTTP/1.1
  3981. * 308 | permanent | always keep method | HTTP/1.1
  3982. */
  3983. const char *redirect_text;
  3984. int ret;
  3985. size_t content_len = 0;
  3986. char reply[MG_BUF_LEN];
  3987. /* In case redirect_code=0, use 307. */
  3988. if (redirect_code == 0) {
  3989. redirect_code = 307;
  3990. }
  3991. /* In case redirect_code is none of the above, return error. */
  3992. if ((redirect_code != 301) && (redirect_code != 302)
  3993. && (redirect_code != 303) && (redirect_code != 307)
  3994. && (redirect_code != 308)) {
  3995. /* Parameter error */
  3996. return -2;
  3997. }
  3998. /* Get proper text for response code */
  3999. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4000. /* If target_url is not defined, redirect to "/". */
  4001. if ((target_url == NULL) || (*target_url == 0)) {
  4002. target_url = "/";
  4003. }
  4004. #if defined(MG_SEND_REDIRECT_BODY)
  4005. /* TODO: condition name? */
  4006. /* Prepare a response body with a hyperlink.
  4007. *
  4008. * According to RFC2616 (and RFC1945 before):
  4009. * Unless the request method was HEAD, the entity of the
  4010. * response SHOULD contain a short hypertext note with a hyperlink to
  4011. * the new URI(s).
  4012. *
  4013. * However, this response body is not useful in M2M communication.
  4014. * Probably the original reason in the RFC was, clients not supporting
  4015. * a 30x HTTP redirect could still show the HTML page and let the user
  4016. * press the link. Since current browsers support 30x HTTP, the additional
  4017. * HTML body does not seem to make sense anymore.
  4018. *
  4019. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4020. * but it only notes:
  4021. * The server's response payload usually contains a short
  4022. * hypertext note with a hyperlink to the new URI(s).
  4023. *
  4024. * Deactivated by default. If you need the 30x body, set the define.
  4025. */
  4026. mg_snprintf(
  4027. conn,
  4028. NULL /* ignore truncation */,
  4029. reply,
  4030. sizeof(reply),
  4031. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4032. redirect_text,
  4033. target_url,
  4034. target_url);
  4035. content_len = strlen(reply);
  4036. #else
  4037. reply[0] = 0;
  4038. #endif
  4039. /* Do not send any additional header. For all other options,
  4040. * including caching, there are suitable defaults. */
  4041. ret = mg_printf(conn,
  4042. "HTTP/1.1 %i %s\r\n"
  4043. "Location: %s\r\n"
  4044. "Content-Length: %u\r\n"
  4045. "Connection: %s\r\n\r\n",
  4046. redirect_code,
  4047. redirect_text,
  4048. target_url,
  4049. (unsigned int)content_len,
  4050. suggest_connection_header(conn));
  4051. /* Send response body */
  4052. if (ret > 0) {
  4053. /* ... unless it is a HEAD request */
  4054. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4055. ret = mg_write(conn, reply, content_len);
  4056. }
  4057. }
  4058. return (ret > 0) ? ret : -1;
  4059. }
  4060. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4061. /* Create substitutes for POSIX functions in Win32. */
  4062. #if defined(__MINGW32__)
  4063. /* Show no warning in case system functions are not used. */
  4064. #pragma GCC diagnostic push
  4065. #pragma GCC diagnostic ignored "-Wunused-function"
  4066. #endif
  4067. FUNCTION_MAY_BE_UNUSED
  4068. static int
  4069. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4070. {
  4071. (void)unused;
  4072. *mutex = CreateMutex(NULL, FALSE, NULL);
  4073. return (*mutex == NULL) ? -1 : 0;
  4074. }
  4075. FUNCTION_MAY_BE_UNUSED
  4076. static int
  4077. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4078. {
  4079. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  4080. }
  4081. FUNCTION_MAY_BE_UNUSED
  4082. static int
  4083. pthread_mutex_lock(pthread_mutex_t *mutex)
  4084. {
  4085. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  4086. : -1;
  4087. }
  4088. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  4089. FUNCTION_MAY_BE_UNUSED
  4090. static int
  4091. pthread_mutex_trylock(pthread_mutex_t *mutex)
  4092. {
  4093. switch (WaitForSingleObject(*mutex, 0)) {
  4094. case WAIT_OBJECT_0:
  4095. return 0;
  4096. case WAIT_TIMEOUT:
  4097. return -2; /* EBUSY */
  4098. }
  4099. return -1;
  4100. }
  4101. #endif
  4102. FUNCTION_MAY_BE_UNUSED
  4103. static int
  4104. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4105. {
  4106. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  4107. }
  4108. FUNCTION_MAY_BE_UNUSED
  4109. static int
  4110. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4111. {
  4112. (void)unused;
  4113. InitializeCriticalSection(&cv->threadIdSec);
  4114. cv->waiting_thread = NULL;
  4115. return 0;
  4116. }
  4117. FUNCTION_MAY_BE_UNUSED
  4118. static int
  4119. pthread_cond_timedwait(pthread_cond_t *cv,
  4120. pthread_mutex_t *mutex,
  4121. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4122. {
  4123. struct mg_workerTLS **ptls,
  4124. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4125. int ok;
  4126. int64_t nsnow, nswaitabs, nswaitrel;
  4127. DWORD mswaitrel;
  4128. EnterCriticalSection(&cv->threadIdSec);
  4129. /* Add this thread to cv's waiting list */
  4130. ptls = &cv->waiting_thread;
  4131. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4132. ;
  4133. tls->next_waiting_thread = NULL;
  4134. *ptls = tls;
  4135. LeaveCriticalSection(&cv->threadIdSec);
  4136. if (abstime) {
  4137. nsnow = mg_get_current_time_ns();
  4138. nswaitabs =
  4139. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4140. nswaitrel = nswaitabs - nsnow;
  4141. if (nswaitrel < 0) {
  4142. nswaitrel = 0;
  4143. }
  4144. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4145. } else {
  4146. mswaitrel = (DWORD)INFINITE;
  4147. }
  4148. pthread_mutex_unlock(mutex);
  4149. ok = (WAIT_OBJECT_0
  4150. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4151. if (!ok) {
  4152. ok = 1;
  4153. EnterCriticalSection(&cv->threadIdSec);
  4154. ptls = &cv->waiting_thread;
  4155. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4156. if (*ptls == tls) {
  4157. *ptls = tls->next_waiting_thread;
  4158. ok = 0;
  4159. break;
  4160. }
  4161. }
  4162. LeaveCriticalSection(&cv->threadIdSec);
  4163. if (ok) {
  4164. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4165. (DWORD)INFINITE);
  4166. }
  4167. }
  4168. /* This thread has been removed from cv's waiting list */
  4169. pthread_mutex_lock(mutex);
  4170. return ok ? 0 : -1;
  4171. }
  4172. FUNCTION_MAY_BE_UNUSED
  4173. static int
  4174. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4175. {
  4176. return pthread_cond_timedwait(cv, mutex, NULL);
  4177. }
  4178. FUNCTION_MAY_BE_UNUSED
  4179. static int
  4180. pthread_cond_signal(pthread_cond_t *cv)
  4181. {
  4182. HANDLE wkup = NULL;
  4183. BOOL ok = FALSE;
  4184. EnterCriticalSection(&cv->threadIdSec);
  4185. if (cv->waiting_thread) {
  4186. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4187. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4188. ok = SetEvent(wkup);
  4189. DEBUG_ASSERT(ok);
  4190. }
  4191. LeaveCriticalSection(&cv->threadIdSec);
  4192. return ok ? 0 : 1;
  4193. }
  4194. FUNCTION_MAY_BE_UNUSED
  4195. static int
  4196. pthread_cond_broadcast(pthread_cond_t *cv)
  4197. {
  4198. EnterCriticalSection(&cv->threadIdSec);
  4199. while (cv->waiting_thread) {
  4200. pthread_cond_signal(cv);
  4201. }
  4202. LeaveCriticalSection(&cv->threadIdSec);
  4203. return 0;
  4204. }
  4205. FUNCTION_MAY_BE_UNUSED
  4206. static int
  4207. pthread_cond_destroy(pthread_cond_t *cv)
  4208. {
  4209. EnterCriticalSection(&cv->threadIdSec);
  4210. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4211. LeaveCriticalSection(&cv->threadIdSec);
  4212. DeleteCriticalSection(&cv->threadIdSec);
  4213. return 0;
  4214. }
  4215. #if defined(ALTERNATIVE_QUEUE)
  4216. FUNCTION_MAY_BE_UNUSED
  4217. static void *
  4218. event_create(void)
  4219. {
  4220. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4221. }
  4222. FUNCTION_MAY_BE_UNUSED
  4223. static int
  4224. event_wait(void *eventhdl)
  4225. {
  4226. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4227. return (res == WAIT_OBJECT_0);
  4228. }
  4229. FUNCTION_MAY_BE_UNUSED
  4230. static int
  4231. event_signal(void *eventhdl)
  4232. {
  4233. return (int)SetEvent((HANDLE)eventhdl);
  4234. }
  4235. FUNCTION_MAY_BE_UNUSED
  4236. static void
  4237. event_destroy(void *eventhdl)
  4238. {
  4239. CloseHandle((HANDLE)eventhdl);
  4240. }
  4241. #endif
  4242. #if defined(__MINGW32__)
  4243. /* Enable unused function warning again */
  4244. #pragma GCC diagnostic pop
  4245. #endif
  4246. /* For Windows, change all slashes to backslashes in path names. */
  4247. static void
  4248. change_slashes_to_backslashes(char *path)
  4249. {
  4250. int i;
  4251. for (i = 0; path[i] != '\0'; i++) {
  4252. if (path[i] == '/') {
  4253. path[i] = '\\';
  4254. }
  4255. /* remove double backslash (check i > 0 to preserve UNC paths,
  4256. * like \\server\file.txt) */
  4257. if ((path[i] == '\\') && (i > 0)) {
  4258. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4259. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4260. }
  4261. }
  4262. }
  4263. }
  4264. static int
  4265. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4266. {
  4267. int diff;
  4268. do {
  4269. diff = tolower(*s1) - tolower(*s2);
  4270. s1++;
  4271. s2++;
  4272. } while ((diff == 0) && (s1[-1] != '\0'));
  4273. return diff;
  4274. }
  4275. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4276. * wbuf and wbuf_len is a target buffer and its length. */
  4277. static void
  4278. path_to_unicode(const struct mg_connection *conn,
  4279. const char *path,
  4280. wchar_t *wbuf,
  4281. size_t wbuf_len)
  4282. {
  4283. char buf[PATH_MAX], buf2[PATH_MAX];
  4284. wchar_t wbuf2[W_PATH_MAX + 1];
  4285. DWORD long_len, err;
  4286. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4287. mg_strlcpy(buf, path, sizeof(buf));
  4288. change_slashes_to_backslashes(buf);
  4289. /* Convert to Unicode and back. If doubly-converted string does not
  4290. * match the original, something is fishy, reject. */
  4291. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4292. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4293. WideCharToMultiByte(
  4294. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4295. if (strcmp(buf, buf2) != 0) {
  4296. wbuf[0] = L'\0';
  4297. }
  4298. /* Windows file systems are not case sensitive, but you can still use
  4299. * uppercase and lowercase letters (on all modern file systems).
  4300. * The server can check if the URI uses the same upper/lowercase
  4301. * letters an the file system, effectively making Windows servers
  4302. * case sensitive (like Linux servers are). It is still not possible
  4303. * to use two files with the same name in different cases on Windows
  4304. * (like /a and /A) - this would be possible in Linux.
  4305. * As a default, Windows is not case sensitive, but the case sensitive
  4306. * file name check can be activated by an additional configuration. */
  4307. if (conn) {
  4308. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4309. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4310. "yes")) {
  4311. /* Use case sensitive compare function */
  4312. fcompare = wcscmp;
  4313. }
  4314. }
  4315. (void)conn; /* conn is currently unused */
  4316. #if !defined(_WIN32_WCE)
  4317. /* Only accept a full file path, not a Windows short (8.3) path. */
  4318. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4319. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4320. if (long_len == 0) {
  4321. err = GetLastError();
  4322. if (err == ERROR_FILE_NOT_FOUND) {
  4323. /* File does not exist. This is not always a problem here. */
  4324. return;
  4325. }
  4326. }
  4327. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4328. /* Short name is used. */
  4329. wbuf[0] = L'\0';
  4330. }
  4331. #else
  4332. (void)long_len;
  4333. (void)wbuf2;
  4334. (void)err;
  4335. if (strchr(path, '~')) {
  4336. wbuf[0] = L'\0';
  4337. }
  4338. #endif
  4339. }
  4340. /* Windows happily opens files with some garbage at the end of file name.
  4341. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4342. * "a.cgi", despite one would expect an error back.
  4343. * This function returns non-0 if path ends with some garbage. */
  4344. static int
  4345. path_cannot_disclose_cgi(const char *path)
  4346. {
  4347. static const char *allowed_last_characters = "_-";
  4348. int last = path[strlen(path) - 1];
  4349. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4350. }
  4351. static int
  4352. mg_stat(const struct mg_connection *conn,
  4353. const char *path,
  4354. struct mg_file_stat *filep)
  4355. {
  4356. wchar_t wbuf[W_PATH_MAX];
  4357. WIN32_FILE_ATTRIBUTE_DATA info;
  4358. time_t creation_time;
  4359. if (!filep) {
  4360. return 0;
  4361. }
  4362. memset(filep, 0, sizeof(*filep));
  4363. if (conn && is_file_in_memory(conn, path)) {
  4364. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4365. * memset */
  4366. /* Quick fix (for 1.9.x): */
  4367. /* mg_stat must fill all fields, also for files in memory */
  4368. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4369. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4370. filep->size = tmp_file.stat.size;
  4371. filep->location = 2;
  4372. /* TODO: for 1.10: restructure how files in memory are handled */
  4373. /* The "file in memory" feature is a candidate for deletion.
  4374. * Please join the discussion at
  4375. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4376. */
  4377. filep->last_modified = time(NULL); /* TODO */
  4378. /* last_modified = now ... assumes the file may change during
  4379. * runtime,
  4380. * so every mg_fopen call may return different data */
  4381. /* last_modified = conn->phys_ctx.start_time;
  4382. * May be used it the data does not change during runtime. This
  4383. * allows
  4384. * browser caching. Since we do not know, we have to assume the file
  4385. * in memory may change. */
  4386. return 1;
  4387. }
  4388. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4389. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4390. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4391. filep->last_modified =
  4392. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4393. info.ftLastWriteTime.dwHighDateTime);
  4394. /* On Windows, the file creation time can be higher than the
  4395. * modification time, e.g. when a file is copied.
  4396. * Since the Last-Modified timestamp is used for caching
  4397. * it should be based on the most recent timestamp. */
  4398. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4399. info.ftCreationTime.dwHighDateTime);
  4400. if (creation_time > filep->last_modified) {
  4401. filep->last_modified = creation_time;
  4402. }
  4403. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4404. /* If file name is fishy, reset the file structure and return
  4405. * error.
  4406. * Note it is important to reset, not just return the error, cause
  4407. * functions like is_file_opened() check the struct. */
  4408. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4409. memset(filep, 0, sizeof(*filep));
  4410. return 0;
  4411. }
  4412. return 1;
  4413. }
  4414. return 0;
  4415. }
  4416. static int
  4417. mg_remove(const struct mg_connection *conn, const char *path)
  4418. {
  4419. wchar_t wbuf[W_PATH_MAX];
  4420. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4421. return DeleteFileW(wbuf) ? 0 : -1;
  4422. }
  4423. static int
  4424. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4425. {
  4426. wchar_t wbuf[W_PATH_MAX];
  4427. (void)mode;
  4428. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4429. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4430. }
  4431. /* Create substitutes for POSIX functions in Win32. */
  4432. #if defined(__MINGW32__)
  4433. /* Show no warning in case system functions are not used. */
  4434. #pragma GCC diagnostic push
  4435. #pragma GCC diagnostic ignored "-Wunused-function"
  4436. #endif
  4437. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4438. FUNCTION_MAY_BE_UNUSED
  4439. static DIR *
  4440. mg_opendir(const struct mg_connection *conn, const char *name)
  4441. {
  4442. DIR *dir = NULL;
  4443. wchar_t wpath[W_PATH_MAX];
  4444. DWORD attrs;
  4445. if (name == NULL) {
  4446. SetLastError(ERROR_BAD_ARGUMENTS);
  4447. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4448. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4449. } else {
  4450. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4451. attrs = GetFileAttributesW(wpath);
  4452. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4453. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4454. (void)wcscat(wpath, L"\\*");
  4455. dir->handle = FindFirstFileW(wpath, &dir->info);
  4456. dir->result.d_name[0] = '\0';
  4457. } else {
  4458. mg_free(dir);
  4459. dir = NULL;
  4460. }
  4461. }
  4462. return dir;
  4463. }
  4464. FUNCTION_MAY_BE_UNUSED
  4465. static int
  4466. mg_closedir(DIR *dir)
  4467. {
  4468. int result = 0;
  4469. if (dir != NULL) {
  4470. if (dir->handle != INVALID_HANDLE_VALUE)
  4471. result = FindClose(dir->handle) ? 0 : -1;
  4472. mg_free(dir);
  4473. } else {
  4474. result = -1;
  4475. SetLastError(ERROR_BAD_ARGUMENTS);
  4476. }
  4477. return result;
  4478. }
  4479. FUNCTION_MAY_BE_UNUSED
  4480. static struct dirent *
  4481. mg_readdir(DIR *dir)
  4482. {
  4483. struct dirent *result = 0;
  4484. if (dir) {
  4485. if (dir->handle != INVALID_HANDLE_VALUE) {
  4486. result = &dir->result;
  4487. (void)WideCharToMultiByte(CP_UTF8,
  4488. 0,
  4489. dir->info.cFileName,
  4490. -1,
  4491. result->d_name,
  4492. sizeof(result->d_name),
  4493. NULL,
  4494. NULL);
  4495. if (!FindNextFileW(dir->handle, &dir->info)) {
  4496. (void)FindClose(dir->handle);
  4497. dir->handle = INVALID_HANDLE_VALUE;
  4498. }
  4499. } else {
  4500. SetLastError(ERROR_FILE_NOT_FOUND);
  4501. }
  4502. } else {
  4503. SetLastError(ERROR_BAD_ARGUMENTS);
  4504. }
  4505. return result;
  4506. }
  4507. #if !defined(HAVE_POLL)
  4508. FUNCTION_MAY_BE_UNUSED
  4509. static int
  4510. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4511. {
  4512. struct timeval tv;
  4513. fd_set set;
  4514. unsigned int i;
  4515. int result;
  4516. SOCKET maxfd = 0;
  4517. memset(&tv, 0, sizeof(tv));
  4518. tv.tv_sec = milliseconds / 1000;
  4519. tv.tv_usec = (milliseconds % 1000) * 1000;
  4520. FD_ZERO(&set);
  4521. for (i = 0; i < n; i++) {
  4522. FD_SET((SOCKET)pfd[i].fd, &set);
  4523. pfd[i].revents = 0;
  4524. if (pfd[i].fd > maxfd) {
  4525. maxfd = pfd[i].fd;
  4526. }
  4527. }
  4528. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4529. for (i = 0; i < n; i++) {
  4530. if (FD_ISSET(pfd[i].fd, &set)) {
  4531. pfd[i].revents = POLLIN;
  4532. }
  4533. }
  4534. }
  4535. /* We should subtract the time used in select from remaining
  4536. * "milliseconds", in particular if called from mg_poll with a
  4537. * timeout quantum.
  4538. * Unfortunately, the remaining time is not stored in "tv" in all
  4539. * implementations, so the result in "tv" must be considered undefined.
  4540. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4541. return result;
  4542. }
  4543. #endif /* HAVE_POLL */
  4544. #if defined(__MINGW32__)
  4545. /* Enable unused function warning again */
  4546. #pragma GCC diagnostic pop
  4547. #endif
  4548. static void
  4549. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4550. {
  4551. (void)conn; /* Unused. */
  4552. #if defined(_WIN32_WCE)
  4553. (void)sock;
  4554. #else
  4555. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4556. #endif
  4557. }
  4558. int
  4559. mg_start_thread(mg_thread_func_t f, void *p)
  4560. {
  4561. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4562. /* Compile-time option to control stack size, e.g.
  4563. * -DUSE_STACK_SIZE=16384
  4564. */
  4565. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4566. == ((uintptr_t)(-1L)))
  4567. ? -1
  4568. : 0);
  4569. #else
  4570. return (
  4571. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4572. ? -1
  4573. : 0);
  4574. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4575. }
  4576. /* Start a thread storing the thread context. */
  4577. static int
  4578. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4579. void *p,
  4580. pthread_t *threadidptr)
  4581. {
  4582. uintptr_t uip;
  4583. HANDLE threadhandle;
  4584. int result = -1;
  4585. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4586. threadhandle = (HANDLE)uip;
  4587. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4588. *threadidptr = threadhandle;
  4589. result = 0;
  4590. }
  4591. return result;
  4592. }
  4593. /* Wait for a thread to finish. */
  4594. static int
  4595. mg_join_thread(pthread_t threadid)
  4596. {
  4597. int result;
  4598. DWORD dwevent;
  4599. result = -1;
  4600. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4601. if (dwevent == WAIT_FAILED) {
  4602. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4603. } else {
  4604. if (dwevent == WAIT_OBJECT_0) {
  4605. CloseHandle(threadid);
  4606. result = 0;
  4607. }
  4608. }
  4609. return result;
  4610. }
  4611. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4612. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4613. /* Create substitutes for POSIX functions in Win32. */
  4614. #if defined(__MINGW32__)
  4615. /* Show no warning in case system functions are not used. */
  4616. #pragma GCC diagnostic push
  4617. #pragma GCC diagnostic ignored "-Wunused-function"
  4618. #endif
  4619. FUNCTION_MAY_BE_UNUSED
  4620. static HANDLE
  4621. dlopen(const char *dll_name, int flags)
  4622. {
  4623. wchar_t wbuf[W_PATH_MAX];
  4624. (void)flags;
  4625. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4626. return LoadLibraryW(wbuf);
  4627. }
  4628. FUNCTION_MAY_BE_UNUSED
  4629. static int
  4630. dlclose(void *handle)
  4631. {
  4632. int result;
  4633. if (FreeLibrary((HMODULE)handle) != 0) {
  4634. result = 0;
  4635. } else {
  4636. result = -1;
  4637. }
  4638. return result;
  4639. }
  4640. #if defined(__MINGW32__)
  4641. /* Enable unused function warning again */
  4642. #pragma GCC diagnostic pop
  4643. #endif
  4644. #endif
  4645. #if !defined(NO_CGI)
  4646. #define SIGKILL (0)
  4647. static int
  4648. kill(pid_t pid, int sig_num)
  4649. {
  4650. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4651. (void)CloseHandle((HANDLE)pid);
  4652. return 0;
  4653. }
  4654. #ifndef WNOHANG
  4655. #define WNOHANG (1)
  4656. #endif
  4657. pid_t
  4658. waitpid(pid_t pid, int *status, int flags)
  4659. {
  4660. DWORD timeout = INFINITE;
  4661. DWORD waitres;
  4662. (void)status; /* Currently not used by any client here */
  4663. if ((flags | WNOHANG) == WNOHANG) {
  4664. timeout = 0;
  4665. }
  4666. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4667. if (waitres == WAIT_OBJECT_0) {
  4668. return pid;
  4669. }
  4670. if (waitres == WAIT_TIMEOUT) {
  4671. return 0;
  4672. }
  4673. return (pid_t)-1;
  4674. }
  4675. static void
  4676. trim_trailing_whitespaces(char *s)
  4677. {
  4678. char *e = s + strlen(s) - 1;
  4679. while ((e > s) && isspace(*(unsigned char *)e)) {
  4680. *e-- = '\0';
  4681. }
  4682. }
  4683. static pid_t
  4684. spawn_process(struct mg_connection *conn,
  4685. const char *prog,
  4686. char *envblk,
  4687. char *envp[],
  4688. int fdin[2],
  4689. int fdout[2],
  4690. int fderr[2],
  4691. const char *dir)
  4692. {
  4693. HANDLE me;
  4694. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4695. cmdline[PATH_MAX], buf[PATH_MAX];
  4696. int truncated;
  4697. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4698. STARTUPINFOA si;
  4699. PROCESS_INFORMATION pi = {0};
  4700. (void)envp;
  4701. memset(&si, 0, sizeof(si));
  4702. si.cb = sizeof(si);
  4703. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4704. si.wShowWindow = SW_HIDE;
  4705. me = GetCurrentProcess();
  4706. DuplicateHandle(me,
  4707. (HANDLE)_get_osfhandle(fdin[0]),
  4708. me,
  4709. &si.hStdInput,
  4710. 0,
  4711. TRUE,
  4712. DUPLICATE_SAME_ACCESS);
  4713. DuplicateHandle(me,
  4714. (HANDLE)_get_osfhandle(fdout[1]),
  4715. me,
  4716. &si.hStdOutput,
  4717. 0,
  4718. TRUE,
  4719. DUPLICATE_SAME_ACCESS);
  4720. DuplicateHandle(me,
  4721. (HANDLE)_get_osfhandle(fderr[1]),
  4722. me,
  4723. &si.hStdError,
  4724. 0,
  4725. TRUE,
  4726. DUPLICATE_SAME_ACCESS);
  4727. /* Mark handles that should not be inherited. See
  4728. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4729. */
  4730. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4731. HANDLE_FLAG_INHERIT,
  4732. 0);
  4733. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4734. HANDLE_FLAG_INHERIT,
  4735. 0);
  4736. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4737. HANDLE_FLAG_INHERIT,
  4738. 0);
  4739. /* If CGI file is a script, try to read the interpreter line */
  4740. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4741. if (interp == NULL) {
  4742. buf[0] = buf[1] = '\0';
  4743. /* Read the first line of the script into the buffer */
  4744. mg_snprintf(
  4745. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4746. if (truncated) {
  4747. pi.hProcess = (pid_t)-1;
  4748. goto spawn_cleanup;
  4749. }
  4750. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4751. #if defined(MG_USE_OPEN_FILE)
  4752. p = (char *)file.access.membuf;
  4753. #else
  4754. p = (char *)NULL;
  4755. #endif
  4756. mg_fgets(buf, sizeof(buf), &file, &p);
  4757. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4758. buf[sizeof(buf) - 1] = '\0';
  4759. }
  4760. if ((buf[0] == '#') && (buf[1] == '!')) {
  4761. trim_trailing_whitespaces(buf + 2);
  4762. } else {
  4763. buf[2] = '\0';
  4764. }
  4765. interp = buf + 2;
  4766. }
  4767. if (interp[0] != '\0') {
  4768. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4769. interp = full_interp;
  4770. }
  4771. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4772. if (interp[0] != '\0') {
  4773. mg_snprintf(conn,
  4774. &truncated,
  4775. cmdline,
  4776. sizeof(cmdline),
  4777. "\"%s\" \"%s\\%s\"",
  4778. interp,
  4779. full_dir,
  4780. prog);
  4781. } else {
  4782. mg_snprintf(conn,
  4783. &truncated,
  4784. cmdline,
  4785. sizeof(cmdline),
  4786. "\"%s\\%s\"",
  4787. full_dir,
  4788. prog);
  4789. }
  4790. if (truncated) {
  4791. pi.hProcess = (pid_t)-1;
  4792. goto spawn_cleanup;
  4793. }
  4794. DEBUG_TRACE("Running [%s]", cmdline);
  4795. if (CreateProcessA(NULL,
  4796. cmdline,
  4797. NULL,
  4798. NULL,
  4799. TRUE,
  4800. CREATE_NEW_PROCESS_GROUP,
  4801. envblk,
  4802. NULL,
  4803. &si,
  4804. &pi) == 0) {
  4805. mg_cry_internal(
  4806. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4807. pi.hProcess = (pid_t)-1;
  4808. /* goto spawn_cleanup; */
  4809. }
  4810. spawn_cleanup:
  4811. (void)CloseHandle(si.hStdOutput);
  4812. (void)CloseHandle(si.hStdError);
  4813. (void)CloseHandle(si.hStdInput);
  4814. if (pi.hThread != NULL) {
  4815. (void)CloseHandle(pi.hThread);
  4816. }
  4817. return (pid_t)pi.hProcess;
  4818. }
  4819. #endif /* !NO_CGI */
  4820. static int
  4821. set_blocking_mode(SOCKET sock)
  4822. {
  4823. unsigned long non_blocking = 0;
  4824. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4825. }
  4826. static int
  4827. set_non_blocking_mode(SOCKET sock)
  4828. {
  4829. unsigned long non_blocking = 1;
  4830. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4831. }
  4832. #else
  4833. static int
  4834. mg_stat(const struct mg_connection *conn,
  4835. const char *path,
  4836. struct mg_file_stat *filep)
  4837. {
  4838. struct stat st;
  4839. if (!filep) {
  4840. return 0;
  4841. }
  4842. memset(filep, 0, sizeof(*filep));
  4843. if (conn && is_file_in_memory(conn, path)) {
  4844. /* Quick fix (for 1.9.x): */
  4845. /* mg_stat must fill all fields, also for files in memory */
  4846. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4847. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4848. filep->size = tmp_file.stat.size;
  4849. filep->last_modified = time(NULL);
  4850. filep->location = 2;
  4851. /* TODO: remove legacy "files in memory" feature */
  4852. return 1;
  4853. }
  4854. if (0 == stat(path, &st)) {
  4855. filep->size = (uint64_t)(st.st_size);
  4856. filep->last_modified = st.st_mtime;
  4857. filep->is_directory = S_ISDIR(st.st_mode);
  4858. return 1;
  4859. }
  4860. return 0;
  4861. }
  4862. static void
  4863. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4864. {
  4865. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4866. if (conn) {
  4867. mg_cry_internal(conn,
  4868. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4869. __func__,
  4870. strerror(ERRNO));
  4871. }
  4872. }
  4873. }
  4874. int
  4875. mg_start_thread(mg_thread_func_t func, void *param)
  4876. {
  4877. pthread_t thread_id;
  4878. pthread_attr_t attr;
  4879. int result;
  4880. (void)pthread_attr_init(&attr);
  4881. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4882. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4883. /* Compile-time option to control stack size,
  4884. * e.g. -DUSE_STACK_SIZE=16384 */
  4885. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4886. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4887. result = pthread_create(&thread_id, &attr, func, param);
  4888. pthread_attr_destroy(&attr);
  4889. return result;
  4890. }
  4891. /* Start a thread storing the thread context. */
  4892. static int
  4893. mg_start_thread_with_id(mg_thread_func_t func,
  4894. void *param,
  4895. pthread_t *threadidptr)
  4896. {
  4897. pthread_t thread_id;
  4898. pthread_attr_t attr;
  4899. int result;
  4900. (void)pthread_attr_init(&attr);
  4901. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4902. /* Compile-time option to control stack size,
  4903. * e.g. -DUSE_STACK_SIZE=16384 */
  4904. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4905. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4906. result = pthread_create(&thread_id, &attr, func, param);
  4907. pthread_attr_destroy(&attr);
  4908. if ((result == 0) && (threadidptr != NULL)) {
  4909. *threadidptr = thread_id;
  4910. }
  4911. return result;
  4912. }
  4913. /* Wait for a thread to finish. */
  4914. static int
  4915. mg_join_thread(pthread_t threadid)
  4916. {
  4917. int result;
  4918. result = pthread_join(threadid, NULL);
  4919. return result;
  4920. }
  4921. #if !defined(NO_CGI)
  4922. static pid_t
  4923. spawn_process(struct mg_connection *conn,
  4924. const char *prog,
  4925. char *envblk,
  4926. char *envp[],
  4927. int fdin[2],
  4928. int fdout[2],
  4929. int fderr[2],
  4930. const char *dir)
  4931. {
  4932. pid_t pid;
  4933. const char *interp;
  4934. (void)envblk;
  4935. if (conn == NULL) {
  4936. return 0;
  4937. }
  4938. if ((pid = fork()) == -1) {
  4939. /* Parent */
  4940. mg_send_http_error(conn,
  4941. 500,
  4942. "Error: Creating CGI process\nfork(): %s",
  4943. strerror(ERRNO));
  4944. } else if (pid == 0) {
  4945. /* Child */
  4946. if (chdir(dir) != 0) {
  4947. mg_cry_internal(
  4948. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4949. } else if (dup2(fdin[0], 0) == -1) {
  4950. mg_cry_internal(conn,
  4951. "%s: dup2(%d, 0): %s",
  4952. __func__,
  4953. fdin[0],
  4954. strerror(ERRNO));
  4955. } else if (dup2(fdout[1], 1) == -1) {
  4956. mg_cry_internal(conn,
  4957. "%s: dup2(%d, 1): %s",
  4958. __func__,
  4959. fdout[1],
  4960. strerror(ERRNO));
  4961. } else if (dup2(fderr[1], 2) == -1) {
  4962. mg_cry_internal(conn,
  4963. "%s: dup2(%d, 2): %s",
  4964. __func__,
  4965. fderr[1],
  4966. strerror(ERRNO));
  4967. } else {
  4968. /* Keep stderr and stdout in two different pipes.
  4969. * Stdout will be sent back to the client,
  4970. * stderr should go into a server error log. */
  4971. (void)close(fdin[0]);
  4972. (void)close(fdout[1]);
  4973. (void)close(fderr[1]);
  4974. /* Close write end fdin and read end fdout and fderr */
  4975. (void)close(fdin[1]);
  4976. (void)close(fdout[0]);
  4977. (void)close(fderr[0]);
  4978. /* After exec, all signal handlers are restored to their default
  4979. * values, with one exception of SIGCHLD. According to
  4980. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4981. * will leave unchanged after exec if it was set to be ignored.
  4982. * Restore it to default action. */
  4983. signal(SIGCHLD, SIG_DFL);
  4984. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4985. if (interp == NULL) {
  4986. (void)execle(prog, prog, NULL, envp);
  4987. mg_cry_internal(conn,
  4988. "%s: execle(%s): %s",
  4989. __func__,
  4990. prog,
  4991. strerror(ERRNO));
  4992. } else {
  4993. (void)execle(interp, interp, prog, NULL, envp);
  4994. mg_cry_internal(conn,
  4995. "%s: execle(%s %s): %s",
  4996. __func__,
  4997. interp,
  4998. prog,
  4999. strerror(ERRNO));
  5000. }
  5001. }
  5002. exit(EXIT_FAILURE);
  5003. }
  5004. return pid;
  5005. }
  5006. #endif /* !NO_CGI */
  5007. static int
  5008. set_non_blocking_mode(SOCKET sock)
  5009. {
  5010. int flags = fcntl(sock, F_GETFL, 0);
  5011. if (flags < 0) {
  5012. return -1;
  5013. }
  5014. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5015. return -1;
  5016. }
  5017. return 0;
  5018. }
  5019. static int
  5020. set_blocking_mode(SOCKET sock)
  5021. {
  5022. int flags = fcntl(sock, F_GETFL, 0);
  5023. if (flags < 0) {
  5024. return -1;
  5025. }
  5026. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5027. return -1;
  5028. }
  5029. return 0;
  5030. }
  5031. #endif /* _WIN32 / else */
  5032. /* End of initial operating system specific define block. */
  5033. /* Get a random number (independent of C rand function) */
  5034. static uint64_t
  5035. get_random(void)
  5036. {
  5037. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5038. static uint64_t lcg = 0; /* Linear congruential generator */
  5039. uint64_t now = mg_get_current_time_ns();
  5040. if (lfsr == 0) {
  5041. /* lfsr will be only 0 if has not been initialized,
  5042. * so this code is called only once. */
  5043. lfsr = mg_get_current_time_ns();
  5044. lcg = mg_get_current_time_ns();
  5045. } else {
  5046. /* Get the next step of both random number generators. */
  5047. lfsr = (lfsr >> 1)
  5048. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5049. << 63);
  5050. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5051. }
  5052. /* Combining two pseudo-random number generators and a high resolution
  5053. * part
  5054. * of the current server time will make it hard (impossible?) to guess
  5055. * the
  5056. * next number. */
  5057. return (lfsr ^ lcg ^ now);
  5058. }
  5059. static int
  5060. mg_poll(struct pollfd *pfd,
  5061. unsigned int n,
  5062. int milliseconds,
  5063. volatile int *stop_server)
  5064. {
  5065. /* Call poll, but only for a maximum time of a few seconds.
  5066. * This will allow to stop the server after some seconds, instead
  5067. * of having to wait for a long socket timeout. */
  5068. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5069. do {
  5070. int result;
  5071. if (*stop_server) {
  5072. /* Shut down signal */
  5073. return -2;
  5074. }
  5075. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5076. ms_now = milliseconds;
  5077. }
  5078. result = poll(pfd, n, ms_now);
  5079. if (result != 0) {
  5080. /* Poll returned either success (1) or error (-1).
  5081. * Forward both to the caller. */
  5082. return result;
  5083. }
  5084. /* Poll returned timeout (0). */
  5085. if (milliseconds > 0) {
  5086. milliseconds -= ms_now;
  5087. }
  5088. } while (milliseconds != 0);
  5089. /* timeout: return 0 */
  5090. return 0;
  5091. }
  5092. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5093. * descriptor.
  5094. * Return value:
  5095. * >=0 .. number of bytes successfully written
  5096. * -1 .. timeout
  5097. * -2 .. error
  5098. */
  5099. static int
  5100. push_inner(struct mg_context *ctx,
  5101. FILE *fp,
  5102. SOCKET sock,
  5103. SSL *ssl,
  5104. const char *buf,
  5105. int len,
  5106. double timeout)
  5107. {
  5108. uint64_t start = 0, now = 0, timeout_ns = 0;
  5109. int n, err;
  5110. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5111. #if defined(_WIN32)
  5112. typedef int len_t;
  5113. #else
  5114. typedef size_t len_t;
  5115. #endif
  5116. if (timeout > 0) {
  5117. now = mg_get_current_time_ns();
  5118. start = now;
  5119. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5120. }
  5121. if (ctx == NULL) {
  5122. return -2;
  5123. }
  5124. #if defined(NO_SSL)
  5125. if (ssl) {
  5126. return -2;
  5127. }
  5128. #endif
  5129. /* Try to read until it succeeds, fails, times out, or the server
  5130. * shuts down. */
  5131. for (;;) {
  5132. #if !defined(NO_SSL)
  5133. if (ssl != NULL) {
  5134. n = SSL_write(ssl, buf, len);
  5135. if (n <= 0) {
  5136. err = SSL_get_error(ssl, n);
  5137. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5138. err = ERRNO;
  5139. } else if ((err == SSL_ERROR_WANT_READ)
  5140. || (err == SSL_ERROR_WANT_WRITE)) {
  5141. n = 0;
  5142. } else {
  5143. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5144. return -2;
  5145. }
  5146. } else {
  5147. err = 0;
  5148. }
  5149. } else
  5150. #endif
  5151. if (fp != NULL) {
  5152. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5153. if (ferror(fp)) {
  5154. n = -1;
  5155. err = ERRNO;
  5156. } else {
  5157. err = 0;
  5158. }
  5159. } else {
  5160. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5161. err = (n < 0) ? ERRNO : 0;
  5162. #if defined(_WIN32)
  5163. if (err == WSAEWOULDBLOCK) {
  5164. err = 0;
  5165. n = 0;
  5166. }
  5167. #else
  5168. if (err == EWOULDBLOCK) {
  5169. err = 0;
  5170. n = 0;
  5171. }
  5172. #endif
  5173. if (n < 0) {
  5174. /* shutdown of the socket at client side */
  5175. return -2;
  5176. }
  5177. }
  5178. if (ctx->stop_flag) {
  5179. return -2;
  5180. }
  5181. if ((n > 0) || ((n == 0) && (len == 0))) {
  5182. /* some data has been read, or no data was requested */
  5183. return n;
  5184. }
  5185. if (n < 0) {
  5186. /* socket error - check errno */
  5187. DEBUG_TRACE("send() failed, error %d", err);
  5188. /* TODO (mid): error handling depending on the error code.
  5189. * These codes are different between Windows and Linux.
  5190. * Currently there is no problem with failing send calls,
  5191. * if there is a reproducible situation, it should be
  5192. * investigated in detail.
  5193. */
  5194. return -2;
  5195. }
  5196. /* Only in case n=0 (timeout), repeat calling the write function */
  5197. /* If send failed, wait before retry */
  5198. if (fp != NULL) {
  5199. /* For files, just wait a fixed time.
  5200. * Maybe it helps, maybe not. */
  5201. mg_sleep(5);
  5202. } else {
  5203. /* For sockets, wait for the socket using select */
  5204. fd_set wfds;
  5205. struct timeval tv;
  5206. int sret;
  5207. #if defined(__GNUC__) || defined(__MINGW32__)
  5208. /* GCC seems to have a flaw with it's own socket macros:
  5209. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  5210. */
  5211. #pragma GCC diagnostic push
  5212. #pragma GCC diagnostic ignored "-Wsign-conversion"
  5213. #endif
  5214. FD_ZERO(&wfds);
  5215. FD_SET(sock, &wfds);
  5216. tv.tv_sec = (time_t)(ms_wait / 1000);
  5217. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  5218. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  5219. #if defined(__GNUC__) || defined(__MINGW32__)
  5220. #pragma GCC diagnostic pop
  5221. #endif
  5222. if (sret > 0) {
  5223. /* We got ready to write. Don't check the timeout
  5224. * but directly go back to write again. */
  5225. continue;
  5226. }
  5227. }
  5228. if (timeout > 0) {
  5229. now = mg_get_current_time_ns();
  5230. if ((now - start) > timeout_ns) {
  5231. /* Timeout */
  5232. break;
  5233. }
  5234. }
  5235. }
  5236. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5237. used */
  5238. return -1;
  5239. }
  5240. static int64_t
  5241. push_all(struct mg_context *ctx,
  5242. FILE *fp,
  5243. SOCKET sock,
  5244. SSL *ssl,
  5245. const char *buf,
  5246. int64_t len)
  5247. {
  5248. double timeout = -1.0;
  5249. int64_t n, nwritten = 0;
  5250. if (ctx == NULL) {
  5251. return -1;
  5252. }
  5253. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5254. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5255. }
  5256. while ((len > 0) && (ctx->stop_flag == 0)) {
  5257. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  5258. if (n < 0) {
  5259. if (nwritten == 0) {
  5260. nwritten = n; /* Propagate the error */
  5261. }
  5262. break;
  5263. } else if (n == 0) {
  5264. break; /* No more data to write */
  5265. } else {
  5266. nwritten += n;
  5267. len -= n;
  5268. }
  5269. }
  5270. return nwritten;
  5271. }
  5272. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5273. * Return value:
  5274. * >=0 .. number of bytes successfully read
  5275. * -1 .. timeout
  5276. * -2 .. error
  5277. */
  5278. static int
  5279. pull_inner(FILE *fp,
  5280. struct mg_connection *conn,
  5281. char *buf,
  5282. int len,
  5283. double timeout)
  5284. {
  5285. int nread, err = 0;
  5286. #if defined(_WIN32)
  5287. typedef int len_t;
  5288. #else
  5289. typedef size_t len_t;
  5290. #endif
  5291. #if !defined(NO_SSL)
  5292. int ssl_pending;
  5293. #endif
  5294. /* We need an additional wait loop around this, because in some cases
  5295. * with TLSwe may get data from the socket but not from SSL_read.
  5296. * In this case we need to repeat at least once.
  5297. */
  5298. if (fp != NULL) {
  5299. #if !defined(_WIN32_WCE)
  5300. /* Use read() instead of fread(), because if we're reading from the
  5301. * CGI pipe, fread() may block until IO buffer is filled up. We
  5302. * cannot afford to block and must pass all read bytes immediately
  5303. * to the client. */
  5304. nread = (int)read(fileno(fp), buf, (size_t)len);
  5305. #else
  5306. /* WinCE does not support CGI pipes */
  5307. nread = (int)fread(buf, 1, (size_t)len, fp);
  5308. #endif
  5309. err = (nread < 0) ? ERRNO : 0;
  5310. if ((nread == 0) && (len > 0)) {
  5311. /* Should get data, but got EOL */
  5312. return -2;
  5313. }
  5314. #if !defined(NO_SSL)
  5315. } else if ((conn->ssl != NULL)
  5316. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5317. /* We already know there is no more data buffered in conn->buf
  5318. * but there is more available in the SSL layer. So don't poll
  5319. * conn->client.sock yet. */
  5320. if (ssl_pending > len) {
  5321. ssl_pending = len;
  5322. }
  5323. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5324. if (nread <= 0) {
  5325. err = SSL_get_error(conn->ssl, nread);
  5326. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5327. err = ERRNO;
  5328. } else if ((err == SSL_ERROR_WANT_READ)
  5329. || (err == SSL_ERROR_WANT_WRITE)) {
  5330. nread = 0;
  5331. } else {
  5332. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5333. return -1;
  5334. }
  5335. } else {
  5336. err = 0;
  5337. }
  5338. } else if (conn->ssl != NULL) {
  5339. struct pollfd pfd[1];
  5340. int pollres;
  5341. pfd[0].fd = conn->client.sock;
  5342. pfd[0].events = POLLIN;
  5343. pollres = mg_poll(pfd,
  5344. 1,
  5345. (int)(timeout * 1000.0),
  5346. &(conn->phys_ctx->stop_flag));
  5347. if (conn->phys_ctx->stop_flag) {
  5348. return -2;
  5349. }
  5350. if (pollres > 0) {
  5351. nread = SSL_read(conn->ssl, buf, len);
  5352. if (nread <= 0) {
  5353. err = SSL_get_error(conn->ssl, nread);
  5354. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5355. err = ERRNO;
  5356. } else if ((err == SSL_ERROR_WANT_READ)
  5357. || (err == SSL_ERROR_WANT_WRITE)) {
  5358. nread = 0;
  5359. } else {
  5360. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5361. return -2;
  5362. }
  5363. } else {
  5364. err = 0;
  5365. }
  5366. } else if (pollres < 0) {
  5367. /* Error */
  5368. return -2;
  5369. } else {
  5370. /* pollres = 0 means timeout */
  5371. nread = 0;
  5372. }
  5373. #endif
  5374. } else {
  5375. struct pollfd pfd[1];
  5376. int pollres;
  5377. pfd[0].fd = conn->client.sock;
  5378. pfd[0].events = POLLIN;
  5379. pollres = mg_poll(pfd,
  5380. 1,
  5381. (int)(timeout * 1000.0),
  5382. &(conn->phys_ctx->stop_flag));
  5383. if (conn->phys_ctx->stop_flag) {
  5384. return -2;
  5385. }
  5386. if (pollres > 0) {
  5387. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5388. err = (nread < 0) ? ERRNO : 0;
  5389. if (nread <= 0) {
  5390. /* shutdown of the socket at client side */
  5391. return -2;
  5392. }
  5393. } else if (pollres < 0) {
  5394. /* error callint poll */
  5395. return -2;
  5396. } else {
  5397. /* pollres = 0 means timeout */
  5398. nread = 0;
  5399. }
  5400. }
  5401. if (conn->phys_ctx->stop_flag) {
  5402. return -2;
  5403. }
  5404. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5405. /* some data has been read, or no data was requested */
  5406. return nread;
  5407. }
  5408. if (nread < 0) {
  5409. /* socket error - check errno */
  5410. #if defined(_WIN32)
  5411. if (err == WSAEWOULDBLOCK) {
  5412. /* TODO (low): check if this is still required */
  5413. /* standard case if called from close_socket_gracefully */
  5414. return -2;
  5415. } else if (err == WSAETIMEDOUT) {
  5416. /* TODO (low): check if this is still required */
  5417. /* timeout is handled by the while loop */
  5418. return 0;
  5419. } else if (err == WSAECONNABORTED) {
  5420. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5421. return -2;
  5422. } else {
  5423. DEBUG_TRACE("recv() failed, error %d", err);
  5424. return -2;
  5425. }
  5426. #else
  5427. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5428. * if the timeout is reached and if the socket was set to non-
  5429. * blocking in close_socket_gracefully, so we can not distinguish
  5430. * here. We have to wait for the timeout in both cases for now.
  5431. */
  5432. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5433. /* TODO (low): check if this is still required */
  5434. /* EAGAIN/EWOULDBLOCK:
  5435. * standard case if called from close_socket_gracefully
  5436. * => should return -1 */
  5437. /* or timeout occurred
  5438. * => the code must stay in the while loop */
  5439. /* EINTR can be generated on a socket with a timeout set even
  5440. * when SA_RESTART is effective for all relevant signals
  5441. * (see signal(7)).
  5442. * => stay in the while loop */
  5443. } else {
  5444. DEBUG_TRACE("recv() failed, error %d", err);
  5445. return -2;
  5446. }
  5447. #endif
  5448. }
  5449. /* Timeout occurred, but no data available. */
  5450. return -1;
  5451. }
  5452. static int
  5453. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5454. {
  5455. int n, nread = 0;
  5456. double timeout = -1.0;
  5457. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5458. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5459. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5460. }
  5461. if (timeout >= 0.0) {
  5462. start_time = mg_get_current_time_ns();
  5463. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5464. }
  5465. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5466. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5467. if (n == -2) {
  5468. if (nread == 0) {
  5469. nread = -1; /* Propagate the error */
  5470. }
  5471. break;
  5472. } else if (n == -1) {
  5473. /* timeout */
  5474. if (timeout >= 0.0) {
  5475. now = mg_get_current_time_ns();
  5476. if ((now - start_time) <= timeout_ns) {
  5477. continue;
  5478. }
  5479. }
  5480. break;
  5481. } else if (n == 0) {
  5482. break; /* No more data to read */
  5483. } else {
  5484. conn->consumed_content += n;
  5485. nread += n;
  5486. len -= n;
  5487. }
  5488. }
  5489. return nread;
  5490. }
  5491. static void
  5492. discard_unread_request_data(struct mg_connection *conn)
  5493. {
  5494. char buf[MG_BUF_LEN];
  5495. size_t to_read;
  5496. int nread;
  5497. if (conn == NULL) {
  5498. return;
  5499. }
  5500. to_read = sizeof(buf);
  5501. if (conn->is_chunked) {
  5502. /* Chunked encoding: 3=chunk read completely
  5503. * completely */
  5504. while (conn->is_chunked != 3) {
  5505. nread = mg_read(conn, buf, to_read);
  5506. if (nread <= 0) {
  5507. break;
  5508. }
  5509. }
  5510. } else {
  5511. /* Not chunked: content length is known */
  5512. while (conn->consumed_content < conn->content_len) {
  5513. if (to_read
  5514. > (size_t)(conn->content_len - conn->consumed_content)) {
  5515. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5516. }
  5517. nread = mg_read(conn, buf, to_read);
  5518. if (nread <= 0) {
  5519. break;
  5520. }
  5521. }
  5522. }
  5523. }
  5524. static int
  5525. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5526. {
  5527. int64_t n, buffered_len, nread;
  5528. int64_t len64 =
  5529. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5530. * int, we may not read more
  5531. * bytes */
  5532. const char *body;
  5533. if (conn == NULL) {
  5534. return 0;
  5535. }
  5536. /* If Content-Length is not set for a request with body data
  5537. * (e.g., a PUT or POST request), we do not know in advance
  5538. * how much data should be read. */
  5539. if (conn->consumed_content == 0) {
  5540. if (conn->is_chunked == 1) {
  5541. conn->content_len = len64;
  5542. conn->is_chunked = 2;
  5543. } else if (conn->content_len == -1) {
  5544. /* The body data is completed when the connection
  5545. * is closed. */
  5546. conn->content_len = INT64_MAX;
  5547. conn->must_close = 1;
  5548. }
  5549. }
  5550. nread = 0;
  5551. if (conn->consumed_content < conn->content_len) {
  5552. /* Adjust number of bytes to read. */
  5553. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5554. if (left_to_read < len64) {
  5555. /* Do not read more than the total content length of the
  5556. * request.
  5557. */
  5558. len64 = left_to_read;
  5559. }
  5560. /* Return buffered data */
  5561. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5562. - conn->consumed_content;
  5563. if (buffered_len > 0) {
  5564. if (len64 < buffered_len) {
  5565. buffered_len = len64;
  5566. }
  5567. body = conn->buf + conn->request_len + conn->consumed_content;
  5568. memcpy(buf, body, (size_t)buffered_len);
  5569. len64 -= buffered_len;
  5570. conn->consumed_content += buffered_len;
  5571. nread += buffered_len;
  5572. buf = (char *)buf + buffered_len;
  5573. }
  5574. /* We have returned all buffered data. Read new data from the remote
  5575. * socket.
  5576. */
  5577. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5578. nread += n;
  5579. } else {
  5580. nread = ((nread > 0) ? nread : n);
  5581. }
  5582. }
  5583. return (int)nread;
  5584. }
  5585. static char
  5586. mg_getc(struct mg_connection *conn)
  5587. {
  5588. char c;
  5589. if (conn == NULL) {
  5590. return 0;
  5591. }
  5592. if (mg_read_inner(conn, &c, 1) <= 0) {
  5593. return (char)0;
  5594. }
  5595. return c;
  5596. }
  5597. int
  5598. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5599. {
  5600. if (len > INT_MAX) {
  5601. len = INT_MAX;
  5602. }
  5603. if (conn == NULL) {
  5604. return 0;
  5605. }
  5606. if (conn->is_chunked) {
  5607. size_t all_read = 0;
  5608. while (len > 0) {
  5609. if (conn->is_chunked == 3) {
  5610. /* No more data left to read */
  5611. return 0;
  5612. }
  5613. if (conn->chunk_remainder) {
  5614. /* copy from the remainder of the last received chunk */
  5615. long read_ret;
  5616. size_t read_now =
  5617. ((conn->chunk_remainder > len) ? (len)
  5618. : (conn->chunk_remainder));
  5619. conn->content_len += (int)read_now;
  5620. read_ret =
  5621. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5622. if (read_ret < 1) {
  5623. /* read error */
  5624. return -1;
  5625. }
  5626. all_read += (size_t)read_ret;
  5627. conn->chunk_remainder -= (size_t)read_ret;
  5628. len -= (size_t)read_ret;
  5629. if (conn->chunk_remainder == 0) {
  5630. /* Add data bytes in the current chunk have been read,
  5631. * so we are expecting \r\n now. */
  5632. char x1, x2;
  5633. conn->content_len += 2;
  5634. x1 = mg_getc(conn);
  5635. x2 = mg_getc(conn);
  5636. if ((x1 != '\r') || (x2 != '\n')) {
  5637. /* Protocol violation */
  5638. return -1;
  5639. }
  5640. }
  5641. } else {
  5642. /* fetch a new chunk */
  5643. int i = 0;
  5644. char lenbuf[64];
  5645. char *end = 0;
  5646. unsigned long chunkSize = 0;
  5647. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5648. conn->content_len++;
  5649. lenbuf[i] = mg_getc(conn);
  5650. if ((i > 0) && (lenbuf[i] == '\r')
  5651. && (lenbuf[i - 1] != '\r')) {
  5652. continue;
  5653. }
  5654. if ((i > 1) && (lenbuf[i] == '\n')
  5655. && (lenbuf[i - 1] == '\r')) {
  5656. lenbuf[i + 1] = 0;
  5657. chunkSize = strtoul(lenbuf, &end, 16);
  5658. if (chunkSize == 0) {
  5659. /* regular end of content */
  5660. conn->is_chunked = 3;
  5661. }
  5662. break;
  5663. }
  5664. if (!isxdigit(lenbuf[i])) {
  5665. /* illegal character for chunk length */
  5666. return -1;
  5667. }
  5668. }
  5669. if ((end == NULL) || (*end != '\r')) {
  5670. /* chunksize not set correctly */
  5671. return -1;
  5672. }
  5673. if (chunkSize == 0) {
  5674. break;
  5675. }
  5676. conn->chunk_remainder = chunkSize;
  5677. }
  5678. }
  5679. return (int)all_read;
  5680. }
  5681. return mg_read_inner(conn, buf, len);
  5682. }
  5683. int
  5684. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5685. {
  5686. time_t now;
  5687. int64_t n, total, allowed;
  5688. if (conn == NULL) {
  5689. return 0;
  5690. }
  5691. if (conn->throttle > 0) {
  5692. if ((now = time(NULL)) != conn->last_throttle_time) {
  5693. conn->last_throttle_time = now;
  5694. conn->last_throttle_bytes = 0;
  5695. }
  5696. allowed = conn->throttle - conn->last_throttle_bytes;
  5697. if (allowed > (int64_t)len) {
  5698. allowed = (int64_t)len;
  5699. }
  5700. if ((total = push_all(conn->phys_ctx,
  5701. NULL,
  5702. conn->client.sock,
  5703. conn->ssl,
  5704. (const char *)buf,
  5705. (int64_t)allowed)) == allowed) {
  5706. buf = (const char *)buf + total;
  5707. conn->last_throttle_bytes += total;
  5708. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5709. allowed = (conn->throttle > ((int64_t)len - total))
  5710. ? (int64_t)len - total
  5711. : conn->throttle;
  5712. if ((n = push_all(conn->phys_ctx,
  5713. NULL,
  5714. conn->client.sock,
  5715. conn->ssl,
  5716. (const char *)buf,
  5717. (int64_t)allowed)) != allowed) {
  5718. break;
  5719. }
  5720. sleep(1);
  5721. conn->last_throttle_bytes = allowed;
  5722. conn->last_throttle_time = time(NULL);
  5723. buf = (const char *)buf + n;
  5724. total += n;
  5725. }
  5726. }
  5727. } else {
  5728. total = push_all(conn->phys_ctx,
  5729. NULL,
  5730. conn->client.sock,
  5731. conn->ssl,
  5732. (const char *)buf,
  5733. (int64_t)len);
  5734. }
  5735. if (total > 0) {
  5736. conn->num_bytes_sent += total;
  5737. }
  5738. return (int)total;
  5739. }
  5740. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5741. int
  5742. mg_send_chunk(struct mg_connection *conn,
  5743. const char *chunk,
  5744. unsigned int chunk_len)
  5745. {
  5746. char lenbuf[16];
  5747. size_t lenbuf_len;
  5748. int ret;
  5749. int t;
  5750. /* First store the length information in a text buffer. */
  5751. sprintf(lenbuf, "%x\r\n", chunk_len);
  5752. lenbuf_len = strlen(lenbuf);
  5753. /* Then send length information, chunk and terminating \r\n. */
  5754. ret = mg_write(conn, lenbuf, lenbuf_len);
  5755. if (ret != (int)lenbuf_len) {
  5756. return -1;
  5757. }
  5758. t = ret;
  5759. ret = mg_write(conn, chunk, chunk_len);
  5760. if (ret != (int)chunk_len) {
  5761. return -1;
  5762. }
  5763. t += ret;
  5764. ret = mg_write(conn, "\r\n", 2);
  5765. if (ret != 2) {
  5766. return -1;
  5767. }
  5768. t += ret;
  5769. return t;
  5770. }
  5771. #if defined(__GNUC__) || defined(__MINGW32__)
  5772. /* This block forwards format strings to printf implementations,
  5773. * so we need to disable the format-nonliteral warning. */
  5774. #pragma GCC diagnostic push
  5775. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5776. #endif
  5777. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5778. static int
  5779. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5780. {
  5781. va_list ap_copy;
  5782. size_t size = MG_BUF_LEN / 4;
  5783. int len = -1;
  5784. *buf = NULL;
  5785. while (len < 0) {
  5786. if (*buf) {
  5787. mg_free(*buf);
  5788. }
  5789. size *= 4;
  5790. *buf = (char *)mg_malloc(size);
  5791. if (!*buf) {
  5792. break;
  5793. }
  5794. va_copy(ap_copy, ap);
  5795. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5796. va_end(ap_copy);
  5797. (*buf)[size - 1] = 0;
  5798. }
  5799. return len;
  5800. }
  5801. /* Print message to buffer. If buffer is large enough to hold the message,
  5802. * return buffer. If buffer is to small, allocate large enough buffer on
  5803. * heap,
  5804. * and return allocated buffer. */
  5805. static int
  5806. alloc_vprintf(char **out_buf,
  5807. char *prealloc_buf,
  5808. size_t prealloc_size,
  5809. const char *fmt,
  5810. va_list ap)
  5811. {
  5812. va_list ap_copy;
  5813. int len;
  5814. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5815. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5816. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5817. * Therefore, we make two passes: on first pass, get required message
  5818. * length.
  5819. * On second pass, actually print the message. */
  5820. va_copy(ap_copy, ap);
  5821. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5822. va_end(ap_copy);
  5823. if (len < 0) {
  5824. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5825. * Switch to alternative code path that uses incremental
  5826. * allocations.
  5827. */
  5828. va_copy(ap_copy, ap);
  5829. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5830. va_end(ap_copy);
  5831. } else if ((size_t)(len) >= prealloc_size) {
  5832. /* The pre-allocated buffer not large enough. */
  5833. /* Allocate a new buffer. */
  5834. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5835. if (!*out_buf) {
  5836. /* Allocation failed. Return -1 as "out of memory" error. */
  5837. return -1;
  5838. }
  5839. /* Buffer allocation successful. Store the string there. */
  5840. va_copy(ap_copy, ap);
  5841. IGNORE_UNUSED_RESULT(
  5842. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5843. va_end(ap_copy);
  5844. } else {
  5845. /* The pre-allocated buffer is large enough.
  5846. * Use it to store the string and return the address. */
  5847. va_copy(ap_copy, ap);
  5848. IGNORE_UNUSED_RESULT(
  5849. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5850. va_end(ap_copy);
  5851. *out_buf = prealloc_buf;
  5852. }
  5853. return len;
  5854. }
  5855. #if defined(__GNUC__) || defined(__MINGW32__)
  5856. /* Enable format-nonliteral warning again. */
  5857. #pragma GCC diagnostic pop
  5858. #endif
  5859. static int
  5860. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5861. {
  5862. char mem[MG_BUF_LEN];
  5863. char *buf = NULL;
  5864. int len;
  5865. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5866. len = mg_write(conn, buf, (size_t)len);
  5867. }
  5868. if ((buf != mem) && (buf != NULL)) {
  5869. mg_free(buf);
  5870. }
  5871. return len;
  5872. }
  5873. int
  5874. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5875. {
  5876. va_list ap;
  5877. int result;
  5878. va_start(ap, fmt);
  5879. result = mg_vprintf(conn, fmt, ap);
  5880. va_end(ap);
  5881. return result;
  5882. }
  5883. int
  5884. mg_url_decode(const char *src,
  5885. int src_len,
  5886. char *dst,
  5887. int dst_len,
  5888. int is_form_url_encoded)
  5889. {
  5890. int i, j, a, b;
  5891. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5892. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5893. if ((i < src_len - 2) && (src[i] == '%')
  5894. && isxdigit(*(const unsigned char *)(src + i + 1))
  5895. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5896. a = tolower(*(const unsigned char *)(src + i + 1));
  5897. b = tolower(*(const unsigned char *)(src + i + 2));
  5898. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5899. i += 2;
  5900. } else if (is_form_url_encoded && (src[i] == '+')) {
  5901. dst[j] = ' ';
  5902. } else {
  5903. dst[j] = src[i];
  5904. }
  5905. }
  5906. dst[j] = '\0'; /* Null-terminate the destination */
  5907. return (i >= src_len) ? j : -1;
  5908. }
  5909. int
  5910. mg_get_var(const char *data,
  5911. size_t data_len,
  5912. const char *name,
  5913. char *dst,
  5914. size_t dst_len)
  5915. {
  5916. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5917. }
  5918. int
  5919. mg_get_var2(const char *data,
  5920. size_t data_len,
  5921. const char *name,
  5922. char *dst,
  5923. size_t dst_len,
  5924. size_t occurrence)
  5925. {
  5926. const char *p, *e, *s;
  5927. size_t name_len;
  5928. int len;
  5929. if ((dst == NULL) || (dst_len == 0)) {
  5930. len = -2;
  5931. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5932. len = -1;
  5933. dst[0] = '\0';
  5934. } else {
  5935. name_len = strlen(name);
  5936. e = data + data_len;
  5937. len = -1;
  5938. dst[0] = '\0';
  5939. /* data is "var1=val1&var2=val2...". Find variable first */
  5940. for (p = data; p + name_len < e; p++) {
  5941. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5942. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5943. /* Point p to variable value */
  5944. p += name_len + 1;
  5945. /* Point s to the end of the value */
  5946. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5947. if (s == NULL) {
  5948. s = e;
  5949. }
  5950. DEBUG_ASSERT(s >= p);
  5951. if (s < p) {
  5952. return -3;
  5953. }
  5954. /* Decode variable into destination buffer */
  5955. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5956. /* Redirect error code from -1 to -2 (destination buffer too
  5957. * small). */
  5958. if (len == -1) {
  5959. len = -2;
  5960. }
  5961. break;
  5962. }
  5963. }
  5964. }
  5965. return len;
  5966. }
  5967. /* HCP24: some changes to compare hole var_name */
  5968. int
  5969. mg_get_cookie(const char *cookie_header,
  5970. const char *var_name,
  5971. char *dst,
  5972. size_t dst_size)
  5973. {
  5974. const char *s, *p, *end;
  5975. int name_len, len = -1;
  5976. if ((dst == NULL) || (dst_size == 0)) {
  5977. return -2;
  5978. }
  5979. dst[0] = '\0';
  5980. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5981. return -1;
  5982. }
  5983. name_len = (int)strlen(var_name);
  5984. end = s + strlen(s);
  5985. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5986. if (s[name_len] == '=') {
  5987. /* HCP24: now check is it a substring or a full cookie name */
  5988. if ((s == cookie_header) || (s[-1] == ' ')) {
  5989. s += name_len + 1;
  5990. if ((p = strchr(s, ' ')) == NULL) {
  5991. p = end;
  5992. }
  5993. if (p[-1] == ';') {
  5994. p--;
  5995. }
  5996. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5997. s++;
  5998. p--;
  5999. }
  6000. if ((size_t)(p - s) < dst_size) {
  6001. len = (int)(p - s);
  6002. mg_strlcpy(dst, s, (size_t)len + 1);
  6003. } else {
  6004. len = -3;
  6005. }
  6006. break;
  6007. }
  6008. }
  6009. }
  6010. return len;
  6011. }
  6012. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6013. static void
  6014. base64_encode(const unsigned char *src, int src_len, char *dst)
  6015. {
  6016. static const char *b64 =
  6017. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6018. int i, j, a, b, c;
  6019. for (i = j = 0; i < src_len; i += 3) {
  6020. a = src[i];
  6021. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6022. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6023. dst[j++] = b64[a >> 2];
  6024. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6025. if (i + 1 < src_len) {
  6026. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6027. }
  6028. if (i + 2 < src_len) {
  6029. dst[j++] = b64[c & 63];
  6030. }
  6031. }
  6032. while (j % 4 != 0) {
  6033. dst[j++] = '=';
  6034. }
  6035. dst[j++] = '\0';
  6036. }
  6037. #endif
  6038. #if defined(USE_LUA)
  6039. static unsigned char
  6040. b64reverse(char letter)
  6041. {
  6042. if ((letter >= 'A') && (letter <= 'Z')) {
  6043. return letter - 'A';
  6044. }
  6045. if ((letter >= 'a') && (letter <= 'z')) {
  6046. return letter - 'a' + 26;
  6047. }
  6048. if ((letter >= '0') && (letter <= '9')) {
  6049. return letter - '0' + 52;
  6050. }
  6051. if (letter == '+') {
  6052. return 62;
  6053. }
  6054. if (letter == '/') {
  6055. return 63;
  6056. }
  6057. if (letter == '=') {
  6058. return 255; /* normal end */
  6059. }
  6060. return 254; /* error */
  6061. }
  6062. static int
  6063. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6064. {
  6065. int i;
  6066. unsigned char a, b, c, d;
  6067. *dst_len = 0;
  6068. for (i = 0; i < src_len; i += 4) {
  6069. a = b64reverse(src[i]);
  6070. if (a >= 254) {
  6071. return i;
  6072. }
  6073. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6074. if (b >= 254) {
  6075. return i + 1;
  6076. }
  6077. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6078. if (c == 254) {
  6079. return i + 2;
  6080. }
  6081. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6082. if (d == 254) {
  6083. return i + 3;
  6084. }
  6085. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6086. if (c != 255) {
  6087. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6088. if (d != 255) {
  6089. dst[(*dst_len)++] = (c << 6) + d;
  6090. }
  6091. }
  6092. }
  6093. return -1;
  6094. }
  6095. #endif
  6096. static int
  6097. is_put_or_delete_method(const struct mg_connection *conn)
  6098. {
  6099. if (conn) {
  6100. const char *s = conn->request_info.request_method;
  6101. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6102. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6103. }
  6104. return 0;
  6105. }
  6106. #if !defined(NO_FILES)
  6107. static int
  6108. extention_matches_script(
  6109. struct mg_connection *conn, /* in: request (must be valid) */
  6110. const char *filename /* in: filename (must be valid) */
  6111. )
  6112. {
  6113. #if !defined(NO_CGI)
  6114. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6115. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6116. filename) > 0) {
  6117. return 1;
  6118. }
  6119. #endif
  6120. #if defined(USE_LUA)
  6121. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6122. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6123. filename) > 0) {
  6124. return 1;
  6125. }
  6126. #endif
  6127. #if defined(USE_DUKTAPE)
  6128. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6129. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6130. filename) > 0) {
  6131. return 1;
  6132. }
  6133. #endif
  6134. /* filename and conn could be unused, if all preocessor conditions
  6135. * are false (no script language supported). */
  6136. (void)filename;
  6137. (void)conn;
  6138. return 0;
  6139. }
  6140. /* For given directory path, substitute it to valid index file.
  6141. * Return 1 if index file has been found, 0 if not found.
  6142. * If the file is found, it's stats is returned in stp. */
  6143. static int
  6144. substitute_index_file(struct mg_connection *conn,
  6145. char *path,
  6146. size_t path_len,
  6147. struct mg_file_stat *filestat)
  6148. {
  6149. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6150. struct vec filename_vec;
  6151. size_t n = strlen(path);
  6152. int found = 0;
  6153. /* The 'path' given to us points to the directory. Remove all trailing
  6154. * directory separator characters from the end of the path, and
  6155. * then append single directory separator character. */
  6156. while ((n > 0) && (path[n - 1] == '/')) {
  6157. n--;
  6158. }
  6159. path[n] = '/';
  6160. /* Traverse index files list. For each entry, append it to the given
  6161. * path and see if the file exists. If it exists, break the loop */
  6162. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6163. /* Ignore too long entries that may overflow path buffer */
  6164. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6165. continue;
  6166. }
  6167. /* Prepare full path to the index file */
  6168. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6169. /* Does it exist? */
  6170. if (mg_stat(conn, path, filestat)) {
  6171. /* Yes it does, break the loop */
  6172. found = 1;
  6173. break;
  6174. }
  6175. }
  6176. /* If no index file exists, restore directory path */
  6177. if (!found) {
  6178. path[n] = '\0';
  6179. }
  6180. return found;
  6181. }
  6182. #endif
  6183. static void
  6184. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6185. char *filename, /* out: filename */
  6186. size_t filename_buf_len, /* in: size of filename buffer */
  6187. struct mg_file_stat *filestat, /* out: file status structure */
  6188. int *is_found, /* out: file found (directly) */
  6189. int *is_script_resource, /* out: handled by a script? */
  6190. int *is_websocket_request, /* out: websocket connetion? */
  6191. int *is_put_or_delete_request /* out: put/delete a file? */
  6192. )
  6193. {
  6194. char const *accept_encoding;
  6195. #if !defined(NO_FILES)
  6196. const char *uri = conn->request_info.local_uri;
  6197. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6198. const char *rewrite;
  6199. struct vec a, b;
  6200. ptrdiff_t match_len;
  6201. char gz_path[PATH_MAX];
  6202. int truncated;
  6203. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6204. char *tmp_str;
  6205. size_t tmp_str_len, sep_pos;
  6206. int allow_substitute_script_subresources;
  6207. #endif
  6208. #else
  6209. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6210. #endif
  6211. /* Step 1: Set all initially unknown outputs to zero */
  6212. memset(filestat, 0, sizeof(*filestat));
  6213. *filename = 0;
  6214. *is_found = 0;
  6215. *is_script_resource = 0;
  6216. /* Step 2: Check if the request attempts to modify the file system */
  6217. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6218. /* Step 3: Check if it is a websocket request, and modify the document
  6219. * root if required */
  6220. #if defined(USE_WEBSOCKET)
  6221. *is_websocket_request = is_websocket_protocol(conn);
  6222. #if !defined(NO_FILES)
  6223. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6224. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6225. }
  6226. #endif /* !NO_FILES */
  6227. #else /* USE_WEBSOCKET */
  6228. *is_websocket_request = 0;
  6229. #endif /* USE_WEBSOCKET */
  6230. /* Step 4: Check if gzip encoded response is allowed */
  6231. conn->accept_gzip = 0;
  6232. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6233. if (strstr(accept_encoding, "gzip") != NULL) {
  6234. conn->accept_gzip = 1;
  6235. }
  6236. }
  6237. #if !defined(NO_FILES)
  6238. /* Step 5: If there is no root directory, don't look for files. */
  6239. /* Note that root == NULL is a regular use case here. This occurs,
  6240. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6241. * config is not required. */
  6242. if (root == NULL) {
  6243. /* all file related outputs have already been set to 0, just return
  6244. */
  6245. return;
  6246. }
  6247. /* Step 6: Determine the local file path from the root path and the
  6248. * request uri. */
  6249. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6250. * part of the path one byte on the right. */
  6251. mg_snprintf(
  6252. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6253. if (truncated) {
  6254. goto interpret_cleanup;
  6255. }
  6256. /* Step 7: URI rewriting */
  6257. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6258. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6259. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6260. mg_snprintf(conn,
  6261. &truncated,
  6262. filename,
  6263. filename_buf_len - 1,
  6264. "%.*s%s",
  6265. (int)b.len,
  6266. b.ptr,
  6267. uri + match_len);
  6268. break;
  6269. }
  6270. }
  6271. if (truncated) {
  6272. goto interpret_cleanup;
  6273. }
  6274. /* Step 8: Check if the file exists at the server */
  6275. /* Local file path and name, corresponding to requested URI
  6276. * is now stored in "filename" variable. */
  6277. if (mg_stat(conn, filename, filestat)) {
  6278. int uri_len = (int)strlen(uri);
  6279. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6280. /* 8.1: File exists. */
  6281. *is_found = 1;
  6282. /* 8.2: Check if it is a script type. */
  6283. if (extention_matches_script(conn, filename)) {
  6284. /* The request addresses a CGI resource, Lua script or
  6285. * server-side javascript.
  6286. * The URI corresponds to the script itself (like
  6287. * /path/script.cgi), and there is no additional resource
  6288. * path (like /path/script.cgi/something).
  6289. * Requests that modify (replace or delete) a resource, like
  6290. * PUT and DELETE requests, should replace/delete the script
  6291. * file.
  6292. * Requests that read or write from/to a resource, like GET and
  6293. * POST requests, should call the script and return the
  6294. * generated response. */
  6295. *is_script_resource = (!*is_put_or_delete_request);
  6296. }
  6297. /* 8.3: If the request target is a directory, there could be
  6298. * a substitute file (index.html, index.cgi, ...). */
  6299. if (filestat->is_directory && is_uri_end_slash) {
  6300. /* Use a local copy here, since substitute_index_file will
  6301. * change the content of the file status */
  6302. struct mg_file_stat tmp_filestat;
  6303. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6304. if (substitute_index_file(
  6305. conn, filename, filename_buf_len, &tmp_filestat)) {
  6306. /* Substitute file found. Copy stat to the output, then
  6307. * check if the file is a script file */
  6308. *filestat = tmp_filestat;
  6309. if (extention_matches_script(conn, filename)) {
  6310. /* Substitute file is a script file */
  6311. *is_script_resource = 1;
  6312. } else {
  6313. /* Substitute file is a regular file */
  6314. *is_script_resource = 0;
  6315. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6316. }
  6317. }
  6318. /* If there is no substitute file, the server could return
  6319. * a directory listing in a later step */
  6320. }
  6321. return;
  6322. }
  6323. /* Step 9: Check for zipped files: */
  6324. /* If we can't find the actual file, look for the file
  6325. * with the same name but a .gz extension. If we find it,
  6326. * use that and set the gzipped flag in the file struct
  6327. * to indicate that the response need to have the content-
  6328. * encoding: gzip header.
  6329. * We can only do this if the browser declares support. */
  6330. if (conn->accept_gzip) {
  6331. mg_snprintf(
  6332. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6333. if (truncated) {
  6334. goto interpret_cleanup;
  6335. }
  6336. if (mg_stat(conn, gz_path, filestat)) {
  6337. if (filestat) {
  6338. filestat->is_gzipped = 1;
  6339. *is_found = 1;
  6340. }
  6341. /* Currently gz files can not be scripts. */
  6342. return;
  6343. }
  6344. }
  6345. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6346. /* Step 10: Script resources may handle sub-resources */
  6347. /* Support PATH_INFO for CGI scripts. */
  6348. tmp_str_len = strlen(filename);
  6349. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6350. if (!tmp_str) {
  6351. /* Out of memory */
  6352. goto interpret_cleanup;
  6353. }
  6354. memcpy(tmp_str, filename, tmp_str_len + 1);
  6355. /* Check config, if index scripts may have sub-resources */
  6356. allow_substitute_script_subresources =
  6357. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6358. "yes");
  6359. sep_pos = tmp_str_len;
  6360. while (sep_pos > 0) {
  6361. sep_pos--;
  6362. if (tmp_str[sep_pos] == '/') {
  6363. int is_script = 0, does_exist = 0;
  6364. tmp_str[sep_pos] = 0;
  6365. if (tmp_str[0]) {
  6366. is_script = extention_matches_script(conn, tmp_str);
  6367. does_exist = mg_stat(conn, tmp_str, filestat);
  6368. }
  6369. if (does_exist && is_script) {
  6370. filename[sep_pos] = 0;
  6371. memmove(filename + sep_pos + 2,
  6372. filename + sep_pos + 1,
  6373. strlen(filename + sep_pos + 1) + 1);
  6374. conn->path_info = filename + sep_pos + 1;
  6375. filename[sep_pos + 1] = '/';
  6376. *is_script_resource = 1;
  6377. *is_found = 1;
  6378. break;
  6379. }
  6380. if (allow_substitute_script_subresources) {
  6381. if (substitute_index_file(
  6382. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6383. /* some intermediate directory has an index file */
  6384. if (extention_matches_script(conn, tmp_str)) {
  6385. char *tmp_str2;
  6386. DEBUG_TRACE("Substitute script %s serving path %s",
  6387. tmp_str,
  6388. filename);
  6389. /* this index file is a script */
  6390. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6391. conn->phys_ctx);
  6392. mg_snprintf(conn,
  6393. &truncated,
  6394. filename,
  6395. filename_buf_len,
  6396. "%s//%s",
  6397. tmp_str,
  6398. tmp_str2);
  6399. mg_free(tmp_str2);
  6400. if (truncated) {
  6401. mg_free(tmp_str);
  6402. goto interpret_cleanup;
  6403. }
  6404. sep_pos = strlen(tmp_str);
  6405. filename[sep_pos] = 0;
  6406. conn->path_info = filename + sep_pos + 1;
  6407. *is_script_resource = 1;
  6408. *is_found = 1;
  6409. break;
  6410. } else {
  6411. DEBUG_TRACE("Substitute file %s serving path %s",
  6412. tmp_str,
  6413. filename);
  6414. /* non-script files will not have sub-resources */
  6415. filename[sep_pos] = 0;
  6416. conn->path_info = 0;
  6417. *is_script_resource = 0;
  6418. *is_found = 0;
  6419. break;
  6420. }
  6421. }
  6422. }
  6423. tmp_str[sep_pos] = '/';
  6424. }
  6425. }
  6426. mg_free(tmp_str);
  6427. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6428. #endif /* !defined(NO_FILES) */
  6429. return;
  6430. #if !defined(NO_FILES)
  6431. /* Reset all outputs */
  6432. interpret_cleanup:
  6433. memset(filestat, 0, sizeof(*filestat));
  6434. *filename = 0;
  6435. *is_found = 0;
  6436. *is_script_resource = 0;
  6437. *is_websocket_request = 0;
  6438. *is_put_or_delete_request = 0;
  6439. #endif /* !defined(NO_FILES) */
  6440. }
  6441. /* Check whether full request is buffered. Return:
  6442. * -1 if request or response is malformed
  6443. * 0 if request or response is not yet fully buffered
  6444. * >0 actual request length, including last \r\n\r\n */
  6445. static int
  6446. get_http_header_len(const char *buf, int buflen)
  6447. {
  6448. int i;
  6449. for (i = 0; i < buflen; i++) {
  6450. /* Do an unsigned comparison in some conditions below */
  6451. const unsigned char c = ((const unsigned char *)buf)[i];
  6452. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6453. && !isprint(c)) {
  6454. /* abort scan as soon as one malformed character is found */
  6455. return -1;
  6456. }
  6457. if (i < buflen - 1) {
  6458. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6459. /* Two newline, no carriage return - not standard compliant,
  6460. * but
  6461. * it
  6462. * should be accepted */
  6463. return i + 2;
  6464. }
  6465. }
  6466. if (i < buflen - 3) {
  6467. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6468. && (buf[i + 3] == '\n')) {
  6469. /* Two \r\n - standard compliant */
  6470. return i + 4;
  6471. }
  6472. }
  6473. }
  6474. return 0;
  6475. }
  6476. #if !defined(NO_CACHING)
  6477. /* Convert month to the month number. Return -1 on error, or month number */
  6478. static int
  6479. get_month_index(const char *s)
  6480. {
  6481. size_t i;
  6482. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6483. if (!strcmp(s, month_names[i])) {
  6484. return (int)i;
  6485. }
  6486. }
  6487. return -1;
  6488. }
  6489. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6490. static time_t
  6491. parse_date_string(const char *datetime)
  6492. {
  6493. char month_str[32] = {0};
  6494. int second, minute, hour, day, month, year;
  6495. time_t result = (time_t)0;
  6496. struct tm tm;
  6497. if ((sscanf(datetime,
  6498. "%d/%3s/%d %d:%d:%d",
  6499. &day,
  6500. month_str,
  6501. &year,
  6502. &hour,
  6503. &minute,
  6504. &second) == 6) || (sscanf(datetime,
  6505. "%d %3s %d %d:%d:%d",
  6506. &day,
  6507. month_str,
  6508. &year,
  6509. &hour,
  6510. &minute,
  6511. &second) == 6)
  6512. || (sscanf(datetime,
  6513. "%*3s, %d %3s %d %d:%d:%d",
  6514. &day,
  6515. month_str,
  6516. &year,
  6517. &hour,
  6518. &minute,
  6519. &second) == 6) || (sscanf(datetime,
  6520. "%d-%3s-%d %d:%d:%d",
  6521. &day,
  6522. month_str,
  6523. &year,
  6524. &hour,
  6525. &minute,
  6526. &second) == 6)) {
  6527. month = get_month_index(month_str);
  6528. if ((month >= 0) && (year >= 1970)) {
  6529. memset(&tm, 0, sizeof(tm));
  6530. tm.tm_year = year - 1900;
  6531. tm.tm_mon = month;
  6532. tm.tm_mday = day;
  6533. tm.tm_hour = hour;
  6534. tm.tm_min = minute;
  6535. tm.tm_sec = second;
  6536. result = timegm(&tm);
  6537. }
  6538. }
  6539. return result;
  6540. }
  6541. #endif /* !NO_CACHING */
  6542. /* Protect against directory disclosure attack by removing '..',
  6543. * excessive '/' and '\' characters */
  6544. static void
  6545. remove_double_dots_and_double_slashes(char *s)
  6546. {
  6547. char *p = s;
  6548. while ((s[0] == '.') && (s[1] == '.')) {
  6549. s++;
  6550. }
  6551. while (*s != '\0') {
  6552. *p++ = *s++;
  6553. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6554. /* Skip all following slashes, backslashes and double-dots */
  6555. while (s[0] != '\0') {
  6556. if ((s[0] == '/') || (s[0] == '\\')) {
  6557. s++;
  6558. } else if ((s[0] == '.') && (s[1] == '.')) {
  6559. s += 2;
  6560. } else {
  6561. break;
  6562. }
  6563. }
  6564. }
  6565. }
  6566. *p = '\0';
  6567. }
  6568. static const struct {
  6569. const char *extension;
  6570. size_t ext_len;
  6571. const char *mime_type;
  6572. } builtin_mime_types[] = {
  6573. /* IANA registered MIME types
  6574. * (http://www.iana.org/assignments/media-types)
  6575. * application types */
  6576. {".doc", 4, "application/msword"},
  6577. {".eps", 4, "application/postscript"},
  6578. {".exe", 4, "application/octet-stream"},
  6579. {".js", 3, "application/javascript"},
  6580. {".json", 5, "application/json"},
  6581. {".pdf", 4, "application/pdf"},
  6582. {".ps", 3, "application/postscript"},
  6583. {".rtf", 4, "application/rtf"},
  6584. {".xhtml", 6, "application/xhtml+xml"},
  6585. {".xsl", 4, "application/xml"},
  6586. {".xslt", 5, "application/xml"},
  6587. /* fonts */
  6588. {".ttf", 4, "application/font-sfnt"},
  6589. {".cff", 4, "application/font-sfnt"},
  6590. {".otf", 4, "application/font-sfnt"},
  6591. {".aat", 4, "application/font-sfnt"},
  6592. {".sil", 4, "application/font-sfnt"},
  6593. {".pfr", 4, "application/font-tdpfr"},
  6594. {".woff", 5, "application/font-woff"},
  6595. /* audio */
  6596. {".mp3", 4, "audio/mpeg"},
  6597. {".oga", 4, "audio/ogg"},
  6598. {".ogg", 4, "audio/ogg"},
  6599. /* image */
  6600. {".gif", 4, "image/gif"},
  6601. {".ief", 4, "image/ief"},
  6602. {".jpeg", 5, "image/jpeg"},
  6603. {".jpg", 4, "image/jpeg"},
  6604. {".jpm", 4, "image/jpm"},
  6605. {".jpx", 4, "image/jpx"},
  6606. {".png", 4, "image/png"},
  6607. {".svg", 4, "image/svg+xml"},
  6608. {".tif", 4, "image/tiff"},
  6609. {".tiff", 5, "image/tiff"},
  6610. /* model */
  6611. {".wrl", 4, "model/vrml"},
  6612. /* text */
  6613. {".css", 4, "text/css"},
  6614. {".csv", 4, "text/csv"},
  6615. {".htm", 4, "text/html"},
  6616. {".html", 5, "text/html"},
  6617. {".sgm", 4, "text/sgml"},
  6618. {".shtm", 5, "text/html"},
  6619. {".shtml", 6, "text/html"},
  6620. {".txt", 4, "text/plain"},
  6621. {".xml", 4, "text/xml"},
  6622. /* video */
  6623. {".mov", 4, "video/quicktime"},
  6624. {".mp4", 4, "video/mp4"},
  6625. {".mpeg", 5, "video/mpeg"},
  6626. {".mpg", 4, "video/mpeg"},
  6627. {".ogv", 4, "video/ogg"},
  6628. {".qt", 3, "video/quicktime"},
  6629. /* not registered types
  6630. * (http://reference.sitepoint.com/html/mime-types-full,
  6631. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6632. {".arj", 4, "application/x-arj-compressed"},
  6633. {".gz", 3, "application/x-gunzip"},
  6634. {".rar", 4, "application/x-arj-compressed"},
  6635. {".swf", 4, "application/x-shockwave-flash"},
  6636. {".tar", 4, "application/x-tar"},
  6637. {".tgz", 4, "application/x-tar-gz"},
  6638. {".torrent", 8, "application/x-bittorrent"},
  6639. {".ppt", 4, "application/x-mspowerpoint"},
  6640. {".xls", 4, "application/x-msexcel"},
  6641. {".zip", 4, "application/x-zip-compressed"},
  6642. {".aac",
  6643. 4,
  6644. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6645. {".aif", 4, "audio/x-aif"},
  6646. {".m3u", 4, "audio/x-mpegurl"},
  6647. {".mid", 4, "audio/x-midi"},
  6648. {".ra", 3, "audio/x-pn-realaudio"},
  6649. {".ram", 4, "audio/x-pn-realaudio"},
  6650. {".wav", 4, "audio/x-wav"},
  6651. {".bmp", 4, "image/bmp"},
  6652. {".ico", 4, "image/x-icon"},
  6653. {".pct", 4, "image/x-pct"},
  6654. {".pict", 5, "image/pict"},
  6655. {".rgb", 4, "image/x-rgb"},
  6656. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6657. {".asf", 4, "video/x-ms-asf"},
  6658. {".avi", 4, "video/x-msvideo"},
  6659. {".m4v", 4, "video/x-m4v"},
  6660. {NULL, 0, NULL}};
  6661. const char *
  6662. mg_get_builtin_mime_type(const char *path)
  6663. {
  6664. const char *ext;
  6665. size_t i, path_len;
  6666. path_len = strlen(path);
  6667. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6668. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6669. if ((path_len > builtin_mime_types[i].ext_len)
  6670. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6671. return builtin_mime_types[i].mime_type;
  6672. }
  6673. }
  6674. return "text/plain";
  6675. }
  6676. /* Look at the "path" extension and figure what mime type it has.
  6677. * Store mime type in the vector. */
  6678. static void
  6679. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6680. {
  6681. struct vec ext_vec, mime_vec;
  6682. const char *list, *ext;
  6683. size_t path_len;
  6684. path_len = strlen(path);
  6685. if ((conn == NULL) || (vec == NULL)) {
  6686. if (vec != NULL) {
  6687. memset(vec, '\0', sizeof(struct vec));
  6688. }
  6689. return;
  6690. }
  6691. /* Scan user-defined mime types first, in case user wants to
  6692. * override default mime types. */
  6693. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6694. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6695. /* ext now points to the path suffix */
  6696. ext = path + path_len - ext_vec.len;
  6697. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6698. *vec = mime_vec;
  6699. return;
  6700. }
  6701. }
  6702. vec->ptr = mg_get_builtin_mime_type(path);
  6703. vec->len = strlen(vec->ptr);
  6704. }
  6705. /* Stringify binary data. Output buffer must be twice as big as input,
  6706. * because each byte takes 2 bytes in string representation */
  6707. static void
  6708. bin2str(char *to, const unsigned char *p, size_t len)
  6709. {
  6710. static const char *hex = "0123456789abcdef";
  6711. for (; len--; p++) {
  6712. *to++ = hex[p[0] >> 4];
  6713. *to++ = hex[p[0] & 0x0f];
  6714. }
  6715. *to = '\0';
  6716. }
  6717. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6718. */
  6719. char *
  6720. mg_md5(char buf[33], ...)
  6721. {
  6722. md5_byte_t hash[16];
  6723. const char *p;
  6724. va_list ap;
  6725. md5_state_t ctx;
  6726. md5_init(&ctx);
  6727. va_start(ap, buf);
  6728. while ((p = va_arg(ap, const char *)) != NULL) {
  6729. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6730. }
  6731. va_end(ap);
  6732. md5_finish(&ctx, hash);
  6733. bin2str(buf, hash, sizeof(hash));
  6734. return buf;
  6735. }
  6736. /* Check the user's password, return 1 if OK */
  6737. static int
  6738. check_password(const char *method,
  6739. const char *ha1,
  6740. const char *uri,
  6741. const char *nonce,
  6742. const char *nc,
  6743. const char *cnonce,
  6744. const char *qop,
  6745. const char *response)
  6746. {
  6747. char ha2[32 + 1], expected_response[32 + 1];
  6748. /* Some of the parameters may be NULL */
  6749. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6750. || (qop == NULL) || (response == NULL)) {
  6751. return 0;
  6752. }
  6753. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6754. if (strlen(response) != 32) {
  6755. return 0;
  6756. }
  6757. mg_md5(ha2, method, ":", uri, NULL);
  6758. mg_md5(expected_response,
  6759. ha1,
  6760. ":",
  6761. nonce,
  6762. ":",
  6763. nc,
  6764. ":",
  6765. cnonce,
  6766. ":",
  6767. qop,
  6768. ":",
  6769. ha2,
  6770. NULL);
  6771. return mg_strcasecmp(response, expected_response) == 0;
  6772. }
  6773. /* Use the global passwords file, if specified by auth_gpass option,
  6774. * or search for .htpasswd in the requested directory. */
  6775. static void
  6776. open_auth_file(struct mg_connection *conn,
  6777. const char *path,
  6778. struct mg_file *filep)
  6779. {
  6780. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6781. char name[PATH_MAX];
  6782. const char *p, *e,
  6783. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6784. int truncated;
  6785. if (gpass != NULL) {
  6786. /* Use global passwords file */
  6787. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6788. #if defined(DEBUG)
  6789. /* Use mg_cry_internal here, since gpass has been configured. */
  6790. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6791. #endif
  6792. }
  6793. /* Important: using local struct mg_file to test path for
  6794. * is_directory flag. If filep is used, mg_stat() makes it
  6795. * appear as if auth file was opened.
  6796. * TODO(mid): Check if this is still required after rewriting
  6797. * mg_stat */
  6798. } else if (mg_stat(conn, path, &filep->stat)
  6799. && filep->stat.is_directory) {
  6800. mg_snprintf(conn,
  6801. &truncated,
  6802. name,
  6803. sizeof(name),
  6804. "%s/%s",
  6805. path,
  6806. PASSWORDS_FILE_NAME);
  6807. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6808. #if defined(DEBUG)
  6809. /* Don't use mg_cry_internal here, but only a trace, since this
  6810. * is
  6811. * a typical case. It will occur for every directory
  6812. * without a password file. */
  6813. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6814. #endif
  6815. }
  6816. } else {
  6817. /* Try to find .htpasswd in requested directory. */
  6818. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6819. if (e[0] == '/') {
  6820. break;
  6821. }
  6822. }
  6823. mg_snprintf(conn,
  6824. &truncated,
  6825. name,
  6826. sizeof(name),
  6827. "%.*s/%s",
  6828. (int)(e - p),
  6829. p,
  6830. PASSWORDS_FILE_NAME);
  6831. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6832. #if defined(DEBUG)
  6833. /* Don't use mg_cry_internal here, but only a trace, since this
  6834. * is
  6835. * a typical case. It will occur for every directory
  6836. * without a password file. */
  6837. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6838. #endif
  6839. }
  6840. }
  6841. }
  6842. }
  6843. /* Parsed Authorization header */
  6844. struct ah {
  6845. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6846. };
  6847. /* Return 1 on success. Always initializes the ah structure. */
  6848. static int
  6849. parse_auth_header(struct mg_connection *conn,
  6850. char *buf,
  6851. size_t buf_size,
  6852. struct ah *ah)
  6853. {
  6854. char *name, *value, *s;
  6855. const char *auth_header;
  6856. uint64_t nonce;
  6857. if (!ah || !conn) {
  6858. return 0;
  6859. }
  6860. (void)memset(ah, 0, sizeof(*ah));
  6861. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6862. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6863. return 0;
  6864. }
  6865. /* Make modifiable copy of the auth header */
  6866. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6867. s = buf;
  6868. /* Parse authorization header */
  6869. for (;;) {
  6870. /* Gobble initial spaces */
  6871. while (isspace(*(unsigned char *)s)) {
  6872. s++;
  6873. }
  6874. name = skip_quoted(&s, "=", " ", 0);
  6875. /* Value is either quote-delimited, or ends at first comma or space.
  6876. */
  6877. if (s[0] == '\"') {
  6878. s++;
  6879. value = skip_quoted(&s, "\"", " ", '\\');
  6880. if (s[0] == ',') {
  6881. s++;
  6882. }
  6883. } else {
  6884. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6885. * spaces */
  6886. }
  6887. if (*name == '\0') {
  6888. break;
  6889. }
  6890. if (!strcmp(name, "username")) {
  6891. ah->user = value;
  6892. } else if (!strcmp(name, "cnonce")) {
  6893. ah->cnonce = value;
  6894. } else if (!strcmp(name, "response")) {
  6895. ah->response = value;
  6896. } else if (!strcmp(name, "uri")) {
  6897. ah->uri = value;
  6898. } else if (!strcmp(name, "qop")) {
  6899. ah->qop = value;
  6900. } else if (!strcmp(name, "nc")) {
  6901. ah->nc = value;
  6902. } else if (!strcmp(name, "nonce")) {
  6903. ah->nonce = value;
  6904. }
  6905. }
  6906. #if !defined(NO_NONCE_CHECK)
  6907. /* Read the nonce from the response. */
  6908. if (ah->nonce == NULL) {
  6909. return 0;
  6910. }
  6911. s = NULL;
  6912. nonce = strtoull(ah->nonce, &s, 10);
  6913. if ((s == NULL) || (*s != 0)) {
  6914. return 0;
  6915. }
  6916. /* Convert the nonce from the client to a number. */
  6917. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6918. /* The converted number corresponds to the time the nounce has been
  6919. * created. This should not be earlier than the server start. */
  6920. /* Server side nonce check is valuable in all situations but one:
  6921. * if the server restarts frequently, but the client should not see
  6922. * that, so the server should accept nonces from previous starts. */
  6923. /* However, the reasonable default is to not accept a nonce from a
  6924. * previous start, so if anyone changed the access rights between
  6925. * two restarts, a new login is required. */
  6926. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6927. /* nonce is from a previous start of the server and no longer valid
  6928. * (replay attack?) */
  6929. return 0;
  6930. }
  6931. /* Check if the nonce is too high, so it has not (yet) been used by the
  6932. * server. */
  6933. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6934. + conn->dom_ctx->nonce_count)) {
  6935. return 0;
  6936. }
  6937. #else
  6938. (void)nonce;
  6939. #endif
  6940. /* CGI needs it as REMOTE_USER */
  6941. if (ah->user != NULL) {
  6942. conn->request_info.remote_user =
  6943. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6944. } else {
  6945. return 0;
  6946. }
  6947. return 1;
  6948. }
  6949. static const char *
  6950. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6951. {
  6952. #if defined(MG_USE_OPEN_FILE)
  6953. const char *eof;
  6954. size_t len;
  6955. const char *memend;
  6956. #else
  6957. (void)p; /* parameter is unused */
  6958. #endif
  6959. if (!filep) {
  6960. return NULL;
  6961. }
  6962. #if defined(MG_USE_OPEN_FILE)
  6963. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6964. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6965. /* Search for \n from p till the end of stream */
  6966. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6967. if (eof != NULL) {
  6968. eof += 1; /* Include \n */
  6969. } else {
  6970. eof = memend; /* Copy remaining data */
  6971. }
  6972. len =
  6973. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6974. memcpy(buf, *p, len);
  6975. buf[len] = '\0';
  6976. *p += len;
  6977. return len ? eof : NULL;
  6978. } else /* filep->access.fp block below */
  6979. #endif
  6980. if (filep->access.fp != NULL) {
  6981. return fgets(buf, (int)size, filep->access.fp);
  6982. } else {
  6983. return NULL;
  6984. }
  6985. }
  6986. /* Define the initial recursion depth for procesesing htpasswd files that
  6987. * include other htpasswd
  6988. * (or even the same) files. It is not difficult to provide a file or files
  6989. * s.t. they force civetweb
  6990. * to infinitely recurse and then crash.
  6991. */
  6992. #define INITIAL_DEPTH 9
  6993. #if INITIAL_DEPTH <= 0
  6994. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6995. #endif
  6996. struct read_auth_file_struct {
  6997. struct mg_connection *conn;
  6998. struct ah ah;
  6999. const char *domain;
  7000. char buf[256 + 256 + 40];
  7001. const char *f_user;
  7002. const char *f_domain;
  7003. const char *f_ha1;
  7004. };
  7005. static int
  7006. read_auth_file(struct mg_file *filep,
  7007. struct read_auth_file_struct *workdata,
  7008. int depth)
  7009. {
  7010. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7011. int is_authorized = 0;
  7012. struct mg_file fp;
  7013. size_t l;
  7014. if (!filep || !workdata || (0 == depth)) {
  7015. return 0;
  7016. }
  7017. /* Loop over passwords file */
  7018. #if defined(MG_USE_OPEN_FILE)
  7019. p = (char *)filep->access.membuf;
  7020. #endif
  7021. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7022. l = strlen(workdata->buf);
  7023. while (l > 0) {
  7024. if (isspace(workdata->buf[l - 1])
  7025. || iscntrl(workdata->buf[l - 1])) {
  7026. l--;
  7027. workdata->buf[l] = 0;
  7028. } else
  7029. break;
  7030. }
  7031. if (l < 1) {
  7032. continue;
  7033. }
  7034. workdata->f_user = workdata->buf;
  7035. if (workdata->f_user[0] == ':') {
  7036. /* user names may not contain a ':' and may not be empty,
  7037. * so lines starting with ':' may be used for a special purpose
  7038. */
  7039. if (workdata->f_user[1] == '#') {
  7040. /* :# is a comment */
  7041. continue;
  7042. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7043. if (mg_fopen(workdata->conn,
  7044. workdata->f_user + 9,
  7045. MG_FOPEN_MODE_READ,
  7046. &fp)) {
  7047. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7048. (void)mg_fclose(
  7049. &fp.access); /* ignore error on read only file */
  7050. /* No need to continue processing files once we have a
  7051. * match, since nothing will reset it back
  7052. * to 0.
  7053. */
  7054. if (is_authorized) {
  7055. return is_authorized;
  7056. }
  7057. } else {
  7058. mg_cry_internal(workdata->conn,
  7059. "%s: cannot open authorization file: %s",
  7060. __func__,
  7061. workdata->buf);
  7062. }
  7063. continue;
  7064. }
  7065. /* everything is invalid for the moment (might change in the
  7066. * future) */
  7067. mg_cry_internal(workdata->conn,
  7068. "%s: syntax error in authorization file: %s",
  7069. __func__,
  7070. workdata->buf);
  7071. continue;
  7072. }
  7073. workdata->f_domain = strchr(workdata->f_user, ':');
  7074. if (workdata->f_domain == NULL) {
  7075. mg_cry_internal(workdata->conn,
  7076. "%s: syntax error in authorization file: %s",
  7077. __func__,
  7078. workdata->buf);
  7079. continue;
  7080. }
  7081. *(char *)(workdata->f_domain) = 0;
  7082. (workdata->f_domain)++;
  7083. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7084. if (workdata->f_ha1 == NULL) {
  7085. mg_cry_internal(workdata->conn,
  7086. "%s: syntax error in authorization file: %s",
  7087. __func__,
  7088. workdata->buf);
  7089. continue;
  7090. }
  7091. *(char *)(workdata->f_ha1) = 0;
  7092. (workdata->f_ha1)++;
  7093. if (!strcmp(workdata->ah.user, workdata->f_user)
  7094. && !strcmp(workdata->domain, workdata->f_domain)) {
  7095. return check_password(workdata->conn->request_info.request_method,
  7096. workdata->f_ha1,
  7097. workdata->ah.uri,
  7098. workdata->ah.nonce,
  7099. workdata->ah.nc,
  7100. workdata->ah.cnonce,
  7101. workdata->ah.qop,
  7102. workdata->ah.response);
  7103. }
  7104. }
  7105. return is_authorized;
  7106. }
  7107. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7108. static int
  7109. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7110. {
  7111. struct read_auth_file_struct workdata;
  7112. char buf[MG_BUF_LEN];
  7113. if (!conn || !conn->dom_ctx) {
  7114. return 0;
  7115. }
  7116. memset(&workdata, 0, sizeof(workdata));
  7117. workdata.conn = conn;
  7118. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7119. return 0;
  7120. }
  7121. if (realm) {
  7122. workdata.domain = realm;
  7123. } else {
  7124. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7125. }
  7126. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7127. }
  7128. /* Public function to check http digest authentication header */
  7129. int
  7130. mg_check_digest_access_authentication(struct mg_connection *conn,
  7131. const char *realm,
  7132. const char *filename)
  7133. {
  7134. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7135. int auth;
  7136. if (!conn || !filename) {
  7137. return -1;
  7138. }
  7139. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7140. return -2;
  7141. }
  7142. auth = authorize(conn, &file, realm);
  7143. mg_fclose(&file.access);
  7144. return auth;
  7145. }
  7146. /* Return 1 if request is authorised, 0 otherwise. */
  7147. static int
  7148. check_authorization(struct mg_connection *conn, const char *path)
  7149. {
  7150. char fname[PATH_MAX];
  7151. struct vec uri_vec, filename_vec;
  7152. const char *list;
  7153. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7154. int authorized = 1, truncated;
  7155. if (!conn || !conn->dom_ctx) {
  7156. return 0;
  7157. }
  7158. list = conn->dom_ctx->config[PROTECT_URI];
  7159. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7160. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7161. mg_snprintf(conn,
  7162. &truncated,
  7163. fname,
  7164. sizeof(fname),
  7165. "%.*s",
  7166. (int)filename_vec.len,
  7167. filename_vec.ptr);
  7168. if (truncated
  7169. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7170. mg_cry_internal(conn,
  7171. "%s: cannot open %s: %s",
  7172. __func__,
  7173. fname,
  7174. strerror(errno));
  7175. }
  7176. break;
  7177. }
  7178. }
  7179. if (!is_file_opened(&file.access)) {
  7180. open_auth_file(conn, path, &file);
  7181. }
  7182. if (is_file_opened(&file.access)) {
  7183. authorized = authorize(conn, &file, NULL);
  7184. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7185. }
  7186. return authorized;
  7187. }
  7188. /* Internal function. Assumes conn is valid */
  7189. static void
  7190. send_authorization_request(struct mg_connection *conn, const char *realm)
  7191. {
  7192. char date[64];
  7193. time_t curtime = time(NULL);
  7194. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7195. if (!realm) {
  7196. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7197. }
  7198. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7199. nonce += conn->dom_ctx->nonce_count;
  7200. ++conn->dom_ctx->nonce_count;
  7201. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7202. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7203. conn->status_code = 401;
  7204. conn->must_close = 1;
  7205. gmt_time_string(date, sizeof(date), &curtime);
  7206. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7207. send_no_cache_header(conn);
  7208. send_additional_header(conn);
  7209. mg_printf(conn,
  7210. "Date: %s\r\n"
  7211. "Connection: %s\r\n"
  7212. "Content-Length: 0\r\n"
  7213. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7214. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7215. date,
  7216. suggest_connection_header(conn),
  7217. realm,
  7218. nonce);
  7219. }
  7220. /* Interface function. Parameters are provided by the user, so do
  7221. * at least some basic checks.
  7222. */
  7223. int
  7224. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7225. const char *realm)
  7226. {
  7227. if (conn && conn->dom_ctx) {
  7228. send_authorization_request(conn, realm);
  7229. return 0;
  7230. }
  7231. return -1;
  7232. }
  7233. #if !defined(NO_FILES)
  7234. static int
  7235. is_authorized_for_put(struct mg_connection *conn)
  7236. {
  7237. if (conn) {
  7238. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7239. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7240. int ret = 0;
  7241. if (passfile != NULL
  7242. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7243. ret = authorize(conn, &file, NULL);
  7244. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7245. }
  7246. return ret;
  7247. }
  7248. return 0;
  7249. }
  7250. #endif
  7251. int
  7252. mg_modify_passwords_file(const char *fname,
  7253. const char *domain,
  7254. const char *user,
  7255. const char *pass)
  7256. {
  7257. int found, i;
  7258. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7259. FILE *fp, *fp2;
  7260. found = 0;
  7261. fp = fp2 = NULL;
  7262. /* Regard empty password as no password - remove user record. */
  7263. if ((pass != NULL) && (pass[0] == '\0')) {
  7264. pass = NULL;
  7265. }
  7266. /* Other arguments must not be empty */
  7267. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7268. return 0;
  7269. }
  7270. /* Using the given file format, user name and domain must not contain
  7271. * ':'
  7272. */
  7273. if (strchr(user, ':') != NULL) {
  7274. return 0;
  7275. }
  7276. if (strchr(domain, ':') != NULL) {
  7277. return 0;
  7278. }
  7279. /* Do not allow control characters like newline in user name and domain.
  7280. * Do not allow excessively long names either. */
  7281. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7282. if (iscntrl(user[i])) {
  7283. return 0;
  7284. }
  7285. }
  7286. if (user[i]) {
  7287. return 0;
  7288. }
  7289. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7290. if (iscntrl(domain[i])) {
  7291. return 0;
  7292. }
  7293. }
  7294. if (domain[i]) {
  7295. return 0;
  7296. }
  7297. /* The maximum length of the path to the password file is limited */
  7298. if ((strlen(fname) + 4) >= PATH_MAX) {
  7299. return 0;
  7300. }
  7301. /* Create a temporary file name. Length has been checked before. */
  7302. strcpy(tmp, fname);
  7303. strcat(tmp, ".tmp");
  7304. /* Create the file if does not exist */
  7305. /* Use of fopen here is OK, since fname is only ASCII */
  7306. if ((fp = fopen(fname, "a+")) != NULL) {
  7307. (void)fclose(fp);
  7308. }
  7309. /* Open the given file and temporary file */
  7310. if ((fp = fopen(fname, "r")) == NULL) {
  7311. return 0;
  7312. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7313. fclose(fp);
  7314. return 0;
  7315. }
  7316. /* Copy the stuff to temporary file */
  7317. while (fgets(line, sizeof(line), fp) != NULL) {
  7318. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7319. continue;
  7320. }
  7321. u[255] = 0;
  7322. d[255] = 0;
  7323. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7324. found++;
  7325. if (pass != NULL) {
  7326. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7327. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7328. }
  7329. } else {
  7330. fprintf(fp2, "%s", line);
  7331. }
  7332. }
  7333. /* If new user, just add it */
  7334. if (!found && (pass != NULL)) {
  7335. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7336. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7337. }
  7338. /* Close files */
  7339. fclose(fp);
  7340. fclose(fp2);
  7341. /* Put the temp file in place of real file */
  7342. IGNORE_UNUSED_RESULT(remove(fname));
  7343. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7344. return 1;
  7345. }
  7346. static int
  7347. is_valid_port(unsigned long port)
  7348. {
  7349. return (port <= 0xffff);
  7350. }
  7351. static int
  7352. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7353. {
  7354. struct addrinfo hints, *res, *ressave;
  7355. int func_ret = 0;
  7356. int gai_ret;
  7357. memset(&hints, 0, sizeof(struct addrinfo));
  7358. hints.ai_family = af;
  7359. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7360. if (gai_ret != 0) {
  7361. /* gai_strerror could be used to convert gai_ret to a string */
  7362. /* POSIX return values: see
  7363. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7364. */
  7365. /* Windows return values: see
  7366. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7367. */
  7368. return 0;
  7369. }
  7370. ressave = res;
  7371. while (res) {
  7372. if (dstlen >= (size_t)res->ai_addrlen) {
  7373. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7374. func_ret = 1;
  7375. }
  7376. res = res->ai_next;
  7377. }
  7378. freeaddrinfo(ressave);
  7379. return func_ret;
  7380. }
  7381. static int
  7382. connect_socket(struct mg_context *ctx /* may be NULL */,
  7383. const char *host,
  7384. int port,
  7385. int use_ssl,
  7386. char *ebuf,
  7387. size_t ebuf_len,
  7388. SOCKET *sock /* output: socket, must not be NULL */,
  7389. union usa *sa /* output: socket address, must not be NULL */
  7390. )
  7391. {
  7392. int ip_ver = 0;
  7393. int conn_ret = -1;
  7394. *sock = INVALID_SOCKET;
  7395. memset(sa, 0, sizeof(*sa));
  7396. if (ebuf_len > 0) {
  7397. *ebuf = 0;
  7398. }
  7399. if (host == NULL) {
  7400. mg_snprintf(NULL,
  7401. NULL, /* No truncation check for ebuf */
  7402. ebuf,
  7403. ebuf_len,
  7404. "%s",
  7405. "NULL host");
  7406. return 0;
  7407. }
  7408. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7409. mg_snprintf(NULL,
  7410. NULL, /* No truncation check for ebuf */
  7411. ebuf,
  7412. ebuf_len,
  7413. "%s",
  7414. "invalid port");
  7415. return 0;
  7416. }
  7417. #if !defined(NO_SSL)
  7418. #if !defined(NO_SSL_DL)
  7419. #if defined(OPENSSL_API_1_1)
  7420. if (use_ssl && (TLS_client_method == NULL)) {
  7421. mg_snprintf(NULL,
  7422. NULL, /* No truncation check for ebuf */
  7423. ebuf,
  7424. ebuf_len,
  7425. "%s",
  7426. "SSL is not initialized");
  7427. return 0;
  7428. }
  7429. #else
  7430. if (use_ssl && (SSLv23_client_method == NULL)) {
  7431. mg_snprintf(NULL,
  7432. NULL, /* No truncation check for ebuf */
  7433. ebuf,
  7434. ebuf_len,
  7435. "%s",
  7436. "SSL is not initialized");
  7437. return 0;
  7438. }
  7439. #endif /* OPENSSL_API_1_1 */
  7440. #else
  7441. (void)use_ssl;
  7442. #endif /* NO_SSL_DL */
  7443. #else
  7444. (void)use_ssl;
  7445. #endif /* !defined(NO_SSL) */
  7446. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7447. sa->sin.sin_family = AF_INET;
  7448. sa->sin.sin_port = htons((uint16_t)port);
  7449. ip_ver = 4;
  7450. #if defined(USE_IPV6)
  7451. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7452. sa->sin6.sin6_family = AF_INET6;
  7453. sa->sin6.sin6_port = htons((uint16_t)port);
  7454. ip_ver = 6;
  7455. } else if (host[0] == '[') {
  7456. /* While getaddrinfo on Windows will work with [::1],
  7457. * getaddrinfo on Linux only works with ::1 (without []). */
  7458. size_t l = strlen(host + 1);
  7459. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7460. if (h) {
  7461. h[l - 1] = 0;
  7462. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7463. sa->sin6.sin6_family = AF_INET6;
  7464. sa->sin6.sin6_port = htons((uint16_t)port);
  7465. ip_ver = 6;
  7466. }
  7467. mg_free(h);
  7468. }
  7469. #endif
  7470. }
  7471. if (ip_ver == 0) {
  7472. mg_snprintf(NULL,
  7473. NULL, /* No truncation check for ebuf */
  7474. ebuf,
  7475. ebuf_len,
  7476. "%s",
  7477. "host not found");
  7478. return 0;
  7479. }
  7480. if (ip_ver == 4) {
  7481. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7482. }
  7483. #if defined(USE_IPV6)
  7484. else if (ip_ver == 6) {
  7485. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7486. }
  7487. #endif
  7488. if (*sock == INVALID_SOCKET) {
  7489. mg_snprintf(NULL,
  7490. NULL, /* No truncation check for ebuf */
  7491. ebuf,
  7492. ebuf_len,
  7493. "socket(): %s",
  7494. strerror(ERRNO));
  7495. return 0;
  7496. }
  7497. if (0 != set_non_blocking_mode(*sock)) {
  7498. mg_snprintf(NULL,
  7499. NULL, /* No truncation check for ebuf */
  7500. ebuf,
  7501. ebuf_len,
  7502. "Cannot set socket to non-blocking: %s",
  7503. strerror(ERRNO));
  7504. closesocket(*sock);
  7505. *sock = INVALID_SOCKET;
  7506. return 0;
  7507. }
  7508. set_close_on_exec(*sock, fc(ctx));
  7509. if (ip_ver == 4) {
  7510. /* connected with IPv4 */
  7511. conn_ret = connect(*sock,
  7512. (struct sockaddr *)((void *)&sa->sin),
  7513. sizeof(sa->sin));
  7514. }
  7515. #if defined(USE_IPV6)
  7516. else if (ip_ver == 6) {
  7517. /* connected with IPv6 */
  7518. conn_ret = connect(*sock,
  7519. (struct sockaddr *)((void *)&sa->sin6),
  7520. sizeof(sa->sin6));
  7521. }
  7522. #endif
  7523. if (conn_ret != 0) {
  7524. fd_set fdset;
  7525. struct timeval timeout;
  7526. int sockerr = -1;
  7527. void *psockerr = &sockerr;
  7528. #if defined(_WIN32)
  7529. int len = (int)sizeof(sockerr);
  7530. #else
  7531. socklen_t len = (socklen_t)sizeof(sockerr);
  7532. #endif
  7533. FD_ZERO(&fdset);
  7534. FD_SET(*sock, &fdset);
  7535. timeout.tv_sec = 10; /* 10 second timeout */
  7536. timeout.tv_usec = 0;
  7537. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7538. /* Not connected */
  7539. mg_snprintf(NULL,
  7540. NULL, /* No truncation check for ebuf */
  7541. ebuf,
  7542. ebuf_len,
  7543. "connect(%s:%d): timeout",
  7544. host,
  7545. port);
  7546. closesocket(*sock);
  7547. *sock = INVALID_SOCKET;
  7548. return 0;
  7549. }
  7550. #if defined(_WIN32)
  7551. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7552. #else
  7553. getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7554. #endif
  7555. if (sockerr != 0) {
  7556. /* Not connected */
  7557. mg_snprintf(NULL,
  7558. NULL, /* No truncation check for ebuf */
  7559. ebuf,
  7560. ebuf_len,
  7561. "connect(%s:%d): error %s",
  7562. host,
  7563. port,
  7564. strerror(sockerr));
  7565. closesocket(*sock);
  7566. *sock = INVALID_SOCKET;
  7567. return 0;
  7568. }
  7569. }
  7570. return 1;
  7571. }
  7572. int
  7573. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7574. {
  7575. static const char *dont_escape = "._-$,;~()";
  7576. static const char *hex = "0123456789abcdef";
  7577. char *pos = dst;
  7578. const char *end = dst + dst_len - 1;
  7579. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7580. if (isalnum(*(const unsigned char *)src)
  7581. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7582. *pos = *src;
  7583. } else if (pos + 2 < end) {
  7584. pos[0] = '%';
  7585. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7586. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7587. pos += 2;
  7588. } else {
  7589. break;
  7590. }
  7591. }
  7592. *pos = '\0';
  7593. return (*src == '\0') ? (int)(pos - dst) : -1;
  7594. }
  7595. /* Return 0 on success, non-zero if an error occurs. */
  7596. static int
  7597. print_dir_entry(struct de *de)
  7598. {
  7599. size_t hrefsize;
  7600. char *href;
  7601. char size[64], mod[64];
  7602. #if defined(REENTRANT_TIME)
  7603. struct tm _tm;
  7604. struct tm *tm = &_tm;
  7605. #else
  7606. struct tm *tm;
  7607. #endif
  7608. hrefsize = PATH_MAX * 3; /* worst case */
  7609. href = (char *)mg_malloc(hrefsize);
  7610. if (href == NULL) {
  7611. return -1;
  7612. }
  7613. if (de->file.is_directory) {
  7614. mg_snprintf(de->conn,
  7615. NULL, /* Buffer is big enough */
  7616. size,
  7617. sizeof(size),
  7618. "%s",
  7619. "[DIRECTORY]");
  7620. } else {
  7621. /* We use (signed) cast below because MSVC 6 compiler cannot
  7622. * convert unsigned __int64 to double. Sigh. */
  7623. if (de->file.size < 1024) {
  7624. mg_snprintf(de->conn,
  7625. NULL, /* Buffer is big enough */
  7626. size,
  7627. sizeof(size),
  7628. "%d",
  7629. (int)de->file.size);
  7630. } else if (de->file.size < 0x100000) {
  7631. mg_snprintf(de->conn,
  7632. NULL, /* Buffer is big enough */
  7633. size,
  7634. sizeof(size),
  7635. "%.1fk",
  7636. (double)de->file.size / 1024.0);
  7637. } else if (de->file.size < 0x40000000) {
  7638. mg_snprintf(de->conn,
  7639. NULL, /* Buffer is big enough */
  7640. size,
  7641. sizeof(size),
  7642. "%.1fM",
  7643. (double)de->file.size / 1048576);
  7644. } else {
  7645. mg_snprintf(de->conn,
  7646. NULL, /* Buffer is big enough */
  7647. size,
  7648. sizeof(size),
  7649. "%.1fG",
  7650. (double)de->file.size / 1073741824);
  7651. }
  7652. }
  7653. /* Note: mg_snprintf will not cause a buffer overflow above.
  7654. * So, string truncation checks are not required here. */
  7655. #if defined(REENTRANT_TIME)
  7656. localtime_r(&de->file.last_modified, tm);
  7657. #else
  7658. tm = localtime(&de->file.last_modified);
  7659. #endif
  7660. if (tm != NULL) {
  7661. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7662. } else {
  7663. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7664. mod[sizeof(mod) - 1] = '\0';
  7665. }
  7666. mg_url_encode(de->file_name, href, hrefsize);
  7667. mg_printf(de->conn,
  7668. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7669. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7670. de->conn->request_info.local_uri,
  7671. href,
  7672. de->file.is_directory ? "/" : "",
  7673. de->file_name,
  7674. de->file.is_directory ? "/" : "",
  7675. mod,
  7676. size);
  7677. mg_free(href);
  7678. return 0;
  7679. }
  7680. /* This function is called from send_directory() and used for
  7681. * sorting directory entries by size, or name, or modification time.
  7682. * On windows, __cdecl specification is needed in case if project is built
  7683. * with __stdcall convention. qsort always requires __cdels callback. */
  7684. static int WINCDECL
  7685. compare_dir_entries(const void *p1, const void *p2)
  7686. {
  7687. if (p1 && p2) {
  7688. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7689. const char *query_string = a->conn->request_info.query_string;
  7690. int cmp_result = 0;
  7691. if (query_string == NULL) {
  7692. query_string = "na";
  7693. }
  7694. if (a->file.is_directory && !b->file.is_directory) {
  7695. return -1; /* Always put directories on top */
  7696. } else if (!a->file.is_directory && b->file.is_directory) {
  7697. return 1; /* Always put directories on top */
  7698. } else if (*query_string == 'n') {
  7699. cmp_result = strcmp(a->file_name, b->file_name);
  7700. } else if (*query_string == 's') {
  7701. cmp_result = (a->file.size == b->file.size)
  7702. ? 0
  7703. : ((a->file.size > b->file.size) ? 1 : -1);
  7704. } else if (*query_string == 'd') {
  7705. cmp_result =
  7706. (a->file.last_modified == b->file.last_modified)
  7707. ? 0
  7708. : ((a->file.last_modified > b->file.last_modified) ? 1
  7709. : -1);
  7710. }
  7711. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7712. }
  7713. return 0;
  7714. }
  7715. static int
  7716. must_hide_file(struct mg_connection *conn, const char *path)
  7717. {
  7718. if (conn && conn->dom_ctx) {
  7719. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7720. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7721. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7722. || ((pattern != NULL)
  7723. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7724. }
  7725. return 0;
  7726. }
  7727. static int
  7728. scan_directory(struct mg_connection *conn,
  7729. const char *dir,
  7730. void *data,
  7731. int (*cb)(struct de *, void *))
  7732. {
  7733. char path[PATH_MAX];
  7734. struct dirent *dp;
  7735. DIR *dirp;
  7736. struct de de;
  7737. int truncated;
  7738. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7739. return 0;
  7740. } else {
  7741. de.conn = conn;
  7742. while ((dp = mg_readdir(dirp)) != NULL) {
  7743. /* Do not show current dir and hidden files */
  7744. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7745. || must_hide_file(conn, dp->d_name)) {
  7746. continue;
  7747. }
  7748. mg_snprintf(
  7749. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7750. /* If we don't memset stat structure to zero, mtime will have
  7751. * garbage and strftime() will segfault later on in
  7752. * print_dir_entry(). memset is required only if mg_stat()
  7753. * fails. For more details, see
  7754. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7755. memset(&de.file, 0, sizeof(de.file));
  7756. if (truncated) {
  7757. /* If the path is not complete, skip processing. */
  7758. continue;
  7759. }
  7760. if (!mg_stat(conn, path, &de.file)) {
  7761. mg_cry_internal(conn,
  7762. "%s: mg_stat(%s) failed: %s",
  7763. __func__,
  7764. path,
  7765. strerror(ERRNO));
  7766. }
  7767. de.file_name = dp->d_name;
  7768. cb(&de, data);
  7769. }
  7770. (void)mg_closedir(dirp);
  7771. }
  7772. return 1;
  7773. }
  7774. #if !defined(NO_FILES)
  7775. static int
  7776. remove_directory(struct mg_connection *conn, const char *dir)
  7777. {
  7778. char path[PATH_MAX];
  7779. struct dirent *dp;
  7780. DIR *dirp;
  7781. struct de de;
  7782. int truncated;
  7783. int ok = 1;
  7784. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7785. return 0;
  7786. } else {
  7787. de.conn = conn;
  7788. while ((dp = mg_readdir(dirp)) != NULL) {
  7789. /* Do not show current dir (but show hidden files as they will
  7790. * also be removed) */
  7791. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7792. continue;
  7793. }
  7794. mg_snprintf(
  7795. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7796. /* If we don't memset stat structure to zero, mtime will have
  7797. * garbage and strftime() will segfault later on in
  7798. * print_dir_entry(). memset is required only if mg_stat()
  7799. * fails. For more details, see
  7800. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7801. memset(&de.file, 0, sizeof(de.file));
  7802. if (truncated) {
  7803. /* Do not delete anything shorter */
  7804. ok = 0;
  7805. continue;
  7806. }
  7807. if (!mg_stat(conn, path, &de.file)) {
  7808. mg_cry_internal(conn,
  7809. "%s: mg_stat(%s) failed: %s",
  7810. __func__,
  7811. path,
  7812. strerror(ERRNO));
  7813. ok = 0;
  7814. }
  7815. if (de.file.is_directory) {
  7816. if (remove_directory(conn, path) == 0) {
  7817. ok = 0;
  7818. }
  7819. } else {
  7820. /* This will fail file is the file is in memory */
  7821. if (mg_remove(conn, path) == 0) {
  7822. ok = 0;
  7823. }
  7824. }
  7825. }
  7826. (void)mg_closedir(dirp);
  7827. IGNORE_UNUSED_RESULT(rmdir(dir));
  7828. }
  7829. return ok;
  7830. }
  7831. #endif
  7832. struct dir_scan_data {
  7833. struct de *entries;
  7834. unsigned int num_entries;
  7835. unsigned int arr_size;
  7836. };
  7837. /* Behaves like realloc(), but frees original pointer on failure */
  7838. static void *
  7839. realloc2(void *ptr, size_t size)
  7840. {
  7841. void *new_ptr = mg_realloc(ptr, size);
  7842. if (new_ptr == NULL) {
  7843. mg_free(ptr);
  7844. }
  7845. return new_ptr;
  7846. }
  7847. static int
  7848. dir_scan_callback(struct de *de, void *data)
  7849. {
  7850. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7851. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7852. dsd->arr_size *= 2;
  7853. dsd->entries =
  7854. (struct de *)realloc2(dsd->entries,
  7855. dsd->arr_size * sizeof(dsd->entries[0]));
  7856. }
  7857. if (dsd->entries == NULL) {
  7858. /* TODO(lsm, low): propagate an error to the caller */
  7859. dsd->num_entries = 0;
  7860. } else {
  7861. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7862. dsd->entries[dsd->num_entries].file = de->file;
  7863. dsd->entries[dsd->num_entries].conn = de->conn;
  7864. dsd->num_entries++;
  7865. }
  7866. return 0;
  7867. }
  7868. static void
  7869. handle_directory_request(struct mg_connection *conn, const char *dir)
  7870. {
  7871. unsigned int i;
  7872. int sort_direction;
  7873. struct dir_scan_data data = {NULL, 0, 128};
  7874. char date[64];
  7875. time_t curtime = time(NULL);
  7876. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7877. mg_send_http_error(conn,
  7878. 500,
  7879. "Error: Cannot open directory\nopendir(%s): %s",
  7880. dir,
  7881. strerror(ERRNO));
  7882. return;
  7883. }
  7884. gmt_time_string(date, sizeof(date), &curtime);
  7885. if (!conn) {
  7886. return;
  7887. }
  7888. sort_direction = ((conn->request_info.query_string != NULL)
  7889. && (conn->request_info.query_string[1] == 'd'))
  7890. ? 'a'
  7891. : 'd';
  7892. conn->must_close = 1;
  7893. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7894. send_static_cache_header(conn);
  7895. send_additional_header(conn);
  7896. mg_printf(conn,
  7897. "Date: %s\r\n"
  7898. "Connection: close\r\n"
  7899. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7900. date);
  7901. mg_printf(conn,
  7902. "<html><head><title>Index of %s</title>"
  7903. "<style>th {text-align: left;}</style></head>"
  7904. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7905. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7906. "<th><a href=\"?d%c\">Modified</a></th>"
  7907. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7908. "<tr><td colspan=\"3\"><hr></td></tr>",
  7909. conn->request_info.local_uri,
  7910. conn->request_info.local_uri,
  7911. sort_direction,
  7912. sort_direction,
  7913. sort_direction);
  7914. /* Print first entry - link to a parent directory */
  7915. mg_printf(conn,
  7916. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7917. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7918. conn->request_info.local_uri,
  7919. "..",
  7920. "Parent directory",
  7921. "-",
  7922. "-");
  7923. /* Sort and print directory entries */
  7924. if (data.entries != NULL) {
  7925. qsort(data.entries,
  7926. (size_t)data.num_entries,
  7927. sizeof(data.entries[0]),
  7928. compare_dir_entries);
  7929. for (i = 0; i < data.num_entries; i++) {
  7930. print_dir_entry(&data.entries[i]);
  7931. mg_free(data.entries[i].file_name);
  7932. }
  7933. mg_free(data.entries);
  7934. }
  7935. mg_printf(conn, "%s", "</table></body></html>");
  7936. conn->status_code = 200;
  7937. }
  7938. /* Send len bytes from the opened file to the client. */
  7939. static void
  7940. send_file_data(struct mg_connection *conn,
  7941. struct mg_file *filep,
  7942. int64_t offset,
  7943. int64_t len)
  7944. {
  7945. char buf[MG_BUF_LEN];
  7946. int to_read, num_read, num_written;
  7947. int64_t size;
  7948. if (!filep || !conn) {
  7949. return;
  7950. }
  7951. /* Sanity check the offset */
  7952. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7953. : (int64_t)(filep->stat.size);
  7954. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7955. #if defined(MG_USE_OPEN_FILE)
  7956. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7957. /* file stored in memory */
  7958. if (len > size - offset) {
  7959. len = size - offset;
  7960. }
  7961. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7962. } else /* else block below */
  7963. #endif
  7964. if (len > 0 && filep->access.fp != NULL) {
  7965. /* file stored on disk */
  7966. #if defined(__linux__)
  7967. /* sendfile is only available for Linux */
  7968. if ((conn->ssl == 0) && (conn->throttle == 0)
  7969. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7970. "yes"))) {
  7971. off_t sf_offs = (off_t)offset;
  7972. ssize_t sf_sent;
  7973. int sf_file = fileno(filep->access.fp);
  7974. int loop_cnt = 0;
  7975. do {
  7976. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7977. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7978. size_t sf_tosend =
  7979. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7980. sf_sent =
  7981. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7982. if (sf_sent > 0) {
  7983. len -= sf_sent;
  7984. offset += sf_sent;
  7985. } else if (loop_cnt == 0) {
  7986. /* This file can not be sent using sendfile.
  7987. * This might be the case for pseudo-files in the
  7988. * /sys/ and /proc/ file system.
  7989. * Use the regular user mode copy code instead. */
  7990. break;
  7991. } else if (sf_sent == 0) {
  7992. /* No error, but 0 bytes sent. May be EOF? */
  7993. return;
  7994. }
  7995. loop_cnt++;
  7996. } while ((len > 0) && (sf_sent >= 0));
  7997. if (sf_sent > 0) {
  7998. return; /* OK */
  7999. }
  8000. /* sf_sent<0 means error, thus fall back to the classic way */
  8001. /* This is always the case, if sf_file is not a "normal" file,
  8002. * e.g., for sending data from the output of a CGI process. */
  8003. offset = (int64_t)sf_offs;
  8004. }
  8005. #endif
  8006. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8007. mg_cry_internal(conn,
  8008. "%s: fseeko() failed: %s",
  8009. __func__,
  8010. strerror(ERRNO));
  8011. mg_send_http_error(
  8012. conn,
  8013. 500,
  8014. "%s",
  8015. "Error: Unable to access file at requested position.");
  8016. } else {
  8017. while (len > 0) {
  8018. /* Calculate how much to read from the file in the buffer */
  8019. to_read = sizeof(buf);
  8020. if ((int64_t)to_read > len) {
  8021. to_read = (int)len;
  8022. }
  8023. /* Read from file, exit the loop on error */
  8024. if ((num_read =
  8025. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8026. <= 0) {
  8027. break;
  8028. }
  8029. /* Send read bytes to the client, exit the loop on error */
  8030. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8031. != num_read) {
  8032. break;
  8033. }
  8034. /* Both read and were successful, adjust counters */
  8035. len -= num_written;
  8036. }
  8037. }
  8038. }
  8039. }
  8040. static int
  8041. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8042. {
  8043. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8044. }
  8045. static void
  8046. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8047. {
  8048. if ((filestat != NULL) && (buf != NULL)) {
  8049. mg_snprintf(NULL,
  8050. NULL, /* All calls to construct_etag use 64 byte buffer */
  8051. buf,
  8052. buf_len,
  8053. "\"%lx.%" INT64_FMT "\"",
  8054. (unsigned long)filestat->last_modified,
  8055. filestat->size);
  8056. }
  8057. }
  8058. static void
  8059. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8060. {
  8061. if (filep != NULL && filep->fp != NULL) {
  8062. #if defined(_WIN32)
  8063. (void)conn; /* Unused. */
  8064. #else
  8065. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8066. mg_cry_internal(conn,
  8067. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8068. __func__,
  8069. strerror(ERRNO));
  8070. }
  8071. #endif
  8072. }
  8073. }
  8074. #if defined(USE_ZLIB)
  8075. #include "mod_zlib.inl"
  8076. #endif
  8077. static void
  8078. handle_static_file_request(struct mg_connection *conn,
  8079. const char *path,
  8080. struct mg_file *filep,
  8081. const char *mime_type,
  8082. const char *additional_headers)
  8083. {
  8084. char date[64], lm[64], etag[64];
  8085. char range[128]; /* large enough, so there will be no overflow */
  8086. const char *msg = "OK", *hdr;
  8087. time_t curtime = time(NULL);
  8088. int64_t cl, r1, r2;
  8089. struct vec mime_vec;
  8090. int n, truncated;
  8091. char gz_path[PATH_MAX];
  8092. const char *encoding = "";
  8093. const char *cors1, *cors2, *cors3;
  8094. int is_head_request;
  8095. #if defined(USE_ZLIB)
  8096. /* Compression is allowed, unless there is a reason not to use compression.
  8097. * If the file is already compressed, too small or a "range" request was
  8098. * made, on the fly compression is not possible. */
  8099. int allow_on_the_fly_compression = 1;
  8100. #endif
  8101. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8102. return;
  8103. }
  8104. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8105. if (mime_type == NULL) {
  8106. get_mime_type(conn, path, &mime_vec);
  8107. } else {
  8108. mime_vec.ptr = mime_type;
  8109. mime_vec.len = strlen(mime_type);
  8110. }
  8111. if (filep->stat.size > INT64_MAX) {
  8112. mg_send_http_error(conn,
  8113. 500,
  8114. "Error: File size is too large to send\n%" INT64_FMT,
  8115. filep->stat.size);
  8116. return;
  8117. }
  8118. cl = (int64_t)filep->stat.size;
  8119. conn->status_code = 200;
  8120. range[0] = '\0';
  8121. #if defined(USE_ZLIB)
  8122. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8123. * it's important to rewrite the filename after resolving
  8124. * the mime type from it, to preserve the actual file's type */
  8125. if (!conn->accept_gzip) {
  8126. allow_on_the_fly_compression = 0;
  8127. }
  8128. #endif
  8129. if (filep->stat.is_gzipped) {
  8130. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8131. if (truncated) {
  8132. mg_send_http_error(conn,
  8133. 500,
  8134. "Error: Path of zipped file too long (%s)",
  8135. path);
  8136. return;
  8137. }
  8138. path = gz_path;
  8139. encoding = "Content-Encoding: gzip\r\n";
  8140. #if defined(USE_ZLIB)
  8141. /* File is already compressed. No "on the fly" compression. */
  8142. allow_on_the_fly_compression = 0;
  8143. #endif
  8144. }
  8145. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8146. mg_send_http_error(conn,
  8147. 500,
  8148. "Error: Cannot open file\nfopen(%s): %s",
  8149. path,
  8150. strerror(ERRNO));
  8151. return;
  8152. }
  8153. fclose_on_exec(&filep->access, conn);
  8154. /* If "Range" request was made: parse header, send only selected part
  8155. * of the file. */
  8156. r1 = r2 = 0;
  8157. hdr = mg_get_header(conn, "Range");
  8158. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  8159. && (r1 >= 0) && (r2 >= 0)) {
  8160. /* actually, range requests don't play well with a pre-gzipped
  8161. * file (since the range is specified in the uncompressed space) */
  8162. if (filep->stat.is_gzipped) {
  8163. mg_send_http_error(
  8164. conn,
  8165. 416, /* 416 = Range Not Satisfiable */
  8166. "%s",
  8167. "Error: Range requests in gzipped files are not supported");
  8168. (void)mg_fclose(
  8169. &filep->access); /* ignore error on read only file */
  8170. return;
  8171. }
  8172. conn->status_code = 206;
  8173. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8174. mg_snprintf(conn,
  8175. NULL, /* range buffer is big enough */
  8176. range,
  8177. sizeof(range),
  8178. "Content-Range: bytes "
  8179. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8180. r1,
  8181. r1 + cl - 1,
  8182. filep->stat.size);
  8183. msg = "Partial Content";
  8184. #if defined(USE_ZLIB)
  8185. /* Do not compress ranges. */
  8186. allow_on_the_fly_compression = 0;
  8187. #endif
  8188. }
  8189. /* Do not compress small files. Small files do not benefit from file
  8190. * compression, but there is still some overhead. */
  8191. #if defined(USE_ZLIB)
  8192. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8193. /* File is below the size limit. */
  8194. allow_on_the_fly_compression = 0;
  8195. }
  8196. #endif
  8197. /* Standard CORS header */
  8198. hdr = mg_get_header(conn, "Origin");
  8199. if (hdr) {
  8200. /* Cross-origin resource sharing (CORS), see
  8201. * http://www.html5rocks.com/en/tutorials/cors/,
  8202. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8203. * -
  8204. * preflight is not supported for files. */
  8205. cors1 = "Access-Control-Allow-Origin: ";
  8206. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8207. cors3 = "\r\n";
  8208. } else {
  8209. cors1 = cors2 = cors3 = "";
  8210. }
  8211. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8212. * according to
  8213. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8214. gmt_time_string(date, sizeof(date), &curtime);
  8215. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8216. construct_etag(etag, sizeof(etag), &filep->stat);
  8217. /* Send header */
  8218. (void)mg_printf(conn,
  8219. "HTTP/1.1 %d %s\r\n"
  8220. "%s%s%s" /* CORS */
  8221. "Date: %s\r\n"
  8222. "Last-Modified: %s\r\n"
  8223. "Etag: %s\r\n"
  8224. "Content-Type: %.*s\r\n"
  8225. "Connection: %s\r\n",
  8226. conn->status_code,
  8227. msg,
  8228. cors1,
  8229. cors2,
  8230. cors3,
  8231. date,
  8232. lm,
  8233. etag,
  8234. (int)mime_vec.len,
  8235. mime_vec.ptr,
  8236. suggest_connection_header(conn));
  8237. send_static_cache_header(conn);
  8238. send_additional_header(conn);
  8239. #if defined(USE_ZLIB)
  8240. /* On the fly compression allowed */
  8241. if (allow_on_the_fly_compression) {
  8242. /* For on the fly compression, we don't know the content size in
  8243. * advance, so we have to use chunked encoding */
  8244. (void)mg_printf(conn,
  8245. "Content-Encoding: gzip\r\n"
  8246. "Transfer-Encoding: chunked\r\n");
  8247. } else
  8248. #endif
  8249. {
  8250. /* Without on-the-fly compression, we know the content-length
  8251. * and we can use ranges (with on-the-fly compression we cannot).
  8252. * So we send these response headers only in this case. */
  8253. (void)mg_printf(conn,
  8254. "Content-Length: %" INT64_FMT "\r\n"
  8255. "Accept-Ranges: bytes\r\n"
  8256. "%s" /* range */
  8257. "%s" /* encoding */,
  8258. cl,
  8259. range,
  8260. encoding);
  8261. }
  8262. /* The previous code must not add any header starting with X- to make
  8263. * sure no one of the additional_headers is included twice */
  8264. if (additional_headers != NULL) {
  8265. (void)mg_printf(conn,
  8266. "%.*s\r\n\r\n",
  8267. (int)strlen(additional_headers),
  8268. additional_headers);
  8269. } else {
  8270. (void)mg_printf(conn, "\r\n");
  8271. }
  8272. if (!is_head_request) {
  8273. #if defined(USE_ZLIB)
  8274. if (allow_on_the_fly_compression) {
  8275. /* Compress and send */
  8276. send_compressed_data(conn, filep);
  8277. } else
  8278. #endif
  8279. {
  8280. /* Send file directly */
  8281. send_file_data(conn, filep, r1, cl);
  8282. }
  8283. }
  8284. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8285. }
  8286. #if !defined(NO_CACHING)
  8287. /* Return True if we should reply 304 Not Modified. */
  8288. static int
  8289. is_not_modified(const struct mg_connection *conn,
  8290. const struct mg_file_stat *filestat)
  8291. {
  8292. char etag[64];
  8293. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8294. const char *inm = mg_get_header(conn, "If-None-Match");
  8295. construct_etag(etag, sizeof(etag), filestat);
  8296. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8297. || ((ims != NULL)
  8298. && (filestat->last_modified <= parse_date_string(ims)));
  8299. }
  8300. static void
  8301. handle_not_modified_static_file_request(struct mg_connection *conn,
  8302. struct mg_file *filep)
  8303. {
  8304. char date[64], lm[64], etag[64];
  8305. time_t curtime = time(NULL);
  8306. if ((conn == NULL) || (filep == NULL)) {
  8307. return;
  8308. }
  8309. conn->status_code = 304;
  8310. gmt_time_string(date, sizeof(date), &curtime);
  8311. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8312. construct_etag(etag, sizeof(etag), &filep->stat);
  8313. (void)mg_printf(conn,
  8314. "HTTP/1.1 %d %s\r\n"
  8315. "Date: %s\r\n",
  8316. conn->status_code,
  8317. mg_get_response_code_text(conn, conn->status_code),
  8318. date);
  8319. send_static_cache_header(conn);
  8320. send_additional_header(conn);
  8321. (void)mg_printf(conn,
  8322. "Last-Modified: %s\r\n"
  8323. "Etag: %s\r\n"
  8324. "Connection: %s\r\n"
  8325. "\r\n",
  8326. lm,
  8327. etag,
  8328. suggest_connection_header(conn));
  8329. }
  8330. #endif
  8331. void
  8332. mg_send_file(struct mg_connection *conn, const char *path)
  8333. {
  8334. mg_send_mime_file(conn, path, NULL);
  8335. }
  8336. void
  8337. mg_send_mime_file(struct mg_connection *conn,
  8338. const char *path,
  8339. const char *mime_type)
  8340. {
  8341. mg_send_mime_file2(conn, path, mime_type, NULL);
  8342. }
  8343. void
  8344. mg_send_mime_file2(struct mg_connection *conn,
  8345. const char *path,
  8346. const char *mime_type,
  8347. const char *additional_headers)
  8348. {
  8349. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8350. if (!conn) {
  8351. /* No conn */
  8352. return;
  8353. }
  8354. if (mg_stat(conn, path, &file.stat)) {
  8355. #if !defined(NO_CACHING)
  8356. if (is_not_modified(conn, &file.stat)) {
  8357. /* Send 304 "Not Modified" - this must not send any body data */
  8358. handle_not_modified_static_file_request(conn, &file);
  8359. } else
  8360. #endif /* NO_CACHING */
  8361. if (file.stat.is_directory) {
  8362. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8363. "yes")) {
  8364. handle_directory_request(conn, path);
  8365. } else {
  8366. mg_send_http_error(conn,
  8367. 403,
  8368. "%s",
  8369. "Error: Directory listing denied");
  8370. }
  8371. } else {
  8372. handle_static_file_request(
  8373. conn, path, &file, mime_type, additional_headers);
  8374. }
  8375. } else {
  8376. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8377. }
  8378. }
  8379. /* For a given PUT path, create all intermediate subdirectories.
  8380. * Return 0 if the path itself is a directory.
  8381. * Return 1 if the path leads to a file.
  8382. * Return -1 for if the path is too long.
  8383. * Return -2 if path can not be created.
  8384. */
  8385. static int
  8386. put_dir(struct mg_connection *conn, const char *path)
  8387. {
  8388. char buf[PATH_MAX];
  8389. const char *s, *p;
  8390. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8391. size_t len;
  8392. int res = 1;
  8393. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8394. len = (size_t)(p - path);
  8395. if (len >= sizeof(buf)) {
  8396. /* path too long */
  8397. res = -1;
  8398. break;
  8399. }
  8400. memcpy(buf, path, len);
  8401. buf[len] = '\0';
  8402. /* Try to create intermediate directory */
  8403. DEBUG_TRACE("mkdir(%s)", buf);
  8404. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8405. /* path does not exixt and can not be created */
  8406. res = -2;
  8407. break;
  8408. }
  8409. /* Is path itself a directory? */
  8410. if (p[1] == '\0') {
  8411. res = 0;
  8412. }
  8413. }
  8414. return res;
  8415. }
  8416. static void
  8417. remove_bad_file(const struct mg_connection *conn, const char *path)
  8418. {
  8419. int r = mg_remove(conn, path);
  8420. if (r != 0) {
  8421. mg_cry_internal(conn,
  8422. "%s: Cannot remove invalid file %s",
  8423. __func__,
  8424. path);
  8425. }
  8426. }
  8427. long long
  8428. mg_store_body(struct mg_connection *conn, const char *path)
  8429. {
  8430. char buf[MG_BUF_LEN];
  8431. long long len = 0;
  8432. int ret, n;
  8433. struct mg_file fi;
  8434. if (conn->consumed_content != 0) {
  8435. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8436. return -11;
  8437. }
  8438. ret = put_dir(conn, path);
  8439. if (ret < 0) {
  8440. /* -1 for path too long,
  8441. * -2 for path can not be created. */
  8442. return ret;
  8443. }
  8444. if (ret != 1) {
  8445. /* Return 0 means, path itself is a directory. */
  8446. return 0;
  8447. }
  8448. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8449. return -12;
  8450. }
  8451. ret = mg_read(conn, buf, sizeof(buf));
  8452. while (ret > 0) {
  8453. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8454. if (n != ret) {
  8455. (void)mg_fclose(
  8456. &fi.access); /* File is bad and will be removed anyway. */
  8457. remove_bad_file(conn, path);
  8458. return -13;
  8459. }
  8460. len += ret;
  8461. ret = mg_read(conn, buf, sizeof(buf));
  8462. }
  8463. /* File is open for writing. If fclose fails, there was probably an
  8464. * error flushing the buffer to disk, so the file on disk might be
  8465. * broken. Delete it and return an error to the caller. */
  8466. if (mg_fclose(&fi.access) != 0) {
  8467. remove_bad_file(conn, path);
  8468. return -14;
  8469. }
  8470. return len;
  8471. }
  8472. /* Parse a buffer:
  8473. * Forward the string pointer till the end of a word, then
  8474. * terminate it and forward till the begin of the next word.
  8475. */
  8476. static int
  8477. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8478. {
  8479. /* Forward until a space is found - use isgraph here */
  8480. /* See http://www.cplusplus.com/reference/cctype/ */
  8481. while (isgraph(**ppw)) {
  8482. (*ppw)++;
  8483. }
  8484. /* Check end of word */
  8485. if (eol) {
  8486. /* must be a end of line */
  8487. if ((**ppw != '\r') && (**ppw != '\n')) {
  8488. return -1;
  8489. }
  8490. } else {
  8491. /* must be a end of a word, but not a line */
  8492. if (**ppw != ' ') {
  8493. return -1;
  8494. }
  8495. }
  8496. /* Terminate and forward to the next word */
  8497. do {
  8498. **ppw = 0;
  8499. (*ppw)++;
  8500. } while ((**ppw) && isspace(**ppw));
  8501. /* Check after term */
  8502. if (!eol) {
  8503. /* if it's not the end of line, there must be a next word */
  8504. if (!isgraph(**ppw)) {
  8505. return -1;
  8506. }
  8507. }
  8508. /* ok */
  8509. return 1;
  8510. }
  8511. /* Parse HTTP headers from the given buffer, advance buf pointer
  8512. * to the point where parsing stopped.
  8513. * All parameters must be valid pointers (not NULL).
  8514. * Return <0 on error. */
  8515. static int
  8516. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8517. {
  8518. int i;
  8519. int num_headers = 0;
  8520. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8521. char *dp = *buf;
  8522. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8523. dp++;
  8524. }
  8525. if (dp == *buf) {
  8526. /* End of headers reached. */
  8527. break;
  8528. }
  8529. if (*dp != ':') {
  8530. /* This is not a valid field. */
  8531. return -1;
  8532. }
  8533. /* End of header key (*dp == ':') */
  8534. /* Truncate here and set the key name */
  8535. *dp = 0;
  8536. hdr[i].name = *buf;
  8537. do {
  8538. dp++;
  8539. } while (*dp == ' ');
  8540. /* The rest of the line is the value */
  8541. hdr[i].value = dp;
  8542. *buf = dp + strcspn(dp, "\r\n");
  8543. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8544. *buf = NULL;
  8545. }
  8546. num_headers = i + 1;
  8547. if (*buf) {
  8548. (*buf)[0] = 0;
  8549. (*buf)[1] = 0;
  8550. *buf += 2;
  8551. } else {
  8552. *buf = dp;
  8553. break;
  8554. }
  8555. if ((*buf)[0] == '\r') {
  8556. /* This is the end of the header */
  8557. break;
  8558. }
  8559. }
  8560. return num_headers;
  8561. }
  8562. struct mg_http_method_info {
  8563. const char *name;
  8564. int request_has_body;
  8565. int response_has_body;
  8566. int is_safe;
  8567. int is_idempotent;
  8568. int is_cacheable;
  8569. };
  8570. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8571. static struct mg_http_method_info http_methods[] = {
  8572. /* HTTP (RFC 2616) */
  8573. {"GET", 0, 1, 1, 1, 1},
  8574. {"POST", 1, 1, 0, 0, 0},
  8575. {"PUT", 1, 0, 0, 1, 0},
  8576. {"DELETE", 0, 0, 0, 1, 0},
  8577. {"HEAD", 0, 0, 1, 1, 1},
  8578. {"OPTIONS", 0, 0, 1, 1, 0},
  8579. {"CONNECT", 1, 1, 0, 0, 0},
  8580. /* TRACE method (RFC 2616) is not supported for security reasons */
  8581. /* PATCH method (RFC 5789) */
  8582. {"PATCH", 1, 0, 0, 0, 0},
  8583. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8584. /* WEBDAV (RFC 2518) */
  8585. {"PROPFIND", 0, 1, 1, 1, 0},
  8586. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8587. * Some PROPFIND results MAY be cached, with care,
  8588. * as there is no cache validation mechanism for
  8589. * most properties. This method is both safe and
  8590. * idempotent (see Section 9.1 of [RFC2616]). */
  8591. {"MKCOL", 0, 0, 0, 1, 0},
  8592. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8593. * When MKCOL is invoked without a request body,
  8594. * the newly created collection SHOULD have no
  8595. * members. A MKCOL request message may contain
  8596. * a message body. The precise behavior of a MKCOL
  8597. * request when the body is present is undefined,
  8598. * ... ==> We do not support MKCOL with body data.
  8599. * This method is idempotent, but not safe (see
  8600. * Section 9.1 of [RFC2616]). Responses to this
  8601. * method MUST NOT be cached. */
  8602. /* Unsupported WEBDAV Methods: */
  8603. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8604. /* + 11 methods from RFC 3253 */
  8605. /* ORDERPATCH (RFC 3648) */
  8606. /* ACL (RFC 3744) */
  8607. /* SEARCH (RFC 5323) */
  8608. /* + MicroSoft extensions
  8609. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8610. /* REPORT method (RFC 3253) */
  8611. {"REPORT", 1, 1, 1, 1, 1},
  8612. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8613. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8614. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8615. * to be useful for REST in case a "GET request with body" is
  8616. * required. */
  8617. {NULL, 0, 0, 0, 0, 0}
  8618. /* end of list */
  8619. };
  8620. static const struct mg_http_method_info *
  8621. get_http_method_info(const char *method)
  8622. {
  8623. /* Check if the method is known to the server. The list of all known
  8624. * HTTP methods can be found here at
  8625. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8626. */
  8627. const struct mg_http_method_info *m = http_methods;
  8628. while (m->name) {
  8629. if (!strcmp(m->name, method)) {
  8630. return m;
  8631. }
  8632. m++;
  8633. }
  8634. return NULL;
  8635. }
  8636. static int
  8637. is_valid_http_method(const char *method)
  8638. {
  8639. return (get_http_method_info(method) != NULL);
  8640. }
  8641. /* Parse HTTP request, fill in mg_request_info structure.
  8642. * This function modifies the buffer by NUL-terminating
  8643. * HTTP request components, header names and header values.
  8644. * Parameters:
  8645. * buf (in/out): pointer to the HTTP header to parse and split
  8646. * len (in): length of HTTP header buffer
  8647. * re (out): parsed header as mg_request_info
  8648. * buf and ri must be valid pointers (not NULL), len>0.
  8649. * Returns <0 on error. */
  8650. static int
  8651. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8652. {
  8653. int request_length;
  8654. int init_skip = 0;
  8655. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8656. * remote_port */
  8657. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8658. NULL;
  8659. ri->num_headers = 0;
  8660. /* RFC says that all initial whitespaces should be ingored */
  8661. /* This included all leading \r and \n (isspace) */
  8662. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8663. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8664. buf++;
  8665. len--;
  8666. init_skip++;
  8667. }
  8668. if (len == 0) {
  8669. /* Incomplete request */
  8670. return 0;
  8671. }
  8672. /* Control characters are not allowed, including zero */
  8673. if (iscntrl(*(unsigned char *)buf)) {
  8674. return -1;
  8675. }
  8676. /* Find end of HTTP header */
  8677. request_length = get_http_header_len(buf, len);
  8678. if (request_length <= 0) {
  8679. return request_length;
  8680. }
  8681. buf[request_length - 1] = '\0';
  8682. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8683. return -1;
  8684. }
  8685. /* The first word has to be the HTTP method */
  8686. ri->request_method = buf;
  8687. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8688. return -1;
  8689. }
  8690. /* Check for a valid http method */
  8691. if (!is_valid_http_method(ri->request_method)) {
  8692. return -1;
  8693. }
  8694. /* The second word is the URI */
  8695. ri->request_uri = buf;
  8696. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8697. return -1;
  8698. }
  8699. /* Next would be the HTTP version */
  8700. ri->http_version = buf;
  8701. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8702. return -1;
  8703. }
  8704. /* Check for a valid HTTP version key */
  8705. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8706. /* Invalid request */
  8707. return -1;
  8708. }
  8709. ri->http_version += 5;
  8710. /* Parse all HTTP headers */
  8711. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8712. if (ri->num_headers < 0) {
  8713. /* Error while parsing headers */
  8714. return -1;
  8715. }
  8716. return request_length + init_skip;
  8717. }
  8718. static int
  8719. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8720. {
  8721. int response_length;
  8722. int init_skip = 0;
  8723. char *tmp, *tmp2;
  8724. long l;
  8725. /* Initialize elements. */
  8726. ri->http_version = ri->status_text = NULL;
  8727. ri->num_headers = ri->status_code = 0;
  8728. /* RFC says that all initial whitespaces should be ingored */
  8729. /* This included all leading \r and \n (isspace) */
  8730. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8731. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8732. buf++;
  8733. len--;
  8734. init_skip++;
  8735. }
  8736. if (len == 0) {
  8737. /* Incomplete request */
  8738. return 0;
  8739. }
  8740. /* Control characters are not allowed, including zero */
  8741. if (iscntrl(*(unsigned char *)buf)) {
  8742. return -1;
  8743. }
  8744. /* Find end of HTTP header */
  8745. response_length = get_http_header_len(buf, len);
  8746. if (response_length <= 0) {
  8747. return response_length;
  8748. }
  8749. buf[response_length - 1] = '\0';
  8750. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8751. return -1;
  8752. }
  8753. /* The first word is the HTTP version */
  8754. /* Check for a valid HTTP version key */
  8755. if (strncmp(buf, "HTTP/", 5) != 0) {
  8756. /* Invalid request */
  8757. return -1;
  8758. }
  8759. buf += 5;
  8760. if (!isgraph(buf[0])) {
  8761. /* Invalid request */
  8762. return -1;
  8763. }
  8764. ri->http_version = buf;
  8765. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8766. return -1;
  8767. }
  8768. /* The second word is the status as a number */
  8769. tmp = buf;
  8770. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8771. return -1;
  8772. }
  8773. l = strtol(tmp, &tmp2, 10);
  8774. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8775. /* Everything else but a 3 digit code is invalid */
  8776. return -1;
  8777. }
  8778. ri->status_code = (int)l;
  8779. /* The rest of the line is the status text */
  8780. ri->status_text = buf;
  8781. /* Find end of status text */
  8782. /* isgraph or isspace = isprint */
  8783. while (isprint(*buf)) {
  8784. buf++;
  8785. }
  8786. if ((*buf != '\r') && (*buf != '\n')) {
  8787. return -1;
  8788. }
  8789. /* Terminate string and forward buf to next line */
  8790. do {
  8791. *buf = 0;
  8792. buf++;
  8793. } while ((*buf) && isspace(*buf));
  8794. /* Parse all HTTP headers */
  8795. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8796. if (ri->num_headers < 0) {
  8797. /* Error while parsing headers */
  8798. return -1;
  8799. }
  8800. return response_length + init_skip;
  8801. }
  8802. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8803. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8804. * buffer (which marks the end of HTTP request). Buffer buf may already
  8805. * have some data. The length of the data is stored in nread.
  8806. * Upon every read operation, increase nread by the number of bytes read. */
  8807. static int
  8808. read_message(FILE *fp,
  8809. struct mg_connection *conn,
  8810. char *buf,
  8811. int bufsiz,
  8812. int *nread)
  8813. {
  8814. int request_len, n = 0;
  8815. struct timespec last_action_time;
  8816. double request_timeout;
  8817. if (!conn) {
  8818. return 0;
  8819. }
  8820. memset(&last_action_time, 0, sizeof(last_action_time));
  8821. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8822. /* value of request_timeout is in seconds, config in milliseconds */
  8823. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8824. } else {
  8825. request_timeout = -1.0;
  8826. }
  8827. if (conn->handled_requests > 0) {
  8828. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8829. request_timeout =
  8830. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8831. }
  8832. }
  8833. request_len = get_http_header_len(buf, *nread);
  8834. /* first time reading from this connection */
  8835. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8836. while (request_len == 0) {
  8837. /* Full request not yet received */
  8838. if (conn->phys_ctx->stop_flag != 0) {
  8839. /* Server is to be stopped. */
  8840. return -1;
  8841. }
  8842. if (*nread >= bufsiz) {
  8843. /* Request too long */
  8844. return -2;
  8845. }
  8846. n = pull_inner(
  8847. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8848. if (n == -2) {
  8849. /* Receive error */
  8850. return -1;
  8851. }
  8852. if (n > 0) {
  8853. *nread += n;
  8854. request_len = get_http_header_len(buf, *nread);
  8855. } else {
  8856. request_len = 0;
  8857. }
  8858. if ((request_len == 0) && (request_timeout >= 0)) {
  8859. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8860. > request_timeout) {
  8861. /* Timeout */
  8862. return -1;
  8863. }
  8864. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8865. }
  8866. }
  8867. return request_len;
  8868. }
  8869. #if !defined(NO_CGI) || !defined(NO_FILES)
  8870. static int
  8871. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8872. {
  8873. const char *expect, *body;
  8874. char buf[MG_BUF_LEN];
  8875. int to_read, nread, success = 0;
  8876. int64_t buffered_len;
  8877. double timeout = -1.0;
  8878. if (!conn) {
  8879. return 0;
  8880. }
  8881. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8882. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8883. }
  8884. expect = mg_get_header(conn, "Expect");
  8885. DEBUG_ASSERT(fp != NULL);
  8886. if (!fp) {
  8887. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8888. return 0;
  8889. }
  8890. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8891. /* Content length is not specified by the client. */
  8892. mg_send_http_error(conn,
  8893. 411,
  8894. "%s",
  8895. "Error: Client did not specify content length");
  8896. } else if ((expect != NULL)
  8897. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8898. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8899. */
  8900. mg_send_http_error(conn,
  8901. 417,
  8902. "Error: Can not fulfill expectation %s",
  8903. expect);
  8904. } else {
  8905. if (expect != NULL) {
  8906. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8907. conn->status_code = 100;
  8908. } else {
  8909. conn->status_code = 200;
  8910. }
  8911. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8912. - conn->consumed_content;
  8913. DEBUG_ASSERT(buffered_len >= 0);
  8914. DEBUG_ASSERT(conn->consumed_content == 0);
  8915. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8916. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8917. return 0;
  8918. }
  8919. if (buffered_len > 0) {
  8920. if ((int64_t)buffered_len > conn->content_len) {
  8921. buffered_len = (int)conn->content_len;
  8922. }
  8923. body = conn->buf + conn->request_len + conn->consumed_content;
  8924. push_all(
  8925. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8926. conn->consumed_content += buffered_len;
  8927. }
  8928. nread = 0;
  8929. while (conn->consumed_content < conn->content_len) {
  8930. to_read = sizeof(buf);
  8931. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8932. to_read = (int)(conn->content_len - conn->consumed_content);
  8933. }
  8934. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8935. if (nread == -2) {
  8936. /* error */
  8937. break;
  8938. }
  8939. if (nread > 0) {
  8940. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8941. != nread) {
  8942. break;
  8943. }
  8944. }
  8945. conn->consumed_content += nread;
  8946. }
  8947. if (conn->consumed_content == conn->content_len) {
  8948. success = (nread >= 0);
  8949. }
  8950. /* Each error code path in this function must send an error */
  8951. if (!success) {
  8952. /* NOTE: Maybe some data has already been sent. */
  8953. /* TODO (low): If some data has been sent, a correct error
  8954. * reply can no longer be sent, so just close the connection */
  8955. mg_send_http_error(conn, 500, "%s", "");
  8956. }
  8957. }
  8958. return success;
  8959. }
  8960. #endif
  8961. #if !defined(NO_CGI)
  8962. /* This structure helps to create an environment for the spawned CGI
  8963. * program.
  8964. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8965. * last element must be NULL.
  8966. * However, on Windows there is a requirement that all these
  8967. * VARIABLE=VALUE\0
  8968. * strings must reside in a contiguous buffer. The end of the buffer is
  8969. * marked by two '\0' characters.
  8970. * We satisfy both worlds: we create an envp array (which is vars), all
  8971. * entries are actually pointers inside buf. */
  8972. struct cgi_environment {
  8973. struct mg_connection *conn;
  8974. /* Data block */
  8975. char *buf; /* Environment buffer */
  8976. size_t buflen; /* Space available in buf */
  8977. size_t bufused; /* Space taken in buf */
  8978. /* Index block */
  8979. char **var; /* char **envp */
  8980. size_t varlen; /* Number of variables available in var */
  8981. size_t varused; /* Number of variables stored in var */
  8982. };
  8983. static void addenv(struct cgi_environment *env,
  8984. PRINTF_FORMAT_STRING(const char *fmt),
  8985. ...) PRINTF_ARGS(2, 3);
  8986. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8987. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8988. static void
  8989. addenv(struct cgi_environment *env, const char *fmt, ...)
  8990. {
  8991. size_t n, space;
  8992. int truncated = 0;
  8993. char *added;
  8994. va_list ap;
  8995. /* Calculate how much space is left in the buffer */
  8996. space = (env->buflen - env->bufused);
  8997. /* Calculate an estimate for the required space */
  8998. n = strlen(fmt) + 2 + 128;
  8999. do {
  9000. if (space <= n) {
  9001. /* Allocate new buffer */
  9002. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9003. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9004. if (!added) {
  9005. /* Out of memory */
  9006. mg_cry_internal(
  9007. env->conn,
  9008. "%s: Cannot allocate memory for CGI variable [%s]",
  9009. __func__,
  9010. fmt);
  9011. return;
  9012. }
  9013. env->buf = added;
  9014. env->buflen = n;
  9015. space = (env->buflen - env->bufused);
  9016. }
  9017. /* Make a pointer to the free space int the buffer */
  9018. added = env->buf + env->bufused;
  9019. /* Copy VARIABLE=VALUE\0 string into the free space */
  9020. va_start(ap, fmt);
  9021. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  9022. va_end(ap);
  9023. /* Do not add truncated strings to the environment */
  9024. if (truncated) {
  9025. /* Reallocate the buffer */
  9026. space = 0;
  9027. n = 1;
  9028. }
  9029. } while (truncated);
  9030. /* Calculate number of bytes added to the environment */
  9031. n = strlen(added) + 1;
  9032. env->bufused += n;
  9033. /* Now update the variable index */
  9034. space = (env->varlen - env->varused);
  9035. if (space < 2) {
  9036. mg_cry_internal(env->conn,
  9037. "%s: Cannot register CGI variable [%s]",
  9038. __func__,
  9039. fmt);
  9040. return;
  9041. }
  9042. /* Append a pointer to the added string into the envp array */
  9043. env->var[env->varused] = added;
  9044. env->varused++;
  9045. }
  9046. /* Return 0 on success, non-zero if an error occurs. */
  9047. static int
  9048. prepare_cgi_environment(struct mg_connection *conn,
  9049. const char *prog,
  9050. struct cgi_environment *env)
  9051. {
  9052. const char *s;
  9053. struct vec var_vec;
  9054. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9055. int i, truncated, uri_len;
  9056. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9057. return -1;
  9058. }
  9059. env->conn = conn;
  9060. env->buflen = CGI_ENVIRONMENT_SIZE;
  9061. env->bufused = 0;
  9062. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9063. if (env->buf == NULL) {
  9064. mg_cry_internal(conn,
  9065. "%s: Not enough memory for environmental buffer",
  9066. __func__);
  9067. return -1;
  9068. }
  9069. env->varlen = MAX_CGI_ENVIR_VARS;
  9070. env->varused = 0;
  9071. env->var =
  9072. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  9073. if (env->var == NULL) {
  9074. mg_cry_internal(conn,
  9075. "%s: Not enough memory for environmental variables",
  9076. __func__);
  9077. mg_free(env->buf);
  9078. return -1;
  9079. }
  9080. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9081. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9082. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9083. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9084. /* Prepare the environment block */
  9085. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9086. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9087. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9088. #if defined(USE_IPV6)
  9089. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9090. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9091. } else
  9092. #endif
  9093. {
  9094. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9095. }
  9096. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9097. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9098. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9099. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9100. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9101. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9102. /* SCRIPT_NAME */
  9103. uri_len = (int)strlen(conn->request_info.local_uri);
  9104. if (conn->path_info == NULL) {
  9105. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9106. /* URI: /path_to_script/script.cgi */
  9107. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9108. } else {
  9109. /* URI: /path_to_script/ ... using index.cgi */
  9110. const char *index_file = strrchr(prog, '/');
  9111. if (index_file) {
  9112. addenv(env,
  9113. "SCRIPT_NAME=%s%s",
  9114. conn->request_info.local_uri,
  9115. index_file + 1);
  9116. }
  9117. }
  9118. } else {
  9119. /* URI: /path_to_script/script.cgi/path_info */
  9120. addenv(env,
  9121. "SCRIPT_NAME=%.*s",
  9122. uri_len - (int)strlen(conn->path_info),
  9123. conn->request_info.local_uri);
  9124. }
  9125. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9126. if (conn->path_info == NULL) {
  9127. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9128. } else {
  9129. addenv(env,
  9130. "PATH_TRANSLATED=%s%s",
  9131. conn->dom_ctx->config[DOCUMENT_ROOT],
  9132. conn->path_info);
  9133. }
  9134. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9135. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9136. addenv(env, "CONTENT_TYPE=%s", s);
  9137. }
  9138. if (conn->request_info.query_string != NULL) {
  9139. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9140. }
  9141. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9142. addenv(env, "CONTENT_LENGTH=%s", s);
  9143. }
  9144. if ((s = getenv("PATH")) != NULL) {
  9145. addenv(env, "PATH=%s", s);
  9146. }
  9147. if (conn->path_info != NULL) {
  9148. addenv(env, "PATH_INFO=%s", conn->path_info);
  9149. }
  9150. if (conn->status_code > 0) {
  9151. /* CGI error handler should show the status code */
  9152. addenv(env, "STATUS=%d", conn->status_code);
  9153. }
  9154. #if defined(_WIN32)
  9155. if ((s = getenv("COMSPEC")) != NULL) {
  9156. addenv(env, "COMSPEC=%s", s);
  9157. }
  9158. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9159. addenv(env, "SYSTEMROOT=%s", s);
  9160. }
  9161. if ((s = getenv("SystemDrive")) != NULL) {
  9162. addenv(env, "SystemDrive=%s", s);
  9163. }
  9164. if ((s = getenv("ProgramFiles")) != NULL) {
  9165. addenv(env, "ProgramFiles=%s", s);
  9166. }
  9167. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9168. addenv(env, "ProgramFiles(x86)=%s", s);
  9169. }
  9170. #else
  9171. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9172. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9173. }
  9174. #endif /* _WIN32 */
  9175. if ((s = getenv("PERLLIB")) != NULL) {
  9176. addenv(env, "PERLLIB=%s", s);
  9177. }
  9178. if (conn->request_info.remote_user != NULL) {
  9179. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9180. addenv(env, "%s", "AUTH_TYPE=Digest");
  9181. }
  9182. /* Add all headers as HTTP_* variables */
  9183. for (i = 0; i < conn->request_info.num_headers; i++) {
  9184. (void)mg_snprintf(conn,
  9185. &truncated,
  9186. http_var_name,
  9187. sizeof(http_var_name),
  9188. "HTTP_%s",
  9189. conn->request_info.http_headers[i].name);
  9190. if (truncated) {
  9191. mg_cry_internal(conn,
  9192. "%s: HTTP header variable too long [%s]",
  9193. __func__,
  9194. conn->request_info.http_headers[i].name);
  9195. continue;
  9196. }
  9197. /* Convert variable name into uppercase, and change - to _ */
  9198. for (p = http_var_name; *p != '\0'; p++) {
  9199. if (*p == '-') {
  9200. *p = '_';
  9201. }
  9202. *p = (char)toupper(*(unsigned char *)p);
  9203. }
  9204. addenv(env,
  9205. "%s=%s",
  9206. http_var_name,
  9207. conn->request_info.http_headers[i].value);
  9208. }
  9209. /* Add user-specified variables */
  9210. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9211. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9212. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9213. }
  9214. env->var[env->varused] = NULL;
  9215. env->buf[env->bufused] = '\0';
  9216. return 0;
  9217. }
  9218. #if defined(USE_TIMERS)
  9219. #define TIMER_API static
  9220. #include "timer.inl"
  9221. static int
  9222. abort_process(void *data)
  9223. {
  9224. /* Waitpid checks for child status and won't work for a pid that does not
  9225. * identify a child of the current process. Thus, if the pid is reused,
  9226. * we will not affect a different process. */
  9227. pid_t pid = (pid_t)data;
  9228. int status = 0;
  9229. pid_t rpid = waitpid(pid, &status, WNOHANG);
  9230. if ((rpid != (pid_t)-1) && (status == 0)) {
  9231. /* Stop child process */
  9232. DEBUG_TRACE("CGI timer: Stop child process %p\n", pid);
  9233. kill(pid, SIGABRT);
  9234. /* Wait until process is terminated (don't leave zombies) */
  9235. while (waitpid(pid, &status, 0) != -1) /* nop */
  9236. ;
  9237. } else {
  9238. DEBUG_TRACE("CGI timer: Child process %p already stopped in time\n",
  9239. pid);
  9240. }
  9241. return 0;
  9242. }
  9243. #endif /* USE_TIMERS */
  9244. static void
  9245. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9246. {
  9247. char *buf;
  9248. size_t buflen;
  9249. int headers_len, data_len, i, truncated;
  9250. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9251. const char *status, *status_text, *connection_state;
  9252. char *pbuf, dir[PATH_MAX], *p;
  9253. struct mg_request_info ri;
  9254. struct cgi_environment blk;
  9255. FILE *in = NULL, *out = NULL, *err = NULL;
  9256. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9257. pid_t pid = (pid_t)-1;
  9258. if (conn == NULL) {
  9259. return;
  9260. }
  9261. buf = NULL;
  9262. buflen = conn->phys_ctx->max_request_size;
  9263. i = prepare_cgi_environment(conn, prog, &blk);
  9264. if (i != 0) {
  9265. blk.buf = NULL;
  9266. blk.var = NULL;
  9267. goto done;
  9268. }
  9269. /* CGI must be executed in its own directory. 'dir' must point to the
  9270. * directory containing executable program, 'p' must point to the
  9271. * executable program name relative to 'dir'. */
  9272. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9273. if (truncated) {
  9274. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9275. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9276. goto done;
  9277. }
  9278. if ((p = strrchr(dir, '/')) != NULL) {
  9279. *p++ = '\0';
  9280. } else {
  9281. dir[0] = '.';
  9282. dir[1] = '\0';
  9283. p = (char *)prog;
  9284. }
  9285. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9286. status = strerror(ERRNO);
  9287. mg_cry_internal(
  9288. conn,
  9289. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9290. prog,
  9291. status);
  9292. mg_send_http_error(conn,
  9293. 500,
  9294. "Error: Cannot create CGI pipe: %s",
  9295. status);
  9296. goto done;
  9297. }
  9298. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9299. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9300. if (pid == (pid_t)-1) {
  9301. status = strerror(ERRNO);
  9302. mg_cry_internal(
  9303. conn,
  9304. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9305. prog,
  9306. status);
  9307. mg_send_http_error(conn,
  9308. 500,
  9309. "Error: Cannot spawn CGI process [%s]: %s",
  9310. prog,
  9311. status);
  9312. goto done;
  9313. }
  9314. #if defined(USE_TIMERS)
  9315. // TODO (#618): set a timeout
  9316. timer_add(
  9317. conn->phys_ctx, /* one minute */ 60.0, 0.0, 1, abort_process, pid);
  9318. #endif
  9319. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  9320. */
  9321. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9322. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9323. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9324. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9325. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9326. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9327. /* Parent closes only one side of the pipes.
  9328. * If we don't mark them as closed, close() attempt before
  9329. * return from this function throws an exception on Windows.
  9330. * Windows does not like when closed descriptor is closed again. */
  9331. (void)close(fdin[0]);
  9332. (void)close(fdout[1]);
  9333. (void)close(fderr[1]);
  9334. fdin[0] = fdout[1] = fderr[1] = -1;
  9335. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9336. status = strerror(ERRNO);
  9337. mg_cry_internal(conn,
  9338. "Error: CGI program \"%s\": Can not open stdin: %s",
  9339. prog,
  9340. status);
  9341. mg_send_http_error(conn,
  9342. 500,
  9343. "Error: CGI can not open fdin\nfopen: %s",
  9344. status);
  9345. goto done;
  9346. }
  9347. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9348. status = strerror(ERRNO);
  9349. mg_cry_internal(conn,
  9350. "Error: CGI program \"%s\": Can not open stdout: %s",
  9351. prog,
  9352. status);
  9353. mg_send_http_error(conn,
  9354. 500,
  9355. "Error: CGI can not open fdout\nfopen: %s",
  9356. status);
  9357. goto done;
  9358. }
  9359. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9360. status = strerror(ERRNO);
  9361. mg_cry_internal(conn,
  9362. "Error: CGI program \"%s\": Can not open stderr: %s",
  9363. prog,
  9364. status);
  9365. mg_send_http_error(conn,
  9366. 500,
  9367. "Error: CGI can not open fderr\nfopen: %s",
  9368. status);
  9369. goto done;
  9370. }
  9371. setbuf(in, NULL);
  9372. setbuf(out, NULL);
  9373. setbuf(err, NULL);
  9374. fout.access.fp = out;
  9375. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9376. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9377. (signed long long)conn->request_info.content_length);
  9378. /* This is a POST/PUT request, or another request with body data. */
  9379. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9380. /* Error sending the body data */
  9381. mg_cry_internal(
  9382. conn,
  9383. "Error: CGI program \"%s\": Forward body data failed",
  9384. prog);
  9385. goto done;
  9386. }
  9387. }
  9388. /* Close so child gets an EOF. */
  9389. fclose(in);
  9390. in = NULL;
  9391. fdin[1] = -1;
  9392. /* Now read CGI reply into a buffer. We need to set correct
  9393. * status code, thus we need to see all HTTP headers first.
  9394. * Do not send anything back to client, until we buffer in all
  9395. * HTTP headers. */
  9396. data_len = 0;
  9397. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9398. if (buf == NULL) {
  9399. mg_send_http_error(conn,
  9400. 500,
  9401. "Error: Not enough memory for CGI buffer (%u bytes)",
  9402. (unsigned int)buflen);
  9403. mg_cry_internal(
  9404. conn,
  9405. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9406. "bytes)",
  9407. prog,
  9408. (unsigned int)buflen);
  9409. goto done;
  9410. }
  9411. DEBUG_TRACE("CGI: %s", "wait for response");
  9412. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9413. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9414. if (headers_len <= 0) {
  9415. /* Could not parse the CGI response. Check if some error message on
  9416. * stderr. */
  9417. i = pull_all(err, conn, buf, (int)buflen);
  9418. if (i > 0) {
  9419. /* CGI program explicitly sent an error */
  9420. /* Write the error message to the internal log */
  9421. mg_cry_internal(conn,
  9422. "Error: CGI program \"%s\" sent error "
  9423. "message: [%.*s]",
  9424. prog,
  9425. i,
  9426. buf);
  9427. /* Don't send the error message back to the client */
  9428. mg_send_http_error(conn,
  9429. 500,
  9430. "Error: CGI program \"%s\" failed.",
  9431. prog);
  9432. } else {
  9433. /* CGI program did not explicitly send an error, but a broken
  9434. * respon header */
  9435. mg_cry_internal(conn,
  9436. "Error: CGI program sent malformed or too big "
  9437. "(>%u bytes) HTTP headers: [%.*s]",
  9438. (unsigned)buflen,
  9439. data_len,
  9440. buf);
  9441. mg_send_http_error(conn,
  9442. 500,
  9443. "Error: CGI program sent malformed or too big "
  9444. "(>%u bytes) HTTP headers: [%.*s]",
  9445. (unsigned)buflen,
  9446. data_len,
  9447. buf);
  9448. }
  9449. /* in both cases, abort processing CGI */
  9450. goto done;
  9451. }
  9452. pbuf = buf;
  9453. buf[headers_len - 1] = '\0';
  9454. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9455. /* Make up and send the status line */
  9456. status_text = "OK";
  9457. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9458. != NULL) {
  9459. conn->status_code = atoi(status);
  9460. status_text = status;
  9461. while (isdigit(*(const unsigned char *)status_text)
  9462. || *status_text == ' ') {
  9463. status_text++;
  9464. }
  9465. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9466. != NULL) {
  9467. conn->status_code = 307;
  9468. } else {
  9469. conn->status_code = 200;
  9470. }
  9471. connection_state =
  9472. get_header(ri.http_headers, ri.num_headers, "Connection");
  9473. if (!header_has_option(connection_state, "keep-alive")) {
  9474. conn->must_close = 1;
  9475. }
  9476. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9477. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9478. /* Send headers */
  9479. for (i = 0; i < ri.num_headers; i++) {
  9480. mg_printf(conn,
  9481. "%s: %s\r\n",
  9482. ri.http_headers[i].name,
  9483. ri.http_headers[i].value);
  9484. }
  9485. mg_write(conn, "\r\n", 2);
  9486. /* Send chunk of data that may have been read after the headers */
  9487. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9488. /* Read the rest of CGI output and send to the client */
  9489. DEBUG_TRACE("CGI: %s", "forward all data");
  9490. send_file_data(conn, &fout, 0, INT64_MAX);
  9491. DEBUG_TRACE("CGI: %s", "all data sent");
  9492. done:
  9493. mg_free(blk.var);
  9494. mg_free(blk.buf);
  9495. if (pid != (pid_t)-1) {
  9496. #if defined(USE_TIMERS)
  9497. abort_process((void *)pid);
  9498. #endif
  9499. }
  9500. if (fdin[0] != -1) {
  9501. close(fdin[0]);
  9502. }
  9503. if (fdout[1] != -1) {
  9504. close(fdout[1]);
  9505. }
  9506. if (in != NULL) {
  9507. fclose(in);
  9508. } else if (fdin[1] != -1) {
  9509. close(fdin[1]);
  9510. }
  9511. if (out != NULL) {
  9512. fclose(out);
  9513. } else if (fdout[0] != -1) {
  9514. close(fdout[0]);
  9515. }
  9516. if (err != NULL) {
  9517. fclose(err);
  9518. } else if (fderr[0] != -1) {
  9519. close(fderr[0]);
  9520. }
  9521. if (buf != NULL) {
  9522. mg_free(buf);
  9523. }
  9524. }
  9525. #endif /* !NO_CGI */
  9526. #if !defined(NO_FILES)
  9527. static void
  9528. mkcol(struct mg_connection *conn, const char *path)
  9529. {
  9530. int rc, body_len;
  9531. struct de de;
  9532. char date[64];
  9533. time_t curtime = time(NULL);
  9534. if (conn == NULL) {
  9535. return;
  9536. }
  9537. /* TODO (mid): Check the mg_send_http_error situations in this function
  9538. */
  9539. memset(&de.file, 0, sizeof(de.file));
  9540. if (!mg_stat(conn, path, &de.file)) {
  9541. mg_cry_internal(conn,
  9542. "%s: mg_stat(%s) failed: %s",
  9543. __func__,
  9544. path,
  9545. strerror(ERRNO));
  9546. }
  9547. if (de.file.last_modified) {
  9548. /* TODO (mid): This check does not seem to make any sense ! */
  9549. /* TODO (mid): Add a webdav unit test first, before changing
  9550. * anything here. */
  9551. mg_send_http_error(
  9552. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9553. return;
  9554. }
  9555. body_len = conn->data_len - conn->request_len;
  9556. if (body_len > 0) {
  9557. mg_send_http_error(
  9558. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9559. return;
  9560. }
  9561. rc = mg_mkdir(conn, path, 0755);
  9562. if (rc == 0) {
  9563. conn->status_code = 201;
  9564. gmt_time_string(date, sizeof(date), &curtime);
  9565. mg_printf(conn,
  9566. "HTTP/1.1 %d Created\r\n"
  9567. "Date: %s\r\n",
  9568. conn->status_code,
  9569. date);
  9570. send_static_cache_header(conn);
  9571. send_additional_header(conn);
  9572. mg_printf(conn,
  9573. "Content-Length: 0\r\n"
  9574. "Connection: %s\r\n\r\n",
  9575. suggest_connection_header(conn));
  9576. } else {
  9577. if (errno == EEXIST) {
  9578. mg_send_http_error(
  9579. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9580. } else if (errno == EACCES) {
  9581. mg_send_http_error(
  9582. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9583. } else if (errno == ENOENT) {
  9584. mg_send_http_error(
  9585. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9586. } else {
  9587. mg_send_http_error(
  9588. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9589. }
  9590. }
  9591. }
  9592. static void
  9593. put_file(struct mg_connection *conn, const char *path)
  9594. {
  9595. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9596. const char *range;
  9597. int64_t r1, r2;
  9598. int rc;
  9599. char date[64];
  9600. time_t curtime = time(NULL);
  9601. if (conn == NULL) {
  9602. return;
  9603. }
  9604. if (mg_stat(conn, path, &file.stat)) {
  9605. /* File already exists */
  9606. conn->status_code = 200;
  9607. if (file.stat.is_directory) {
  9608. /* This is an already existing directory,
  9609. * so there is nothing to do for the server. */
  9610. rc = 0;
  9611. } else {
  9612. /* File exists and is not a directory. */
  9613. /* Can it be replaced? */
  9614. #if defined(MG_USE_OPEN_FILE)
  9615. if (file.access.membuf != NULL) {
  9616. /* This is an "in-memory" file, that can not be replaced */
  9617. mg_send_http_error(conn,
  9618. 405,
  9619. "Error: Put not possible\nReplacing %s "
  9620. "is not supported",
  9621. path);
  9622. return;
  9623. }
  9624. #endif
  9625. /* Check if the server may write this file */
  9626. if (access(path, W_OK) == 0) {
  9627. /* Access granted */
  9628. conn->status_code = 200;
  9629. rc = 1;
  9630. } else {
  9631. mg_send_http_error(
  9632. conn,
  9633. 403,
  9634. "Error: Put not possible\nReplacing %s is not allowed",
  9635. path);
  9636. return;
  9637. }
  9638. }
  9639. } else {
  9640. /* File should be created */
  9641. conn->status_code = 201;
  9642. rc = put_dir(conn, path);
  9643. }
  9644. if (rc == 0) {
  9645. /* put_dir returns 0 if path is a directory */
  9646. gmt_time_string(date, sizeof(date), &curtime);
  9647. mg_printf(conn,
  9648. "HTTP/1.1 %d %s\r\n",
  9649. conn->status_code,
  9650. mg_get_response_code_text(NULL, conn->status_code));
  9651. send_no_cache_header(conn);
  9652. send_additional_header(conn);
  9653. mg_printf(conn,
  9654. "Date: %s\r\n"
  9655. "Content-Length: 0\r\n"
  9656. "Connection: %s\r\n\r\n",
  9657. date,
  9658. suggest_connection_header(conn));
  9659. /* Request to create a directory has been fulfilled successfully.
  9660. * No need to put a file. */
  9661. return;
  9662. }
  9663. if (rc == -1) {
  9664. /* put_dir returns -1 if the path is too long */
  9665. mg_send_http_error(conn,
  9666. 414,
  9667. "Error: Path too long\nput_dir(%s): %s",
  9668. path,
  9669. strerror(ERRNO));
  9670. return;
  9671. }
  9672. if (rc == -2) {
  9673. /* put_dir returns -2 if the directory can not be created */
  9674. mg_send_http_error(conn,
  9675. 500,
  9676. "Error: Can not create directory\nput_dir(%s): %s",
  9677. path,
  9678. strerror(ERRNO));
  9679. return;
  9680. }
  9681. /* A file should be created or overwritten. */
  9682. /* Currently CivetWeb does not nead read+write access. */
  9683. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9684. || file.access.fp == NULL) {
  9685. (void)mg_fclose(&file.access);
  9686. mg_send_http_error(conn,
  9687. 500,
  9688. "Error: Can not create file\nfopen(%s): %s",
  9689. path,
  9690. strerror(ERRNO));
  9691. return;
  9692. }
  9693. fclose_on_exec(&file.access, conn);
  9694. range = mg_get_header(conn, "Content-Range");
  9695. r1 = r2 = 0;
  9696. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9697. conn->status_code = 206; /* Partial content */
  9698. fseeko(file.access.fp, r1, SEEK_SET);
  9699. }
  9700. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9701. /* forward_body_data failed.
  9702. * The error code has already been sent to the client,
  9703. * and conn->status_code is already set. */
  9704. (void)mg_fclose(&file.access);
  9705. return;
  9706. }
  9707. if (mg_fclose(&file.access) != 0) {
  9708. /* fclose failed. This might have different reasons, but a likely
  9709. * one is "no space on disk", http 507. */
  9710. conn->status_code = 507;
  9711. }
  9712. gmt_time_string(date, sizeof(date), &curtime);
  9713. mg_printf(conn,
  9714. "HTTP/1.1 %d %s\r\n",
  9715. conn->status_code,
  9716. mg_get_response_code_text(NULL, conn->status_code));
  9717. send_no_cache_header(conn);
  9718. send_additional_header(conn);
  9719. mg_printf(conn,
  9720. "Date: %s\r\n"
  9721. "Content-Length: 0\r\n"
  9722. "Connection: %s\r\n\r\n",
  9723. date,
  9724. suggest_connection_header(conn));
  9725. }
  9726. static void
  9727. delete_file(struct mg_connection *conn, const char *path)
  9728. {
  9729. struct de de;
  9730. memset(&de.file, 0, sizeof(de.file));
  9731. if (!mg_stat(conn, path, &de.file)) {
  9732. /* mg_stat returns 0 if the file does not exist */
  9733. mg_send_http_error(conn,
  9734. 404,
  9735. "Error: Cannot delete file\nFile %s not found",
  9736. path);
  9737. return;
  9738. }
  9739. #if 0 /* Ignore if a file in memory is inside a folder */
  9740. if (de.access.membuf != NULL) {
  9741. /* the file is cached in memory */
  9742. mg_send_http_error(
  9743. conn,
  9744. 405,
  9745. "Error: Delete not possible\nDeleting %s is not supported",
  9746. path);
  9747. return;
  9748. }
  9749. #endif
  9750. if (de.file.is_directory) {
  9751. if (remove_directory(conn, path)) {
  9752. /* Delete is successful: Return 204 without content. */
  9753. mg_send_http_error(conn, 204, "%s", "");
  9754. } else {
  9755. /* Delete is not successful: Return 500 (Server error). */
  9756. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9757. }
  9758. return;
  9759. }
  9760. /* This is an existing file (not a directory).
  9761. * Check if write permission is granted. */
  9762. if (access(path, W_OK) != 0) {
  9763. /* File is read only */
  9764. mg_send_http_error(
  9765. conn,
  9766. 403,
  9767. "Error: Delete not possible\nDeleting %s is not allowed",
  9768. path);
  9769. return;
  9770. }
  9771. /* Try to delete it. */
  9772. if (mg_remove(conn, path) == 0) {
  9773. /* Delete was successful: Return 204 without content. */
  9774. mg_send_http_error(conn, 204, "%s", "");
  9775. } else {
  9776. /* Delete not successful (file locked). */
  9777. mg_send_http_error(conn,
  9778. 423,
  9779. "Error: Cannot delete file\nremove(%s): %s",
  9780. path,
  9781. strerror(ERRNO));
  9782. }
  9783. }
  9784. #endif /* !NO_FILES */
  9785. static void
  9786. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9787. static void
  9788. do_ssi_include(struct mg_connection *conn,
  9789. const char *ssi,
  9790. char *tag,
  9791. int include_level)
  9792. {
  9793. char file_name[MG_BUF_LEN], path[512], *p;
  9794. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9795. size_t len;
  9796. int truncated = 0;
  9797. if (conn == NULL) {
  9798. return;
  9799. }
  9800. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9801. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9802. * always < MG_BUF_LEN. */
  9803. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9804. /* File name is relative to the webserver root */
  9805. file_name[511] = 0;
  9806. (void)mg_snprintf(conn,
  9807. &truncated,
  9808. path,
  9809. sizeof(path),
  9810. "%s/%s",
  9811. conn->dom_ctx->config[DOCUMENT_ROOT],
  9812. file_name);
  9813. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9814. /* File name is relative to the webserver working directory
  9815. * or it is absolute system path */
  9816. file_name[511] = 0;
  9817. (void)
  9818. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9819. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9820. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9821. /* File name is relative to the currect document */
  9822. file_name[511] = 0;
  9823. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9824. if (!truncated) {
  9825. if ((p = strrchr(path, '/')) != NULL) {
  9826. p[1] = '\0';
  9827. }
  9828. len = strlen(path);
  9829. (void)mg_snprintf(conn,
  9830. &truncated,
  9831. path + len,
  9832. sizeof(path) - len,
  9833. "%s",
  9834. file_name);
  9835. }
  9836. } else {
  9837. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9838. return;
  9839. }
  9840. if (truncated) {
  9841. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9842. return;
  9843. }
  9844. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9845. mg_cry_internal(conn,
  9846. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9847. tag,
  9848. path,
  9849. strerror(ERRNO));
  9850. } else {
  9851. fclose_on_exec(&file.access, conn);
  9852. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9853. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9854. path) > 0) {
  9855. send_ssi_file(conn, path, &file, include_level + 1);
  9856. } else {
  9857. send_file_data(conn, &file, 0, INT64_MAX);
  9858. }
  9859. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9860. }
  9861. }
  9862. #if !defined(NO_POPEN)
  9863. static void
  9864. do_ssi_exec(struct mg_connection *conn, char *tag)
  9865. {
  9866. char cmd[1024] = "";
  9867. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9868. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9869. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9870. } else {
  9871. cmd[1023] = 0;
  9872. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9873. mg_cry_internal(conn,
  9874. "Cannot SSI #exec: [%s]: %s",
  9875. cmd,
  9876. strerror(ERRNO));
  9877. } else {
  9878. send_file_data(conn, &file, 0, INT64_MAX);
  9879. pclose(file.access.fp);
  9880. }
  9881. }
  9882. }
  9883. #endif /* !NO_POPEN */
  9884. static int
  9885. mg_fgetc(struct mg_file *filep, int offset)
  9886. {
  9887. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  9888. if (filep == NULL) {
  9889. return EOF;
  9890. }
  9891. #if defined(MG_USE_OPEN_FILE)
  9892. if ((filep->access.membuf != NULL) && (offset >= 0)
  9893. && (((unsigned int)(offset)) < filep->stat.size)) {
  9894. return ((const unsigned char *)filep->access.membuf)[offset];
  9895. } else /* else block below */
  9896. #endif
  9897. if (filep->access.fp != NULL) {
  9898. return fgetc(filep->access.fp);
  9899. } else {
  9900. return EOF;
  9901. }
  9902. }
  9903. static void
  9904. send_ssi_file(struct mg_connection *conn,
  9905. const char *path,
  9906. struct mg_file *filep,
  9907. int include_level)
  9908. {
  9909. char buf[MG_BUF_LEN];
  9910. int ch, offset, len, in_tag, in_ssi_tag;
  9911. if (include_level > 10) {
  9912. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  9913. return;
  9914. }
  9915. in_tag = in_ssi_tag = len = offset = 0;
  9916. /* Read file, byte by byte, and look for SSI include tags */
  9917. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9918. if (in_tag) {
  9919. /* We are in a tag, either SSI tag or html tag */
  9920. if (ch == '>') {
  9921. /* Tag is closing */
  9922. buf[len++] = '>';
  9923. if (in_ssi_tag) {
  9924. /* Handle SSI tag */
  9925. buf[len] = 0;
  9926. if (!memcmp(buf + 5, "include", 7)) {
  9927. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9928. #if !defined(NO_POPEN)
  9929. } else if (!memcmp(buf + 5, "exec", 4)) {
  9930. do_ssi_exec(conn, buf + 9);
  9931. #endif /* !NO_POPEN */
  9932. } else {
  9933. mg_cry_internal(conn,
  9934. "%s: unknown SSI "
  9935. "command: \"%s\"",
  9936. path,
  9937. buf);
  9938. }
  9939. len = 0;
  9940. in_ssi_tag = in_tag = 0;
  9941. } else {
  9942. /* Not an SSI tag */
  9943. /* Flush buffer */
  9944. (void)mg_write(conn, buf, (size_t)len);
  9945. len = 0;
  9946. in_tag = 0;
  9947. }
  9948. } else {
  9949. /* Tag is still open */
  9950. buf[len++] = (char)(ch & 0xff);
  9951. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9952. /* All SSI tags start with <!--# */
  9953. in_ssi_tag = 1;
  9954. }
  9955. if ((len + 2) > (int)sizeof(buf)) {
  9956. /* Tag to long for buffer */
  9957. mg_cry_internal(conn, "%s: tag is too large", path);
  9958. return;
  9959. }
  9960. }
  9961. } else {
  9962. /* We are not in a tag yet. */
  9963. if (ch == '<') {
  9964. /* Tag is opening */
  9965. in_tag = 1;
  9966. if (len > 0) {
  9967. /* Flush current buffer.
  9968. * Buffer is filled with "len" bytes. */
  9969. (void)mg_write(conn, buf, (size_t)len);
  9970. }
  9971. /* Store the < */
  9972. len = 1;
  9973. buf[0] = '<';
  9974. } else {
  9975. /* No Tag */
  9976. /* Add data to buffer */
  9977. buf[len++] = (char)(ch & 0xff);
  9978. /* Flush if buffer is full */
  9979. if (len == (int)sizeof(buf)) {
  9980. mg_write(conn, buf, (size_t)len);
  9981. len = 0;
  9982. }
  9983. }
  9984. }
  9985. }
  9986. /* Send the rest of buffered data */
  9987. if (len > 0) {
  9988. mg_write(conn, buf, (size_t)len);
  9989. }
  9990. }
  9991. static void
  9992. handle_ssi_file_request(struct mg_connection *conn,
  9993. const char *path,
  9994. struct mg_file *filep)
  9995. {
  9996. char date[64];
  9997. time_t curtime = time(NULL);
  9998. const char *cors1, *cors2, *cors3;
  9999. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10000. return;
  10001. }
  10002. if (mg_get_header(conn, "Origin")) {
  10003. /* Cross-origin resource sharing (CORS). */
  10004. cors1 = "Access-Control-Allow-Origin: ";
  10005. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10006. cors3 = "\r\n";
  10007. } else {
  10008. cors1 = cors2 = cors3 = "";
  10009. }
  10010. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10011. /* File exists (precondition for calling this function),
  10012. * but can not be opened by the server. */
  10013. mg_send_http_error(conn,
  10014. 500,
  10015. "Error: Cannot read file\nfopen(%s): %s",
  10016. path,
  10017. strerror(ERRNO));
  10018. } else {
  10019. conn->must_close = 1;
  10020. gmt_time_string(date, sizeof(date), &curtime);
  10021. fclose_on_exec(&filep->access, conn);
  10022. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10023. send_no_cache_header(conn);
  10024. send_additional_header(conn);
  10025. mg_printf(conn,
  10026. "%s%s%s"
  10027. "Date: %s\r\n"
  10028. "Content-Type: text/html\r\n"
  10029. "Connection: %s\r\n\r\n",
  10030. cors1,
  10031. cors2,
  10032. cors3,
  10033. date,
  10034. suggest_connection_header(conn));
  10035. send_ssi_file(conn, path, filep, 0);
  10036. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10037. }
  10038. }
  10039. #if !defined(NO_FILES)
  10040. static void
  10041. send_options(struct mg_connection *conn)
  10042. {
  10043. char date[64];
  10044. time_t curtime = time(NULL);
  10045. if (!conn) {
  10046. return;
  10047. }
  10048. conn->status_code = 200;
  10049. conn->must_close = 1;
  10050. gmt_time_string(date, sizeof(date), &curtime);
  10051. /* We do not set a "Cache-Control" header here, but leave the default.
  10052. * Since browsers do not send an OPTIONS request, we can not test the
  10053. * effect anyway. */
  10054. mg_printf(conn,
  10055. "HTTP/1.1 200 OK\r\n"
  10056. "Date: %s\r\n"
  10057. "Connection: %s\r\n"
  10058. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10059. "PROPFIND, MKCOL\r\n"
  10060. "DAV: 1\r\n",
  10061. date,
  10062. suggest_connection_header(conn));
  10063. send_additional_header(conn);
  10064. mg_printf(conn, "\r\n");
  10065. }
  10066. /* Writes PROPFIND properties for a collection element */
  10067. static void
  10068. print_props(struct mg_connection *conn,
  10069. const char *uri,
  10070. struct mg_file_stat *filep)
  10071. {
  10072. char mtime[64];
  10073. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  10074. return;
  10075. }
  10076. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10077. mg_printf(conn,
  10078. "<d:response>"
  10079. "<d:href>%s</d:href>"
  10080. "<d:propstat>"
  10081. "<d:prop>"
  10082. "<d:resourcetype>%s</d:resourcetype>"
  10083. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10084. "<d:getlastmodified>%s</d:getlastmodified>"
  10085. "</d:prop>"
  10086. "<d:status>HTTP/1.1 200 OK</d:status>"
  10087. "</d:propstat>"
  10088. "</d:response>\n",
  10089. uri,
  10090. filep->is_directory ? "<d:collection/>" : "",
  10091. filep->size,
  10092. mtime);
  10093. }
  10094. static int
  10095. print_dav_dir_entry(struct de *de, void *data)
  10096. {
  10097. char href[PATH_MAX];
  10098. int truncated;
  10099. struct mg_connection *conn = (struct mg_connection *)data;
  10100. if (!de || !conn) {
  10101. return -1;
  10102. }
  10103. mg_snprintf(conn,
  10104. &truncated,
  10105. href,
  10106. sizeof(href),
  10107. "%s%s",
  10108. conn->request_info.local_uri,
  10109. de->file_name);
  10110. if (!truncated) {
  10111. size_t href_encoded_size;
  10112. char *href_encoded;
  10113. href_encoded_size = PATH_MAX * 3; /* worst case */
  10114. href_encoded = (char *)mg_malloc(href_encoded_size);
  10115. if (href_encoded == NULL) {
  10116. return -1;
  10117. }
  10118. mg_url_encode(href, href_encoded, href_encoded_size);
  10119. print_props(conn, href_encoded, &de->file);
  10120. mg_free(href_encoded);
  10121. }
  10122. return 0;
  10123. }
  10124. static void
  10125. handle_propfind(struct mg_connection *conn,
  10126. const char *path,
  10127. struct mg_file_stat *filep)
  10128. {
  10129. const char *depth = mg_get_header(conn, "Depth");
  10130. char date[64];
  10131. time_t curtime = time(NULL);
  10132. gmt_time_string(date, sizeof(date), &curtime);
  10133. if (!conn || !path || !filep || !conn->dom_ctx) {
  10134. return;
  10135. }
  10136. conn->must_close = 1;
  10137. conn->status_code = 207;
  10138. mg_printf(conn,
  10139. "HTTP/1.1 207 Multi-Status\r\n"
  10140. "Date: %s\r\n",
  10141. date);
  10142. send_static_cache_header(conn);
  10143. send_additional_header(conn);
  10144. mg_printf(conn,
  10145. "Connection: %s\r\n"
  10146. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10147. suggest_connection_header(conn));
  10148. mg_printf(conn,
  10149. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10150. "<d:multistatus xmlns:d='DAV:'>\n");
  10151. /* Print properties for the requested resource itself */
  10152. print_props(conn, conn->request_info.local_uri, filep);
  10153. /* If it is a directory, print directory entries too if Depth is not 0
  10154. */
  10155. if (filep->is_directory
  10156. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10157. "yes")
  10158. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10159. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10160. }
  10161. mg_printf(conn, "%s\n", "</d:multistatus>");
  10162. }
  10163. #endif
  10164. void
  10165. mg_lock_connection(struct mg_connection *conn)
  10166. {
  10167. if (conn) {
  10168. (void)pthread_mutex_lock(&conn->mutex);
  10169. }
  10170. }
  10171. void
  10172. mg_unlock_connection(struct mg_connection *conn)
  10173. {
  10174. if (conn) {
  10175. (void)pthread_mutex_unlock(&conn->mutex);
  10176. }
  10177. }
  10178. void
  10179. mg_lock_context(struct mg_context *ctx)
  10180. {
  10181. if (ctx) {
  10182. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10183. }
  10184. }
  10185. void
  10186. mg_unlock_context(struct mg_context *ctx)
  10187. {
  10188. if (ctx) {
  10189. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10190. }
  10191. }
  10192. #if defined(USE_LUA)
  10193. #include "mod_lua.inl"
  10194. #endif /* USE_LUA */
  10195. #if defined(USE_DUKTAPE)
  10196. #include "mod_duktape.inl"
  10197. #endif /* USE_DUKTAPE */
  10198. #if defined(USE_WEBSOCKET)
  10199. #if !defined(NO_SSL_DL)
  10200. #define SHA_API static
  10201. #include "sha1.inl"
  10202. #endif
  10203. static int
  10204. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10205. {
  10206. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10207. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10208. SHA_CTX sha_ctx;
  10209. int truncated;
  10210. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10211. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10212. if (truncated) {
  10213. conn->must_close = 1;
  10214. return 0;
  10215. }
  10216. DEBUG_TRACE("%s", "Send websocket handshake");
  10217. SHA1_Init(&sha_ctx);
  10218. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10219. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10220. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10221. mg_printf(conn,
  10222. "HTTP/1.1 101 Switching Protocols\r\n"
  10223. "Upgrade: websocket\r\n"
  10224. "Connection: Upgrade\r\n"
  10225. "Sec-WebSocket-Accept: %s\r\n",
  10226. b64_sha);
  10227. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10228. mg_printf(conn,
  10229. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10230. conn->request_info.acceptedWebSocketSubprotocol);
  10231. } else {
  10232. mg_printf(conn, "%s", "\r\n");
  10233. }
  10234. return 1;
  10235. }
  10236. #if !defined(MG_MAX_UNANSWERED_PING)
  10237. /* Configuration of the maximum number of websocket PINGs that might
  10238. * stay unanswered before the connection is considered broken.
  10239. * Note: The name of this define may still change (until it is
  10240. * defined as a compile parameter in a documentation).
  10241. */
  10242. #define MG_MAX_UNANSWERED_PING (5)
  10243. #endif
  10244. static void
  10245. read_websocket(struct mg_connection *conn,
  10246. mg_websocket_data_handler ws_data_handler,
  10247. void *callback_data)
  10248. {
  10249. /* Pointer to the beginning of the portion of the incoming websocket
  10250. * message queue.
  10251. * The original websocket upgrade request is never removed, so the queue
  10252. * begins after it. */
  10253. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10254. int n, error, exit_by_callback;
  10255. int ret;
  10256. /* body_len is the length of the entire queue in bytes
  10257. * len is the length of the current message
  10258. * data_len is the length of the current message's data payload
  10259. * header_len is the length of the current message's header */
  10260. size_t i, len, mask_len = 0, header_len, body_len;
  10261. uint64_t data_len = 0;
  10262. /* "The masking key is a 32-bit value chosen at random by the client."
  10263. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10264. */
  10265. unsigned char mask[4];
  10266. /* data points to the place where the message is stored when passed to
  10267. * the websocket_data callback. This is either mem on the stack, or a
  10268. * dynamically allocated buffer if it is too large. */
  10269. unsigned char mem[4096];
  10270. unsigned char mop; /* mask flag and opcode */
  10271. /* Variables used for connection monitoring */
  10272. double timeout = -1.0;
  10273. int enable_ping_pong = 0;
  10274. int ping_count = 0;
  10275. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10276. enable_ping_pong =
  10277. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10278. "yes");
  10279. }
  10280. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10281. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10282. }
  10283. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10284. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10285. }
  10286. /* Enter data processing loop */
  10287. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10288. conn->request_info.remote_addr,
  10289. conn->request_info.remote_port);
  10290. conn->in_websocket_handling = 1;
  10291. mg_set_thread_name("wsock");
  10292. /* Loop continuously, reading messages from the socket, invoking the
  10293. * callback, and waiting repeatedly until an error occurs. */
  10294. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10295. header_len = 0;
  10296. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10297. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10298. len = buf[1] & 127;
  10299. mask_len = (buf[1] & 128) ? 4 : 0;
  10300. if ((len < 126) && (body_len >= mask_len)) {
  10301. /* inline 7-bit length field */
  10302. data_len = len;
  10303. header_len = 2 + mask_len;
  10304. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10305. /* 16-bit length field */
  10306. header_len = 4 + mask_len;
  10307. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10308. } else if (body_len >= (10 + mask_len)) {
  10309. /* 64-bit length field */
  10310. uint32_t l1, l2;
  10311. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10312. memcpy(&l2, &buf[6], 4);
  10313. header_len = 10 + mask_len;
  10314. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10315. if (data_len > (uint64_t)0x7FFF0000ul) {
  10316. /* no can do */
  10317. mg_cry_internal(
  10318. conn,
  10319. "%s",
  10320. "websocket out of memory; closing connection");
  10321. break;
  10322. }
  10323. }
  10324. }
  10325. if ((header_len > 0) && (body_len >= header_len)) {
  10326. /* Allocate space to hold websocket payload */
  10327. unsigned char *data = mem;
  10328. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10329. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10330. conn->phys_ctx);
  10331. if (data == NULL) {
  10332. /* Allocation failed, exit the loop and then close the
  10333. * connection */
  10334. mg_cry_internal(
  10335. conn,
  10336. "%s",
  10337. "websocket out of memory; closing connection");
  10338. break;
  10339. }
  10340. }
  10341. /* Copy the mask before we shift the queue and destroy it */
  10342. if (mask_len > 0) {
  10343. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10344. } else {
  10345. memset(mask, 0, sizeof(mask));
  10346. }
  10347. /* Read frame payload from the first message in the queue into
  10348. * data and advance the queue by moving the memory in place. */
  10349. DEBUG_ASSERT(body_len >= header_len);
  10350. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10351. mop = buf[0]; /* current mask and opcode */
  10352. /* Overflow case */
  10353. len = body_len - header_len;
  10354. memcpy(data, buf + header_len, len);
  10355. error = 0;
  10356. while ((uint64_t)len < data_len) {
  10357. n = pull_inner(NULL,
  10358. conn,
  10359. (char *)(data + len),
  10360. (int)(data_len - len),
  10361. timeout);
  10362. if (n <= -2) {
  10363. error = 1;
  10364. break;
  10365. } else if (n > 0) {
  10366. len += (size_t)n;
  10367. } else {
  10368. /* Timeout: should retry */
  10369. /* TODO: retry condition */
  10370. }
  10371. }
  10372. if (error) {
  10373. mg_cry_internal(
  10374. conn,
  10375. "%s",
  10376. "Websocket pull failed; closing connection");
  10377. if (data != mem) {
  10378. mg_free(data);
  10379. }
  10380. break;
  10381. }
  10382. conn->data_len = conn->request_len;
  10383. } else {
  10384. mop = buf[0]; /* current mask and opcode, overwritten by
  10385. * memmove() */
  10386. /* Length of the message being read at the front of the
  10387. * queue. Cast to 31 bit is OK, since we limited
  10388. * data_len before. */
  10389. len = (size_t)data_len + header_len;
  10390. /* Copy the data payload into the data pointer for the
  10391. * callback. Cast to 31 bit is OK, since we
  10392. * limited data_len */
  10393. memcpy(data, buf + header_len, (size_t)data_len);
  10394. /* Move the queue forward len bytes */
  10395. memmove(buf, buf + len, body_len - len);
  10396. /* Mark the queue as advanced */
  10397. conn->data_len -= (int)len;
  10398. }
  10399. /* Apply mask if necessary */
  10400. if (mask_len > 0) {
  10401. for (i = 0; i < (size_t)data_len; i++) {
  10402. data[i] ^= mask[i & 3];
  10403. }
  10404. }
  10405. exit_by_callback = 0;
  10406. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10407. /* filter PONG messages */
  10408. DEBUG_TRACE("PONG from %s:%u",
  10409. conn->request_info.remote_addr,
  10410. conn->request_info.remote_port);
  10411. /* No unanwered PINGs left */
  10412. ping_count = 0;
  10413. } else if (enable_ping_pong
  10414. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10415. /* reply PING messages */
  10416. DEBUG_TRACE("Reply PING from %s:%u",
  10417. conn->request_info.remote_addr,
  10418. conn->request_info.remote_port);
  10419. ret = mg_websocket_write(conn,
  10420. MG_WEBSOCKET_OPCODE_PONG,
  10421. (char *)data,
  10422. (size_t)data_len);
  10423. if (ret <= 0) {
  10424. /* Error: send failed */
  10425. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10426. break;
  10427. }
  10428. } else {
  10429. /* Exit the loop if callback signals to exit (server side),
  10430. * or "connection close" opcode received (client side). */
  10431. if ((ws_data_handler != NULL)
  10432. && !ws_data_handler(conn,
  10433. mop,
  10434. (char *)data,
  10435. (size_t)data_len,
  10436. callback_data)) {
  10437. exit_by_callback = 1;
  10438. }
  10439. }
  10440. /* It a buffer has been allocated, free it again */
  10441. if (data != mem) {
  10442. mg_free(data);
  10443. }
  10444. if (exit_by_callback) {
  10445. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10446. conn->request_info.remote_addr,
  10447. conn->request_info.remote_port);
  10448. break;
  10449. }
  10450. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10451. /* Opcode == 8, connection close */
  10452. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10453. conn->request_info.remote_addr,
  10454. conn->request_info.remote_port);
  10455. break;
  10456. }
  10457. /* Not breaking the loop, process next websocket frame. */
  10458. } else {
  10459. /* Read from the socket into the next available location in the
  10460. * message queue. */
  10461. n = pull_inner(NULL,
  10462. conn,
  10463. conn->buf + conn->data_len,
  10464. conn->buf_size - conn->data_len,
  10465. timeout);
  10466. if (n <= -2) {
  10467. /* Error, no bytes read */
  10468. DEBUG_TRACE("PULL from %s:%u failed",
  10469. conn->request_info.remote_addr,
  10470. conn->request_info.remote_port);
  10471. break;
  10472. }
  10473. if (n > 0) {
  10474. conn->data_len += n;
  10475. /* Reset open PING count */
  10476. ping_count = 0;
  10477. } else {
  10478. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10479. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10480. /* Stop sending PING */
  10481. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10482. "- closing connection",
  10483. ping_count,
  10484. conn->request_info.remote_addr,
  10485. conn->request_info.remote_port);
  10486. break;
  10487. }
  10488. if (enable_ping_pong) {
  10489. /* Send Websocket PING message */
  10490. DEBUG_TRACE("PING to %s:%u",
  10491. conn->request_info.remote_addr,
  10492. conn->request_info.remote_port);
  10493. ret = mg_websocket_write(conn,
  10494. MG_WEBSOCKET_OPCODE_PING,
  10495. NULL,
  10496. 0);
  10497. if (ret <= 0) {
  10498. /* Error: send failed */
  10499. DEBUG_TRACE("Send PING failed (%i)", ret);
  10500. break;
  10501. }
  10502. ping_count++;
  10503. }
  10504. }
  10505. /* Timeout: should retry */
  10506. /* TODO: get timeout def */
  10507. }
  10508. }
  10509. }
  10510. /* Leave data processing loop */
  10511. mg_set_thread_name("worker");
  10512. conn->in_websocket_handling = 0;
  10513. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10514. conn->request_info.remote_addr,
  10515. conn->request_info.remote_port);
  10516. }
  10517. static int
  10518. mg_websocket_write_exec(struct mg_connection *conn,
  10519. int opcode,
  10520. const char *data,
  10521. size_t dataLen,
  10522. uint32_t masking_key)
  10523. {
  10524. unsigned char header[14];
  10525. size_t headerLen;
  10526. int retval;
  10527. #if defined(__GNUC__) || defined(__MINGW32__)
  10528. /* Disable spurious conversion warning for GCC */
  10529. #pragma GCC diagnostic push
  10530. #pragma GCC diagnostic ignored "-Wconversion"
  10531. #endif
  10532. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10533. #if defined(__GNUC__) || defined(__MINGW32__)
  10534. #pragma GCC diagnostic pop
  10535. #endif
  10536. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10537. if (dataLen < 126) {
  10538. /* inline 7-bit length field */
  10539. header[1] = (unsigned char)dataLen;
  10540. headerLen = 2;
  10541. } else if (dataLen <= 0xFFFF) {
  10542. /* 16-bit length field */
  10543. uint16_t len = htons((uint16_t)dataLen);
  10544. header[1] = 126;
  10545. memcpy(header + 2, &len, 2);
  10546. headerLen = 4;
  10547. } else {
  10548. /* 64-bit length field */
  10549. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10550. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10551. header[1] = 127;
  10552. memcpy(header + 2, &len1, 4);
  10553. memcpy(header + 6, &len2, 4);
  10554. headerLen = 10;
  10555. }
  10556. if (masking_key) {
  10557. /* add mask */
  10558. header[1] |= 0x80;
  10559. memcpy(header + headerLen, &masking_key, 4);
  10560. headerLen += 4;
  10561. }
  10562. /* Note that POSIX/Winsock's send() is threadsafe
  10563. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10564. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10565. * push(), although that is only a problem if the packet is large or
  10566. * outgoing buffer is full). */
  10567. /* TODO: Check if this lock should be moved to user land.
  10568. * Currently the server sets this lock for websockets, but
  10569. * not for any other connection. It must be set for every
  10570. * conn read/written by more than one thread, no matter if
  10571. * it is a websocket or regular connection. */
  10572. (void)mg_lock_connection(conn);
  10573. retval = mg_write(conn, header, headerLen);
  10574. if (retval != (int)headerLen) {
  10575. /* Did not send complete header */
  10576. retval = -1;
  10577. } else {
  10578. if (dataLen > 0) {
  10579. retval = mg_write(conn, data, dataLen);
  10580. }
  10581. /* if dataLen == 0, the header length (2) is returned */
  10582. }
  10583. /* TODO: Remove this unlock as well, when lock is removed. */
  10584. mg_unlock_connection(conn);
  10585. return retval;
  10586. }
  10587. int
  10588. mg_websocket_write(struct mg_connection *conn,
  10589. int opcode,
  10590. const char *data,
  10591. size_t dataLen)
  10592. {
  10593. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10594. }
  10595. static void
  10596. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10597. {
  10598. size_t i = 0;
  10599. i = 0;
  10600. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10601. /* Convert in 32 bit words, if data is 4 byte aligned */
  10602. while (i < (in_len - 3)) {
  10603. *(uint32_t *)(void *)(out + i) =
  10604. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10605. i += 4;
  10606. }
  10607. }
  10608. if (i != in_len) {
  10609. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10610. while (i < in_len) {
  10611. *(uint8_t *)(void *)(out + i) =
  10612. *(uint8_t *)(void *)(in + i)
  10613. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10614. i++;
  10615. }
  10616. }
  10617. }
  10618. int
  10619. mg_websocket_client_write(struct mg_connection *conn,
  10620. int opcode,
  10621. const char *data,
  10622. size_t dataLen)
  10623. {
  10624. int retval = -1;
  10625. char *masked_data =
  10626. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10627. uint32_t masking_key = 0;
  10628. if (masked_data == NULL) {
  10629. /* Return -1 in an error case */
  10630. mg_cry_internal(conn,
  10631. "%s",
  10632. "Cannot allocate buffer for masked websocket response: "
  10633. "Out of memory");
  10634. return -1;
  10635. }
  10636. do {
  10637. /* Get a masking key - but not 0 */
  10638. masking_key = (uint32_t)get_random();
  10639. } while (masking_key == 0);
  10640. mask_data(data, dataLen, masking_key, masked_data);
  10641. retval = mg_websocket_write_exec(
  10642. conn, opcode, masked_data, dataLen, masking_key);
  10643. mg_free(masked_data);
  10644. return retval;
  10645. }
  10646. static void
  10647. handle_websocket_request(struct mg_connection *conn,
  10648. const char *path,
  10649. int is_callback_resource,
  10650. struct mg_websocket_subprotocols *subprotocols,
  10651. mg_websocket_connect_handler ws_connect_handler,
  10652. mg_websocket_ready_handler ws_ready_handler,
  10653. mg_websocket_data_handler ws_data_handler,
  10654. mg_websocket_close_handler ws_close_handler,
  10655. void *cbData)
  10656. {
  10657. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10658. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10659. ptrdiff_t lua_websock = 0;
  10660. #if !defined(USE_LUA)
  10661. (void)path;
  10662. #endif
  10663. /* Step 1: Check websocket protocol version. */
  10664. /* Step 1.1: Check Sec-WebSocket-Key. */
  10665. if (!websock_key) {
  10666. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10667. * requires a Sec-WebSocket-Key header.
  10668. */
  10669. /* It could be the hixie draft version
  10670. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10671. */
  10672. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10673. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10674. char key3[8];
  10675. if ((key1 != NULL) && (key2 != NULL)) {
  10676. /* This version uses 8 byte body data in a GET request */
  10677. conn->content_len = 8;
  10678. if (8 == mg_read(conn, key3, 8)) {
  10679. /* This is the hixie version */
  10680. mg_send_http_error(conn,
  10681. 426,
  10682. "%s",
  10683. "Protocol upgrade to RFC 6455 required");
  10684. return;
  10685. }
  10686. }
  10687. /* This is an unknown version */
  10688. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10689. return;
  10690. }
  10691. /* Step 1.2: Check websocket protocol version. */
  10692. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10693. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10694. /* Reject wrong versions */
  10695. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10696. return;
  10697. }
  10698. /* Step 1.3: Could check for "Host", but we do not really nead this
  10699. * value for anything, so just ignore it. */
  10700. /* Step 2: If a callback is responsible, call it. */
  10701. if (is_callback_resource) {
  10702. /* Step 2.1 check and select subprotocol */
  10703. const char *protocols[64]; // max 64 headers
  10704. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10705. "Sec-WebSocket-Protocol",
  10706. protocols,
  10707. 64);
  10708. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10709. int cnt = 0;
  10710. int idx;
  10711. unsigned long len;
  10712. const char *sep, *curSubProtocol,
  10713. *acceptedWebSocketSubprotocol = NULL;
  10714. /* look for matching subprotocol */
  10715. do {
  10716. const char *protocol = protocols[cnt];
  10717. do {
  10718. sep = strchr(protocol, ',');
  10719. curSubProtocol = protocol;
  10720. len = sep ? (unsigned long)(sep - protocol)
  10721. : (unsigned long)strlen(protocol);
  10722. while (sep && isspace(*++sep))
  10723. ; // ignore leading whitespaces
  10724. protocol = sep;
  10725. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10726. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10727. && (strncmp(curSubProtocol,
  10728. subprotocols->subprotocols[idx],
  10729. len) == 0)) {
  10730. acceptedWebSocketSubprotocol =
  10731. subprotocols->subprotocols[idx];
  10732. break;
  10733. }
  10734. }
  10735. } while (sep && !acceptedWebSocketSubprotocol);
  10736. } while (++cnt < nbSubprotocolHeader
  10737. && !acceptedWebSocketSubprotocol);
  10738. conn->request_info.acceptedWebSocketSubprotocol =
  10739. acceptedWebSocketSubprotocol;
  10740. } else if (nbSubprotocolHeader > 0) {
  10741. /* keep legacy behavior */
  10742. const char *protocol = protocols[0];
  10743. /* The protocol is a comma separated list of names. */
  10744. /* The server must only return one value from this list. */
  10745. /* First check if it is a list or just a single value. */
  10746. const char *sep = strrchr(protocol, ',');
  10747. if (sep == NULL) {
  10748. /* Just a single protocol -> accept it. */
  10749. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10750. } else {
  10751. /* Multiple protocols -> accept the last one. */
  10752. /* This is just a quick fix if the client offers multiple
  10753. * protocols. The handler should have a list of accepted
  10754. * protocols on his own
  10755. * and use it to select one protocol among those the client
  10756. * has
  10757. * offered.
  10758. */
  10759. while (isspace(*++sep)) {
  10760. ; /* ignore leading whitespaces */
  10761. }
  10762. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10763. }
  10764. }
  10765. if ((ws_connect_handler != NULL)
  10766. && (ws_connect_handler(conn, cbData) != 0)) {
  10767. /* C callback has returned non-zero, do not proceed with
  10768. * handshake.
  10769. */
  10770. /* Note that C callbacks are no longer called when Lua is
  10771. * responsible, so C can no longer filter callbacks for Lua. */
  10772. return;
  10773. }
  10774. }
  10775. #if defined(USE_LUA)
  10776. /* Step 3: No callback. Check if Lua is responsible. */
  10777. else {
  10778. /* Step 3.1: Check if Lua is responsible. */
  10779. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10780. lua_websock = match_prefix(
  10781. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10782. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10783. path);
  10784. }
  10785. if (lua_websock) {
  10786. /* Step 3.2: Lua is responsible: call it. */
  10787. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10788. if (!conn->lua_websocket_state) {
  10789. /* Lua rejected the new client */
  10790. return;
  10791. }
  10792. }
  10793. }
  10794. #endif
  10795. /* Step 4: Check if there is a responsible websocket handler. */
  10796. if (!is_callback_resource && !lua_websock) {
  10797. /* There is no callback, and Lua is not responsible either. */
  10798. /* Reply with a 404 Not Found. We are still at a standard
  10799. * HTTP request here, before the websocket handshake, so
  10800. * we can still send standard HTTP error replies. */
  10801. mg_send_http_error(conn, 404, "%s", "Not found");
  10802. return;
  10803. }
  10804. /* Step 5: The websocket connection has been accepted */
  10805. if (!send_websocket_handshake(conn, websock_key)) {
  10806. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10807. return;
  10808. }
  10809. /* Step 6: Call the ready handler */
  10810. if (is_callback_resource) {
  10811. if (ws_ready_handler != NULL) {
  10812. ws_ready_handler(conn, cbData);
  10813. }
  10814. #if defined(USE_LUA)
  10815. } else if (lua_websock) {
  10816. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10817. /* the ready handler returned false */
  10818. return;
  10819. }
  10820. #endif
  10821. }
  10822. /* Step 7: Enter the read loop */
  10823. if (is_callback_resource) {
  10824. read_websocket(conn, ws_data_handler, cbData);
  10825. #if defined(USE_LUA)
  10826. } else if (lua_websock) {
  10827. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10828. #endif
  10829. }
  10830. /* Step 8: Call the close handler */
  10831. if (ws_close_handler) {
  10832. ws_close_handler(conn, cbData);
  10833. }
  10834. }
  10835. static int
  10836. is_websocket_protocol(const struct mg_connection *conn)
  10837. {
  10838. const char *upgrade, *connection;
  10839. /* A websocket protocoll has the following HTTP headers:
  10840. *
  10841. * Connection: Upgrade
  10842. * Upgrade: Websocket
  10843. */
  10844. upgrade = mg_get_header(conn, "Upgrade");
  10845. if (upgrade == NULL) {
  10846. return 0; /* fail early, don't waste time checking other header
  10847. * fields
  10848. */
  10849. }
  10850. if (!mg_strcasestr(upgrade, "websocket")) {
  10851. return 0;
  10852. }
  10853. connection = mg_get_header(conn, "Connection");
  10854. if (connection == NULL) {
  10855. return 0;
  10856. }
  10857. if (!mg_strcasestr(connection, "upgrade")) {
  10858. return 0;
  10859. }
  10860. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10861. * "Sec-WebSocket-Version" are also required.
  10862. * Don't check them here, since even an unsupported websocket protocol
  10863. * request still IS a websocket request (in contrast to a standard HTTP
  10864. * request). It will fail later in handle_websocket_request.
  10865. */
  10866. return 1;
  10867. }
  10868. #endif /* !USE_WEBSOCKET */
  10869. static int
  10870. isbyte(int n)
  10871. {
  10872. return (n >= 0) && (n <= 255);
  10873. }
  10874. static int
  10875. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10876. {
  10877. int n, a, b, c, d, slash = 32, len = 0;
  10878. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10879. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10880. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10881. && (slash < 33)) {
  10882. len = n;
  10883. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10884. | (uint32_t)d;
  10885. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10886. }
  10887. return len;
  10888. }
  10889. static int
  10890. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10891. {
  10892. int throttle = 0;
  10893. struct vec vec, val;
  10894. uint32_t net, mask;
  10895. char mult;
  10896. double v;
  10897. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10898. mult = ',';
  10899. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10900. || (v < 0) || ((lowercase(&mult) != 'k')
  10901. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10902. continue;
  10903. }
  10904. v *= (lowercase(&mult) == 'k')
  10905. ? 1024
  10906. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10907. if (vec.len == 1 && vec.ptr[0] == '*') {
  10908. throttle = (int)v;
  10909. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10910. if ((remote_ip & mask) == net) {
  10911. throttle = (int)v;
  10912. }
  10913. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10914. throttle = (int)v;
  10915. }
  10916. }
  10917. return throttle;
  10918. }
  10919. static uint32_t
  10920. get_remote_ip(const struct mg_connection *conn)
  10921. {
  10922. if (!conn) {
  10923. return 0;
  10924. }
  10925. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10926. }
  10927. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10928. #include "handle_form.inl"
  10929. #if defined(MG_LEGACY_INTERFACE)
  10930. /* Implement the deprecated mg_upload function by calling the new
  10931. * mg_handle_form_request function. While mg_upload could only handle
  10932. * HTML forms sent as POST request in multipart/form-data format
  10933. * containing only file input elements, mg_handle_form_request can
  10934. * handle all form input elements and all standard request methods. */
  10935. struct mg_upload_user_data {
  10936. struct mg_connection *conn;
  10937. const char *destination_dir;
  10938. int num_uploaded_files;
  10939. };
  10940. /* Helper function for deprecated mg_upload. */
  10941. static int
  10942. mg_upload_field_found(const char *key,
  10943. const char *filename,
  10944. char *path,
  10945. size_t pathlen,
  10946. void *user_data)
  10947. {
  10948. int truncated = 0;
  10949. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10950. (void)key;
  10951. if (!filename) {
  10952. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  10953. return FORM_FIELD_STORAGE_ABORT;
  10954. }
  10955. mg_snprintf(fud->conn,
  10956. &truncated,
  10957. path,
  10958. pathlen - 1,
  10959. "%s/%s",
  10960. fud->destination_dir,
  10961. filename);
  10962. if (truncated) {
  10963. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  10964. return FORM_FIELD_STORAGE_ABORT;
  10965. }
  10966. return FORM_FIELD_STORAGE_STORE;
  10967. }
  10968. /* Helper function for deprecated mg_upload. */
  10969. static int
  10970. mg_upload_field_get(const char *key,
  10971. const char *value,
  10972. size_t value_size,
  10973. void *user_data)
  10974. {
  10975. /* Function should never be called */
  10976. (void)key;
  10977. (void)value;
  10978. (void)value_size;
  10979. (void)user_data;
  10980. return 0;
  10981. }
  10982. /* Helper function for deprecated mg_upload. */
  10983. static int
  10984. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10985. {
  10986. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10987. (void)file_size;
  10988. fud->num_uploaded_files++;
  10989. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  10990. return 0;
  10991. }
  10992. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10993. int
  10994. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10995. {
  10996. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10997. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10998. mg_upload_field_get,
  10999. mg_upload_field_stored,
  11000. 0};
  11001. int ret;
  11002. fdh.user_data = (void *)&fud;
  11003. ret = mg_handle_form_request(conn, &fdh);
  11004. if (ret < 0) {
  11005. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11006. }
  11007. return fud.num_uploaded_files;
  11008. }
  11009. #endif
  11010. static int
  11011. get_first_ssl_listener_index(const struct mg_context *ctx)
  11012. {
  11013. unsigned int i;
  11014. int idx = -1;
  11015. if (ctx) {
  11016. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11017. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11018. }
  11019. }
  11020. return idx;
  11021. }
  11022. /* Return host (without port) */
  11023. /* Use mg_free to free the result */
  11024. static const char *
  11025. alloc_get_host(struct mg_connection *conn)
  11026. {
  11027. char buf[1025];
  11028. size_t buflen = sizeof(buf);
  11029. const char *host_header = get_header(conn->request_info.http_headers,
  11030. conn->request_info.num_headers,
  11031. "Host");
  11032. char *host;
  11033. if (host_header != NULL) {
  11034. char *pos;
  11035. /* Create a local copy of the "Host" header, since it might be
  11036. * modified here. */
  11037. mg_strlcpy(buf, host_header, buflen);
  11038. buf[buflen - 1] = '\0';
  11039. host = buf;
  11040. while (isspace(*host)) {
  11041. host++;
  11042. }
  11043. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11044. * is found. */
  11045. if (*host == '[') {
  11046. pos = strchr(host, ']');
  11047. if (!pos) {
  11048. /* Malformed hostname starts with '[', but no ']' found */
  11049. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11050. return NULL;
  11051. }
  11052. /* terminate after ']' */
  11053. pos[1] = 0;
  11054. } else {
  11055. /* Otherwise, a ':' separates hostname and port number */
  11056. pos = strchr(host, ':');
  11057. if (pos != NULL) {
  11058. *pos = '\0';
  11059. }
  11060. }
  11061. if (conn->ssl) {
  11062. /* This is a HTTPS connection, maybe we have a hostname
  11063. * from SNI (set in ssl_servername_callback). */
  11064. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11065. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11066. /* We are not using the default domain */
  11067. if (mg_strcasecmp(host, sslhost)) {
  11068. /* Mismatch between SNI domain and HTTP domain */
  11069. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11070. sslhost,
  11071. host);
  11072. return NULL;
  11073. }
  11074. }
  11075. DEBUG_TRACE("HTTPS Host: %s", host);
  11076. } else {
  11077. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11078. while (dom) {
  11079. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11080. /* Found matching domain */
  11081. DEBUG_TRACE("HTTP domain %s found",
  11082. dom->config[AUTHENTICATION_DOMAIN]);
  11083. /* TODO: Check if this is a HTTP or HTTPS domain */
  11084. conn->dom_ctx = dom;
  11085. break;
  11086. }
  11087. dom = dom->next;
  11088. }
  11089. DEBUG_TRACE("HTTP Host: %s", host);
  11090. }
  11091. } else {
  11092. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11093. host = buf;
  11094. DEBUG_TRACE("IP: %s", host);
  11095. }
  11096. return mg_strdup_ctx(host, conn->phys_ctx);
  11097. }
  11098. static void
  11099. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11100. {
  11101. char target_url[MG_BUF_LEN];
  11102. int truncated = 0;
  11103. conn->must_close = 1;
  11104. /* Send host, port, uri and (if it exists) ?query_string */
  11105. if (conn->host) {
  11106. /* Use "308 Permanent Redirect" */
  11107. int redirect_code = 308;
  11108. /* Create target URL */
  11109. mg_snprintf(
  11110. conn,
  11111. &truncated,
  11112. target_url,
  11113. sizeof(target_url),
  11114. "Location: https://%s:%d%s%s%s",
  11115. conn->host,
  11116. #if defined(USE_IPV6)
  11117. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11118. == AF_INET6)
  11119. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11120. .lsa.sin6.sin6_port)
  11121. :
  11122. #endif
  11123. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11124. .lsa.sin.sin_port),
  11125. conn->request_info.local_uri,
  11126. (conn->request_info.query_string == NULL) ? "" : "?",
  11127. (conn->request_info.query_string == NULL)
  11128. ? ""
  11129. : conn->request_info.query_string);
  11130. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11131. * is used as buffer size) */
  11132. if (truncated) {
  11133. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11134. return;
  11135. }
  11136. /* Use redirect helper function */
  11137. mg_send_http_redirect(conn, target_url, redirect_code);
  11138. }
  11139. }
  11140. static void
  11141. handler_info_acquire(struct mg_handler_info *handler_info)
  11142. {
  11143. pthread_mutex_lock(&handler_info->refcount_mutex);
  11144. handler_info->refcount++;
  11145. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11146. }
  11147. static void
  11148. handler_info_release(struct mg_handler_info *handler_info)
  11149. {
  11150. pthread_mutex_lock(&handler_info->refcount_mutex);
  11151. handler_info->refcount--;
  11152. pthread_cond_signal(&handler_info->refcount_cond);
  11153. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11154. }
  11155. static void
  11156. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11157. {
  11158. pthread_mutex_lock(&handler_info->refcount_mutex);
  11159. while (handler_info->refcount) {
  11160. pthread_cond_wait(&handler_info->refcount_cond,
  11161. &handler_info->refcount_mutex);
  11162. }
  11163. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11164. }
  11165. static void
  11166. mg_set_handler_type(struct mg_context *phys_ctx,
  11167. struct mg_domain_context *dom_ctx,
  11168. const char *uri,
  11169. int handler_type,
  11170. int is_delete_request,
  11171. mg_request_handler handler,
  11172. struct mg_websocket_subprotocols *subprotocols,
  11173. mg_websocket_connect_handler connect_handler,
  11174. mg_websocket_ready_handler ready_handler,
  11175. mg_websocket_data_handler data_handler,
  11176. mg_websocket_close_handler close_handler,
  11177. mg_authorization_handler auth_handler,
  11178. void *cbdata)
  11179. {
  11180. struct mg_handler_info *tmp_rh, **lastref;
  11181. size_t urilen = strlen(uri);
  11182. if (handler_type == WEBSOCKET_HANDLER) {
  11183. DEBUG_ASSERT(handler == NULL);
  11184. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11185. || ready_handler != NULL
  11186. || data_handler != NULL
  11187. || close_handler != NULL);
  11188. DEBUG_ASSERT(auth_handler == NULL);
  11189. if (handler != NULL) {
  11190. return;
  11191. }
  11192. if (!is_delete_request && (connect_handler == NULL)
  11193. && (ready_handler == NULL) && (data_handler == NULL)
  11194. && (close_handler == NULL)) {
  11195. return;
  11196. }
  11197. if (auth_handler != NULL) {
  11198. return;
  11199. }
  11200. } else if (handler_type == REQUEST_HANDLER) {
  11201. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11202. && data_handler == NULL
  11203. && close_handler == NULL);
  11204. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11205. DEBUG_ASSERT(auth_handler == NULL);
  11206. if ((connect_handler != NULL) || (ready_handler != NULL)
  11207. || (data_handler != NULL) || (close_handler != NULL)) {
  11208. return;
  11209. }
  11210. if (!is_delete_request && (handler == NULL)) {
  11211. return;
  11212. }
  11213. if (auth_handler != NULL) {
  11214. return;
  11215. }
  11216. } else { /* AUTH_HANDLER */
  11217. DEBUG_ASSERT(handler == NULL);
  11218. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11219. && data_handler == NULL
  11220. && close_handler == NULL);
  11221. DEBUG_ASSERT(auth_handler != NULL);
  11222. if (handler != NULL) {
  11223. return;
  11224. }
  11225. if ((connect_handler != NULL) || (ready_handler != NULL)
  11226. || (data_handler != NULL) || (close_handler != NULL)) {
  11227. return;
  11228. }
  11229. if (!is_delete_request && (auth_handler == NULL)) {
  11230. return;
  11231. }
  11232. }
  11233. if (!phys_ctx || !dom_ctx) {
  11234. return;
  11235. }
  11236. mg_lock_context(phys_ctx);
  11237. /* first try to find an existing handler */
  11238. lastref = &(dom_ctx->handlers);
  11239. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11240. if (tmp_rh->handler_type == handler_type) {
  11241. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11242. if (!is_delete_request) {
  11243. /* update existing handler */
  11244. if (handler_type == REQUEST_HANDLER) {
  11245. /* Wait for end of use before updating */
  11246. handler_info_wait_unused(tmp_rh);
  11247. /* Ok, the handler is no more use -> Update it */
  11248. tmp_rh->handler = handler;
  11249. } else if (handler_type == WEBSOCKET_HANDLER) {
  11250. tmp_rh->subprotocols = subprotocols;
  11251. tmp_rh->connect_handler = connect_handler;
  11252. tmp_rh->ready_handler = ready_handler;
  11253. tmp_rh->data_handler = data_handler;
  11254. tmp_rh->close_handler = close_handler;
  11255. } else { /* AUTH_HANDLER */
  11256. tmp_rh->auth_handler = auth_handler;
  11257. }
  11258. tmp_rh->cbdata = cbdata;
  11259. } else {
  11260. /* remove existing handler */
  11261. if (handler_type == REQUEST_HANDLER) {
  11262. /* Wait for end of use before removing */
  11263. handler_info_wait_unused(tmp_rh);
  11264. /* Ok, the handler is no more used -> Destroy resources
  11265. */
  11266. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11267. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11268. }
  11269. *lastref = tmp_rh->next;
  11270. mg_free(tmp_rh->uri);
  11271. mg_free(tmp_rh);
  11272. }
  11273. mg_unlock_context(phys_ctx);
  11274. return;
  11275. }
  11276. }
  11277. lastref = &(tmp_rh->next);
  11278. }
  11279. if (is_delete_request) {
  11280. /* no handler to set, this was a remove request to a non-existing
  11281. * handler */
  11282. mg_unlock_context(phys_ctx);
  11283. return;
  11284. }
  11285. tmp_rh =
  11286. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11287. 1,
  11288. phys_ctx);
  11289. if (tmp_rh == NULL) {
  11290. mg_unlock_context(phys_ctx);
  11291. mg_cry_internal(fc(phys_ctx),
  11292. "%s",
  11293. "Cannot create new request handler struct, OOM");
  11294. return;
  11295. }
  11296. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11297. if (!tmp_rh->uri) {
  11298. mg_unlock_context(phys_ctx);
  11299. mg_free(tmp_rh);
  11300. mg_cry_internal(fc(phys_ctx),
  11301. "%s",
  11302. "Cannot create new request handler struct, OOM");
  11303. return;
  11304. }
  11305. tmp_rh->uri_len = urilen;
  11306. if (handler_type == REQUEST_HANDLER) {
  11307. /* Init refcount mutex and condition */
  11308. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11309. mg_unlock_context(phys_ctx);
  11310. mg_free(tmp_rh);
  11311. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11312. return;
  11313. }
  11314. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11315. mg_unlock_context(phys_ctx);
  11316. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11317. mg_free(tmp_rh);
  11318. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11319. return;
  11320. }
  11321. tmp_rh->refcount = 0;
  11322. tmp_rh->handler = handler;
  11323. } else if (handler_type == WEBSOCKET_HANDLER) {
  11324. tmp_rh->subprotocols = subprotocols;
  11325. tmp_rh->connect_handler = connect_handler;
  11326. tmp_rh->ready_handler = ready_handler;
  11327. tmp_rh->data_handler = data_handler;
  11328. tmp_rh->close_handler = close_handler;
  11329. } else { /* AUTH_HANDLER */
  11330. tmp_rh->auth_handler = auth_handler;
  11331. }
  11332. tmp_rh->cbdata = cbdata;
  11333. tmp_rh->handler_type = handler_type;
  11334. tmp_rh->next = NULL;
  11335. *lastref = tmp_rh;
  11336. mg_unlock_context(phys_ctx);
  11337. }
  11338. void
  11339. mg_set_request_handler(struct mg_context *ctx,
  11340. const char *uri,
  11341. mg_request_handler handler,
  11342. void *cbdata)
  11343. {
  11344. mg_set_handler_type(ctx,
  11345. &(ctx->dd),
  11346. uri,
  11347. REQUEST_HANDLER,
  11348. handler == NULL,
  11349. handler,
  11350. NULL,
  11351. NULL,
  11352. NULL,
  11353. NULL,
  11354. NULL,
  11355. NULL,
  11356. cbdata);
  11357. }
  11358. void
  11359. mg_set_websocket_handler(struct mg_context *ctx,
  11360. const char *uri,
  11361. mg_websocket_connect_handler connect_handler,
  11362. mg_websocket_ready_handler ready_handler,
  11363. mg_websocket_data_handler data_handler,
  11364. mg_websocket_close_handler close_handler,
  11365. void *cbdata)
  11366. {
  11367. mg_set_websocket_handler_with_subprotocols(ctx,
  11368. uri,
  11369. NULL,
  11370. connect_handler,
  11371. ready_handler,
  11372. data_handler,
  11373. close_handler,
  11374. cbdata);
  11375. }
  11376. void
  11377. mg_set_websocket_handler_with_subprotocols(
  11378. struct mg_context *ctx,
  11379. const char *uri,
  11380. struct mg_websocket_subprotocols *subprotocols,
  11381. mg_websocket_connect_handler connect_handler,
  11382. mg_websocket_ready_handler ready_handler,
  11383. mg_websocket_data_handler data_handler,
  11384. mg_websocket_close_handler close_handler,
  11385. void *cbdata)
  11386. {
  11387. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11388. && (data_handler == NULL)
  11389. && (close_handler == NULL);
  11390. mg_set_handler_type(ctx,
  11391. &(ctx->dd),
  11392. uri,
  11393. WEBSOCKET_HANDLER,
  11394. is_delete_request,
  11395. NULL,
  11396. subprotocols,
  11397. connect_handler,
  11398. ready_handler,
  11399. data_handler,
  11400. close_handler,
  11401. NULL,
  11402. cbdata);
  11403. }
  11404. void
  11405. mg_set_auth_handler(struct mg_context *ctx,
  11406. const char *uri,
  11407. mg_request_handler handler,
  11408. void *cbdata)
  11409. {
  11410. mg_set_handler_type(ctx,
  11411. &(ctx->dd),
  11412. uri,
  11413. AUTH_HANDLER,
  11414. handler == NULL,
  11415. NULL,
  11416. NULL,
  11417. NULL,
  11418. NULL,
  11419. NULL,
  11420. NULL,
  11421. handler,
  11422. cbdata);
  11423. }
  11424. static int
  11425. get_request_handler(struct mg_connection *conn,
  11426. int handler_type,
  11427. mg_request_handler *handler,
  11428. struct mg_websocket_subprotocols **subprotocols,
  11429. mg_websocket_connect_handler *connect_handler,
  11430. mg_websocket_ready_handler *ready_handler,
  11431. mg_websocket_data_handler *data_handler,
  11432. mg_websocket_close_handler *close_handler,
  11433. mg_authorization_handler *auth_handler,
  11434. void **cbdata,
  11435. struct mg_handler_info **handler_info)
  11436. {
  11437. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11438. if (request_info) {
  11439. const char *uri = request_info->local_uri;
  11440. size_t urilen = strlen(uri);
  11441. struct mg_handler_info *tmp_rh;
  11442. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11443. return 0;
  11444. }
  11445. mg_lock_context(conn->phys_ctx);
  11446. /* first try for an exact match */
  11447. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11448. tmp_rh = tmp_rh->next) {
  11449. if (tmp_rh->handler_type == handler_type) {
  11450. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11451. if (handler_type == WEBSOCKET_HANDLER) {
  11452. *subprotocols = tmp_rh->subprotocols;
  11453. *connect_handler = tmp_rh->connect_handler;
  11454. *ready_handler = tmp_rh->ready_handler;
  11455. *data_handler = tmp_rh->data_handler;
  11456. *close_handler = tmp_rh->close_handler;
  11457. } else if (handler_type == REQUEST_HANDLER) {
  11458. *handler = tmp_rh->handler;
  11459. /* Acquire handler and give it back */
  11460. handler_info_acquire(tmp_rh);
  11461. *handler_info = tmp_rh;
  11462. } else { /* AUTH_HANDLER */
  11463. *auth_handler = tmp_rh->auth_handler;
  11464. }
  11465. *cbdata = tmp_rh->cbdata;
  11466. mg_unlock_context(conn->phys_ctx);
  11467. return 1;
  11468. }
  11469. }
  11470. }
  11471. /* next try for a partial match, we will accept uri/something */
  11472. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11473. tmp_rh = tmp_rh->next) {
  11474. if (tmp_rh->handler_type == handler_type) {
  11475. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11476. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11477. if (handler_type == WEBSOCKET_HANDLER) {
  11478. *subprotocols = tmp_rh->subprotocols;
  11479. *connect_handler = tmp_rh->connect_handler;
  11480. *ready_handler = tmp_rh->ready_handler;
  11481. *data_handler = tmp_rh->data_handler;
  11482. *close_handler = tmp_rh->close_handler;
  11483. } else if (handler_type == REQUEST_HANDLER) {
  11484. *handler = tmp_rh->handler;
  11485. /* Acquire handler and give it back */
  11486. handler_info_acquire(tmp_rh);
  11487. *handler_info = tmp_rh;
  11488. } else { /* AUTH_HANDLER */
  11489. *auth_handler = tmp_rh->auth_handler;
  11490. }
  11491. *cbdata = tmp_rh->cbdata;
  11492. mg_unlock_context(conn->phys_ctx);
  11493. return 1;
  11494. }
  11495. }
  11496. }
  11497. /* finally try for pattern match */
  11498. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11499. tmp_rh = tmp_rh->next) {
  11500. if (tmp_rh->handler_type == handler_type) {
  11501. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11502. if (handler_type == WEBSOCKET_HANDLER) {
  11503. *subprotocols = tmp_rh->subprotocols;
  11504. *connect_handler = tmp_rh->connect_handler;
  11505. *ready_handler = tmp_rh->ready_handler;
  11506. *data_handler = tmp_rh->data_handler;
  11507. *close_handler = tmp_rh->close_handler;
  11508. } else if (handler_type == REQUEST_HANDLER) {
  11509. *handler = tmp_rh->handler;
  11510. /* Acquire handler and give it back */
  11511. handler_info_acquire(tmp_rh);
  11512. *handler_info = tmp_rh;
  11513. } else { /* AUTH_HANDLER */
  11514. *auth_handler = tmp_rh->auth_handler;
  11515. }
  11516. *cbdata = tmp_rh->cbdata;
  11517. mg_unlock_context(conn->phys_ctx);
  11518. return 1;
  11519. }
  11520. }
  11521. }
  11522. mg_unlock_context(conn->phys_ctx);
  11523. }
  11524. return 0; /* none found */
  11525. }
  11526. /* Check if the script file is in a path, allowed for script files.
  11527. * This can be used if uploading files is possible not only for the server
  11528. * admin, and the upload mechanism does not check the file extension.
  11529. */
  11530. static int
  11531. is_in_script_path(const struct mg_connection *conn, const char *path)
  11532. {
  11533. /* TODO (Feature): Add config value for allowed script path.
  11534. * Default: All allowed. */
  11535. (void)conn;
  11536. (void)path;
  11537. return 1;
  11538. }
  11539. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11540. static int
  11541. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11542. void *cbdata)
  11543. {
  11544. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11545. if (pcallbacks->websocket_connect) {
  11546. return pcallbacks->websocket_connect(conn);
  11547. }
  11548. /* No handler set - assume "OK" */
  11549. return 0;
  11550. }
  11551. static void
  11552. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11553. {
  11554. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11555. if (pcallbacks->websocket_ready) {
  11556. pcallbacks->websocket_ready(conn);
  11557. }
  11558. }
  11559. static int
  11560. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11561. int bits,
  11562. char *data,
  11563. size_t len,
  11564. void *cbdata)
  11565. {
  11566. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11567. if (pcallbacks->websocket_data) {
  11568. return pcallbacks->websocket_data(conn, bits, data, len);
  11569. }
  11570. /* No handler set - assume "OK" */
  11571. return 1;
  11572. }
  11573. #endif
  11574. /* This is the heart of the Civetweb's logic.
  11575. * This function is called when the request is read, parsed and validated,
  11576. * and Civetweb must decide what action to take: serve a file, or
  11577. * a directory, or call embedded function, etcetera. */
  11578. static void
  11579. handle_request(struct mg_connection *conn)
  11580. {
  11581. struct mg_request_info *ri = &conn->request_info;
  11582. char path[PATH_MAX];
  11583. int uri_len, ssl_index;
  11584. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11585. is_put_or_delete_request = 0, is_callback_resource = 0;
  11586. int i;
  11587. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11588. mg_request_handler callback_handler = NULL;
  11589. struct mg_handler_info *handler_info = NULL;
  11590. struct mg_websocket_subprotocols *subprotocols;
  11591. mg_websocket_connect_handler ws_connect_handler = NULL;
  11592. mg_websocket_ready_handler ws_ready_handler = NULL;
  11593. mg_websocket_data_handler ws_data_handler = NULL;
  11594. mg_websocket_close_handler ws_close_handler = NULL;
  11595. void *callback_data = NULL;
  11596. mg_authorization_handler auth_handler = NULL;
  11597. void *auth_callback_data = NULL;
  11598. int handler_type;
  11599. time_t curtime = time(NULL);
  11600. char date[64];
  11601. path[0] = 0;
  11602. /* 1. get the request url */
  11603. /* 1.1. split into url and query string */
  11604. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11605. != NULL) {
  11606. *((char *)conn->request_info.query_string++) = '\0';
  11607. }
  11608. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11609. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11610. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11611. if (ssl_index >= 0) {
  11612. redirect_to_https_port(conn, ssl_index);
  11613. } else {
  11614. /* A http to https forward port has been specified,
  11615. * but no https port to forward to. */
  11616. mg_send_http_error(conn,
  11617. 503,
  11618. "%s",
  11619. "Error: SSL forward not configured properly");
  11620. mg_cry_internal(conn,
  11621. "%s",
  11622. "Can not redirect to SSL, no SSL port available");
  11623. }
  11624. return;
  11625. }
  11626. uri_len = (int)strlen(ri->local_uri);
  11627. /* 1.3. decode url (if config says so) */
  11628. if (should_decode_url(conn)) {
  11629. mg_url_decode(
  11630. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11631. }
  11632. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11633. * not possible */
  11634. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11635. /* step 1. completed, the url is known now */
  11636. uri_len = (int)strlen(ri->local_uri);
  11637. DEBUG_TRACE("URL: %s", ri->local_uri);
  11638. /* 2. if this ip has limited speed, set it for this connection */
  11639. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11640. get_remote_ip(conn),
  11641. ri->local_uri);
  11642. /* 3. call a "handle everything" callback, if registered */
  11643. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11644. /* Note that since V1.7 the "begin_request" function is called
  11645. * before an authorization check. If an authorization check is
  11646. * required, use a request_handler instead. */
  11647. i = conn->phys_ctx->callbacks.begin_request(conn);
  11648. if (i > 0) {
  11649. /* callback already processed the request. Store the
  11650. return value as a status code for the access log. */
  11651. conn->status_code = i;
  11652. discard_unread_request_data(conn);
  11653. return;
  11654. } else if (i == 0) {
  11655. /* civetweb should process the request */
  11656. } else {
  11657. /* unspecified - may change with the next version */
  11658. return;
  11659. }
  11660. }
  11661. /* request not yet handled by a handler or redirect, so the request
  11662. * is processed here */
  11663. /* 4. Check for CORS preflight requests and handle them (if configured).
  11664. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11665. */
  11666. if (!strcmp(ri->request_method, "OPTIONS")) {
  11667. /* Send a response to CORS preflights only if
  11668. * access_control_allow_methods is not NULL and not an empty string.
  11669. * In this case, scripts can still handle CORS. */
  11670. const char *cors_meth_cfg =
  11671. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11672. const char *cors_orig_cfg =
  11673. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11674. const char *cors_origin =
  11675. get_header(ri->http_headers, ri->num_headers, "Origin");
  11676. const char *cors_acrm = get_header(ri->http_headers,
  11677. ri->num_headers,
  11678. "Access-Control-Request-Method");
  11679. /* Todo: check if cors_origin is in cors_orig_cfg.
  11680. * Or, let the client check this. */
  11681. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11682. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11683. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11684. /* This is a valid CORS preflight, and the server is configured
  11685. * to
  11686. * handle it automatically. */
  11687. const char *cors_acrh =
  11688. get_header(ri->http_headers,
  11689. ri->num_headers,
  11690. "Access-Control-Request-Headers");
  11691. gmt_time_string(date, sizeof(date), &curtime);
  11692. mg_printf(conn,
  11693. "HTTP/1.1 200 OK\r\n"
  11694. "Date: %s\r\n"
  11695. "Access-Control-Allow-Origin: %s\r\n"
  11696. "Access-Control-Allow-Methods: %s\r\n"
  11697. "Content-Length: 0\r\n"
  11698. "Connection: %s\r\n",
  11699. date,
  11700. cors_orig_cfg,
  11701. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11702. suggest_connection_header(conn));
  11703. if (cors_acrh != NULL) {
  11704. /* CORS request is asking for additional headers */
  11705. const char *cors_hdr_cfg =
  11706. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11707. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11708. /* Allow only if access_control_allow_headers is
  11709. * not NULL and not an empty string. If this
  11710. * configuration is set to *, allow everything.
  11711. * Otherwise this configuration must be a list
  11712. * of allowed HTTP header names. */
  11713. mg_printf(conn,
  11714. "Access-Control-Allow-Headers: %s\r\n",
  11715. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11716. : cors_hdr_cfg));
  11717. }
  11718. }
  11719. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11720. mg_printf(conn, "\r\n");
  11721. return;
  11722. }
  11723. }
  11724. /* 5. interpret the url to find out how the request must be handled
  11725. */
  11726. /* 5.1. first test, if the request targets the regular http(s)://
  11727. * protocol namespace or the websocket ws(s):// protocol namespace.
  11728. */
  11729. is_websocket_request = is_websocket_protocol(conn);
  11730. #if defined(USE_WEBSOCKET)
  11731. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11732. #else
  11733. handler_type = REQUEST_HANDLER;
  11734. #endif /* defined(USE_WEBSOCKET) */
  11735. /* 5.2. check if the request will be handled by a callback */
  11736. if (get_request_handler(conn,
  11737. handler_type,
  11738. &callback_handler,
  11739. &subprotocols,
  11740. &ws_connect_handler,
  11741. &ws_ready_handler,
  11742. &ws_data_handler,
  11743. &ws_close_handler,
  11744. NULL,
  11745. &callback_data,
  11746. &handler_info)) {
  11747. /* 5.2.1. A callback will handle this request. All requests
  11748. * handled
  11749. * by a callback have to be considered as requests to a script
  11750. * resource. */
  11751. is_callback_resource = 1;
  11752. is_script_resource = 1;
  11753. is_put_or_delete_request = is_put_or_delete_method(conn);
  11754. } else {
  11755. no_callback_resource:
  11756. /* 5.2.2. No callback is responsible for this request. The URI
  11757. * addresses a file based resource (static content or Lua/cgi
  11758. * scripts in the file system). */
  11759. is_callback_resource = 0;
  11760. interpret_uri(conn,
  11761. path,
  11762. sizeof(path),
  11763. &file.stat,
  11764. &is_found,
  11765. &is_script_resource,
  11766. &is_websocket_request,
  11767. &is_put_or_delete_request);
  11768. }
  11769. /* 6. authorization check */
  11770. /* 6.1. a custom authorization handler is installed */
  11771. if (get_request_handler(conn,
  11772. AUTH_HANDLER,
  11773. NULL,
  11774. NULL,
  11775. NULL,
  11776. NULL,
  11777. NULL,
  11778. NULL,
  11779. &auth_handler,
  11780. &auth_callback_data,
  11781. NULL)) {
  11782. if (!auth_handler(conn, auth_callback_data)) {
  11783. return;
  11784. }
  11785. } else if (is_put_or_delete_request && !is_script_resource
  11786. && !is_callback_resource) {
  11787. /* 6.2. this request is a PUT/DELETE to a real file */
  11788. /* 6.2.1. thus, the server must have real files */
  11789. #if defined(NO_FILES)
  11790. if (1) {
  11791. #else
  11792. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11793. #endif
  11794. /* This server does not have any real files, thus the
  11795. * PUT/DELETE methods are not valid. */
  11796. mg_send_http_error(conn,
  11797. 405,
  11798. "%s method not allowed",
  11799. conn->request_info.request_method);
  11800. return;
  11801. }
  11802. #if !defined(NO_FILES)
  11803. /* 6.2.2. Check if put authorization for static files is
  11804. * available.
  11805. */
  11806. if (!is_authorized_for_put(conn)) {
  11807. send_authorization_request(conn, NULL);
  11808. return;
  11809. }
  11810. #endif
  11811. } else {
  11812. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11813. * or it is a PUT or DELETE request to a resource that does not
  11814. * correspond to a file. Check authorization. */
  11815. if (!check_authorization(conn, path)) {
  11816. send_authorization_request(conn, NULL);
  11817. return;
  11818. }
  11819. }
  11820. /* request is authorized or does not need authorization */
  11821. /* 7. check if there are request handlers for this uri */
  11822. if (is_callback_resource) {
  11823. if (!is_websocket_request) {
  11824. i = callback_handler(conn, callback_data);
  11825. /* Callback handler will not be used anymore. Release it */
  11826. handler_info_release(handler_info);
  11827. if (i > 0) {
  11828. /* Do nothing, callback has served the request. Store
  11829. * then return value as status code for the log and discard
  11830. * all data from the client not used by the callback. */
  11831. conn->status_code = i;
  11832. discard_unread_request_data(conn);
  11833. } else {
  11834. /* The handler did NOT handle the request. */
  11835. /* Some proper reactions would be:
  11836. * a) close the connections without sending anything
  11837. * b) send a 404 not found
  11838. * c) try if there is a file matching the URI
  11839. * It would be possible to do a, b or c in the callback
  11840. * implementation, and return 1 - we cannot do anything
  11841. * here, that is not possible in the callback.
  11842. *
  11843. * TODO: What would be the best reaction here?
  11844. * (Note: The reaction may change, if there is a better
  11845. *idea.)
  11846. */
  11847. /* For the moment, use option c: We look for a proper file,
  11848. * but since a file request is not always a script resource,
  11849. * the authorization check might be different. */
  11850. interpret_uri(conn,
  11851. path,
  11852. sizeof(path),
  11853. &file.stat,
  11854. &is_found,
  11855. &is_script_resource,
  11856. &is_websocket_request,
  11857. &is_put_or_delete_request);
  11858. callback_handler = NULL;
  11859. /* Here we are at a dead end:
  11860. * According to URI matching, a callback should be
  11861. * responsible for handling the request,
  11862. * we called it, but the callback declared itself
  11863. * not responsible.
  11864. * We use a goto here, to get out of this dead end,
  11865. * and continue with the default handling.
  11866. * A goto here is simpler and better to understand
  11867. * than some curious loop. */
  11868. goto no_callback_resource;
  11869. }
  11870. } else {
  11871. #if defined(USE_WEBSOCKET)
  11872. handle_websocket_request(conn,
  11873. path,
  11874. is_callback_resource,
  11875. subprotocols,
  11876. ws_connect_handler,
  11877. ws_ready_handler,
  11878. ws_data_handler,
  11879. ws_close_handler,
  11880. callback_data);
  11881. #endif
  11882. }
  11883. return;
  11884. }
  11885. /* 8. handle websocket requests */
  11886. #if defined(USE_WEBSOCKET)
  11887. if (is_websocket_request) {
  11888. if (is_script_resource) {
  11889. if (is_in_script_path(conn, path)) {
  11890. /* Websocket Lua script */
  11891. handle_websocket_request(conn,
  11892. path,
  11893. 0 /* Lua Script */,
  11894. NULL,
  11895. NULL,
  11896. NULL,
  11897. NULL,
  11898. NULL,
  11899. conn->phys_ctx->user_data);
  11900. } else {
  11901. /* Script was in an illegal path */
  11902. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11903. }
  11904. } else {
  11905. #if defined(MG_LEGACY_INTERFACE)
  11906. handle_websocket_request(
  11907. conn,
  11908. path,
  11909. !is_script_resource /* could be deprecated global callback */,
  11910. NULL,
  11911. deprecated_websocket_connect_wrapper,
  11912. deprecated_websocket_ready_wrapper,
  11913. deprecated_websocket_data_wrapper,
  11914. NULL,
  11915. conn->phys_ctx->user_data);
  11916. #else
  11917. mg_send_http_error(conn, 404, "%s", "Not found");
  11918. #endif
  11919. }
  11920. return;
  11921. } else
  11922. #endif
  11923. #if defined(NO_FILES)
  11924. /* 9a. In case the server uses only callbacks, this uri is
  11925. * unknown.
  11926. * Then, all request handling ends here. */
  11927. mg_send_http_error(conn, 404, "%s", "Not Found");
  11928. #else
  11929. /* 9b. This request is either for a static file or resource handled
  11930. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11931. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11932. mg_send_http_error(conn, 404, "%s", "Not Found");
  11933. return;
  11934. }
  11935. /* 10. Request is handled by a script */
  11936. if (is_script_resource) {
  11937. handle_file_based_request(conn, path, &file);
  11938. return;
  11939. }
  11940. /* 11. Handle put/delete/mkcol requests */
  11941. if (is_put_or_delete_request) {
  11942. /* 11.1. PUT method */
  11943. if (!strcmp(ri->request_method, "PUT")) {
  11944. put_file(conn, path);
  11945. return;
  11946. }
  11947. /* 11.2. DELETE method */
  11948. if (!strcmp(ri->request_method, "DELETE")) {
  11949. delete_file(conn, path);
  11950. return;
  11951. }
  11952. /* 11.3. MKCOL method */
  11953. if (!strcmp(ri->request_method, "MKCOL")) {
  11954. mkcol(conn, path);
  11955. return;
  11956. }
  11957. /* 11.4. PATCH method
  11958. * This method is not supported for static resources,
  11959. * only for scripts (Lua, CGI) and callbacks. */
  11960. mg_send_http_error(conn,
  11961. 405,
  11962. "%s method not allowed",
  11963. conn->request_info.request_method);
  11964. return;
  11965. }
  11966. /* 11. File does not exist, or it was configured that it should be
  11967. * hidden */
  11968. if (!is_found || (must_hide_file(conn, path))) {
  11969. mg_send_http_error(conn, 404, "%s", "Not found");
  11970. return;
  11971. }
  11972. /* 12. Directory uris should end with a slash */
  11973. if (file.stat.is_directory && (uri_len > 0)
  11974. && (ri->local_uri[uri_len - 1] != '/')) {
  11975. gmt_time_string(date, sizeof(date), &curtime);
  11976. mg_printf(conn,
  11977. "HTTP/1.1 301 Moved Permanently\r\n"
  11978. "Location: %s/\r\n"
  11979. "Date: %s\r\n"
  11980. /* "Cache-Control: private\r\n" (= default) */
  11981. "Content-Length: 0\r\n"
  11982. "Connection: %s\r\n",
  11983. ri->request_uri,
  11984. date,
  11985. suggest_connection_header(conn));
  11986. send_additional_header(conn);
  11987. mg_printf(conn, "\r\n");
  11988. return;
  11989. }
  11990. /* 13. Handle other methods than GET/HEAD */
  11991. /* 13.1. Handle PROPFIND */
  11992. if (!strcmp(ri->request_method, "PROPFIND")) {
  11993. handle_propfind(conn, path, &file.stat);
  11994. return;
  11995. }
  11996. /* 13.2. Handle OPTIONS for files */
  11997. if (!strcmp(ri->request_method, "OPTIONS")) {
  11998. /* This standard handler is only used for real files.
  11999. * Scripts should support the OPTIONS method themselves, to allow a
  12000. * maximum flexibility.
  12001. * Lua and CGI scripts may fully support CORS this way (including
  12002. * preflights). */
  12003. send_options(conn);
  12004. return;
  12005. }
  12006. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12007. if ((0 != strcmp(ri->request_method, "GET"))
  12008. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12009. mg_send_http_error(conn,
  12010. 405,
  12011. "%s method not allowed",
  12012. conn->request_info.request_method);
  12013. return;
  12014. }
  12015. /* 14. directories */
  12016. if (file.stat.is_directory) {
  12017. /* Substitute files have already been handled above. */
  12018. /* Here we can either generate and send a directory listing,
  12019. * or send an "access denied" error. */
  12020. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12021. "yes")) {
  12022. handle_directory_request(conn, path);
  12023. } else {
  12024. mg_send_http_error(conn,
  12025. 403,
  12026. "%s",
  12027. "Error: Directory listing denied");
  12028. }
  12029. return;
  12030. }
  12031. /* 15. read a normal file with GET or HEAD */
  12032. handle_file_based_request(conn, path, &file);
  12033. #endif /* !defined(NO_FILES) */
  12034. }
  12035. static void
  12036. handle_file_based_request(struct mg_connection *conn,
  12037. const char *path,
  12038. struct mg_file *file)
  12039. {
  12040. if (!conn || !conn->dom_ctx) {
  12041. return;
  12042. }
  12043. if (0) {
  12044. #if defined(USE_LUA)
  12045. } else if (match_prefix(
  12046. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12047. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12048. path) > 0) {
  12049. if (is_in_script_path(conn, path)) {
  12050. /* Lua server page: an SSI like page containing mostly plain
  12051. * html
  12052. * code
  12053. * plus some tags with server generated contents. */
  12054. handle_lsp_request(conn, path, file, NULL);
  12055. } else {
  12056. /* Script was in an illegal path */
  12057. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12058. }
  12059. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12060. strlen(
  12061. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12062. path) > 0) {
  12063. if (is_in_script_path(conn, path)) {
  12064. /* Lua in-server module script: a CGI like script used to
  12065. * generate
  12066. * the
  12067. * entire reply. */
  12068. mg_exec_lua_script(conn, path, NULL);
  12069. } else {
  12070. /* Script was in an illegal path */
  12071. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12072. }
  12073. #endif
  12074. #if defined(USE_DUKTAPE)
  12075. } else if (match_prefix(
  12076. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12077. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12078. path) > 0) {
  12079. if (is_in_script_path(conn, path)) {
  12080. /* Call duktape to generate the page */
  12081. mg_exec_duktape_script(conn, path);
  12082. } else {
  12083. /* Script was in an illegal path */
  12084. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12085. }
  12086. #endif
  12087. #if !defined(NO_CGI)
  12088. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12089. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12090. path) > 0) {
  12091. if (is_in_script_path(conn, path)) {
  12092. /* CGI scripts may support all HTTP methods */
  12093. handle_cgi_request(conn, path);
  12094. } else {
  12095. /* Script was in an illegal path */
  12096. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12097. }
  12098. #endif /* !NO_CGI */
  12099. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12100. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12101. path) > 0) {
  12102. if (is_in_script_path(conn, path)) {
  12103. handle_ssi_file_request(conn, path, file);
  12104. } else {
  12105. /* Script was in an illegal path */
  12106. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12107. }
  12108. #if !defined(NO_CACHING)
  12109. } else if ((!conn->in_error_handler)
  12110. && is_not_modified(conn, &file->stat)) {
  12111. /* Send 304 "Not Modified" - this must not send any body data */
  12112. handle_not_modified_static_file_request(conn, file);
  12113. #endif /* !NO_CACHING */
  12114. } else {
  12115. handle_static_file_request(conn, path, file, NULL, NULL);
  12116. }
  12117. }
  12118. static void
  12119. close_all_listening_sockets(struct mg_context *ctx)
  12120. {
  12121. unsigned int i;
  12122. if (!ctx) {
  12123. return;
  12124. }
  12125. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12126. closesocket(ctx->listening_sockets[i].sock);
  12127. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12128. }
  12129. mg_free(ctx->listening_sockets);
  12130. ctx->listening_sockets = NULL;
  12131. mg_free(ctx->listening_socket_fds);
  12132. ctx->listening_socket_fds = NULL;
  12133. }
  12134. /* Valid listening port specification is: [ip_address:]port[s]
  12135. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12136. * Examples for IPv6: [::]:80, [::1]:80,
  12137. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12138. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12139. * In order to bind to both, IPv4 and IPv6, you can either add
  12140. * both ports using 8080,[::]:8080, or the short form +8080.
  12141. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12142. * one only accepting IPv4 the other only IPv6. +8080 creates
  12143. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12144. * environment, they might work differently, or might not work
  12145. * at all - it must be tested what options work best in the
  12146. * relevant network environment.
  12147. */
  12148. static int
  12149. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12150. {
  12151. unsigned int a, b, c, d, port;
  12152. int ch, len;
  12153. const char *cb;
  12154. #if defined(USE_IPV6)
  12155. char buf[100] = {0};
  12156. #endif
  12157. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12158. * Also, all-zeroes in the socket address means binding to all addresses
  12159. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12160. memset(so, 0, sizeof(*so));
  12161. so->lsa.sin.sin_family = AF_INET;
  12162. *ip_version = 0;
  12163. /* Initialize port and len as invalid. */
  12164. port = 0;
  12165. len = 0;
  12166. /* Test for different ways to format this string */
  12167. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12168. == 5) {
  12169. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12170. so->lsa.sin.sin_addr.s_addr =
  12171. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12172. so->lsa.sin.sin_port = htons((uint16_t)port);
  12173. *ip_version = 4;
  12174. #if defined(USE_IPV6)
  12175. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12176. && mg_inet_pton(
  12177. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12178. /* IPv6 address, examples: see above */
  12179. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12180. */
  12181. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12182. *ip_version = 6;
  12183. #endif
  12184. } else if ((vec->ptr[0] == '+')
  12185. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12186. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12187. /* Add 1 to len for the + character we skipped before */
  12188. len++;
  12189. #if defined(USE_IPV6)
  12190. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12191. so->lsa.sin6.sin6_family = AF_INET6;
  12192. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12193. *ip_version = 4 + 6;
  12194. #else
  12195. /* Bind to IPv4 only, since IPv6 is not built in. */
  12196. so->lsa.sin.sin_port = htons((uint16_t)port);
  12197. *ip_version = 4;
  12198. #endif
  12199. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12200. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12201. so->lsa.sin.sin_port = htons((uint16_t)port);
  12202. *ip_version = 4;
  12203. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12204. /* String could be a hostname. This check algotithm
  12205. * will only work for RFC 952 compliant hostnames,
  12206. * starting with a letter, containing only letters,
  12207. * digits and hyphen ('-'). Newer specs may allow
  12208. * more, but this is not guaranteed here, since it
  12209. * may interfere with rules for port option lists. */
  12210. /* According to RFC 1035, hostnames are restricted to 255 characters
  12211. * in total (63 between two dots). */
  12212. char hostname[256];
  12213. size_t hostnlen = (size_t)(cb - vec->ptr);
  12214. if (hostnlen >= sizeof(hostname)) {
  12215. /* This would be invalid in any case */
  12216. *ip_version = 0;
  12217. return 0;
  12218. }
  12219. memcpy(hostname, vec->ptr, hostnlen);
  12220. hostname[hostnlen] = 0;
  12221. if (mg_inet_pton(
  12222. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12223. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12224. *ip_version = 4;
  12225. so->lsa.sin.sin_family = AF_INET;
  12226. so->lsa.sin.sin_port = htons((uint16_t)port);
  12227. len += (int)(hostnlen + 1);
  12228. } else {
  12229. port = 0;
  12230. len = 0;
  12231. }
  12232. #if defined(USE_IPV6)
  12233. } else if (mg_inet_pton(AF_INET6,
  12234. vec->ptr,
  12235. &so->lsa.sin6,
  12236. sizeof(so->lsa.sin6))) {
  12237. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12238. *ip_version = 6;
  12239. so->lsa.sin6.sin6_family = AF_INET6;
  12240. so->lsa.sin.sin_port = htons((uint16_t)port);
  12241. len += (int)(hostnlen + 1);
  12242. } else {
  12243. port = 0;
  12244. len = 0;
  12245. }
  12246. #endif
  12247. }
  12248. } else {
  12249. /* Parsing failure. */
  12250. }
  12251. /* sscanf and the option splitting code ensure the following condition
  12252. */
  12253. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12254. *ip_version = 0;
  12255. return 0;
  12256. }
  12257. ch = vec->ptr[len]; /* Next character after the port number */
  12258. so->is_ssl = (ch == 's');
  12259. so->ssl_redir = (ch == 'r');
  12260. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12261. if (is_valid_port(port)
  12262. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12263. return 1;
  12264. }
  12265. /* Reset ip_version to 0 if there is an error */
  12266. *ip_version = 0;
  12267. return 0;
  12268. }
  12269. /* Is there any SSL port in use? */
  12270. static int
  12271. is_ssl_port_used(const char *ports)
  12272. {
  12273. if (ports) {
  12274. /* There are several different allowed syntax variants:
  12275. * - "80" for a single port using every network interface
  12276. * - "localhost:80" for a single port using only localhost
  12277. * - "80,localhost:8080" for two ports, one bound to localhost
  12278. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12279. * to IPv4 localhost, one to IPv6 localhost
  12280. * - "+80" use port 80 for IPv4 and IPv6
  12281. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12282. * for both: IPv4 and IPv4
  12283. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12284. * additionally port 8080 bound to localhost connections
  12285. *
  12286. * If we just look for 's' anywhere in the string, "localhost:80"
  12287. * will be detected as SSL (false positive).
  12288. * Looking for 's' after a digit may cause false positives in
  12289. * "my24service:8080".
  12290. * Looking from 's' backward if there are only ':' and numbers
  12291. * before will not work for "24service:8080" (non SSL, port 8080)
  12292. * or "24s" (SSL, port 24).
  12293. *
  12294. * Remark: Initially hostnames were not allowed to start with a
  12295. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12296. * Section 2.1).
  12297. *
  12298. * To get this correct, the entire string must be parsed as a whole,
  12299. * reading it as a list element for element and parsing with an
  12300. * algorithm equivalent to parse_port_string.
  12301. *
  12302. * In fact, we use local interface names here, not arbitrary hostnames,
  12303. * so in most cases the only name will be "localhost".
  12304. *
  12305. * So, for now, we use this simple algorithm, that may still return
  12306. * a false positive in bizarre cases.
  12307. */
  12308. int i;
  12309. int portslen = (int)strlen(ports);
  12310. char prevIsNumber = 0;
  12311. for (i = 0; i < portslen; i++) {
  12312. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12313. return 1;
  12314. }
  12315. if (ports[i] >= '0' && ports[i] <= '9') {
  12316. prevIsNumber = 1;
  12317. } else {
  12318. prevIsNumber = 0;
  12319. }
  12320. }
  12321. }
  12322. return 0;
  12323. }
  12324. static int
  12325. set_ports_option(struct mg_context *phys_ctx)
  12326. {
  12327. const char *list;
  12328. int on = 1;
  12329. #if defined(USE_IPV6)
  12330. int off = 0;
  12331. #endif
  12332. struct vec vec;
  12333. struct socket so, *ptr;
  12334. struct pollfd *pfd;
  12335. union usa usa;
  12336. socklen_t len;
  12337. int ip_version;
  12338. int portsTotal = 0;
  12339. int portsOk = 0;
  12340. if (!phys_ctx) {
  12341. return 0;
  12342. }
  12343. memset(&so, 0, sizeof(so));
  12344. memset(&usa, 0, sizeof(usa));
  12345. len = sizeof(usa);
  12346. list = phys_ctx->dd.config[LISTENING_PORTS];
  12347. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12348. portsTotal++;
  12349. if (!parse_port_string(&vec, &so, &ip_version)) {
  12350. mg_cry_internal(
  12351. fc(phys_ctx),
  12352. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12353. (int)vec.len,
  12354. vec.ptr,
  12355. portsTotal,
  12356. "[IP_ADDRESS:]PORT[s|r]");
  12357. continue;
  12358. }
  12359. #if !defined(NO_SSL)
  12360. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12361. mg_cry_internal(fc(phys_ctx),
  12362. "Cannot add SSL socket (entry %i)",
  12363. portsTotal);
  12364. continue;
  12365. }
  12366. #endif
  12367. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12368. == INVALID_SOCKET) {
  12369. mg_cry_internal(fc(phys_ctx),
  12370. "cannot create socket (entry %i)",
  12371. portsTotal);
  12372. continue;
  12373. }
  12374. #if defined(_WIN32)
  12375. /* Windows SO_REUSEADDR lets many procs binds to a
  12376. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12377. * if someone already has the socket -- DTL */
  12378. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12379. * Windows might need a few seconds before
  12380. * the same port can be used again in the
  12381. * same process, so a short Sleep may be
  12382. * required between mg_stop and mg_start.
  12383. */
  12384. if (setsockopt(so.sock,
  12385. SOL_SOCKET,
  12386. SO_EXCLUSIVEADDRUSE,
  12387. (SOCK_OPT_TYPE)&on,
  12388. sizeof(on)) != 0) {
  12389. /* Set reuse option, but don't abort on errors. */
  12390. mg_cry_internal(
  12391. fc(phys_ctx),
  12392. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12393. portsTotal);
  12394. }
  12395. #else
  12396. if (setsockopt(so.sock,
  12397. SOL_SOCKET,
  12398. SO_REUSEADDR,
  12399. (SOCK_OPT_TYPE)&on,
  12400. sizeof(on)) != 0) {
  12401. /* Set reuse option, but don't abort on errors. */
  12402. mg_cry_internal(fc(phys_ctx),
  12403. "cannot set socket option SO_REUSEADDR (entry %i)",
  12404. portsTotal);
  12405. }
  12406. #endif
  12407. if (ip_version > 4) {
  12408. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12409. #if defined(USE_IPV6)
  12410. if (ip_version > 6) {
  12411. if (so.lsa.sa.sa_family == AF_INET6
  12412. && setsockopt(so.sock,
  12413. IPPROTO_IPV6,
  12414. IPV6_V6ONLY,
  12415. (void *)&off,
  12416. sizeof(off)) != 0) {
  12417. /* Set IPv6 only option, but don't abort on errors. */
  12418. mg_cry_internal(
  12419. fc(phys_ctx),
  12420. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12421. portsTotal);
  12422. }
  12423. } else {
  12424. if (so.lsa.sa.sa_family == AF_INET6
  12425. && setsockopt(so.sock,
  12426. IPPROTO_IPV6,
  12427. IPV6_V6ONLY,
  12428. (void *)&on,
  12429. sizeof(on)) != 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=on (entry %i)",
  12434. portsTotal);
  12435. }
  12436. }
  12437. #else
  12438. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12439. closesocket(so.sock);
  12440. so.sock = INVALID_SOCKET;
  12441. continue;
  12442. #endif
  12443. }
  12444. if (so.lsa.sa.sa_family == AF_INET) {
  12445. len = sizeof(so.lsa.sin);
  12446. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12447. mg_cry_internal(fc(phys_ctx),
  12448. "cannot bind to %.*s: %d (%s)",
  12449. (int)vec.len,
  12450. vec.ptr,
  12451. (int)ERRNO,
  12452. strerror(errno));
  12453. closesocket(so.sock);
  12454. so.sock = INVALID_SOCKET;
  12455. continue;
  12456. }
  12457. }
  12458. #if defined(USE_IPV6)
  12459. else if (so.lsa.sa.sa_family == AF_INET6) {
  12460. len = sizeof(so.lsa.sin6);
  12461. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12462. mg_cry_internal(fc(phys_ctx),
  12463. "cannot bind to IPv6 %.*s: %d (%s)",
  12464. (int)vec.len,
  12465. vec.ptr,
  12466. (int)ERRNO,
  12467. strerror(errno));
  12468. closesocket(so.sock);
  12469. so.sock = INVALID_SOCKET;
  12470. continue;
  12471. }
  12472. }
  12473. #endif
  12474. else {
  12475. mg_cry_internal(
  12476. fc(phys_ctx),
  12477. "cannot bind: address family not supported (entry %i)",
  12478. portsTotal);
  12479. closesocket(so.sock);
  12480. so.sock = INVALID_SOCKET;
  12481. continue;
  12482. }
  12483. if (listen(so.sock, SOMAXCONN) != 0) {
  12484. mg_cry_internal(fc(phys_ctx),
  12485. "cannot listen to %.*s: %d (%s)",
  12486. (int)vec.len,
  12487. vec.ptr,
  12488. (int)ERRNO,
  12489. strerror(errno));
  12490. closesocket(so.sock);
  12491. so.sock = INVALID_SOCKET;
  12492. continue;
  12493. }
  12494. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12495. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12496. int err = (int)ERRNO;
  12497. mg_cry_internal(fc(phys_ctx),
  12498. "call to getsockname failed %.*s: %d (%s)",
  12499. (int)vec.len,
  12500. vec.ptr,
  12501. err,
  12502. strerror(errno));
  12503. closesocket(so.sock);
  12504. so.sock = INVALID_SOCKET;
  12505. continue;
  12506. }
  12507. /* Update lsa port in case of random free ports */
  12508. #if defined(USE_IPV6)
  12509. if (so.lsa.sa.sa_family == AF_INET6) {
  12510. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12511. } else
  12512. #endif
  12513. {
  12514. so.lsa.sin.sin_port = usa.sin.sin_port;
  12515. }
  12516. if ((ptr = (struct socket *)
  12517. mg_realloc_ctx(phys_ctx->listening_sockets,
  12518. (phys_ctx->num_listening_sockets + 1)
  12519. * sizeof(phys_ctx->listening_sockets[0]),
  12520. phys_ctx)) == NULL) {
  12521. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12522. closesocket(so.sock);
  12523. so.sock = INVALID_SOCKET;
  12524. continue;
  12525. }
  12526. if ((pfd = (struct pollfd *)
  12527. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12528. (phys_ctx->num_listening_sockets + 1)
  12529. * sizeof(phys_ctx->listening_socket_fds[0]),
  12530. phys_ctx)) == NULL) {
  12531. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12532. closesocket(so.sock);
  12533. so.sock = INVALID_SOCKET;
  12534. mg_free(ptr);
  12535. continue;
  12536. }
  12537. set_close_on_exec(so.sock, fc(phys_ctx));
  12538. phys_ctx->listening_sockets = ptr;
  12539. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12540. phys_ctx->listening_socket_fds = pfd;
  12541. phys_ctx->num_listening_sockets++;
  12542. portsOk++;
  12543. }
  12544. if (portsOk != portsTotal) {
  12545. close_all_listening_sockets(phys_ctx);
  12546. portsOk = 0;
  12547. }
  12548. return portsOk;
  12549. }
  12550. static const char *
  12551. header_val(const struct mg_connection *conn, const char *header)
  12552. {
  12553. const char *header_value;
  12554. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12555. return "-";
  12556. } else {
  12557. return header_value;
  12558. }
  12559. }
  12560. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12561. static void log_access(const struct mg_connection *conn);
  12562. #include "external_log_access.inl"
  12563. #else
  12564. static void
  12565. log_access(const struct mg_connection *conn)
  12566. {
  12567. const struct mg_request_info *ri;
  12568. struct mg_file fi;
  12569. char date[64], src_addr[IP_ADDR_STR_LEN];
  12570. struct tm *tm;
  12571. const char *referer;
  12572. const char *user_agent;
  12573. char buf[4096];
  12574. if (!conn || !conn->dom_ctx) {
  12575. return;
  12576. }
  12577. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12578. if (mg_fopen(conn,
  12579. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12580. MG_FOPEN_MODE_APPEND,
  12581. &fi) == 0) {
  12582. fi.access.fp = NULL;
  12583. }
  12584. } else {
  12585. fi.access.fp = NULL;
  12586. }
  12587. /* Log is written to a file and/or a callback. If both are not set,
  12588. * executing the rest of the function is pointless. */
  12589. if ((fi.access.fp == NULL)
  12590. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12591. return;
  12592. }
  12593. tm = localtime(&conn->conn_birth_time);
  12594. if (tm != NULL) {
  12595. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12596. } else {
  12597. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12598. date[sizeof(date) - 1] = '\0';
  12599. }
  12600. ri = &conn->request_info;
  12601. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12602. referer = header_val(conn, "Referer");
  12603. user_agent = header_val(conn, "User-Agent");
  12604. mg_snprintf(conn,
  12605. NULL, /* Ignore truncation in access log */
  12606. buf,
  12607. sizeof(buf),
  12608. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12609. src_addr,
  12610. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12611. date,
  12612. ri->request_method ? ri->request_method : "-",
  12613. ri->request_uri ? ri->request_uri : "-",
  12614. ri->query_string ? "?" : "",
  12615. ri->query_string ? ri->query_string : "",
  12616. ri->http_version,
  12617. conn->status_code,
  12618. conn->num_bytes_sent,
  12619. referer,
  12620. user_agent);
  12621. if (conn->phys_ctx->callbacks.log_access) {
  12622. conn->phys_ctx->callbacks.log_access(conn, buf);
  12623. }
  12624. if (fi.access.fp) {
  12625. int ok = 1;
  12626. flockfile(fi.access.fp);
  12627. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12628. ok = 0;
  12629. }
  12630. if (fflush(fi.access.fp) != 0) {
  12631. ok = 0;
  12632. }
  12633. funlockfile(fi.access.fp);
  12634. if (mg_fclose(&fi.access) != 0) {
  12635. ok = 0;
  12636. }
  12637. if (!ok) {
  12638. mg_cry_internal(conn,
  12639. "Error writing log file %s",
  12640. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12641. }
  12642. }
  12643. }
  12644. #endif /* Externally provided function */
  12645. /* Verify given socket address against the ACL.
  12646. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12647. */
  12648. static int
  12649. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12650. {
  12651. int allowed, flag;
  12652. uint32_t net, mask;
  12653. struct vec vec;
  12654. if (phys_ctx) {
  12655. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12656. /* If any ACL is set, deny by default */
  12657. allowed = (list == NULL) ? '+' : '-';
  12658. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12659. flag = vec.ptr[0];
  12660. if ((flag != '+' && flag != '-')
  12661. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12662. mg_cry_internal(fc(phys_ctx),
  12663. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12664. __func__);
  12665. return -1;
  12666. }
  12667. if (net == (remote_ip & mask)) {
  12668. allowed = flag;
  12669. }
  12670. }
  12671. return allowed == '+';
  12672. }
  12673. return -1;
  12674. }
  12675. #if !defined(_WIN32)
  12676. static int
  12677. set_uid_option(struct mg_context *phys_ctx)
  12678. {
  12679. int success = 0;
  12680. if (phys_ctx) {
  12681. /* We are currently running as curr_uid. */
  12682. const uid_t curr_uid = getuid();
  12683. /* If set, we want to run as run_as_user. */
  12684. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12685. const struct passwd *to_pw = NULL;
  12686. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12687. /* run_as_user does not exist on the system. We can't proceed
  12688. * further. */
  12689. mg_cry_internal(fc(phys_ctx),
  12690. "%s: unknown user [%s]",
  12691. __func__,
  12692. run_as_user);
  12693. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12694. /* There was either no request to change user, or we're already
  12695. * running as run_as_user. Nothing else to do.
  12696. */
  12697. success = 1;
  12698. } else {
  12699. /* Valid change request. */
  12700. if (setgid(to_pw->pw_gid) == -1) {
  12701. mg_cry_internal(fc(phys_ctx),
  12702. "%s: setgid(%s): %s",
  12703. __func__,
  12704. run_as_user,
  12705. strerror(errno));
  12706. } else if (setgroups(0, NULL) == -1) {
  12707. mg_cry_internal(fc(phys_ctx),
  12708. "%s: setgroups(): %s",
  12709. __func__,
  12710. strerror(errno));
  12711. } else if (setuid(to_pw->pw_uid) == -1) {
  12712. mg_cry_internal(fc(phys_ctx),
  12713. "%s: setuid(%s): %s",
  12714. __func__,
  12715. run_as_user,
  12716. strerror(errno));
  12717. } else {
  12718. success = 1;
  12719. }
  12720. }
  12721. }
  12722. return success;
  12723. }
  12724. #endif /* !_WIN32 */
  12725. static void
  12726. tls_dtor(void *key)
  12727. {
  12728. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12729. /* key == pthread_getspecific(sTlsKey); */
  12730. if (tls) {
  12731. if (tls->is_master == 2) {
  12732. tls->is_master = -3; /* Mark memory as dead */
  12733. mg_free(tls);
  12734. }
  12735. }
  12736. pthread_setspecific(sTlsKey, NULL);
  12737. }
  12738. #if !defined(NO_SSL)
  12739. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12740. struct mg_domain_context *dom_ctx,
  12741. const char *pem,
  12742. const char *chain);
  12743. static const char *ssl_error(void);
  12744. static int
  12745. refresh_trust(struct mg_connection *conn)
  12746. {
  12747. static int reload_lock = 0;
  12748. static long int data_check = 0;
  12749. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12750. struct stat cert_buf;
  12751. long int t;
  12752. const char *pem;
  12753. const char *chain;
  12754. int should_verify_peer;
  12755. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12756. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12757. * refresh_trust still can not work. */
  12758. return 0;
  12759. }
  12760. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12761. if (chain == NULL) {
  12762. /* pem is not NULL here */
  12763. chain = pem;
  12764. }
  12765. if (*chain == 0) {
  12766. chain = NULL;
  12767. }
  12768. t = data_check;
  12769. if (stat(pem, &cert_buf) != -1) {
  12770. t = (long int)cert_buf.st_mtime;
  12771. }
  12772. if (data_check != t) {
  12773. data_check = t;
  12774. should_verify_peer = 0;
  12775. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12776. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12777. == 0) {
  12778. should_verify_peer = 1;
  12779. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12780. "optional") == 0) {
  12781. should_verify_peer = 1;
  12782. }
  12783. }
  12784. if (should_verify_peer) {
  12785. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12786. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12787. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12788. ca_file,
  12789. ca_path) != 1) {
  12790. mg_cry_internal(
  12791. fc(conn->phys_ctx),
  12792. "SSL_CTX_load_verify_locations error: %s "
  12793. "ssl_verify_peer requires setting "
  12794. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12795. "present in "
  12796. "the .conf file?",
  12797. ssl_error());
  12798. return 0;
  12799. }
  12800. }
  12801. if (1 == mg_atomic_inc(p_reload_lock)) {
  12802. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12803. == 0) {
  12804. return 0;
  12805. }
  12806. *p_reload_lock = 0;
  12807. }
  12808. }
  12809. /* lock while cert is reloading */
  12810. while (*p_reload_lock) {
  12811. sleep(1);
  12812. }
  12813. return 1;
  12814. }
  12815. #if defined(OPENSSL_API_1_1)
  12816. #else
  12817. static pthread_mutex_t *ssl_mutexes;
  12818. #endif /* OPENSSL_API_1_1 */
  12819. static int
  12820. sslize(struct mg_connection *conn,
  12821. SSL_CTX *s,
  12822. int (*func)(SSL *),
  12823. volatile int *stop_server)
  12824. {
  12825. int ret, err;
  12826. int short_trust;
  12827. unsigned i;
  12828. if (!conn) {
  12829. return 0;
  12830. }
  12831. short_trust =
  12832. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12833. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12834. if (short_trust) {
  12835. int trust_ret = refresh_trust(conn);
  12836. if (!trust_ret) {
  12837. return trust_ret;
  12838. }
  12839. }
  12840. conn->ssl = SSL_new(s);
  12841. if (conn->ssl == NULL) {
  12842. return 0;
  12843. }
  12844. SSL_set_app_data(conn->ssl, (char *)conn);
  12845. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12846. if (ret != 1) {
  12847. err = SSL_get_error(conn->ssl, ret);
  12848. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  12849. SSL_free(conn->ssl);
  12850. conn->ssl = NULL;
  12851. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12852. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12853. #if !defined(OPENSSL_API_1_1)
  12854. ERR_remove_state(0);
  12855. #endif
  12856. return 0;
  12857. }
  12858. /* SSL functions may fail and require to be called again:
  12859. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  12860. * Here "func" could be SSL_connect or SSL_accept. */
  12861. for (i = 16; i <= 1024; i *= 2) {
  12862. ret = func(conn->ssl);
  12863. if (ret != 1) {
  12864. err = SSL_get_error(conn->ssl, ret);
  12865. if ((err == SSL_ERROR_WANT_CONNECT)
  12866. || (err == SSL_ERROR_WANT_ACCEPT)
  12867. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  12868. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  12869. /* Need to retry the function call "later".
  12870. * See https://linux.die.net/man/3/ssl_get_error
  12871. * This is typical for non-blocking sockets. */
  12872. if (*stop_server) {
  12873. /* Don't wait if the server is going to be stopped. */
  12874. break;
  12875. }
  12876. mg_sleep(i);
  12877. } else if (err == SSL_ERROR_SYSCALL) {
  12878. /* This is an IO error. Look at errno. */
  12879. err = errno;
  12880. mg_cry_internal(conn, "SSL syscall error %i", err);
  12881. break;
  12882. } else {
  12883. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  12884. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  12885. break;
  12886. }
  12887. } else {
  12888. /* success */
  12889. break;
  12890. }
  12891. }
  12892. if (ret != 1) {
  12893. SSL_free(conn->ssl);
  12894. conn->ssl = NULL;
  12895. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12896. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12897. #if !defined(OPENSSL_API_1_1)
  12898. ERR_remove_state(0);
  12899. #endif
  12900. return 0;
  12901. }
  12902. return 1;
  12903. }
  12904. /* Return OpenSSL error message (from CRYPTO lib) */
  12905. static const char *
  12906. ssl_error(void)
  12907. {
  12908. unsigned long err;
  12909. err = ERR_get_error();
  12910. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  12911. }
  12912. static int
  12913. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  12914. {
  12915. int i;
  12916. const char hexdigit[] = "0123456789abcdef";
  12917. if ((memlen <= 0) || (buflen <= 0)) {
  12918. return 0;
  12919. }
  12920. if (buflen < (3 * memlen)) {
  12921. return 0;
  12922. }
  12923. for (i = 0; i < memlen; i++) {
  12924. if (i > 0) {
  12925. buf[3 * i - 1] = ' ';
  12926. }
  12927. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12928. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12929. }
  12930. buf[3 * memlen - 1] = 0;
  12931. return 1;
  12932. }
  12933. static void
  12934. ssl_get_client_cert_info(struct mg_connection *conn)
  12935. {
  12936. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12937. if (cert) {
  12938. char str_subject[1024];
  12939. char str_issuer[1024];
  12940. char str_finger[1024];
  12941. unsigned char buf[256];
  12942. char *str_serial = NULL;
  12943. unsigned int ulen;
  12944. int ilen;
  12945. unsigned char *tmp_buf;
  12946. unsigned char *tmp_p;
  12947. /* Handle to algorithm used for fingerprint */
  12948. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12949. /* Get Subject and issuer */
  12950. X509_NAME *subj = X509_get_subject_name(cert);
  12951. X509_NAME *iss = X509_get_issuer_name(cert);
  12952. /* Get serial number */
  12953. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12954. /* Translate serial number to a hex string */
  12955. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12956. str_serial = BN_bn2hex(serial_bn);
  12957. BN_free(serial_bn);
  12958. /* Translate subject and issuer to a string */
  12959. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12960. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12961. /* Calculate SHA1 fingerprint and store as a hex string */
  12962. ulen = 0;
  12963. /* ASN1_digest is deprecated. Do the calculation manually,
  12964. * using EVP_Digest. */
  12965. ilen = i2d_X509(cert, NULL);
  12966. tmp_buf = (ilen > 0)
  12967. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  12968. conn->phys_ctx)
  12969. : NULL;
  12970. if (tmp_buf) {
  12971. tmp_p = tmp_buf;
  12972. (void)i2d_X509(cert, &tmp_p);
  12973. if (!EVP_Digest(
  12974. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12975. ulen = 0;
  12976. }
  12977. mg_free(tmp_buf);
  12978. }
  12979. if (!hexdump2string(
  12980. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12981. *str_finger = 0;
  12982. }
  12983. conn->request_info.client_cert = (struct mg_client_cert *)
  12984. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  12985. if (conn->request_info.client_cert) {
  12986. conn->request_info.client_cert->peer_cert = (void *)cert;
  12987. conn->request_info.client_cert->subject =
  12988. mg_strdup_ctx(str_subject, conn->phys_ctx);
  12989. conn->request_info.client_cert->issuer =
  12990. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  12991. conn->request_info.client_cert->serial =
  12992. mg_strdup_ctx(str_serial, conn->phys_ctx);
  12993. conn->request_info.client_cert->finger =
  12994. mg_strdup_ctx(str_finger, conn->phys_ctx);
  12995. } else {
  12996. mg_cry_internal(conn,
  12997. "%s",
  12998. "Out of memory: Cannot allocate memory for client "
  12999. "certificate");
  13000. }
  13001. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13002. * see https://linux.die.net/man/3/bn_bn2hex */
  13003. OPENSSL_free(str_serial);
  13004. }
  13005. }
  13006. #if defined(OPENSSL_API_1_1)
  13007. #else
  13008. static void
  13009. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13010. {
  13011. (void)line;
  13012. (void)file;
  13013. if (mode & 1) {
  13014. /* 1 is CRYPTO_LOCK */
  13015. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13016. } else {
  13017. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13018. }
  13019. }
  13020. #endif /* OPENSSL_API_1_1 */
  13021. #if !defined(NO_SSL_DL)
  13022. static void *
  13023. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13024. {
  13025. union {
  13026. void *p;
  13027. void (*fp)(void);
  13028. } u;
  13029. void *dll_handle;
  13030. struct ssl_func *fp;
  13031. int ok;
  13032. int truncated = 0;
  13033. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13034. mg_snprintf(NULL,
  13035. NULL, /* No truncation check for ebuf */
  13036. ebuf,
  13037. ebuf_len,
  13038. "%s: cannot load %s",
  13039. __func__,
  13040. dll_name);
  13041. return NULL;
  13042. }
  13043. ok = 1;
  13044. for (fp = sw; fp->name != NULL; fp++) {
  13045. #if defined(_WIN32)
  13046. /* GetProcAddress() returns pointer to function */
  13047. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13048. #else
  13049. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13050. * pointers to function pointers. We need to use a union to make a
  13051. * cast. */
  13052. u.p = dlsym(dll_handle, fp->name);
  13053. #endif /* _WIN32 */
  13054. if (u.fp == NULL) {
  13055. if (ok) {
  13056. mg_snprintf(NULL,
  13057. &truncated,
  13058. ebuf,
  13059. ebuf_len,
  13060. "%s: %s: cannot find %s",
  13061. __func__,
  13062. dll_name,
  13063. fp->name);
  13064. ok = 0;
  13065. } else {
  13066. size_t cur_len = strlen(ebuf);
  13067. if (!truncated) {
  13068. mg_snprintf(NULL,
  13069. &truncated,
  13070. ebuf + cur_len,
  13071. ebuf_len - cur_len - 3,
  13072. ", %s",
  13073. fp->name);
  13074. if (truncated) {
  13075. /* If truncated, add "..." */
  13076. strcat(ebuf, "...");
  13077. }
  13078. }
  13079. }
  13080. /* Debug:
  13081. * printf("Missing function: %s\n", fp->name); */
  13082. } else {
  13083. fp->ptr = u.fp;
  13084. }
  13085. }
  13086. if (!ok) {
  13087. (void)dlclose(dll_handle);
  13088. return NULL;
  13089. }
  13090. return dll_handle;
  13091. }
  13092. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13093. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13094. #endif /* NO_SSL_DL */
  13095. #if defined(SSL_ALREADY_INITIALIZED)
  13096. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13097. #else
  13098. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13099. #endif
  13100. static int
  13101. initialize_ssl(char *ebuf, size_t ebuf_len)
  13102. {
  13103. #if defined(OPENSSL_API_1_1)
  13104. if (ebuf_len > 0) {
  13105. ebuf[0] = 0;
  13106. }
  13107. #if !defined(NO_SSL_DL)
  13108. if (!cryptolib_dll_handle) {
  13109. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13110. if (!cryptolib_dll_handle) {
  13111. mg_snprintf(NULL,
  13112. NULL, /* No truncation check for ebuf */
  13113. ebuf,
  13114. ebuf_len,
  13115. "%s: error loading library %s",
  13116. __func__,
  13117. CRYPTO_LIB);
  13118. DEBUG_TRACE("%s", ebuf);
  13119. return 0;
  13120. }
  13121. }
  13122. #endif /* NO_SSL_DL */
  13123. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13124. return 1;
  13125. }
  13126. #else /* not OPENSSL_API_1_1 */
  13127. int i, num_locks;
  13128. size_t size;
  13129. if (ebuf_len > 0) {
  13130. ebuf[0] = 0;
  13131. }
  13132. #if !defined(NO_SSL_DL)
  13133. if (!cryptolib_dll_handle) {
  13134. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13135. if (!cryptolib_dll_handle) {
  13136. mg_snprintf(NULL,
  13137. NULL, /* No truncation check for ebuf */
  13138. ebuf,
  13139. ebuf_len,
  13140. "%s: error loading library %s",
  13141. __func__,
  13142. CRYPTO_LIB);
  13143. DEBUG_TRACE("%s", ebuf);
  13144. return 0;
  13145. }
  13146. }
  13147. #endif /* NO_SSL_DL */
  13148. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13149. return 1;
  13150. }
  13151. /* Initialize locking callbacks, needed for thread safety.
  13152. * http://www.openssl.org/support/faq.html#PROG1
  13153. */
  13154. num_locks = CRYPTO_num_locks();
  13155. if (num_locks < 0) {
  13156. num_locks = 0;
  13157. }
  13158. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13159. /* allocate mutex array, if required */
  13160. if (num_locks == 0) {
  13161. /* No mutex array required */
  13162. ssl_mutexes = NULL;
  13163. } else {
  13164. /* Mutex array required - allocate it */
  13165. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13166. /* Check OOM */
  13167. if (ssl_mutexes == NULL) {
  13168. mg_snprintf(NULL,
  13169. NULL, /* No truncation check for ebuf */
  13170. ebuf,
  13171. ebuf_len,
  13172. "%s: cannot allocate mutexes: %s",
  13173. __func__,
  13174. ssl_error());
  13175. DEBUG_TRACE("%s", ebuf);
  13176. return 0;
  13177. }
  13178. /* initialize mutex array */
  13179. for (i = 0; i < num_locks; i++) {
  13180. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13181. mg_snprintf(NULL,
  13182. NULL, /* No truncation check for ebuf */
  13183. ebuf,
  13184. ebuf_len,
  13185. "%s: error initializing mutex %i of %i",
  13186. __func__,
  13187. i,
  13188. num_locks);
  13189. DEBUG_TRACE("%s", ebuf);
  13190. mg_free(ssl_mutexes);
  13191. return 0;
  13192. }
  13193. }
  13194. }
  13195. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13196. CRYPTO_set_id_callback(&mg_current_thread_id);
  13197. #endif /* OPENSSL_API_1_1 */
  13198. #if !defined(NO_SSL_DL)
  13199. if (!ssllib_dll_handle) {
  13200. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13201. if (!ssllib_dll_handle) {
  13202. mg_free(ssl_mutexes);
  13203. DEBUG_TRACE("%s", ebuf);
  13204. return 0;
  13205. }
  13206. }
  13207. #endif /* NO_SSL_DL */
  13208. #if defined(OPENSSL_API_1_1)
  13209. /* Initialize SSL library */
  13210. OPENSSL_init_ssl(0, NULL);
  13211. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13212. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13213. NULL);
  13214. #else
  13215. /* Initialize SSL library */
  13216. SSL_library_init();
  13217. SSL_load_error_strings();
  13218. #endif
  13219. return 1;
  13220. }
  13221. static int
  13222. ssl_use_pem_file(struct mg_context *phys_ctx,
  13223. struct mg_domain_context *dom_ctx,
  13224. const char *pem,
  13225. const char *chain)
  13226. {
  13227. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13228. mg_cry_internal(fc(phys_ctx),
  13229. "%s: cannot open certificate file %s: %s",
  13230. __func__,
  13231. pem,
  13232. ssl_error());
  13233. return 0;
  13234. }
  13235. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13236. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13237. mg_cry_internal(fc(phys_ctx),
  13238. "%s: cannot open private key file %s: %s",
  13239. __func__,
  13240. pem,
  13241. ssl_error());
  13242. return 0;
  13243. }
  13244. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13245. mg_cry_internal(fc(phys_ctx),
  13246. "%s: certificate and private key do not match: %s",
  13247. __func__,
  13248. pem);
  13249. return 0;
  13250. }
  13251. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13252. * chain files that contain private keys and certificates in
  13253. * SSL_CTX_use_certificate_chain_file.
  13254. * The CivetWeb-Server used pem-Files that contained both information.
  13255. * In order to make wolfSSL work, it is split in two files.
  13256. * One file that contains key and certificate used by the server and
  13257. * an optional chain file for the ssl stack.
  13258. */
  13259. if (chain) {
  13260. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13261. mg_cry_internal(fc(phys_ctx),
  13262. "%s: cannot use certificate chain file %s: %s",
  13263. __func__,
  13264. pem,
  13265. ssl_error());
  13266. return 0;
  13267. }
  13268. }
  13269. return 1;
  13270. }
  13271. #if defined(OPENSSL_API_1_1)
  13272. static unsigned long
  13273. ssl_get_protocol(int version_id)
  13274. {
  13275. long unsigned ret = SSL_OP_ALL;
  13276. if (version_id > 0)
  13277. ret |= SSL_OP_NO_SSLv2;
  13278. if (version_id > 1)
  13279. ret |= SSL_OP_NO_SSLv3;
  13280. if (version_id > 2)
  13281. ret |= SSL_OP_NO_TLSv1;
  13282. if (version_id > 3)
  13283. ret |= SSL_OP_NO_TLSv1_1;
  13284. return ret;
  13285. }
  13286. #else
  13287. static long
  13288. ssl_get_protocol(int version_id)
  13289. {
  13290. long ret = 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. #endif /* OPENSSL_API_1_1 */
  13302. /* SSL callback documentation:
  13303. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13304. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13305. * https://linux.die.net/man/3/ssl_set_info_callback */
  13306. /* Note: There is no "const" for the first argument in the documentation,
  13307. * however some (maybe most, but not all) headers of OpenSSL versions /
  13308. * OpenSSL compatibility layers have it. Having a different definition
  13309. * will cause a warning in C and an error in C++. With inconsitent
  13310. * definitions of this function, having a warning in one version or
  13311. * another is unavoidable. */
  13312. static void
  13313. ssl_info_callback(SSL *ssl, int what, int ret)
  13314. {
  13315. (void)ret;
  13316. if (what & SSL_CB_HANDSHAKE_START) {
  13317. SSL_get_app_data(ssl);
  13318. }
  13319. if (what & SSL_CB_HANDSHAKE_DONE) {
  13320. /* TODO: check for openSSL 1.1 */
  13321. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13322. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13323. }
  13324. }
  13325. static int
  13326. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13327. {
  13328. struct mg_context *ctx = (struct mg_context *)arg;
  13329. struct mg_domain_context *dom =
  13330. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13331. #if defined(__GNUC__) || defined(__MINGW32__)
  13332. #pragma GCC diagnostic push
  13333. #pragma GCC diagnostic ignored "-Wcast-align"
  13334. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13335. /* We used an aligned pointer in SSL_set_app_data */
  13336. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13337. #if defined(__GNUC__) || defined(__MINGW32__)
  13338. #pragma GCC diagnostic pop
  13339. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13340. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13341. (void)ad;
  13342. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13343. DEBUG_TRACE("%s", "internal error - assertion failed");
  13344. return SSL_TLSEXT_ERR_NOACK;
  13345. }
  13346. /* Old clients (Win XP) will not support SNI. Then, there
  13347. * is no server name available in the request - we can
  13348. * only work with the default certificate.
  13349. * Multiple HTTPS hosts on one IP+port are only possible
  13350. * with a certificate containing all alternative names.
  13351. */
  13352. if ((servername == NULL) || (*servername == 0)) {
  13353. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13354. conn->dom_ctx = &(ctx->dd);
  13355. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13356. return SSL_TLSEXT_ERR_NOACK;
  13357. }
  13358. DEBUG_TRACE("TLS connection to host %s", servername);
  13359. while (dom) {
  13360. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13361. /* Found matching domain */
  13362. DEBUG_TRACE("TLS domain %s found",
  13363. dom->config[AUTHENTICATION_DOMAIN]);
  13364. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13365. conn->dom_ctx = dom;
  13366. return SSL_TLSEXT_ERR_OK;
  13367. }
  13368. dom = dom->next;
  13369. }
  13370. /* Default domain */
  13371. DEBUG_TRACE("TLS default domain %s used",
  13372. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13373. conn->dom_ctx = &(ctx->dd);
  13374. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13375. return SSL_TLSEXT_ERR_OK;
  13376. }
  13377. /* Setup SSL CTX as required by CivetWeb */
  13378. static int
  13379. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13380. struct mg_domain_context *dom_ctx,
  13381. const char *pem,
  13382. const char *chain)
  13383. {
  13384. int callback_ret;
  13385. int should_verify_peer;
  13386. int peer_certificate_optional;
  13387. const char *ca_path;
  13388. const char *ca_file;
  13389. int use_default_verify_paths;
  13390. int verify_depth;
  13391. struct timespec now_mt;
  13392. md5_byte_t ssl_context_id[16];
  13393. md5_state_t md5state;
  13394. int protocol_ver;
  13395. #if defined(OPENSSL_API_1_1)
  13396. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13397. mg_cry_internal(fc(phys_ctx),
  13398. "SSL_CTX_new (server) error: %s",
  13399. ssl_error());
  13400. return 0;
  13401. }
  13402. #else
  13403. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13404. mg_cry_internal(fc(phys_ctx),
  13405. "SSL_CTX_new (server) error: %s",
  13406. ssl_error());
  13407. return 0;
  13408. }
  13409. #endif /* OPENSSL_API_1_1 */
  13410. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13411. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13412. | SSL_OP_NO_TLSv1_1);
  13413. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13414. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13415. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13416. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13417. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13418. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13419. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13420. #if !defined(NO_SSL_DL)
  13421. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13422. #endif /* NO_SSL_DL */
  13423. #if defined(__clang__)
  13424. #pragma clang diagnostic push
  13425. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  13426. #endif
  13427. #if defined(__GNUC__) || defined(__MINGW32__)
  13428. #pragma GCC diagnostic push
  13429. #pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
  13430. #endif
  13431. /* Depending on the OpenSSL version, the callback may be
  13432. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  13433. * yielding in an "incompatible-pointer-type" warning for the other
  13434. * version. It seems to be "unclear" what is correct:
  13435. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13436. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13437. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13438. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13439. * Disable this warning here.
  13440. * Alternative would be a version dependent ssl_info_callback and
  13441. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  13442. */
  13443. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13444. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13445. ssl_servername_callback);
  13446. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13447. #if defined(__GNUC__) || defined(__MINGW32__)
  13448. #pragma GCC diagnostic pop
  13449. #endif
  13450. #if defined(__clang__)
  13451. #pragma clang diagnostic pop
  13452. #endif
  13453. /* If a callback has been specified, call it. */
  13454. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13455. ? 0
  13456. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13457. phys_ctx->user_data));
  13458. /* If callback returns 0, civetweb sets up the SSL certificate.
  13459. * If it returns 1, civetweb assumes the calback already did this.
  13460. * If it returns -1, initializing ssl fails. */
  13461. if (callback_ret < 0) {
  13462. mg_cry_internal(fc(phys_ctx),
  13463. "SSL callback returned error: %i",
  13464. callback_ret);
  13465. return 0;
  13466. }
  13467. if (callback_ret > 0) {
  13468. /* Callback did everything. */
  13469. return 1;
  13470. }
  13471. /* Use some combination of start time, domain and port as a SSL
  13472. * context ID. This should be unique on the current machine. */
  13473. md5_init(&md5state);
  13474. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13475. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13476. md5_append(&md5state,
  13477. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13478. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13479. md5_append(&md5state,
  13480. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13481. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13482. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13483. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13484. md5_finish(&md5state, ssl_context_id);
  13485. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13486. (unsigned char *)ssl_context_id,
  13487. sizeof(ssl_context_id));
  13488. if (pem != NULL) {
  13489. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13490. return 0;
  13491. }
  13492. }
  13493. /* Should we support client certificates? */
  13494. /* Default is "no". */
  13495. should_verify_peer = 0;
  13496. peer_certificate_optional = 0;
  13497. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13498. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13499. /* Yes, they are mandatory */
  13500. should_verify_peer = 1;
  13501. peer_certificate_optional = 0;
  13502. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13503. "optional") == 0) {
  13504. /* Yes, they are optional */
  13505. should_verify_peer = 1;
  13506. peer_certificate_optional = 1;
  13507. }
  13508. }
  13509. use_default_verify_paths =
  13510. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13511. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13512. == 0);
  13513. if (should_verify_peer) {
  13514. ca_path = dom_ctx->config[SSL_CA_PATH];
  13515. ca_file = dom_ctx->config[SSL_CA_FILE];
  13516. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13517. != 1) {
  13518. mg_cry_internal(fc(phys_ctx),
  13519. "SSL_CTX_load_verify_locations error: %s "
  13520. "ssl_verify_peer requires setting "
  13521. "either ssl_ca_path or ssl_ca_file. "
  13522. "Is any of them present in the "
  13523. ".conf file?",
  13524. ssl_error());
  13525. return 0;
  13526. }
  13527. if (peer_certificate_optional) {
  13528. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13529. } else {
  13530. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13531. SSL_VERIFY_PEER
  13532. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13533. NULL);
  13534. }
  13535. if (use_default_verify_paths
  13536. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13537. mg_cry_internal(fc(phys_ctx),
  13538. "SSL_CTX_set_default_verify_paths error: %s",
  13539. ssl_error());
  13540. return 0;
  13541. }
  13542. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13543. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13544. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13545. }
  13546. }
  13547. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13548. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13549. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  13550. mg_cry_internal(fc(phys_ctx),
  13551. "SSL_CTX_set_cipher_list error: %s",
  13552. ssl_error());
  13553. }
  13554. }
  13555. return 1;
  13556. }
  13557. /* Check if SSL is required.
  13558. * If so, dynamically load SSL library
  13559. * and set up ctx->ssl_ctx pointer. */
  13560. static int
  13561. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13562. {
  13563. void *ssl_ctx = 0;
  13564. int callback_ret;
  13565. const char *pem;
  13566. const char *chain;
  13567. char ebuf[128];
  13568. if (!phys_ctx) {
  13569. return 0;
  13570. }
  13571. if (!dom_ctx) {
  13572. dom_ctx = &(phys_ctx->dd);
  13573. }
  13574. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13575. /* No SSL port is set. No need to setup SSL. */
  13576. return 1;
  13577. }
  13578. /* Check for external SSL_CTX */
  13579. callback_ret =
  13580. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13581. ? 0
  13582. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13583. phys_ctx->user_data));
  13584. if (callback_ret < 0) {
  13585. mg_cry_internal(fc(phys_ctx),
  13586. "external_ssl_ctx callback returned error: %i",
  13587. callback_ret);
  13588. return 0;
  13589. } else if (callback_ret > 0) {
  13590. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13591. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13592. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13593. return 0;
  13594. }
  13595. return 1;
  13596. }
  13597. /* else: external_ssl_ctx does not exist or returns 0,
  13598. * CivetWeb should continue initializing SSL */
  13599. /* If PEM file is not specified and the init_ssl callback
  13600. * is not specified, setup will fail. */
  13601. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13602. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13603. /* No certificate and no callback:
  13604. * Essential data to set up TLS is missing.
  13605. */
  13606. mg_cry_internal(fc(phys_ctx),
  13607. "Initializing SSL failed: -%s is not set",
  13608. config_options[SSL_CERTIFICATE].name);
  13609. return 0;
  13610. }
  13611. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13612. if (chain == NULL) {
  13613. chain = pem;
  13614. }
  13615. if ((chain != NULL) && (*chain == 0)) {
  13616. chain = NULL;
  13617. }
  13618. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13619. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13620. return 0;
  13621. }
  13622. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13623. }
  13624. static void
  13625. uninitialize_ssl(void)
  13626. {
  13627. #if defined(OPENSSL_API_1_1)
  13628. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13629. /* Shutdown according to
  13630. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13631. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13632. */
  13633. CONF_modules_unload(1);
  13634. #else
  13635. int i;
  13636. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13637. /* Shutdown according to
  13638. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13639. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13640. */
  13641. CRYPTO_set_locking_callback(NULL);
  13642. CRYPTO_set_id_callback(NULL);
  13643. ENGINE_cleanup();
  13644. CONF_modules_unload(1);
  13645. ERR_free_strings();
  13646. EVP_cleanup();
  13647. CRYPTO_cleanup_all_ex_data();
  13648. ERR_remove_state(0);
  13649. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13650. pthread_mutex_destroy(&ssl_mutexes[i]);
  13651. }
  13652. mg_free(ssl_mutexes);
  13653. ssl_mutexes = NULL;
  13654. #endif /* OPENSSL_API_1_1 */
  13655. }
  13656. }
  13657. #endif /* !NO_SSL */
  13658. static int
  13659. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13660. {
  13661. if (phys_ctx) {
  13662. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13663. const char *path;
  13664. if (!dom_ctx) {
  13665. dom_ctx = &(phys_ctx->dd);
  13666. }
  13667. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13668. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13669. mg_cry_internal(fc(phys_ctx),
  13670. "Cannot open %s: %s",
  13671. path,
  13672. strerror(ERRNO));
  13673. return 0;
  13674. }
  13675. return 1;
  13676. }
  13677. return 0;
  13678. }
  13679. static int
  13680. set_acl_option(struct mg_context *phys_ctx)
  13681. {
  13682. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13683. }
  13684. static void
  13685. reset_per_request_attributes(struct mg_connection *conn)
  13686. {
  13687. if (!conn) {
  13688. return;
  13689. }
  13690. conn->connection_type =
  13691. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13692. conn->num_bytes_sent = conn->consumed_content = 0;
  13693. conn->path_info = NULL;
  13694. conn->status_code = -1;
  13695. conn->content_len = -1;
  13696. conn->is_chunked = 0;
  13697. conn->must_close = 0;
  13698. conn->request_len = 0;
  13699. conn->throttle = 0;
  13700. conn->data_len = 0;
  13701. conn->chunk_remainder = 0;
  13702. conn->accept_gzip = 0;
  13703. conn->response_info.content_length = conn->request_info.content_length = -1;
  13704. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13705. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13706. conn->response_info.status_text = NULL;
  13707. conn->response_info.status_code = 0;
  13708. conn->request_info.remote_user = NULL;
  13709. conn->request_info.request_method = NULL;
  13710. conn->request_info.request_uri = NULL;
  13711. conn->request_info.local_uri = NULL;
  13712. #if defined(MG_LEGACY_INTERFACE)
  13713. /* Legacy before split into local_uri and request_uri */
  13714. conn->request_info.uri = NULL;
  13715. #endif
  13716. }
  13717. #if 0
  13718. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13719. * Leave this function here (commented out) for reference until
  13720. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13721. * no longer required.
  13722. */
  13723. static int
  13724. set_sock_timeout(SOCKET sock, int milliseconds)
  13725. {
  13726. int r0 = 0, r1, r2;
  13727. #if defined(_WIN32)
  13728. /* Windows specific */
  13729. DWORD tv = (DWORD)milliseconds;
  13730. #else
  13731. /* Linux, ... (not Windows) */
  13732. struct timeval tv;
  13733. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13734. * max. time waiting for the acknowledged of TCP data before the connection
  13735. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13736. * If this option is not set, the default timeout of 20-30 minutes is used.
  13737. */
  13738. /* #define TCP_USER_TIMEOUT (18) */
  13739. #if defined(TCP_USER_TIMEOUT)
  13740. unsigned int uto = (unsigned int)milliseconds;
  13741. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13742. #endif
  13743. memset(&tv, 0, sizeof(tv));
  13744. tv.tv_sec = milliseconds / 1000;
  13745. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13746. #endif /* _WIN32 */
  13747. r1 = setsockopt(
  13748. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13749. r2 = setsockopt(
  13750. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13751. return r0 || r1 || r2;
  13752. }
  13753. #endif
  13754. static int
  13755. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13756. {
  13757. if (setsockopt(sock,
  13758. IPPROTO_TCP,
  13759. TCP_NODELAY,
  13760. (SOCK_OPT_TYPE)&nodelay_on,
  13761. sizeof(nodelay_on)) != 0) {
  13762. /* Error */
  13763. return 1;
  13764. }
  13765. /* OK */
  13766. return 0;
  13767. }
  13768. static void
  13769. close_socket_gracefully(struct mg_connection *conn)
  13770. {
  13771. #if defined(_WIN32)
  13772. char buf[MG_BUF_LEN];
  13773. int n;
  13774. #endif
  13775. struct linger linger;
  13776. int error_code = 0;
  13777. int linger_timeout = -2;
  13778. socklen_t opt_len = sizeof(error_code);
  13779. if (!conn) {
  13780. return;
  13781. }
  13782. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13783. * "Note that enabling a nonzero timeout on a nonblocking socket
  13784. * is not recommended.", so set it to blocking now */
  13785. set_blocking_mode(conn->client.sock);
  13786. /* Send FIN to the client */
  13787. shutdown(conn->client.sock, SHUTDOWN_WR);
  13788. #if defined(_WIN32)
  13789. /* Read and discard pending incoming data. If we do not do that and
  13790. * close
  13791. * the socket, the data in the send buffer may be discarded. This
  13792. * behaviour is seen on Windows, when client keeps sending data
  13793. * when server decides to close the connection; then when client
  13794. * does recv() it gets no data back. */
  13795. do {
  13796. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13797. } while (n > 0);
  13798. #endif
  13799. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13800. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13801. }
  13802. /* Set linger option according to configuration */
  13803. if (linger_timeout >= 0) {
  13804. /* Set linger option to avoid socket hanging out after close. This
  13805. * prevent ephemeral port exhaust problem under high QPS. */
  13806. linger.l_onoff = 1;
  13807. #if defined(_MSC_VER)
  13808. #pragma warning(push)
  13809. #pragma warning(disable : 4244)
  13810. #endif
  13811. #if defined(__GNUC__) || defined(__MINGW32__)
  13812. #pragma GCC diagnostic push
  13813. #pragma GCC diagnostic ignored "-Wconversion"
  13814. #endif
  13815. /* Data type of linger structure elements may differ,
  13816. * so we don't know what cast we need here.
  13817. * Disable type conversion warnings. */
  13818. linger.l_linger = (linger_timeout + 999) / 1000;
  13819. #if defined(__GNUC__) || defined(__MINGW32__)
  13820. #pragma GCC diagnostic pop
  13821. #endif
  13822. #if defined(_MSC_VER)
  13823. #pragma warning(pop)
  13824. #endif
  13825. } else {
  13826. linger.l_onoff = 0;
  13827. linger.l_linger = 0;
  13828. }
  13829. if (linger_timeout < -1) {
  13830. /* Default: don't configure any linger */
  13831. } else if (getsockopt(conn->client.sock,
  13832. SOL_SOCKET,
  13833. SO_ERROR,
  13834. #if defined(_WIN32) /* WinSock uses different data type here */
  13835. (char *)&error_code,
  13836. #else
  13837. &error_code,
  13838. #endif
  13839. &opt_len) != 0) {
  13840. /* Cannot determine if socket is already closed. This should
  13841. * not occur and never did in a test. Log an error message
  13842. * and continue. */
  13843. mg_cry_internal(conn,
  13844. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13845. __func__,
  13846. strerror(ERRNO));
  13847. } else if (error_code == ECONNRESET) {
  13848. /* Socket already closed by client/peer, close socket without linger
  13849. */
  13850. } else {
  13851. /* Set linger timeout */
  13852. if (setsockopt(conn->client.sock,
  13853. SOL_SOCKET,
  13854. SO_LINGER,
  13855. (char *)&linger,
  13856. sizeof(linger)) != 0) {
  13857. mg_cry_internal(
  13858. conn,
  13859. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13860. __func__,
  13861. linger.l_onoff,
  13862. linger.l_linger,
  13863. strerror(ERRNO));
  13864. }
  13865. }
  13866. /* Now we know that our FIN is ACK-ed, safe to close */
  13867. closesocket(conn->client.sock);
  13868. conn->client.sock = INVALID_SOCKET;
  13869. }
  13870. static void
  13871. close_connection(struct mg_connection *conn)
  13872. {
  13873. #if defined(USE_SERVER_STATS)
  13874. conn->conn_state = 6; /* to close */
  13875. #endif
  13876. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13877. if (conn->lua_websocket_state) {
  13878. lua_websocket_close(conn, conn->lua_websocket_state);
  13879. conn->lua_websocket_state = NULL;
  13880. }
  13881. #endif
  13882. mg_lock_connection(conn);
  13883. /* Set close flag, so keep-alive loops will stop */
  13884. conn->must_close = 1;
  13885. /* call the connection_close callback if assigned */
  13886. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13887. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13888. conn->phys_ctx->callbacks.connection_close(conn);
  13889. }
  13890. }
  13891. /* Reset user data, after close callback is called.
  13892. * Do not reuse it. If the user needs a destructor,
  13893. * it must be done in the connection_close callback. */
  13894. mg_set_user_connection_data(conn, NULL);
  13895. #if defined(USE_SERVER_STATS)
  13896. conn->conn_state = 7; /* closing */
  13897. #endif
  13898. #if !defined(NO_SSL)
  13899. if (conn->ssl != NULL) {
  13900. /* Run SSL_shutdown twice to ensure completely close SSL connection
  13901. */
  13902. SSL_shutdown(conn->ssl);
  13903. SSL_free(conn->ssl);
  13904. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13905. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13906. #if !defined(OPENSSL_API_1_1)
  13907. ERR_remove_state(0);
  13908. #endif
  13909. conn->ssl = NULL;
  13910. }
  13911. #endif
  13912. if (conn->client.sock != INVALID_SOCKET) {
  13913. close_socket_gracefully(conn);
  13914. conn->client.sock = INVALID_SOCKET;
  13915. }
  13916. if (conn->host) {
  13917. mg_free((void *)conn->host);
  13918. conn->host = NULL;
  13919. }
  13920. mg_unlock_connection(conn);
  13921. #if defined(USE_SERVER_STATS)
  13922. conn->conn_state = 8; /* closed */
  13923. #endif
  13924. }
  13925. void
  13926. mg_close_connection(struct mg_connection *conn)
  13927. {
  13928. #if defined(USE_WEBSOCKET)
  13929. struct mg_context *client_ctx = NULL;
  13930. #endif /* defined(USE_WEBSOCKET) */
  13931. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13932. return;
  13933. }
  13934. #if defined(USE_WEBSOCKET)
  13935. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13936. if (conn->in_websocket_handling) {
  13937. /* Set close flag, so the server thread can exit. */
  13938. conn->must_close = 1;
  13939. return;
  13940. }
  13941. }
  13942. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  13943. unsigned int i;
  13944. /* ws/wss client */
  13945. client_ctx = conn->phys_ctx;
  13946. /* client context: loops must end */
  13947. client_ctx->stop_flag = 1;
  13948. conn->must_close = 1;
  13949. /* We need to get the client thread out of the select/recv call
  13950. * here. */
  13951. /* Since we use a sleep quantum of some seconds to check for recv
  13952. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13953. /* join worker thread */
  13954. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13955. if (client_ctx->worker_threadids[i] != 0) {
  13956. mg_join_thread(client_ctx->worker_threadids[i]);
  13957. }
  13958. }
  13959. }
  13960. #endif /* defined(USE_WEBSOCKET) */
  13961. close_connection(conn);
  13962. #if !defined(NO_SSL)
  13963. if (conn->client_ssl_ctx != NULL) {
  13964. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13965. }
  13966. #endif
  13967. #if defined(USE_WEBSOCKET)
  13968. if (client_ctx != NULL) {
  13969. /* free context */
  13970. mg_free(client_ctx->worker_threadids);
  13971. mg_free(client_ctx);
  13972. (void)pthread_mutex_destroy(&conn->mutex);
  13973. mg_free(conn);
  13974. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13975. mg_free(conn);
  13976. }
  13977. #else
  13978. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13979. mg_free(conn);
  13980. }
  13981. #endif /* defined(USE_WEBSOCKET) */
  13982. }
  13983. /* Only for memory statistics */
  13984. static struct mg_context common_client_context;
  13985. static struct mg_connection *
  13986. mg_connect_client_impl(const struct mg_client_options *client_options,
  13987. int use_ssl,
  13988. char *ebuf,
  13989. size_t ebuf_len)
  13990. {
  13991. struct mg_connection *conn = NULL;
  13992. SOCKET sock;
  13993. union usa sa;
  13994. struct sockaddr *psa;
  13995. socklen_t len;
  13996. unsigned max_req_size =
  13997. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  13998. /* Size of structures, aligned to 8 bytes */
  13999. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14000. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14001. conn = (struct mg_connection *)mg_calloc_ctx(1,
  14002. conn_size + ctx_size
  14003. + max_req_size,
  14004. &common_client_context);
  14005. if (conn == NULL) {
  14006. mg_snprintf(NULL,
  14007. NULL, /* No truncation check for ebuf */
  14008. ebuf,
  14009. ebuf_len,
  14010. "calloc(): %s",
  14011. strerror(ERRNO));
  14012. return NULL;
  14013. }
  14014. #if defined(__GNUC__) || defined(__MINGW32__)
  14015. #pragma GCC diagnostic push
  14016. #pragma GCC diagnostic ignored "-Wcast-align"
  14017. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  14018. /* conn_size is aligned to 8 bytes */
  14019. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14020. #if defined(__GNUC__) || defined(__MINGW32__)
  14021. #pragma GCC diagnostic pop
  14022. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  14023. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14024. conn->buf_size = (int)max_req_size;
  14025. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14026. conn->dom_ctx = &(conn->phys_ctx->dd);
  14027. if (!connect_socket(&common_client_context,
  14028. client_options->host,
  14029. client_options->port,
  14030. use_ssl,
  14031. ebuf,
  14032. ebuf_len,
  14033. &sock,
  14034. &sa)) {
  14035. /* ebuf is set by connect_socket,
  14036. * free all memory and return NULL; */
  14037. mg_free(conn);
  14038. return NULL;
  14039. }
  14040. #if !defined(NO_SSL)
  14041. #if defined(OPENSSL_API_1_1)
  14042. if (use_ssl
  14043. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  14044. mg_snprintf(NULL,
  14045. NULL, /* No truncation check for ebuf */
  14046. ebuf,
  14047. ebuf_len,
  14048. "SSL_CTX_new error");
  14049. closesocket(sock);
  14050. mg_free(conn);
  14051. return NULL;
  14052. }
  14053. #else
  14054. if (use_ssl
  14055. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14056. == NULL) {
  14057. mg_snprintf(NULL,
  14058. NULL, /* No truncation check for ebuf */
  14059. ebuf,
  14060. ebuf_len,
  14061. "SSL_CTX_new error");
  14062. closesocket(sock);
  14063. mg_free(conn);
  14064. return NULL;
  14065. }
  14066. #endif /* OPENSSL_API_1_1 */
  14067. #endif /* NO_SSL */
  14068. #if defined(USE_IPV6)
  14069. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14070. : sizeof(conn->client.rsa.sin6);
  14071. psa = (sa.sa.sa_family == AF_INET)
  14072. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14073. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14074. #else
  14075. len = sizeof(conn->client.rsa.sin);
  14076. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14077. #endif
  14078. conn->client.sock = sock;
  14079. conn->client.lsa = sa;
  14080. if (getsockname(sock, psa, &len) != 0) {
  14081. mg_cry_internal(conn,
  14082. "%s: getsockname() failed: %s",
  14083. __func__,
  14084. strerror(ERRNO));
  14085. }
  14086. conn->client.is_ssl = use_ssl ? 1 : 0;
  14087. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14088. mg_snprintf(NULL,
  14089. NULL, /* No truncation check for ebuf */
  14090. ebuf,
  14091. ebuf_len,
  14092. "Can not create mutex");
  14093. #if !defined(NO_SSL)
  14094. SSL_CTX_free(conn->client_ssl_ctx);
  14095. #endif
  14096. closesocket(sock);
  14097. mg_free(conn);
  14098. return NULL;
  14099. }
  14100. #if !defined(NO_SSL)
  14101. if (use_ssl) {
  14102. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  14103. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14104. * SSL_CTX_set_verify call is needed to switch off server
  14105. * certificate checking, which is off by default in OpenSSL and
  14106. * on in yaSSL. */
  14107. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  14108. * SSL_VERIFY_PEER, verify_ssl_server); */
  14109. if (client_options->client_cert) {
  14110. if (!ssl_use_pem_file(&common_client_context,
  14111. &(common_client_context.dd),
  14112. client_options->client_cert,
  14113. NULL)) {
  14114. mg_snprintf(NULL,
  14115. NULL, /* No truncation check for ebuf */
  14116. ebuf,
  14117. ebuf_len,
  14118. "Can not use SSL client certificate");
  14119. SSL_CTX_free(conn->client_ssl_ctx);
  14120. closesocket(sock);
  14121. mg_free(conn);
  14122. return NULL;
  14123. }
  14124. }
  14125. if (client_options->server_cert) {
  14126. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  14127. client_options->server_cert,
  14128. NULL);
  14129. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  14130. } else {
  14131. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  14132. }
  14133. if (!sslize(conn,
  14134. conn->client_ssl_ctx,
  14135. SSL_connect,
  14136. &(conn->phys_ctx->stop_flag))) {
  14137. mg_snprintf(NULL,
  14138. NULL, /* No truncation check for ebuf */
  14139. ebuf,
  14140. ebuf_len,
  14141. "SSL connection error");
  14142. SSL_CTX_free(conn->client_ssl_ctx);
  14143. closesocket(sock);
  14144. mg_free(conn);
  14145. return NULL;
  14146. }
  14147. }
  14148. #endif
  14149. if (0 != set_non_blocking_mode(sock)) {
  14150. mg_cry_internal(conn,
  14151. "Cannot set non-blocking mode for client %s:%i",
  14152. client_options->host,
  14153. client_options->port);
  14154. }
  14155. return conn;
  14156. }
  14157. CIVETWEB_API struct mg_connection *
  14158. mg_connect_client_secure(const struct mg_client_options *client_options,
  14159. char *error_buffer,
  14160. size_t error_buffer_size)
  14161. {
  14162. return mg_connect_client_impl(client_options,
  14163. 1,
  14164. error_buffer,
  14165. error_buffer_size);
  14166. }
  14167. struct mg_connection *
  14168. mg_connect_client(const char *host,
  14169. int port,
  14170. int use_ssl,
  14171. char *error_buffer,
  14172. size_t error_buffer_size)
  14173. {
  14174. struct mg_client_options opts;
  14175. memset(&opts, 0, sizeof(opts));
  14176. opts.host = host;
  14177. opts.port = port;
  14178. return mg_connect_client_impl(&opts,
  14179. use_ssl,
  14180. error_buffer,
  14181. error_buffer_size);
  14182. }
  14183. static const struct {
  14184. const char *proto;
  14185. size_t proto_len;
  14186. unsigned default_port;
  14187. } abs_uri_protocols[] = {{"http://", 7, 80},
  14188. {"https://", 8, 443},
  14189. {"ws://", 5, 80},
  14190. {"wss://", 6, 443},
  14191. {NULL, 0, 0}};
  14192. /* Check if the uri is valid.
  14193. * return 0 for invalid uri,
  14194. * return 1 for *,
  14195. * return 2 for relative uri,
  14196. * return 3 for absolute uri without port,
  14197. * return 4 for absolute uri with port */
  14198. static int
  14199. get_uri_type(const char *uri)
  14200. {
  14201. int i;
  14202. const char *hostend, *portbegin;
  14203. char *portend;
  14204. unsigned long port;
  14205. /* According to the HTTP standard
  14206. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14207. * URI can be an asterisk (*) or should start with slash (relative uri),
  14208. * or it should start with the protocol (absolute uri). */
  14209. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14210. /* asterisk */
  14211. return 1;
  14212. }
  14213. /* Valid URIs according to RFC 3986
  14214. * (https://www.ietf.org/rfc/rfc3986.txt)
  14215. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14216. * and unreserved characters A-Z a-z 0-9 and -._~
  14217. * and % encoded symbols.
  14218. */
  14219. for (i = 0; uri[i] != 0; i++) {
  14220. if (uri[i] < 33) {
  14221. /* control characters and spaces are invalid */
  14222. return 0;
  14223. }
  14224. if (uri[i] > 126) {
  14225. /* non-ascii characters must be % encoded */
  14226. return 0;
  14227. } else {
  14228. switch (uri[i]) {
  14229. case '"': /* 34 */
  14230. case '<': /* 60 */
  14231. case '>': /* 62 */
  14232. case '\\': /* 92 */
  14233. case '^': /* 94 */
  14234. case '`': /* 96 */
  14235. case '{': /* 123 */
  14236. case '|': /* 124 */
  14237. case '}': /* 125 */
  14238. return 0;
  14239. default:
  14240. /* character is ok */
  14241. break;
  14242. }
  14243. }
  14244. }
  14245. /* A relative uri starts with a / character */
  14246. if (uri[0] == '/') {
  14247. /* relative uri */
  14248. return 2;
  14249. }
  14250. /* It could be an absolute uri: */
  14251. /* This function only checks if the uri is valid, not if it is
  14252. * addressing the current server. So civetweb can also be used
  14253. * as a proxy server. */
  14254. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14255. if (mg_strncasecmp(uri,
  14256. abs_uri_protocols[i].proto,
  14257. abs_uri_protocols[i].proto_len) == 0) {
  14258. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14259. if (!hostend) {
  14260. return 0;
  14261. }
  14262. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14263. if (!portbegin) {
  14264. return 3;
  14265. }
  14266. port = strtoul(portbegin + 1, &portend, 10);
  14267. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14268. return 0;
  14269. }
  14270. return 4;
  14271. }
  14272. }
  14273. return 0;
  14274. }
  14275. /* Return NULL or the relative uri at the current server */
  14276. static const char *
  14277. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14278. {
  14279. const char *server_domain;
  14280. size_t server_domain_len;
  14281. size_t request_domain_len = 0;
  14282. unsigned long port = 0;
  14283. int i, auth_domain_check_enabled;
  14284. const char *hostbegin = NULL;
  14285. const char *hostend = NULL;
  14286. const char *portbegin;
  14287. char *portend;
  14288. auth_domain_check_enabled =
  14289. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14290. /* DNS is case insensitive, so use case insensitive string compare here
  14291. */
  14292. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14293. if (mg_strncasecmp(uri,
  14294. abs_uri_protocols[i].proto,
  14295. abs_uri_protocols[i].proto_len) == 0) {
  14296. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14297. hostend = strchr(hostbegin, '/');
  14298. if (!hostend) {
  14299. return 0;
  14300. }
  14301. portbegin = strchr(hostbegin, ':');
  14302. if ((!portbegin) || (portbegin > hostend)) {
  14303. port = abs_uri_protocols[i].default_port;
  14304. request_domain_len = (size_t)(hostend - hostbegin);
  14305. } else {
  14306. port = strtoul(portbegin + 1, &portend, 10);
  14307. if ((portend != hostend) || (port <= 0)
  14308. || !is_valid_port(port)) {
  14309. return 0;
  14310. }
  14311. request_domain_len = (size_t)(portbegin - hostbegin);
  14312. }
  14313. /* protocol found, port set */
  14314. break;
  14315. }
  14316. }
  14317. if (!port) {
  14318. /* port remains 0 if the protocol is not found */
  14319. return 0;
  14320. }
  14321. /* Check if the request is directed to a different server. */
  14322. /* First check if the port is the same (IPv4 and IPv6). */
  14323. #if defined(USE_IPV6)
  14324. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14325. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14326. /* Request is directed to a different port */
  14327. return 0;
  14328. }
  14329. } else
  14330. #endif
  14331. {
  14332. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14333. /* Request is directed to a different port */
  14334. return 0;
  14335. }
  14336. }
  14337. /* Finally check if the server corresponds to the authentication
  14338. * domain of the server (the server domain).
  14339. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14340. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14341. * but do not allow substrings (like
  14342. * http://notmydomain.com/path/file.ext
  14343. * or http://mydomain.com.fake/path/file.ext).
  14344. */
  14345. if (auth_domain_check_enabled) {
  14346. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14347. server_domain_len = strlen(server_domain);
  14348. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14349. return 0;
  14350. }
  14351. if ((request_domain_len == server_domain_len)
  14352. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14353. /* Request is directed to this server - full name match. */
  14354. } else {
  14355. if (request_domain_len < (server_domain_len + 2)) {
  14356. /* Request is directed to another server: The server name
  14357. * is longer than the request name.
  14358. * Drop this case here to avoid overflows in the
  14359. * following checks. */
  14360. return 0;
  14361. }
  14362. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14363. /* Request is directed to another server: It could be a
  14364. * substring
  14365. * like notmyserver.com */
  14366. return 0;
  14367. }
  14368. if (0 != memcmp(server_domain,
  14369. hostbegin + request_domain_len - server_domain_len,
  14370. server_domain_len)) {
  14371. /* Request is directed to another server:
  14372. * The server name is different. */
  14373. return 0;
  14374. }
  14375. }
  14376. }
  14377. return hostend;
  14378. }
  14379. static int
  14380. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14381. {
  14382. if (ebuf_len > 0) {
  14383. ebuf[0] = '\0';
  14384. }
  14385. *err = 0;
  14386. reset_per_request_attributes(conn);
  14387. if (!conn) {
  14388. mg_snprintf(conn,
  14389. NULL, /* No truncation check for ebuf */
  14390. ebuf,
  14391. ebuf_len,
  14392. "%s",
  14393. "Internal error");
  14394. *err = 500;
  14395. return 0;
  14396. }
  14397. /* Set the time the request was received. This value should be used for
  14398. * timeouts. */
  14399. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14400. conn->request_len =
  14401. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14402. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14403. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14404. mg_snprintf(conn,
  14405. NULL, /* No truncation check for ebuf */
  14406. ebuf,
  14407. ebuf_len,
  14408. "%s",
  14409. "Invalid message size");
  14410. *err = 500;
  14411. return 0;
  14412. }
  14413. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14414. mg_snprintf(conn,
  14415. NULL, /* No truncation check for ebuf */
  14416. ebuf,
  14417. ebuf_len,
  14418. "%s",
  14419. "Message too large");
  14420. *err = 413;
  14421. return 0;
  14422. }
  14423. if (conn->request_len <= 0) {
  14424. if (conn->data_len > 0) {
  14425. mg_snprintf(conn,
  14426. NULL, /* No truncation check for ebuf */
  14427. ebuf,
  14428. ebuf_len,
  14429. "%s",
  14430. "Malformed message");
  14431. *err = 400;
  14432. } else {
  14433. /* Server did not recv anything -> just close the connection */
  14434. conn->must_close = 1;
  14435. mg_snprintf(conn,
  14436. NULL, /* No truncation check for ebuf */
  14437. ebuf,
  14438. ebuf_len,
  14439. "%s",
  14440. "No data received");
  14441. *err = 0;
  14442. }
  14443. return 0;
  14444. }
  14445. return 1;
  14446. }
  14447. static int
  14448. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14449. {
  14450. const char *cl;
  14451. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14452. return 0;
  14453. }
  14454. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14455. <= 0) {
  14456. mg_snprintf(conn,
  14457. NULL, /* No truncation check for ebuf */
  14458. ebuf,
  14459. ebuf_len,
  14460. "%s",
  14461. "Bad request");
  14462. *err = 400;
  14463. return 0;
  14464. }
  14465. /* Message is a valid request */
  14466. /* Is there a "host" ? */
  14467. conn->host = alloc_get_host(conn);
  14468. if (!conn->host) {
  14469. mg_snprintf(conn,
  14470. NULL, /* No truncation check for ebuf */
  14471. ebuf,
  14472. ebuf_len,
  14473. "%s",
  14474. "Bad request: Host mismatch");
  14475. *err = 400;
  14476. return 0;
  14477. }
  14478. /* Do we know the content length? */
  14479. if ((cl = get_header(conn->request_info.http_headers,
  14480. conn->request_info.num_headers,
  14481. "Content-Length")) != NULL) {
  14482. /* Request/response has content length set */
  14483. char *endptr = NULL;
  14484. conn->content_len = strtoll(cl, &endptr, 10);
  14485. if (endptr == cl) {
  14486. mg_snprintf(conn,
  14487. NULL, /* No truncation check for ebuf */
  14488. ebuf,
  14489. ebuf_len,
  14490. "%s",
  14491. "Bad request");
  14492. *err = 411;
  14493. return 0;
  14494. }
  14495. /* Publish the content length back to the request info. */
  14496. conn->request_info.content_length = conn->content_len;
  14497. } else if ((cl = get_header(conn->request_info.http_headers,
  14498. conn->request_info.num_headers,
  14499. "Transfer-Encoding")) != NULL
  14500. && !mg_strcasecmp(cl, "chunked")) {
  14501. conn->is_chunked = 1;
  14502. conn->content_len = -1; /* unknown content length */
  14503. } else {
  14504. const struct mg_http_method_info *meth =
  14505. get_http_method_info(conn->request_info.request_method);
  14506. if (!meth) {
  14507. /* No valid HTTP method */
  14508. mg_snprintf(conn,
  14509. NULL, /* No truncation check for ebuf */
  14510. ebuf,
  14511. ebuf_len,
  14512. "%s",
  14513. "Bad request");
  14514. *err = 411;
  14515. return 0;
  14516. }
  14517. if (meth->request_has_body) {
  14518. /* POST or PUT request without content length set */
  14519. conn->content_len = -1; /* unknown content length */
  14520. } else {
  14521. /* Other request */
  14522. conn->content_len = 0; /* No content */
  14523. }
  14524. }
  14525. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14526. return 1;
  14527. }
  14528. /* conn is assumed to be valid in this internal function */
  14529. static int
  14530. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14531. {
  14532. const char *cl;
  14533. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14534. return 0;
  14535. }
  14536. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14537. <= 0) {
  14538. mg_snprintf(conn,
  14539. NULL, /* No truncation check for ebuf */
  14540. ebuf,
  14541. ebuf_len,
  14542. "%s",
  14543. "Bad response");
  14544. *err = 400;
  14545. return 0;
  14546. }
  14547. /* Message is a valid response */
  14548. /* Do we know the content length? */
  14549. if ((cl = get_header(conn->response_info.http_headers,
  14550. conn->response_info.num_headers,
  14551. "Content-Length")) != NULL) {
  14552. /* Request/response has content length set */
  14553. char *endptr = NULL;
  14554. conn->content_len = strtoll(cl, &endptr, 10);
  14555. if (endptr == cl) {
  14556. mg_snprintf(conn,
  14557. NULL, /* No truncation check for ebuf */
  14558. ebuf,
  14559. ebuf_len,
  14560. "%s",
  14561. "Bad request");
  14562. *err = 411;
  14563. return 0;
  14564. }
  14565. /* Publish the content length back to the response info. */
  14566. conn->response_info.content_length = conn->content_len;
  14567. /* TODO: check if it is still used in response_info */
  14568. conn->request_info.content_length = conn->content_len;
  14569. } else if ((cl = get_header(conn->response_info.http_headers,
  14570. conn->response_info.num_headers,
  14571. "Transfer-Encoding")) != NULL
  14572. && !mg_strcasecmp(cl, "chunked")) {
  14573. conn->is_chunked = 1;
  14574. conn->content_len = -1; /* unknown content length */
  14575. } else {
  14576. conn->content_len = -1; /* unknown content length */
  14577. }
  14578. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14579. return 1;
  14580. }
  14581. int
  14582. mg_get_response(struct mg_connection *conn,
  14583. char *ebuf,
  14584. size_t ebuf_len,
  14585. int timeout)
  14586. {
  14587. int err, ret;
  14588. char txt[32]; /* will not overflow */
  14589. char *save_timeout;
  14590. char *new_timeout;
  14591. if (ebuf_len > 0) {
  14592. ebuf[0] = '\0';
  14593. }
  14594. if (!conn) {
  14595. mg_snprintf(conn,
  14596. NULL, /* No truncation check for ebuf */
  14597. ebuf,
  14598. ebuf_len,
  14599. "%s",
  14600. "Parameter error");
  14601. return -1;
  14602. }
  14603. /* Implementation of API function for HTTP clients */
  14604. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14605. if (timeout >= 0) {
  14606. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14607. new_timeout = txt;
  14608. /* Not required for non-blocking sockets.
  14609. set_sock_timeout(conn->client.sock, timeout);
  14610. */
  14611. } else {
  14612. new_timeout = NULL;
  14613. }
  14614. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14615. ret = get_response(conn, ebuf, ebuf_len, &err);
  14616. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14617. #if defined(MG_LEGACY_INTERFACE)
  14618. /* TODO: 1) uri is deprecated;
  14619. * 2) here, ri.uri is the http response code */
  14620. conn->request_info.uri = conn->request_info.request_uri;
  14621. #endif
  14622. conn->request_info.local_uri = conn->request_info.request_uri;
  14623. /* TODO (mid): Define proper return values - maybe return length?
  14624. * For the first test use <0 for error and >0 for OK */
  14625. return (ret == 0) ? -1 : +1;
  14626. }
  14627. struct mg_connection *
  14628. mg_download(const char *host,
  14629. int port,
  14630. int use_ssl,
  14631. char *ebuf,
  14632. size_t ebuf_len,
  14633. const char *fmt,
  14634. ...)
  14635. {
  14636. struct mg_connection *conn;
  14637. va_list ap;
  14638. int i;
  14639. int reqerr;
  14640. if (ebuf_len > 0) {
  14641. ebuf[0] = '\0';
  14642. }
  14643. va_start(ap, fmt);
  14644. /* open a connection */
  14645. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14646. if (conn != NULL) {
  14647. i = mg_vprintf(conn, fmt, ap);
  14648. if (i <= 0) {
  14649. mg_snprintf(conn,
  14650. NULL, /* No truncation check for ebuf */
  14651. ebuf,
  14652. ebuf_len,
  14653. "%s",
  14654. "Error sending request");
  14655. } else {
  14656. get_response(conn, ebuf, ebuf_len, &reqerr);
  14657. #if defined(MG_LEGACY_INTERFACE)
  14658. /* TODO: 1) uri is deprecated;
  14659. * 2) here, ri.uri is the http response code */
  14660. conn->request_info.uri = conn->request_info.request_uri;
  14661. #endif
  14662. conn->request_info.local_uri = conn->request_info.request_uri;
  14663. }
  14664. }
  14665. /* if an error occurred, close the connection */
  14666. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14667. mg_close_connection(conn);
  14668. conn = NULL;
  14669. }
  14670. va_end(ap);
  14671. return conn;
  14672. }
  14673. struct websocket_client_thread_data {
  14674. struct mg_connection *conn;
  14675. mg_websocket_data_handler data_handler;
  14676. mg_websocket_close_handler close_handler;
  14677. void *callback_data;
  14678. };
  14679. #if defined(USE_WEBSOCKET)
  14680. #if defined(_WIN32)
  14681. static unsigned __stdcall websocket_client_thread(void *data)
  14682. #else
  14683. static void *
  14684. websocket_client_thread(void *data)
  14685. #endif
  14686. {
  14687. struct websocket_client_thread_data *cdata =
  14688. (struct websocket_client_thread_data *)data;
  14689. #if !defined(_WIN32)
  14690. struct sigaction sa;
  14691. /* Ignore SIGPIPE */
  14692. memset(&sa, 0, sizeof(sa));
  14693. sa.sa_handler = SIG_IGN;
  14694. sigaction(SIGPIPE, &sa, NULL);
  14695. #endif
  14696. mg_set_thread_name("ws-clnt");
  14697. if (cdata->conn->phys_ctx) {
  14698. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14699. /* 3 indicates a websocket client thread */
  14700. /* TODO: check if conn->phys_ctx can be set */
  14701. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14702. 3);
  14703. }
  14704. }
  14705. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14706. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14707. if (cdata->close_handler != NULL) {
  14708. cdata->close_handler(cdata->conn, cdata->callback_data);
  14709. }
  14710. /* The websocket_client context has only this thread. If it runs out,
  14711. set the stop_flag to 2 (= "stopped"). */
  14712. cdata->conn->phys_ctx->stop_flag = 2;
  14713. mg_free((void *)cdata);
  14714. #if defined(_WIN32)
  14715. return 0;
  14716. #else
  14717. return NULL;
  14718. #endif
  14719. }
  14720. #endif
  14721. struct mg_connection *
  14722. mg_connect_websocket_client(const char *host,
  14723. int port,
  14724. int use_ssl,
  14725. char *error_buffer,
  14726. size_t error_buffer_size,
  14727. const char *path,
  14728. const char *origin,
  14729. mg_websocket_data_handler data_func,
  14730. mg_websocket_close_handler close_func,
  14731. void *user_data)
  14732. {
  14733. struct mg_connection *conn = NULL;
  14734. #if defined(USE_WEBSOCKET)
  14735. struct mg_context *newctx = NULL;
  14736. struct websocket_client_thread_data *thread_data;
  14737. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14738. static const char *handshake_req;
  14739. if (origin != NULL) {
  14740. handshake_req = "GET %s HTTP/1.1\r\n"
  14741. "Host: %s\r\n"
  14742. "Upgrade: websocket\r\n"
  14743. "Connection: Upgrade\r\n"
  14744. "Sec-WebSocket-Key: %s\r\n"
  14745. "Sec-WebSocket-Version: 13\r\n"
  14746. "Origin: %s\r\n"
  14747. "\r\n";
  14748. } else {
  14749. handshake_req = "GET %s HTTP/1.1\r\n"
  14750. "Host: %s\r\n"
  14751. "Upgrade: websocket\r\n"
  14752. "Connection: Upgrade\r\n"
  14753. "Sec-WebSocket-Key: %s\r\n"
  14754. "Sec-WebSocket-Version: 13\r\n"
  14755. "\r\n";
  14756. }
  14757. #if defined(__clang__)
  14758. #pragma clang diagnostic push
  14759. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14760. #endif
  14761. /* Establish the client connection and request upgrade */
  14762. conn = mg_download(host,
  14763. port,
  14764. use_ssl,
  14765. error_buffer,
  14766. error_buffer_size,
  14767. handshake_req,
  14768. path,
  14769. host,
  14770. magic,
  14771. origin);
  14772. #if defined(__clang__)
  14773. #pragma clang diagnostic pop
  14774. #endif
  14775. /* Connection object will be null if something goes wrong */
  14776. if (conn == NULL) {
  14777. if (!*error_buffer) {
  14778. /* There should be already an error message */
  14779. mg_snprintf(conn,
  14780. NULL, /* No truncation check for ebuf */
  14781. error_buffer,
  14782. error_buffer_size,
  14783. "Unexpected error");
  14784. }
  14785. return NULL;
  14786. }
  14787. if (conn->response_info.status_code != 101) {
  14788. /* We sent an "upgrade" request. For a correct websocket
  14789. * protocol handshake, we expect a "101 Continue" response.
  14790. * Otherwise it is a protocol violation. Maybe the HTTP
  14791. * Server does not know websockets. */
  14792. if (!*error_buffer) {
  14793. /* set an error, if not yet set */
  14794. mg_snprintf(conn,
  14795. NULL, /* No truncation check for ebuf */
  14796. error_buffer,
  14797. error_buffer_size,
  14798. "Unexpected server reply");
  14799. }
  14800. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14801. mg_free(conn);
  14802. return NULL;
  14803. }
  14804. /* For client connections, mg_context is fake. Since we need to set a
  14805. * callback function, we need to create a copy and modify it. */
  14806. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14807. if (!newctx) {
  14808. DEBUG_TRACE("%s\r\n", "Out of memory");
  14809. mg_free(conn);
  14810. return NULL;
  14811. }
  14812. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14813. newctx->user_data = user_data;
  14814. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14815. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14816. newctx->worker_threadids =
  14817. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14818. sizeof(pthread_t),
  14819. newctx);
  14820. conn->phys_ctx = newctx;
  14821. conn->dom_ctx = &(newctx->dd);
  14822. thread_data = (struct websocket_client_thread_data *)
  14823. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14824. if (!thread_data) {
  14825. DEBUG_TRACE("%s\r\n", "Out of memory");
  14826. mg_free(newctx);
  14827. mg_free(conn);
  14828. return NULL;
  14829. }
  14830. thread_data->conn = conn;
  14831. thread_data->data_handler = data_func;
  14832. thread_data->close_handler = close_func;
  14833. thread_data->callback_data = user_data;
  14834. /* Start a thread to read the websocket client connection
  14835. * This thread will automatically stop when mg_disconnect is
  14836. * called on the client connection */
  14837. if (mg_start_thread_with_id(websocket_client_thread,
  14838. (void *)thread_data,
  14839. newctx->worker_threadids) != 0) {
  14840. mg_free((void *)thread_data);
  14841. mg_free((void *)newctx->worker_threadids);
  14842. mg_free((void *)newctx);
  14843. mg_free((void *)conn);
  14844. conn = NULL;
  14845. DEBUG_TRACE("%s",
  14846. "Websocket client connect thread could not be started\r\n");
  14847. }
  14848. #else
  14849. /* Appease "unused parameter" warnings */
  14850. (void)host;
  14851. (void)port;
  14852. (void)use_ssl;
  14853. (void)error_buffer;
  14854. (void)error_buffer_size;
  14855. (void)path;
  14856. (void)origin;
  14857. (void)user_data;
  14858. (void)data_func;
  14859. (void)close_func;
  14860. #endif
  14861. return conn;
  14862. }
  14863. /* Prepare connection data structure */
  14864. static void
  14865. init_connection(struct mg_connection *conn)
  14866. {
  14867. /* Is keep alive allowed by the server */
  14868. int keep_alive_enabled =
  14869. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  14870. if (!keep_alive_enabled) {
  14871. conn->must_close = 1;
  14872. }
  14873. /* Important: on new connection, reset the receiving buffer. Credit
  14874. * goes to crule42. */
  14875. conn->data_len = 0;
  14876. conn->handled_requests = 0;
  14877. mg_set_user_connection_data(conn, NULL);
  14878. #if defined(USE_SERVER_STATS)
  14879. conn->conn_state = 2; /* init */
  14880. #endif
  14881. /* call the init_connection callback if assigned */
  14882. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  14883. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14884. void *conn_data = NULL;
  14885. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  14886. mg_set_user_connection_data(conn, conn_data);
  14887. }
  14888. }
  14889. }
  14890. /* Process a connection - may handle multiple requests
  14891. * using the same connection.
  14892. * Must be called with a valid connection (conn and
  14893. * conn->phys_ctx must be valid).
  14894. */
  14895. static void
  14896. process_new_connection(struct mg_connection *conn)
  14897. {
  14898. struct mg_request_info *ri = &conn->request_info;
  14899. int keep_alive, discard_len;
  14900. char ebuf[100];
  14901. const char *hostend;
  14902. int reqerr, uri_type;
  14903. #if defined(USE_SERVER_STATS)
  14904. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  14905. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  14906. if (mcon > (conn->phys_ctx->max_connections)) {
  14907. /* could use atomic compare exchange, but this
  14908. * seems overkill for statistics data */
  14909. conn->phys_ctx->max_connections = mcon;
  14910. }
  14911. #endif
  14912. init_connection(conn);
  14913. DEBUG_TRACE("Start processing connection from %s",
  14914. conn->request_info.remote_addr);
  14915. /* Loop over multiple requests sent using the same connection
  14916. * (while "keep alive"). */
  14917. do {
  14918. DEBUG_TRACE("calling get_request (%i times for this connection)",
  14919. conn->handled_requests + 1);
  14920. #if defined(USE_SERVER_STATS)
  14921. conn->conn_state = 3; /* ready */
  14922. #endif
  14923. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  14924. /* The request sent by the client could not be understood by
  14925. * the server, or it was incomplete or a timeout. Send an
  14926. * error message and close the connection. */
  14927. if (reqerr > 0) {
  14928. DEBUG_ASSERT(ebuf[0] != '\0');
  14929. mg_send_http_error(conn, reqerr, "%s", ebuf);
  14930. }
  14931. } else if (strcmp(ri->http_version, "1.0")
  14932. && strcmp(ri->http_version, "1.1")) {
  14933. mg_snprintf(conn,
  14934. NULL, /* No truncation check for ebuf */
  14935. ebuf,
  14936. sizeof(ebuf),
  14937. "Bad HTTP version: [%s]",
  14938. ri->http_version);
  14939. mg_send_http_error(conn, 505, "%s", ebuf);
  14940. }
  14941. if (ebuf[0] == '\0') {
  14942. uri_type = get_uri_type(conn->request_info.request_uri);
  14943. switch (uri_type) {
  14944. case 1:
  14945. /* Asterisk */
  14946. conn->request_info.local_uri = NULL;
  14947. break;
  14948. case 2:
  14949. /* relative uri */
  14950. conn->request_info.local_uri = conn->request_info.request_uri;
  14951. break;
  14952. case 3:
  14953. case 4:
  14954. /* absolute uri (with/without port) */
  14955. hostend = get_rel_url_at_current_server(
  14956. conn->request_info.request_uri, conn);
  14957. if (hostend) {
  14958. conn->request_info.local_uri = hostend;
  14959. } else {
  14960. conn->request_info.local_uri = NULL;
  14961. }
  14962. break;
  14963. default:
  14964. mg_snprintf(conn,
  14965. NULL, /* No truncation check for ebuf */
  14966. ebuf,
  14967. sizeof(ebuf),
  14968. "Invalid URI");
  14969. mg_send_http_error(conn, 400, "%s", ebuf);
  14970. conn->request_info.local_uri = NULL;
  14971. break;
  14972. }
  14973. #if defined(MG_LEGACY_INTERFACE)
  14974. /* Legacy before split into local_uri and request_uri */
  14975. conn->request_info.uri = conn->request_info.local_uri;
  14976. #endif
  14977. }
  14978. DEBUG_TRACE("http: %s, error: %s",
  14979. (ri->http_version ? ri->http_version : "none"),
  14980. (ebuf[0] ? ebuf : "none"));
  14981. if (ebuf[0] == '\0') {
  14982. if (conn->request_info.local_uri) {
  14983. /* handle request to local server */
  14984. #if defined(USE_SERVER_STATS)
  14985. conn->conn_state = 4; /* processing */
  14986. #endif
  14987. handle_request(conn);
  14988. #if defined(USE_SERVER_STATS)
  14989. conn->conn_state = 5; /* processed */
  14990. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  14991. conn->consumed_content);
  14992. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  14993. conn->num_bytes_sent);
  14994. #endif
  14995. DEBUG_TRACE("%s", "handle_request done");
  14996. if (conn->phys_ctx->callbacks.end_request != NULL) {
  14997. conn->phys_ctx->callbacks.end_request(conn,
  14998. conn->status_code);
  14999. DEBUG_TRACE("%s", "end_request callback done");
  15000. }
  15001. log_access(conn);
  15002. } else {
  15003. /* TODO: handle non-local request (PROXY) */
  15004. conn->must_close = 1;
  15005. }
  15006. } else {
  15007. conn->must_close = 1;
  15008. }
  15009. if (ri->remote_user != NULL) {
  15010. mg_free((void *)ri->remote_user);
  15011. /* Important! When having connections with and without auth
  15012. * would cause double free and then crash */
  15013. ri->remote_user = NULL;
  15014. }
  15015. /* NOTE(lsm): order is important here. should_keep_alive() call
  15016. * is using parsed request, which will be invalid after
  15017. * memmove's below.
  15018. * Therefore, memorize should_keep_alive() result now for later
  15019. * use in loop exit condition. */
  15020. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15021. && (conn->content_len >= 0);
  15022. /* Discard all buffered data for this request */
  15023. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  15024. && ((conn->request_len + conn->content_len)
  15025. < (int64_t)conn->data_len))
  15026. ? (int)(conn->request_len + conn->content_len)
  15027. : conn->data_len;
  15028. DEBUG_ASSERT(discard_len >= 0);
  15029. if (discard_len < 0) {
  15030. DEBUG_TRACE("internal error: discard_len = %li",
  15031. (long int)discard_len);
  15032. break;
  15033. }
  15034. conn->data_len -= discard_len;
  15035. if (conn->data_len > 0) {
  15036. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  15037. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  15038. }
  15039. DEBUG_ASSERT(conn->data_len >= 0);
  15040. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15041. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15042. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15043. (long int)conn->data_len,
  15044. (long int)conn->buf_size);
  15045. break;
  15046. }
  15047. conn->handled_requests++;
  15048. } while (keep_alive);
  15049. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15050. conn->request_info.remote_addr,
  15051. difftime(time(NULL), conn->conn_birth_time));
  15052. close_connection(conn);
  15053. #if defined(USE_SERVER_STATS)
  15054. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15055. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15056. #endif
  15057. }
  15058. #if defined(ALTERNATIVE_QUEUE)
  15059. static void
  15060. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15061. {
  15062. unsigned int i;
  15063. while (!ctx->stop_flag) {
  15064. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15065. /* find a free worker slot and signal it */
  15066. if (ctx->client_socks[i].in_use == 0) {
  15067. ctx->client_socks[i] = *sp;
  15068. ctx->client_socks[i].in_use = 1;
  15069. event_signal(ctx->client_wait_events[i]);
  15070. return;
  15071. }
  15072. }
  15073. /* queue is full */
  15074. mg_sleep(1);
  15075. }
  15076. }
  15077. static int
  15078. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15079. {
  15080. DEBUG_TRACE("%s", "going idle");
  15081. ctx->client_socks[thread_index].in_use = 0;
  15082. event_wait(ctx->client_wait_events[thread_index]);
  15083. *sp = ctx->client_socks[thread_index];
  15084. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15085. return !ctx->stop_flag;
  15086. }
  15087. #else /* ALTERNATIVE_QUEUE */
  15088. /* Worker threads take accepted socket from the queue */
  15089. static int
  15090. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15091. {
  15092. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15093. (void)thread_index;
  15094. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15095. DEBUG_TRACE("%s", "going idle");
  15096. /* If the queue is empty, wait. We're idle at this point. */
  15097. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15098. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15099. }
  15100. /* If we're stopping, sq_head may be equal to sq_tail. */
  15101. if (ctx->sq_head > ctx->sq_tail) {
  15102. /* Copy socket from the queue and increment tail */
  15103. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15104. ctx->sq_tail++;
  15105. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15106. /* Wrap pointers if needed */
  15107. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15108. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15109. ctx->sq_head -= QUEUE_SIZE(ctx);
  15110. }
  15111. }
  15112. (void)pthread_cond_signal(&ctx->sq_empty);
  15113. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15114. return !ctx->stop_flag;
  15115. #undef QUEUE_SIZE
  15116. }
  15117. /* Master thread adds accepted socket to a queue */
  15118. static void
  15119. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15120. {
  15121. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15122. if (!ctx) {
  15123. return;
  15124. }
  15125. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15126. /* If the queue is full, wait */
  15127. while ((ctx->stop_flag == 0)
  15128. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15129. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15130. }
  15131. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15132. /* Copy socket to the queue and increment head */
  15133. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15134. ctx->sq_head++;
  15135. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15136. }
  15137. (void)pthread_cond_signal(&ctx->sq_full);
  15138. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15139. #undef QUEUE_SIZE
  15140. }
  15141. #endif /* ALTERNATIVE_QUEUE */
  15142. struct worker_thread_args {
  15143. struct mg_context *ctx;
  15144. int index;
  15145. };
  15146. static void *
  15147. worker_thread_run(struct worker_thread_args *thread_args)
  15148. {
  15149. struct mg_context *ctx = thread_args->ctx;
  15150. struct mg_connection *conn;
  15151. struct mg_workerTLS tls;
  15152. #if defined(MG_LEGACY_INTERFACE)
  15153. uint32_t addr;
  15154. #endif
  15155. mg_set_thread_name("worker");
  15156. tls.is_master = 0;
  15157. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15158. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15159. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15160. #endif
  15161. /* Initialize thread local storage before calling any callback */
  15162. pthread_setspecific(sTlsKey, &tls);
  15163. if (ctx->callbacks.init_thread) {
  15164. /* call init_thread for a worker thread (type 1) */
  15165. ctx->callbacks.init_thread(ctx, 1);
  15166. }
  15167. /* Connection structure has been pre-allocated */
  15168. if (((int)thread_args->index < 0)
  15169. || ((unsigned)thread_args->index
  15170. >= (unsigned)ctx->cfg_worker_threads)) {
  15171. mg_cry_internal(fc(ctx),
  15172. "Internal error: Invalid worker index %i",
  15173. (int)thread_args->index);
  15174. return NULL;
  15175. }
  15176. conn = ctx->worker_connections + thread_args->index;
  15177. /* Request buffers are not pre-allocated. They are private to the
  15178. * request and do not contain any state information that might be
  15179. * of interest to anyone observing a server status. */
  15180. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15181. if (conn->buf == NULL) {
  15182. mg_cry_internal(fc(ctx),
  15183. "Out of memory: Cannot allocate buffer for worker %i",
  15184. (int)thread_args->index);
  15185. return NULL;
  15186. }
  15187. conn->buf_size = (int)ctx->max_request_size;
  15188. conn->phys_ctx = ctx;
  15189. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15190. conn->host = NULL; /* until we have more information. */
  15191. conn->thread_index = thread_args->index;
  15192. conn->request_info.user_data = ctx->user_data;
  15193. /* Allocate a mutex for this connection to allow communication both
  15194. * within the request handler and from elsewhere in the application
  15195. */
  15196. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15197. mg_free(conn->buf);
  15198. mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
  15199. return NULL;
  15200. }
  15201. #if defined(USE_SERVER_STATS)
  15202. conn->conn_state = 1; /* not consumed */
  15203. #endif
  15204. #if defined(ALTERNATIVE_QUEUE)
  15205. while ((ctx->stop_flag == 0)
  15206. && consume_socket(ctx, &conn->client, conn->thread_index)) {
  15207. #else
  15208. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15209. * signal sq_empty condvar to wake up the master waiting in
  15210. * produce_socket() */
  15211. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  15212. #endif
  15213. conn->conn_birth_time = time(NULL);
  15214. /* Fill in IP, port info early so even if SSL setup below fails,
  15215. * error handler would have the corresponding info.
  15216. * Thanks to Johannes Winkelmann for the patch.
  15217. */
  15218. #if defined(USE_IPV6)
  15219. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15220. conn->request_info.remote_port =
  15221. ntohs(conn->client.rsa.sin6.sin6_port);
  15222. } else
  15223. #endif
  15224. {
  15225. conn->request_info.remote_port =
  15226. ntohs(conn->client.rsa.sin.sin_port);
  15227. }
  15228. sockaddr_to_string(conn->request_info.remote_addr,
  15229. sizeof(conn->request_info.remote_addr),
  15230. &conn->client.rsa);
  15231. DEBUG_TRACE("Start processing connection from %s",
  15232. conn->request_info.remote_addr);
  15233. conn->request_info.is_ssl = conn->client.is_ssl;
  15234. if (conn->client.is_ssl) {
  15235. #if !defined(NO_SSL)
  15236. /* HTTPS connection */
  15237. if (sslize(conn,
  15238. conn->dom_ctx->ssl_ctx,
  15239. SSL_accept,
  15240. &(conn->phys_ctx->stop_flag))) {
  15241. /* conn->dom_ctx is set in get_request */
  15242. /* Get SSL client certificate information (if set) */
  15243. ssl_get_client_cert_info(conn);
  15244. /* process HTTPS connection */
  15245. process_new_connection(conn);
  15246. /* Free client certificate info */
  15247. if (conn->request_info.client_cert) {
  15248. mg_free((void *)(conn->request_info.client_cert->subject));
  15249. mg_free((void *)(conn->request_info.client_cert->issuer));
  15250. mg_free((void *)(conn->request_info.client_cert->serial));
  15251. mg_free((void *)(conn->request_info.client_cert->finger));
  15252. /* Free certificate memory */
  15253. X509_free(
  15254. (X509 *)conn->request_info.client_cert->peer_cert);
  15255. conn->request_info.client_cert->peer_cert = 0;
  15256. conn->request_info.client_cert->subject = 0;
  15257. conn->request_info.client_cert->issuer = 0;
  15258. conn->request_info.client_cert->serial = 0;
  15259. conn->request_info.client_cert->finger = 0;
  15260. mg_free(conn->request_info.client_cert);
  15261. conn->request_info.client_cert = 0;
  15262. }
  15263. }
  15264. #endif
  15265. } else {
  15266. /* process HTTP connection */
  15267. process_new_connection(conn);
  15268. }
  15269. DEBUG_TRACE("%s", "Connection closed");
  15270. }
  15271. pthread_setspecific(sTlsKey, NULL);
  15272. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15273. CloseHandle(tls.pthread_cond_helper_mutex);
  15274. #endif
  15275. pthread_mutex_destroy(&conn->mutex);
  15276. /* Free the request buffer. */
  15277. conn->buf_size = 0;
  15278. mg_free(conn->buf);
  15279. conn->buf = NULL;
  15280. #if defined(USE_SERVER_STATS)
  15281. conn->conn_state = 9; /* done */
  15282. #endif
  15283. DEBUG_TRACE("%s", "exiting");
  15284. return NULL;
  15285. }
  15286. /* Threads have different return types on Windows and Unix. */
  15287. #if defined(_WIN32)
  15288. static unsigned __stdcall worker_thread(void *thread_func_param)
  15289. {
  15290. struct worker_thread_args *pwta =
  15291. (struct worker_thread_args *)thread_func_param;
  15292. worker_thread_run(pwta);
  15293. mg_free(thread_func_param);
  15294. return 0;
  15295. }
  15296. #else
  15297. static void *
  15298. worker_thread(void *thread_func_param)
  15299. {
  15300. struct worker_thread_args *pwta =
  15301. (struct worker_thread_args *)thread_func_param;
  15302. struct sigaction sa;
  15303. /* Ignore SIGPIPE */
  15304. memset(&sa, 0, sizeof(sa));
  15305. sa.sa_handler = SIG_IGN;
  15306. sigaction(SIGPIPE, &sa, NULL);
  15307. worker_thread_run(pwta);
  15308. mg_free(thread_func_param);
  15309. return NULL;
  15310. }
  15311. #endif /* _WIN32 */
  15312. /* This is an internal function, thus all arguments are expected to be
  15313. * valid - a NULL check is not required. */
  15314. static void
  15315. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15316. {
  15317. struct socket so;
  15318. char src_addr[IP_ADDR_STR_LEN];
  15319. socklen_t len = sizeof(so.rsa);
  15320. int on = 1;
  15321. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15322. == INVALID_SOCKET) {
  15323. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15324. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15325. mg_cry_internal(fc(ctx),
  15326. "%s: %s is not allowed to connect",
  15327. __func__,
  15328. src_addr);
  15329. closesocket(so.sock);
  15330. } else {
  15331. /* Put so socket structure into the queue */
  15332. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15333. set_close_on_exec(so.sock, fc(ctx));
  15334. so.is_ssl = listener->is_ssl;
  15335. so.ssl_redir = listener->ssl_redir;
  15336. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15337. mg_cry_internal(fc(ctx),
  15338. "%s: getsockname() failed: %s",
  15339. __func__,
  15340. strerror(ERRNO));
  15341. }
  15342. /* Set TCP keep-alive. This is needed because if HTTP-level
  15343. * keep-alive
  15344. * is enabled, and client resets the connection, server won't get
  15345. * TCP FIN or RST and will keep the connection open forever. With
  15346. * TCP keep-alive, next keep-alive handshake will figure out that
  15347. * the client is down and will close the server end.
  15348. * Thanks to Igor Klopov who suggested the patch. */
  15349. if (setsockopt(so.sock,
  15350. SOL_SOCKET,
  15351. SO_KEEPALIVE,
  15352. (SOCK_OPT_TYPE)&on,
  15353. sizeof(on)) != 0) {
  15354. mg_cry_internal(
  15355. fc(ctx),
  15356. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15357. __func__,
  15358. strerror(ERRNO));
  15359. }
  15360. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15361. * to effectively fill up the underlying IP packet payload and
  15362. * reduce the overhead of sending lots of small buffers. However
  15363. * this hurts the server's throughput (ie. operations per second)
  15364. * when HTTP 1.1 persistent connections are used and the responses
  15365. * are relatively small (eg. less than 1400 bytes).
  15366. */
  15367. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15368. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15369. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15370. mg_cry_internal(
  15371. fc(ctx),
  15372. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15373. __func__,
  15374. strerror(ERRNO));
  15375. }
  15376. }
  15377. /* We are using non-blocking sockets. Thus, the
  15378. * set_sock_timeout(so.sock, timeout);
  15379. * call is no longer required. */
  15380. /* The "non blocking" property should already be
  15381. * inherited from the parent socket. Set it for
  15382. * non-compliant socket implementations. */
  15383. set_non_blocking_mode(so.sock);
  15384. so.in_use = 0;
  15385. produce_socket(ctx, &so);
  15386. }
  15387. }
  15388. static void
  15389. master_thread_run(void *thread_func_param)
  15390. {
  15391. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  15392. struct mg_workerTLS tls;
  15393. struct pollfd *pfd;
  15394. unsigned int i;
  15395. unsigned int workerthreadcount;
  15396. if (!ctx) {
  15397. return;
  15398. }
  15399. mg_set_thread_name("master");
  15400. /* Increase priority of the master thread */
  15401. #if defined(_WIN32)
  15402. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15403. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15404. int min_prio = sched_get_priority_min(SCHED_RR);
  15405. int max_prio = sched_get_priority_max(SCHED_RR);
  15406. if ((min_prio >= 0) && (max_prio >= 0)
  15407. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15408. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15409. struct sched_param sched_param = {0};
  15410. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15411. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15412. }
  15413. #endif
  15414. /* Initialize thread local storage */
  15415. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15416. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15417. #endif
  15418. tls.is_master = 1;
  15419. pthread_setspecific(sTlsKey, &tls);
  15420. if (ctx->callbacks.init_thread) {
  15421. /* Callback for the master thread (type 0) */
  15422. ctx->callbacks.init_thread(ctx, 0);
  15423. }
  15424. /* Server starts *now* */
  15425. ctx->start_time = time(NULL);
  15426. /* Start the server */
  15427. pfd = ctx->listening_socket_fds;
  15428. while (ctx->stop_flag == 0) {
  15429. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15430. pfd[i].fd = ctx->listening_sockets[i].sock;
  15431. pfd[i].events = POLLIN;
  15432. }
  15433. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15434. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15435. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15436. * successful poll, and POLLIN is defined as
  15437. * (POLLRDNORM | POLLRDBAND)
  15438. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15439. * pfd[i].revents == POLLIN. */
  15440. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15441. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15442. }
  15443. }
  15444. }
  15445. }
  15446. /* Here stop_flag is 1 - Initiate shutdown. */
  15447. DEBUG_TRACE("%s", "stopping workers");
  15448. /* Stop signal received: somebody called mg_stop. Quit. */
  15449. close_all_listening_sockets(ctx);
  15450. /* Wakeup workers that are waiting for connections to handle. */
  15451. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15452. #if defined(ALTERNATIVE_QUEUE)
  15453. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15454. event_signal(ctx->client_wait_events[i]);
  15455. /* Since we know all sockets, we can shutdown the connections. */
  15456. if (ctx->client_socks[i].in_use) {
  15457. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  15458. }
  15459. }
  15460. #else
  15461. pthread_cond_broadcast(&ctx->sq_full);
  15462. #endif
  15463. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15464. /* Join all worker threads to avoid leaking threads. */
  15465. workerthreadcount = ctx->cfg_worker_threads;
  15466. for (i = 0; i < workerthreadcount; i++) {
  15467. if (ctx->worker_threadids[i] != 0) {
  15468. mg_join_thread(ctx->worker_threadids[i]);
  15469. }
  15470. }
  15471. #if defined(USE_LUA)
  15472. /* Free Lua state of lua background task */
  15473. if (ctx->lua_background_state) {
  15474. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15475. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15476. if (lua_istable(lstate, -1)) {
  15477. reg_boolean(lstate, "shutdown", 1);
  15478. lua_pop(lstate, 1);
  15479. mg_sleep(2);
  15480. }
  15481. lua_close(lstate);
  15482. ctx->lua_background_state = 0;
  15483. }
  15484. #endif
  15485. DEBUG_TRACE("%s", "exiting");
  15486. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15487. CloseHandle(tls.pthread_cond_helper_mutex);
  15488. #endif
  15489. pthread_setspecific(sTlsKey, NULL);
  15490. /* Signal mg_stop() that we're done.
  15491. * WARNING: This must be the very last thing this
  15492. * thread does, as ctx becomes invalid after this line. */
  15493. ctx->stop_flag = 2;
  15494. }
  15495. /* Threads have different return types on Windows and Unix. */
  15496. #if defined(_WIN32)
  15497. static unsigned __stdcall master_thread(void *thread_func_param)
  15498. {
  15499. master_thread_run(thread_func_param);
  15500. return 0;
  15501. }
  15502. #else
  15503. static void *
  15504. master_thread(void *thread_func_param)
  15505. {
  15506. struct sigaction sa;
  15507. /* Ignore SIGPIPE */
  15508. memset(&sa, 0, sizeof(sa));
  15509. sa.sa_handler = SIG_IGN;
  15510. sigaction(SIGPIPE, &sa, NULL);
  15511. master_thread_run(thread_func_param);
  15512. return NULL;
  15513. }
  15514. #endif /* _WIN32 */
  15515. static void
  15516. free_context(struct mg_context *ctx)
  15517. {
  15518. int i;
  15519. struct mg_handler_info *tmp_rh;
  15520. if (ctx == NULL) {
  15521. return;
  15522. }
  15523. if (ctx->callbacks.exit_context) {
  15524. ctx->callbacks.exit_context(ctx);
  15525. }
  15526. /* All threads exited, no sync is needed. Destroy thread mutex and
  15527. * condvars
  15528. */
  15529. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15530. #if defined(ALTERNATIVE_QUEUE)
  15531. mg_free(ctx->client_socks);
  15532. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15533. event_destroy(ctx->client_wait_events[i]);
  15534. }
  15535. mg_free(ctx->client_wait_events);
  15536. #else
  15537. (void)pthread_cond_destroy(&ctx->sq_empty);
  15538. (void)pthread_cond_destroy(&ctx->sq_full);
  15539. #endif
  15540. /* Destroy other context global data structures mutex */
  15541. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15542. #if defined(USE_TIMERS)
  15543. timers_exit(ctx);
  15544. #endif
  15545. /* Deallocate config parameters */
  15546. for (i = 0; i < NUM_OPTIONS; i++) {
  15547. if (ctx->dd.config[i] != NULL) {
  15548. #if defined(_MSC_VER)
  15549. #pragma warning(suppress : 6001)
  15550. #endif
  15551. mg_free(ctx->dd.config[i]);
  15552. }
  15553. }
  15554. /* Deallocate request handlers */
  15555. while (ctx->dd.handlers) {
  15556. tmp_rh = ctx->dd.handlers;
  15557. ctx->dd.handlers = tmp_rh->next;
  15558. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15559. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15560. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15561. }
  15562. mg_free(tmp_rh->uri);
  15563. mg_free(tmp_rh);
  15564. }
  15565. #if !defined(NO_SSL)
  15566. /* Deallocate SSL context */
  15567. if (ctx->dd.ssl_ctx != NULL) {
  15568. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15569. int callback_ret =
  15570. (ctx->callbacks.external_ssl_ctx == NULL)
  15571. ? 0
  15572. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15573. if (callback_ret == 0) {
  15574. SSL_CTX_free(ctx->dd.ssl_ctx);
  15575. }
  15576. /* else: ignore error and ommit SSL_CTX_free in case
  15577. * callback_ret is 1 */
  15578. }
  15579. #endif /* !NO_SSL */
  15580. /* Deallocate worker thread ID array */
  15581. if (ctx->worker_threadids != NULL) {
  15582. mg_free(ctx->worker_threadids);
  15583. }
  15584. /* Deallocate worker thread ID array */
  15585. if (ctx->worker_connections != NULL) {
  15586. mg_free(ctx->worker_connections);
  15587. }
  15588. /* deallocate system name string */
  15589. mg_free(ctx->systemName);
  15590. /* Deallocate context itself */
  15591. mg_free(ctx);
  15592. }
  15593. void
  15594. mg_stop(struct mg_context *ctx)
  15595. {
  15596. pthread_t mt;
  15597. if (!ctx) {
  15598. return;
  15599. }
  15600. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15601. * two threads is not allowed. */
  15602. mt = ctx->masterthreadid;
  15603. if (mt == 0) {
  15604. return;
  15605. }
  15606. ctx->masterthreadid = 0;
  15607. /* Set stop flag, so all threads know they have to exit. */
  15608. ctx->stop_flag = 1;
  15609. /* Wait until everything has stopped. */
  15610. while (ctx->stop_flag != 2) {
  15611. (void)mg_sleep(10);
  15612. }
  15613. mg_join_thread(mt);
  15614. free_context(ctx);
  15615. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15616. (void)WSACleanup();
  15617. #endif /* _WIN32 && !__SYMBIAN32__ */
  15618. }
  15619. static void
  15620. get_system_name(char **sysName)
  15621. {
  15622. #if defined(_WIN32)
  15623. #if !defined(__SYMBIAN32__)
  15624. #if defined(_WIN32_WCE)
  15625. *sysName = mg_strdup("WinCE");
  15626. #else
  15627. char name[128];
  15628. DWORD dwVersion = 0;
  15629. DWORD dwMajorVersion = 0;
  15630. DWORD dwMinorVersion = 0;
  15631. DWORD dwBuild = 0;
  15632. BOOL wowRet, isWoW = FALSE;
  15633. #if defined(_MSC_VER)
  15634. #pragma warning(push)
  15635. /* GetVersion was declared deprecated */
  15636. #pragma warning(disable : 4996)
  15637. #endif
  15638. dwVersion = GetVersion();
  15639. #if defined(_MSC_VER)
  15640. #pragma warning(pop)
  15641. #endif
  15642. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15643. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15644. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15645. (void)dwBuild;
  15646. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15647. sprintf(name,
  15648. "Windows %u.%u%s",
  15649. (unsigned)dwMajorVersion,
  15650. (unsigned)dwMinorVersion,
  15651. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15652. *sysName = mg_strdup(name);
  15653. #endif
  15654. #else
  15655. *sysName = mg_strdup("Symbian");
  15656. #endif
  15657. #else
  15658. struct utsname name;
  15659. memset(&name, 0, sizeof(name));
  15660. uname(&name);
  15661. *sysName = mg_strdup(name.sysname);
  15662. #endif
  15663. }
  15664. struct mg_context *
  15665. mg_start(const struct mg_callbacks *callbacks,
  15666. void *user_data,
  15667. const char **options)
  15668. {
  15669. struct mg_context *ctx;
  15670. const char *name, *value, *default_value;
  15671. int idx, ok, workerthreadcount;
  15672. unsigned int i;
  15673. int itmp;
  15674. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15675. struct mg_workerTLS tls;
  15676. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15677. WSADATA data;
  15678. WSAStartup(MAKEWORD(2, 2), &data);
  15679. #endif /* _WIN32 && !__SYMBIAN32__ */
  15680. /* Allocate context and initialize reasonable general case defaults. */
  15681. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15682. return NULL;
  15683. }
  15684. /* Random number generator will initialize at the first call */
  15685. ctx->dd.auth_nonce_mask =
  15686. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15687. if (mg_init_library_called == 0) {
  15688. /* Legacy INIT, if mg_start is called without mg_init_library.
  15689. * Note: This may cause a memory leak */
  15690. const char *ports_option =
  15691. config_options[LISTENING_PORTS].default_value;
  15692. if (options) {
  15693. const char **run_options = options;
  15694. const char *optname = config_options[LISTENING_PORTS].name;
  15695. /* Try to find the "listening_ports" option */
  15696. while (*run_options) {
  15697. if (!strcmp(*run_options, optname)) {
  15698. ports_option = run_options[1];
  15699. }
  15700. run_options += 2;
  15701. }
  15702. }
  15703. if (is_ssl_port_used(ports_option)) {
  15704. /* Initialize with SSL support */
  15705. mg_init_library(MG_FEATURES_TLS);
  15706. } else {
  15707. /* Initialize without SSL support */
  15708. mg_init_library(MG_FEATURES_DEFAULT);
  15709. }
  15710. }
  15711. tls.is_master = -1;
  15712. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15713. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15714. tls.pthread_cond_helper_mutex = NULL;
  15715. #endif
  15716. pthread_setspecific(sTlsKey, &tls);
  15717. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15718. #if !defined(ALTERNATIVE_QUEUE)
  15719. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15720. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15721. #endif
  15722. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15723. if (!ok) {
  15724. /* Fatal error - abort start. However, this situation should never
  15725. * occur in practice. */
  15726. mg_cry_internal(fc(ctx),
  15727. "%s",
  15728. "Cannot initialize thread synchronization objects");
  15729. mg_free(ctx);
  15730. pthread_setspecific(sTlsKey, NULL);
  15731. return NULL;
  15732. }
  15733. if (callbacks) {
  15734. ctx->callbacks = *callbacks;
  15735. exit_callback = callbacks->exit_context;
  15736. ctx->callbacks.exit_context = 0;
  15737. }
  15738. ctx->user_data = user_data;
  15739. ctx->dd.handlers = NULL;
  15740. ctx->dd.next = NULL;
  15741. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15742. ctx->dd.shared_lua_websockets = NULL;
  15743. #endif
  15744. /* Store options */
  15745. while (options && (name = *options++) != NULL) {
  15746. if ((idx = get_option_index(name)) == -1) {
  15747. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15748. free_context(ctx);
  15749. pthread_setspecific(sTlsKey, NULL);
  15750. return NULL;
  15751. } else if ((value = *options++) == NULL) {
  15752. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15753. free_context(ctx);
  15754. pthread_setspecific(sTlsKey, NULL);
  15755. return NULL;
  15756. }
  15757. if (ctx->dd.config[idx] != NULL) {
  15758. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15759. mg_free(ctx->dd.config[idx]);
  15760. }
  15761. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15762. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15763. }
  15764. /* Set default value if needed */
  15765. for (i = 0; config_options[i].name != NULL; i++) {
  15766. default_value = config_options[i].default_value;
  15767. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15768. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15769. }
  15770. }
  15771. /* Request size option */
  15772. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15773. if (itmp < 1024) {
  15774. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15775. free_context(ctx);
  15776. pthread_setspecific(sTlsKey, NULL);
  15777. return NULL;
  15778. }
  15779. ctx->max_request_size = (unsigned)itmp;
  15780. /* Worker thread count option */
  15781. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15782. if (workerthreadcount > MAX_WORKER_THREADS) {
  15783. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15784. free_context(ctx);
  15785. pthread_setspecific(sTlsKey, NULL);
  15786. return NULL;
  15787. }
  15788. if (workerthreadcount <= 0) {
  15789. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15790. free_context(ctx);
  15791. pthread_setspecific(sTlsKey, NULL);
  15792. return NULL;
  15793. }
  15794. /* Document root */
  15795. #if defined(NO_FILES)
  15796. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15797. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15798. free_context(ctx);
  15799. pthread_setspecific(sTlsKey, NULL);
  15800. return NULL;
  15801. }
  15802. #endif
  15803. get_system_name(&ctx->systemName);
  15804. #if defined(USE_LUA)
  15805. /* If a Lua background script has been configured, start it. */
  15806. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15807. char ebuf[256];
  15808. struct vec opt_vec;
  15809. struct vec eq_vec;
  15810. const char *sparams;
  15811. lua_State *state = mg_prepare_lua_context_script(
  15812. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15813. if (!state) {
  15814. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15815. free_context(ctx);
  15816. pthread_setspecific(sTlsKey, NULL);
  15817. return NULL;
  15818. }
  15819. ctx->lua_background_state = (void *)state;
  15820. lua_newtable(state);
  15821. reg_boolean(state, "shutdown", 0);
  15822. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15823. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15824. reg_llstring(
  15825. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15826. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15827. break;
  15828. }
  15829. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15830. } else {
  15831. ctx->lua_background_state = 0;
  15832. }
  15833. #endif
  15834. /* NOTE(lsm): order is important here. SSL certificates must
  15835. * be initialized before listening ports. UID must be set last. */
  15836. if (!set_gpass_option(ctx, NULL) ||
  15837. #if !defined(NO_SSL)
  15838. !init_ssl_ctx(ctx, NULL) ||
  15839. #endif
  15840. !set_ports_option(ctx) ||
  15841. #if !defined(_WIN32)
  15842. !set_uid_option(ctx) ||
  15843. #endif
  15844. !set_acl_option(ctx)) {
  15845. free_context(ctx);
  15846. pthread_setspecific(sTlsKey, NULL);
  15847. return NULL;
  15848. }
  15849. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  15850. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15851. sizeof(pthread_t),
  15852. ctx);
  15853. if (ctx->worker_threadids == NULL) {
  15854. mg_cry_internal(fc(ctx),
  15855. "%s",
  15856. "Not enough memory for worker thread ID array");
  15857. free_context(ctx);
  15858. pthread_setspecific(sTlsKey, NULL);
  15859. return NULL;
  15860. }
  15861. ctx->worker_connections =
  15862. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15863. sizeof(struct mg_connection),
  15864. ctx);
  15865. if (ctx->worker_connections == NULL) {
  15866. mg_cry_internal(fc(ctx),
  15867. "%s",
  15868. "Not enough memory for worker thread connection array");
  15869. free_context(ctx);
  15870. pthread_setspecific(sTlsKey, NULL);
  15871. return NULL;
  15872. }
  15873. #if defined(ALTERNATIVE_QUEUE)
  15874. ctx->client_wait_events =
  15875. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  15876. ctx->cfg_worker_threads,
  15877. ctx);
  15878. if (ctx->client_wait_events == NULL) {
  15879. mg_cry_internal(fc(ctx),
  15880. "%s",
  15881. "Not enough memory for worker event array");
  15882. mg_free(ctx->worker_threadids);
  15883. free_context(ctx);
  15884. pthread_setspecific(sTlsKey, NULL);
  15885. return NULL;
  15886. }
  15887. ctx->client_socks =
  15888. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  15889. ctx->cfg_worker_threads,
  15890. ctx);
  15891. if (ctx->client_socks == NULL) {
  15892. mg_cry_internal(fc(ctx),
  15893. "%s",
  15894. "Not enough memory for worker socket array");
  15895. mg_free(ctx->client_wait_events);
  15896. mg_free(ctx->worker_threadids);
  15897. free_context(ctx);
  15898. pthread_setspecific(sTlsKey, NULL);
  15899. return NULL;
  15900. }
  15901. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15902. ctx->client_wait_events[i] = event_create();
  15903. if (ctx->client_wait_events[i] == 0) {
  15904. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  15905. while (i > 0) {
  15906. i--;
  15907. event_destroy(ctx->client_wait_events[i]);
  15908. }
  15909. mg_free(ctx->client_socks);
  15910. mg_free(ctx->client_wait_events);
  15911. mg_free(ctx->worker_threadids);
  15912. free_context(ctx);
  15913. pthread_setspecific(sTlsKey, NULL);
  15914. return NULL;
  15915. }
  15916. }
  15917. #endif
  15918. #if defined(USE_TIMERS)
  15919. if (timers_init(ctx) != 0) {
  15920. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  15921. free_context(ctx);
  15922. pthread_setspecific(sTlsKey, NULL);
  15923. return NULL;
  15924. }
  15925. #endif
  15926. /* Context has been created - init user libraries */
  15927. if (ctx->callbacks.init_context) {
  15928. ctx->callbacks.init_context(ctx);
  15929. }
  15930. ctx->callbacks.exit_context = exit_callback;
  15931. ctx->context_type = CONTEXT_SERVER; /* server context */
  15932. /* Start master (listening) thread */
  15933. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  15934. /* Start worker threads */
  15935. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15936. struct worker_thread_args *wta = (struct worker_thread_args *)
  15937. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  15938. if (wta) {
  15939. wta->ctx = ctx;
  15940. wta->index = (int)i;
  15941. }
  15942. if ((wta == NULL)
  15943. || (mg_start_thread_with_id(worker_thread,
  15944. wta,
  15945. &ctx->worker_threadids[i]) != 0)) {
  15946. /* thread was not created */
  15947. if (wta != NULL) {
  15948. mg_free(wta);
  15949. }
  15950. if (i > 0) {
  15951. mg_cry_internal(fc(ctx),
  15952. "Cannot start worker thread %i: error %ld",
  15953. i + 1,
  15954. (long)ERRNO);
  15955. } else {
  15956. mg_cry_internal(fc(ctx),
  15957. "Cannot create threads: error %ld",
  15958. (long)ERRNO);
  15959. free_context(ctx);
  15960. pthread_setspecific(sTlsKey, NULL);
  15961. return NULL;
  15962. }
  15963. break;
  15964. }
  15965. }
  15966. pthread_setspecific(sTlsKey, NULL);
  15967. return ctx;
  15968. }
  15969. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15970. /* Add an additional domain to an already running web server. */
  15971. int
  15972. mg_start_domain(struct mg_context *ctx, const char **options)
  15973. {
  15974. const char *name;
  15975. const char *value;
  15976. const char *default_value;
  15977. struct mg_domain_context *new_dom;
  15978. struct mg_domain_context *dom;
  15979. int idx, i;
  15980. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  15981. return -1;
  15982. }
  15983. new_dom = (struct mg_domain_context *)
  15984. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  15985. if (!new_dom) {
  15986. /* Out of memory */
  15987. return -6;
  15988. }
  15989. /* Store options - TODO: unite duplicate code */
  15990. while (options && (name = *options++) != NULL) {
  15991. if ((idx = get_option_index(name)) == -1) {
  15992. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15993. mg_free(new_dom);
  15994. return -2;
  15995. } else if ((value = *options++) == NULL) {
  15996. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15997. mg_free(new_dom);
  15998. return -2;
  15999. }
  16000. if (new_dom->config[idx] != NULL) {
  16001. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16002. mg_free(new_dom->config[idx]);
  16003. }
  16004. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16005. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16006. }
  16007. /* Authentication domain is mandatory */
  16008. /* TODO: Maybe use a new option hostname? */
  16009. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16010. mg_cry_internal(fc(ctx), "%s", "authentication domain required");
  16011. mg_free(new_dom);
  16012. return -4;
  16013. }
  16014. /* Set default value if needed. Take the config value from
  16015. * ctx as a default value. */
  16016. for (i = 0; config_options[i].name != NULL; i++) {
  16017. default_value = ctx->dd.config[i];
  16018. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16019. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16020. }
  16021. }
  16022. new_dom->handlers = NULL;
  16023. new_dom->next = NULL;
  16024. new_dom->nonce_count = 0;
  16025. new_dom->auth_nonce_mask =
  16026. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16027. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16028. new_dom->shared_lua_websockets = NULL;
  16029. #endif
  16030. if (!init_ssl_ctx(ctx, new_dom)) {
  16031. /* Init SSL failed */
  16032. mg_free(new_dom);
  16033. return -3;
  16034. }
  16035. /* Add element to linked list. */
  16036. mg_lock_context(ctx);
  16037. idx = 0;
  16038. dom = &(ctx->dd);
  16039. for (;;) {
  16040. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16041. dom->config[AUTHENTICATION_DOMAIN])) {
  16042. /* Domain collision */
  16043. mg_cry_internal(fc(ctx),
  16044. "domain %s already in use",
  16045. new_dom->config[AUTHENTICATION_DOMAIN]);
  16046. mg_free(new_dom);
  16047. return -5;
  16048. }
  16049. /* Count number of domains */
  16050. idx++;
  16051. if (dom->next == NULL) {
  16052. dom->next = new_dom;
  16053. break;
  16054. }
  16055. dom = dom->next;
  16056. }
  16057. mg_unlock_context(ctx);
  16058. /* Return domain number */
  16059. return idx;
  16060. }
  16061. #endif
  16062. /* Feature check API function */
  16063. unsigned
  16064. mg_check_feature(unsigned feature)
  16065. {
  16066. static const unsigned feature_set = 0
  16067. /* Set bits for available features according to API documentation.
  16068. * This bit mask is created at compile time, according to the active
  16069. * preprocessor defines. It is a single const value at runtime. */
  16070. #if !defined(NO_FILES)
  16071. | MG_FEATURES_FILES
  16072. #endif
  16073. #if !defined(NO_SSL)
  16074. | MG_FEATURES_SSL
  16075. #endif
  16076. #if !defined(NO_CGI)
  16077. | MG_FEATURES_CGI
  16078. #endif
  16079. #if defined(USE_IPV6)
  16080. | MG_FEATURES_IPV6
  16081. #endif
  16082. #if defined(USE_WEBSOCKET)
  16083. | MG_FEATURES_WEBSOCKET
  16084. #endif
  16085. #if defined(USE_LUA)
  16086. | MG_FEATURES_LUA
  16087. #endif
  16088. #if defined(USE_DUKTAPE)
  16089. | MG_FEATURES_SSJS
  16090. #endif
  16091. #if !defined(NO_CACHING)
  16092. | MG_FEATURES_CACHE
  16093. #endif
  16094. #if defined(USE_SERVER_STATS)
  16095. | MG_FEATURES_STATS
  16096. #endif
  16097. #if defined(USE_ZLIB)
  16098. | MG_FEATURES_COMPRESSION
  16099. #endif
  16100. /* Set some extra bits not defined in the API documentation.
  16101. * These bits may change without further notice. */
  16102. #if defined(MG_LEGACY_INTERFACE)
  16103. | 0x00008000u
  16104. #endif
  16105. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16106. | 0x00004000u
  16107. #endif
  16108. #if defined(MEMORY_DEBUGGING)
  16109. | 0x00001000u
  16110. #endif
  16111. #if defined(USE_TIMERS)
  16112. | 0x00020000u
  16113. #endif
  16114. #if !defined(NO_NONCE_CHECK)
  16115. | 0x00040000u
  16116. #endif
  16117. #if !defined(NO_POPEN)
  16118. | 0x00080000u
  16119. #endif
  16120. ;
  16121. return (feature & feature_set);
  16122. }
  16123. /* strcat with additional NULL check to avoid clang scan-build warning. */
  16124. #define strcat0(a, b) \
  16125. { \
  16126. if ((a != NULL) && (b != NULL)) { \
  16127. strcat(a, b); \
  16128. } \
  16129. }
  16130. /* Get system information. It can be printed or stored by the caller.
  16131. * Return the size of available information. */
  16132. static int
  16133. mg_get_system_info_impl(char *buffer, int buflen)
  16134. {
  16135. char block[256];
  16136. int system_info_length = 0;
  16137. #if defined(_WIN32)
  16138. const char *eol = "\r\n";
  16139. #else
  16140. const char *eol = "\n";
  16141. #endif
  16142. const char *eoobj = "}";
  16143. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16144. if ((buffer == NULL) || (buflen < 1)) {
  16145. buflen = 0;
  16146. } else {
  16147. *buffer = 0;
  16148. }
  16149. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16150. system_info_length += (int)strlen(block);
  16151. if (system_info_length < buflen) {
  16152. strcat0(buffer, block);
  16153. }
  16154. /* Server version */
  16155. {
  16156. const char *version = mg_version();
  16157. mg_snprintf(NULL,
  16158. NULL,
  16159. block,
  16160. sizeof(block),
  16161. "\"version\" : \"%s\",%s",
  16162. version,
  16163. eol);
  16164. system_info_length += (int)strlen(block);
  16165. if (system_info_length < buflen) {
  16166. strcat0(buffer, block);
  16167. }
  16168. }
  16169. /* System info */
  16170. {
  16171. #if defined(_WIN32)
  16172. #if !defined(__SYMBIAN32__)
  16173. DWORD dwVersion = 0;
  16174. DWORD dwMajorVersion = 0;
  16175. DWORD dwMinorVersion = 0;
  16176. SYSTEM_INFO si;
  16177. GetSystemInfo(&si);
  16178. #if defined(_MSC_VER)
  16179. #pragma warning(push)
  16180. /* GetVersion was declared deprecated */
  16181. #pragma warning(disable : 4996)
  16182. #endif
  16183. dwVersion = GetVersion();
  16184. #if defined(_MSC_VER)
  16185. #pragma warning(pop)
  16186. #endif
  16187. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16188. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16189. mg_snprintf(NULL,
  16190. NULL,
  16191. block,
  16192. sizeof(block),
  16193. "\"os\" : \"Windows %u.%u\",%s",
  16194. (unsigned)dwMajorVersion,
  16195. (unsigned)dwMinorVersion,
  16196. eol);
  16197. system_info_length += (int)strlen(block);
  16198. if (system_info_length < buflen) {
  16199. strcat0(buffer, block);
  16200. }
  16201. mg_snprintf(NULL,
  16202. NULL,
  16203. block,
  16204. sizeof(block),
  16205. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  16206. (unsigned)si.wProcessorArchitecture,
  16207. (unsigned)si.dwNumberOfProcessors,
  16208. (unsigned)si.dwActiveProcessorMask,
  16209. eol);
  16210. system_info_length += (int)strlen(block);
  16211. if (system_info_length < buflen) {
  16212. strcat0(buffer, block);
  16213. }
  16214. #else
  16215. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  16216. system_info_length += (int)strlen(block);
  16217. if (system_info_length < buflen) {
  16218. strcat0(buffer, block);
  16219. }
  16220. #endif
  16221. #else
  16222. struct utsname name;
  16223. memset(&name, 0, sizeof(name));
  16224. uname(&name);
  16225. mg_snprintf(NULL,
  16226. NULL,
  16227. block,
  16228. sizeof(block),
  16229. "\"os\" : \"%s %s (%s) - %s\",%s",
  16230. name.sysname,
  16231. name.version,
  16232. name.release,
  16233. name.machine,
  16234. eol);
  16235. system_info_length += (int)strlen(block);
  16236. if (system_info_length < buflen) {
  16237. strcat0(buffer, block);
  16238. }
  16239. #endif
  16240. }
  16241. /* Features */
  16242. {
  16243. mg_snprintf(NULL,
  16244. NULL,
  16245. block,
  16246. sizeof(block),
  16247. "\"features\" : %lu,%s"
  16248. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  16249. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16250. eol,
  16251. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16252. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16253. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16254. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16255. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16256. : "",
  16257. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16258. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16259. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16260. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  16261. eol);
  16262. system_info_length += (int)strlen(block);
  16263. if (system_info_length < buflen) {
  16264. strcat0(buffer, block);
  16265. }
  16266. #if defined(USE_LUA)
  16267. mg_snprintf(NULL,
  16268. NULL,
  16269. block,
  16270. sizeof(block),
  16271. "\"lua_version\" : \"%u (%s)\",%s",
  16272. (unsigned)LUA_VERSION_NUM,
  16273. LUA_RELEASE,
  16274. eol);
  16275. system_info_length += (int)strlen(block);
  16276. if (system_info_length < buflen) {
  16277. strcat0(buffer, block);
  16278. }
  16279. #endif
  16280. #if defined(USE_DUKTAPE)
  16281. mg_snprintf(NULL,
  16282. NULL,
  16283. block,
  16284. sizeof(block),
  16285. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  16286. (unsigned)DUK_VERSION / 10000,
  16287. ((unsigned)DUK_VERSION / 100) % 100,
  16288. (unsigned)DUK_VERSION % 100,
  16289. eol);
  16290. system_info_length += (int)strlen(block);
  16291. if (system_info_length < buflen) {
  16292. strcat0(buffer, block);
  16293. }
  16294. #endif
  16295. }
  16296. /* Build date */
  16297. {
  16298. #if defined(__GNUC__)
  16299. #pragma GCC diagnostic push
  16300. /* Disable bogus compiler warning -Wdate-time */
  16301. #pragma GCC diagnostic ignored "-Wdate-time"
  16302. #endif
  16303. mg_snprintf(NULL,
  16304. NULL,
  16305. block,
  16306. sizeof(block),
  16307. "\"build\" : \"%s\",%s",
  16308. __DATE__,
  16309. eol);
  16310. #if defined(__GNUC__)
  16311. #pragma GCC diagnostic pop
  16312. #endif
  16313. system_info_length += (int)strlen(block);
  16314. if (system_info_length < buflen) {
  16315. strcat0(buffer, block);
  16316. }
  16317. }
  16318. /* Compiler information */
  16319. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16320. {
  16321. #if defined(_MSC_VER)
  16322. mg_snprintf(NULL,
  16323. NULL,
  16324. block,
  16325. sizeof(block),
  16326. "\"compiler\" : \"MSC: %u (%u)\",%s",
  16327. (unsigned)_MSC_VER,
  16328. (unsigned)_MSC_FULL_VER,
  16329. eol);
  16330. system_info_length += (int)strlen(block);
  16331. if (system_info_length < buflen) {
  16332. strcat0(buffer, block);
  16333. }
  16334. #elif defined(__MINGW64__)
  16335. mg_snprintf(NULL,
  16336. NULL,
  16337. block,
  16338. sizeof(block),
  16339. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  16340. (unsigned)__MINGW64_VERSION_MAJOR,
  16341. (unsigned)__MINGW64_VERSION_MINOR,
  16342. eol);
  16343. system_info_length += (int)strlen(block);
  16344. if (system_info_length < buflen) {
  16345. strcat0(buffer, block);
  16346. }
  16347. mg_snprintf(NULL,
  16348. NULL,
  16349. block,
  16350. sizeof(block),
  16351. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16352. (unsigned)__MINGW32_MAJOR_VERSION,
  16353. (unsigned)__MINGW32_MINOR_VERSION,
  16354. eol);
  16355. system_info_length += (int)strlen(block);
  16356. if (system_info_length < buflen) {
  16357. strcat0(buffer, block);
  16358. }
  16359. #elif defined(__MINGW32__)
  16360. mg_snprintf(NULL,
  16361. NULL,
  16362. block,
  16363. sizeof(block),
  16364. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16365. (unsigned)__MINGW32_MAJOR_VERSION,
  16366. (unsigned)__MINGW32_MINOR_VERSION,
  16367. eol);
  16368. system_info_length += (int)strlen(block);
  16369. if (system_info_length < buflen) {
  16370. strcat0(buffer, block);
  16371. }
  16372. #elif defined(__clang__)
  16373. mg_snprintf(NULL,
  16374. NULL,
  16375. block,
  16376. sizeof(block),
  16377. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  16378. __clang_major__,
  16379. __clang_minor__,
  16380. __clang_patchlevel__,
  16381. __clang_version__,
  16382. eol);
  16383. system_info_length += (int)strlen(block);
  16384. if (system_info_length < buflen) {
  16385. strcat0(buffer, block);
  16386. }
  16387. #elif defined(__GNUC__)
  16388. mg_snprintf(NULL,
  16389. NULL,
  16390. block,
  16391. sizeof(block),
  16392. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  16393. (unsigned)__GNUC__,
  16394. (unsigned)__GNUC_MINOR__,
  16395. (unsigned)__GNUC_PATCHLEVEL__,
  16396. eol);
  16397. system_info_length += (int)strlen(block);
  16398. if (system_info_length < buflen) {
  16399. strcat0(buffer, block);
  16400. }
  16401. #elif defined(__INTEL_COMPILER)
  16402. mg_snprintf(NULL,
  16403. NULL,
  16404. block,
  16405. sizeof(block),
  16406. "\"compiler\" : \"Intel C/C++: %u\",%s",
  16407. (unsigned)__INTEL_COMPILER,
  16408. eol);
  16409. system_info_length += (int)strlen(block);
  16410. if (system_info_length < buflen) {
  16411. strcat0(buffer, block);
  16412. }
  16413. #elif defined(__BORLANDC__)
  16414. mg_snprintf(NULL,
  16415. NULL,
  16416. block,
  16417. sizeof(block),
  16418. "\"compiler\" : \"Borland C: 0x%x\",%s",
  16419. (unsigned)__BORLANDC__,
  16420. eol);
  16421. system_info_length += (int)strlen(block);
  16422. if (system_info_length < buflen) {
  16423. strcat0(buffer, block);
  16424. }
  16425. #elif defined(__SUNPRO_C)
  16426. mg_snprintf(NULL,
  16427. NULL,
  16428. block,
  16429. sizeof(block),
  16430. "\"compiler\" : \"Solaris: 0x%x\",%s",
  16431. (unsigned)__SUNPRO_C,
  16432. eol);
  16433. system_info_length += (int)strlen(block);
  16434. if (system_info_length < buflen) {
  16435. strcat0(buffer, block);
  16436. }
  16437. #else
  16438. mg_snprintf(NULL,
  16439. NULL,
  16440. block,
  16441. sizeof(block),
  16442. "\"compiler\" : \"other\",%s",
  16443. eol);
  16444. system_info_length += (int)strlen(block);
  16445. if (system_info_length < buflen) {
  16446. strcat0(buffer, block);
  16447. }
  16448. #endif
  16449. }
  16450. /* Determine 32/64 bit data mode.
  16451. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16452. {
  16453. mg_snprintf(NULL,
  16454. NULL,
  16455. block,
  16456. sizeof(block),
  16457. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16458. "char:%u/%u, "
  16459. "ptr:%u, size:%u, time:%u\"%s",
  16460. (unsigned)sizeof(short),
  16461. (unsigned)sizeof(int),
  16462. (unsigned)sizeof(long),
  16463. (unsigned)sizeof(long long),
  16464. (unsigned)sizeof(float),
  16465. (unsigned)sizeof(double),
  16466. (unsigned)sizeof(long double),
  16467. (unsigned)sizeof(char),
  16468. (unsigned)sizeof(wchar_t),
  16469. (unsigned)sizeof(void *),
  16470. (unsigned)sizeof(size_t),
  16471. (unsigned)sizeof(time_t),
  16472. eol);
  16473. system_info_length += (int)strlen(block);
  16474. if (system_info_length < buflen) {
  16475. strcat0(buffer, block);
  16476. }
  16477. }
  16478. /* Terminate string */
  16479. if ((buflen > 0) && buffer && buffer[0]) {
  16480. if (system_info_length < buflen) {
  16481. strcat0(buffer, eoobj);
  16482. strcat0(buffer, eol);
  16483. }
  16484. }
  16485. system_info_length += reserved_len;
  16486. return system_info_length;
  16487. }
  16488. #if defined(USE_SERVER_STATS)
  16489. /* Get context information. It can be printed or stored by the caller.
  16490. * Return the size of available information. */
  16491. static int
  16492. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  16493. {
  16494. char block[256];
  16495. int context_info_length = 0;
  16496. #if defined(_WIN32)
  16497. const char *eol = "\r\n";
  16498. #else
  16499. const char *eol = "\n";
  16500. #endif
  16501. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16502. const char *eoobj = "}";
  16503. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16504. if ((buffer == NULL) || (buflen < 1)) {
  16505. buflen = 0;
  16506. } else {
  16507. *buffer = 0;
  16508. }
  16509. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16510. context_info_length += (int)strlen(block);
  16511. if (context_info_length < buflen) {
  16512. strcat0(buffer, block);
  16513. }
  16514. if (ms) { /* <-- should be always true */
  16515. /* Memory information */
  16516. mg_snprintf(NULL,
  16517. NULL,
  16518. block,
  16519. sizeof(block),
  16520. "\"memory\" : {%s"
  16521. "\"blocks\" : %i,%s"
  16522. "\"used\" : %" INT64_FMT ",%s"
  16523. "\"maxUsed\" : %" INT64_FMT "%s"
  16524. "}%s%s",
  16525. eol,
  16526. ms->blockCount,
  16527. eol,
  16528. ms->totalMemUsed,
  16529. eol,
  16530. ms->maxMemUsed,
  16531. eol,
  16532. (ctx ? "," : ""),
  16533. eol);
  16534. context_info_length += (int)strlen(block);
  16535. if (context_info_length + reserved_len < buflen) {
  16536. strcat0(buffer, block);
  16537. }
  16538. }
  16539. if (ctx) {
  16540. /* Declare all variables at begin of the block, to comply
  16541. * with old C standards. */
  16542. char start_time_str[64] = {0};
  16543. char now_str[64] = {0};
  16544. time_t start_time = ctx->start_time;
  16545. time_t now = time(NULL);
  16546. /* Connections information */
  16547. mg_snprintf(NULL,
  16548. NULL,
  16549. block,
  16550. sizeof(block),
  16551. "\"connections\" : {%s"
  16552. "\"active\" : %i,%s"
  16553. "\"maxActive\" : %i,%s"
  16554. "\"total\" : %" INT64_FMT "%s"
  16555. "},%s",
  16556. eol,
  16557. ctx->active_connections,
  16558. eol,
  16559. ctx->max_connections,
  16560. eol,
  16561. ctx->total_connections,
  16562. eol,
  16563. eol);
  16564. context_info_length += (int)strlen(block);
  16565. if (context_info_length + reserved_len < buflen) {
  16566. strcat0(buffer, block);
  16567. }
  16568. /* Requests information */
  16569. mg_snprintf(NULL,
  16570. NULL,
  16571. block,
  16572. sizeof(block),
  16573. "\"requests\" : {%s"
  16574. "\"total\" : %" INT64_FMT "%s"
  16575. "},%s",
  16576. eol,
  16577. ctx->total_requests,
  16578. eol,
  16579. eol);
  16580. context_info_length += (int)strlen(block);
  16581. if (context_info_length + reserved_len < buflen) {
  16582. strcat0(buffer, block);
  16583. }
  16584. /* Data information */
  16585. mg_snprintf(NULL,
  16586. NULL,
  16587. block,
  16588. sizeof(block),
  16589. "\"data\" : {%s"
  16590. "\"read\" : %" INT64_FMT "%s,"
  16591. "\"written\" : %" INT64_FMT "%s"
  16592. "},%s",
  16593. eol,
  16594. ctx->total_data_read,
  16595. eol,
  16596. ctx->total_data_written,
  16597. eol,
  16598. eol);
  16599. context_info_length += (int)strlen(block);
  16600. if (context_info_length + reserved_len < buflen) {
  16601. strcat0(buffer, block);
  16602. }
  16603. /* Execution time information */
  16604. gmt_time_string(start_time_str,
  16605. sizeof(start_time_str) - 1,
  16606. &start_time);
  16607. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16608. mg_snprintf(NULL,
  16609. NULL,
  16610. block,
  16611. sizeof(block),
  16612. "\"time\" : {%s"
  16613. "\"uptime\" : %.0f,%s"
  16614. "\"start\" : \"%s\",%s"
  16615. "\"now\" : \"%s\"%s"
  16616. "}%s",
  16617. eol,
  16618. difftime(now, start_time),
  16619. eol,
  16620. start_time_str,
  16621. eol,
  16622. now_str,
  16623. eol,
  16624. eol);
  16625. context_info_length += (int)strlen(block);
  16626. if (context_info_length + reserved_len < buflen) {
  16627. strcat0(buffer, block);
  16628. }
  16629. }
  16630. /* Terminate string */
  16631. if ((buflen > 0) && buffer && buffer[0]) {
  16632. if (context_info_length < buflen) {
  16633. strcat0(buffer, eoobj);
  16634. strcat0(buffer, eol);
  16635. }
  16636. }
  16637. context_info_length += reserved_len;
  16638. return context_info_length;
  16639. }
  16640. #endif
  16641. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16642. /* Get connection information. It can be printed or stored by the caller.
  16643. * Return the size of available information. */
  16644. static int
  16645. mg_get_connection_info_impl(const struct mg_context *ctx,
  16646. int idx,
  16647. char *buffer,
  16648. int buflen)
  16649. {
  16650. const struct mg_connection *conn;
  16651. const struct mg_request_info *ri;
  16652. char block[256];
  16653. int connection_info_length = 0;
  16654. int state = 0;
  16655. const char *state_str = "unknown";
  16656. #if defined(_WIN32)
  16657. const char *eol = "\r\n";
  16658. #else
  16659. const char *eol = "\n";
  16660. #endif
  16661. const char *eoobj = "}";
  16662. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16663. if ((buffer == NULL) || (buflen < 1)) {
  16664. buflen = 0;
  16665. } else {
  16666. *buffer = 0;
  16667. }
  16668. if ((ctx == NULL) || (idx < 0)) {
  16669. /* Parameter error */
  16670. return 0;
  16671. }
  16672. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16673. /* Out of range */
  16674. return 0;
  16675. }
  16676. /* Take connection [idx]. This connection is not locked in
  16677. * any way, so some other thread might use it. */
  16678. conn = (ctx->worker_connections) + idx;
  16679. /* Initialize output string */
  16680. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16681. connection_info_length += (int)strlen(block);
  16682. if (connection_info_length < buflen) {
  16683. strcat0(buffer, block);
  16684. }
  16685. /* Init variables */
  16686. ri = &(conn->request_info);
  16687. #if defined(USE_SERVER_STATS)
  16688. state = conn->conn_state;
  16689. /* State as string */
  16690. switch (state) {
  16691. case 0:
  16692. state_str = "undefined";
  16693. break;
  16694. case 1:
  16695. state_str = "not used";
  16696. break;
  16697. case 2:
  16698. state_str = "init";
  16699. break;
  16700. case 3:
  16701. state_str = "ready";
  16702. break;
  16703. case 4:
  16704. state_str = "processing";
  16705. break;
  16706. case 5:
  16707. state_str = "processed";
  16708. break;
  16709. case 6:
  16710. state_str = "to close";
  16711. break;
  16712. case 7:
  16713. state_str = "closing";
  16714. break;
  16715. case 8:
  16716. state_str = "closed";
  16717. break;
  16718. case 9:
  16719. state_str = "done";
  16720. break;
  16721. }
  16722. #endif
  16723. /* Connection info */
  16724. if ((state >= 3) && (state < 9)) {
  16725. mg_snprintf(NULL,
  16726. NULL,
  16727. block,
  16728. sizeof(block),
  16729. "\"connection\" : {%s"
  16730. "\"remote\" : {%s"
  16731. "\"protocol\" : \"%s\",%s"
  16732. "\"addr\" : \"%s\",%s"
  16733. "\"port\" : %u%s"
  16734. "},%s"
  16735. "\"handled_requests\" : %u%s"
  16736. "},%s",
  16737. eol,
  16738. eol,
  16739. get_proto_name(conn),
  16740. eol,
  16741. ri->remote_addr,
  16742. eol,
  16743. ri->remote_port,
  16744. eol,
  16745. eol,
  16746. conn->handled_requests,
  16747. eol,
  16748. eol);
  16749. connection_info_length += (int)strlen(block);
  16750. if (connection_info_length + reserved_len < buflen) {
  16751. strcat0(buffer, block);
  16752. }
  16753. }
  16754. /* Request info */
  16755. if ((state >= 4) && (state < 6)) {
  16756. mg_snprintf(NULL,
  16757. NULL,
  16758. block,
  16759. sizeof(block),
  16760. "\"request_info\" : {%s"
  16761. "\"method\" : \"%s\",%s"
  16762. "\"uri\" : \"%s\",%s"
  16763. "\"query\" : %s%s%s%s"
  16764. "},%s",
  16765. eol,
  16766. ri->request_method,
  16767. eol,
  16768. ri->request_uri,
  16769. eol,
  16770. ri->query_string ? "\"" : "",
  16771. ri->query_string ? ri->query_string : "null",
  16772. ri->query_string ? "\"" : "",
  16773. eol,
  16774. eol);
  16775. connection_info_length += (int)strlen(block);
  16776. if (connection_info_length + reserved_len < buflen) {
  16777. strcat0(buffer, block);
  16778. }
  16779. }
  16780. /* Execution time information */
  16781. if ((state >= 2) && (state < 9)) {
  16782. char start_time_str[64] = {0};
  16783. char now_str[64] = {0};
  16784. time_t start_time = conn->conn_birth_time;
  16785. time_t now = time(NULL);
  16786. gmt_time_string(start_time_str,
  16787. sizeof(start_time_str) - 1,
  16788. &start_time);
  16789. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16790. mg_snprintf(NULL,
  16791. NULL,
  16792. block,
  16793. sizeof(block),
  16794. "\"time\" : {%s"
  16795. "\"uptime\" : %.0f,%s"
  16796. "\"start\" : \"%s\",%s"
  16797. "\"now\" : \"%s\"%s"
  16798. "},%s",
  16799. eol,
  16800. difftime(now, start_time),
  16801. eol,
  16802. start_time_str,
  16803. eol,
  16804. now_str,
  16805. eol,
  16806. eol);
  16807. connection_info_length += (int)strlen(block);
  16808. if (connection_info_length + reserved_len < buflen) {
  16809. strcat0(buffer, block);
  16810. }
  16811. }
  16812. /* Remote user name */
  16813. if ((ri->remote_user) && (state < 9)) {
  16814. mg_snprintf(NULL,
  16815. NULL,
  16816. block,
  16817. sizeof(block),
  16818. "\"user\" : {%s"
  16819. "\"name\" : \"%s\",%s"
  16820. "},%s",
  16821. eol,
  16822. ri->remote_user,
  16823. eol,
  16824. eol);
  16825. connection_info_length += (int)strlen(block);
  16826. if (connection_info_length + reserved_len < buflen) {
  16827. strcat0(buffer, block);
  16828. }
  16829. }
  16830. /* Data block */
  16831. if (state >= 3) {
  16832. mg_snprintf(NULL,
  16833. NULL,
  16834. block,
  16835. sizeof(block),
  16836. "\"data\" : {%s"
  16837. "\"read\" : %" INT64_FMT ",%s"
  16838. "\"written\" : %" INT64_FMT "%s"
  16839. "},%s",
  16840. eol,
  16841. conn->consumed_content,
  16842. eol,
  16843. conn->num_bytes_sent,
  16844. eol,
  16845. eol);
  16846. connection_info_length += (int)strlen(block);
  16847. if (connection_info_length + reserved_len < buflen) {
  16848. strcat0(buffer, block);
  16849. }
  16850. }
  16851. /* State */
  16852. mg_snprintf(NULL,
  16853. NULL,
  16854. block,
  16855. sizeof(block),
  16856. "\"state\" : \"%s\"%s",
  16857. state_str,
  16858. eol);
  16859. connection_info_length += (int)strlen(block);
  16860. if (connection_info_length + reserved_len < buflen) {
  16861. strcat0(buffer, block);
  16862. }
  16863. /* Terminate string */
  16864. if ((buflen > 0) && buffer && buffer[0]) {
  16865. if (connection_info_length < buflen) {
  16866. strcat0(buffer, eoobj);
  16867. strcat0(buffer, eol);
  16868. }
  16869. }
  16870. connection_info_length += reserved_len;
  16871. return connection_info_length;
  16872. }
  16873. #endif
  16874. /* Get system information. It can be printed or stored by the caller.
  16875. * Return the size of available information. */
  16876. int
  16877. mg_get_system_info(char *buffer, int buflen)
  16878. {
  16879. if ((buffer == NULL) || (buflen < 1)) {
  16880. return mg_get_system_info_impl(NULL, 0);
  16881. } else {
  16882. /* Reset buffer, so we can always use strcat. */
  16883. buffer[0] = 0;
  16884. return mg_get_system_info_impl(buffer, buflen);
  16885. }
  16886. }
  16887. /* Get context information. It can be printed or stored by the caller.
  16888. * Return the size of available information. */
  16889. int
  16890. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16891. {
  16892. #if defined(USE_SERVER_STATS)
  16893. if ((buffer == NULL) || (buflen < 1)) {
  16894. return mg_get_context_info_impl(ctx, NULL, 0);
  16895. } else {
  16896. /* Reset buffer, so we can always use strcat. */
  16897. buffer[0] = 0;
  16898. return mg_get_context_info_impl(ctx, buffer, buflen);
  16899. }
  16900. #else
  16901. (void)ctx;
  16902. if ((buffer != NULL) && (buflen > 0)) {
  16903. buffer[0] = 0;
  16904. }
  16905. return 0;
  16906. #endif
  16907. }
  16908. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16909. int
  16910. mg_get_connection_info(const struct mg_context *ctx,
  16911. int idx,
  16912. char *buffer,
  16913. int buflen)
  16914. {
  16915. if ((buffer == NULL) || (buflen < 1)) {
  16916. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  16917. } else {
  16918. /* Reset buffer, so we can always use strcat. */
  16919. buffer[0] = 0;
  16920. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  16921. }
  16922. }
  16923. #endif
  16924. /* Initialize this library. This function does not need to be thread safe.
  16925. */
  16926. unsigned
  16927. mg_init_library(unsigned features)
  16928. {
  16929. #if !defined(NO_SSL)
  16930. char ebuf[128];
  16931. #endif
  16932. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  16933. unsigned features_inited = features_to_init;
  16934. if (mg_init_library_called <= 0) {
  16935. /* Not initialized yet */
  16936. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  16937. return 0;
  16938. }
  16939. }
  16940. mg_global_lock();
  16941. if (mg_init_library_called <= 0) {
  16942. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  16943. /* Fatal error - abort start. However, this situation should
  16944. * never occur in practice. */
  16945. mg_global_unlock();
  16946. return 0;
  16947. }
  16948. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16949. InitializeCriticalSection(&global_log_file_lock);
  16950. #endif /* _WIN32 && !__SYMBIAN32__ */
  16951. #if !defined(_WIN32)
  16952. pthread_mutexattr_init(&pthread_mutex_attr);
  16953. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  16954. #endif
  16955. #if defined(USE_LUA)
  16956. lua_init_optional_libraries();
  16957. #endif
  16958. }
  16959. mg_global_unlock();
  16960. #if !defined(NO_SSL)
  16961. if (features_to_init & MG_FEATURES_SSL) {
  16962. if (!mg_ssl_initialized) {
  16963. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  16964. mg_ssl_initialized = 1;
  16965. } else {
  16966. (void)ebuf;
  16967. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16968. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  16969. }
  16970. } else {
  16971. /* ssl already initialized */
  16972. }
  16973. }
  16974. #endif
  16975. /* Start WinSock for Windows */
  16976. mg_global_lock();
  16977. if (mg_init_library_called <= 0) {
  16978. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16979. WSADATA data;
  16980. WSAStartup(MAKEWORD(2, 2), &data);
  16981. #endif /* _WIN32 && !__SYMBIAN32__ */
  16982. mg_init_library_called = 1;
  16983. } else {
  16984. mg_init_library_called++;
  16985. }
  16986. mg_global_unlock();
  16987. return features_inited;
  16988. }
  16989. /* Un-initialize this library. */
  16990. unsigned
  16991. mg_exit_library(void)
  16992. {
  16993. if (mg_init_library_called <= 0) {
  16994. return 0;
  16995. }
  16996. mg_global_lock();
  16997. mg_init_library_called--;
  16998. if (mg_init_library_called == 0) {
  16999. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  17000. (void)WSACleanup();
  17001. #endif /* _WIN32 && !__SYMBIAN32__ */
  17002. #if !defined(NO_SSL)
  17003. if (mg_ssl_initialized) {
  17004. uninitialize_ssl();
  17005. mg_ssl_initialized = 0;
  17006. }
  17007. #endif
  17008. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  17009. (void)DeleteCriticalSection(&global_log_file_lock);
  17010. #endif /* _WIN32 && !__SYMBIAN32__ */
  17011. #if !defined(_WIN32)
  17012. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17013. #endif
  17014. (void)pthread_key_delete(sTlsKey);
  17015. #if defined(USE_LUA)
  17016. lua_exit_optional_libraries();
  17017. #endif
  17018. mg_global_unlock();
  17019. (void)pthread_mutex_destroy(&global_lock_mutex);
  17020. return 1;
  17021. }
  17022. mg_global_unlock();
  17023. return 1;
  17024. }
  17025. /* End of civetweb.c */