civetweb.c 556 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708
  1. /* Copyright (c) 2013-2020 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE 8096
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #ifndef DEBUG_TRACE_STREAM
  209. # define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #define DEBUG_ASSERT(cond) \
  220. do { \
  221. if (!(cond)) { \
  222. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  223. exit(2); /* Exit with error */ \
  224. } \
  225. } while (0)
  226. #else
  227. #define DEBUG_ASSERT(cond)
  228. #endif /* DEBUG */
  229. #endif
  230. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  231. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  232. __attribute__((no_instrument_function));
  233. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  234. __attribute__((no_instrument_function));
  235. void
  236. __cyg_profile_func_enter(void *this_fn, void *call_site)
  237. {
  238. if ((void *)this_fn != (void *)printf) {
  239. printf("E %p %p\n", this_fn, call_site);
  240. }
  241. }
  242. void
  243. __cyg_profile_func_exit(void *this_fn, void *call_site)
  244. {
  245. if ((void *)this_fn != (void *)printf) {
  246. printf("X %p %p\n", this_fn, call_site);
  247. }
  248. }
  249. #endif
  250. #if !defined(IGNORE_UNUSED_RESULT)
  251. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  252. #endif
  253. #if defined(__GNUC__) || defined(__MINGW32__)
  254. /* GCC unused function attribute seems fundamentally broken.
  255. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  256. * OR UNUSED" for individual functions failed.
  257. * Either the compiler creates an "unused-function" warning if a
  258. * function is not marked with __attribute__((unused)).
  259. * On the other hand, if the function is marked with this attribute,
  260. * but is used, the compiler raises a completely idiotic
  261. * "used-but-marked-unused" warning - and
  262. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  263. * raises error: unknown option after "#pragma GCC diagnostic".
  264. * Disable this warning completely, until the GCC guys sober up
  265. * again.
  266. */
  267. #pragma GCC diagnostic ignored "-Wunused-function"
  268. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  269. #else
  270. #define FUNCTION_MAY_BE_UNUSED
  271. #endif
  272. /* Some ANSI #includes are not available on Windows CE */
  273. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  274. #include <errno.h>
  275. #include <fcntl.h>
  276. #include <signal.h>
  277. #include <stdlib.h>
  278. #include <sys/stat.h>
  279. #include <sys/types.h>
  280. #endif /* !_WIN32_WCE */
  281. #if defined(__clang__)
  282. /* When using -Weverything, clang does not accept it's own headers
  283. * in a release build configuration. Disable what is too much in
  284. * -Weverything. */
  285. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  286. #endif
  287. #if defined(__GNUC__) || defined(__MINGW32__)
  288. /* Who on earth came to the conclusion, using __DATE__ should rise
  289. * an "expansion of date or time macro is not reproducible"
  290. * warning. That's exactly what was intended by using this macro.
  291. * Just disable this nonsense warning. */
  292. /* And disabling them does not work either:
  293. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  294. * #pragma clang diagnostic ignored "-Wdate-time"
  295. * So we just have to disable ALL warnings for some lines
  296. * of code.
  297. * This seems to be a known GCC bug, not resolved since 2012:
  298. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  299. */
  300. #endif
  301. #if defined(__MACH__) /* Apple OSX section */
  302. #if defined(__clang__)
  303. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  304. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  305. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  306. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  307. #endif
  308. #endif
  309. #define CLOCK_MONOTONIC (1)
  310. #define CLOCK_REALTIME (2)
  311. #include <mach/clock.h>
  312. #include <mach/mach.h>
  313. #include <mach/mach_time.h>
  314. #include <sys/errno.h>
  315. #include <sys/time.h>
  316. /* clock_gettime is not implemented on OSX prior to 10.12 */
  317. static int
  318. _civet_clock_gettime(int clk_id, struct timespec *t)
  319. {
  320. memset(t, 0, sizeof(*t));
  321. if (clk_id == CLOCK_REALTIME) {
  322. struct timeval now;
  323. int rv = gettimeofday(&now, NULL);
  324. if (rv) {
  325. return rv;
  326. }
  327. t->tv_sec = now.tv_sec;
  328. t->tv_nsec = now.tv_usec * 1000;
  329. return 0;
  330. } else if (clk_id == CLOCK_MONOTONIC) {
  331. static uint64_t clock_start_time = 0;
  332. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  333. uint64_t now = mach_absolute_time();
  334. if (clock_start_time == 0) {
  335. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  336. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  337. /* appease "unused variable" warning for release builds */
  338. (void)mach_status;
  339. clock_start_time = now;
  340. }
  341. now = (uint64_t)((double)(now - clock_start_time)
  342. * (double)timebase_ifo.numer
  343. / (double)timebase_ifo.denom);
  344. t->tv_sec = now / 1000000000;
  345. t->tv_nsec = now % 1000000000;
  346. return 0;
  347. }
  348. return -1; /* EINVAL - Clock ID is unknown */
  349. }
  350. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  351. #if defined(__CLOCK_AVAILABILITY)
  352. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  353. * declared but it may be NULL at runtime. So we need to check before using
  354. * it. */
  355. static int
  356. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  357. {
  358. if (clock_gettime) {
  359. return clock_gettime(clk_id, t);
  360. }
  361. return _civet_clock_gettime(clk_id, t);
  362. }
  363. #define clock_gettime _civet_safe_clock_gettime
  364. #else
  365. #define clock_gettime _civet_clock_gettime
  366. #endif
  367. #endif
  368. /********************************************************************/
  369. /* CivetWeb configuration defines */
  370. /********************************************************************/
  371. /* Maximum number of threads that can be configured.
  372. * The number of threads actually created depends on the "num_threads"
  373. * configuration parameter, but this is the upper limit. */
  374. #if !defined(MAX_WORKER_THREADS)
  375. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  376. #endif
  377. /* Timeout interval for select/poll calls.
  378. * The timeouts depend on "*_timeout_ms" configuration values, but long
  379. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  380. * This reduces the time required to stop the server. */
  381. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  382. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  383. #endif
  384. /* Do not try to compress files smaller than this limit. */
  385. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  386. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  387. #endif
  388. #if !defined(PASSWORDS_FILE_NAME)
  389. #define PASSWORDS_FILE_NAME ".htpasswd"
  390. #endif
  391. /* Initial buffer size for all CGI environment variables. In case there is
  392. * not enough space, another block is allocated. */
  393. #if !defined(CGI_ENVIRONMENT_SIZE)
  394. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  395. #endif
  396. /* Maximum number of environment variables. */
  397. #if !defined(MAX_CGI_ENVIR_VARS)
  398. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  399. #endif
  400. /* General purpose buffer size. */
  401. #if !defined(MG_BUF_LEN) /* in bytes */
  402. #define MG_BUF_LEN (1024 * 8)
  403. #endif
  404. /********************************************************************/
  405. /* Helper makros */
  406. #if !defined(ARRAY_SIZE)
  407. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  408. #endif
  409. #include <stdint.h>
  410. /* Standard defines */
  411. #if !defined(INT64_MAX)
  412. #define INT64_MAX (9223372036854775807)
  413. #endif
  414. #define SHUTDOWN_RD (0)
  415. #define SHUTDOWN_WR (1)
  416. #define SHUTDOWN_BOTH (2)
  417. mg_static_assert(MAX_WORKER_THREADS >= 1,
  418. "worker threads must be a positive number");
  419. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  420. "size_t data type size check");
  421. #if defined(_WIN32) /* WINDOWS include block */
  422. #include <malloc.h> /* *alloc( */
  423. #include <stdlib.h> /* *alloc( */
  424. #include <time.h> /* struct timespec */
  425. #include <windows.h>
  426. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  427. #include <ws2tcpip.h>
  428. typedef const char *SOCK_OPT_TYPE;
  429. #if !defined(PATH_MAX)
  430. #define W_PATH_MAX (MAX_PATH)
  431. /* at most three UTF-8 chars per wchar_t */
  432. #define PATH_MAX (W_PATH_MAX * 3)
  433. #else
  434. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  435. #endif
  436. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  437. #if !defined(_IN_PORT_T)
  438. #if !defined(in_port_t)
  439. #define in_port_t u_short
  440. #endif
  441. #endif
  442. #if !defined(_WIN32_WCE)
  443. #include <direct.h>
  444. #include <io.h>
  445. #include <process.h>
  446. #else /* _WIN32_WCE */
  447. #define NO_CGI /* WinCE has no pipes */
  448. #define NO_POPEN /* WinCE has no popen */
  449. typedef long off_t;
  450. #define errno ((int)(GetLastError()))
  451. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  452. #endif /* _WIN32_WCE */
  453. #define MAKEUQUAD(lo, hi) \
  454. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  455. #define RATE_DIFF (10000000) /* 100 nsecs */
  456. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  457. #define SYS2UNIX_TIME(lo, hi) \
  458. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  459. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  460. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  461. * Also use _strtoui64 on modern M$ compilers */
  462. #if defined(_MSC_VER)
  463. #if (_MSC_VER < 1300)
  464. #define STRX(x) #x
  465. #define STR(x) STRX(x)
  466. #define __func__ __FILE__ ":" STR(__LINE__)
  467. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  468. #define strtoll(x, y, z) (_atoi64(x))
  469. #else
  470. #define __func__ __FUNCTION__
  471. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  472. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  473. #endif
  474. #endif /* _MSC_VER */
  475. #define ERRNO ((int)(GetLastError()))
  476. #define NO_SOCKLEN_T
  477. #if defined(_WIN64) || defined(__MINGW64__)
  478. #if !defined(SSL_LIB)
  479. #if defined(OPENSSL_API_1_1)
  480. #define SSL_LIB "libssl-1_1-x64.dll"
  481. #else /* OPENSSL_API_1_1 */
  482. #define SSL_LIB "ssleay64.dll"
  483. #endif /* OPENSSL_API_1_1 */
  484. #endif /* SSL_LIB */
  485. #if !defined(CRYPTO_LIB)
  486. #if defined(OPENSSL_API_1_1)
  487. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  488. #else /* OPENSSL_API_1_1 */
  489. #define CRYPTO_LIB "libeay64.dll"
  490. #endif /* OPENSSL_API_1_1 */
  491. #endif /* CRYPTO_LIB */
  492. #else /* defined(_WIN64) || defined(__MINGW64__) */
  493. #if !defined(SSL_LIB)
  494. #define SSL_LIB "ssleay32.dll"
  495. #endif /* SSL_LIB */
  496. #if !defined(CRYPTO_LIB)
  497. #define CRYPTO_LIB "libeay32.dll"
  498. #endif /* CRYPTO_LIB */
  499. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  500. #define O_NONBLOCK (0)
  501. #if !defined(W_OK)
  502. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  503. #endif
  504. #define _POSIX_
  505. #define INT64_FMT "I64d"
  506. #define UINT64_FMT "I64u"
  507. #define WINCDECL __cdecl
  508. #define vsnprintf_impl _vsnprintf
  509. #define access _access
  510. #define mg_sleep(x) (Sleep(x))
  511. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  512. #if !defined(popen)
  513. #define popen(x, y) (_popen(x, y))
  514. #endif
  515. #if !defined(pclose)
  516. #define pclose(x) (_pclose(x))
  517. #endif
  518. #define close(x) (_close(x))
  519. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  520. #define RTLD_LAZY (0)
  521. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  522. #define fdopen(x, y) (_fdopen((x), (y)))
  523. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  524. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  525. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  526. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  527. #define sleep(x) (Sleep((x)*1000))
  528. #define rmdir(x) (_rmdir(x))
  529. #if defined(_WIN64) || !defined(__MINGW32__)
  530. /* Only MinGW 32 bit is missing this function */
  531. #define timegm(x) (_mkgmtime(x))
  532. #else
  533. time_t timegm(struct tm *tm);
  534. #define NEED_TIMEGM
  535. #endif
  536. #if !defined(fileno)
  537. #define fileno(x) (_fileno(x))
  538. #endif /* !fileno MINGW #defines fileno */
  539. typedef struct {
  540. CRITICAL_SECTION sec; /* Immovable */
  541. } pthread_mutex_t;
  542. typedef DWORD pthread_key_t;
  543. typedef HANDLE pthread_t;
  544. typedef struct {
  545. pthread_mutex_t threadIdSec;
  546. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  547. } pthread_cond_t;
  548. #if !defined(__clockid_t_defined)
  549. typedef DWORD clockid_t;
  550. #endif
  551. #if !defined(CLOCK_MONOTONIC)
  552. #define CLOCK_MONOTONIC (1)
  553. #endif
  554. #if !defined(CLOCK_REALTIME)
  555. #define CLOCK_REALTIME (2)
  556. #endif
  557. #if !defined(CLOCK_THREAD)
  558. #define CLOCK_THREAD (3)
  559. #endif
  560. #if !defined(CLOCK_PROCESS)
  561. #define CLOCK_PROCESS (4)
  562. #endif
  563. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  564. #define _TIMESPEC_DEFINED
  565. #endif
  566. #if !defined(_TIMESPEC_DEFINED)
  567. struct timespec {
  568. time_t tv_sec; /* seconds */
  569. long tv_nsec; /* nanoseconds */
  570. };
  571. #endif
  572. #if !defined(WIN_PTHREADS_TIME_H)
  573. #define MUST_IMPLEMENT_CLOCK_GETTIME
  574. #endif
  575. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  576. #define clock_gettime mg_clock_gettime
  577. static int
  578. clock_gettime(clockid_t clk_id, struct timespec *tp)
  579. {
  580. FILETIME ft;
  581. ULARGE_INTEGER li, li2;
  582. BOOL ok = FALSE;
  583. double d;
  584. static double perfcnt_per_sec = 0.0;
  585. static BOOL initialized = FALSE;
  586. if (!initialized) {
  587. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  588. perfcnt_per_sec = 1.0 / li.QuadPart;
  589. initialized = TRUE;
  590. }
  591. if (tp) {
  592. memset(tp, 0, sizeof(*tp));
  593. if (clk_id == CLOCK_REALTIME) {
  594. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  595. GetSystemTimeAsFileTime(&ft);
  596. li.LowPart = ft.dwLowDateTime;
  597. li.HighPart = ft.dwHighDateTime;
  598. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  599. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  600. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  601. ok = TRUE;
  602. /* END: CLOCK_REALTIME */
  603. } else if (clk_id == CLOCK_MONOTONIC) {
  604. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  605. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  606. d = li.QuadPart * perfcnt_per_sec;
  607. tp->tv_sec = (time_t)d;
  608. d -= (double)tp->tv_sec;
  609. tp->tv_nsec = (long)(d * 1.0E9);
  610. ok = TRUE;
  611. /* END: CLOCK_MONOTONIC */
  612. } else if (clk_id == CLOCK_THREAD) {
  613. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  614. FILETIME t_create, t_exit, t_kernel, t_user;
  615. if (GetThreadTimes(GetCurrentThread(),
  616. &t_create,
  617. &t_exit,
  618. &t_kernel,
  619. &t_user)) {
  620. li.LowPart = t_user.dwLowDateTime;
  621. li.HighPart = t_user.dwHighDateTime;
  622. li2.LowPart = t_kernel.dwLowDateTime;
  623. li2.HighPart = t_kernel.dwHighDateTime;
  624. li.QuadPart += li2.QuadPart;
  625. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  626. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  627. ok = TRUE;
  628. }
  629. /* END: CLOCK_THREAD */
  630. } else if (clk_id == CLOCK_PROCESS) {
  631. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  632. FILETIME t_create, t_exit, t_kernel, t_user;
  633. if (GetProcessTimes(GetCurrentProcess(),
  634. &t_create,
  635. &t_exit,
  636. &t_kernel,
  637. &t_user)) {
  638. li.LowPart = t_user.dwLowDateTime;
  639. li.HighPart = t_user.dwHighDateTime;
  640. li2.LowPart = t_kernel.dwLowDateTime;
  641. li2.HighPart = t_kernel.dwHighDateTime;
  642. li.QuadPart += li2.QuadPart;
  643. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  644. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  645. ok = TRUE;
  646. }
  647. /* END: CLOCK_PROCESS */
  648. } else {
  649. /* BEGIN: unknown clock */
  650. /* ok = FALSE; already set by init */
  651. /* END: unknown clock */
  652. }
  653. }
  654. return ok ? 0 : -1;
  655. }
  656. #endif
  657. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  658. static int pthread_mutex_lock(pthread_mutex_t *);
  659. static int pthread_mutex_unlock(pthread_mutex_t *);
  660. static void path_to_unicode(const struct mg_connection *conn,
  661. const char *path,
  662. wchar_t *wbuf,
  663. size_t wbuf_len);
  664. /* All file operations need to be rewritten to solve #246. */
  665. struct mg_file;
  666. static const char *
  667. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  668. /* POSIX dirent interface */
  669. struct dirent {
  670. char d_name[PATH_MAX];
  671. };
  672. typedef struct DIR {
  673. HANDLE handle;
  674. WIN32_FIND_DATAW info;
  675. struct dirent result;
  676. } DIR;
  677. #if defined(HAVE_POLL)
  678. #define mg_pollfd pollfd
  679. #else
  680. struct mg_pollfd {
  681. SOCKET fd;
  682. short events;
  683. short revents;
  684. };
  685. #endif
  686. /* Mark required libraries */
  687. #if defined(_MSC_VER)
  688. #pragma comment(lib, "Ws2_32.lib")
  689. #endif
  690. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  691. #include <inttypes.h>
  692. typedef const void *SOCK_OPT_TYPE;
  693. #if defined(ANDROID)
  694. typedef unsigned short int in_port_t;
  695. #endif
  696. #if !defined(__ZEPHYR__)
  697. #include <arpa/inet.h>
  698. #include <ctype.h>
  699. #include <dirent.h>
  700. #include <grp.h>
  701. #include <limits.h>
  702. #include <netdb.h>
  703. #include <netinet/in.h>
  704. #include <netinet/tcp.h>
  705. #include <pthread.h>
  706. #include <pwd.h>
  707. #include <stdarg.h>
  708. #include <stddef.h>
  709. #include <stdio.h>
  710. #include <stdlib.h>
  711. #include <string.h>
  712. #include <sys/poll.h>
  713. #include <sys/socket.h>
  714. #include <sys/time.h>
  715. #include <sys/utsname.h>
  716. #include <sys/wait.h>
  717. #include <time.h>
  718. #include <unistd.h>
  719. #endif
  720. #define vsnprintf_impl vsnprintf
  721. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  722. #include <dlfcn.h>
  723. #endif
  724. #if defined(__MACH__)
  725. #define SSL_LIB "libssl.dylib"
  726. #define CRYPTO_LIB "libcrypto.dylib"
  727. #else
  728. #if !defined(SSL_LIB)
  729. #define SSL_LIB "libssl.so"
  730. #endif
  731. #if !defined(CRYPTO_LIB)
  732. #define CRYPTO_LIB "libcrypto.so"
  733. #endif
  734. #endif
  735. #if !defined(O_BINARY)
  736. #define O_BINARY (0)
  737. #endif /* O_BINARY */
  738. #define closesocket(a) (close(a))
  739. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  740. #define mg_remove(conn, x) (remove(x))
  741. #define mg_sleep(x) (usleep((x)*1000))
  742. #define mg_opendir(conn, x) (opendir(x))
  743. #define mg_closedir(x) (closedir(x))
  744. #define mg_readdir(x) (readdir(x))
  745. #define ERRNO (errno)
  746. #define INVALID_SOCKET (-1)
  747. #define INT64_FMT PRId64
  748. #define UINT64_FMT PRIu64
  749. typedef int SOCKET;
  750. #define WINCDECL
  751. #if defined(__hpux)
  752. /* HPUX 11 does not have monotonic, fall back to realtime */
  753. #if !defined(CLOCK_MONOTONIC)
  754. #define CLOCK_MONOTONIC CLOCK_REALTIME
  755. #endif
  756. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  757. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  758. * the prototypes use int* rather than socklen_t* which matches the
  759. * actual library expectation. When called with the wrong size arg
  760. * accept() returns a zero client inet addr and check_acl() always
  761. * fails. Since socklen_t is widely used below, just force replace
  762. * their typedef with int. - DTL
  763. */
  764. #define socklen_t int
  765. #endif /* hpux */
  766. #define mg_pollfd pollfd
  767. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  768. /* In case our C library is missing "timegm", provide an implementation */
  769. #if defined(NEED_TIMEGM)
  770. static inline int
  771. is_leap(int y)
  772. {
  773. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  774. }
  775. static inline int
  776. count_leap(int y)
  777. {
  778. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  779. }
  780. time_t
  781. timegm(struct tm *tm)
  782. {
  783. static const unsigned short ydays[] = {
  784. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  785. int year = tm->tm_year + 1900;
  786. int mon = tm->tm_mon;
  787. int mday = tm->tm_mday - 1;
  788. int hour = tm->tm_hour;
  789. int min = tm->tm_min;
  790. int sec = tm->tm_sec;
  791. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  792. || (mday >= ydays[mon + 1] - ydays[mon]
  793. + (mon == 1 && is_leap(year) ? 1 : 0))
  794. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  795. return -1;
  796. time_t res = year - 1970;
  797. res *= 365;
  798. res += mday;
  799. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  800. res += count_leap(year);
  801. res *= 24;
  802. res += hour;
  803. res *= 60;
  804. res += min;
  805. res *= 60;
  806. res += sec;
  807. return res;
  808. }
  809. #endif /* NEED_TIMEGM */
  810. /* va_copy should always be a macro, C99 and C++11 - DTL */
  811. #if !defined(va_copy)
  812. #define va_copy(x, y) ((x) = (y))
  813. #endif
  814. #if defined(_WIN32)
  815. /* Create substitutes for POSIX functions in Win32. */
  816. #if defined(GCC_DIAGNOSTIC)
  817. /* Show no warning in case system functions are not used. */
  818. #pragma GCC diagnostic push
  819. #pragma GCC diagnostic ignored "-Wunused-function"
  820. #endif
  821. static pthread_mutex_t global_log_file_lock;
  822. FUNCTION_MAY_BE_UNUSED
  823. static DWORD
  824. pthread_self(void)
  825. {
  826. return GetCurrentThreadId();
  827. }
  828. FUNCTION_MAY_BE_UNUSED
  829. static int
  830. pthread_key_create(
  831. pthread_key_t *key,
  832. void (*_ignored)(void *) /* destructor not supported for Windows */
  833. )
  834. {
  835. (void)_ignored;
  836. if ((key != 0)) {
  837. *key = TlsAlloc();
  838. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  839. }
  840. return -2;
  841. }
  842. FUNCTION_MAY_BE_UNUSED
  843. static int
  844. pthread_key_delete(pthread_key_t key)
  845. {
  846. return TlsFree(key) ? 0 : 1;
  847. }
  848. FUNCTION_MAY_BE_UNUSED
  849. static int
  850. pthread_setspecific(pthread_key_t key, void *value)
  851. {
  852. return TlsSetValue(key, value) ? 0 : 1;
  853. }
  854. FUNCTION_MAY_BE_UNUSED
  855. static void *
  856. pthread_getspecific(pthread_key_t key)
  857. {
  858. return TlsGetValue(key);
  859. }
  860. #if defined(GCC_DIAGNOSTIC)
  861. /* Enable unused function warning again */
  862. #pragma GCC diagnostic pop
  863. #endif
  864. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  865. #else
  866. static pthread_mutexattr_t pthread_mutex_attr;
  867. #endif /* _WIN32 */
  868. #if defined(_WIN32_WCE)
  869. /* Create substitutes for POSIX functions in Win32. */
  870. #if defined(GCC_DIAGNOSTIC)
  871. /* Show no warning in case system functions are not used. */
  872. #pragma GCC diagnostic push
  873. #pragma GCC diagnostic ignored "-Wunused-function"
  874. #endif
  875. FUNCTION_MAY_BE_UNUSED
  876. static time_t
  877. time(time_t *ptime)
  878. {
  879. time_t t;
  880. SYSTEMTIME st;
  881. FILETIME ft;
  882. GetSystemTime(&st);
  883. SystemTimeToFileTime(&st, &ft);
  884. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  885. if (ptime != NULL) {
  886. *ptime = t;
  887. }
  888. return t;
  889. }
  890. FUNCTION_MAY_BE_UNUSED
  891. static struct tm *
  892. localtime_s(const time_t *ptime, struct tm *ptm)
  893. {
  894. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  895. FILETIME ft, lft;
  896. SYSTEMTIME st;
  897. TIME_ZONE_INFORMATION tzinfo;
  898. if (ptm == NULL) {
  899. return NULL;
  900. }
  901. *(int64_t *)&ft = t;
  902. FileTimeToLocalFileTime(&ft, &lft);
  903. FileTimeToSystemTime(&lft, &st);
  904. ptm->tm_year = st.wYear - 1900;
  905. ptm->tm_mon = st.wMonth - 1;
  906. ptm->tm_wday = st.wDayOfWeek;
  907. ptm->tm_mday = st.wDay;
  908. ptm->tm_hour = st.wHour;
  909. ptm->tm_min = st.wMinute;
  910. ptm->tm_sec = st.wSecond;
  911. ptm->tm_yday = 0; /* hope nobody uses this */
  912. ptm->tm_isdst =
  913. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  914. return ptm;
  915. }
  916. FUNCTION_MAY_BE_UNUSED
  917. static struct tm *
  918. gmtime_s(const time_t *ptime, struct tm *ptm)
  919. {
  920. /* FIXME(lsm): fix this. */
  921. return localtime_s(ptime, ptm);
  922. }
  923. static int mg_atomic_inc(volatile int *addr);
  924. static struct tm tm_array[MAX_WORKER_THREADS];
  925. static int tm_index = 0;
  926. FUNCTION_MAY_BE_UNUSED
  927. static struct tm *
  928. localtime(const time_t *ptime)
  929. {
  930. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  931. return localtime_s(ptime, tm_array + i);
  932. }
  933. FUNCTION_MAY_BE_UNUSED
  934. static struct tm *
  935. gmtime(const time_t *ptime)
  936. {
  937. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  938. return gmtime_s(ptime, tm_array + i);
  939. }
  940. FUNCTION_MAY_BE_UNUSED
  941. static size_t
  942. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  943. {
  944. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  945. * for WinCE"); */
  946. return 0;
  947. }
  948. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  949. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  950. #define remove(f) mg_remove(NULL, f)
  951. FUNCTION_MAY_BE_UNUSED
  952. static int
  953. rename(const char *a, const char *b)
  954. {
  955. wchar_t wa[W_PATH_MAX];
  956. wchar_t wb[W_PATH_MAX];
  957. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  958. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  959. return MoveFileW(wa, wb) ? 0 : -1;
  960. }
  961. struct stat {
  962. int64_t st_size;
  963. time_t st_mtime;
  964. };
  965. FUNCTION_MAY_BE_UNUSED
  966. static int
  967. stat(const char *name, struct stat *st)
  968. {
  969. wchar_t wbuf[W_PATH_MAX];
  970. WIN32_FILE_ATTRIBUTE_DATA attr;
  971. time_t creation_time, write_time;
  972. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  973. memset(&attr, 0, sizeof(attr));
  974. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  975. st->st_size =
  976. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  977. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  978. attr.ftLastWriteTime.dwHighDateTime);
  979. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  980. attr.ftCreationTime.dwHighDateTime);
  981. if (creation_time > write_time) {
  982. st->st_mtime = creation_time;
  983. } else {
  984. st->st_mtime = write_time;
  985. }
  986. return 0;
  987. }
  988. #define access(x, a) 1 /* not required anyway */
  989. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  990. /* Values from errno.h in Windows SDK (Visual Studio). */
  991. #define EEXIST 17
  992. #define EACCES 13
  993. #define ENOENT 2
  994. #if defined(GCC_DIAGNOSTIC)
  995. /* Enable unused function warning again */
  996. #pragma GCC diagnostic pop
  997. #endif
  998. #endif /* defined(_WIN32_WCE) */
  999. #if defined(GCC_DIAGNOSTIC)
  1000. /* Show no warning in case system functions are not used. */
  1001. #pragma GCC diagnostic push
  1002. #pragma GCC diagnostic ignored "-Wunused-function"
  1003. #endif /* defined(GCC_DIAGNOSTIC) */
  1004. #if defined(__clang__)
  1005. /* Show no warning in case system functions are not used. */
  1006. #pragma clang diagnostic push
  1007. #pragma clang diagnostic ignored "-Wunused-function"
  1008. #endif
  1009. static pthread_mutex_t global_lock_mutex;
  1010. FUNCTION_MAY_BE_UNUSED
  1011. static void
  1012. mg_global_lock(void)
  1013. {
  1014. (void)pthread_mutex_lock(&global_lock_mutex);
  1015. }
  1016. FUNCTION_MAY_BE_UNUSED
  1017. static void
  1018. mg_global_unlock(void)
  1019. {
  1020. (void)pthread_mutex_unlock(&global_lock_mutex);
  1021. }
  1022. FUNCTION_MAY_BE_UNUSED
  1023. static int
  1024. mg_atomic_inc(volatile int *addr)
  1025. {
  1026. int ret;
  1027. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1028. /* Depending on the SDK, this function uses either
  1029. * (volatile unsigned int *) or (volatile LONG *),
  1030. * so whatever you use, the other SDK is likely to raise a warning. */
  1031. ret = InterlockedIncrement((volatile long *)addr);
  1032. #elif defined(__GNUC__) \
  1033. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1034. && !defined(NO_ATOMICS)
  1035. ret = __sync_add_and_fetch(addr, 1);
  1036. #else
  1037. mg_global_lock();
  1038. ret = (++(*addr));
  1039. mg_global_unlock();
  1040. #endif
  1041. return ret;
  1042. }
  1043. FUNCTION_MAY_BE_UNUSED
  1044. static int
  1045. mg_atomic_dec(volatile int *addr)
  1046. {
  1047. int ret;
  1048. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1049. /* Depending on the SDK, this function uses either
  1050. * (volatile unsigned int *) or (volatile LONG *),
  1051. * so whatever you use, the other SDK is likely to raise a warning. */
  1052. ret = InterlockedDecrement((volatile long *)addr);
  1053. #elif defined(__GNUC__) \
  1054. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1055. && !defined(NO_ATOMICS)
  1056. ret = __sync_sub_and_fetch(addr, 1);
  1057. #else
  1058. mg_global_lock();
  1059. ret = (--(*addr));
  1060. mg_global_unlock();
  1061. #endif
  1062. return ret;
  1063. }
  1064. #if defined(USE_SERVER_STATS)
  1065. static int64_t
  1066. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1067. {
  1068. int64_t ret;
  1069. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1070. ret = InterlockedAdd64(addr, value);
  1071. #elif defined(__GNUC__) \
  1072. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1073. && !defined(NO_ATOMICS)
  1074. ret = __sync_add_and_fetch(addr, value);
  1075. #else
  1076. mg_global_lock();
  1077. *addr += value;
  1078. ret = (*addr);
  1079. mg_global_unlock();
  1080. #endif
  1081. return ret;
  1082. }
  1083. #endif
  1084. #if defined(GCC_DIAGNOSTIC)
  1085. /* Show no warning in case system functions are not used. */
  1086. #pragma GCC diagnostic pop
  1087. #endif /* defined(GCC_DIAGNOSTIC) */
  1088. #if defined(__clang__)
  1089. /* Show no warning in case system functions are not used. */
  1090. #pragma clang diagnostic pop
  1091. #endif
  1092. #if defined(USE_SERVER_STATS)
  1093. struct mg_memory_stat {
  1094. volatile int64_t totalMemUsed;
  1095. volatile int64_t maxMemUsed;
  1096. volatile int blockCount;
  1097. };
  1098. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1099. static void *
  1100. mg_malloc_ex(size_t size,
  1101. struct mg_context *ctx,
  1102. const char *file,
  1103. unsigned line)
  1104. {
  1105. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1106. void *memory = 0;
  1107. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1108. #if defined(MEMORY_DEBUGGING)
  1109. char mallocStr[256];
  1110. #else
  1111. (void)file;
  1112. (void)line;
  1113. #endif
  1114. if (data) {
  1115. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1116. if (mmem > mstat->maxMemUsed) {
  1117. /* could use atomic compare exchange, but this
  1118. * seems overkill for statistics data */
  1119. mstat->maxMemUsed = mmem;
  1120. }
  1121. mg_atomic_inc(&mstat->blockCount);
  1122. ((uintptr_t *)data)[0] = size;
  1123. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1124. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1125. }
  1126. #if defined(MEMORY_DEBUGGING)
  1127. sprintf(mallocStr,
  1128. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1129. memory,
  1130. (unsigned long)size,
  1131. (unsigned long)mstat->totalMemUsed,
  1132. (unsigned long)mstat->blockCount,
  1133. file,
  1134. line);
  1135. #if defined(_WIN32)
  1136. OutputDebugStringA(mallocStr);
  1137. #else
  1138. DEBUG_TRACE("%s", mallocStr);
  1139. #endif
  1140. #endif
  1141. return memory;
  1142. }
  1143. static void *
  1144. mg_calloc_ex(size_t count,
  1145. size_t size,
  1146. struct mg_context *ctx,
  1147. const char *file,
  1148. unsigned line)
  1149. {
  1150. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1151. if (data) {
  1152. memset(data, 0, size * count);
  1153. }
  1154. return data;
  1155. }
  1156. static void
  1157. mg_free_ex(void *memory, const char *file, unsigned line)
  1158. {
  1159. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1160. #if defined(MEMORY_DEBUGGING)
  1161. char mallocStr[256];
  1162. #else
  1163. (void)file;
  1164. (void)line;
  1165. #endif
  1166. if (memory) {
  1167. uintptr_t size = ((uintptr_t *)data)[0];
  1168. struct mg_memory_stat *mstat =
  1169. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1170. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1171. mg_atomic_dec(&mstat->blockCount);
  1172. #if defined(MEMORY_DEBUGGING)
  1173. sprintf(mallocStr,
  1174. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1175. memory,
  1176. (unsigned long)size,
  1177. (unsigned long)mstat->totalMemUsed,
  1178. (unsigned long)mstat->blockCount,
  1179. file,
  1180. line);
  1181. #if defined(_WIN32)
  1182. OutputDebugStringA(mallocStr);
  1183. #else
  1184. DEBUG_TRACE("%s", mallocStr);
  1185. #endif
  1186. #endif
  1187. free(data);
  1188. }
  1189. }
  1190. static void *
  1191. mg_realloc_ex(void *memory,
  1192. size_t newsize,
  1193. struct mg_context *ctx,
  1194. const char *file,
  1195. unsigned line)
  1196. {
  1197. void *data;
  1198. void *_realloc;
  1199. uintptr_t oldsize;
  1200. #if defined(MEMORY_DEBUGGING)
  1201. char mallocStr[256];
  1202. #else
  1203. (void)file;
  1204. (void)line;
  1205. #endif
  1206. if (newsize) {
  1207. if (memory) {
  1208. /* Reallocate existing block */
  1209. struct mg_memory_stat *mstat;
  1210. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1211. oldsize = ((uintptr_t *)data)[0];
  1212. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1213. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1214. if (_realloc) {
  1215. data = _realloc;
  1216. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1217. #if defined(MEMORY_DEBUGGING)
  1218. sprintf(mallocStr,
  1219. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1220. memory,
  1221. (unsigned long)oldsize,
  1222. (unsigned long)mstat->totalMemUsed,
  1223. (unsigned long)mstat->blockCount,
  1224. file,
  1225. line);
  1226. #if defined(_WIN32)
  1227. OutputDebugStringA(mallocStr);
  1228. #else
  1229. DEBUG_TRACE("%s", mallocStr);
  1230. #endif
  1231. #endif
  1232. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1233. #if defined(MEMORY_DEBUGGING)
  1234. sprintf(mallocStr,
  1235. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1236. memory,
  1237. (unsigned long)newsize,
  1238. (unsigned long)mstat->totalMemUsed,
  1239. (unsigned long)mstat->blockCount,
  1240. file,
  1241. line);
  1242. #if defined(_WIN32)
  1243. OutputDebugStringA(mallocStr);
  1244. #else
  1245. DEBUG_TRACE("%s", mallocStr);
  1246. #endif
  1247. #endif
  1248. *(uintptr_t *)data = newsize;
  1249. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1250. } else {
  1251. #if defined(MEMORY_DEBUGGING)
  1252. #if defined(_WIN32)
  1253. OutputDebugStringA("MEM: realloc failed\n");
  1254. #else
  1255. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1256. #endif
  1257. #endif
  1258. return _realloc;
  1259. }
  1260. } else {
  1261. /* Allocate new block */
  1262. data = mg_malloc_ex(newsize, ctx, file, line);
  1263. }
  1264. } else {
  1265. /* Free existing block */
  1266. data = 0;
  1267. mg_free_ex(memory, file, line);
  1268. }
  1269. return data;
  1270. }
  1271. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1272. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1273. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1274. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1275. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1276. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1277. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1278. #else /* USE_SERVER_STATS */
  1279. static __inline void *
  1280. mg_malloc(size_t a)
  1281. {
  1282. return malloc(a);
  1283. }
  1284. static __inline void *
  1285. mg_calloc(size_t a, size_t b)
  1286. {
  1287. return calloc(a, b);
  1288. }
  1289. static __inline void *
  1290. mg_realloc(void *a, size_t b)
  1291. {
  1292. return realloc(a, b);
  1293. }
  1294. static __inline void
  1295. mg_free(void *a)
  1296. {
  1297. free(a);
  1298. }
  1299. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1300. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1301. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1302. #define mg_free_ctx(a, c) mg_free(a)
  1303. #endif /* USE_SERVER_STATS */
  1304. static void mg_vsnprintf(const struct mg_connection *conn,
  1305. int *truncated,
  1306. char *buf,
  1307. size_t buflen,
  1308. const char *fmt,
  1309. va_list ap);
  1310. static void mg_snprintf(const struct mg_connection *conn,
  1311. int *truncated,
  1312. char *buf,
  1313. size_t buflen,
  1314. PRINTF_FORMAT_STRING(const char *fmt),
  1315. ...) PRINTF_ARGS(5, 6);
  1316. /* This following lines are just meant as a reminder to use the mg-functions
  1317. * for memory management */
  1318. #if defined(malloc)
  1319. #undef malloc
  1320. #endif
  1321. #if defined(calloc)
  1322. #undef calloc
  1323. #endif
  1324. #if defined(realloc)
  1325. #undef realloc
  1326. #endif
  1327. #if defined(free)
  1328. #undef free
  1329. #endif
  1330. #if defined(snprintf)
  1331. #undef snprintf
  1332. #endif
  1333. #if defined(vsnprintf)
  1334. #undef vsnprintf
  1335. #endif
  1336. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1337. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1338. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1339. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1340. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1341. #if defined(_WIN32)
  1342. /* vsnprintf must not be used in any system,
  1343. * but this define only works well for Windows. */
  1344. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1345. #endif
  1346. /* mg_init_library counter */
  1347. static int mg_init_library_called = 0;
  1348. #if !defined(NO_SSL)
  1349. static int mg_ssl_initialized = 0;
  1350. #endif
  1351. static pthread_key_t sTlsKey; /* Thread local storage index */
  1352. static int thread_idx_max = 0;
  1353. #if defined(MG_LEGACY_INTERFACE)
  1354. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1355. #endif
  1356. struct mg_workerTLS {
  1357. int is_master;
  1358. unsigned long thread_idx;
  1359. void *user_ptr;
  1360. #if defined(_WIN32)
  1361. HANDLE pthread_cond_helper_mutex;
  1362. struct mg_workerTLS *next_waiting_thread;
  1363. #endif
  1364. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1365. char txtbuf[4];
  1366. #endif
  1367. };
  1368. #if defined(GCC_DIAGNOSTIC)
  1369. /* Show no warning in case system functions are not used. */
  1370. #pragma GCC diagnostic push
  1371. #pragma GCC diagnostic ignored "-Wunused-function"
  1372. #endif /* defined(GCC_DIAGNOSTIC) */
  1373. #if defined(__clang__)
  1374. /* Show no warning in case system functions are not used. */
  1375. #pragma clang diagnostic push
  1376. #pragma clang diagnostic ignored "-Wunused-function"
  1377. #endif
  1378. /* Get a unique thread ID as unsigned long, independent from the data type
  1379. * of thread IDs defined by the operating system API.
  1380. * If two calls to mg_current_thread_id return the same value, they calls
  1381. * are done from the same thread. If they return different values, they are
  1382. * done from different threads. (Provided this function is used in the same
  1383. * process context and threads are not repeatedly created and deleted, but
  1384. * CivetWeb does not do that).
  1385. * This function must match the signature required for SSL id callbacks:
  1386. * CRYPTO_set_id_callback
  1387. */
  1388. FUNCTION_MAY_BE_UNUSED
  1389. static unsigned long
  1390. mg_current_thread_id(void)
  1391. {
  1392. #if defined(_WIN32)
  1393. return GetCurrentThreadId();
  1394. #else
  1395. #if defined(__clang__)
  1396. #pragma clang diagnostic push
  1397. #pragma clang diagnostic ignored "-Wunreachable-code"
  1398. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1399. * or not, so one of the two conditions will be unreachable by construction.
  1400. * Unfortunately the C standard does not define a way to check this at
  1401. * compile time, since the #if preprocessor conditions can not use the sizeof
  1402. * operator as an argument. */
  1403. #endif
  1404. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1405. /* This is the problematic case for CRYPTO_set_id_callback:
  1406. * The OS pthread_t can not be cast to unsigned long. */
  1407. struct mg_workerTLS *tls =
  1408. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1409. if (tls == NULL) {
  1410. /* SSL called from an unknown thread: Create some thread index.
  1411. */
  1412. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1413. tls->is_master = -2; /* -2 means "3rd party thread" */
  1414. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1415. pthread_setspecific(sTlsKey, tls);
  1416. }
  1417. return tls->thread_idx;
  1418. } else {
  1419. /* pthread_t may be any data type, so a simple cast to unsigned long
  1420. * can rise a warning/error, depending on the platform.
  1421. * Here memcpy is used as an anything-to-anything cast. */
  1422. unsigned long ret = 0;
  1423. pthread_t t = pthread_self();
  1424. memcpy(&ret, &t, sizeof(pthread_t));
  1425. return ret;
  1426. }
  1427. #if defined(__clang__)
  1428. #pragma clang diagnostic pop
  1429. #endif
  1430. #endif
  1431. }
  1432. FUNCTION_MAY_BE_UNUSED
  1433. static uint64_t
  1434. mg_get_current_time_ns(void)
  1435. {
  1436. struct timespec tsnow;
  1437. clock_gettime(CLOCK_REALTIME, &tsnow);
  1438. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1439. }
  1440. #if defined(GCC_DIAGNOSTIC)
  1441. /* Show no warning in case system functions are not used. */
  1442. #pragma GCC diagnostic pop
  1443. #endif /* defined(GCC_DIAGNOSTIC) */
  1444. #if defined(__clang__)
  1445. /* Show no warning in case system functions are not used. */
  1446. #pragma clang diagnostic pop
  1447. #endif
  1448. #if defined(NEED_DEBUG_TRACE_FUNC)
  1449. static void
  1450. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1451. {
  1452. va_list args;
  1453. uint64_t nsnow;
  1454. static uint64_t nslast;
  1455. struct timespec tsnow;
  1456. /* Get some operating system independent thread id */
  1457. unsigned long thread_id = mg_current_thread_id();
  1458. clock_gettime(CLOCK_REALTIME, &tsnow);
  1459. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1460. + ((uint64_t)tsnow.tv_nsec);
  1461. if (!nslast) {
  1462. nslast = nsnow;
  1463. }
  1464. flockfile(DEBUG_TRACE_STREAM);
  1465. fprintf( DEBUG_TRACE_STREAM,"*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1466. (unsigned long)tsnow.tv_sec,
  1467. (unsigned long)tsnow.tv_nsec,
  1468. nsnow - nslast,
  1469. thread_id,
  1470. func,
  1471. line);
  1472. va_start(args, fmt);
  1473. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1474. va_end(args);
  1475. putc('\n', DEBUG_TRACE_STREAM);
  1476. fflush(DEBUG_TRACE_STREAM);
  1477. funlockfile(DEBUG_TRACE_STREAM);
  1478. nslast = nsnow;
  1479. }
  1480. #endif /* NEED_DEBUG_TRACE_FUNC */
  1481. #define MD5_STATIC static
  1482. #include "md5.inl"
  1483. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1484. #if defined(NO_SOCKLEN_T)
  1485. typedef int socklen_t;
  1486. #endif /* NO_SOCKLEN_T */
  1487. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1488. #if !defined(MSG_NOSIGNAL)
  1489. #define MSG_NOSIGNAL (0)
  1490. #endif
  1491. #if defined(NO_SSL)
  1492. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1493. typedef struct SSL_CTX SSL_CTX;
  1494. #else
  1495. #if defined(NO_SSL_DL)
  1496. #include <openssl/bn.h>
  1497. #include <openssl/conf.h>
  1498. #include <openssl/crypto.h>
  1499. #include <openssl/dh.h>
  1500. #include <openssl/engine.h>
  1501. #include <openssl/err.h>
  1502. #include <openssl/opensslv.h>
  1503. #include <openssl/pem.h>
  1504. #include <openssl/ssl.h>
  1505. #include <openssl/tls1.h>
  1506. #include <openssl/x509.h>
  1507. #if defined(WOLFSSL_VERSION)
  1508. /* Additional defines for WolfSSL, see
  1509. * https://github.com/civetweb/civetweb/issues/583 */
  1510. #include "wolfssl_extras.inl"
  1511. #endif
  1512. #if defined(OPENSSL_IS_BORINGSSL)
  1513. /* From boringssl/src/include/openssl/mem.h:
  1514. *
  1515. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1516. * However, that was written in a time before Valgrind and ASAN. Since we now
  1517. * have those tools, the OpenSSL allocation functions are simply macros around
  1518. * the standard memory functions.
  1519. *
  1520. * #define OPENSSL_free free */
  1521. #define free free
  1522. // disable for boringssl
  1523. #define CONF_modules_unload(a) ((void)0)
  1524. #define ENGINE_cleanup() ((void)0)
  1525. #endif
  1526. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1527. /* If OpenSSL headers are included, automatically select the API version */
  1528. #if !defined(OPENSSL_API_1_1)
  1529. #define OPENSSL_API_1_1
  1530. #endif
  1531. #define OPENSSL_REMOVE_THREAD_STATE()
  1532. #else
  1533. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1534. #endif
  1535. #else
  1536. /* SSL loaded dynamically from DLL.
  1537. * I put the prototypes here to be independent from OpenSSL source
  1538. * installation. */
  1539. typedef struct ssl_st SSL;
  1540. typedef struct ssl_method_st SSL_METHOD;
  1541. typedef struct ssl_ctx_st SSL_CTX;
  1542. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1543. typedef struct x509_name X509_NAME;
  1544. typedef struct asn1_integer ASN1_INTEGER;
  1545. typedef struct bignum BIGNUM;
  1546. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1547. typedef struct evp_md EVP_MD;
  1548. typedef struct x509 X509;
  1549. #define SSL_CTRL_OPTIONS (32)
  1550. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1551. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1552. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1553. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1554. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1555. #define SSL_VERIFY_NONE (0)
  1556. #define SSL_VERIFY_PEER (1)
  1557. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1558. #define SSL_VERIFY_CLIENT_ONCE (4)
  1559. #define SSL_OP_ALL (0x80000BFFul)
  1560. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1561. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1562. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1563. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1564. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1565. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1566. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1567. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1568. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1569. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1570. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1571. #define SSL_CB_HANDSHAKE_START (0x10)
  1572. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1573. #define SSL_ERROR_NONE (0)
  1574. #define SSL_ERROR_SSL (1)
  1575. #define SSL_ERROR_WANT_READ (2)
  1576. #define SSL_ERROR_WANT_WRITE (3)
  1577. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1578. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1579. #define SSL_ERROR_ZERO_RETURN (6)
  1580. #define SSL_ERROR_WANT_CONNECT (7)
  1581. #define SSL_ERROR_WANT_ACCEPT (8)
  1582. #define TLSEXT_TYPE_server_name (0)
  1583. #define TLSEXT_NAMETYPE_host_name (0)
  1584. #define SSL_TLSEXT_ERR_OK (0)
  1585. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1586. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1587. #define SSL_TLSEXT_ERR_NOACK (3)
  1588. struct ssl_func {
  1589. const char *name; /* SSL function name */
  1590. void (*ptr)(void); /* Function pointer */
  1591. };
  1592. #if defined(OPENSSL_API_1_1)
  1593. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1594. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1595. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1596. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1597. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1598. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1599. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1600. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1601. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1602. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1603. #define OPENSSL_init_ssl \
  1604. (*(int (*)(uint64_t opts, \
  1605. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1606. .ptr)
  1607. #define SSL_CTX_use_PrivateKey_file \
  1608. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1609. #define SSL_CTX_use_certificate_file \
  1610. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1611. #define SSL_CTX_set_default_passwd_cb \
  1612. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1613. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1614. #define SSL_CTX_use_certificate_chain_file \
  1615. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1616. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1617. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1618. #define SSL_CTX_set_verify \
  1619. (*(void (*)(SSL_CTX *, \
  1620. int, \
  1621. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1622. .ptr)
  1623. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1624. #define SSL_CTX_load_verify_locations \
  1625. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1626. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1627. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1628. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1629. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1630. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1631. #define SSL_CIPHER_get_name \
  1632. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1633. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1634. #define SSL_CTX_set_session_id_context \
  1635. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1636. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1637. #define SSL_CTX_set_cipher_list \
  1638. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1639. #define SSL_CTX_set_options \
  1640. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1641. #define SSL_CTX_set_info_callback \
  1642. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1643. ssl_sw[32] \
  1644. .ptr)
  1645. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1646. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1647. #define SSL_CTX_callback_ctrl \
  1648. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1649. #define SSL_get_servername \
  1650. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1651. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1652. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1653. #define SSL_CTX_clear_options(ctx, op) \
  1654. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1655. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1656. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1657. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1658. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1659. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1660. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1661. SSL_CTX_callback_ctrl(ctx, \
  1662. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1663. (void (*)(void))cb)
  1664. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1665. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1666. #define SSL_set_tlsext_host_name(ctx, arg) \
  1667. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1668. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1669. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1670. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1671. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1672. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1673. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1674. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1675. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1676. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1677. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1678. #define X509_NAME_oneline \
  1679. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1680. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1681. #define EVP_get_digestbyname \
  1682. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1683. #define EVP_Digest \
  1684. (*(int (*)( \
  1685. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1686. crypto_sw[9] \
  1687. .ptr)
  1688. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1689. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1690. #define ASN1_INTEGER_to_BN \
  1691. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1692. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1693. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1694. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1695. #define OPENSSL_free(a) CRYPTO_free(a)
  1696. #define OPENSSL_REMOVE_THREAD_STATE()
  1697. /* init_ssl_ctx() function updates this array.
  1698. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1699. * of respective functions. The macros above (like SSL_connect()) are really
  1700. * just calling these functions indirectly via the pointer. */
  1701. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1702. {"SSL_accept", NULL},
  1703. {"SSL_connect", NULL},
  1704. {"SSL_read", NULL},
  1705. {"SSL_write", NULL},
  1706. {"SSL_get_error", NULL},
  1707. {"SSL_set_fd", NULL},
  1708. {"SSL_new", NULL},
  1709. {"SSL_CTX_new", NULL},
  1710. {"TLS_server_method", NULL},
  1711. {"OPENSSL_init_ssl", NULL},
  1712. {"SSL_CTX_use_PrivateKey_file", NULL},
  1713. {"SSL_CTX_use_certificate_file", NULL},
  1714. {"SSL_CTX_set_default_passwd_cb", NULL},
  1715. {"SSL_CTX_free", NULL},
  1716. {"SSL_CTX_use_certificate_chain_file", NULL},
  1717. {"TLS_client_method", NULL},
  1718. {"SSL_pending", NULL},
  1719. {"SSL_CTX_set_verify", NULL},
  1720. {"SSL_shutdown", NULL},
  1721. {"SSL_CTX_load_verify_locations", NULL},
  1722. {"SSL_CTX_set_default_verify_paths", NULL},
  1723. {"SSL_CTX_set_verify_depth", NULL},
  1724. {"SSL_get_peer_certificate", NULL},
  1725. {"SSL_get_version", NULL},
  1726. {"SSL_get_current_cipher", NULL},
  1727. {"SSL_CIPHER_get_name", NULL},
  1728. {"SSL_CTX_check_private_key", NULL},
  1729. {"SSL_CTX_set_session_id_context", NULL},
  1730. {"SSL_CTX_ctrl", NULL},
  1731. {"SSL_CTX_set_cipher_list", NULL},
  1732. {"SSL_CTX_set_options", NULL},
  1733. {"SSL_CTX_set_info_callback", NULL},
  1734. {"SSL_get_ex_data", NULL},
  1735. {"SSL_set_ex_data", NULL},
  1736. {"SSL_CTX_callback_ctrl", NULL},
  1737. {"SSL_get_servername", NULL},
  1738. {"SSL_set_SSL_CTX", NULL},
  1739. {"SSL_ctrl", NULL},
  1740. {NULL, NULL}};
  1741. /* Similar array as ssl_sw. These functions could be located in different
  1742. * lib. */
  1743. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1744. {"ERR_error_string", NULL},
  1745. {"CONF_modules_unload", NULL},
  1746. {"X509_free", NULL},
  1747. {"X509_get_subject_name", NULL},
  1748. {"X509_get_issuer_name", NULL},
  1749. {"X509_NAME_oneline", NULL},
  1750. {"X509_get_serialNumber", NULL},
  1751. {"EVP_get_digestbyname", NULL},
  1752. {"EVP_Digest", NULL},
  1753. {"i2d_X509", NULL},
  1754. {"BN_bn2hex", NULL},
  1755. {"ASN1_INTEGER_to_BN", NULL},
  1756. {"BN_free", NULL},
  1757. {"CRYPTO_free", NULL},
  1758. {"ERR_clear_error", NULL},
  1759. {NULL, NULL}};
  1760. #else
  1761. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1762. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1763. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1764. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1765. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1766. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1767. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1768. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1769. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1770. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1771. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1772. #define SSL_CTX_use_PrivateKey_file \
  1773. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1774. #define SSL_CTX_use_certificate_file \
  1775. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1776. #define SSL_CTX_set_default_passwd_cb \
  1777. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1778. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1779. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1780. #define SSL_CTX_use_certificate_chain_file \
  1781. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1782. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1783. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1784. #define SSL_CTX_set_verify \
  1785. (*(void (*)(SSL_CTX *, \
  1786. int, \
  1787. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1788. .ptr)
  1789. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1790. #define SSL_CTX_load_verify_locations \
  1791. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1792. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1793. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1794. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1795. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1796. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1797. #define SSL_CIPHER_get_name \
  1798. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1799. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1800. #define SSL_CTX_set_session_id_context \
  1801. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1802. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1803. #define SSL_CTX_set_cipher_list \
  1804. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1805. #define SSL_CTX_set_info_callback \
  1806. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1807. .ptr)
  1808. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1809. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1810. #define SSL_CTX_callback_ctrl \
  1811. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1812. #define SSL_get_servername \
  1813. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1814. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1815. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1816. #define SSL_CTX_set_options(ctx, op) \
  1817. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1818. #define SSL_CTX_clear_options(ctx, op) \
  1819. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1820. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1821. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1822. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1823. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1824. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1825. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1826. SSL_CTX_callback_ctrl(ctx, \
  1827. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1828. (void (*)(void))cb)
  1829. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1830. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1831. #define SSL_set_tlsext_host_name(ctx, arg) \
  1832. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1833. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1834. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1835. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1836. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1837. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1838. #define CRYPTO_set_locking_callback \
  1839. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1840. #define CRYPTO_set_id_callback \
  1841. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1842. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1843. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1844. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1845. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1846. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1847. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1848. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1849. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1850. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1851. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1852. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1853. #define X509_NAME_oneline \
  1854. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1855. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1856. #define i2c_ASN1_INTEGER \
  1857. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1858. #define EVP_get_digestbyname \
  1859. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1860. #define EVP_Digest \
  1861. (*(int (*)( \
  1862. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1863. crypto_sw[18] \
  1864. .ptr)
  1865. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1866. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1867. #define ASN1_INTEGER_to_BN \
  1868. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1869. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1870. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1871. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1872. #define OPENSSL_free(a) CRYPTO_free(a)
  1873. /* use here ERR_remove_state,
  1874. * while on some platforms function is not included into library due to
  1875. * deprication */
  1876. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1877. /* init_ssl_ctx() function updates this array.
  1878. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1879. * of respective functions. The macros above (like SSL_connect()) are really
  1880. * just calling these functions indirectly via the pointer. */
  1881. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1882. {"SSL_accept", NULL},
  1883. {"SSL_connect", NULL},
  1884. {"SSL_read", NULL},
  1885. {"SSL_write", NULL},
  1886. {"SSL_get_error", NULL},
  1887. {"SSL_set_fd", NULL},
  1888. {"SSL_new", NULL},
  1889. {"SSL_CTX_new", NULL},
  1890. {"SSLv23_server_method", NULL},
  1891. {"SSL_library_init", NULL},
  1892. {"SSL_CTX_use_PrivateKey_file", NULL},
  1893. {"SSL_CTX_use_certificate_file", NULL},
  1894. {"SSL_CTX_set_default_passwd_cb", NULL},
  1895. {"SSL_CTX_free", NULL},
  1896. {"SSL_load_error_strings", NULL},
  1897. {"SSL_CTX_use_certificate_chain_file", NULL},
  1898. {"SSLv23_client_method", NULL},
  1899. {"SSL_pending", NULL},
  1900. {"SSL_CTX_set_verify", NULL},
  1901. {"SSL_shutdown", NULL},
  1902. {"SSL_CTX_load_verify_locations", NULL},
  1903. {"SSL_CTX_set_default_verify_paths", NULL},
  1904. {"SSL_CTX_set_verify_depth", NULL},
  1905. {"SSL_get_peer_certificate", NULL},
  1906. {"SSL_get_version", NULL},
  1907. {"SSL_get_current_cipher", NULL},
  1908. {"SSL_CIPHER_get_name", NULL},
  1909. {"SSL_CTX_check_private_key", NULL},
  1910. {"SSL_CTX_set_session_id_context", NULL},
  1911. {"SSL_CTX_ctrl", NULL},
  1912. {"SSL_CTX_set_cipher_list", NULL},
  1913. {"SSL_CTX_set_info_callback", NULL},
  1914. {"SSL_get_ex_data", NULL},
  1915. {"SSL_set_ex_data", NULL},
  1916. {"SSL_CTX_callback_ctrl", NULL},
  1917. {"SSL_get_servername", NULL},
  1918. {"SSL_set_SSL_CTX", NULL},
  1919. {"SSL_ctrl", NULL},
  1920. {NULL, NULL}};
  1921. /* Similar array as ssl_sw. These functions could be located in different
  1922. * lib. */
  1923. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1924. {"CRYPTO_set_locking_callback", NULL},
  1925. {"CRYPTO_set_id_callback", NULL},
  1926. {"ERR_get_error", NULL},
  1927. {"ERR_error_string", NULL},
  1928. {"ERR_remove_state", NULL},
  1929. {"ERR_free_strings", NULL},
  1930. {"ENGINE_cleanup", NULL},
  1931. {"CONF_modules_unload", NULL},
  1932. {"CRYPTO_cleanup_all_ex_data", NULL},
  1933. {"EVP_cleanup", NULL},
  1934. {"X509_free", NULL},
  1935. {"X509_get_subject_name", NULL},
  1936. {"X509_get_issuer_name", NULL},
  1937. {"X509_NAME_oneline", NULL},
  1938. {"X509_get_serialNumber", NULL},
  1939. {"i2c_ASN1_INTEGER", NULL},
  1940. {"EVP_get_digestbyname", NULL},
  1941. {"EVP_Digest", NULL},
  1942. {"i2d_X509", NULL},
  1943. {"BN_bn2hex", NULL},
  1944. {"ASN1_INTEGER_to_BN", NULL},
  1945. {"BN_free", NULL},
  1946. {"CRYPTO_free", NULL},
  1947. {"ERR_clear_error", NULL},
  1948. {NULL, NULL}};
  1949. #endif /* OPENSSL_API_1_1 */
  1950. #endif /* NO_SSL_DL */
  1951. #endif /* NO_SSL */
  1952. #if !defined(NO_CACHING)
  1953. static const char month_names[][4] = {"Jan",
  1954. "Feb",
  1955. "Mar",
  1956. "Apr",
  1957. "May",
  1958. "Jun",
  1959. "Jul",
  1960. "Aug",
  1961. "Sep",
  1962. "Oct",
  1963. "Nov",
  1964. "Dec"};
  1965. #endif /* !NO_CACHING */
  1966. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1967. * the
  1968. * union u. */
  1969. union usa {
  1970. struct sockaddr sa;
  1971. struct sockaddr_in sin;
  1972. #if defined(USE_IPV6)
  1973. struct sockaddr_in6 sin6;
  1974. #endif
  1975. };
  1976. /* Describes a string (chunk of memory). */
  1977. struct vec {
  1978. const char *ptr;
  1979. size_t len;
  1980. };
  1981. struct mg_file_stat {
  1982. /* File properties filled by mg_stat: */
  1983. uint64_t size;
  1984. time_t last_modified;
  1985. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1986. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1987. * case we need a "Content-Eencoding: gzip" header */
  1988. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1989. };
  1990. struct mg_file_in_memory {
  1991. char *p;
  1992. uint32_t pos;
  1993. char mode;
  1994. };
  1995. struct mg_file_access {
  1996. /* File properties filled by mg_fopen: */
  1997. FILE *fp;
  1998. #if defined(MG_USE_OPEN_FILE)
  1999. /* TODO (low): Remove obsolete "file in memory" implementation.
  2000. * In an "early 2017" discussion at Google groups
  2001. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2002. * we decided to get rid of this feature (after some fade-out
  2003. * phase). */
  2004. const char *membuf;
  2005. #endif
  2006. };
  2007. struct mg_file {
  2008. struct mg_file_stat stat;
  2009. struct mg_file_access access;
  2010. };
  2011. #if defined(MG_USE_OPEN_FILE)
  2012. #define STRUCT_FILE_INITIALIZER \
  2013. { \
  2014. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2015. { \
  2016. (FILE *)NULL, (const char *)NULL \
  2017. } \
  2018. }
  2019. #else
  2020. #define STRUCT_FILE_INITIALIZER \
  2021. { \
  2022. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2023. { \
  2024. (FILE *)NULL \
  2025. } \
  2026. }
  2027. #endif
  2028. /* Describes listening socket, or socket which was accept()-ed by the master
  2029. * thread and queued for future handling by the worker thread. */
  2030. struct socket {
  2031. SOCKET sock; /* Listening socket */
  2032. union usa lsa; /* Local socket address */
  2033. union usa rsa; /* Remote socket address */
  2034. unsigned char is_ssl; /* Is port SSL-ed */
  2035. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2036. * port */
  2037. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2038. };
  2039. /* Enum const for all options must be in sync with
  2040. * static struct mg_option config_options[]
  2041. * This is tested in the unit test (test/private.c)
  2042. * "Private Config Options"
  2043. */
  2044. enum {
  2045. /* Once for each server */
  2046. LISTENING_PORTS,
  2047. NUM_THREADS,
  2048. RUN_AS_USER,
  2049. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2050. * socket option typedef TCP_NODELAY. */
  2051. MAX_REQUEST_SIZE,
  2052. LINGER_TIMEOUT,
  2053. CONNECTION_QUEUE_SIZE,
  2054. LISTEN_BACKLOG_SIZE,
  2055. #if defined(__linux__)
  2056. ALLOW_SENDFILE_CALL,
  2057. #endif
  2058. #if defined(_WIN32)
  2059. CASE_SENSITIVE_FILES,
  2060. #endif
  2061. THROTTLE,
  2062. ACCESS_LOG_FILE,
  2063. ERROR_LOG_FILE,
  2064. ENABLE_KEEP_ALIVE,
  2065. REQUEST_TIMEOUT,
  2066. KEEP_ALIVE_TIMEOUT,
  2067. #if defined(USE_WEBSOCKET)
  2068. WEBSOCKET_TIMEOUT,
  2069. ENABLE_WEBSOCKET_PING_PONG,
  2070. #endif
  2071. DECODE_URL,
  2072. #if defined(USE_LUA)
  2073. LUA_BACKGROUND_SCRIPT,
  2074. LUA_BACKGROUND_SCRIPT_PARAMS,
  2075. #endif
  2076. #if defined(USE_TIMERS)
  2077. CGI_TIMEOUT,
  2078. #endif
  2079. /* Once for each domain */
  2080. DOCUMENT_ROOT,
  2081. CGI_EXTENSIONS,
  2082. CGI_ENVIRONMENT,
  2083. PUT_DELETE_PASSWORDS_FILE,
  2084. CGI_INTERPRETER,
  2085. PROTECT_URI,
  2086. AUTHENTICATION_DOMAIN,
  2087. ENABLE_AUTH_DOMAIN_CHECK,
  2088. SSI_EXTENSIONS,
  2089. ENABLE_DIRECTORY_LISTING,
  2090. GLOBAL_PASSWORDS_FILE,
  2091. INDEX_FILES,
  2092. ACCESS_CONTROL_LIST,
  2093. EXTRA_MIME_TYPES,
  2094. SSL_CERTIFICATE,
  2095. SSL_CERTIFICATE_CHAIN,
  2096. URL_REWRITE_PATTERN,
  2097. HIDE_FILES,
  2098. SSL_DO_VERIFY_PEER,
  2099. SSL_CA_PATH,
  2100. SSL_CA_FILE,
  2101. SSL_VERIFY_DEPTH,
  2102. SSL_DEFAULT_VERIFY_PATHS,
  2103. SSL_CIPHER_LIST,
  2104. SSL_PROTOCOL_VERSION,
  2105. SSL_SHORT_TRUST,
  2106. #if defined(USE_LUA)
  2107. LUA_PRELOAD_FILE,
  2108. LUA_SCRIPT_EXTENSIONS,
  2109. LUA_SERVER_PAGE_EXTENSIONS,
  2110. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2111. LUA_DEBUG_PARAMS,
  2112. #endif
  2113. #endif
  2114. #if defined(USE_DUKTAPE)
  2115. DUKTAPE_SCRIPT_EXTENSIONS,
  2116. #endif
  2117. #if defined(USE_WEBSOCKET)
  2118. WEBSOCKET_ROOT,
  2119. #endif
  2120. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2121. LUA_WEBSOCKET_EXTENSIONS,
  2122. #endif
  2123. ACCESS_CONTROL_ALLOW_ORIGIN,
  2124. ACCESS_CONTROL_ALLOW_METHODS,
  2125. ACCESS_CONTROL_ALLOW_HEADERS,
  2126. ERROR_PAGES,
  2127. #if !defined(NO_CACHING)
  2128. STATIC_FILE_MAX_AGE,
  2129. STATIC_FILE_CACHE_CONTROL,
  2130. #endif
  2131. #if !defined(NO_SSL)
  2132. STRICT_HTTPS_MAX_AGE,
  2133. #endif
  2134. ADDITIONAL_HEADER,
  2135. ALLOW_INDEX_SCRIPT_SUB_RES,
  2136. #if defined(DAEMONIZE)
  2137. ENABLE_DAEMONIZE,
  2138. #endif
  2139. NUM_OPTIONS
  2140. };
  2141. /* Config option name, config types, default value.
  2142. * Must be in the same order as the enum const above.
  2143. */
  2144. static const struct mg_option config_options[] = {
  2145. /* Once for each server */
  2146. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2147. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2148. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2149. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2150. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2151. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2152. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2153. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2154. #if defined(__linux__)
  2155. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2156. #endif
  2157. #if defined(_WIN32)
  2158. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2159. #endif
  2160. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2161. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2162. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2163. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2164. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2165. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2166. #if defined(USE_WEBSOCKET)
  2167. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2168. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2169. #endif
  2170. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2171. #if defined(USE_LUA)
  2172. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2173. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2174. #endif
  2175. #if defined(USE_TIMERS)
  2176. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2177. #endif
  2178. /* Once for each domain */
  2179. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2180. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2181. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2182. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2183. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2184. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2185. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2186. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2187. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2188. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2189. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2190. {"index_files",
  2191. MG_CONFIG_TYPE_STRING_LIST,
  2192. #if defined(USE_LUA)
  2193. "index.xhtml,index.html,index.htm,"
  2194. "index.lp,index.lsp,index.lua,index.cgi,"
  2195. "index.shtml,index.php"},
  2196. #else
  2197. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2198. #endif
  2199. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2200. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2201. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2202. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2203. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2204. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2205. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2206. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2207. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2208. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2209. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2210. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2211. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2212. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2213. #if defined(USE_LUA)
  2214. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2215. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2216. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2217. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2218. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2219. #endif
  2220. #endif
  2221. #if defined(USE_DUKTAPE)
  2222. /* The support for duktape is still in alpha version state.
  2223. * The name of this config option might change. */
  2224. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2225. #endif
  2226. #if defined(USE_WEBSOCKET)
  2227. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2228. #endif
  2229. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2230. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2231. #endif
  2232. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2233. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2234. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2235. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2236. #if !defined(NO_CACHING)
  2237. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2238. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2239. #endif
  2240. #if !defined(NO_SSL)
  2241. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2242. #endif
  2243. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2244. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2245. #if defined(DAEMONIZE)
  2246. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2247. #endif
  2248. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2249. /* Check if the config_options and the corresponding enum have compatible
  2250. * sizes. */
  2251. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2252. == (NUM_OPTIONS + 1),
  2253. "config_options and enum not sync");
  2254. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2255. struct mg_handler_info {
  2256. /* Name/Pattern of the URI. */
  2257. char *uri;
  2258. size_t uri_len;
  2259. /* handler type */
  2260. int handler_type;
  2261. /* Handler for http/https or authorization requests. */
  2262. mg_request_handler handler;
  2263. unsigned int refcount;
  2264. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2265. pthread_cond_t
  2266. refcount_cond; /* Signaled when handler refcount is decremented */
  2267. /* Handler for ws/wss (websocket) requests. */
  2268. mg_websocket_connect_handler connect_handler;
  2269. mg_websocket_ready_handler ready_handler;
  2270. mg_websocket_data_handler data_handler;
  2271. mg_websocket_close_handler close_handler;
  2272. /* accepted subprotocols for ws/wss requests. */
  2273. struct mg_websocket_subprotocols *subprotocols;
  2274. /* Handler for authorization requests */
  2275. mg_authorization_handler auth_handler;
  2276. /* User supplied argument for the handler function. */
  2277. void *cbdata;
  2278. /* next handler in a linked list */
  2279. struct mg_handler_info *next;
  2280. };
  2281. enum {
  2282. CONTEXT_INVALID,
  2283. CONTEXT_SERVER,
  2284. CONTEXT_HTTP_CLIENT,
  2285. CONTEXT_WS_CLIENT
  2286. };
  2287. struct mg_domain_context {
  2288. SSL_CTX *ssl_ctx; /* SSL context */
  2289. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2290. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2291. /* Server nonce */
  2292. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2293. unsigned long nonce_count; /* Used nonces, used for authentication */
  2294. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2295. /* linked list of shared lua websockets */
  2296. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2297. #endif
  2298. /* Linked list of domains */
  2299. struct mg_domain_context *next;
  2300. };
  2301. struct mg_context {
  2302. /* Part 1 - Physical context:
  2303. * This holds threads, ports, timeouts, ...
  2304. * set for the entire server, independent from the
  2305. * addressed hostname.
  2306. */
  2307. /* Connection related */
  2308. int context_type; /* See CONTEXT_* above */
  2309. struct socket *listening_sockets;
  2310. struct mg_pollfd *listening_socket_fds;
  2311. unsigned int num_listening_sockets;
  2312. struct mg_connection *worker_connections; /* The connection struct, pre-
  2313. * allocated for each worker */
  2314. #if defined(USE_SERVER_STATS)
  2315. int active_connections;
  2316. int max_active_connections;
  2317. int64_t total_connections;
  2318. int64_t total_requests;
  2319. int64_t total_data_read;
  2320. int64_t total_data_written;
  2321. #endif
  2322. /* Thread related */
  2323. volatile int stop_flag; /* Should we stop event loop */
  2324. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2325. pthread_t masterthreadid; /* The master thread ID */
  2326. unsigned int
  2327. cfg_worker_threads; /* The number of configured worker threads. */
  2328. pthread_t *worker_threadids; /* The worker thread IDs */
  2329. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2330. /* Connection to thread dispatching */
  2331. #if defined(ALTERNATIVE_QUEUE)
  2332. struct socket *client_socks;
  2333. void **client_wait_events;
  2334. #else
  2335. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2336. worker thread */
  2337. volatile int sq_head; /* Head of the socket queue */
  2338. volatile int sq_tail; /* Tail of the socket queue */
  2339. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2340. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2341. volatile int sq_blocked; /* Status information: sq is full */
  2342. int sq_size; /* No of elements in socket queue */
  2343. #if defined(USE_SERVER_STATS)
  2344. int sq_max_fill;
  2345. #endif /* USE_SERVER_STATS */
  2346. #endif /* ALTERNATIVE_QUEUE */
  2347. /* Memory related */
  2348. unsigned int max_request_size; /* The max request size */
  2349. #if defined(USE_SERVER_STATS)
  2350. struct mg_memory_stat ctx_memory;
  2351. #endif
  2352. /* Operating system related */
  2353. char *systemName; /* What operating system is running */
  2354. time_t start_time; /* Server start time, used for authentication
  2355. * and for diagnstics. */
  2356. #if defined(USE_TIMERS)
  2357. struct ttimers *timers;
  2358. #endif
  2359. /* Lua specific: Background operations and shared websockets */
  2360. #if defined(USE_LUA)
  2361. void *lua_background_state;
  2362. #endif
  2363. /* Server nonce */
  2364. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2365. /* Server callbacks */
  2366. struct mg_callbacks callbacks; /* User-defined callback function */
  2367. void *user_data; /* User-defined data */
  2368. /* Part 2 - Logical domain:
  2369. * This holds hostname, TLS certificate, document root, ...
  2370. * set for a domain hosted at the server.
  2371. * There may be multiple domains hosted at one physical server.
  2372. * The default domain "dd" is the first element of a list of
  2373. * domains.
  2374. */
  2375. struct mg_domain_context dd; /* default domain */
  2376. };
  2377. #if defined(USE_SERVER_STATS)
  2378. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2379. static struct mg_memory_stat *
  2380. get_memory_stat(struct mg_context *ctx)
  2381. {
  2382. if (ctx) {
  2383. return &(ctx->ctx_memory);
  2384. }
  2385. return &mg_common_memory;
  2386. }
  2387. #endif
  2388. enum {
  2389. CONNECTION_TYPE_INVALID,
  2390. CONNECTION_TYPE_REQUEST,
  2391. CONNECTION_TYPE_RESPONSE
  2392. };
  2393. struct mg_connection {
  2394. int connection_type; /* see CONNECTION_TYPE_* above */
  2395. struct mg_request_info request_info;
  2396. struct mg_response_info response_info;
  2397. struct mg_context *phys_ctx;
  2398. struct mg_domain_context *dom_ctx;
  2399. #if defined(USE_SERVER_STATS)
  2400. int conn_state; /* 0 = undef, numerical value may change in different
  2401. * versions. For the current definition, see
  2402. * mg_get_connection_info_impl */
  2403. #endif
  2404. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2405. SSL *ssl; /* SSL descriptor */
  2406. struct socket client; /* Connected client */
  2407. time_t conn_birth_time; /* Time (wall clock) when connection was
  2408. * established */
  2409. #if defined(USE_SERVER_STATS)
  2410. time_t conn_close_time; /* Time (wall clock) when connection was
  2411. * closed (or 0 if still open) */
  2412. #endif
  2413. struct timespec req_time; /* Time (since system start) when the request
  2414. * was received */
  2415. int64_t num_bytes_sent; /* Total bytes sent to client */
  2416. int64_t content_len; /* How many bytes of content can be read
  2417. * !is_chunked: Content-Length header value
  2418. * or -1 (until connection closed,
  2419. * not allowed for a request)
  2420. * is_chunked: >= 0, appended gradually
  2421. */
  2422. int64_t consumed_content; /* How many bytes of content have been read */
  2423. int is_chunked; /* Transfer-Encoding is chunked:
  2424. * 0 = not chunked,
  2425. * 1 = chunked, not yet, or some data read,
  2426. * 2 = chunked, has error,
  2427. * 3 = chunked, all data read except trailer,
  2428. * 4 = chunked, all data read
  2429. */
  2430. char *buf; /* Buffer for received data */
  2431. char *path_info; /* PATH_INFO part of the URL */
  2432. int must_close; /* 1 if connection must be closed */
  2433. int accept_gzip; /* 1 if gzip encoding is accepted */
  2434. int in_error_handler; /* 1 if in handler for user defined error
  2435. * pages */
  2436. #if defined(USE_WEBSOCKET)
  2437. int in_websocket_handling; /* 1 if in read_websocket */
  2438. #endif
  2439. int handled_requests; /* Number of requests handled by this connection
  2440. */
  2441. int buf_size; /* Buffer size */
  2442. int request_len; /* Size of the request + headers in a buffer */
  2443. int data_len; /* Total size of data in a buffer */
  2444. int status_code; /* HTTP reply status code, e.g. 200 */
  2445. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2446. * throttle */
  2447. time_t last_throttle_time; /* Last time throttled data was sent */
  2448. int last_throttle_bytes; /* Bytes sent this second */
  2449. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2450. * atomic transmissions for websockets */
  2451. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2452. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2453. #endif
  2454. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2455. * for quick access */
  2456. };
  2457. /* Directory entry */
  2458. struct de {
  2459. struct mg_connection *conn;
  2460. char *file_name;
  2461. struct mg_file_stat file;
  2462. };
  2463. #if defined(USE_WEBSOCKET)
  2464. static int is_websocket_protocol(const struct mg_connection *conn);
  2465. #else
  2466. #define is_websocket_protocol(conn) (0)
  2467. #endif
  2468. #define mg_cry_internal(conn, fmt, ...) \
  2469. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2470. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2471. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2472. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2473. struct mg_context *ctx,
  2474. const char *func,
  2475. unsigned line,
  2476. const char *fmt,
  2477. ...) PRINTF_ARGS(5, 6);
  2478. #if !defined(NO_THREAD_NAME)
  2479. #if defined(_WIN32) && defined(_MSC_VER)
  2480. /* Set the thread name for debugging purposes in Visual Studio
  2481. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2482. */
  2483. #pragma pack(push, 8)
  2484. typedef struct tagTHREADNAME_INFO {
  2485. DWORD dwType; /* Must be 0x1000. */
  2486. LPCSTR szName; /* Pointer to name (in user addr space). */
  2487. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2488. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2489. } THREADNAME_INFO;
  2490. #pragma pack(pop)
  2491. #elif defined(__linux__)
  2492. #include <sys/prctl.h>
  2493. #include <sys/sendfile.h>
  2494. #if defined(ALTERNATIVE_QUEUE)
  2495. #include <sys/eventfd.h>
  2496. #endif /* ALTERNATIVE_QUEUE */
  2497. #if defined(ALTERNATIVE_QUEUE)
  2498. static void *
  2499. event_create(void)
  2500. {
  2501. int evhdl = eventfd(0, EFD_CLOEXEC);
  2502. int *ret;
  2503. if (evhdl == -1) {
  2504. /* Linux uses -1 on error, Windows NULL. */
  2505. /* However, Linux does not return 0 on success either. */
  2506. return 0;
  2507. }
  2508. ret = (int *)mg_malloc(sizeof(int));
  2509. if (ret) {
  2510. *ret = evhdl;
  2511. } else {
  2512. (void)close(evhdl);
  2513. }
  2514. return (void *)ret;
  2515. }
  2516. static int
  2517. event_wait(void *eventhdl)
  2518. {
  2519. uint64_t u;
  2520. int evhdl, s;
  2521. if (!eventhdl) {
  2522. /* error */
  2523. return 0;
  2524. }
  2525. evhdl = *(int *)eventhdl;
  2526. s = (int)read(evhdl, &u, sizeof(u));
  2527. if (s != sizeof(u)) {
  2528. /* error */
  2529. return 0;
  2530. }
  2531. (void)u; /* the value is not required */
  2532. return 1;
  2533. }
  2534. static int
  2535. event_signal(void *eventhdl)
  2536. {
  2537. uint64_t u = 1;
  2538. int evhdl, s;
  2539. if (!eventhdl) {
  2540. /* error */
  2541. return 0;
  2542. }
  2543. evhdl = *(int *)eventhdl;
  2544. s = (int)write(evhdl, &u, sizeof(u));
  2545. if (s != sizeof(u)) {
  2546. /* error */
  2547. return 0;
  2548. }
  2549. return 1;
  2550. }
  2551. static void
  2552. event_destroy(void *eventhdl)
  2553. {
  2554. int evhdl;
  2555. if (!eventhdl) {
  2556. /* error */
  2557. return;
  2558. }
  2559. evhdl = *(int *)eventhdl;
  2560. close(evhdl);
  2561. mg_free(eventhdl);
  2562. }
  2563. #endif
  2564. #endif
  2565. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2566. struct posix_event {
  2567. pthread_mutex_t mutex;
  2568. pthread_cond_t cond;
  2569. int signaled;
  2570. };
  2571. static void *
  2572. event_create(void)
  2573. {
  2574. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2575. if (ret == 0) {
  2576. /* out of memory */
  2577. return 0;
  2578. }
  2579. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2580. /* pthread mutex not available */
  2581. mg_free(ret);
  2582. return 0;
  2583. }
  2584. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2585. /* pthread cond not available */
  2586. pthread_mutex_destroy(&(ret->mutex));
  2587. mg_free(ret);
  2588. return 0;
  2589. }
  2590. ret->signaled = 0;
  2591. return (void *)ret;
  2592. }
  2593. static int
  2594. event_wait(void *eventhdl)
  2595. {
  2596. struct posix_event *ev = (struct posix_event *)eventhdl;
  2597. pthread_mutex_lock(&(ev->mutex));
  2598. while (!ev->signaled) {
  2599. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2600. }
  2601. ev->signaled = 0;
  2602. pthread_mutex_unlock(&(ev->mutex));
  2603. return 1;
  2604. }
  2605. static int
  2606. event_signal(void *eventhdl)
  2607. {
  2608. struct posix_event *ev = (struct posix_event *)eventhdl;
  2609. pthread_mutex_lock(&(ev->mutex));
  2610. pthread_cond_signal(&(ev->cond));
  2611. ev->signaled = 1;
  2612. pthread_mutex_unlock(&(ev->mutex));
  2613. return 1;
  2614. }
  2615. static void
  2616. event_destroy(void *eventhdl)
  2617. {
  2618. struct posix_event *ev = (struct posix_event *)eventhdl;
  2619. pthread_cond_destroy(&(ev->cond));
  2620. pthread_mutex_destroy(&(ev->mutex));
  2621. mg_free(ev);
  2622. }
  2623. #endif
  2624. static void
  2625. mg_set_thread_name(const char *name)
  2626. {
  2627. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2628. mg_snprintf(
  2629. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2630. #if defined(_WIN32)
  2631. #if defined(_MSC_VER)
  2632. /* Windows and Visual Studio Compiler */
  2633. __try {
  2634. THREADNAME_INFO info;
  2635. info.dwType = 0x1000;
  2636. info.szName = threadName;
  2637. info.dwThreadID = ~0U;
  2638. info.dwFlags = 0;
  2639. RaiseException(0x406D1388,
  2640. 0,
  2641. sizeof(info) / sizeof(ULONG_PTR),
  2642. (ULONG_PTR *)&info);
  2643. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2644. }
  2645. #elif defined(__MINGW32__)
  2646. /* No option known to set thread name for MinGW known */
  2647. #endif
  2648. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2649. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2650. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2651. #if defined(__MACH__)
  2652. /* OS X only current thread name can be changed */
  2653. (void)pthread_setname_np(threadName);
  2654. #else
  2655. (void)pthread_setname_np(pthread_self(), threadName);
  2656. #endif
  2657. #elif defined(__linux__)
  2658. /* On Linux we can use the prctl function.
  2659. * When building for Linux Standard Base (LSB) use
  2660. * NO_THREAD_NAME. However, thread names are a big
  2661. * help for debugging, so the stadard is to set them.
  2662. */
  2663. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2664. #endif
  2665. }
  2666. #else /* !defined(NO_THREAD_NAME) */
  2667. void
  2668. mg_set_thread_name(const char *threadName)
  2669. {
  2670. }
  2671. #endif
  2672. #if defined(MG_LEGACY_INTERFACE)
  2673. const char **
  2674. mg_get_valid_option_names(void)
  2675. {
  2676. /* This function is deprecated. Use mg_get_valid_options instead. */
  2677. static const char
  2678. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2679. int i;
  2680. for (i = 0; config_options[i].name != NULL; i++) {
  2681. data[i * 2] = config_options[i].name;
  2682. data[i * 2 + 1] = config_options[i].default_value;
  2683. }
  2684. return data;
  2685. }
  2686. #endif
  2687. const struct mg_option *
  2688. mg_get_valid_options(void)
  2689. {
  2690. return config_options;
  2691. }
  2692. /* Do not open file (used in is_file_in_memory) */
  2693. #define MG_FOPEN_MODE_NONE (0)
  2694. /* Open file for read only access */
  2695. #define MG_FOPEN_MODE_READ (1)
  2696. /* Open file for writing, create and overwrite */
  2697. #define MG_FOPEN_MODE_WRITE (2)
  2698. /* Open file for writing, create and append */
  2699. #define MG_FOPEN_MODE_APPEND (4)
  2700. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2701. * output filep and return 1, otherwise return 0 and don't modify anything.
  2702. */
  2703. static int
  2704. open_file_in_memory(const struct mg_connection *conn,
  2705. const char *path,
  2706. struct mg_file *filep,
  2707. int mode)
  2708. {
  2709. #if defined(MG_USE_OPEN_FILE)
  2710. size_t size = 0;
  2711. const char *buf = NULL;
  2712. if (!conn) {
  2713. return 0;
  2714. }
  2715. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2716. return 0;
  2717. }
  2718. if (conn->phys_ctx->callbacks.open_file) {
  2719. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2720. if (buf != NULL) {
  2721. if (filep == NULL) {
  2722. /* This is a file in memory, but we cannot store the
  2723. * properties
  2724. * now.
  2725. * Called from "is_file_in_memory" function. */
  2726. return 1;
  2727. }
  2728. /* NOTE: override filep->size only on success. Otherwise, it
  2729. * might
  2730. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2731. filep->access.membuf = buf;
  2732. filep->access.fp = NULL;
  2733. /* Size was set by the callback */
  2734. filep->stat.size = size;
  2735. /* Assume the data may change during runtime by setting
  2736. * last_modified = now */
  2737. filep->stat.last_modified = time(NULL);
  2738. filep->stat.is_directory = 0;
  2739. filep->stat.is_gzipped = 0;
  2740. }
  2741. }
  2742. return (buf != NULL);
  2743. #else
  2744. (void)conn;
  2745. (void)path;
  2746. (void)filep;
  2747. (void)mode;
  2748. return 0;
  2749. #endif
  2750. }
  2751. static int
  2752. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2753. {
  2754. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2755. }
  2756. static int
  2757. is_file_opened(const struct mg_file_access *fileacc)
  2758. {
  2759. if (!fileacc) {
  2760. return 0;
  2761. }
  2762. #if defined(MG_USE_OPEN_FILE)
  2763. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2764. #else
  2765. return (fileacc->fp != NULL);
  2766. #endif
  2767. }
  2768. #if !defined(NO_FILESYSTEMS)
  2769. static int mg_stat(const struct mg_connection *conn,
  2770. const char *path,
  2771. struct mg_file_stat *filep);
  2772. /* mg_fopen will open a file either in memory or on the disk.
  2773. * The input parameter path is a string in UTF-8 encoding.
  2774. * The input parameter mode is MG_FOPEN_MODE_*
  2775. * On success, either fp or membuf will be set in the output
  2776. * struct file. All status members will also be set.
  2777. * The function returns 1 on success, 0 on error. */
  2778. static int
  2779. mg_fopen(const struct mg_connection *conn,
  2780. const char *path,
  2781. int mode,
  2782. struct mg_file *filep)
  2783. {
  2784. int found;
  2785. if (!filep) {
  2786. return 0;
  2787. }
  2788. filep->access.fp = NULL;
  2789. #if defined(MG_USE_OPEN_FILE)
  2790. filep->access.membuf = NULL;
  2791. #endif
  2792. if (!is_file_in_memory(conn, path)) {
  2793. /* filep is initialized in mg_stat: all fields with memset to,
  2794. * some fields like size and modification date with values */
  2795. found = mg_stat(conn, path, &(filep->stat));
  2796. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2797. /* file does not exist and will not be created */
  2798. return 0;
  2799. }
  2800. #if defined(_WIN32)
  2801. {
  2802. wchar_t wbuf[W_PATH_MAX];
  2803. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2804. switch (mode) {
  2805. case MG_FOPEN_MODE_READ:
  2806. filep->access.fp = _wfopen(wbuf, L"rb");
  2807. break;
  2808. case MG_FOPEN_MODE_WRITE:
  2809. filep->access.fp = _wfopen(wbuf, L"wb");
  2810. break;
  2811. case MG_FOPEN_MODE_APPEND:
  2812. filep->access.fp = _wfopen(wbuf, L"ab");
  2813. break;
  2814. }
  2815. }
  2816. #else
  2817. /* Linux et al already use unicode. No need to convert. */
  2818. switch (mode) {
  2819. case MG_FOPEN_MODE_READ:
  2820. filep->access.fp = fopen(path, "r");
  2821. break;
  2822. case MG_FOPEN_MODE_WRITE:
  2823. filep->access.fp = fopen(path, "w");
  2824. break;
  2825. case MG_FOPEN_MODE_APPEND:
  2826. filep->access.fp = fopen(path, "a");
  2827. break;
  2828. }
  2829. #endif
  2830. if (!found) {
  2831. /* File did not exist before fopen was called.
  2832. * Maybe it has been created now. Get stat info
  2833. * like creation time now. */
  2834. found = mg_stat(conn, path, &(filep->stat));
  2835. (void)found;
  2836. }
  2837. /* file is on disk */
  2838. return (filep->access.fp != NULL);
  2839. } else {
  2840. #if defined(MG_USE_OPEN_FILE)
  2841. /* is_file_in_memory returned true */
  2842. if (open_file_in_memory(conn, path, filep, mode)) {
  2843. /* file is in memory */
  2844. return (filep->access.membuf != NULL);
  2845. }
  2846. #endif
  2847. }
  2848. /* Open failed */
  2849. return 0;
  2850. }
  2851. /* return 0 on success, just like fclose */
  2852. static int
  2853. mg_fclose(struct mg_file_access *fileacc)
  2854. {
  2855. int ret = -1;
  2856. if (fileacc != NULL) {
  2857. if (fileacc->fp != NULL) {
  2858. ret = fclose(fileacc->fp);
  2859. #if defined(MG_USE_OPEN_FILE)
  2860. } else if (fileacc->membuf != NULL) {
  2861. ret = 0;
  2862. #endif
  2863. }
  2864. /* reset all members of fileacc */
  2865. memset(fileacc, 0, sizeof(*fileacc));
  2866. }
  2867. return ret;
  2868. }
  2869. #endif /* NO_FILESYSTEMS */
  2870. static void
  2871. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2872. {
  2873. for (; *src != '\0' && n > 1; n--) {
  2874. *dst++ = *src++;
  2875. }
  2876. *dst = '\0';
  2877. }
  2878. static int
  2879. lowercase(const char *s)
  2880. {
  2881. return tolower((unsigned char)*s);
  2882. }
  2883. int
  2884. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2885. {
  2886. int diff = 0;
  2887. if (len > 0) {
  2888. do {
  2889. diff = lowercase(s1++) - lowercase(s2++);
  2890. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2891. }
  2892. return diff;
  2893. }
  2894. int
  2895. mg_strcasecmp(const char *s1, const char *s2)
  2896. {
  2897. int diff;
  2898. do {
  2899. diff = lowercase(s1++) - lowercase(s2++);
  2900. } while (diff == 0 && s1[-1] != '\0');
  2901. return diff;
  2902. }
  2903. static char *
  2904. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2905. {
  2906. char *p;
  2907. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2908. * defined */
  2909. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2910. mg_strlcpy(p, ptr, len + 1);
  2911. }
  2912. return p;
  2913. }
  2914. static char *
  2915. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2916. {
  2917. return mg_strndup_ctx(str, strlen(str), ctx);
  2918. }
  2919. static char *
  2920. mg_strdup(const char *str)
  2921. {
  2922. return mg_strndup_ctx(str, strlen(str), NULL);
  2923. }
  2924. static const char *
  2925. mg_strcasestr(const char *big_str, const char *small_str)
  2926. {
  2927. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2928. if (big_len >= small_len) {
  2929. for (i = 0; i <= (big_len - small_len); i++) {
  2930. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2931. return big_str + i;
  2932. }
  2933. }
  2934. }
  2935. return NULL;
  2936. }
  2937. /* Return null terminated string of given maximum length.
  2938. * Report errors if length is exceeded. */
  2939. static void
  2940. mg_vsnprintf(const struct mg_connection *conn,
  2941. int *truncated,
  2942. char *buf,
  2943. size_t buflen,
  2944. const char *fmt,
  2945. va_list ap)
  2946. {
  2947. int n, ok;
  2948. if (buflen == 0) {
  2949. if (truncated) {
  2950. *truncated = 1;
  2951. }
  2952. return;
  2953. }
  2954. #if defined(__clang__)
  2955. #pragma clang diagnostic push
  2956. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2957. /* Using fmt as a non-literal is intended here, since it is mostly called
  2958. * indirectly by mg_snprintf */
  2959. #endif
  2960. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2961. ok = (n >= 0) && ((size_t)n < buflen);
  2962. #if defined(__clang__)
  2963. #pragma clang diagnostic pop
  2964. #endif
  2965. if (ok) {
  2966. if (truncated) {
  2967. *truncated = 0;
  2968. }
  2969. } else {
  2970. if (truncated) {
  2971. *truncated = 1;
  2972. }
  2973. mg_cry_internal(conn,
  2974. "truncating vsnprintf buffer: [%.*s]",
  2975. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2976. buf);
  2977. n = (int)buflen - 1;
  2978. }
  2979. buf[n] = '\0';
  2980. }
  2981. static void
  2982. mg_snprintf(const struct mg_connection *conn,
  2983. int *truncated,
  2984. char *buf,
  2985. size_t buflen,
  2986. const char *fmt,
  2987. ...)
  2988. {
  2989. va_list ap;
  2990. va_start(ap, fmt);
  2991. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2992. va_end(ap);
  2993. }
  2994. static int
  2995. get_option_index(const char *name)
  2996. {
  2997. int i;
  2998. for (i = 0; config_options[i].name != NULL; i++) {
  2999. if (strcmp(config_options[i].name, name) == 0) {
  3000. return i;
  3001. }
  3002. }
  3003. return -1;
  3004. }
  3005. const char *
  3006. mg_get_option(const struct mg_context *ctx, const char *name)
  3007. {
  3008. int i;
  3009. if ((i = get_option_index(name)) == -1) {
  3010. return NULL;
  3011. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3012. return "";
  3013. } else {
  3014. return ctx->dd.config[i];
  3015. }
  3016. }
  3017. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3018. struct mg_context *
  3019. mg_get_context(const struct mg_connection *conn)
  3020. {
  3021. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3022. }
  3023. void *
  3024. mg_get_user_data(const struct mg_context *ctx)
  3025. {
  3026. return (ctx == NULL) ? NULL : ctx->user_data;
  3027. }
  3028. void *
  3029. mg_get_user_context_data(const struct mg_connection *conn)
  3030. {
  3031. return mg_get_user_data(mg_get_context(conn));
  3032. }
  3033. void *
  3034. mg_get_thread_pointer(const struct mg_connection *conn)
  3035. {
  3036. /* both methods should return the same pointer */
  3037. if (conn) {
  3038. /* quick access, in case conn is known */
  3039. return conn->tls_user_ptr;
  3040. } else {
  3041. /* otherwise get pointer from thread local storage (TLS) */
  3042. struct mg_workerTLS *tls =
  3043. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3044. return tls->user_ptr;
  3045. }
  3046. }
  3047. void
  3048. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3049. {
  3050. if (conn != NULL) {
  3051. conn->request_info.conn_data = data;
  3052. }
  3053. }
  3054. void *
  3055. mg_get_user_connection_data(const struct mg_connection *conn)
  3056. {
  3057. if (conn != NULL) {
  3058. return conn->request_info.conn_data;
  3059. }
  3060. return NULL;
  3061. }
  3062. #if defined(MG_LEGACY_INTERFACE)
  3063. /* Deprecated: Use mg_get_server_ports instead. */
  3064. size_t
  3065. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3066. {
  3067. size_t i;
  3068. if (!ctx) {
  3069. return 0;
  3070. }
  3071. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3072. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3073. ports[i] =
  3074. #if defined(USE_IPV6)
  3075. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3076. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3077. :
  3078. #endif
  3079. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3080. }
  3081. return i;
  3082. }
  3083. #endif
  3084. int
  3085. mg_get_server_ports(const struct mg_context *ctx,
  3086. int size,
  3087. struct mg_server_port *ports)
  3088. {
  3089. int i, cnt = 0;
  3090. if (size <= 0) {
  3091. return -1;
  3092. }
  3093. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3094. if (!ctx) {
  3095. return -1;
  3096. }
  3097. if (!ctx->listening_sockets) {
  3098. return -1;
  3099. }
  3100. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3101. ports[cnt].port =
  3102. #if defined(USE_IPV6)
  3103. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3104. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3105. :
  3106. #endif
  3107. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3108. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3109. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3110. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3111. /* IPv4 */
  3112. ports[cnt].protocol = 1;
  3113. cnt++;
  3114. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3115. /* IPv6 */
  3116. ports[cnt].protocol = 3;
  3117. cnt++;
  3118. }
  3119. }
  3120. return cnt;
  3121. }
  3122. static void
  3123. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3124. {
  3125. buf[0] = '\0';
  3126. if (!usa) {
  3127. return;
  3128. }
  3129. if (usa->sa.sa_family == AF_INET) {
  3130. getnameinfo(&usa->sa,
  3131. sizeof(usa->sin),
  3132. buf,
  3133. (unsigned)len,
  3134. NULL,
  3135. 0,
  3136. NI_NUMERICHOST);
  3137. }
  3138. #if defined(USE_IPV6)
  3139. else if (usa->sa.sa_family == AF_INET6) {
  3140. getnameinfo(&usa->sa,
  3141. sizeof(usa->sin6),
  3142. buf,
  3143. (unsigned)len,
  3144. NULL,
  3145. 0,
  3146. NI_NUMERICHOST);
  3147. }
  3148. #endif
  3149. }
  3150. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3151. * included in all responses other than 100, 101, 5xx. */
  3152. static void
  3153. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3154. {
  3155. #if !defined(REENTRANT_TIME)
  3156. struct tm *tm;
  3157. tm = ((t != NULL) ? gmtime(t) : NULL);
  3158. if (tm != NULL) {
  3159. #else
  3160. struct tm _tm;
  3161. struct tm *tm = &_tm;
  3162. if (t != NULL) {
  3163. gmtime_r(t, tm);
  3164. #endif
  3165. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3166. } else {
  3167. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3168. buf[buf_len - 1] = '\0';
  3169. }
  3170. }
  3171. /* difftime for struct timespec. Return value is in seconds. */
  3172. static double
  3173. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3174. {
  3175. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3176. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3177. }
  3178. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3179. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3180. const char *func,
  3181. unsigned line,
  3182. const char *fmt,
  3183. va_list ap);
  3184. #include "external_mg_cry_internal_impl.inl"
  3185. #elif !defined(NO_FILESYSTEMS)
  3186. /* Print error message to the opened error log stream. */
  3187. static void
  3188. mg_cry_internal_impl(const struct mg_connection *conn,
  3189. const char *func,
  3190. unsigned line,
  3191. const char *fmt,
  3192. va_list ap)
  3193. {
  3194. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3195. struct mg_file fi;
  3196. time_t timestamp;
  3197. /* Unused, in the RELEASE build */
  3198. (void)func;
  3199. (void)line;
  3200. #if defined(GCC_DIAGNOSTIC)
  3201. #pragma GCC diagnostic push
  3202. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3203. #endif
  3204. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3205. #if defined(GCC_DIAGNOSTIC)
  3206. #pragma GCC diagnostic pop
  3207. #endif
  3208. buf[sizeof(buf) - 1] = 0;
  3209. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3210. if (!conn) {
  3211. puts(buf);
  3212. return;
  3213. }
  3214. /* Do not lock when getting the callback value, here and below.
  3215. * I suppose this is fine, since function cannot disappear in the
  3216. * same way string option can. */
  3217. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3218. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3219. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3220. if (mg_fopen(conn,
  3221. conn->dom_ctx->config[ERROR_LOG_FILE],
  3222. MG_FOPEN_MODE_APPEND,
  3223. &fi)
  3224. == 0) {
  3225. fi.access.fp = NULL;
  3226. }
  3227. } else {
  3228. fi.access.fp = NULL;
  3229. }
  3230. if (fi.access.fp != NULL) {
  3231. flockfile(fi.access.fp);
  3232. timestamp = time(NULL);
  3233. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3234. fprintf(fi.access.fp,
  3235. "[%010lu] [error] [client %s] ",
  3236. (unsigned long)timestamp,
  3237. src_addr);
  3238. if (conn->request_info.request_method != NULL) {
  3239. fprintf(fi.access.fp,
  3240. "%s %s: ",
  3241. conn->request_info.request_method,
  3242. conn->request_info.request_uri
  3243. ? conn->request_info.request_uri
  3244. : "");
  3245. }
  3246. fprintf(fi.access.fp, "%s", buf);
  3247. fputc('\n', fi.access.fp);
  3248. fflush(fi.access.fp);
  3249. funlockfile(fi.access.fp);
  3250. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3251. * mg_cry here anyway ;-) */
  3252. }
  3253. }
  3254. }
  3255. #else
  3256. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3257. #endif /* Externally provided function */
  3258. /* Construct fake connection structure. Used for logging, if connection
  3259. * is not applicable at the moment of logging. */
  3260. static struct mg_connection *
  3261. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3262. {
  3263. static const struct mg_connection conn_zero = {0};
  3264. *fc = conn_zero;
  3265. fc->phys_ctx = ctx;
  3266. fc->dom_ctx = &(ctx->dd);
  3267. return fc;
  3268. }
  3269. static void
  3270. mg_cry_internal_wrap(const struct mg_connection *conn,
  3271. struct mg_context *ctx,
  3272. const char *func,
  3273. unsigned line,
  3274. const char *fmt,
  3275. ...)
  3276. {
  3277. va_list ap;
  3278. va_start(ap, fmt);
  3279. if (!conn && ctx) {
  3280. struct mg_connection fc;
  3281. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3282. } else {
  3283. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3284. }
  3285. va_end(ap);
  3286. }
  3287. void
  3288. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3289. {
  3290. va_list ap;
  3291. va_start(ap, fmt);
  3292. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3293. va_end(ap);
  3294. }
  3295. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3296. const char *
  3297. mg_version(void)
  3298. {
  3299. return CIVETWEB_VERSION;
  3300. }
  3301. const struct mg_request_info *
  3302. mg_get_request_info(const struct mg_connection *conn)
  3303. {
  3304. if (!conn) {
  3305. return NULL;
  3306. }
  3307. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3308. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3309. char txt[16];
  3310. struct mg_workerTLS *tls =
  3311. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3312. sprintf(txt, "%03i", conn->response_info.status_code);
  3313. if (strlen(txt) == 3) {
  3314. memcpy(tls->txtbuf, txt, 4);
  3315. } else {
  3316. strcpy(tls->txtbuf, "ERR");
  3317. }
  3318. ((struct mg_connection *)conn)->request_info.local_uri =
  3319. ((struct mg_connection *)conn)->request_info.request_uri =
  3320. tls->txtbuf; /* use thread safe buffer */
  3321. ((struct mg_connection *)conn)->request_info.num_headers =
  3322. conn->response_info.num_headers;
  3323. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3324. conn->response_info.http_headers,
  3325. sizeof(conn->response_info.http_headers));
  3326. } else
  3327. #endif
  3328. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3329. return NULL;
  3330. }
  3331. return &conn->request_info;
  3332. }
  3333. const struct mg_response_info *
  3334. mg_get_response_info(const struct mg_connection *conn)
  3335. {
  3336. if (!conn) {
  3337. return NULL;
  3338. }
  3339. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3340. return NULL;
  3341. }
  3342. return &conn->response_info;
  3343. }
  3344. static const char *
  3345. get_proto_name(const struct mg_connection *conn)
  3346. {
  3347. #if defined(__clang__)
  3348. #pragma clang diagnostic push
  3349. #pragma clang diagnostic ignored "-Wunreachable-code"
  3350. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3351. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3352. * unreachable, but splitting into four different #ifdef clauses here is more
  3353. * complicated.
  3354. */
  3355. #endif
  3356. const struct mg_request_info *ri = &conn->request_info;
  3357. const char *proto =
  3358. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3359. : (ri->is_ssl ? "https" : "http"));
  3360. return proto;
  3361. #if defined(__clang__)
  3362. #pragma clang diagnostic pop
  3363. #endif
  3364. }
  3365. int
  3366. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3367. {
  3368. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3369. return -1;
  3370. } else {
  3371. int truncated = 0;
  3372. const struct mg_request_info *ri = &conn->request_info;
  3373. const char *proto = get_proto_name(conn);
  3374. if (ri->local_uri == NULL) {
  3375. return -1;
  3376. }
  3377. if ((ri->request_uri != NULL)
  3378. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3379. /* The request uri is different from the local uri.
  3380. * This is usually if an absolute URI, including server
  3381. * name has been provided. */
  3382. mg_snprintf(conn,
  3383. &truncated,
  3384. buf,
  3385. buflen,
  3386. "%s://%s",
  3387. proto,
  3388. ri->request_uri);
  3389. if (truncated) {
  3390. return -1;
  3391. }
  3392. return 0;
  3393. } else {
  3394. /* The common case is a relative URI, so we have to
  3395. * construct an absolute URI from server name and port */
  3396. #if defined(USE_IPV6)
  3397. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3398. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3399. : htons(conn->client.lsa.sin.sin_port);
  3400. #else
  3401. int port = htons(conn->client.lsa.sin.sin_port);
  3402. #endif
  3403. int def_port = ri->is_ssl ? 443 : 80;
  3404. int auth_domain_check_enabled =
  3405. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3406. && (!mg_strcasecmp(
  3407. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3408. const char *server_domain =
  3409. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3410. char portstr[16];
  3411. char server_ip[48];
  3412. if (port != def_port) {
  3413. sprintf(portstr, ":%u", (unsigned)port);
  3414. } else {
  3415. portstr[0] = 0;
  3416. }
  3417. if (!auth_domain_check_enabled || !server_domain) {
  3418. sockaddr_to_string(server_ip,
  3419. sizeof(server_ip),
  3420. &conn->client.lsa);
  3421. server_domain = server_ip;
  3422. }
  3423. mg_snprintf(conn,
  3424. &truncated,
  3425. buf,
  3426. buflen,
  3427. "%s://%s%s%s",
  3428. proto,
  3429. server_domain,
  3430. portstr,
  3431. ri->local_uri);
  3432. if (truncated) {
  3433. return -1;
  3434. }
  3435. return 0;
  3436. }
  3437. }
  3438. }
  3439. /* Skip the characters until one of the delimiters characters found.
  3440. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3441. * Advance pointer to buffer to the next word. Return found 0-terminated
  3442. * word.
  3443. * Delimiters can be quoted with quotechar. */
  3444. static char *
  3445. skip_quoted(char **buf,
  3446. const char *delimiters,
  3447. const char *whitespace,
  3448. char quotechar)
  3449. {
  3450. char *p, *begin_word, *end_word, *end_whitespace;
  3451. begin_word = *buf;
  3452. end_word = begin_word + strcspn(begin_word, delimiters);
  3453. /* Check for quotechar */
  3454. if (end_word > begin_word) {
  3455. p = end_word - 1;
  3456. while (*p == quotechar) {
  3457. /* While the delimiter is quoted, look for the next delimiter.
  3458. */
  3459. /* This happens, e.g., in calls from parse_auth_header,
  3460. * if the user name contains a " character. */
  3461. /* If there is anything beyond end_word, copy it. */
  3462. if (*end_word != '\0') {
  3463. size_t end_off = strcspn(end_word + 1, delimiters);
  3464. memmove(p, end_word, end_off + 1);
  3465. p += end_off; /* p must correspond to end_word - 1 */
  3466. end_word += end_off + 1;
  3467. } else {
  3468. *p = '\0';
  3469. break;
  3470. }
  3471. }
  3472. for (p++; p < end_word; p++) {
  3473. *p = '\0';
  3474. }
  3475. }
  3476. if (*end_word == '\0') {
  3477. *buf = end_word;
  3478. } else {
  3479. #if defined(GCC_DIAGNOSTIC)
  3480. /* Disable spurious conversion warning for GCC */
  3481. #pragma GCC diagnostic push
  3482. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3483. #endif /* defined(GCC_DIAGNOSTIC) */
  3484. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3485. #if defined(GCC_DIAGNOSTIC)
  3486. #pragma GCC diagnostic pop
  3487. #endif /* defined(GCC_DIAGNOSTIC) */
  3488. for (p = end_word; p < end_whitespace; p++) {
  3489. *p = '\0';
  3490. }
  3491. *buf = end_whitespace;
  3492. }
  3493. return begin_word;
  3494. }
  3495. /* Return HTTP header value, or NULL if not found. */
  3496. static const char *
  3497. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3498. {
  3499. int i;
  3500. for (i = 0; i < num_hdr; i++) {
  3501. if (!mg_strcasecmp(name, hdr[i].name)) {
  3502. return hdr[i].value;
  3503. }
  3504. }
  3505. return NULL;
  3506. }
  3507. #if defined(USE_WEBSOCKET)
  3508. /* Retrieve requested HTTP header multiple values, and return the number of
  3509. * found occurrences */
  3510. static int
  3511. get_req_headers(const struct mg_request_info *ri,
  3512. const char *name,
  3513. const char **output,
  3514. int output_max_size)
  3515. {
  3516. int i;
  3517. int cnt = 0;
  3518. if (ri) {
  3519. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3520. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3521. output[cnt++] = ri->http_headers[i].value;
  3522. }
  3523. }
  3524. }
  3525. return cnt;
  3526. }
  3527. #endif
  3528. const char *
  3529. mg_get_header(const struct mg_connection *conn, const char *name)
  3530. {
  3531. if (!conn) {
  3532. return NULL;
  3533. }
  3534. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3535. return get_header(conn->request_info.http_headers,
  3536. conn->request_info.num_headers,
  3537. name);
  3538. }
  3539. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3540. return get_header(conn->response_info.http_headers,
  3541. conn->response_info.num_headers,
  3542. name);
  3543. }
  3544. return NULL;
  3545. }
  3546. static const char *
  3547. get_http_version(const struct mg_connection *conn)
  3548. {
  3549. if (!conn) {
  3550. return NULL;
  3551. }
  3552. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3553. return conn->request_info.http_version;
  3554. }
  3555. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3556. return conn->response_info.http_version;
  3557. }
  3558. return NULL;
  3559. }
  3560. /* A helper function for traversing a comma separated list of values.
  3561. * It returns a list pointer shifted to the next value, or NULL if the end
  3562. * of the list found.
  3563. * Value is stored in val vector. If value has form "x=y", then eq_val
  3564. * vector is initialized to point to the "y" part, and val vector length
  3565. * is adjusted to point only to "x". */
  3566. static const char *
  3567. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3568. {
  3569. int end;
  3570. reparse:
  3571. if (val == NULL || list == NULL || *list == '\0') {
  3572. /* End of the list */
  3573. return NULL;
  3574. }
  3575. /* Skip over leading LWS */
  3576. while (*list == ' ' || *list == '\t')
  3577. list++;
  3578. val->ptr = list;
  3579. if ((list = strchr(val->ptr, ',')) != NULL) {
  3580. /* Comma found. Store length and shift the list ptr */
  3581. val->len = ((size_t)(list - val->ptr));
  3582. list++;
  3583. } else {
  3584. /* This value is the last one */
  3585. list = val->ptr + strlen(val->ptr);
  3586. val->len = ((size_t)(list - val->ptr));
  3587. }
  3588. /* Adjust length for trailing LWS */
  3589. end = (int)val->len - 1;
  3590. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3591. end--;
  3592. val->len = (size_t)(end) + (size_t)(1);
  3593. if (val->len == 0) {
  3594. /* Ignore any empty entries. */
  3595. goto reparse;
  3596. }
  3597. if (eq_val != NULL) {
  3598. /* Value has form "x=y", adjust pointers and lengths
  3599. * so that val points to "x", and eq_val points to "y". */
  3600. eq_val->len = 0;
  3601. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3602. if (eq_val->ptr != NULL) {
  3603. eq_val->ptr++; /* Skip over '=' character */
  3604. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3605. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3606. }
  3607. }
  3608. return list;
  3609. }
  3610. /* A helper function for checking if a comma separated list of values
  3611. * contains
  3612. * the given option (case insensitvely).
  3613. * 'header' can be NULL, in which case false is returned. */
  3614. static int
  3615. header_has_option(const char *header, const char *option)
  3616. {
  3617. struct vec opt_vec;
  3618. struct vec eq_vec;
  3619. DEBUG_ASSERT(option != NULL);
  3620. DEBUG_ASSERT(option[0] != '\0');
  3621. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3622. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3623. return 1;
  3624. }
  3625. return 0;
  3626. }
  3627. /* Perform case-insensitive match of string against pattern */
  3628. static ptrdiff_t
  3629. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3630. {
  3631. const char *or_str;
  3632. ptrdiff_t i, j, len, res;
  3633. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3634. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3635. return (res > 0) ? res
  3636. : match_prefix(or_str + 1,
  3637. (size_t)((pattern + pattern_len)
  3638. - (or_str + 1)),
  3639. str);
  3640. }
  3641. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3642. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3643. continue;
  3644. } else if (pattern[i] == '$') {
  3645. return (str[j] == '\0') ? j : -1;
  3646. } else if (pattern[i] == '*') {
  3647. i++;
  3648. if (pattern[i] == '*') {
  3649. i++;
  3650. len = strlen(str + j);
  3651. } else {
  3652. len = strcspn(str + j, "/");
  3653. }
  3654. if (i == (ptrdiff_t)pattern_len) {
  3655. return j + len;
  3656. }
  3657. do {
  3658. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3659. } while (res == -1 && len-- > 0);
  3660. return (res == -1) ? -1 : j + res + len;
  3661. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3662. return -1;
  3663. }
  3664. }
  3665. return (ptrdiff_t)j;
  3666. }
  3667. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3668. * This function must tolerate situations when connection info is not
  3669. * set up, for example if request parsing failed. */
  3670. static int
  3671. should_keep_alive(const struct mg_connection *conn)
  3672. {
  3673. const char *http_version;
  3674. const char *header;
  3675. /* First satisfy needs of the server */
  3676. if ((conn == NULL) || conn->must_close) {
  3677. /* Close, if civetweb framework needs to close */
  3678. return 0;
  3679. }
  3680. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3681. /* Close, if keep alive is not enabled */
  3682. return 0;
  3683. }
  3684. /* Check explicit wish of the client */
  3685. header = mg_get_header(conn, "Connection");
  3686. if (header) {
  3687. /* If there is a connection header from the client, obey */
  3688. if (header_has_option(header, "keep-alive")) {
  3689. return 1;
  3690. }
  3691. return 0;
  3692. }
  3693. /* Use default of the standard */
  3694. http_version = get_http_version(conn);
  3695. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3696. /* HTTP 1.1 default is keep alive */
  3697. return 1;
  3698. }
  3699. /* HTTP 1.0 (and earlier) default is to close the connection */
  3700. return 0;
  3701. }
  3702. static int
  3703. should_decode_url(const struct mg_connection *conn)
  3704. {
  3705. if (!conn || !conn->dom_ctx) {
  3706. return 0;
  3707. }
  3708. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3709. }
  3710. static const char *
  3711. suggest_connection_header(const struct mg_connection *conn)
  3712. {
  3713. return should_keep_alive(conn) ? "keep-alive" : "close";
  3714. }
  3715. static int
  3716. send_no_cache_header(struct mg_connection *conn)
  3717. {
  3718. /* Send all current and obsolete cache opt-out directives. */
  3719. return mg_printf(conn,
  3720. "Cache-Control: no-cache, no-store, "
  3721. "must-revalidate, private, max-age=0\r\n"
  3722. "Pragma: no-cache\r\n"
  3723. "Expires: 0\r\n");
  3724. }
  3725. static int
  3726. send_static_cache_header(struct mg_connection *conn)
  3727. {
  3728. #if !defined(NO_CACHING)
  3729. int max_age;
  3730. const char *cache_control =
  3731. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3732. if (cache_control != NULL) {
  3733. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3734. }
  3735. /* Read the server config to check how long a file may be cached.
  3736. * The configuration is in seconds. */
  3737. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3738. if (max_age <= 0) {
  3739. /* 0 means "do not cache". All values <0 are reserved
  3740. * and may be used differently in the future. */
  3741. /* If a file should not be cached, do not only send
  3742. * max-age=0, but also pragmas and Expires headers. */
  3743. return send_no_cache_header(conn);
  3744. }
  3745. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3746. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3747. /* See also https://www.mnot.net/cache_docs/ */
  3748. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3749. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3750. * leap
  3751. * year to 31622400 seconds. For the moment, we just send whatever has
  3752. * been configured, still the behavior for >1 year should be considered
  3753. * as undefined. */
  3754. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3755. #else /* NO_CACHING */
  3756. return send_no_cache_header(conn);
  3757. #endif /* !NO_CACHING */
  3758. }
  3759. static int
  3760. send_additional_header(struct mg_connection *conn)
  3761. {
  3762. int i = 0;
  3763. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3764. #if !defined(NO_SSL)
  3765. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3766. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3767. if (max_age >= 0) {
  3768. i += mg_printf(conn,
  3769. "Strict-Transport-Security: max-age=%u\r\n",
  3770. (unsigned)max_age);
  3771. }
  3772. }
  3773. #endif
  3774. if (header && header[0]) {
  3775. i += mg_printf(conn, "%s\r\n", header);
  3776. }
  3777. return i;
  3778. }
  3779. #if !defined(NO_FILESYSTEMS)
  3780. static void handle_file_based_request(struct mg_connection *conn,
  3781. const char *path,
  3782. struct mg_file *filep);
  3783. #endif /* NO_FILESYSTEMS */
  3784. const char *
  3785. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3786. {
  3787. /* See IANA HTTP status code assignment:
  3788. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3789. */
  3790. switch (response_code) {
  3791. /* RFC2616 Section 10.1 - Informational 1xx */
  3792. case 100:
  3793. return "Continue"; /* RFC2616 Section 10.1.1 */
  3794. case 101:
  3795. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3796. case 102:
  3797. return "Processing"; /* RFC2518 Section 10.1 */
  3798. /* RFC2616 Section 10.2 - Successful 2xx */
  3799. case 200:
  3800. return "OK"; /* RFC2616 Section 10.2.1 */
  3801. case 201:
  3802. return "Created"; /* RFC2616 Section 10.2.2 */
  3803. case 202:
  3804. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3805. case 203:
  3806. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3807. case 204:
  3808. return "No Content"; /* RFC2616 Section 10.2.5 */
  3809. case 205:
  3810. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3811. case 206:
  3812. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3813. case 207:
  3814. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3815. */
  3816. case 208:
  3817. return "Already Reported"; /* RFC5842 Section 7.1 */
  3818. case 226:
  3819. return "IM used"; /* RFC3229 Section 10.4.1 */
  3820. /* RFC2616 Section 10.3 - Redirection 3xx */
  3821. case 300:
  3822. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3823. case 301:
  3824. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3825. case 302:
  3826. return "Found"; /* RFC2616 Section 10.3.3 */
  3827. case 303:
  3828. return "See Other"; /* RFC2616 Section 10.3.4 */
  3829. case 304:
  3830. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3831. case 305:
  3832. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3833. case 307:
  3834. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3835. case 308:
  3836. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3837. /* RFC2616 Section 10.4 - Client Error 4xx */
  3838. case 400:
  3839. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3840. case 401:
  3841. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3842. case 402:
  3843. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3844. case 403:
  3845. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3846. case 404:
  3847. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3848. case 405:
  3849. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3850. case 406:
  3851. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3852. case 407:
  3853. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3854. case 408:
  3855. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3856. case 409:
  3857. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3858. case 410:
  3859. return "Gone"; /* RFC2616 Section 10.4.11 */
  3860. case 411:
  3861. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3862. case 412:
  3863. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3864. case 413:
  3865. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3866. case 414:
  3867. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3868. case 415:
  3869. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3870. case 416:
  3871. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3872. */
  3873. case 417:
  3874. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3875. case 421:
  3876. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3877. case 422:
  3878. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3879. * Section 11.2 */
  3880. case 423:
  3881. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3882. case 424:
  3883. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3884. * Section 11.4 */
  3885. case 426:
  3886. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3887. case 428:
  3888. return "Precondition Required"; /* RFC 6585, Section 3 */
  3889. case 429:
  3890. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3891. case 431:
  3892. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3893. case 451:
  3894. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3895. * Section 3 */
  3896. /* RFC2616 Section 10.5 - Server Error 5xx */
  3897. case 500:
  3898. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3899. case 501:
  3900. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3901. case 502:
  3902. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3903. case 503:
  3904. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3905. case 504:
  3906. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3907. case 505:
  3908. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3909. case 506:
  3910. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3911. case 507:
  3912. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3913. * Section 11.5 */
  3914. case 508:
  3915. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3916. case 510:
  3917. return "Not Extended"; /* RFC 2774, Section 7 */
  3918. case 511:
  3919. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3920. /* Other status codes, not shown in the IANA HTTP status code
  3921. * assignment.
  3922. * E.g., "de facto" standards due to common use, ... */
  3923. case 418:
  3924. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3925. case 419:
  3926. return "Authentication Timeout"; /* common use */
  3927. case 420:
  3928. return "Enhance Your Calm"; /* common use */
  3929. case 440:
  3930. return "Login Timeout"; /* common use */
  3931. case 509:
  3932. return "Bandwidth Limit Exceeded"; /* common use */
  3933. default:
  3934. /* This error code is unknown. This should not happen. */
  3935. if (conn) {
  3936. mg_cry_internal(conn,
  3937. "Unknown HTTP response code: %u",
  3938. response_code);
  3939. }
  3940. /* Return at least a category according to RFC 2616 Section 10. */
  3941. if (response_code >= 100 && response_code < 200) {
  3942. /* Unknown informational status code */
  3943. return "Information";
  3944. }
  3945. if (response_code >= 200 && response_code < 300) {
  3946. /* Unknown success code */
  3947. return "Success";
  3948. }
  3949. if (response_code >= 300 && response_code < 400) {
  3950. /* Unknown redirection code */
  3951. return "Redirection";
  3952. }
  3953. if (response_code >= 400 && response_code < 500) {
  3954. /* Unknown request error code */
  3955. return "Client Error";
  3956. }
  3957. if (response_code >= 500 && response_code < 600) {
  3958. /* Unknown server error code */
  3959. return "Server Error";
  3960. }
  3961. /* Response code not even within reasonable range */
  3962. return "";
  3963. }
  3964. }
  3965. static int
  3966. mg_send_http_error_impl(struct mg_connection *conn,
  3967. int status,
  3968. const char *fmt,
  3969. va_list args)
  3970. {
  3971. char errmsg_buf[MG_BUF_LEN];
  3972. va_list ap;
  3973. int has_body;
  3974. char date[64];
  3975. time_t curtime = time(NULL);
  3976. #if !defined(NO_FILESYSTEMS)
  3977. char path_buf[PATH_MAX];
  3978. int len, i, page_handler_found, scope, truncated;
  3979. const char *error_handler = NULL;
  3980. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3981. const char *error_page_file_ext, *tstr;
  3982. #endif /* NO_FILESYSTEMS */
  3983. int handled_by_callback = 0;
  3984. const char *status_text = mg_get_response_code_text(conn, status);
  3985. if ((conn == NULL) || (fmt == NULL)) {
  3986. return -2;
  3987. }
  3988. /* Set status (for log) */
  3989. conn->status_code = status;
  3990. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3991. has_body = ((status > 199) && (status != 204) && (status != 304));
  3992. /* Prepare message in buf, if required */
  3993. if (has_body
  3994. || (!conn->in_error_handler
  3995. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3996. /* Store error message in errmsg_buf */
  3997. va_copy(ap, args);
  3998. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3999. va_end(ap);
  4000. /* In a debug build, print all html errors */
  4001. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4002. }
  4003. /* If there is a http_error callback, call it.
  4004. * But don't do it recursively, if callback calls mg_send_http_error again.
  4005. */
  4006. if (!conn->in_error_handler
  4007. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4008. /* Mark in_error_handler to avoid recursion and call user callback. */
  4009. conn->in_error_handler = 1;
  4010. handled_by_callback =
  4011. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4012. == 0);
  4013. conn->in_error_handler = 0;
  4014. }
  4015. if (!handled_by_callback) {
  4016. /* Check for recursion */
  4017. if (conn->in_error_handler) {
  4018. DEBUG_TRACE(
  4019. "Recursion when handling error %u - fall back to default",
  4020. status);
  4021. #if !defined(NO_FILESYSTEMS)
  4022. } else {
  4023. /* Send user defined error pages, if defined */
  4024. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4025. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4026. page_handler_found = 0;
  4027. if (error_handler != NULL) {
  4028. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4029. switch (scope) {
  4030. case 1: /* Handler for specific error, e.g. 404 error */
  4031. mg_snprintf(conn,
  4032. &truncated,
  4033. path_buf,
  4034. sizeof(path_buf) - 32,
  4035. "%serror%03u.",
  4036. error_handler,
  4037. status);
  4038. break;
  4039. case 2: /* Handler for error group, e.g., 5xx error
  4040. * handler
  4041. * for all server errors (500-599) */
  4042. mg_snprintf(conn,
  4043. &truncated,
  4044. path_buf,
  4045. sizeof(path_buf) - 32,
  4046. "%serror%01uxx.",
  4047. error_handler,
  4048. status / 100);
  4049. break;
  4050. default: /* Handler for all errors */
  4051. mg_snprintf(conn,
  4052. &truncated,
  4053. path_buf,
  4054. sizeof(path_buf) - 32,
  4055. "%serror.",
  4056. error_handler);
  4057. break;
  4058. }
  4059. /* String truncation in buf may only occur if
  4060. * error_handler is too long. This string is
  4061. * from the config, not from a client. */
  4062. (void)truncated;
  4063. len = (int)strlen(path_buf);
  4064. tstr = strchr(error_page_file_ext, '.');
  4065. while (tstr) {
  4066. for (i = 1;
  4067. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4068. i++) {
  4069. /* buffer overrun is not possible here, since
  4070. * (i < 32) && (len < sizeof(path_buf) - 32)
  4071. * ==> (i + len) < sizeof(path_buf) */
  4072. path_buf[len + i - 1] = tstr[i];
  4073. }
  4074. /* buffer overrun is not possible here, since
  4075. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4076. * ==> (i + len) <= sizeof(path_buf) */
  4077. path_buf[len + i - 1] = 0;
  4078. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4079. DEBUG_TRACE("Check error page %s - found",
  4080. path_buf);
  4081. page_handler_found = 1;
  4082. break;
  4083. }
  4084. DEBUG_TRACE("Check error page %s - not found",
  4085. path_buf);
  4086. tstr = strchr(tstr + i, '.');
  4087. }
  4088. }
  4089. }
  4090. if (page_handler_found) {
  4091. conn->in_error_handler = 1;
  4092. handle_file_based_request(conn, path_buf, &error_page_file);
  4093. conn->in_error_handler = 0;
  4094. return 0;
  4095. }
  4096. #endif /* NO_FILESYSTEMS */
  4097. }
  4098. /* No custom error page. Send default error page. */
  4099. gmt_time_string(date, sizeof(date), &curtime);
  4100. conn->must_close = 1;
  4101. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4102. send_no_cache_header(conn);
  4103. send_additional_header(conn);
  4104. if (has_body) {
  4105. mg_printf(conn,
  4106. "%s",
  4107. "Content-Type: text/plain; charset=utf-8\r\n");
  4108. }
  4109. mg_printf(conn,
  4110. "Date: %s\r\n"
  4111. "Connection: close\r\n\r\n",
  4112. date);
  4113. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4114. if (has_body) {
  4115. /* For other errors, send a generic error message. */
  4116. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4117. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4118. } else {
  4119. /* No body allowed. Close the connection. */
  4120. DEBUG_TRACE("Error %i", status);
  4121. }
  4122. }
  4123. return 0;
  4124. }
  4125. int
  4126. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4127. {
  4128. va_list ap;
  4129. int ret;
  4130. va_start(ap, fmt);
  4131. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4132. va_end(ap);
  4133. return ret;
  4134. }
  4135. int
  4136. mg_send_http_ok(struct mg_connection *conn,
  4137. const char *mime_type,
  4138. long long content_length)
  4139. {
  4140. char date[64];
  4141. time_t curtime = time(NULL);
  4142. if ((mime_type == NULL) || (*mime_type == 0)) {
  4143. /* No content type defined: default to text/html */
  4144. mime_type = "text/html";
  4145. }
  4146. gmt_time_string(date, sizeof(date), &curtime);
  4147. mg_printf(conn,
  4148. "HTTP/1.1 200 OK\r\n"
  4149. "Content-Type: %s\r\n"
  4150. "Date: %s\r\n"
  4151. "Connection: %s\r\n",
  4152. mime_type,
  4153. date,
  4154. suggest_connection_header(conn));
  4155. send_no_cache_header(conn);
  4156. send_additional_header(conn);
  4157. if (content_length < 0) {
  4158. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4159. } else {
  4160. mg_printf(conn,
  4161. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4162. (uint64_t)content_length);
  4163. }
  4164. return 0;
  4165. }
  4166. int
  4167. mg_send_http_redirect(struct mg_connection *conn,
  4168. const char *target_url,
  4169. int redirect_code)
  4170. {
  4171. /* Send a 30x redirect response.
  4172. *
  4173. * Redirect types (status codes):
  4174. *
  4175. * Status | Perm/Temp | Method | Version
  4176. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4177. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4178. * 303 | temporary | always use GET | HTTP/1.1
  4179. * 307 | temporary | always keep method | HTTP/1.1
  4180. * 308 | permanent | always keep method | HTTP/1.1
  4181. */
  4182. const char *redirect_text;
  4183. int ret;
  4184. size_t content_len = 0;
  4185. char reply[MG_BUF_LEN];
  4186. /* In case redirect_code=0, use 307. */
  4187. if (redirect_code == 0) {
  4188. redirect_code = 307;
  4189. }
  4190. /* In case redirect_code is none of the above, return error. */
  4191. if ((redirect_code != 301) && (redirect_code != 302)
  4192. && (redirect_code != 303) && (redirect_code != 307)
  4193. && (redirect_code != 308)) {
  4194. /* Parameter error */
  4195. return -2;
  4196. }
  4197. /* Get proper text for response code */
  4198. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4199. /* If target_url is not defined, redirect to "/". */
  4200. if ((target_url == NULL) || (*target_url == 0)) {
  4201. target_url = "/";
  4202. }
  4203. #if defined(MG_SEND_REDIRECT_BODY)
  4204. /* TODO: condition name? */
  4205. /* Prepare a response body with a hyperlink.
  4206. *
  4207. * According to RFC2616 (and RFC1945 before):
  4208. * Unless the request method was HEAD, the entity of the
  4209. * response SHOULD contain a short hypertext note with a hyperlink to
  4210. * the new URI(s).
  4211. *
  4212. * However, this response body is not useful in M2M communication.
  4213. * Probably the original reason in the RFC was, clients not supporting
  4214. * a 30x HTTP redirect could still show the HTML page and let the user
  4215. * press the link. Since current browsers support 30x HTTP, the additional
  4216. * HTML body does not seem to make sense anymore.
  4217. *
  4218. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4219. * but it only notes:
  4220. * The server's response payload usually contains a short
  4221. * hypertext note with a hyperlink to the new URI(s).
  4222. *
  4223. * Deactivated by default. If you need the 30x body, set the define.
  4224. */
  4225. mg_snprintf(
  4226. conn,
  4227. NULL /* ignore truncation */,
  4228. reply,
  4229. sizeof(reply),
  4230. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4231. redirect_text,
  4232. target_url,
  4233. target_url);
  4234. content_len = strlen(reply);
  4235. #else
  4236. reply[0] = 0;
  4237. #endif
  4238. /* Do not send any additional header. For all other options,
  4239. * including caching, there are suitable defaults. */
  4240. ret = mg_printf(conn,
  4241. "HTTP/1.1 %i %s\r\n"
  4242. "Location: %s\r\n"
  4243. "Content-Length: %u\r\n"
  4244. "Connection: %s\r\n\r\n",
  4245. redirect_code,
  4246. redirect_text,
  4247. target_url,
  4248. (unsigned int)content_len,
  4249. suggest_connection_header(conn));
  4250. /* Send response body */
  4251. if (ret > 0) {
  4252. /* ... unless it is a HEAD request */
  4253. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4254. ret = mg_write(conn, reply, content_len);
  4255. }
  4256. }
  4257. return (ret > 0) ? ret : -1;
  4258. }
  4259. #if defined(_WIN32)
  4260. /* Create substitutes for POSIX functions in Win32. */
  4261. #if defined(GCC_DIAGNOSTIC)
  4262. /* Show no warning in case system functions are not used. */
  4263. #pragma GCC diagnostic push
  4264. #pragma GCC diagnostic ignored "-Wunused-function"
  4265. #endif
  4266. static int
  4267. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4268. {
  4269. (void)unused;
  4270. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4271. InitializeCriticalSection(&mutex->sec);
  4272. return 0;
  4273. }
  4274. static int
  4275. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4276. {
  4277. DeleteCriticalSection(&mutex->sec);
  4278. return 0;
  4279. }
  4280. static int
  4281. pthread_mutex_lock(pthread_mutex_t *mutex)
  4282. {
  4283. EnterCriticalSection(&mutex->sec);
  4284. return 0;
  4285. }
  4286. static int
  4287. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4288. {
  4289. LeaveCriticalSection(&mutex->sec);
  4290. return 0;
  4291. }
  4292. FUNCTION_MAY_BE_UNUSED
  4293. static int
  4294. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4295. {
  4296. (void)unused;
  4297. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4298. cv->waiting_thread = NULL;
  4299. return 0;
  4300. }
  4301. FUNCTION_MAY_BE_UNUSED
  4302. static int
  4303. pthread_cond_timedwait(pthread_cond_t *cv,
  4304. pthread_mutex_t *mutex,
  4305. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4306. {
  4307. struct mg_workerTLS **ptls,
  4308. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4309. int ok;
  4310. int64_t nsnow, nswaitabs, nswaitrel;
  4311. DWORD mswaitrel;
  4312. pthread_mutex_lock(&cv->threadIdSec);
  4313. /* Add this thread to cv's waiting list */
  4314. ptls = &cv->waiting_thread;
  4315. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4316. ;
  4317. tls->next_waiting_thread = NULL;
  4318. *ptls = tls;
  4319. pthread_mutex_unlock(&cv->threadIdSec);
  4320. if (abstime) {
  4321. nsnow = mg_get_current_time_ns();
  4322. nswaitabs =
  4323. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4324. nswaitrel = nswaitabs - nsnow;
  4325. if (nswaitrel < 0) {
  4326. nswaitrel = 0;
  4327. }
  4328. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4329. } else {
  4330. mswaitrel = (DWORD)INFINITE;
  4331. }
  4332. pthread_mutex_unlock(mutex);
  4333. ok = (WAIT_OBJECT_0
  4334. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4335. if (!ok) {
  4336. ok = 1;
  4337. pthread_mutex_lock(&cv->threadIdSec);
  4338. ptls = &cv->waiting_thread;
  4339. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4340. if (*ptls == tls) {
  4341. *ptls = tls->next_waiting_thread;
  4342. ok = 0;
  4343. break;
  4344. }
  4345. }
  4346. pthread_mutex_unlock(&cv->threadIdSec);
  4347. if (ok) {
  4348. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4349. (DWORD)INFINITE);
  4350. }
  4351. }
  4352. /* This thread has been removed from cv's waiting list */
  4353. pthread_mutex_lock(mutex);
  4354. return ok ? 0 : -1;
  4355. }
  4356. FUNCTION_MAY_BE_UNUSED
  4357. static int
  4358. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4359. {
  4360. return pthread_cond_timedwait(cv, mutex, NULL);
  4361. }
  4362. FUNCTION_MAY_BE_UNUSED
  4363. static int
  4364. pthread_cond_signal(pthread_cond_t *cv)
  4365. {
  4366. HANDLE wkup = NULL;
  4367. BOOL ok = FALSE;
  4368. pthread_mutex_lock(&cv->threadIdSec);
  4369. if (cv->waiting_thread) {
  4370. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4371. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4372. ok = SetEvent(wkup);
  4373. DEBUG_ASSERT(ok);
  4374. }
  4375. pthread_mutex_unlock(&cv->threadIdSec);
  4376. return ok ? 0 : 1;
  4377. }
  4378. FUNCTION_MAY_BE_UNUSED
  4379. static int
  4380. pthread_cond_broadcast(pthread_cond_t *cv)
  4381. {
  4382. pthread_mutex_lock(&cv->threadIdSec);
  4383. while (cv->waiting_thread) {
  4384. pthread_cond_signal(cv);
  4385. }
  4386. pthread_mutex_unlock(&cv->threadIdSec);
  4387. return 0;
  4388. }
  4389. FUNCTION_MAY_BE_UNUSED
  4390. static int
  4391. pthread_cond_destroy(pthread_cond_t *cv)
  4392. {
  4393. pthread_mutex_lock(&cv->threadIdSec);
  4394. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4395. pthread_mutex_unlock(&cv->threadIdSec);
  4396. pthread_mutex_destroy(&cv->threadIdSec);
  4397. return 0;
  4398. }
  4399. #if defined(ALTERNATIVE_QUEUE)
  4400. FUNCTION_MAY_BE_UNUSED
  4401. static void *
  4402. event_create(void)
  4403. {
  4404. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4405. }
  4406. FUNCTION_MAY_BE_UNUSED
  4407. static int
  4408. event_wait(void *eventhdl)
  4409. {
  4410. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4411. return (res == WAIT_OBJECT_0);
  4412. }
  4413. FUNCTION_MAY_BE_UNUSED
  4414. static int
  4415. event_signal(void *eventhdl)
  4416. {
  4417. return (int)SetEvent((HANDLE)eventhdl);
  4418. }
  4419. FUNCTION_MAY_BE_UNUSED
  4420. static void
  4421. event_destroy(void *eventhdl)
  4422. {
  4423. CloseHandle((HANDLE)eventhdl);
  4424. }
  4425. #endif
  4426. #if defined(GCC_DIAGNOSTIC)
  4427. /* Enable unused function warning again */
  4428. #pragma GCC diagnostic pop
  4429. #endif
  4430. /* For Windows, change all slashes to backslashes in path names. */
  4431. static void
  4432. change_slashes_to_backslashes(char *path)
  4433. {
  4434. int i;
  4435. for (i = 0; path[i] != '\0'; i++) {
  4436. if (path[i] == '/') {
  4437. path[i] = '\\';
  4438. }
  4439. /* remove double backslash (check i > 0 to preserve UNC paths,
  4440. * like \\server\file.txt) */
  4441. if ((path[i] == '\\') && (i > 0)) {
  4442. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4443. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4444. }
  4445. }
  4446. }
  4447. }
  4448. static int
  4449. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4450. {
  4451. int diff;
  4452. do {
  4453. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4454. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4455. s1++;
  4456. s2++;
  4457. } while ((diff == 0) && (s1[-1] != L'\0'));
  4458. return diff;
  4459. }
  4460. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4461. * wbuf and wbuf_len is a target buffer and its length. */
  4462. static void
  4463. path_to_unicode(const struct mg_connection *conn,
  4464. const char *path,
  4465. wchar_t *wbuf,
  4466. size_t wbuf_len)
  4467. {
  4468. char buf[PATH_MAX], buf2[PATH_MAX];
  4469. wchar_t wbuf2[W_PATH_MAX + 1];
  4470. DWORD long_len, err;
  4471. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4472. mg_strlcpy(buf, path, sizeof(buf));
  4473. change_slashes_to_backslashes(buf);
  4474. /* Convert to Unicode and back. If doubly-converted string does not
  4475. * match the original, something is fishy, reject. */
  4476. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4477. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4478. WideCharToMultiByte(
  4479. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4480. if (strcmp(buf, buf2) != 0) {
  4481. wbuf[0] = L'\0';
  4482. }
  4483. /* Windows file systems are not case sensitive, but you can still use
  4484. * uppercase and lowercase letters (on all modern file systems).
  4485. * The server can check if the URI uses the same upper/lowercase
  4486. * letters an the file system, effectively making Windows servers
  4487. * case sensitive (like Linux servers are). It is still not possible
  4488. * to use two files with the same name in different cases on Windows
  4489. * (like /a and /A) - this would be possible in Linux.
  4490. * As a default, Windows is not case sensitive, but the case sensitive
  4491. * file name check can be activated by an additional configuration. */
  4492. if (conn) {
  4493. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4494. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4495. "yes")) {
  4496. /* Use case sensitive compare function */
  4497. fcompare = wcscmp;
  4498. }
  4499. }
  4500. (void)conn; /* conn is currently unused */
  4501. #if !defined(_WIN32_WCE)
  4502. /* Only accept a full file path, not a Windows short (8.3) path. */
  4503. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4504. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4505. if (long_len == 0) {
  4506. err = GetLastError();
  4507. if (err == ERROR_FILE_NOT_FOUND) {
  4508. /* File does not exist. This is not always a problem here. */
  4509. return;
  4510. }
  4511. }
  4512. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4513. /* Short name is used. */
  4514. wbuf[0] = L'\0';
  4515. }
  4516. #else
  4517. (void)long_len;
  4518. (void)wbuf2;
  4519. (void)err;
  4520. if (strchr(path, '~')) {
  4521. wbuf[0] = L'\0';
  4522. }
  4523. #endif
  4524. }
  4525. #if !defined(NO_FILESYSTEMS)
  4526. static int
  4527. mg_stat(const struct mg_connection *conn,
  4528. const char *path,
  4529. struct mg_file_stat *filep)
  4530. {
  4531. wchar_t wbuf[W_PATH_MAX];
  4532. WIN32_FILE_ATTRIBUTE_DATA info;
  4533. time_t creation_time;
  4534. size_t len;
  4535. if (!filep) {
  4536. return 0;
  4537. }
  4538. memset(filep, 0, sizeof(*filep));
  4539. if (conn && is_file_in_memory(conn, path)) {
  4540. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4541. * memset */
  4542. /* Quick fix (for 1.9.x): */
  4543. /* mg_stat must fill all fields, also for files in memory */
  4544. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4545. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4546. filep->size = tmp_file.stat.size;
  4547. filep->location = 2;
  4548. /* TODO: for 1.10: restructure how files in memory are handled */
  4549. /* The "file in memory" feature is a candidate for deletion.
  4550. * Please join the discussion at
  4551. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4552. */
  4553. filep->last_modified = time(NULL); /* TODO */
  4554. /* last_modified = now ... assumes the file may change during
  4555. * runtime,
  4556. * so every mg_fopen call may return different data */
  4557. /* last_modified = conn->phys_ctx.start_time;
  4558. * May be used it the data does not change during runtime. This
  4559. * allows
  4560. * browser caching. Since we do not know, we have to assume the file
  4561. * in memory may change. */
  4562. return 1;
  4563. }
  4564. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4565. /* Windows happily opens files with some garbage at the end of file name.
  4566. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4567. * "a.cgi", despite one would expect an error back. */
  4568. len = strlen(path);
  4569. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4570. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4571. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4572. filep->last_modified =
  4573. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4574. info.ftLastWriteTime.dwHighDateTime);
  4575. /* On Windows, the file creation time can be higher than the
  4576. * modification time, e.g. when a file is copied.
  4577. * Since the Last-Modified timestamp is used for caching
  4578. * it should be based on the most recent timestamp. */
  4579. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4580. info.ftCreationTime.dwHighDateTime);
  4581. if (creation_time > filep->last_modified) {
  4582. filep->last_modified = creation_time;
  4583. }
  4584. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4585. return 1;
  4586. }
  4587. return 0;
  4588. }
  4589. #endif
  4590. static int
  4591. mg_remove(const struct mg_connection *conn, const char *path)
  4592. {
  4593. wchar_t wbuf[W_PATH_MAX];
  4594. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4595. return DeleteFileW(wbuf) ? 0 : -1;
  4596. }
  4597. static int
  4598. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4599. {
  4600. wchar_t wbuf[W_PATH_MAX];
  4601. (void)mode;
  4602. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4603. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4604. }
  4605. /* Create substitutes for POSIX functions in Win32. */
  4606. #if defined(GCC_DIAGNOSTIC)
  4607. /* Show no warning in case system functions are not used. */
  4608. #pragma GCC diagnostic push
  4609. #pragma GCC diagnostic ignored "-Wunused-function"
  4610. #endif
  4611. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4612. FUNCTION_MAY_BE_UNUSED
  4613. static DIR *
  4614. mg_opendir(const struct mg_connection *conn, const char *name)
  4615. {
  4616. DIR *dir = NULL;
  4617. wchar_t wpath[W_PATH_MAX];
  4618. DWORD attrs;
  4619. if (name == NULL) {
  4620. SetLastError(ERROR_BAD_ARGUMENTS);
  4621. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4622. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4623. } else {
  4624. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4625. attrs = GetFileAttributesW(wpath);
  4626. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4627. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4628. (void)wcscat(wpath, L"\\*");
  4629. dir->handle = FindFirstFileW(wpath, &dir->info);
  4630. dir->result.d_name[0] = '\0';
  4631. } else {
  4632. mg_free(dir);
  4633. dir = NULL;
  4634. }
  4635. }
  4636. return dir;
  4637. }
  4638. FUNCTION_MAY_BE_UNUSED
  4639. static int
  4640. mg_closedir(DIR *dir)
  4641. {
  4642. int result = 0;
  4643. if (dir != NULL) {
  4644. if (dir->handle != INVALID_HANDLE_VALUE)
  4645. result = FindClose(dir->handle) ? 0 : -1;
  4646. mg_free(dir);
  4647. } else {
  4648. result = -1;
  4649. SetLastError(ERROR_BAD_ARGUMENTS);
  4650. }
  4651. return result;
  4652. }
  4653. FUNCTION_MAY_BE_UNUSED
  4654. static struct dirent *
  4655. mg_readdir(DIR *dir)
  4656. {
  4657. struct dirent *result = 0;
  4658. if (dir) {
  4659. if (dir->handle != INVALID_HANDLE_VALUE) {
  4660. result = &dir->result;
  4661. (void)WideCharToMultiByte(CP_UTF8,
  4662. 0,
  4663. dir->info.cFileName,
  4664. -1,
  4665. result->d_name,
  4666. sizeof(result->d_name),
  4667. NULL,
  4668. NULL);
  4669. if (!FindNextFileW(dir->handle, &dir->info)) {
  4670. (void)FindClose(dir->handle);
  4671. dir->handle = INVALID_HANDLE_VALUE;
  4672. }
  4673. } else {
  4674. SetLastError(ERROR_FILE_NOT_FOUND);
  4675. }
  4676. } else {
  4677. SetLastError(ERROR_BAD_ARGUMENTS);
  4678. }
  4679. return result;
  4680. }
  4681. #if !defined(HAVE_POLL)
  4682. #undef POLLIN
  4683. #undef POLLPRI
  4684. #undef POLLOUT
  4685. #define POLLIN (1) /* Data ready - read will not block. */
  4686. #define POLLPRI (2) /* Priority data ready. */
  4687. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4688. FUNCTION_MAY_BE_UNUSED
  4689. static int
  4690. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4691. {
  4692. struct timeval tv;
  4693. fd_set rset;
  4694. fd_set wset;
  4695. unsigned int i;
  4696. int result;
  4697. SOCKET maxfd = 0;
  4698. memset(&tv, 0, sizeof(tv));
  4699. tv.tv_sec = milliseconds / 1000;
  4700. tv.tv_usec = (milliseconds % 1000) * 1000;
  4701. FD_ZERO(&rset);
  4702. FD_ZERO(&wset);
  4703. for (i = 0; i < n; i++) {
  4704. if (pfd[i].events & POLLIN) {
  4705. FD_SET(pfd[i].fd, &rset);
  4706. }
  4707. if (pfd[i].events & POLLOUT) {
  4708. FD_SET(pfd[i].fd, &wset);
  4709. }
  4710. pfd[i].revents = 0;
  4711. if (pfd[i].fd > maxfd) {
  4712. maxfd = pfd[i].fd;
  4713. }
  4714. }
  4715. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4716. for (i = 0; i < n; i++) {
  4717. if (FD_ISSET(pfd[i].fd, &rset)) {
  4718. pfd[i].revents |= POLLIN;
  4719. }
  4720. if (FD_ISSET(pfd[i].fd, &wset)) {
  4721. pfd[i].revents |= POLLOUT;
  4722. }
  4723. }
  4724. }
  4725. /* We should subtract the time used in select from remaining
  4726. * "milliseconds", in particular if called from mg_poll with a
  4727. * timeout quantum.
  4728. * Unfortunately, the remaining time is not stored in "tv" in all
  4729. * implementations, so the result in "tv" must be considered undefined.
  4730. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4731. return result;
  4732. }
  4733. #endif /* HAVE_POLL */
  4734. #if defined(GCC_DIAGNOSTIC)
  4735. /* Enable unused function warning again */
  4736. #pragma GCC diagnostic pop
  4737. #endif
  4738. static void
  4739. set_close_on_exec(SOCKET sock,
  4740. const struct mg_connection *conn /* may be null */,
  4741. struct mg_context *ctx /* may be null */)
  4742. {
  4743. (void)conn; /* Unused. */
  4744. (void)ctx;
  4745. #if defined(_WIN32_WCE)
  4746. (void)sock;
  4747. #else
  4748. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4749. #endif
  4750. }
  4751. int
  4752. mg_start_thread(mg_thread_func_t f, void *p)
  4753. {
  4754. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4755. /* Compile-time option to control stack size, e.g.
  4756. * -DUSE_STACK_SIZE=16384
  4757. */
  4758. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4759. == ((uintptr_t)(-1L)))
  4760. ? -1
  4761. : 0);
  4762. #else
  4763. return (
  4764. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4765. ? -1
  4766. : 0);
  4767. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4768. }
  4769. /* Start a thread storing the thread context. */
  4770. static int
  4771. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4772. void *p,
  4773. pthread_t *threadidptr)
  4774. {
  4775. uintptr_t uip;
  4776. HANDLE threadhandle;
  4777. int result = -1;
  4778. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4779. threadhandle = (HANDLE)uip;
  4780. if ((uip != 0) && (threadidptr != NULL)) {
  4781. *threadidptr = threadhandle;
  4782. result = 0;
  4783. }
  4784. return result;
  4785. }
  4786. /* Wait for a thread to finish. */
  4787. static int
  4788. mg_join_thread(pthread_t threadid)
  4789. {
  4790. int result;
  4791. DWORD dwevent;
  4792. result = -1;
  4793. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4794. if (dwevent == WAIT_FAILED) {
  4795. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4796. } else {
  4797. if (dwevent == WAIT_OBJECT_0) {
  4798. CloseHandle(threadid);
  4799. result = 0;
  4800. }
  4801. }
  4802. return result;
  4803. }
  4804. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4805. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4806. /* Create substitutes for POSIX functions in Win32. */
  4807. #if defined(GCC_DIAGNOSTIC)
  4808. /* Show no warning in case system functions are not used. */
  4809. #pragma GCC diagnostic push
  4810. #pragma GCC diagnostic ignored "-Wunused-function"
  4811. #endif
  4812. FUNCTION_MAY_BE_UNUSED
  4813. static HANDLE
  4814. dlopen(const char *dll_name, int flags)
  4815. {
  4816. wchar_t wbuf[W_PATH_MAX];
  4817. (void)flags;
  4818. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4819. return LoadLibraryW(wbuf);
  4820. }
  4821. FUNCTION_MAY_BE_UNUSED
  4822. static int
  4823. dlclose(void *handle)
  4824. {
  4825. int result;
  4826. if (FreeLibrary((HMODULE)handle) != 0) {
  4827. result = 0;
  4828. } else {
  4829. result = -1;
  4830. }
  4831. return result;
  4832. }
  4833. #if defined(GCC_DIAGNOSTIC)
  4834. /* Enable unused function warning again */
  4835. #pragma GCC diagnostic pop
  4836. #endif
  4837. #endif
  4838. #if !defined(NO_CGI)
  4839. #define SIGKILL (0)
  4840. static int
  4841. kill(pid_t pid, int sig_num)
  4842. {
  4843. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4844. (void)CloseHandle((HANDLE)pid);
  4845. return 0;
  4846. }
  4847. #if !defined(WNOHANG)
  4848. #define WNOHANG (1)
  4849. #endif
  4850. static pid_t
  4851. waitpid(pid_t pid, int *status, int flags)
  4852. {
  4853. DWORD timeout = INFINITE;
  4854. DWORD waitres;
  4855. (void)status; /* Currently not used by any client here */
  4856. if ((flags | WNOHANG) == WNOHANG) {
  4857. timeout = 0;
  4858. }
  4859. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4860. if (waitres == WAIT_OBJECT_0) {
  4861. return pid;
  4862. }
  4863. if (waitres == WAIT_TIMEOUT) {
  4864. return 0;
  4865. }
  4866. return (pid_t)-1;
  4867. }
  4868. static void
  4869. trim_trailing_whitespaces(char *s)
  4870. {
  4871. char *e = s + strlen(s);
  4872. while ((e > s) && isspace((unsigned char)e[-1])) {
  4873. *(--e) = '\0';
  4874. }
  4875. }
  4876. static pid_t
  4877. spawn_process(struct mg_connection *conn,
  4878. const char *prog,
  4879. char *envblk,
  4880. char *envp[],
  4881. int fdin[2],
  4882. int fdout[2],
  4883. int fderr[2],
  4884. const char *dir)
  4885. {
  4886. HANDLE me;
  4887. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4888. cmdline[PATH_MAX], buf[PATH_MAX];
  4889. int truncated;
  4890. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4891. STARTUPINFOA si;
  4892. PROCESS_INFORMATION pi = {0};
  4893. (void)envp;
  4894. memset(&si, 0, sizeof(si));
  4895. si.cb = sizeof(si);
  4896. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4897. si.wShowWindow = SW_HIDE;
  4898. me = GetCurrentProcess();
  4899. DuplicateHandle(me,
  4900. (HANDLE)_get_osfhandle(fdin[0]),
  4901. me,
  4902. &si.hStdInput,
  4903. 0,
  4904. TRUE,
  4905. DUPLICATE_SAME_ACCESS);
  4906. DuplicateHandle(me,
  4907. (HANDLE)_get_osfhandle(fdout[1]),
  4908. me,
  4909. &si.hStdOutput,
  4910. 0,
  4911. TRUE,
  4912. DUPLICATE_SAME_ACCESS);
  4913. DuplicateHandle(me,
  4914. (HANDLE)_get_osfhandle(fderr[1]),
  4915. me,
  4916. &si.hStdError,
  4917. 0,
  4918. TRUE,
  4919. DUPLICATE_SAME_ACCESS);
  4920. /* Mark handles that should not be inherited. See
  4921. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4922. */
  4923. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4924. HANDLE_FLAG_INHERIT,
  4925. 0);
  4926. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4927. HANDLE_FLAG_INHERIT,
  4928. 0);
  4929. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4930. HANDLE_FLAG_INHERIT,
  4931. 0);
  4932. /* If CGI file is a script, try to read the interpreter line */
  4933. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4934. if (interp == NULL) {
  4935. buf[0] = buf[1] = '\0';
  4936. /* Read the first line of the script into the buffer */
  4937. mg_snprintf(
  4938. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4939. if (truncated) {
  4940. pi.hProcess = (pid_t)-1;
  4941. goto spawn_cleanup;
  4942. }
  4943. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4944. #if defined(MG_USE_OPEN_FILE)
  4945. p = (char *)file.access.membuf;
  4946. #else
  4947. p = (char *)NULL;
  4948. #endif
  4949. mg_fgets(buf, sizeof(buf), &file, &p);
  4950. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4951. buf[sizeof(buf) - 1] = '\0';
  4952. }
  4953. if ((buf[0] == '#') && (buf[1] == '!')) {
  4954. trim_trailing_whitespaces(buf + 2);
  4955. } else {
  4956. buf[2] = '\0';
  4957. }
  4958. interp = buf + 2;
  4959. }
  4960. if (interp[0] != '\0') {
  4961. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4962. interp = full_interp;
  4963. }
  4964. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4965. if (interp[0] != '\0') {
  4966. mg_snprintf(conn,
  4967. &truncated,
  4968. cmdline,
  4969. sizeof(cmdline),
  4970. "\"%s\" \"%s\\%s\"",
  4971. interp,
  4972. full_dir,
  4973. prog);
  4974. } else {
  4975. mg_snprintf(conn,
  4976. &truncated,
  4977. cmdline,
  4978. sizeof(cmdline),
  4979. "\"%s\\%s\"",
  4980. full_dir,
  4981. prog);
  4982. }
  4983. if (truncated) {
  4984. pi.hProcess = (pid_t)-1;
  4985. goto spawn_cleanup;
  4986. }
  4987. DEBUG_TRACE("Running [%s]", cmdline);
  4988. if (CreateProcessA(NULL,
  4989. cmdline,
  4990. NULL,
  4991. NULL,
  4992. TRUE,
  4993. CREATE_NEW_PROCESS_GROUP,
  4994. envblk,
  4995. NULL,
  4996. &si,
  4997. &pi)
  4998. == 0) {
  4999. mg_cry_internal(
  5000. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5001. pi.hProcess = (pid_t)-1;
  5002. /* goto spawn_cleanup; */
  5003. }
  5004. spawn_cleanup:
  5005. (void)CloseHandle(si.hStdOutput);
  5006. (void)CloseHandle(si.hStdError);
  5007. (void)CloseHandle(si.hStdInput);
  5008. if (pi.hThread != NULL) {
  5009. (void)CloseHandle(pi.hThread);
  5010. }
  5011. return (pid_t)pi.hProcess;
  5012. }
  5013. #endif /* !NO_CGI */
  5014. static int
  5015. set_blocking_mode(SOCKET sock)
  5016. {
  5017. unsigned long non_blocking = 0;
  5018. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5019. }
  5020. static int
  5021. set_non_blocking_mode(SOCKET sock)
  5022. {
  5023. unsigned long non_blocking = 1;
  5024. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5025. }
  5026. #else
  5027. #if !defined(NO_FILESYSTEMS)
  5028. static int
  5029. mg_stat(const struct mg_connection *conn,
  5030. const char *path,
  5031. struct mg_file_stat *filep)
  5032. {
  5033. struct stat st;
  5034. if (!filep) {
  5035. return 0;
  5036. }
  5037. memset(filep, 0, sizeof(*filep));
  5038. if (conn && is_file_in_memory(conn, path)) {
  5039. /* Quick fix (for 1.9.x): */
  5040. /* mg_stat must fill all fields, also for files in memory */
  5041. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5042. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5043. filep->size = tmp_file.stat.size;
  5044. filep->last_modified = time(NULL);
  5045. filep->location = 2;
  5046. /* TODO: remove legacy "files in memory" feature */
  5047. return 1;
  5048. }
  5049. if (0 == stat(path, &st)) {
  5050. filep->size = (uint64_t)(st.st_size);
  5051. filep->last_modified = st.st_mtime;
  5052. filep->is_directory = S_ISDIR(st.st_mode);
  5053. return 1;
  5054. }
  5055. return 0;
  5056. }
  5057. #endif /* NO_FILESYSTEMS */
  5058. static void
  5059. set_close_on_exec(int fd,
  5060. const struct mg_connection *conn /* may be null */,
  5061. struct mg_context *ctx /* may be null */)
  5062. {
  5063. #if defined(__ZEPHYR__)
  5064. (void)fd;
  5065. (void)conn;
  5066. (void)ctx;
  5067. #else
  5068. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5069. if (conn || ctx) {
  5070. struct mg_connection fc;
  5071. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5072. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5073. __func__,
  5074. strerror(ERRNO));
  5075. }
  5076. }
  5077. #endif
  5078. }
  5079. int
  5080. mg_start_thread(mg_thread_func_t func, void *param)
  5081. {
  5082. pthread_t thread_id;
  5083. pthread_attr_t attr;
  5084. int result;
  5085. (void)pthread_attr_init(&attr);
  5086. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5087. #if defined(__ZEPHYR__)
  5088. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5089. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5090. /* Compile-time option to control stack size,
  5091. * e.g. -DUSE_STACK_SIZE=16384 */
  5092. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5093. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5094. result = pthread_create(&thread_id, &attr, func, param);
  5095. pthread_attr_destroy(&attr);
  5096. return result;
  5097. }
  5098. /* Start a thread storing the thread context. */
  5099. static int
  5100. mg_start_thread_with_id(mg_thread_func_t func,
  5101. void *param,
  5102. pthread_t *threadidptr)
  5103. {
  5104. pthread_t thread_id;
  5105. pthread_attr_t attr;
  5106. int result;
  5107. (void)pthread_attr_init(&attr);
  5108. #if defined(__ZEPHYR__)
  5109. pthread_attr_setstack(&attr,
  5110. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5111. ZEPHYR_STACK_SIZE);
  5112. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5113. /* Compile-time option to control stack size,
  5114. * e.g. -DUSE_STACK_SIZE=16384 */
  5115. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5116. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5117. result = pthread_create(&thread_id, &attr, func, param);
  5118. pthread_attr_destroy(&attr);
  5119. if ((result == 0) && (threadidptr != NULL)) {
  5120. *threadidptr = thread_id;
  5121. }
  5122. return result;
  5123. }
  5124. /* Wait for a thread to finish. */
  5125. static int
  5126. mg_join_thread(pthread_t threadid)
  5127. {
  5128. int result;
  5129. result = pthread_join(threadid, NULL);
  5130. return result;
  5131. }
  5132. #if !defined(NO_CGI)
  5133. static pid_t
  5134. spawn_process(struct mg_connection *conn,
  5135. const char *prog,
  5136. char *envblk,
  5137. char *envp[],
  5138. int fdin[2],
  5139. int fdout[2],
  5140. int fderr[2],
  5141. const char *dir)
  5142. {
  5143. pid_t pid;
  5144. const char *interp;
  5145. (void)envblk;
  5146. if ((pid = fork()) == -1) {
  5147. /* Parent */
  5148. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5149. } else if (pid != 0) {
  5150. /* Make sure children close parent-side descriptors.
  5151. * The caller will close the child-side immediately. */
  5152. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5153. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5154. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5155. } else {
  5156. /* Child */
  5157. if (chdir(dir) != 0) {
  5158. mg_cry_internal(
  5159. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5160. } else if (dup2(fdin[0], 0) == -1) {
  5161. mg_cry_internal(conn,
  5162. "%s: dup2(%d, 0): %s",
  5163. __func__,
  5164. fdin[0],
  5165. strerror(ERRNO));
  5166. } else if (dup2(fdout[1], 1) == -1) {
  5167. mg_cry_internal(conn,
  5168. "%s: dup2(%d, 1): %s",
  5169. __func__,
  5170. fdout[1],
  5171. strerror(ERRNO));
  5172. } else if (dup2(fderr[1], 2) == -1) {
  5173. mg_cry_internal(conn,
  5174. "%s: dup2(%d, 2): %s",
  5175. __func__,
  5176. fderr[1],
  5177. strerror(ERRNO));
  5178. } else {
  5179. struct sigaction sa;
  5180. /* Keep stderr and stdout in two different pipes.
  5181. * Stdout will be sent back to the client,
  5182. * stderr should go into a server error log. */
  5183. (void)close(fdin[0]);
  5184. (void)close(fdout[1]);
  5185. (void)close(fderr[1]);
  5186. /* Close write end fdin and read end fdout and fderr */
  5187. (void)close(fdin[1]);
  5188. (void)close(fdout[0]);
  5189. (void)close(fderr[0]);
  5190. /* After exec, all signal handlers are restored to their default
  5191. * values, with one exception of SIGCHLD. According to
  5192. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5193. * will leave unchanged after exec if it was set to be ignored.
  5194. * Restore it to default action. */
  5195. memset(&sa, 0, sizeof(sa));
  5196. sa.sa_handler = SIG_DFL;
  5197. sigaction(SIGCHLD, &sa, NULL);
  5198. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5199. if (interp == NULL) {
  5200. (void)execle(prog, prog, NULL, envp);
  5201. mg_cry_internal(conn,
  5202. "%s: execle(%s): %s",
  5203. __func__,
  5204. prog,
  5205. strerror(ERRNO));
  5206. } else {
  5207. (void)execle(interp, interp, prog, NULL, envp);
  5208. mg_cry_internal(conn,
  5209. "%s: execle(%s %s): %s",
  5210. __func__,
  5211. interp,
  5212. prog,
  5213. strerror(ERRNO));
  5214. }
  5215. }
  5216. exit(EXIT_FAILURE);
  5217. }
  5218. return pid;
  5219. }
  5220. #endif /* !NO_CGI */
  5221. static int
  5222. set_non_blocking_mode(SOCKET sock)
  5223. {
  5224. int flags = fcntl(sock, F_GETFL, 0);
  5225. if (flags < 0) {
  5226. return -1;
  5227. }
  5228. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5229. return -1;
  5230. }
  5231. return 0;
  5232. }
  5233. static int
  5234. set_blocking_mode(SOCKET sock)
  5235. {
  5236. int flags = fcntl(sock, F_GETFL, 0);
  5237. if (flags < 0) {
  5238. return -1;
  5239. }
  5240. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5241. return -1;
  5242. }
  5243. return 0;
  5244. }
  5245. #endif /* _WIN32 / else */
  5246. /* End of initial operating system specific define block. */
  5247. /* Get a random number (independent of C rand function) */
  5248. static uint64_t
  5249. get_random(void)
  5250. {
  5251. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5252. static uint64_t lcg = 0; /* Linear congruential generator */
  5253. uint64_t now = mg_get_current_time_ns();
  5254. if (lfsr == 0) {
  5255. /* lfsr will be only 0 if has not been initialized,
  5256. * so this code is called only once. */
  5257. lfsr = mg_get_current_time_ns();
  5258. lcg = mg_get_current_time_ns();
  5259. } else {
  5260. /* Get the next step of both random number generators. */
  5261. lfsr = (lfsr >> 1)
  5262. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5263. << 63);
  5264. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5265. }
  5266. /* Combining two pseudo-random number generators and a high resolution
  5267. * part
  5268. * of the current server time will make it hard (impossible?) to guess
  5269. * the
  5270. * next number. */
  5271. return (lfsr ^ lcg ^ now);
  5272. }
  5273. static int
  5274. mg_poll(struct mg_pollfd *pfd,
  5275. unsigned int n,
  5276. int milliseconds,
  5277. volatile int *stop_server)
  5278. {
  5279. /* Call poll, but only for a maximum time of a few seconds.
  5280. * This will allow to stop the server after some seconds, instead
  5281. * of having to wait for a long socket timeout. */
  5282. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5283. do {
  5284. int result;
  5285. if (*stop_server) {
  5286. /* Shut down signal */
  5287. return -2;
  5288. }
  5289. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5290. ms_now = milliseconds;
  5291. }
  5292. result = poll(pfd, n, ms_now);
  5293. if (result != 0) {
  5294. /* Poll returned either success (1) or error (-1).
  5295. * Forward both to the caller. */
  5296. return result;
  5297. }
  5298. /* Poll returned timeout (0). */
  5299. if (milliseconds > 0) {
  5300. milliseconds -= ms_now;
  5301. }
  5302. } while (milliseconds != 0);
  5303. /* timeout: return 0 */
  5304. return 0;
  5305. }
  5306. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5307. * descriptor.
  5308. * Return value:
  5309. * >=0 .. number of bytes successfully written
  5310. * -1 .. timeout
  5311. * -2 .. error
  5312. */
  5313. static int
  5314. push_inner(struct mg_context *ctx,
  5315. FILE *fp,
  5316. SOCKET sock,
  5317. SSL *ssl,
  5318. const char *buf,
  5319. int len,
  5320. double timeout)
  5321. {
  5322. uint64_t start = 0, now = 0, timeout_ns = 0;
  5323. int n, err;
  5324. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5325. #if defined(_WIN32)
  5326. typedef int len_t;
  5327. #else
  5328. typedef size_t len_t;
  5329. #endif
  5330. if (timeout > 0) {
  5331. now = mg_get_current_time_ns();
  5332. start = now;
  5333. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5334. }
  5335. if (ctx == NULL) {
  5336. return -2;
  5337. }
  5338. #if defined(NO_SSL)
  5339. if (ssl) {
  5340. return -2;
  5341. }
  5342. #endif
  5343. /* Try to read until it succeeds, fails, times out, or the server
  5344. * shuts down. */
  5345. for (;;) {
  5346. #if !defined(NO_SSL)
  5347. if (ssl != NULL) {
  5348. n = SSL_write(ssl, buf, len);
  5349. if (n <= 0) {
  5350. err = SSL_get_error(ssl, n);
  5351. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5352. err = ERRNO;
  5353. } else if ((err == SSL_ERROR_WANT_READ)
  5354. || (err == SSL_ERROR_WANT_WRITE)) {
  5355. n = 0;
  5356. } else {
  5357. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5358. return -2;
  5359. }
  5360. } else {
  5361. err = 0;
  5362. }
  5363. } else
  5364. #endif
  5365. if (fp != NULL) {
  5366. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5367. if (ferror(fp)) {
  5368. n = -1;
  5369. err = ERRNO;
  5370. } else {
  5371. err = 0;
  5372. }
  5373. } else {
  5374. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5375. err = (n < 0) ? ERRNO : 0;
  5376. #if defined(_WIN32)
  5377. if (err == WSAEWOULDBLOCK) {
  5378. err = 0;
  5379. n = 0;
  5380. }
  5381. #else
  5382. if (err == EWOULDBLOCK) {
  5383. err = 0;
  5384. n = 0;
  5385. }
  5386. #endif
  5387. if (n < 0) {
  5388. /* shutdown of the socket at client side */
  5389. return -2;
  5390. }
  5391. }
  5392. if (ctx->stop_flag) {
  5393. return -2;
  5394. }
  5395. if ((n > 0) || ((n == 0) && (len == 0))) {
  5396. /* some data has been read, or no data was requested */
  5397. return n;
  5398. }
  5399. if (n < 0) {
  5400. /* socket error - check errno */
  5401. DEBUG_TRACE("send() failed, error %d", err);
  5402. /* TODO (mid): error handling depending on the error code.
  5403. * These codes are different between Windows and Linux.
  5404. * Currently there is no problem with failing send calls,
  5405. * if there is a reproducible situation, it should be
  5406. * investigated in detail.
  5407. */
  5408. return -2;
  5409. }
  5410. /* Only in case n=0 (timeout), repeat calling the write function */
  5411. /* If send failed, wait before retry */
  5412. if (fp != NULL) {
  5413. /* For files, just wait a fixed time.
  5414. * Maybe it helps, maybe not. */
  5415. mg_sleep(5);
  5416. } else {
  5417. /* For sockets, wait for the socket using poll */
  5418. struct mg_pollfd pfd[1];
  5419. int pollres;
  5420. pfd[0].fd = sock;
  5421. pfd[0].events = POLLOUT;
  5422. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5423. if (ctx->stop_flag) {
  5424. return -2;
  5425. }
  5426. if (pollres > 0) {
  5427. continue;
  5428. }
  5429. }
  5430. if (timeout > 0) {
  5431. now = mg_get_current_time_ns();
  5432. if ((now - start) > timeout_ns) {
  5433. /* Timeout */
  5434. break;
  5435. }
  5436. }
  5437. }
  5438. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5439. used */
  5440. return -1;
  5441. }
  5442. static int
  5443. push_all(struct mg_context *ctx,
  5444. FILE *fp,
  5445. SOCKET sock,
  5446. SSL *ssl,
  5447. const char *buf,
  5448. int len)
  5449. {
  5450. double timeout = -1.0;
  5451. int n, nwritten = 0;
  5452. if (ctx == NULL) {
  5453. return -1;
  5454. }
  5455. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5456. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5457. }
  5458. while ((len > 0) && (ctx->stop_flag == 0)) {
  5459. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5460. if (n < 0) {
  5461. if (nwritten == 0) {
  5462. nwritten = -1; /* Propagate the error */
  5463. }
  5464. break;
  5465. } else if (n == 0) {
  5466. break; /* No more data to write */
  5467. } else {
  5468. nwritten += n;
  5469. len -= n;
  5470. }
  5471. }
  5472. return nwritten;
  5473. }
  5474. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5475. * Return value:
  5476. * >=0 .. number of bytes successfully read
  5477. * -1 .. timeout
  5478. * -2 .. error
  5479. */
  5480. static int
  5481. pull_inner(FILE *fp,
  5482. struct mg_connection *conn,
  5483. char *buf,
  5484. int len,
  5485. double timeout)
  5486. {
  5487. int nread, err = 0;
  5488. #if defined(_WIN32)
  5489. typedef int len_t;
  5490. #else
  5491. typedef size_t len_t;
  5492. #endif
  5493. #if !defined(NO_SSL)
  5494. int ssl_pending;
  5495. #endif
  5496. /* We need an additional wait loop around this, because in some cases
  5497. * with TLSwe may get data from the socket but not from SSL_read.
  5498. * In this case we need to repeat at least once.
  5499. */
  5500. if (fp != NULL) {
  5501. #if !defined(_WIN32_WCE)
  5502. /* Use read() instead of fread(), because if we're reading from the
  5503. * CGI pipe, fread() may block until IO buffer is filled up. We
  5504. * cannot afford to block and must pass all read bytes immediately
  5505. * to the client. */
  5506. nread = (int)read(fileno(fp), buf, (size_t)len);
  5507. #else
  5508. /* WinCE does not support CGI pipes */
  5509. nread = (int)fread(buf, 1, (size_t)len, fp);
  5510. #endif
  5511. err = (nread < 0) ? ERRNO : 0;
  5512. if ((nread == 0) && (len > 0)) {
  5513. /* Should get data, but got EOL */
  5514. return -2;
  5515. }
  5516. #if !defined(NO_SSL)
  5517. } else if ((conn->ssl != NULL)
  5518. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5519. /* We already know there is no more data buffered in conn->buf
  5520. * but there is more available in the SSL layer. So don't poll
  5521. * conn->client.sock yet. */
  5522. if (ssl_pending > len) {
  5523. ssl_pending = len;
  5524. }
  5525. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5526. if (nread <= 0) {
  5527. err = SSL_get_error(conn->ssl, nread);
  5528. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5529. err = ERRNO;
  5530. } else if ((err == SSL_ERROR_WANT_READ)
  5531. || (err == SSL_ERROR_WANT_WRITE)) {
  5532. nread = 0;
  5533. } else {
  5534. /* All errors should return -2 */
  5535. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5536. return -2;
  5537. }
  5538. ERR_clear_error();
  5539. } else {
  5540. err = 0;
  5541. }
  5542. } else if (conn->ssl != NULL) {
  5543. struct mg_pollfd pfd[1];
  5544. int pollres;
  5545. pfd[0].fd = conn->client.sock;
  5546. pfd[0].events = POLLIN;
  5547. pollres = mg_poll(pfd,
  5548. 1,
  5549. (int)(timeout * 1000.0),
  5550. &(conn->phys_ctx->stop_flag));
  5551. if (conn->phys_ctx->stop_flag) {
  5552. return -2;
  5553. }
  5554. if (pollres > 0) {
  5555. nread = SSL_read(conn->ssl, buf, len);
  5556. if (nread <= 0) {
  5557. err = SSL_get_error(conn->ssl, nread);
  5558. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5559. err = ERRNO;
  5560. } else if ((err == SSL_ERROR_WANT_READ)
  5561. || (err == SSL_ERROR_WANT_WRITE)) {
  5562. nread = 0;
  5563. } else {
  5564. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5565. return -2;
  5566. }
  5567. } else {
  5568. err = 0;
  5569. }
  5570. ERR_clear_error();
  5571. } else if (pollres < 0) {
  5572. /* Error */
  5573. return -2;
  5574. } else {
  5575. /* pollres = 0 means timeout */
  5576. nread = 0;
  5577. }
  5578. #endif
  5579. } else {
  5580. struct mg_pollfd pfd[1];
  5581. int pollres;
  5582. pfd[0].fd = conn->client.sock;
  5583. pfd[0].events = POLLIN;
  5584. pollres = mg_poll(pfd,
  5585. 1,
  5586. (int)(timeout * 1000.0),
  5587. &(conn->phys_ctx->stop_flag));
  5588. if (conn->phys_ctx->stop_flag) {
  5589. return -2;
  5590. }
  5591. if (pollres > 0) {
  5592. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5593. err = (nread < 0) ? ERRNO : 0;
  5594. if (nread <= 0) {
  5595. /* shutdown of the socket at client side */
  5596. return -2;
  5597. }
  5598. } else if (pollres < 0) {
  5599. /* error callint poll */
  5600. return -2;
  5601. } else {
  5602. /* pollres = 0 means timeout */
  5603. nread = 0;
  5604. }
  5605. }
  5606. if (conn->phys_ctx->stop_flag) {
  5607. return -2;
  5608. }
  5609. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5610. /* some data has been read, or no data was requested */
  5611. return nread;
  5612. }
  5613. if (nread < 0) {
  5614. /* socket error - check errno */
  5615. #if defined(_WIN32)
  5616. if (err == WSAEWOULDBLOCK) {
  5617. /* TODO (low): check if this is still required */
  5618. /* standard case if called from close_socket_gracefully */
  5619. return -2;
  5620. } else if (err == WSAETIMEDOUT) {
  5621. /* TODO (low): check if this is still required */
  5622. /* timeout is handled by the while loop */
  5623. return 0;
  5624. } else if (err == WSAECONNABORTED) {
  5625. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5626. return -2;
  5627. } else {
  5628. DEBUG_TRACE("recv() failed, error %d", err);
  5629. return -2;
  5630. }
  5631. #else
  5632. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5633. * if the timeout is reached and if the socket was set to non-
  5634. * blocking in close_socket_gracefully, so we can not distinguish
  5635. * here. We have to wait for the timeout in both cases for now.
  5636. */
  5637. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5638. /* TODO (low): check if this is still required */
  5639. /* EAGAIN/EWOULDBLOCK:
  5640. * standard case if called from close_socket_gracefully
  5641. * => should return -1 */
  5642. /* or timeout occurred
  5643. * => the code must stay in the while loop */
  5644. /* EINTR can be generated on a socket with a timeout set even
  5645. * when SA_RESTART is effective for all relevant signals
  5646. * (see signal(7)).
  5647. * => stay in the while loop */
  5648. } else {
  5649. DEBUG_TRACE("recv() failed, error %d", err);
  5650. return -2;
  5651. }
  5652. #endif
  5653. }
  5654. /* Timeout occurred, but no data available. */
  5655. return -1;
  5656. }
  5657. static int
  5658. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5659. {
  5660. int n, nread = 0;
  5661. double timeout = -1.0;
  5662. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5663. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5664. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5665. }
  5666. if (timeout >= 0.0) {
  5667. start_time = mg_get_current_time_ns();
  5668. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5669. }
  5670. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5671. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5672. if (n == -2) {
  5673. if (nread == 0) {
  5674. nread = -1; /* Propagate the error */
  5675. }
  5676. break;
  5677. } else if (n == -1) {
  5678. /* timeout */
  5679. if (timeout >= 0.0) {
  5680. now = mg_get_current_time_ns();
  5681. if ((now - start_time) <= timeout_ns) {
  5682. continue;
  5683. }
  5684. }
  5685. break;
  5686. } else if (n == 0) {
  5687. break; /* No more data to read */
  5688. } else {
  5689. nread += n;
  5690. len -= n;
  5691. }
  5692. }
  5693. return nread;
  5694. }
  5695. static void
  5696. discard_unread_request_data(struct mg_connection *conn)
  5697. {
  5698. char buf[MG_BUF_LEN];
  5699. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5700. ;
  5701. }
  5702. static int
  5703. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5704. {
  5705. int64_t content_len, n, buffered_len, nread;
  5706. int64_t len64 =
  5707. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5708. * int, we may not read more
  5709. * bytes */
  5710. const char *body;
  5711. if (conn == NULL) {
  5712. return 0;
  5713. }
  5714. /* If Content-Length is not set for a response with body data,
  5715. * we do not know in advance how much data should be read. */
  5716. content_len = conn->content_len;
  5717. if (content_len < 0) {
  5718. /* The body data is completed when the connection is closed. */
  5719. content_len = INT64_MAX;
  5720. }
  5721. nread = 0;
  5722. if (conn->consumed_content < content_len) {
  5723. /* Adjust number of bytes to read. */
  5724. int64_t left_to_read = content_len - conn->consumed_content;
  5725. if (left_to_read < len64) {
  5726. /* Do not read more than the total content length of the
  5727. * request.
  5728. */
  5729. len64 = left_to_read;
  5730. }
  5731. /* Return buffered data */
  5732. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5733. - conn->consumed_content;
  5734. if (buffered_len > 0) {
  5735. if (len64 < buffered_len) {
  5736. buffered_len = len64;
  5737. }
  5738. body = conn->buf + conn->request_len + conn->consumed_content;
  5739. memcpy(buf, body, (size_t)buffered_len);
  5740. len64 -= buffered_len;
  5741. conn->consumed_content += buffered_len;
  5742. nread += buffered_len;
  5743. buf = (char *)buf + buffered_len;
  5744. }
  5745. /* We have returned all buffered data. Read new data from the remote
  5746. * socket.
  5747. */
  5748. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5749. conn->consumed_content += n;
  5750. nread += n;
  5751. } else {
  5752. nread = ((nread > 0) ? nread : n);
  5753. }
  5754. }
  5755. return (int)nread;
  5756. }
  5757. int
  5758. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5759. {
  5760. if (len > INT_MAX) {
  5761. len = INT_MAX;
  5762. }
  5763. if (conn == NULL) {
  5764. return 0;
  5765. }
  5766. if (conn->is_chunked) {
  5767. size_t all_read = 0;
  5768. while (len > 0) {
  5769. if (conn->is_chunked >= 3) {
  5770. /* No more data left to read */
  5771. return 0;
  5772. }
  5773. if (conn->is_chunked != 1) {
  5774. /* Has error */
  5775. return -1;
  5776. }
  5777. if (conn->consumed_content != conn->content_len) {
  5778. /* copy from the current chunk */
  5779. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5780. if (read_ret < 1) {
  5781. /* read error */
  5782. conn->is_chunked = 2;
  5783. return -1;
  5784. }
  5785. all_read += (size_t)read_ret;
  5786. len -= (size_t)read_ret;
  5787. if (conn->consumed_content == conn->content_len) {
  5788. /* Add data bytes in the current chunk have been read,
  5789. * so we are expecting \r\n now. */
  5790. char x[2];
  5791. conn->content_len += 2;
  5792. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5793. || (x[1] != '\n')) {
  5794. /* Protocol violation */
  5795. conn->is_chunked = 2;
  5796. return -1;
  5797. }
  5798. }
  5799. } else {
  5800. /* fetch a new chunk */
  5801. size_t i;
  5802. char lenbuf[64];
  5803. char *end = NULL;
  5804. unsigned long chunkSize = 0;
  5805. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5806. conn->content_len++;
  5807. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5808. lenbuf[i] = 0;
  5809. }
  5810. if ((i > 0) && (lenbuf[i] == '\r')
  5811. && (lenbuf[i - 1] != '\r')) {
  5812. continue;
  5813. }
  5814. if ((i > 1) && (lenbuf[i] == '\n')
  5815. && (lenbuf[i - 1] == '\r')) {
  5816. lenbuf[i + 1] = 0;
  5817. chunkSize = strtoul(lenbuf, &end, 16);
  5818. if (chunkSize == 0) {
  5819. /* regular end of content */
  5820. conn->is_chunked = 3;
  5821. }
  5822. break;
  5823. }
  5824. if (!isxdigit((unsigned char)lenbuf[i])) {
  5825. /* illegal character for chunk length */
  5826. conn->is_chunked = 2;
  5827. return -1;
  5828. }
  5829. }
  5830. if ((end == NULL) || (*end != '\r')) {
  5831. /* chunksize not set correctly */
  5832. conn->is_chunked = 2;
  5833. return -1;
  5834. }
  5835. if (chunkSize == 0) {
  5836. /* try discarding trailer for keep-alive */
  5837. conn->content_len += 2;
  5838. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5839. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5840. conn->is_chunked = 4;
  5841. }
  5842. break;
  5843. }
  5844. /* append a new chunk */
  5845. conn->content_len += chunkSize;
  5846. }
  5847. }
  5848. return (int)all_read;
  5849. }
  5850. return mg_read_inner(conn, buf, len);
  5851. }
  5852. int
  5853. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5854. {
  5855. time_t now;
  5856. int n, total, allowed;
  5857. if (conn == NULL) {
  5858. return 0;
  5859. }
  5860. if (len > INT_MAX) {
  5861. return -1;
  5862. }
  5863. if (conn->throttle > 0) {
  5864. if ((now = time(NULL)) != conn->last_throttle_time) {
  5865. conn->last_throttle_time = now;
  5866. conn->last_throttle_bytes = 0;
  5867. }
  5868. allowed = conn->throttle - conn->last_throttle_bytes;
  5869. if (allowed > (int)len) {
  5870. allowed = (int)len;
  5871. }
  5872. if ((total = push_all(conn->phys_ctx,
  5873. NULL,
  5874. conn->client.sock,
  5875. conn->ssl,
  5876. (const char *)buf,
  5877. allowed))
  5878. == allowed) {
  5879. buf = (const char *)buf + total;
  5880. conn->last_throttle_bytes += total;
  5881. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5882. allowed = (conn->throttle > ((int)len - total))
  5883. ? (int)len - total
  5884. : conn->throttle;
  5885. if ((n = push_all(conn->phys_ctx,
  5886. NULL,
  5887. conn->client.sock,
  5888. conn->ssl,
  5889. (const char *)buf,
  5890. allowed))
  5891. != allowed) {
  5892. break;
  5893. }
  5894. sleep(1);
  5895. conn->last_throttle_bytes = allowed;
  5896. conn->last_throttle_time = time(NULL);
  5897. buf = (const char *)buf + n;
  5898. total += n;
  5899. }
  5900. }
  5901. } else {
  5902. total = push_all(conn->phys_ctx,
  5903. NULL,
  5904. conn->client.sock,
  5905. conn->ssl,
  5906. (const char *)buf,
  5907. (int)len);
  5908. }
  5909. if (total > 0) {
  5910. conn->num_bytes_sent += total;
  5911. }
  5912. return total;
  5913. }
  5914. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5915. int
  5916. mg_send_chunk(struct mg_connection *conn,
  5917. const char *chunk,
  5918. unsigned int chunk_len)
  5919. {
  5920. char lenbuf[16];
  5921. size_t lenbuf_len;
  5922. int ret;
  5923. int t;
  5924. /* First store the length information in a text buffer. */
  5925. sprintf(lenbuf, "%x\r\n", chunk_len);
  5926. lenbuf_len = strlen(lenbuf);
  5927. /* Then send length information, chunk and terminating \r\n. */
  5928. ret = mg_write(conn, lenbuf, lenbuf_len);
  5929. if (ret != (int)lenbuf_len) {
  5930. return -1;
  5931. }
  5932. t = ret;
  5933. ret = mg_write(conn, chunk, chunk_len);
  5934. if (ret != (int)chunk_len) {
  5935. return -1;
  5936. }
  5937. t += ret;
  5938. ret = mg_write(conn, "\r\n", 2);
  5939. if (ret != 2) {
  5940. return -1;
  5941. }
  5942. t += ret;
  5943. return t;
  5944. }
  5945. #if defined(GCC_DIAGNOSTIC)
  5946. /* This block forwards format strings to printf implementations,
  5947. * so we need to disable the format-nonliteral warning. */
  5948. #pragma GCC diagnostic push
  5949. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5950. #endif
  5951. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5952. static int
  5953. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5954. {
  5955. va_list ap_copy;
  5956. size_t size = MG_BUF_LEN / 4;
  5957. int len = -1;
  5958. *buf = NULL;
  5959. while (len < 0) {
  5960. if (*buf) {
  5961. mg_free(*buf);
  5962. }
  5963. size *= 4;
  5964. *buf = (char *)mg_malloc(size);
  5965. if (!*buf) {
  5966. break;
  5967. }
  5968. va_copy(ap_copy, ap);
  5969. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5970. va_end(ap_copy);
  5971. (*buf)[size - 1] = 0;
  5972. }
  5973. return len;
  5974. }
  5975. /* Print message to buffer. If buffer is large enough to hold the message,
  5976. * return buffer. If buffer is to small, allocate large enough buffer on
  5977. * heap,
  5978. * and return allocated buffer. */
  5979. static int
  5980. alloc_vprintf(char **out_buf,
  5981. char *prealloc_buf,
  5982. size_t prealloc_size,
  5983. const char *fmt,
  5984. va_list ap)
  5985. {
  5986. va_list ap_copy;
  5987. int len;
  5988. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5989. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5990. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5991. * Therefore, we make two passes: on first pass, get required message
  5992. * length.
  5993. * On second pass, actually print the message. */
  5994. va_copy(ap_copy, ap);
  5995. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5996. va_end(ap_copy);
  5997. if (len < 0) {
  5998. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5999. * Switch to alternative code path that uses incremental
  6000. * allocations.
  6001. */
  6002. va_copy(ap_copy, ap);
  6003. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6004. va_end(ap_copy);
  6005. } else if ((size_t)(len) >= prealloc_size) {
  6006. /* The pre-allocated buffer not large enough. */
  6007. /* Allocate a new buffer. */
  6008. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6009. if (!*out_buf) {
  6010. /* Allocation failed. Return -1 as "out of memory" error. */
  6011. return -1;
  6012. }
  6013. /* Buffer allocation successful. Store the string there. */
  6014. va_copy(ap_copy, ap);
  6015. IGNORE_UNUSED_RESULT(
  6016. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6017. va_end(ap_copy);
  6018. } else {
  6019. /* The pre-allocated buffer is large enough.
  6020. * Use it to store the string and return the address. */
  6021. va_copy(ap_copy, ap);
  6022. IGNORE_UNUSED_RESULT(
  6023. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6024. va_end(ap_copy);
  6025. *out_buf = prealloc_buf;
  6026. }
  6027. return len;
  6028. }
  6029. #if defined(GCC_DIAGNOSTIC)
  6030. /* Enable format-nonliteral warning again. */
  6031. #pragma GCC diagnostic pop
  6032. #endif
  6033. static int
  6034. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6035. {
  6036. char mem[MG_BUF_LEN];
  6037. char *buf = NULL;
  6038. int len;
  6039. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6040. len = mg_write(conn, buf, (size_t)len);
  6041. }
  6042. if (buf != mem) {
  6043. mg_free(buf);
  6044. }
  6045. return len;
  6046. }
  6047. int
  6048. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6049. {
  6050. va_list ap;
  6051. int result;
  6052. va_start(ap, fmt);
  6053. result = mg_vprintf(conn, fmt, ap);
  6054. va_end(ap);
  6055. return result;
  6056. }
  6057. int
  6058. mg_url_decode(const char *src,
  6059. int src_len,
  6060. char *dst,
  6061. int dst_len,
  6062. int is_form_url_encoded)
  6063. {
  6064. int i, j, a, b;
  6065. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6066. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6067. if ((i < src_len - 2) && (src[i] == '%')
  6068. && isxdigit((unsigned char)src[i + 1])
  6069. && isxdigit((unsigned char)src[i + 2])) {
  6070. a = tolower((unsigned char)src[i + 1]);
  6071. b = tolower((unsigned char)src[i + 2]);
  6072. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6073. i += 2;
  6074. } else if (is_form_url_encoded && (src[i] == '+')) {
  6075. dst[j] = ' ';
  6076. } else {
  6077. dst[j] = src[i];
  6078. }
  6079. }
  6080. dst[j] = '\0'; /* Null-terminate the destination */
  6081. return (i >= src_len) ? j : -1;
  6082. }
  6083. int
  6084. mg_get_var(const char *data,
  6085. size_t data_len,
  6086. const char *name,
  6087. char *dst,
  6088. size_t dst_len)
  6089. {
  6090. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6091. }
  6092. int
  6093. mg_get_var2(const char *data,
  6094. size_t data_len,
  6095. const char *name,
  6096. char *dst,
  6097. size_t dst_len,
  6098. size_t occurrence)
  6099. {
  6100. const char *p, *e, *s;
  6101. size_t name_len;
  6102. int len;
  6103. if ((dst == NULL) || (dst_len == 0)) {
  6104. len = -2;
  6105. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6106. len = -1;
  6107. dst[0] = '\0';
  6108. } else {
  6109. name_len = strlen(name);
  6110. e = data + data_len;
  6111. len = -1;
  6112. dst[0] = '\0';
  6113. /* data is "var1=val1&var2=val2...". Find variable first */
  6114. for (p = data; p + name_len < e; p++) {
  6115. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6116. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6117. /* Point p to variable value */
  6118. p += name_len + 1;
  6119. /* Point s to the end of the value */
  6120. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6121. if (s == NULL) {
  6122. s = e;
  6123. }
  6124. DEBUG_ASSERT(s >= p);
  6125. if (s < p) {
  6126. return -3;
  6127. }
  6128. /* Decode variable into destination buffer */
  6129. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6130. /* Redirect error code from -1 to -2 (destination buffer too
  6131. * small). */
  6132. if (len == -1) {
  6133. len = -2;
  6134. }
  6135. break;
  6136. }
  6137. }
  6138. }
  6139. return len;
  6140. }
  6141. /* HCP24: some changes to compare hole var_name */
  6142. int
  6143. mg_get_cookie(const char *cookie_header,
  6144. const char *var_name,
  6145. char *dst,
  6146. size_t dst_size)
  6147. {
  6148. const char *s, *p, *end;
  6149. int name_len, len = -1;
  6150. if ((dst == NULL) || (dst_size == 0)) {
  6151. return -2;
  6152. }
  6153. dst[0] = '\0';
  6154. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6155. return -1;
  6156. }
  6157. name_len = (int)strlen(var_name);
  6158. end = s + strlen(s);
  6159. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6160. if (s[name_len] == '=') {
  6161. /* HCP24: now check is it a substring or a full cookie name */
  6162. if ((s == cookie_header) || (s[-1] == ' ')) {
  6163. s += name_len + 1;
  6164. if ((p = strchr(s, ' ')) == NULL) {
  6165. p = end;
  6166. }
  6167. if (p[-1] == ';') {
  6168. p--;
  6169. }
  6170. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6171. s++;
  6172. p--;
  6173. }
  6174. if ((size_t)(p - s) < dst_size) {
  6175. len = (int)(p - s);
  6176. mg_strlcpy(dst, s, (size_t)len + 1);
  6177. } else {
  6178. len = -3;
  6179. }
  6180. break;
  6181. }
  6182. }
  6183. }
  6184. return len;
  6185. }
  6186. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6187. static void
  6188. base64_encode(const unsigned char *src, int src_len, char *dst)
  6189. {
  6190. static const char *b64 =
  6191. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6192. int i, j, a, b, c;
  6193. for (i = j = 0; i < src_len; i += 3) {
  6194. a = src[i];
  6195. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6196. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6197. dst[j++] = b64[a >> 2];
  6198. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6199. if (i + 1 < src_len) {
  6200. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6201. }
  6202. if (i + 2 < src_len) {
  6203. dst[j++] = b64[c & 63];
  6204. }
  6205. }
  6206. while (j % 4 != 0) {
  6207. dst[j++] = '=';
  6208. }
  6209. dst[j++] = '\0';
  6210. }
  6211. #endif
  6212. #if defined(USE_LUA)
  6213. static unsigned char
  6214. b64reverse(char letter)
  6215. {
  6216. if ((letter >= 'A') && (letter <= 'Z')) {
  6217. return letter - 'A';
  6218. }
  6219. if ((letter >= 'a') && (letter <= 'z')) {
  6220. return letter - 'a' + 26;
  6221. }
  6222. if ((letter >= '0') && (letter <= '9')) {
  6223. return letter - '0' + 52;
  6224. }
  6225. if (letter == '+') {
  6226. return 62;
  6227. }
  6228. if (letter == '/') {
  6229. return 63;
  6230. }
  6231. if (letter == '=') {
  6232. return 255; /* normal end */
  6233. }
  6234. return 254; /* error */
  6235. }
  6236. static int
  6237. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6238. {
  6239. int i;
  6240. unsigned char a, b, c, d;
  6241. *dst_len = 0;
  6242. for (i = 0; i < src_len; i += 4) {
  6243. a = b64reverse(src[i]);
  6244. if (a >= 254) {
  6245. return i;
  6246. }
  6247. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6248. if (b >= 254) {
  6249. return i + 1;
  6250. }
  6251. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6252. if (c == 254) {
  6253. return i + 2;
  6254. }
  6255. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6256. if (d == 254) {
  6257. return i + 3;
  6258. }
  6259. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6260. if (c != 255) {
  6261. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6262. if (d != 255) {
  6263. dst[(*dst_len)++] = (c << 6) + d;
  6264. }
  6265. }
  6266. }
  6267. return -1;
  6268. }
  6269. #endif
  6270. static int
  6271. is_put_or_delete_method(const struct mg_connection *conn)
  6272. {
  6273. if (conn) {
  6274. const char *s = conn->request_info.request_method;
  6275. return (s != NULL)
  6276. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6277. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6278. }
  6279. return 0;
  6280. }
  6281. #if !defined(NO_FILES)
  6282. static int
  6283. extention_matches_script(
  6284. struct mg_connection *conn, /* in: request (must be valid) */
  6285. const char *filename /* in: filename (must be valid) */
  6286. )
  6287. {
  6288. #if !defined(NO_CGI)
  6289. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6290. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6291. filename)
  6292. > 0) {
  6293. return 1;
  6294. }
  6295. #endif
  6296. #if defined(USE_LUA)
  6297. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6298. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6299. filename)
  6300. > 0) {
  6301. return 1;
  6302. }
  6303. #endif
  6304. #if defined(USE_DUKTAPE)
  6305. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6306. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6307. filename)
  6308. > 0) {
  6309. return 1;
  6310. }
  6311. #endif
  6312. /* filename and conn could be unused, if all preocessor conditions
  6313. * are false (no script language supported). */
  6314. (void)filename;
  6315. (void)conn;
  6316. return 0;
  6317. }
  6318. /* For given directory path, substitute it to valid index file.
  6319. * Return 1 if index file has been found, 0 if not found.
  6320. * If the file is found, it's stats is returned in stp. */
  6321. static int
  6322. substitute_index_file(struct mg_connection *conn,
  6323. char *path,
  6324. size_t path_len,
  6325. struct mg_file_stat *filestat)
  6326. {
  6327. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6328. struct vec filename_vec;
  6329. size_t n = strlen(path);
  6330. int found = 0;
  6331. /* The 'path' given to us points to the directory. Remove all trailing
  6332. * directory separator characters from the end of the path, and
  6333. * then append single directory separator character. */
  6334. while ((n > 0) && (path[n - 1] == '/')) {
  6335. n--;
  6336. }
  6337. path[n] = '/';
  6338. /* Traverse index files list. For each entry, append it to the given
  6339. * path and see if the file exists. If it exists, break the loop */
  6340. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6341. /* Ignore too long entries that may overflow path buffer */
  6342. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6343. continue;
  6344. }
  6345. /* Prepare full path to the index file */
  6346. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6347. /* Does it exist? */
  6348. if (mg_stat(conn, path, filestat)) {
  6349. /* Yes it does, break the loop */
  6350. found = 1;
  6351. break;
  6352. }
  6353. }
  6354. /* If no index file exists, restore directory path */
  6355. if (!found) {
  6356. path[n] = '\0';
  6357. }
  6358. return found;
  6359. }
  6360. #endif
  6361. static void
  6362. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6363. char *filename, /* out: filename */
  6364. size_t filename_buf_len, /* in: size of filename buffer */
  6365. struct mg_file_stat *filestat, /* out: file status structure */
  6366. int *is_found, /* out: file found (directly) */
  6367. int *is_script_resource, /* out: handled by a script? */
  6368. int *is_websocket_request, /* out: websocket connetion? */
  6369. int *is_put_or_delete_request /* out: put/delete a file? */
  6370. )
  6371. {
  6372. char const *accept_encoding;
  6373. #if !defined(NO_FILES)
  6374. const char *uri = conn->request_info.local_uri;
  6375. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6376. const char *rewrite;
  6377. struct vec a, b;
  6378. ptrdiff_t match_len;
  6379. char gz_path[PATH_MAX];
  6380. int truncated;
  6381. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6382. char *tmp_str;
  6383. size_t tmp_str_len, sep_pos;
  6384. int allow_substitute_script_subresources;
  6385. #endif
  6386. #else
  6387. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6388. #endif
  6389. /* Step 1: Set all initially unknown outputs to zero */
  6390. memset(filestat, 0, sizeof(*filestat));
  6391. *filename = 0;
  6392. *is_found = 0;
  6393. *is_script_resource = 0;
  6394. /* Step 2: Check if the request attempts to modify the file system */
  6395. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6396. /* Step 3: Check if it is a websocket request, and modify the document
  6397. * root if required */
  6398. #if defined(USE_WEBSOCKET)
  6399. *is_websocket_request = is_websocket_protocol(conn);
  6400. #if !defined(NO_FILES)
  6401. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6402. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6403. }
  6404. #endif /* !NO_FILES */
  6405. #else /* USE_WEBSOCKET */
  6406. *is_websocket_request = 0;
  6407. #endif /* USE_WEBSOCKET */
  6408. /* Step 4: Check if gzip encoded response is allowed */
  6409. conn->accept_gzip = 0;
  6410. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6411. if (strstr(accept_encoding, "gzip") != NULL) {
  6412. conn->accept_gzip = 1;
  6413. }
  6414. }
  6415. #if !defined(NO_FILES)
  6416. /* Step 5: If there is no root directory, don't look for files. */
  6417. /* Note that root == NULL is a regular use case here. This occurs,
  6418. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6419. * config is not required. */
  6420. if (root == NULL) {
  6421. /* all file related outputs have already been set to 0, just return
  6422. */
  6423. return;
  6424. }
  6425. /* Step 6: Determine the local file path from the root path and the
  6426. * request uri. */
  6427. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6428. * part of the path one byte on the right. */
  6429. mg_snprintf(
  6430. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6431. if (truncated) {
  6432. goto interpret_cleanup;
  6433. }
  6434. /* Step 7: URI rewriting */
  6435. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6436. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6437. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6438. mg_snprintf(conn,
  6439. &truncated,
  6440. filename,
  6441. filename_buf_len - 1,
  6442. "%.*s%s",
  6443. (int)b.len,
  6444. b.ptr,
  6445. uri + match_len);
  6446. break;
  6447. }
  6448. }
  6449. if (truncated) {
  6450. goto interpret_cleanup;
  6451. }
  6452. /* Step 8: Check if the file exists at the server */
  6453. /* Local file path and name, corresponding to requested URI
  6454. * is now stored in "filename" variable. */
  6455. if (mg_stat(conn, filename, filestat)) {
  6456. int uri_len = (int)strlen(uri);
  6457. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6458. /* 8.1: File exists. */
  6459. *is_found = 1;
  6460. /* 8.2: Check if it is a script type. */
  6461. if (extention_matches_script(conn, filename)) {
  6462. /* The request addresses a CGI resource, Lua script or
  6463. * server-side javascript.
  6464. * The URI corresponds to the script itself (like
  6465. * /path/script.cgi), and there is no additional resource
  6466. * path (like /path/script.cgi/something).
  6467. * Requests that modify (replace or delete) a resource, like
  6468. * PUT and DELETE requests, should replace/delete the script
  6469. * file.
  6470. * Requests that read or write from/to a resource, like GET and
  6471. * POST requests, should call the script and return the
  6472. * generated response. */
  6473. *is_script_resource = (!*is_put_or_delete_request);
  6474. }
  6475. /* 8.3: If the request target is a directory, there could be
  6476. * a substitute file (index.html, index.cgi, ...). */
  6477. if (filestat->is_directory && is_uri_end_slash) {
  6478. /* Use a local copy here, since substitute_index_file will
  6479. * change the content of the file status */
  6480. struct mg_file_stat tmp_filestat;
  6481. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6482. if (substitute_index_file(
  6483. conn, filename, filename_buf_len, &tmp_filestat)) {
  6484. /* Substitute file found. Copy stat to the output, then
  6485. * check if the file is a script file */
  6486. *filestat = tmp_filestat;
  6487. if (extention_matches_script(conn, filename)) {
  6488. /* Substitute file is a script file */
  6489. *is_script_resource = 1;
  6490. } else {
  6491. /* Substitute file is a regular file */
  6492. *is_script_resource = 0;
  6493. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6494. }
  6495. }
  6496. /* If there is no substitute file, the server could return
  6497. * a directory listing in a later step */
  6498. }
  6499. return;
  6500. }
  6501. /* Step 9: Check for zipped files: */
  6502. /* If we can't find the actual file, look for the file
  6503. * with the same name but a .gz extension. If we find it,
  6504. * use that and set the gzipped flag in the file struct
  6505. * to indicate that the response need to have the content-
  6506. * encoding: gzip header.
  6507. * We can only do this if the browser declares support. */
  6508. if (conn->accept_gzip) {
  6509. mg_snprintf(
  6510. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6511. if (truncated) {
  6512. goto interpret_cleanup;
  6513. }
  6514. if (mg_stat(conn, gz_path, filestat)) {
  6515. if (filestat) {
  6516. filestat->is_gzipped = 1;
  6517. *is_found = 1;
  6518. }
  6519. /* Currently gz files can not be scripts. */
  6520. return;
  6521. }
  6522. }
  6523. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6524. /* Step 10: Script resources may handle sub-resources */
  6525. /* Support PATH_INFO for CGI scripts. */
  6526. tmp_str_len = strlen(filename);
  6527. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6528. if (!tmp_str) {
  6529. /* Out of memory */
  6530. goto interpret_cleanup;
  6531. }
  6532. memcpy(tmp_str, filename, tmp_str_len + 1);
  6533. /* Check config, if index scripts may have sub-resources */
  6534. allow_substitute_script_subresources =
  6535. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6536. "yes");
  6537. sep_pos = tmp_str_len;
  6538. while (sep_pos > 0) {
  6539. sep_pos--;
  6540. if (tmp_str[sep_pos] == '/') {
  6541. int is_script = 0, does_exist = 0;
  6542. tmp_str[sep_pos] = 0;
  6543. if (tmp_str[0]) {
  6544. is_script = extention_matches_script(conn, tmp_str);
  6545. does_exist = mg_stat(conn, tmp_str, filestat);
  6546. }
  6547. if (does_exist && is_script) {
  6548. filename[sep_pos] = 0;
  6549. memmove(filename + sep_pos + 2,
  6550. filename + sep_pos + 1,
  6551. strlen(filename + sep_pos + 1) + 1);
  6552. conn->path_info = filename + sep_pos + 1;
  6553. filename[sep_pos + 1] = '/';
  6554. *is_script_resource = 1;
  6555. *is_found = 1;
  6556. break;
  6557. }
  6558. if (allow_substitute_script_subresources) {
  6559. if (substitute_index_file(
  6560. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6561. /* some intermediate directory has an index file */
  6562. if (extention_matches_script(conn, tmp_str)) {
  6563. char *tmp_str2;
  6564. DEBUG_TRACE("Substitute script %s serving path %s",
  6565. tmp_str,
  6566. filename);
  6567. /* this index file is a script */
  6568. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6569. conn->phys_ctx);
  6570. mg_snprintf(conn,
  6571. &truncated,
  6572. filename,
  6573. filename_buf_len,
  6574. "%s//%s",
  6575. tmp_str,
  6576. tmp_str2);
  6577. mg_free(tmp_str2);
  6578. if (truncated) {
  6579. mg_free(tmp_str);
  6580. goto interpret_cleanup;
  6581. }
  6582. sep_pos = strlen(tmp_str);
  6583. filename[sep_pos] = 0;
  6584. conn->path_info = filename + sep_pos + 1;
  6585. *is_script_resource = 1;
  6586. *is_found = 1;
  6587. break;
  6588. } else {
  6589. DEBUG_TRACE("Substitute file %s serving path %s",
  6590. tmp_str,
  6591. filename);
  6592. /* non-script files will not have sub-resources */
  6593. filename[sep_pos] = 0;
  6594. conn->path_info = 0;
  6595. *is_script_resource = 0;
  6596. *is_found = 0;
  6597. break;
  6598. }
  6599. }
  6600. }
  6601. tmp_str[sep_pos] = '/';
  6602. }
  6603. }
  6604. mg_free(tmp_str);
  6605. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6606. #endif /* !defined(NO_FILES) */
  6607. return;
  6608. #if !defined(NO_FILES)
  6609. /* Reset all outputs */
  6610. interpret_cleanup:
  6611. memset(filestat, 0, sizeof(*filestat));
  6612. *filename = 0;
  6613. *is_found = 0;
  6614. *is_script_resource = 0;
  6615. *is_websocket_request = 0;
  6616. *is_put_or_delete_request = 0;
  6617. #endif /* !defined(NO_FILES) */
  6618. }
  6619. /* Check whether full request is buffered. Return:
  6620. * -1 if request or response is malformed
  6621. * 0 if request or response is not yet fully buffered
  6622. * >0 actual request length, including last \r\n\r\n */
  6623. static int
  6624. get_http_header_len(const char *buf, int buflen)
  6625. {
  6626. int i;
  6627. for (i = 0; i < buflen; i++) {
  6628. /* Do an unsigned comparison in some conditions below */
  6629. const unsigned char c = (unsigned char)buf[i];
  6630. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6631. && !isprint(c)) {
  6632. /* abort scan as soon as one malformed character is found */
  6633. return -1;
  6634. }
  6635. if (i < buflen - 1) {
  6636. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6637. /* Two newline, no carriage return - not standard compliant,
  6638. * but
  6639. * it
  6640. * should be accepted */
  6641. return i + 2;
  6642. }
  6643. }
  6644. if (i < buflen - 3) {
  6645. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6646. && (buf[i + 3] == '\n')) {
  6647. /* Two \r\n - standard compliant */
  6648. return i + 4;
  6649. }
  6650. }
  6651. }
  6652. return 0;
  6653. }
  6654. #if !defined(NO_CACHING)
  6655. /* Convert month to the month number. Return -1 on error, or month number */
  6656. static int
  6657. get_month_index(const char *s)
  6658. {
  6659. size_t i;
  6660. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6661. if (!strcmp(s, month_names[i])) {
  6662. return (int)i;
  6663. }
  6664. }
  6665. return -1;
  6666. }
  6667. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6668. static time_t
  6669. parse_date_string(const char *datetime)
  6670. {
  6671. char month_str[32] = {0};
  6672. int second, minute, hour, day, month, year;
  6673. time_t result = (time_t)0;
  6674. struct tm tm;
  6675. if ((sscanf(datetime,
  6676. "%d/%3s/%d %d:%d:%d",
  6677. &day,
  6678. month_str,
  6679. &year,
  6680. &hour,
  6681. &minute,
  6682. &second)
  6683. == 6)
  6684. || (sscanf(datetime,
  6685. "%d %3s %d %d:%d:%d",
  6686. &day,
  6687. month_str,
  6688. &year,
  6689. &hour,
  6690. &minute,
  6691. &second)
  6692. == 6)
  6693. || (sscanf(datetime,
  6694. "%*3s, %d %3s %d %d:%d:%d",
  6695. &day,
  6696. month_str,
  6697. &year,
  6698. &hour,
  6699. &minute,
  6700. &second)
  6701. == 6)
  6702. || (sscanf(datetime,
  6703. "%d-%3s-%d %d:%d:%d",
  6704. &day,
  6705. month_str,
  6706. &year,
  6707. &hour,
  6708. &minute,
  6709. &second)
  6710. == 6)) {
  6711. month = get_month_index(month_str);
  6712. if ((month >= 0) && (year >= 1970)) {
  6713. memset(&tm, 0, sizeof(tm));
  6714. tm.tm_year = year - 1900;
  6715. tm.tm_mon = month;
  6716. tm.tm_mday = day;
  6717. tm.tm_hour = hour;
  6718. tm.tm_min = minute;
  6719. tm.tm_sec = second;
  6720. result = timegm(&tm);
  6721. }
  6722. }
  6723. return result;
  6724. }
  6725. #endif /* !NO_CACHING */
  6726. /* Pre-process URIs according to RFC + protect against directory disclosure
  6727. * attacks by removing '..', excessive '/' and '\' characters */
  6728. static void
  6729. remove_dot_segments(char *inout)
  6730. {
  6731. /* Windows backend protection
  6732. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash in
  6733. * URI by slash */
  6734. char *in_copy = mg_strdup(inout);
  6735. char *out_begin = inout;
  6736. char *out_end = inout;
  6737. char *in = in_copy;
  6738. int replaced;
  6739. while (*in) {
  6740. if (*in == '\\') {
  6741. *in = '/';
  6742. }
  6743. in++;
  6744. }
  6745. /* Algorithm "remove_dot_segments" from
  6746. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6747. /* Step 1:
  6748. * The input buffer is initialized.
  6749. * The output buffer is initialized to the empty string.
  6750. */
  6751. in = in_copy;
  6752. /* Step 2:
  6753. * While the input buffer is not empty, loop as follows:
  6754. */
  6755. while (*in) {
  6756. /* Step 2a:
  6757. * If the input buffer begins with a prefix of "../" or "./",
  6758. * then remove that prefix from the input buffer;
  6759. */
  6760. if (!strncmp(in, "../", 3)) {
  6761. in += 3;
  6762. } else if (!strncmp(in, "./", 2)) {
  6763. in += 2;
  6764. }
  6765. /* otherwise */
  6766. /* Step 2b:
  6767. * if the input buffer begins with a prefix of "/./" or "/.",
  6768. * where "." is a complete path segment, then replace that
  6769. * prefix with "/" in the input buffer;
  6770. */
  6771. else if (!strncmp(in, "/./", 3)) {
  6772. in += 2;
  6773. } else if (!strcmp(in, "/.")) {
  6774. in[1] = 0;
  6775. }
  6776. /* otherwise */
  6777. /* Step 2c:
  6778. * if the input buffer begins with a prefix of "/../" or "/..",
  6779. * where ".." is a complete path segment, then replace that
  6780. * prefix with "/" in the input buffer and remove the last
  6781. * segment and its preceding "/" (if any) from the output
  6782. * buffer;
  6783. */
  6784. else if (!strncmp(in, "/../", 4)) {
  6785. in += 3;
  6786. if (out_begin != out_end) {
  6787. /* remove last segment */
  6788. do {
  6789. out_end--;
  6790. *out_end = 0;
  6791. } while ((out_begin != out_end) && (*out_end != '/'));
  6792. }
  6793. } else if (!strcmp(in, "/..")) {
  6794. in[1] = 0;
  6795. if (out_begin != out_end) {
  6796. /* remove last segment */
  6797. do {
  6798. out_end--;
  6799. *out_end = 0;
  6800. } while ((out_begin != out_end) && (*out_end != '/'));
  6801. }
  6802. }
  6803. /* otherwise */
  6804. /* Step 2d:
  6805. * if the input buffer consists only of "." or "..", then remove
  6806. * that from the input buffer;
  6807. */
  6808. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6809. *in = 0;
  6810. }
  6811. /* otherwise */
  6812. /* Step 2e:
  6813. * move the first path segment in the input buffer to the end of
  6814. * the output buffer, including the initial "/" character (if
  6815. * any) and any subsequent characters up to, but not including,
  6816. * the next "/" character or the end of the input buffer.
  6817. */
  6818. else {
  6819. do {
  6820. *out_end = *in;
  6821. out_end++;
  6822. in++;
  6823. } while ((*in != 0) && (*in != '/'));
  6824. }
  6825. }
  6826. /* Step 3:
  6827. * Finally, the output buffer is returned as the result of
  6828. * remove_dot_segments.
  6829. */
  6830. /* Terminate output */
  6831. *out_end = 0;
  6832. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6833. * extension) are identical. Replace all "./" by "/" and remove a "." at the
  6834. * end.
  6835. * Also replace all "//" by "/".
  6836. * Repeat until there is no "./" or "//" anymore.
  6837. */
  6838. do {
  6839. replaced = 0;
  6840. /* replace ./ by / */
  6841. out_end = out_begin;
  6842. while (*out_end) {
  6843. if ((*out_end == '.')
  6844. && ((out_end[1] == '/') || (out_end[1] == 0))) {
  6845. char *r = out_end;
  6846. do {
  6847. r[0] = r[1];
  6848. r++;
  6849. replaced = 1;
  6850. } while (r[0] != 0);
  6851. }
  6852. out_end++;
  6853. }
  6854. /* replace ./ by / */
  6855. out_end = out_begin;
  6856. while (*out_end) {
  6857. if ((out_end[0] == '/') && (out_end[1] == '/')) {
  6858. char *c = out_end;
  6859. while (*c) {
  6860. c[0] = c[1];
  6861. c++;
  6862. }
  6863. replaced = 1;
  6864. }
  6865. out_end++;
  6866. }
  6867. } while (replaced);
  6868. /* Free temporary copies */
  6869. mg_free(in_copy);
  6870. }
  6871. static const struct {
  6872. const char *extension;
  6873. size_t ext_len;
  6874. const char *mime_type;
  6875. } builtin_mime_types[] = {
  6876. /* IANA registered MIME types
  6877. * (http://www.iana.org/assignments/media-types)
  6878. * application types */
  6879. {".doc", 4, "application/msword"},
  6880. {".eps", 4, "application/postscript"},
  6881. {".exe", 4, "application/octet-stream"},
  6882. {".js", 3, "application/javascript"},
  6883. {".json", 5, "application/json"},
  6884. {".pdf", 4, "application/pdf"},
  6885. {".ps", 3, "application/postscript"},
  6886. {".rtf", 4, "application/rtf"},
  6887. {".xhtml", 6, "application/xhtml+xml"},
  6888. {".xsl", 4, "application/xml"},
  6889. {".xslt", 5, "application/xml"},
  6890. /* fonts */
  6891. {".ttf", 4, "application/font-sfnt"},
  6892. {".cff", 4, "application/font-sfnt"},
  6893. {".otf", 4, "application/font-sfnt"},
  6894. {".aat", 4, "application/font-sfnt"},
  6895. {".sil", 4, "application/font-sfnt"},
  6896. {".pfr", 4, "application/font-tdpfr"},
  6897. {".woff", 5, "application/font-woff"},
  6898. /* audio */
  6899. {".mp3", 4, "audio/mpeg"},
  6900. {".oga", 4, "audio/ogg"},
  6901. {".ogg", 4, "audio/ogg"},
  6902. /* image */
  6903. {".gif", 4, "image/gif"},
  6904. {".ief", 4, "image/ief"},
  6905. {".jpeg", 5, "image/jpeg"},
  6906. {".jpg", 4, "image/jpeg"},
  6907. {".jpm", 4, "image/jpm"},
  6908. {".jpx", 4, "image/jpx"},
  6909. {".png", 4, "image/png"},
  6910. {".svg", 4, "image/svg+xml"},
  6911. {".tif", 4, "image/tiff"},
  6912. {".tiff", 5, "image/tiff"},
  6913. /* model */
  6914. {".wrl", 4, "model/vrml"},
  6915. /* text */
  6916. {".css", 4, "text/css"},
  6917. {".csv", 4, "text/csv"},
  6918. {".htm", 4, "text/html"},
  6919. {".html", 5, "text/html"},
  6920. {".sgm", 4, "text/sgml"},
  6921. {".shtm", 5, "text/html"},
  6922. {".shtml", 6, "text/html"},
  6923. {".txt", 4, "text/plain"},
  6924. {".xml", 4, "text/xml"},
  6925. /* video */
  6926. {".mov", 4, "video/quicktime"},
  6927. {".mp4", 4, "video/mp4"},
  6928. {".mpeg", 5, "video/mpeg"},
  6929. {".mpg", 4, "video/mpeg"},
  6930. {".ogv", 4, "video/ogg"},
  6931. {".qt", 3, "video/quicktime"},
  6932. /* not registered types
  6933. * (http://reference.sitepoint.com/html/mime-types-full,
  6934. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6935. {".arj", 4, "application/x-arj-compressed"},
  6936. {".gz", 3, "application/x-gunzip"},
  6937. {".rar", 4, "application/x-arj-compressed"},
  6938. {".swf", 4, "application/x-shockwave-flash"},
  6939. {".tar", 4, "application/x-tar"},
  6940. {".tgz", 4, "application/x-tar-gz"},
  6941. {".torrent", 8, "application/x-bittorrent"},
  6942. {".ppt", 4, "application/x-mspowerpoint"},
  6943. {".xls", 4, "application/x-msexcel"},
  6944. {".zip", 4, "application/x-zip-compressed"},
  6945. {".aac",
  6946. 4,
  6947. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6948. {".aif", 4, "audio/x-aif"},
  6949. {".m3u", 4, "audio/x-mpegurl"},
  6950. {".mid", 4, "audio/x-midi"},
  6951. {".ra", 3, "audio/x-pn-realaudio"},
  6952. {".ram", 4, "audio/x-pn-realaudio"},
  6953. {".wav", 4, "audio/x-wav"},
  6954. {".bmp", 4, "image/bmp"},
  6955. {".ico", 4, "image/x-icon"},
  6956. {".pct", 4, "image/x-pct"},
  6957. {".pict", 5, "image/pict"},
  6958. {".rgb", 4, "image/x-rgb"},
  6959. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6960. {".asf", 4, "video/x-ms-asf"},
  6961. {".avi", 4, "video/x-msvideo"},
  6962. {".m4v", 4, "video/x-m4v"},
  6963. {NULL, 0, NULL}};
  6964. const char *
  6965. mg_get_builtin_mime_type(const char *path)
  6966. {
  6967. const char *ext;
  6968. size_t i, path_len;
  6969. path_len = strlen(path);
  6970. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6971. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6972. if ((path_len > builtin_mime_types[i].ext_len)
  6973. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6974. return builtin_mime_types[i].mime_type;
  6975. }
  6976. }
  6977. return "text/plain";
  6978. }
  6979. /* Look at the "path" extension and figure what mime type it has.
  6980. * Store mime type in the vector. */
  6981. static void
  6982. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6983. {
  6984. struct vec ext_vec, mime_vec;
  6985. const char *list, *ext;
  6986. size_t path_len;
  6987. path_len = strlen(path);
  6988. if ((conn == NULL) || (vec == NULL)) {
  6989. if (vec != NULL) {
  6990. memset(vec, '\0', sizeof(struct vec));
  6991. }
  6992. return;
  6993. }
  6994. /* Scan user-defined mime types first, in case user wants to
  6995. * override default mime types. */
  6996. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6997. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6998. /* ext now points to the path suffix */
  6999. ext = path + path_len - ext_vec.len;
  7000. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7001. *vec = mime_vec;
  7002. return;
  7003. }
  7004. }
  7005. vec->ptr = mg_get_builtin_mime_type(path);
  7006. vec->len = strlen(vec->ptr);
  7007. }
  7008. /* Stringify binary data. Output buffer must be twice as big as input,
  7009. * because each byte takes 2 bytes in string representation */
  7010. static void
  7011. bin2str(char *to, const unsigned char *p, size_t len)
  7012. {
  7013. static const char *hex = "0123456789abcdef";
  7014. for (; len--; p++) {
  7015. *to++ = hex[p[0] >> 4];
  7016. *to++ = hex[p[0] & 0x0f];
  7017. }
  7018. *to = '\0';
  7019. }
  7020. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7021. */
  7022. char *
  7023. mg_md5(char buf[33], ...)
  7024. {
  7025. md5_byte_t hash[16];
  7026. const char *p;
  7027. va_list ap;
  7028. md5_state_t ctx;
  7029. md5_init(&ctx);
  7030. va_start(ap, buf);
  7031. while ((p = va_arg(ap, const char *)) != NULL) {
  7032. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7033. }
  7034. va_end(ap);
  7035. md5_finish(&ctx, hash);
  7036. bin2str(buf, hash, sizeof(hash));
  7037. return buf;
  7038. }
  7039. /* Check the user's password, return 1 if OK */
  7040. static int
  7041. check_password(const char *method,
  7042. const char *ha1,
  7043. const char *uri,
  7044. const char *nonce,
  7045. const char *nc,
  7046. const char *cnonce,
  7047. const char *qop,
  7048. const char *response)
  7049. {
  7050. char ha2[32 + 1], expected_response[32 + 1];
  7051. /* Some of the parameters may be NULL */
  7052. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7053. || (qop == NULL) || (response == NULL)) {
  7054. return 0;
  7055. }
  7056. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7057. if (strlen(response) != 32) {
  7058. return 0;
  7059. }
  7060. mg_md5(ha2, method, ":", uri, NULL);
  7061. mg_md5(expected_response,
  7062. ha1,
  7063. ":",
  7064. nonce,
  7065. ":",
  7066. nc,
  7067. ":",
  7068. cnonce,
  7069. ":",
  7070. qop,
  7071. ":",
  7072. ha2,
  7073. NULL);
  7074. return mg_strcasecmp(response, expected_response) == 0;
  7075. }
  7076. #if !defined(NO_FILESYSTEMS)
  7077. /* Use the global passwords file, if specified by auth_gpass option,
  7078. * or search for .htpasswd in the requested directory. */
  7079. static void
  7080. open_auth_file(struct mg_connection *conn,
  7081. const char *path,
  7082. struct mg_file *filep)
  7083. {
  7084. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7085. char name[PATH_MAX];
  7086. const char *p, *e,
  7087. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7088. int truncated;
  7089. if (gpass != NULL) {
  7090. /* Use global passwords file */
  7091. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7092. #if defined(DEBUG)
  7093. /* Use mg_cry_internal here, since gpass has been configured. */
  7094. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7095. #endif
  7096. }
  7097. /* Important: using local struct mg_file to test path for
  7098. * is_directory flag. If filep is used, mg_stat() makes it
  7099. * appear as if auth file was opened.
  7100. * TODO(mid): Check if this is still required after rewriting
  7101. * mg_stat */
  7102. } else if (mg_stat(conn, path, &filep->stat)
  7103. && filep->stat.is_directory) {
  7104. mg_snprintf(conn,
  7105. &truncated,
  7106. name,
  7107. sizeof(name),
  7108. "%s/%s",
  7109. path,
  7110. PASSWORDS_FILE_NAME);
  7111. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7112. #if defined(DEBUG)
  7113. /* Don't use mg_cry_internal here, but only a trace, since this
  7114. * is
  7115. * a typical case. It will occur for every directory
  7116. * without a password file. */
  7117. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7118. #endif
  7119. }
  7120. } else {
  7121. /* Try to find .htpasswd in requested directory. */
  7122. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7123. if (e[0] == '/') {
  7124. break;
  7125. }
  7126. }
  7127. mg_snprintf(conn,
  7128. &truncated,
  7129. name,
  7130. sizeof(name),
  7131. "%.*s/%s",
  7132. (int)(e - p),
  7133. p,
  7134. PASSWORDS_FILE_NAME);
  7135. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7136. #if defined(DEBUG)
  7137. /* Don't use mg_cry_internal here, but only a trace, since this
  7138. * is
  7139. * a typical case. It will occur for every directory
  7140. * without a password file. */
  7141. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7142. #endif
  7143. }
  7144. }
  7145. }
  7146. }
  7147. #endif /* NO_FILESYSTEMS */
  7148. /* Parsed Authorization header */
  7149. struct ah {
  7150. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7151. };
  7152. /* Return 1 on success. Always initializes the ah structure. */
  7153. static int
  7154. parse_auth_header(struct mg_connection *conn,
  7155. char *buf,
  7156. size_t buf_size,
  7157. struct ah *ah)
  7158. {
  7159. char *name, *value, *s;
  7160. const char *auth_header;
  7161. uint64_t nonce;
  7162. if (!ah || !conn) {
  7163. return 0;
  7164. }
  7165. (void)memset(ah, 0, sizeof(*ah));
  7166. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7167. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7168. return 0;
  7169. }
  7170. /* Make modifiable copy of the auth header */
  7171. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7172. s = buf;
  7173. /* Parse authorization header */
  7174. for (;;) {
  7175. /* Gobble initial spaces */
  7176. while (isspace((unsigned char)*s)) {
  7177. s++;
  7178. }
  7179. name = skip_quoted(&s, "=", " ", 0);
  7180. /* Value is either quote-delimited, or ends at first comma or space.
  7181. */
  7182. if (s[0] == '\"') {
  7183. s++;
  7184. value = skip_quoted(&s, "\"", " ", '\\');
  7185. if (s[0] == ',') {
  7186. s++;
  7187. }
  7188. } else {
  7189. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  7190. * spaces */
  7191. }
  7192. if (*name == '\0') {
  7193. break;
  7194. }
  7195. if (!strcmp(name, "username")) {
  7196. ah->user = value;
  7197. } else if (!strcmp(name, "cnonce")) {
  7198. ah->cnonce = value;
  7199. } else if (!strcmp(name, "response")) {
  7200. ah->response = value;
  7201. } else if (!strcmp(name, "uri")) {
  7202. ah->uri = value;
  7203. } else if (!strcmp(name, "qop")) {
  7204. ah->qop = value;
  7205. } else if (!strcmp(name, "nc")) {
  7206. ah->nc = value;
  7207. } else if (!strcmp(name, "nonce")) {
  7208. ah->nonce = value;
  7209. }
  7210. }
  7211. #if !defined(NO_NONCE_CHECK)
  7212. /* Read the nonce from the response. */
  7213. if (ah->nonce == NULL) {
  7214. return 0;
  7215. }
  7216. s = NULL;
  7217. nonce = strtoull(ah->nonce, &s, 10);
  7218. if ((s == NULL) || (*s != 0)) {
  7219. return 0;
  7220. }
  7221. /* Convert the nonce from the client to a number. */
  7222. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7223. /* The converted number corresponds to the time the nounce has been
  7224. * created. This should not be earlier than the server start. */
  7225. /* Server side nonce check is valuable in all situations but one:
  7226. * if the server restarts frequently, but the client should not see
  7227. * that, so the server should accept nonces from previous starts. */
  7228. /* However, the reasonable default is to not accept a nonce from a
  7229. * previous start, so if anyone changed the access rights between
  7230. * two restarts, a new login is required. */
  7231. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7232. /* nonce is from a previous start of the server and no longer valid
  7233. * (replay attack?) */
  7234. return 0;
  7235. }
  7236. /* Check if the nonce is too high, so it has not (yet) been used by the
  7237. * server. */
  7238. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7239. + conn->dom_ctx->nonce_count)) {
  7240. return 0;
  7241. }
  7242. #else
  7243. (void)nonce;
  7244. #endif
  7245. /* CGI needs it as REMOTE_USER */
  7246. if (ah->user != NULL) {
  7247. conn->request_info.remote_user =
  7248. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7249. } else {
  7250. return 0;
  7251. }
  7252. return 1;
  7253. }
  7254. static const char *
  7255. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7256. {
  7257. #if defined(MG_USE_OPEN_FILE)
  7258. const char *eof;
  7259. size_t len;
  7260. const char *memend;
  7261. #else
  7262. (void)p; /* parameter is unused */
  7263. #endif
  7264. if (!filep) {
  7265. return NULL;
  7266. }
  7267. #if defined(MG_USE_OPEN_FILE)
  7268. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7269. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7270. /* Search for \n from p till the end of stream */
  7271. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7272. if (eof != NULL) {
  7273. eof += 1; /* Include \n */
  7274. } else {
  7275. eof = memend; /* Copy remaining data */
  7276. }
  7277. len =
  7278. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7279. memcpy(buf, *p, len);
  7280. buf[len] = '\0';
  7281. *p += len;
  7282. return len ? eof : NULL;
  7283. } else /* filep->access.fp block below */
  7284. #endif
  7285. if (filep->access.fp != NULL) {
  7286. return fgets(buf, (int)size, filep->access.fp);
  7287. } else {
  7288. return NULL;
  7289. }
  7290. }
  7291. /* Define the initial recursion depth for procesesing htpasswd files that
  7292. * include other htpasswd
  7293. * (or even the same) files. It is not difficult to provide a file or files
  7294. * s.t. they force civetweb
  7295. * to infinitely recurse and then crash.
  7296. */
  7297. #define INITIAL_DEPTH 9
  7298. #if INITIAL_DEPTH <= 0
  7299. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7300. #endif
  7301. #if !defined(NO_FILESYSTEMS)
  7302. struct read_auth_file_struct {
  7303. struct mg_connection *conn;
  7304. struct ah ah;
  7305. const char *domain;
  7306. char buf[256 + 256 + 40];
  7307. const char *f_user;
  7308. const char *f_domain;
  7309. const char *f_ha1;
  7310. };
  7311. static int
  7312. read_auth_file(struct mg_file *filep,
  7313. struct read_auth_file_struct *workdata,
  7314. int depth)
  7315. {
  7316. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7317. int is_authorized = 0;
  7318. struct mg_file fp;
  7319. size_t l;
  7320. if (!filep || !workdata || (0 == depth)) {
  7321. return 0;
  7322. }
  7323. /* Loop over passwords file */
  7324. #if defined(MG_USE_OPEN_FILE)
  7325. p = (char *)filep->access.membuf;
  7326. #endif
  7327. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7328. l = strlen(workdata->buf);
  7329. while (l > 0) {
  7330. if (isspace((unsigned char)workdata->buf[l - 1])
  7331. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7332. l--;
  7333. workdata->buf[l] = 0;
  7334. } else
  7335. break;
  7336. }
  7337. if (l < 1) {
  7338. continue;
  7339. }
  7340. workdata->f_user = workdata->buf;
  7341. if (workdata->f_user[0] == ':') {
  7342. /* user names may not contain a ':' and may not be empty,
  7343. * so lines starting with ':' may be used for a special purpose
  7344. */
  7345. if (workdata->f_user[1] == '#') {
  7346. /* :# is a comment */
  7347. continue;
  7348. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7349. if (mg_fopen(workdata->conn,
  7350. workdata->f_user + 9,
  7351. MG_FOPEN_MODE_READ,
  7352. &fp)) {
  7353. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7354. (void)mg_fclose(
  7355. &fp.access); /* ignore error on read only file */
  7356. /* No need to continue processing files once we have a
  7357. * match, since nothing will reset it back
  7358. * to 0.
  7359. */
  7360. if (is_authorized) {
  7361. return is_authorized;
  7362. }
  7363. } else {
  7364. mg_cry_internal(workdata->conn,
  7365. "%s: cannot open authorization file: %s",
  7366. __func__,
  7367. workdata->buf);
  7368. }
  7369. continue;
  7370. }
  7371. /* everything is invalid for the moment (might change in the
  7372. * future) */
  7373. mg_cry_internal(workdata->conn,
  7374. "%s: syntax error in authorization file: %s",
  7375. __func__,
  7376. workdata->buf);
  7377. continue;
  7378. }
  7379. workdata->f_domain = strchr(workdata->f_user, ':');
  7380. if (workdata->f_domain == NULL) {
  7381. mg_cry_internal(workdata->conn,
  7382. "%s: syntax error in authorization file: %s",
  7383. __func__,
  7384. workdata->buf);
  7385. continue;
  7386. }
  7387. *(char *)(workdata->f_domain) = 0;
  7388. (workdata->f_domain)++;
  7389. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7390. if (workdata->f_ha1 == NULL) {
  7391. mg_cry_internal(workdata->conn,
  7392. "%s: syntax error in authorization file: %s",
  7393. __func__,
  7394. workdata->buf);
  7395. continue;
  7396. }
  7397. *(char *)(workdata->f_ha1) = 0;
  7398. (workdata->f_ha1)++;
  7399. if (!strcmp(workdata->ah.user, workdata->f_user)
  7400. && !strcmp(workdata->domain, workdata->f_domain)) {
  7401. return check_password(workdata->conn->request_info.request_method,
  7402. workdata->f_ha1,
  7403. workdata->ah.uri,
  7404. workdata->ah.nonce,
  7405. workdata->ah.nc,
  7406. workdata->ah.cnonce,
  7407. workdata->ah.qop,
  7408. workdata->ah.response);
  7409. }
  7410. }
  7411. return is_authorized;
  7412. }
  7413. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7414. static int
  7415. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7416. {
  7417. struct read_auth_file_struct workdata;
  7418. char buf[MG_BUF_LEN];
  7419. if (!conn || !conn->dom_ctx) {
  7420. return 0;
  7421. }
  7422. memset(&workdata, 0, sizeof(workdata));
  7423. workdata.conn = conn;
  7424. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7425. return 0;
  7426. }
  7427. if (realm) {
  7428. workdata.domain = realm;
  7429. } else {
  7430. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7431. }
  7432. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7433. }
  7434. /* Public function to check http digest authentication header */
  7435. int
  7436. mg_check_digest_access_authentication(struct mg_connection *conn,
  7437. const char *realm,
  7438. const char *filename)
  7439. {
  7440. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7441. int auth;
  7442. if (!conn || !filename) {
  7443. return -1;
  7444. }
  7445. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7446. return -2;
  7447. }
  7448. auth = authorize(conn, &file, realm);
  7449. mg_fclose(&file.access);
  7450. return auth;
  7451. }
  7452. #endif /* NO_FILESYSTEMS */
  7453. /* Return 1 if request is authorised, 0 otherwise. */
  7454. static int
  7455. check_authorization(struct mg_connection *conn, const char *path)
  7456. {
  7457. #if !defined(NO_FILESYSTEMS)
  7458. char fname[PATH_MAX];
  7459. struct vec uri_vec, filename_vec;
  7460. const char *list;
  7461. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7462. int authorized = 1, truncated;
  7463. if (!conn || !conn->dom_ctx) {
  7464. return 0;
  7465. }
  7466. list = conn->dom_ctx->config[PROTECT_URI];
  7467. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7468. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7469. mg_snprintf(conn,
  7470. &truncated,
  7471. fname,
  7472. sizeof(fname),
  7473. "%.*s",
  7474. (int)filename_vec.len,
  7475. filename_vec.ptr);
  7476. if (truncated
  7477. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7478. mg_cry_internal(conn,
  7479. "%s: cannot open %s: %s",
  7480. __func__,
  7481. fname,
  7482. strerror(errno));
  7483. }
  7484. break;
  7485. }
  7486. }
  7487. if (!is_file_opened(&file.access)) {
  7488. open_auth_file(conn, path, &file);
  7489. }
  7490. if (is_file_opened(&file.access)) {
  7491. authorized = authorize(conn, &file, NULL);
  7492. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7493. }
  7494. return authorized;
  7495. #else
  7496. (void)conn;
  7497. (void)path;
  7498. return 1;
  7499. #endif /* NO_FILESYSTEMS */
  7500. }
  7501. /* Internal function. Assumes conn is valid */
  7502. static void
  7503. send_authorization_request(struct mg_connection *conn, const char *realm)
  7504. {
  7505. char date[64];
  7506. time_t curtime = time(NULL);
  7507. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7508. if (!realm) {
  7509. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7510. }
  7511. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7512. nonce += conn->dom_ctx->nonce_count;
  7513. ++conn->dom_ctx->nonce_count;
  7514. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7515. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7516. conn->status_code = 401;
  7517. conn->must_close = 1;
  7518. gmt_time_string(date, sizeof(date), &curtime);
  7519. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7520. send_no_cache_header(conn);
  7521. send_additional_header(conn);
  7522. mg_printf(conn,
  7523. "Date: %s\r\n"
  7524. "Connection: %s\r\n"
  7525. "Content-Length: 0\r\n"
  7526. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7527. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7528. date,
  7529. suggest_connection_header(conn),
  7530. realm,
  7531. nonce);
  7532. }
  7533. /* Interface function. Parameters are provided by the user, so do
  7534. * at least some basic checks.
  7535. */
  7536. int
  7537. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7538. const char *realm)
  7539. {
  7540. if (conn && conn->dom_ctx) {
  7541. send_authorization_request(conn, realm);
  7542. return 0;
  7543. }
  7544. return -1;
  7545. }
  7546. #if !defined(NO_FILES)
  7547. static int
  7548. is_authorized_for_put(struct mg_connection *conn)
  7549. {
  7550. if (conn) {
  7551. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7552. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7553. int ret = 0;
  7554. if (passfile != NULL
  7555. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7556. ret = authorize(conn, &file, NULL);
  7557. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7558. }
  7559. return ret;
  7560. }
  7561. return 0;
  7562. }
  7563. #endif
  7564. int
  7565. mg_modify_passwords_file(const char *fname,
  7566. const char *domain,
  7567. const char *user,
  7568. const char *pass)
  7569. {
  7570. int found, i;
  7571. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7572. FILE *fp, *fp2;
  7573. found = 0;
  7574. fp = fp2 = NULL;
  7575. /* Regard empty password as no password - remove user record. */
  7576. if ((pass != NULL) && (pass[0] == '\0')) {
  7577. pass = NULL;
  7578. }
  7579. /* Other arguments must not be empty */
  7580. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7581. return 0;
  7582. }
  7583. /* Using the given file format, user name and domain must not contain
  7584. * ':'
  7585. */
  7586. if (strchr(user, ':') != NULL) {
  7587. return 0;
  7588. }
  7589. if (strchr(domain, ':') != NULL) {
  7590. return 0;
  7591. }
  7592. /* Do not allow control characters like newline in user name and domain.
  7593. * Do not allow excessively long names either. */
  7594. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7595. if (iscntrl((unsigned char)user[i])) {
  7596. return 0;
  7597. }
  7598. }
  7599. if (user[i]) {
  7600. return 0;
  7601. }
  7602. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7603. if (iscntrl((unsigned char)domain[i])) {
  7604. return 0;
  7605. }
  7606. }
  7607. if (domain[i]) {
  7608. return 0;
  7609. }
  7610. /* The maximum length of the path to the password file is limited */
  7611. if ((strlen(fname) + 4) >= PATH_MAX) {
  7612. return 0;
  7613. }
  7614. /* Create a temporary file name. Length has been checked before. */
  7615. strcpy(tmp, fname);
  7616. strcat(tmp, ".tmp");
  7617. /* Create the file if does not exist */
  7618. /* Use of fopen here is OK, since fname is only ASCII */
  7619. if ((fp = fopen(fname, "a+")) != NULL) {
  7620. (void)fclose(fp);
  7621. }
  7622. /* Open the given file and temporary file */
  7623. if ((fp = fopen(fname, "r")) == NULL) {
  7624. return 0;
  7625. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7626. fclose(fp);
  7627. return 0;
  7628. }
  7629. /* Copy the stuff to temporary file */
  7630. while (fgets(line, sizeof(line), fp) != NULL) {
  7631. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7632. continue;
  7633. }
  7634. u[255] = 0;
  7635. d[255] = 0;
  7636. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7637. found++;
  7638. if (pass != NULL) {
  7639. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7640. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7641. }
  7642. } else {
  7643. fprintf(fp2, "%s", line);
  7644. }
  7645. }
  7646. /* If new user, just add it */
  7647. if (!found && (pass != NULL)) {
  7648. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7649. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7650. }
  7651. /* Close files */
  7652. fclose(fp);
  7653. fclose(fp2);
  7654. /* Put the temp file in place of real file */
  7655. IGNORE_UNUSED_RESULT(remove(fname));
  7656. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7657. return 1;
  7658. }
  7659. static int
  7660. is_valid_port(unsigned long port)
  7661. {
  7662. return (port <= 0xffff);
  7663. }
  7664. static int
  7665. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7666. {
  7667. struct addrinfo hints, *res, *ressave;
  7668. int func_ret = 0;
  7669. int gai_ret;
  7670. memset(&hints, 0, sizeof(struct addrinfo));
  7671. hints.ai_family = af;
  7672. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7673. if (gai_ret != 0) {
  7674. /* gai_strerror could be used to convert gai_ret to a string */
  7675. /* POSIX return values: see
  7676. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7677. */
  7678. /* Windows return values: see
  7679. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7680. */
  7681. return 0;
  7682. }
  7683. ressave = res;
  7684. while (res) {
  7685. if (dstlen >= (size_t)res->ai_addrlen) {
  7686. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7687. func_ret = 1;
  7688. }
  7689. res = res->ai_next;
  7690. }
  7691. freeaddrinfo(ressave);
  7692. return func_ret;
  7693. }
  7694. static int
  7695. connect_socket(struct mg_context *ctx /* may be NULL */,
  7696. const char *host,
  7697. int port,
  7698. int use_ssl,
  7699. char *ebuf,
  7700. size_t ebuf_len,
  7701. SOCKET *sock /* output: socket, must not be NULL */,
  7702. union usa *sa /* output: socket address, must not be NULL */
  7703. )
  7704. {
  7705. int ip_ver = 0;
  7706. int conn_ret = -1;
  7707. int sockerr = 0;
  7708. *sock = INVALID_SOCKET;
  7709. memset(sa, 0, sizeof(*sa));
  7710. if (ebuf_len > 0) {
  7711. *ebuf = 0;
  7712. }
  7713. if (host == NULL) {
  7714. mg_snprintf(NULL,
  7715. NULL, /* No truncation check for ebuf */
  7716. ebuf,
  7717. ebuf_len,
  7718. "%s",
  7719. "NULL host");
  7720. return 0;
  7721. }
  7722. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7723. mg_snprintf(NULL,
  7724. NULL, /* No truncation check for ebuf */
  7725. ebuf,
  7726. ebuf_len,
  7727. "%s",
  7728. "invalid port");
  7729. return 0;
  7730. }
  7731. #if !defined(NO_SSL)
  7732. #if !defined(NO_SSL_DL)
  7733. #if defined(OPENSSL_API_1_1)
  7734. if (use_ssl && (TLS_client_method == NULL)) {
  7735. mg_snprintf(NULL,
  7736. NULL, /* No truncation check for ebuf */
  7737. ebuf,
  7738. ebuf_len,
  7739. "%s",
  7740. "SSL is not initialized");
  7741. return 0;
  7742. }
  7743. #else
  7744. if (use_ssl && (SSLv23_client_method == NULL)) {
  7745. mg_snprintf(NULL,
  7746. NULL, /* No truncation check for ebuf */
  7747. ebuf,
  7748. ebuf_len,
  7749. "%s",
  7750. "SSL is not initialized");
  7751. return 0;
  7752. }
  7753. #endif /* OPENSSL_API_1_1 */
  7754. #else
  7755. (void)use_ssl;
  7756. #endif /* NO_SSL_DL */
  7757. #else
  7758. (void)use_ssl;
  7759. #endif /* !defined(NO_SSL) */
  7760. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7761. sa->sin.sin_family = AF_INET;
  7762. sa->sin.sin_port = htons((uint16_t)port);
  7763. ip_ver = 4;
  7764. #if defined(USE_IPV6)
  7765. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7766. sa->sin6.sin6_family = AF_INET6;
  7767. sa->sin6.sin6_port = htons((uint16_t)port);
  7768. ip_ver = 6;
  7769. } else if (host[0] == '[') {
  7770. /* While getaddrinfo on Windows will work with [::1],
  7771. * getaddrinfo on Linux only works with ::1 (without []). */
  7772. size_t l = strlen(host + 1);
  7773. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7774. if (h) {
  7775. h[l - 1] = 0;
  7776. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7777. sa->sin6.sin6_family = AF_INET6;
  7778. sa->sin6.sin6_port = htons((uint16_t)port);
  7779. ip_ver = 6;
  7780. }
  7781. mg_free(h);
  7782. }
  7783. #endif
  7784. }
  7785. if (ip_ver == 0) {
  7786. mg_snprintf(NULL,
  7787. NULL, /* No truncation check for ebuf */
  7788. ebuf,
  7789. ebuf_len,
  7790. "%s",
  7791. "host not found");
  7792. return 0;
  7793. }
  7794. if (ip_ver == 4) {
  7795. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7796. }
  7797. #if defined(USE_IPV6)
  7798. else if (ip_ver == 6) {
  7799. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7800. }
  7801. #endif
  7802. if (*sock == INVALID_SOCKET) {
  7803. mg_snprintf(NULL,
  7804. NULL, /* No truncation check for ebuf */
  7805. ebuf,
  7806. ebuf_len,
  7807. "socket(): %s",
  7808. strerror(ERRNO));
  7809. return 0;
  7810. }
  7811. if (0 != set_non_blocking_mode(*sock)) {
  7812. mg_snprintf(NULL,
  7813. NULL, /* No truncation check for ebuf */
  7814. ebuf,
  7815. ebuf_len,
  7816. "Cannot set socket to non-blocking: %s",
  7817. strerror(ERRNO));
  7818. closesocket(*sock);
  7819. *sock = INVALID_SOCKET;
  7820. return 0;
  7821. }
  7822. set_close_on_exec(*sock, NULL, ctx);
  7823. if (ip_ver == 4) {
  7824. /* connected with IPv4 */
  7825. conn_ret = connect(*sock,
  7826. (struct sockaddr *)((void *)&sa->sin),
  7827. sizeof(sa->sin));
  7828. }
  7829. #if defined(USE_IPV6)
  7830. else if (ip_ver == 6) {
  7831. /* connected with IPv6 */
  7832. conn_ret = connect(*sock,
  7833. (struct sockaddr *)((void *)&sa->sin6),
  7834. sizeof(sa->sin6));
  7835. }
  7836. #endif
  7837. if (conn_ret != 0) {
  7838. sockerr = ERRNO;
  7839. }
  7840. #if defined(_WIN32)
  7841. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7842. #else
  7843. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7844. #endif
  7845. /* Data for getsockopt */
  7846. void *psockerr = &sockerr;
  7847. int ret;
  7848. #if defined(_WIN32)
  7849. int len = (int)sizeof(sockerr);
  7850. #else
  7851. socklen_t len = (socklen_t)sizeof(sockerr);
  7852. #endif
  7853. /* Data for poll */
  7854. struct mg_pollfd pfd[1];
  7855. int pollres;
  7856. int ms_wait = 10000; /* 10 second timeout */
  7857. int nonstop = 0;
  7858. /* For a non-blocking socket, the connect sequence is:
  7859. * 1) call connect (will not block)
  7860. * 2) wait until the socket is ready for writing (select or poll)
  7861. * 3) check connection state with getsockopt
  7862. */
  7863. pfd[0].fd = *sock;
  7864. pfd[0].events = POLLOUT;
  7865. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7866. if (pollres != 1) {
  7867. /* Not connected */
  7868. mg_snprintf(NULL,
  7869. NULL, /* No truncation check for ebuf */
  7870. ebuf,
  7871. ebuf_len,
  7872. "connect(%s:%d): timeout",
  7873. host,
  7874. port);
  7875. closesocket(*sock);
  7876. *sock = INVALID_SOCKET;
  7877. return 0;
  7878. }
  7879. #if defined(_WIN32)
  7880. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7881. #else
  7882. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7883. #endif
  7884. if ((ret == 0) && (sockerr == 0)) {
  7885. conn_ret = 0;
  7886. }
  7887. }
  7888. if (conn_ret != 0) {
  7889. /* Not connected */
  7890. mg_snprintf(NULL,
  7891. NULL, /* No truncation check for ebuf */
  7892. ebuf,
  7893. ebuf_len,
  7894. "connect(%s:%d): error %s",
  7895. host,
  7896. port,
  7897. strerror(sockerr));
  7898. closesocket(*sock);
  7899. *sock = INVALID_SOCKET;
  7900. return 0;
  7901. }
  7902. return 1;
  7903. }
  7904. int
  7905. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7906. {
  7907. static const char *dont_escape = "._-$,;~()";
  7908. static const char *hex = "0123456789abcdef";
  7909. char *pos = dst;
  7910. const char *end = dst + dst_len - 1;
  7911. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7912. if (isalnum((unsigned char)*src)
  7913. || (strchr(dont_escape, *src) != NULL)) {
  7914. *pos = *src;
  7915. } else if (pos + 2 < end) {
  7916. pos[0] = '%';
  7917. pos[1] = hex[(unsigned char)*src >> 4];
  7918. pos[2] = hex[(unsigned char)*src & 0xf];
  7919. pos += 2;
  7920. } else {
  7921. break;
  7922. }
  7923. }
  7924. *pos = '\0';
  7925. return (*src == '\0') ? (int)(pos - dst) : -1;
  7926. }
  7927. /* Return 0 on success, non-zero if an error occurs. */
  7928. static int
  7929. print_dir_entry(struct de *de)
  7930. {
  7931. size_t namesize, escsize, i;
  7932. char *href, *esc, *p;
  7933. char size[64], mod[64];
  7934. #if defined(REENTRANT_TIME)
  7935. struct tm _tm;
  7936. struct tm *tm = &_tm;
  7937. #else
  7938. struct tm *tm;
  7939. #endif
  7940. /* Estimate worst case size for encoding and escaping */
  7941. namesize = strlen(de->file_name) + 1;
  7942. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7943. href = (char *)mg_malloc(namesize * 3 + escsize);
  7944. if (href == NULL) {
  7945. return -1;
  7946. }
  7947. mg_url_encode(de->file_name, href, namesize * 3);
  7948. esc = NULL;
  7949. if (escsize > 0) {
  7950. /* HTML escaping needed */
  7951. esc = href + namesize * 3;
  7952. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7953. mg_strlcpy(p, de->file_name + i, 2);
  7954. if (*p == '&') {
  7955. strcpy(p, "&amp;");
  7956. } else if (*p == '<') {
  7957. strcpy(p, "&lt;");
  7958. } else if (*p == '>') {
  7959. strcpy(p, "&gt;");
  7960. }
  7961. }
  7962. }
  7963. if (de->file.is_directory) {
  7964. mg_snprintf(de->conn,
  7965. NULL, /* Buffer is big enough */
  7966. size,
  7967. sizeof(size),
  7968. "%s",
  7969. "[DIRECTORY]");
  7970. } else {
  7971. /* We use (signed) cast below because MSVC 6 compiler cannot
  7972. * convert unsigned __int64 to double. Sigh. */
  7973. if (de->file.size < 1024) {
  7974. mg_snprintf(de->conn,
  7975. NULL, /* Buffer is big enough */
  7976. size,
  7977. sizeof(size),
  7978. "%d",
  7979. (int)de->file.size);
  7980. } else if (de->file.size < 0x100000) {
  7981. mg_snprintf(de->conn,
  7982. NULL, /* Buffer is big enough */
  7983. size,
  7984. sizeof(size),
  7985. "%.1fk",
  7986. (double)de->file.size / 1024.0);
  7987. } else if (de->file.size < 0x40000000) {
  7988. mg_snprintf(de->conn,
  7989. NULL, /* Buffer is big enough */
  7990. size,
  7991. sizeof(size),
  7992. "%.1fM",
  7993. (double)de->file.size / 1048576);
  7994. } else {
  7995. mg_snprintf(de->conn,
  7996. NULL, /* Buffer is big enough */
  7997. size,
  7998. sizeof(size),
  7999. "%.1fG",
  8000. (double)de->file.size / 1073741824);
  8001. }
  8002. }
  8003. /* Note: mg_snprintf will not cause a buffer overflow above.
  8004. * So, string truncation checks are not required here. */
  8005. #if defined(REENTRANT_TIME)
  8006. localtime_r(&de->file.last_modified, tm);
  8007. #else
  8008. tm = localtime(&de->file.last_modified);
  8009. #endif
  8010. if (tm != NULL) {
  8011. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8012. } else {
  8013. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8014. mod[sizeof(mod) - 1] = '\0';
  8015. }
  8016. mg_printf(de->conn,
  8017. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8018. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8019. href,
  8020. de->file.is_directory ? "/" : "",
  8021. esc ? esc : de->file_name,
  8022. de->file.is_directory ? "/" : "",
  8023. mod,
  8024. size);
  8025. mg_free(href);
  8026. return 0;
  8027. }
  8028. /* This function is called from send_directory() and used for
  8029. * sorting directory entries by size, or name, or modification time.
  8030. * On windows, __cdecl specification is needed in case if project is built
  8031. * with __stdcall convention. qsort always requires __cdels callback. */
  8032. static int WINCDECL
  8033. compare_dir_entries(const void *p1, const void *p2)
  8034. {
  8035. if (p1 && p2) {
  8036. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8037. const char *query_string = a->conn->request_info.query_string;
  8038. int cmp_result = 0;
  8039. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8040. query_string = "n";
  8041. }
  8042. if (a->file.is_directory && !b->file.is_directory) {
  8043. return -1; /* Always put directories on top */
  8044. } else if (!a->file.is_directory && b->file.is_directory) {
  8045. return 1; /* Always put directories on top */
  8046. } else if (*query_string == 'n') {
  8047. cmp_result = strcmp(a->file_name, b->file_name);
  8048. } else if (*query_string == 's') {
  8049. cmp_result = (a->file.size == b->file.size)
  8050. ? 0
  8051. : ((a->file.size > b->file.size) ? 1 : -1);
  8052. } else if (*query_string == 'd') {
  8053. cmp_result =
  8054. (a->file.last_modified == b->file.last_modified)
  8055. ? 0
  8056. : ((a->file.last_modified > b->file.last_modified) ? 1
  8057. : -1);
  8058. }
  8059. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8060. }
  8061. return 0;
  8062. }
  8063. static int
  8064. must_hide_file(struct mg_connection *conn, const char *path)
  8065. {
  8066. if (conn && conn->dom_ctx) {
  8067. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8068. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8069. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8070. || ((pattern != NULL)
  8071. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8072. }
  8073. return 0;
  8074. }
  8075. #if !defined(NO_FILESYSTEMS)
  8076. static int
  8077. scan_directory(struct mg_connection *conn,
  8078. const char *dir,
  8079. void *data,
  8080. int (*cb)(struct de *, void *))
  8081. {
  8082. char path[PATH_MAX];
  8083. struct dirent *dp;
  8084. DIR *dirp;
  8085. struct de de;
  8086. int truncated;
  8087. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8088. return 0;
  8089. } else {
  8090. de.conn = conn;
  8091. while ((dp = mg_readdir(dirp)) != NULL) {
  8092. /* Do not show current dir and hidden files */
  8093. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8094. || must_hide_file(conn, dp->d_name)) {
  8095. continue;
  8096. }
  8097. mg_snprintf(
  8098. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8099. /* If we don't memset stat structure to zero, mtime will have
  8100. * garbage and strftime() will segfault later on in
  8101. * print_dir_entry(). memset is required only if mg_stat()
  8102. * fails. For more details, see
  8103. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8104. memset(&de.file, 0, sizeof(de.file));
  8105. if (truncated) {
  8106. /* If the path is not complete, skip processing. */
  8107. continue;
  8108. }
  8109. if (!mg_stat(conn, path, &de.file)) {
  8110. mg_cry_internal(conn,
  8111. "%s: mg_stat(%s) failed: %s",
  8112. __func__,
  8113. path,
  8114. strerror(ERRNO));
  8115. }
  8116. de.file_name = dp->d_name;
  8117. cb(&de, data);
  8118. }
  8119. (void)mg_closedir(dirp);
  8120. }
  8121. return 1;
  8122. }
  8123. #endif /* NO_FILESYSTEMS */
  8124. #if !defined(NO_FILES)
  8125. static int
  8126. remove_directory(struct mg_connection *conn, const char *dir)
  8127. {
  8128. char path[PATH_MAX];
  8129. struct dirent *dp;
  8130. DIR *dirp;
  8131. struct de de;
  8132. int truncated;
  8133. int ok = 1;
  8134. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8135. return 0;
  8136. } else {
  8137. de.conn = conn;
  8138. while ((dp = mg_readdir(dirp)) != NULL) {
  8139. /* Do not show current dir (but show hidden files as they will
  8140. * also be removed) */
  8141. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8142. continue;
  8143. }
  8144. mg_snprintf(
  8145. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8146. /* If we don't memset stat structure to zero, mtime will have
  8147. * garbage and strftime() will segfault later on in
  8148. * print_dir_entry(). memset is required only if mg_stat()
  8149. * fails. For more details, see
  8150. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8151. memset(&de.file, 0, sizeof(de.file));
  8152. if (truncated) {
  8153. /* Do not delete anything shorter */
  8154. ok = 0;
  8155. continue;
  8156. }
  8157. if (!mg_stat(conn, path, &de.file)) {
  8158. mg_cry_internal(conn,
  8159. "%s: mg_stat(%s) failed: %s",
  8160. __func__,
  8161. path,
  8162. strerror(ERRNO));
  8163. ok = 0;
  8164. }
  8165. if (de.file.is_directory) {
  8166. if (remove_directory(conn, path) == 0) {
  8167. ok = 0;
  8168. }
  8169. } else {
  8170. /* This will fail file is the file is in memory */
  8171. if (mg_remove(conn, path) == 0) {
  8172. ok = 0;
  8173. }
  8174. }
  8175. }
  8176. (void)mg_closedir(dirp);
  8177. IGNORE_UNUSED_RESULT(rmdir(dir));
  8178. }
  8179. return ok;
  8180. }
  8181. #endif
  8182. struct dir_scan_data {
  8183. struct de *entries;
  8184. unsigned int num_entries;
  8185. unsigned int arr_size;
  8186. };
  8187. /* Behaves like realloc(), but frees original pointer on failure */
  8188. static void *
  8189. realloc2(void *ptr, size_t size)
  8190. {
  8191. void *new_ptr = mg_realloc(ptr, size);
  8192. if ((new_ptr == NULL) && (size > 0)) {
  8193. mg_free(ptr);
  8194. }
  8195. return new_ptr;
  8196. }
  8197. #if !defined(NO_FILESYSTEMS)
  8198. static int
  8199. dir_scan_callback(struct de *de, void *data)
  8200. {
  8201. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8202. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8203. dsd->arr_size *= 2;
  8204. dsd->entries =
  8205. (struct de *)realloc2(dsd->entries,
  8206. dsd->arr_size * sizeof(dsd->entries[0]));
  8207. }
  8208. if (dsd->entries == NULL) {
  8209. /* TODO(lsm, low): propagate an error to the caller */
  8210. dsd->num_entries = 0;
  8211. } else {
  8212. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8213. dsd->entries[dsd->num_entries].file = de->file;
  8214. dsd->entries[dsd->num_entries].conn = de->conn;
  8215. dsd->num_entries++;
  8216. }
  8217. return 0;
  8218. }
  8219. static void
  8220. handle_directory_request(struct mg_connection *conn, const char *dir)
  8221. {
  8222. unsigned int i;
  8223. int sort_direction;
  8224. struct dir_scan_data data = {NULL, 0, 128};
  8225. char date[64], *esc, *p;
  8226. const char *title;
  8227. time_t curtime = time(NULL);
  8228. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8229. mg_send_http_error(conn,
  8230. 500,
  8231. "Error: Cannot open directory\nopendir(%s): %s",
  8232. dir,
  8233. strerror(ERRNO));
  8234. return;
  8235. }
  8236. gmt_time_string(date, sizeof(date), &curtime);
  8237. if (!conn) {
  8238. return;
  8239. }
  8240. esc = NULL;
  8241. title = conn->request_info.local_uri;
  8242. if (title[strcspn(title, "&<>")]) {
  8243. /* HTML escaping needed */
  8244. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8245. if (esc) {
  8246. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8247. mg_strlcpy(p, title + i, 2);
  8248. if (*p == '&') {
  8249. strcpy(p, "&amp;");
  8250. } else if (*p == '<') {
  8251. strcpy(p, "&lt;");
  8252. } else if (*p == '>') {
  8253. strcpy(p, "&gt;");
  8254. }
  8255. }
  8256. } else {
  8257. title = "";
  8258. }
  8259. }
  8260. sort_direction = ((conn->request_info.query_string != NULL)
  8261. && (conn->request_info.query_string[0] != '\0')
  8262. && (conn->request_info.query_string[1] == 'd'))
  8263. ? 'a'
  8264. : 'd';
  8265. conn->must_close = 1;
  8266. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8267. send_static_cache_header(conn);
  8268. send_additional_header(conn);
  8269. mg_printf(conn,
  8270. "Date: %s\r\n"
  8271. "Connection: close\r\n"
  8272. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8273. date);
  8274. mg_printf(conn,
  8275. "<html><head><title>Index of %s</title>"
  8276. "<style>th {text-align: left;}</style></head>"
  8277. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8278. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8279. "<th><a href=\"?d%c\">Modified</a></th>"
  8280. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8281. "<tr><td colspan=\"3\"><hr></td></tr>",
  8282. esc ? esc : title,
  8283. esc ? esc : title,
  8284. sort_direction,
  8285. sort_direction,
  8286. sort_direction);
  8287. mg_free(esc);
  8288. /* Print first entry - link to a parent directory */
  8289. mg_printf(conn,
  8290. "<tr><td><a href=\"%s\">%s</a></td>"
  8291. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8292. "..",
  8293. "Parent directory",
  8294. "-",
  8295. "-");
  8296. /* Sort and print directory entries */
  8297. if (data.entries != NULL) {
  8298. qsort(data.entries,
  8299. (size_t)data.num_entries,
  8300. sizeof(data.entries[0]),
  8301. compare_dir_entries);
  8302. for (i = 0; i < data.num_entries; i++) {
  8303. print_dir_entry(&data.entries[i]);
  8304. mg_free(data.entries[i].file_name);
  8305. }
  8306. mg_free(data.entries);
  8307. }
  8308. mg_printf(conn, "%s", "</table></pre></body></html>");
  8309. conn->status_code = 200;
  8310. }
  8311. #endif /* NO_FILESYSTEMS */
  8312. /* Send len bytes from the opened file to the client. */
  8313. static void
  8314. send_file_data(struct mg_connection *conn,
  8315. struct mg_file *filep,
  8316. int64_t offset,
  8317. int64_t len)
  8318. {
  8319. char buf[MG_BUF_LEN];
  8320. int to_read, num_read, num_written;
  8321. int64_t size;
  8322. if (!filep || !conn) {
  8323. return;
  8324. }
  8325. /* Sanity check the offset */
  8326. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8327. : (int64_t)(filep->stat.size);
  8328. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8329. #if defined(MG_USE_OPEN_FILE)
  8330. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8331. /* file stored in memory */
  8332. if (len > size - offset) {
  8333. len = size - offset;
  8334. }
  8335. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8336. } else /* else block below */
  8337. #endif
  8338. if (len > 0 && filep->access.fp != NULL) {
  8339. /* file stored on disk */
  8340. #if defined(__linux__)
  8341. /* sendfile is only available for Linux */
  8342. if ((conn->ssl == 0) && (conn->throttle == 0)
  8343. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8344. "yes"))) {
  8345. off_t sf_offs = (off_t)offset;
  8346. ssize_t sf_sent;
  8347. int sf_file = fileno(filep->access.fp);
  8348. int loop_cnt = 0;
  8349. do {
  8350. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8351. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8352. size_t sf_tosend =
  8353. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8354. sf_sent =
  8355. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8356. if (sf_sent > 0) {
  8357. len -= sf_sent;
  8358. offset += sf_sent;
  8359. } else if (loop_cnt == 0) {
  8360. /* This file can not be sent using sendfile.
  8361. * This might be the case for pseudo-files in the
  8362. * /sys/ and /proc/ file system.
  8363. * Use the regular user mode copy code instead. */
  8364. break;
  8365. } else if (sf_sent == 0) {
  8366. /* No error, but 0 bytes sent. May be EOF? */
  8367. return;
  8368. }
  8369. loop_cnt++;
  8370. } while ((len > 0) && (sf_sent >= 0));
  8371. if (sf_sent > 0) {
  8372. return; /* OK */
  8373. }
  8374. /* sf_sent<0 means error, thus fall back to the classic way */
  8375. /* This is always the case, if sf_file is not a "normal" file,
  8376. * e.g., for sending data from the output of a CGI process. */
  8377. offset = (int64_t)sf_offs;
  8378. }
  8379. #endif
  8380. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8381. mg_cry_internal(conn,
  8382. "%s: fseeko() failed: %s",
  8383. __func__,
  8384. strerror(ERRNO));
  8385. mg_send_http_error(
  8386. conn,
  8387. 500,
  8388. "%s",
  8389. "Error: Unable to access file at requested position.");
  8390. } else {
  8391. while (len > 0) {
  8392. /* Calculate how much to read from the file in the buffer */
  8393. to_read = sizeof(buf);
  8394. if ((int64_t)to_read > len) {
  8395. to_read = (int)len;
  8396. }
  8397. /* Read from file, exit the loop on error */
  8398. if ((num_read =
  8399. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8400. <= 0) {
  8401. break;
  8402. }
  8403. /* Send read bytes to the client, exit the loop on error */
  8404. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8405. != num_read) {
  8406. break;
  8407. }
  8408. /* Both read and were successful, adjust counters */
  8409. len -= num_written;
  8410. }
  8411. }
  8412. }
  8413. }
  8414. static int
  8415. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8416. {
  8417. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8418. }
  8419. static void
  8420. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8421. {
  8422. if ((filestat != NULL) && (buf != NULL)) {
  8423. mg_snprintf(NULL,
  8424. NULL, /* All calls to construct_etag use 64 byte buffer */
  8425. buf,
  8426. buf_len,
  8427. "\"%lx.%" INT64_FMT "\"",
  8428. (unsigned long)filestat->last_modified,
  8429. filestat->size);
  8430. }
  8431. }
  8432. static void
  8433. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8434. {
  8435. if (filep != NULL && filep->fp != NULL) {
  8436. #if defined(_WIN32)
  8437. (void)conn; /* Unused. */
  8438. #else
  8439. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8440. mg_cry_internal(conn,
  8441. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8442. __func__,
  8443. strerror(ERRNO));
  8444. }
  8445. #endif
  8446. }
  8447. }
  8448. #if defined(USE_ZLIB)
  8449. #include "mod_zlib.inl"
  8450. #endif
  8451. #if !defined(NO_FILESYSTEMS)
  8452. static void
  8453. handle_static_file_request(struct mg_connection *conn,
  8454. const char *path,
  8455. struct mg_file *filep,
  8456. const char *mime_type,
  8457. const char *additional_headers)
  8458. {
  8459. char date[64], lm[64], etag[64];
  8460. char range[128]; /* large enough, so there will be no overflow */
  8461. const char *msg = "OK";
  8462. const char *range_hdr;
  8463. time_t curtime = time(NULL);
  8464. int64_t cl, r1, r2;
  8465. struct vec mime_vec;
  8466. int n, truncated;
  8467. char gz_path[PATH_MAX];
  8468. const char *encoding = "";
  8469. const char *origin_hdr;
  8470. const char *cors_orig_cfg;
  8471. const char *cors1, *cors2, *cors3;
  8472. int is_head_request;
  8473. #if defined(USE_ZLIB)
  8474. /* Compression is allowed, unless there is a reason not to use compression.
  8475. * If the file is already compressed, too small or a "range" request was
  8476. * made, on the fly compression is not possible. */
  8477. int allow_on_the_fly_compression = 1;
  8478. #endif
  8479. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8480. return;
  8481. }
  8482. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8483. if (mime_type == NULL) {
  8484. get_mime_type(conn, path, &mime_vec);
  8485. } else {
  8486. mime_vec.ptr = mime_type;
  8487. mime_vec.len = strlen(mime_type);
  8488. }
  8489. if (filep->stat.size > INT64_MAX) {
  8490. mg_send_http_error(conn,
  8491. 500,
  8492. "Error: File size is too large to send\n%" INT64_FMT,
  8493. filep->stat.size);
  8494. return;
  8495. }
  8496. cl = (int64_t)filep->stat.size;
  8497. conn->status_code = 200;
  8498. range[0] = '\0';
  8499. #if defined(USE_ZLIB)
  8500. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8501. * it's important to rewrite the filename after resolving
  8502. * the mime type from it, to preserve the actual file's type */
  8503. if (!conn->accept_gzip) {
  8504. allow_on_the_fly_compression = 0;
  8505. }
  8506. #endif
  8507. /* Check if there is a range header */
  8508. range_hdr = mg_get_header(conn, "Range");
  8509. /* For gzipped files, add *.gz */
  8510. if (filep->stat.is_gzipped) {
  8511. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8512. if (truncated) {
  8513. mg_send_http_error(conn,
  8514. 500,
  8515. "Error: Path of zipped file too long (%s)",
  8516. path);
  8517. return;
  8518. }
  8519. path = gz_path;
  8520. encoding = "Content-Encoding: gzip\r\n";
  8521. #if defined(USE_ZLIB)
  8522. /* File is already compressed. No "on the fly" compression. */
  8523. allow_on_the_fly_compression = 0;
  8524. #endif
  8525. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8526. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8527. struct mg_file_stat file_stat;
  8528. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8529. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8530. && !file_stat.is_directory) {
  8531. file_stat.is_gzipped = 1;
  8532. filep->stat = file_stat;
  8533. cl = (int64_t)filep->stat.size;
  8534. path = gz_path;
  8535. encoding = "Content-Encoding: gzip\r\n";
  8536. #if defined(USE_ZLIB)
  8537. /* File is already compressed. No "on the fly" compression. */
  8538. allow_on_the_fly_compression = 0;
  8539. #endif
  8540. }
  8541. }
  8542. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8543. mg_send_http_error(conn,
  8544. 500,
  8545. "Error: Cannot open file\nfopen(%s): %s",
  8546. path,
  8547. strerror(ERRNO));
  8548. return;
  8549. }
  8550. fclose_on_exec(&filep->access, conn);
  8551. /* If "Range" request was made: parse header, send only selected part
  8552. * of the file. */
  8553. r1 = r2 = 0;
  8554. if ((range_hdr != NULL)
  8555. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8556. && (r2 >= 0)) {
  8557. /* actually, range requests don't play well with a pre-gzipped
  8558. * file (since the range is specified in the uncompressed space) */
  8559. if (filep->stat.is_gzipped) {
  8560. mg_send_http_error(
  8561. conn,
  8562. 416, /* 416 = Range Not Satisfiable */
  8563. "%s",
  8564. "Error: Range requests in gzipped files are not supported");
  8565. (void)mg_fclose(
  8566. &filep->access); /* ignore error on read only file */
  8567. return;
  8568. }
  8569. conn->status_code = 206;
  8570. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8571. mg_snprintf(conn,
  8572. NULL, /* range buffer is big enough */
  8573. range,
  8574. sizeof(range),
  8575. "Content-Range: bytes "
  8576. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8577. r1,
  8578. r1 + cl - 1,
  8579. filep->stat.size);
  8580. msg = "Partial Content";
  8581. #if defined(USE_ZLIB)
  8582. /* Do not compress ranges. */
  8583. allow_on_the_fly_compression = 0;
  8584. #endif
  8585. }
  8586. /* Do not compress small files. Small files do not benefit from file
  8587. * compression, but there is still some overhead. */
  8588. #if defined(USE_ZLIB)
  8589. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8590. /* File is below the size limit. */
  8591. allow_on_the_fly_compression = 0;
  8592. }
  8593. #endif
  8594. /* Standard CORS header */
  8595. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8596. origin_hdr = mg_get_header(conn, "Origin");
  8597. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8598. /* Cross-origin resource sharing (CORS), see
  8599. * http://www.html5rocks.com/en/tutorials/cors/,
  8600. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8601. * -
  8602. * preflight is not supported for files. */
  8603. cors1 = "Access-Control-Allow-Origin: ";
  8604. cors2 = cors_orig_cfg;
  8605. cors3 = "\r\n";
  8606. } else {
  8607. cors1 = cors2 = cors3 = "";
  8608. }
  8609. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8610. * according to
  8611. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8612. gmt_time_string(date, sizeof(date), &curtime);
  8613. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8614. construct_etag(etag, sizeof(etag), &filep->stat);
  8615. /* Send header */
  8616. (void)mg_printf(conn,
  8617. "HTTP/1.1 %d %s\r\n"
  8618. "%s%s%s" /* CORS */
  8619. "Date: %s\r\n"
  8620. "Last-Modified: %s\r\n"
  8621. "Etag: %s\r\n"
  8622. "Content-Type: %.*s\r\n"
  8623. "Connection: %s\r\n",
  8624. conn->status_code,
  8625. msg,
  8626. cors1,
  8627. cors2,
  8628. cors3,
  8629. date,
  8630. lm,
  8631. etag,
  8632. (int)mime_vec.len,
  8633. mime_vec.ptr,
  8634. suggest_connection_header(conn));
  8635. send_static_cache_header(conn);
  8636. send_additional_header(conn);
  8637. #if defined(USE_ZLIB)
  8638. /* On the fly compression allowed */
  8639. if (allow_on_the_fly_compression) {
  8640. /* For on the fly compression, we don't know the content size in
  8641. * advance, so we have to use chunked encoding */
  8642. (void)mg_printf(conn,
  8643. "Content-Encoding: gzip\r\n"
  8644. "Transfer-Encoding: chunked\r\n");
  8645. } else
  8646. #endif
  8647. {
  8648. /* Without on-the-fly compression, we know the content-length
  8649. * and we can use ranges (with on-the-fly compression we cannot).
  8650. * So we send these response headers only in this case. */
  8651. (void)mg_printf(conn,
  8652. "Content-Length: %" INT64_FMT "\r\n"
  8653. "Accept-Ranges: bytes\r\n"
  8654. "%s" /* range */
  8655. "%s" /* encoding */,
  8656. cl,
  8657. range,
  8658. encoding);
  8659. }
  8660. /* The previous code must not add any header starting with X- to make
  8661. * sure no one of the additional_headers is included twice */
  8662. if (additional_headers != NULL) {
  8663. (void)mg_printf(conn,
  8664. "%.*s\r\n\r\n",
  8665. (int)strlen(additional_headers),
  8666. additional_headers);
  8667. } else {
  8668. (void)mg_printf(conn, "\r\n");
  8669. }
  8670. if (!is_head_request) {
  8671. #if defined(USE_ZLIB)
  8672. if (allow_on_the_fly_compression) {
  8673. /* Compress and send */
  8674. send_compressed_data(conn, filep);
  8675. } else
  8676. #endif
  8677. {
  8678. /* Send file directly */
  8679. send_file_data(conn, filep, r1, cl);
  8680. }
  8681. }
  8682. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8683. }
  8684. int
  8685. mg_send_file_body(struct mg_connection *conn, const char *path)
  8686. {
  8687. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8688. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8689. return -1;
  8690. }
  8691. fclose_on_exec(&file.access, conn);
  8692. send_file_data(conn, &file, 0, INT64_MAX);
  8693. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8694. return 0; /* >= 0 for OK */
  8695. }
  8696. #endif /* NO_FILESYSTEMS */
  8697. #if !defined(NO_CACHING)
  8698. /* Return True if we should reply 304 Not Modified. */
  8699. static int
  8700. is_not_modified(const struct mg_connection *conn,
  8701. const struct mg_file_stat *filestat)
  8702. {
  8703. char etag[64];
  8704. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8705. const char *inm = mg_get_header(conn, "If-None-Match");
  8706. construct_etag(etag, sizeof(etag), filestat);
  8707. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8708. || ((ims != NULL)
  8709. && (filestat->last_modified <= parse_date_string(ims)));
  8710. }
  8711. static void
  8712. handle_not_modified_static_file_request(struct mg_connection *conn,
  8713. struct mg_file *filep)
  8714. {
  8715. char date[64], lm[64], etag[64];
  8716. time_t curtime = time(NULL);
  8717. if ((conn == NULL) || (filep == NULL)) {
  8718. return;
  8719. }
  8720. conn->status_code = 304;
  8721. gmt_time_string(date, sizeof(date), &curtime);
  8722. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8723. construct_etag(etag, sizeof(etag), &filep->stat);
  8724. (void)mg_printf(conn,
  8725. "HTTP/1.1 %d %s\r\n"
  8726. "Date: %s\r\n",
  8727. conn->status_code,
  8728. mg_get_response_code_text(conn, conn->status_code),
  8729. date);
  8730. send_static_cache_header(conn);
  8731. send_additional_header(conn);
  8732. (void)mg_printf(conn,
  8733. "Last-Modified: %s\r\n"
  8734. "Etag: %s\r\n"
  8735. "Connection: %s\r\n"
  8736. "\r\n",
  8737. lm,
  8738. etag,
  8739. suggest_connection_header(conn));
  8740. }
  8741. #endif
  8742. #if !defined(NO_FILESYSTEMS)
  8743. void
  8744. mg_send_file(struct mg_connection *conn, const char *path)
  8745. {
  8746. mg_send_mime_file2(conn, path, NULL, NULL);
  8747. }
  8748. void
  8749. mg_send_mime_file(struct mg_connection *conn,
  8750. const char *path,
  8751. const char *mime_type)
  8752. {
  8753. mg_send_mime_file2(conn, path, mime_type, NULL);
  8754. }
  8755. void
  8756. mg_send_mime_file2(struct mg_connection *conn,
  8757. const char *path,
  8758. const char *mime_type,
  8759. const char *additional_headers)
  8760. {
  8761. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8762. if (!conn) {
  8763. /* No conn */
  8764. return;
  8765. }
  8766. if (mg_stat(conn, path, &file.stat)) {
  8767. #if !defined(NO_CACHING)
  8768. if (is_not_modified(conn, &file.stat)) {
  8769. /* Send 304 "Not Modified" - this must not send any body data */
  8770. handle_not_modified_static_file_request(conn, &file);
  8771. } else
  8772. #endif /* NO_CACHING */
  8773. if (file.stat.is_directory) {
  8774. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8775. "yes")) {
  8776. handle_directory_request(conn, path);
  8777. } else {
  8778. mg_send_http_error(conn,
  8779. 403,
  8780. "%s",
  8781. "Error: Directory listing denied");
  8782. }
  8783. } else {
  8784. handle_static_file_request(
  8785. conn, path, &file, mime_type, additional_headers);
  8786. }
  8787. } else {
  8788. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8789. }
  8790. }
  8791. /* For a given PUT path, create all intermediate subdirectories.
  8792. * Return 0 if the path itself is a directory.
  8793. * Return 1 if the path leads to a file.
  8794. * Return -1 for if the path is too long.
  8795. * Return -2 if path can not be created.
  8796. */
  8797. static int
  8798. put_dir(struct mg_connection *conn, const char *path)
  8799. {
  8800. char buf[PATH_MAX];
  8801. const char *s, *p;
  8802. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8803. size_t len;
  8804. int res = 1;
  8805. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8806. len = (size_t)(p - path);
  8807. if (len >= sizeof(buf)) {
  8808. /* path too long */
  8809. res = -1;
  8810. break;
  8811. }
  8812. memcpy(buf, path, len);
  8813. buf[len] = '\0';
  8814. /* Try to create intermediate directory */
  8815. DEBUG_TRACE("mkdir(%s)", buf);
  8816. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8817. /* path does not exixt and can not be created */
  8818. res = -2;
  8819. break;
  8820. }
  8821. /* Is path itself a directory? */
  8822. if (p[1] == '\0') {
  8823. res = 0;
  8824. }
  8825. }
  8826. return res;
  8827. }
  8828. static void
  8829. remove_bad_file(const struct mg_connection *conn, const char *path)
  8830. {
  8831. int r = mg_remove(conn, path);
  8832. if (r != 0) {
  8833. mg_cry_internal(conn,
  8834. "%s: Cannot remove invalid file %s",
  8835. __func__,
  8836. path);
  8837. }
  8838. }
  8839. long long
  8840. mg_store_body(struct mg_connection *conn, const char *path)
  8841. {
  8842. char buf[MG_BUF_LEN];
  8843. long long len = 0;
  8844. int ret, n;
  8845. struct mg_file fi;
  8846. if (conn->consumed_content != 0) {
  8847. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8848. return -11;
  8849. }
  8850. ret = put_dir(conn, path);
  8851. if (ret < 0) {
  8852. /* -1 for path too long,
  8853. * -2 for path can not be created. */
  8854. return ret;
  8855. }
  8856. if (ret != 1) {
  8857. /* Return 0 means, path itself is a directory. */
  8858. return 0;
  8859. }
  8860. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8861. return -12;
  8862. }
  8863. ret = mg_read(conn, buf, sizeof(buf));
  8864. while (ret > 0) {
  8865. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8866. if (n != ret) {
  8867. (void)mg_fclose(
  8868. &fi.access); /* File is bad and will be removed anyway. */
  8869. remove_bad_file(conn, path);
  8870. return -13;
  8871. }
  8872. len += ret;
  8873. ret = mg_read(conn, buf, sizeof(buf));
  8874. }
  8875. /* File is open for writing. If fclose fails, there was probably an
  8876. * error flushing the buffer to disk, so the file on disk might be
  8877. * broken. Delete it and return an error to the caller. */
  8878. if (mg_fclose(&fi.access) != 0) {
  8879. remove_bad_file(conn, path);
  8880. return -14;
  8881. }
  8882. return len;
  8883. }
  8884. #endif /* NO_FILESYSTEMS */
  8885. /* Parse a buffer:
  8886. * Forward the string pointer till the end of a word, then
  8887. * terminate it and forward till the begin of the next word.
  8888. */
  8889. static int
  8890. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8891. {
  8892. /* Forward until a space is found - use isgraph here */
  8893. /* See http://www.cplusplus.com/reference/cctype/ */
  8894. while (isgraph((unsigned char)**ppw)) {
  8895. (*ppw)++;
  8896. }
  8897. /* Check end of word */
  8898. if (eol) {
  8899. /* must be a end of line */
  8900. if ((**ppw != '\r') && (**ppw != '\n')) {
  8901. return -1;
  8902. }
  8903. } else {
  8904. /* must be a end of a word, but not a line */
  8905. if (**ppw != ' ') {
  8906. return -1;
  8907. }
  8908. }
  8909. /* Terminate and forward to the next word */
  8910. do {
  8911. **ppw = 0;
  8912. (*ppw)++;
  8913. } while (isspace((unsigned char)**ppw));
  8914. /* Check after term */
  8915. if (!eol) {
  8916. /* if it's not the end of line, there must be a next word */
  8917. if (!isgraph((unsigned char)**ppw)) {
  8918. return -1;
  8919. }
  8920. }
  8921. /* ok */
  8922. return 1;
  8923. }
  8924. /* Parse HTTP headers from the given buffer, advance buf pointer
  8925. * to the point where parsing stopped.
  8926. * All parameters must be valid pointers (not NULL).
  8927. * Return <0 on error. */
  8928. static int
  8929. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8930. {
  8931. int i;
  8932. int num_headers = 0;
  8933. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8934. char *dp = *buf;
  8935. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8936. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8937. dp++;
  8938. }
  8939. if (dp == *buf) {
  8940. /* End of headers reached. */
  8941. break;
  8942. }
  8943. if (*dp != ':') {
  8944. /* This is not a valid field. */
  8945. return -1;
  8946. }
  8947. /* End of header key (*dp == ':') */
  8948. /* Truncate here and set the key name */
  8949. *dp = 0;
  8950. hdr[i].name = *buf;
  8951. /* Skip all spaces */
  8952. do {
  8953. dp++;
  8954. } while ((*dp == ' ') || (*dp == '\t'));
  8955. /* The rest of the line is the value */
  8956. hdr[i].value = dp;
  8957. /* Find end of line */
  8958. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8959. dp++;
  8960. };
  8961. /* eliminate \r */
  8962. if (*dp == '\r') {
  8963. *dp = 0;
  8964. dp++;
  8965. if (*dp != '\n') {
  8966. /* This is not a valid line. */
  8967. return -1;
  8968. }
  8969. }
  8970. /* here *dp is either 0 or '\n' */
  8971. /* in any case, we have a new header */
  8972. num_headers = i + 1;
  8973. if (*dp) {
  8974. *dp = 0;
  8975. dp++;
  8976. *buf = dp;
  8977. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8978. /* This is the end of the header */
  8979. break;
  8980. }
  8981. } else {
  8982. *buf = dp;
  8983. break;
  8984. }
  8985. }
  8986. return num_headers;
  8987. }
  8988. struct mg_http_method_info {
  8989. const char *name;
  8990. int request_has_body;
  8991. int response_has_body;
  8992. int is_safe;
  8993. int is_idempotent;
  8994. int is_cacheable;
  8995. };
  8996. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8997. static struct mg_http_method_info http_methods[] = {
  8998. /* HTTP (RFC 2616) */
  8999. {"GET", 0, 1, 1, 1, 1},
  9000. {"POST", 1, 1, 0, 0, 0},
  9001. {"PUT", 1, 0, 0, 1, 0},
  9002. {"DELETE", 0, 0, 0, 1, 0},
  9003. {"HEAD", 0, 0, 1, 1, 1},
  9004. {"OPTIONS", 0, 0, 1, 1, 0},
  9005. {"CONNECT", 1, 1, 0, 0, 0},
  9006. /* TRACE method (RFC 2616) is not supported for security reasons */
  9007. /* PATCH method (RFC 5789) */
  9008. {"PATCH", 1, 0, 0, 0, 0},
  9009. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9010. /* WEBDAV (RFC 2518) */
  9011. {"PROPFIND", 0, 1, 1, 1, 0},
  9012. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9013. * Some PROPFIND results MAY be cached, with care,
  9014. * as there is no cache validation mechanism for
  9015. * most properties. This method is both safe and
  9016. * idempotent (see Section 9.1 of [RFC2616]). */
  9017. {"MKCOL", 0, 0, 0, 1, 0},
  9018. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9019. * When MKCOL is invoked without a request body,
  9020. * the newly created collection SHOULD have no
  9021. * members. A MKCOL request message may contain
  9022. * a message body. The precise behavior of a MKCOL
  9023. * request when the body is present is undefined,
  9024. * ... ==> We do not support MKCOL with body data.
  9025. * This method is idempotent, but not safe (see
  9026. * Section 9.1 of [RFC2616]). Responses to this
  9027. * method MUST NOT be cached. */
  9028. /* Unsupported WEBDAV Methods: */
  9029. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9030. /* + 11 methods from RFC 3253 */
  9031. /* ORDERPATCH (RFC 3648) */
  9032. /* ACL (RFC 3744) */
  9033. /* SEARCH (RFC 5323) */
  9034. /* + MicroSoft extensions
  9035. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9036. /* REPORT method (RFC 3253) */
  9037. {"REPORT", 1, 1, 1, 1, 1},
  9038. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9039. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9040. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9041. * to be useful for REST in case a "GET request with body" is
  9042. * required. */
  9043. {NULL, 0, 0, 0, 0, 0}
  9044. /* end of list */
  9045. };
  9046. static const struct mg_http_method_info *
  9047. get_http_method_info(const char *method)
  9048. {
  9049. /* Check if the method is known to the server. The list of all known
  9050. * HTTP methods can be found here at
  9051. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9052. */
  9053. const struct mg_http_method_info *m = http_methods;
  9054. while (m->name) {
  9055. if (!strcmp(m->name, method)) {
  9056. return m;
  9057. }
  9058. m++;
  9059. }
  9060. return NULL;
  9061. }
  9062. static int
  9063. is_valid_http_method(const char *method)
  9064. {
  9065. return (get_http_method_info(method) != NULL);
  9066. }
  9067. /* Parse HTTP request, fill in mg_request_info structure.
  9068. * This function modifies the buffer by NUL-terminating
  9069. * HTTP request components, header names and header values.
  9070. * Parameters:
  9071. * buf (in/out): pointer to the HTTP header to parse and split
  9072. * len (in): length of HTTP header buffer
  9073. * re (out): parsed header as mg_request_info
  9074. * buf and ri must be valid pointers (not NULL), len>0.
  9075. * Returns <0 on error. */
  9076. static int
  9077. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9078. {
  9079. int request_length;
  9080. int init_skip = 0;
  9081. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9082. * remote_port */
  9083. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9084. NULL;
  9085. ri->num_headers = 0;
  9086. /* RFC says that all initial whitespaces should be ingored */
  9087. /* This included all leading \r and \n (isspace) */
  9088. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9089. while ((len > 0) && isspace((unsigned char)*buf)) {
  9090. buf++;
  9091. len--;
  9092. init_skip++;
  9093. }
  9094. if (len == 0) {
  9095. /* Incomplete request */
  9096. return 0;
  9097. }
  9098. /* Control characters are not allowed, including zero */
  9099. if (iscntrl((unsigned char)*buf)) {
  9100. return -1;
  9101. }
  9102. /* Find end of HTTP header */
  9103. request_length = get_http_header_len(buf, len);
  9104. if (request_length <= 0) {
  9105. return request_length;
  9106. }
  9107. buf[request_length - 1] = '\0';
  9108. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9109. return -1;
  9110. }
  9111. /* The first word has to be the HTTP method */
  9112. ri->request_method = buf;
  9113. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9114. return -1;
  9115. }
  9116. /* Check for a valid http method */
  9117. if (!is_valid_http_method(ri->request_method)) {
  9118. return -1;
  9119. }
  9120. /* The second word is the URI */
  9121. ri->request_uri = buf;
  9122. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9123. return -1;
  9124. }
  9125. /* Next would be the HTTP version */
  9126. ri->http_version = buf;
  9127. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9128. return -1;
  9129. }
  9130. /* Check for a valid HTTP version key */
  9131. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9132. /* Invalid request */
  9133. return -1;
  9134. }
  9135. ri->http_version += 5;
  9136. /* Parse all HTTP headers */
  9137. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9138. if (ri->num_headers < 0) {
  9139. /* Error while parsing headers */
  9140. return -1;
  9141. }
  9142. return request_length + init_skip;
  9143. }
  9144. static int
  9145. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9146. {
  9147. int response_length;
  9148. int init_skip = 0;
  9149. char *tmp, *tmp2;
  9150. long l;
  9151. /* Initialize elements. */
  9152. ri->http_version = ri->status_text = NULL;
  9153. ri->num_headers = ri->status_code = 0;
  9154. /* RFC says that all initial whitespaces should be ingored */
  9155. /* This included all leading \r and \n (isspace) */
  9156. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9157. while ((len > 0) && isspace((unsigned char)*buf)) {
  9158. buf++;
  9159. len--;
  9160. init_skip++;
  9161. }
  9162. if (len == 0) {
  9163. /* Incomplete request */
  9164. return 0;
  9165. }
  9166. /* Control characters are not allowed, including zero */
  9167. if (iscntrl((unsigned char)*buf)) {
  9168. return -1;
  9169. }
  9170. /* Find end of HTTP header */
  9171. response_length = get_http_header_len(buf, len);
  9172. if (response_length <= 0) {
  9173. return response_length;
  9174. }
  9175. buf[response_length - 1] = '\0';
  9176. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9177. return -1;
  9178. }
  9179. /* The first word is the HTTP version */
  9180. /* Check for a valid HTTP version key */
  9181. if (strncmp(buf, "HTTP/", 5) != 0) {
  9182. /* Invalid request */
  9183. return -1;
  9184. }
  9185. buf += 5;
  9186. if (!isgraph((unsigned char)buf[0])) {
  9187. /* Invalid request */
  9188. return -1;
  9189. }
  9190. ri->http_version = buf;
  9191. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9192. return -1;
  9193. }
  9194. /* The second word is the status as a number */
  9195. tmp = buf;
  9196. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9197. return -1;
  9198. }
  9199. l = strtol(tmp, &tmp2, 10);
  9200. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9201. /* Everything else but a 3 digit code is invalid */
  9202. return -1;
  9203. }
  9204. ri->status_code = (int)l;
  9205. /* The rest of the line is the status text */
  9206. ri->status_text = buf;
  9207. /* Find end of status text */
  9208. /* isgraph or isspace = isprint */
  9209. while (isprint((unsigned char)*buf)) {
  9210. buf++;
  9211. }
  9212. if ((*buf != '\r') && (*buf != '\n')) {
  9213. return -1;
  9214. }
  9215. /* Terminate string and forward buf to next line */
  9216. do {
  9217. *buf = 0;
  9218. buf++;
  9219. } while (isspace((unsigned char)*buf));
  9220. /* Parse all HTTP headers */
  9221. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9222. if (ri->num_headers < 0) {
  9223. /* Error while parsing headers */
  9224. return -1;
  9225. }
  9226. return response_length + init_skip;
  9227. }
  9228. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9229. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9230. * buffer (which marks the end of HTTP request). Buffer buf may already
  9231. * have some data. The length of the data is stored in nread.
  9232. * Upon every read operation, increase nread by the number of bytes read. */
  9233. static int
  9234. read_message(FILE *fp,
  9235. struct mg_connection *conn,
  9236. char *buf,
  9237. int bufsiz,
  9238. int *nread)
  9239. {
  9240. int request_len, n = 0;
  9241. struct timespec last_action_time;
  9242. double request_timeout;
  9243. if (!conn) {
  9244. return 0;
  9245. }
  9246. memset(&last_action_time, 0, sizeof(last_action_time));
  9247. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9248. /* value of request_timeout is in seconds, config in milliseconds */
  9249. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9250. } else {
  9251. request_timeout = -1.0;
  9252. }
  9253. if (conn->handled_requests > 0) {
  9254. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9255. request_timeout =
  9256. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9257. }
  9258. }
  9259. request_len = get_http_header_len(buf, *nread);
  9260. while (request_len == 0) {
  9261. /* Full request not yet received */
  9262. if (conn->phys_ctx->stop_flag != 0) {
  9263. /* Server is to be stopped. */
  9264. return -1;
  9265. }
  9266. if (*nread >= bufsiz) {
  9267. /* Request too long */
  9268. return -2;
  9269. }
  9270. n = pull_inner(
  9271. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9272. if (n == -2) {
  9273. /* Receive error */
  9274. return -1;
  9275. }
  9276. /* update clock after every read request */
  9277. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9278. if (n > 0) {
  9279. *nread += n;
  9280. request_len = get_http_header_len(buf, *nread);
  9281. } else {
  9282. request_len = 0;
  9283. }
  9284. if ((request_len == 0) && (request_timeout >= 0)) {
  9285. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9286. > request_timeout) {
  9287. /* Timeout */
  9288. return -1;
  9289. }
  9290. }
  9291. }
  9292. return request_len;
  9293. }
  9294. #if !defined(NO_CGI) || !defined(NO_FILES)
  9295. static int
  9296. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9297. {
  9298. const char *expect;
  9299. char buf[MG_BUF_LEN];
  9300. int success = 0;
  9301. if (!conn) {
  9302. return 0;
  9303. }
  9304. expect = mg_get_header(conn, "Expect");
  9305. DEBUG_ASSERT(fp != NULL);
  9306. if (!fp) {
  9307. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9308. return 0;
  9309. }
  9310. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9311. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9312. */
  9313. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9314. } else {
  9315. if (expect != NULL) {
  9316. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9317. conn->status_code = 100;
  9318. } else {
  9319. conn->status_code = 200;
  9320. }
  9321. DEBUG_ASSERT(conn->consumed_content == 0);
  9322. if (conn->consumed_content != 0) {
  9323. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9324. return 0;
  9325. }
  9326. for (;;) {
  9327. int nread = mg_read(conn, buf, sizeof(buf));
  9328. if (nread <= 0) {
  9329. success = (nread == 0);
  9330. break;
  9331. }
  9332. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9333. break;
  9334. }
  9335. }
  9336. /* Each error code path in this function must send an error */
  9337. if (!success) {
  9338. /* NOTE: Maybe some data has already been sent. */
  9339. /* TODO (low): If some data has been sent, a correct error
  9340. * reply can no longer be sent, so just close the connection */
  9341. mg_send_http_error(conn, 500, "%s", "");
  9342. }
  9343. }
  9344. return success;
  9345. }
  9346. #endif
  9347. #if defined(USE_TIMERS)
  9348. #define TIMER_API static
  9349. #include "timer.inl"
  9350. #endif /* USE_TIMERS */
  9351. #if !defined(NO_CGI)
  9352. /* This structure helps to create an environment for the spawned CGI
  9353. * program.
  9354. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9355. * last element must be NULL.
  9356. * However, on Windows there is a requirement that all these
  9357. * VARIABLE=VALUE\0
  9358. * strings must reside in a contiguous buffer. The end of the buffer is
  9359. * marked by two '\0' characters.
  9360. * We satisfy both worlds: we create an envp array (which is vars), all
  9361. * entries are actually pointers inside buf. */
  9362. struct cgi_environment {
  9363. struct mg_connection *conn;
  9364. /* Data block */
  9365. char *buf; /* Environment buffer */
  9366. size_t buflen; /* Space available in buf */
  9367. size_t bufused; /* Space taken in buf */
  9368. /* Index block */
  9369. char **var; /* char **envp */
  9370. size_t varlen; /* Number of variables available in var */
  9371. size_t varused; /* Number of variables stored in var */
  9372. };
  9373. static void addenv(struct cgi_environment *env,
  9374. PRINTF_FORMAT_STRING(const char *fmt),
  9375. ...) PRINTF_ARGS(2, 3);
  9376. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9377. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9378. static void
  9379. addenv(struct cgi_environment *env, const char *fmt, ...)
  9380. {
  9381. size_t i, n, space;
  9382. int truncated = 0;
  9383. char *added;
  9384. va_list ap;
  9385. if ((env->varlen - env->varused) < 2) {
  9386. mg_cry_internal(env->conn,
  9387. "%s: Cannot register CGI variable [%s]",
  9388. __func__,
  9389. fmt);
  9390. return;
  9391. }
  9392. /* Calculate how much space is left in the buffer */
  9393. space = (env->buflen - env->bufused);
  9394. do {
  9395. /* Space for "\0\0" is always needed. */
  9396. if (space <= 2) {
  9397. /* Allocate new buffer */
  9398. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9399. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9400. if (!added) {
  9401. /* Out of memory */
  9402. mg_cry_internal(
  9403. env->conn,
  9404. "%s: Cannot allocate memory for CGI variable [%s]",
  9405. __func__,
  9406. fmt);
  9407. return;
  9408. }
  9409. /* Retarget pointers */
  9410. env->buf = added;
  9411. env->buflen = n;
  9412. for (i = 0, n = 0; i < env->varused; i++) {
  9413. env->var[i] = added + n;
  9414. n += strlen(added + n) + 1;
  9415. }
  9416. space = (env->buflen - env->bufused);
  9417. }
  9418. /* Make a pointer to the free space int the buffer */
  9419. added = env->buf + env->bufused;
  9420. /* Copy VARIABLE=VALUE\0 string into the free space */
  9421. va_start(ap, fmt);
  9422. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9423. va_end(ap);
  9424. /* Do not add truncated strings to the environment */
  9425. if (truncated) {
  9426. /* Reallocate the buffer */
  9427. space = 0;
  9428. }
  9429. } while (truncated);
  9430. /* Calculate number of bytes added to the environment */
  9431. n = strlen(added) + 1;
  9432. env->bufused += n;
  9433. /* Append a pointer to the added string into the envp array */
  9434. env->var[env->varused] = added;
  9435. env->varused++;
  9436. }
  9437. /* Return 0 on success, non-zero if an error occurs. */
  9438. static int
  9439. prepare_cgi_environment(struct mg_connection *conn,
  9440. const char *prog,
  9441. struct cgi_environment *env)
  9442. {
  9443. const char *s;
  9444. struct vec var_vec;
  9445. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9446. int i, truncated, uri_len;
  9447. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9448. return -1;
  9449. }
  9450. env->conn = conn;
  9451. env->buflen = CGI_ENVIRONMENT_SIZE;
  9452. env->bufused = 0;
  9453. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9454. if (env->buf == NULL) {
  9455. mg_cry_internal(conn,
  9456. "%s: Not enough memory for environmental buffer",
  9457. __func__);
  9458. return -1;
  9459. }
  9460. env->varlen = MAX_CGI_ENVIR_VARS;
  9461. env->varused = 0;
  9462. env->var =
  9463. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9464. if (env->var == NULL) {
  9465. mg_cry_internal(conn,
  9466. "%s: Not enough memory for environmental variables",
  9467. __func__);
  9468. mg_free(env->buf);
  9469. return -1;
  9470. }
  9471. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9472. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9473. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9474. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9475. /* Prepare the environment block */
  9476. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9477. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9478. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9479. #if defined(USE_IPV6)
  9480. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9481. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9482. } else
  9483. #endif
  9484. {
  9485. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9486. }
  9487. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9488. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9489. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9490. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9491. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9492. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9493. /* SCRIPT_NAME */
  9494. uri_len = (int)strlen(conn->request_info.local_uri);
  9495. if (conn->path_info == NULL) {
  9496. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9497. /* URI: /path_to_script/script.cgi */
  9498. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9499. } else {
  9500. /* URI: /path_to_script/ ... using index.cgi */
  9501. const char *index_file = strrchr(prog, '/');
  9502. if (index_file) {
  9503. addenv(env,
  9504. "SCRIPT_NAME=%s%s",
  9505. conn->request_info.local_uri,
  9506. index_file + 1);
  9507. }
  9508. }
  9509. } else {
  9510. /* URI: /path_to_script/script.cgi/path_info */
  9511. addenv(env,
  9512. "SCRIPT_NAME=%.*s",
  9513. uri_len - (int)strlen(conn->path_info),
  9514. conn->request_info.local_uri);
  9515. }
  9516. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9517. if (conn->path_info == NULL) {
  9518. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9519. } else {
  9520. addenv(env,
  9521. "PATH_TRANSLATED=%s%s",
  9522. conn->dom_ctx->config[DOCUMENT_ROOT],
  9523. conn->path_info);
  9524. }
  9525. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9526. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9527. addenv(env, "CONTENT_TYPE=%s", s);
  9528. }
  9529. if (conn->request_info.query_string != NULL) {
  9530. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9531. }
  9532. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9533. addenv(env, "CONTENT_LENGTH=%s", s);
  9534. }
  9535. if ((s = getenv("PATH")) != NULL) {
  9536. addenv(env, "PATH=%s", s);
  9537. }
  9538. if (conn->path_info != NULL) {
  9539. addenv(env, "PATH_INFO=%s", conn->path_info);
  9540. }
  9541. if (conn->status_code > 0) {
  9542. /* CGI error handler should show the status code */
  9543. addenv(env, "STATUS=%d", conn->status_code);
  9544. }
  9545. #if defined(_WIN32)
  9546. if ((s = getenv("COMSPEC")) != NULL) {
  9547. addenv(env, "COMSPEC=%s", s);
  9548. }
  9549. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9550. addenv(env, "SYSTEMROOT=%s", s);
  9551. }
  9552. if ((s = getenv("SystemDrive")) != NULL) {
  9553. addenv(env, "SystemDrive=%s", s);
  9554. }
  9555. if ((s = getenv("ProgramFiles")) != NULL) {
  9556. addenv(env, "ProgramFiles=%s", s);
  9557. }
  9558. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9559. addenv(env, "ProgramFiles(x86)=%s", s);
  9560. }
  9561. #else
  9562. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9563. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9564. }
  9565. #endif /* _WIN32 */
  9566. if ((s = getenv("PERLLIB")) != NULL) {
  9567. addenv(env, "PERLLIB=%s", s);
  9568. }
  9569. if (conn->request_info.remote_user != NULL) {
  9570. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9571. addenv(env, "%s", "AUTH_TYPE=Digest");
  9572. }
  9573. /* Add all headers as HTTP_* variables */
  9574. for (i = 0; i < conn->request_info.num_headers; i++) {
  9575. (void)mg_snprintf(conn,
  9576. &truncated,
  9577. http_var_name,
  9578. sizeof(http_var_name),
  9579. "HTTP_%s",
  9580. conn->request_info.http_headers[i].name);
  9581. if (truncated) {
  9582. mg_cry_internal(conn,
  9583. "%s: HTTP header variable too long [%s]",
  9584. __func__,
  9585. conn->request_info.http_headers[i].name);
  9586. continue;
  9587. }
  9588. /* Convert variable name into uppercase, and change - to _ */
  9589. for (p = http_var_name; *p != '\0'; p++) {
  9590. if (*p == '-') {
  9591. *p = '_';
  9592. }
  9593. *p = (char)toupper((unsigned char)*p);
  9594. }
  9595. addenv(env,
  9596. "%s=%s",
  9597. http_var_name,
  9598. conn->request_info.http_headers[i].value);
  9599. }
  9600. /* Add user-specified variables */
  9601. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9602. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9603. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9604. }
  9605. env->var[env->varused] = NULL;
  9606. env->buf[env->bufused] = '\0';
  9607. return 0;
  9608. }
  9609. /* Data for CGI process control: PID and number of references */
  9610. struct process_control_data {
  9611. pid_t pid;
  9612. int references;
  9613. };
  9614. static int
  9615. abort_process(void *data)
  9616. {
  9617. /* Waitpid checks for child status and won't work for a pid that does not
  9618. * identify a child of the current process. Thus, if the pid is reused,
  9619. * we will not affect a different process. */
  9620. struct process_control_data *proc = (struct process_control_data *)data;
  9621. int status = 0;
  9622. int refs;
  9623. pid_t ret_pid;
  9624. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9625. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9626. /* Stop child process */
  9627. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9628. kill(proc->pid, SIGABRT);
  9629. /* Wait until process is terminated (don't leave zombies) */
  9630. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9631. ;
  9632. } else {
  9633. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9634. }
  9635. /* Dec reference counter */
  9636. refs = mg_atomic_dec(&proc->references);
  9637. if (refs == 0) {
  9638. /* no more references - free data */
  9639. mg_free(data);
  9640. }
  9641. return 0;
  9642. }
  9643. /* Local (static) function assumes all arguments are valid. */
  9644. static void
  9645. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9646. {
  9647. char *buf;
  9648. size_t buflen;
  9649. int headers_len, data_len, i, truncated;
  9650. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9651. const char *status, *status_text, *connection_state;
  9652. char *pbuf, dir[PATH_MAX], *p;
  9653. struct mg_request_info ri;
  9654. struct cgi_environment blk;
  9655. FILE *in = NULL, *out = NULL, *err = NULL;
  9656. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9657. pid_t pid = (pid_t)-1;
  9658. struct process_control_data *proc = NULL;
  9659. #if defined(USE_TIMERS)
  9660. double cgi_timeout = -1.0;
  9661. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9662. /* Get timeout in seconds */
  9663. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9664. }
  9665. #endif
  9666. buf = NULL;
  9667. buflen = conn->phys_ctx->max_request_size;
  9668. i = prepare_cgi_environment(conn, prog, &blk);
  9669. if (i != 0) {
  9670. blk.buf = NULL;
  9671. blk.var = NULL;
  9672. goto done;
  9673. }
  9674. /* CGI must be executed in its own directory. 'dir' must point to the
  9675. * directory containing executable program, 'p' must point to the
  9676. * executable program name relative to 'dir'. */
  9677. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9678. if (truncated) {
  9679. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9680. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9681. goto done;
  9682. }
  9683. if ((p = strrchr(dir, '/')) != NULL) {
  9684. *p++ = '\0';
  9685. } else {
  9686. dir[0] = '.';
  9687. dir[1] = '\0';
  9688. p = (char *)prog;
  9689. }
  9690. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9691. status = strerror(ERRNO);
  9692. mg_cry_internal(
  9693. conn,
  9694. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9695. prog,
  9696. status);
  9697. mg_send_http_error(conn,
  9698. 500,
  9699. "Error: Cannot create CGI pipe: %s",
  9700. status);
  9701. goto done;
  9702. }
  9703. proc = (struct process_control_data *)
  9704. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9705. if (proc == NULL) {
  9706. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9707. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9708. goto done;
  9709. }
  9710. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9711. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9712. if (pid == (pid_t)-1) {
  9713. status = strerror(ERRNO);
  9714. mg_cry_internal(
  9715. conn,
  9716. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9717. prog,
  9718. status);
  9719. mg_send_http_error(conn,
  9720. 500,
  9721. "Error: Cannot spawn CGI process [%s]: %s",
  9722. prog,
  9723. status);
  9724. mg_free(proc);
  9725. proc = NULL;
  9726. goto done;
  9727. }
  9728. /* Store data in shared process_control_data */
  9729. proc->pid = pid;
  9730. proc->references = 1;
  9731. #if defined(USE_TIMERS)
  9732. if (cgi_timeout > 0.0) {
  9733. proc->references = 2;
  9734. // Start a timer for CGI
  9735. timer_add(conn->phys_ctx,
  9736. cgi_timeout /* in seconds */,
  9737. 0.0,
  9738. 1,
  9739. abort_process,
  9740. (void *)proc);
  9741. }
  9742. #endif
  9743. /* Parent closes only one side of the pipes.
  9744. * If we don't mark them as closed, close() attempt before
  9745. * return from this function throws an exception on Windows.
  9746. * Windows does not like when closed descriptor is closed again. */
  9747. (void)close(fdin[0]);
  9748. (void)close(fdout[1]);
  9749. (void)close(fderr[1]);
  9750. fdin[0] = fdout[1] = fderr[1] = -1;
  9751. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9752. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9753. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9754. status = strerror(ERRNO);
  9755. mg_cry_internal(conn,
  9756. "Error: CGI program \"%s\": Can not open fd: %s",
  9757. prog,
  9758. status);
  9759. mg_send_http_error(conn,
  9760. 500,
  9761. "Error: CGI can not open fd\nfdopen: %s",
  9762. status);
  9763. goto done;
  9764. }
  9765. setbuf(in, NULL);
  9766. setbuf(out, NULL);
  9767. setbuf(err, NULL);
  9768. fout.access.fp = out;
  9769. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9770. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9771. conn->content_len);
  9772. /* This is a POST/PUT request, or another request with body data. */
  9773. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9774. /* Error sending the body data */
  9775. mg_cry_internal(
  9776. conn,
  9777. "Error: CGI program \"%s\": Forward body data failed",
  9778. prog);
  9779. goto done;
  9780. }
  9781. }
  9782. /* Close so child gets an EOF. */
  9783. fclose(in);
  9784. in = NULL;
  9785. fdin[1] = -1;
  9786. /* Now read CGI reply into a buffer. We need to set correct
  9787. * status code, thus we need to see all HTTP headers first.
  9788. * Do not send anything back to client, until we buffer in all
  9789. * HTTP headers. */
  9790. data_len = 0;
  9791. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9792. if (buf == NULL) {
  9793. mg_send_http_error(conn,
  9794. 500,
  9795. "Error: Not enough memory for CGI buffer (%u bytes)",
  9796. (unsigned int)buflen);
  9797. mg_cry_internal(
  9798. conn,
  9799. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9800. "bytes)",
  9801. prog,
  9802. (unsigned int)buflen);
  9803. goto done;
  9804. }
  9805. DEBUG_TRACE("CGI: %s", "wait for response");
  9806. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9807. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9808. if (headers_len <= 0) {
  9809. /* Could not parse the CGI response. Check if some error message on
  9810. * stderr. */
  9811. i = pull_all(err, conn, buf, (int)buflen);
  9812. if (i > 0) {
  9813. /* CGI program explicitly sent an error */
  9814. /* Write the error message to the internal log */
  9815. mg_cry_internal(conn,
  9816. "Error: CGI program \"%s\" sent error "
  9817. "message: [%.*s]",
  9818. prog,
  9819. i,
  9820. buf);
  9821. /* Don't send the error message back to the client */
  9822. mg_send_http_error(conn,
  9823. 500,
  9824. "Error: CGI program \"%s\" failed.",
  9825. prog);
  9826. } else {
  9827. /* CGI program did not explicitly send an error, but a broken
  9828. * respon header */
  9829. mg_cry_internal(conn,
  9830. "Error: CGI program sent malformed or too big "
  9831. "(>%u bytes) HTTP headers: [%.*s]",
  9832. (unsigned)buflen,
  9833. data_len,
  9834. buf);
  9835. mg_send_http_error(conn,
  9836. 500,
  9837. "Error: CGI program sent malformed or too big "
  9838. "(>%u bytes) HTTP headers: [%.*s]",
  9839. (unsigned)buflen,
  9840. data_len,
  9841. buf);
  9842. }
  9843. /* in both cases, abort processing CGI */
  9844. goto done;
  9845. }
  9846. pbuf = buf;
  9847. buf[headers_len - 1] = '\0';
  9848. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9849. /* Make up and send the status line */
  9850. status_text = "OK";
  9851. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9852. != NULL) {
  9853. conn->status_code = atoi(status);
  9854. status_text = status;
  9855. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9856. status_text++;
  9857. }
  9858. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9859. != NULL) {
  9860. conn->status_code = 307;
  9861. } else {
  9862. conn->status_code = 200;
  9863. }
  9864. connection_state =
  9865. get_header(ri.http_headers, ri.num_headers, "Connection");
  9866. if (!header_has_option(connection_state, "keep-alive")) {
  9867. conn->must_close = 1;
  9868. }
  9869. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9870. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9871. /* Send headers */
  9872. for (i = 0; i < ri.num_headers; i++) {
  9873. DEBUG_TRACE("CGI header: %s: %s",
  9874. ri.http_headers[i].name,
  9875. ri.http_headers[i].value);
  9876. mg_printf(conn,
  9877. "%s: %s\r\n",
  9878. ri.http_headers[i].name,
  9879. ri.http_headers[i].value);
  9880. }
  9881. mg_write(conn, "\r\n", 2);
  9882. /* Send chunk of data that may have been read after the headers */
  9883. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9884. /* Read the rest of CGI output and send to the client */
  9885. DEBUG_TRACE("CGI: %s", "forward all data");
  9886. send_file_data(conn, &fout, 0, INT64_MAX);
  9887. DEBUG_TRACE("CGI: %s", "all data sent");
  9888. done:
  9889. mg_free(blk.var);
  9890. mg_free(blk.buf);
  9891. if (pid != (pid_t)-1) {
  9892. abort_process((void *)proc);
  9893. }
  9894. if (fdin[0] != -1) {
  9895. close(fdin[0]);
  9896. }
  9897. if (fdout[1] != -1) {
  9898. close(fdout[1]);
  9899. }
  9900. if (fderr[1] != -1) {
  9901. close(fderr[1]);
  9902. }
  9903. if (in != NULL) {
  9904. fclose(in);
  9905. } else if (fdin[1] != -1) {
  9906. close(fdin[1]);
  9907. }
  9908. if (out != NULL) {
  9909. fclose(out);
  9910. } else if (fdout[0] != -1) {
  9911. close(fdout[0]);
  9912. }
  9913. if (err != NULL) {
  9914. fclose(err);
  9915. } else if (fderr[0] != -1) {
  9916. close(fderr[0]);
  9917. }
  9918. mg_free(buf);
  9919. }
  9920. #endif /* !NO_CGI */
  9921. #if !defined(NO_FILES)
  9922. static void
  9923. mkcol(struct mg_connection *conn, const char *path)
  9924. {
  9925. int rc, body_len;
  9926. struct de de;
  9927. char date[64];
  9928. time_t curtime = time(NULL);
  9929. if (conn == NULL) {
  9930. return;
  9931. }
  9932. /* TODO (mid): Check the mg_send_http_error situations in this function
  9933. */
  9934. memset(&de.file, 0, sizeof(de.file));
  9935. if (!mg_stat(conn, path, &de.file)) {
  9936. mg_cry_internal(conn,
  9937. "%s: mg_stat(%s) failed: %s",
  9938. __func__,
  9939. path,
  9940. strerror(ERRNO));
  9941. }
  9942. if (de.file.last_modified) {
  9943. /* TODO (mid): This check does not seem to make any sense ! */
  9944. /* TODO (mid): Add a webdav unit test first, before changing
  9945. * anything here. */
  9946. mg_send_http_error(
  9947. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9948. return;
  9949. }
  9950. body_len = conn->data_len - conn->request_len;
  9951. if (body_len > 0) {
  9952. mg_send_http_error(
  9953. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9954. return;
  9955. }
  9956. rc = mg_mkdir(conn, path, 0755);
  9957. if (rc == 0) {
  9958. conn->status_code = 201;
  9959. gmt_time_string(date, sizeof(date), &curtime);
  9960. mg_printf(conn,
  9961. "HTTP/1.1 %d Created\r\n"
  9962. "Date: %s\r\n",
  9963. conn->status_code,
  9964. date);
  9965. send_static_cache_header(conn);
  9966. send_additional_header(conn);
  9967. mg_printf(conn,
  9968. "Content-Length: 0\r\n"
  9969. "Connection: %s\r\n\r\n",
  9970. suggest_connection_header(conn));
  9971. } else {
  9972. if (errno == EEXIST) {
  9973. mg_send_http_error(
  9974. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9975. } else if (errno == EACCES) {
  9976. mg_send_http_error(
  9977. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9978. } else if (errno == ENOENT) {
  9979. mg_send_http_error(
  9980. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9981. } else {
  9982. mg_send_http_error(
  9983. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9984. }
  9985. }
  9986. }
  9987. static void
  9988. put_file(struct mg_connection *conn, const char *path)
  9989. {
  9990. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9991. const char *range;
  9992. int64_t r1, r2;
  9993. int rc;
  9994. char date[64];
  9995. time_t curtime = time(NULL);
  9996. if (conn == NULL) {
  9997. return;
  9998. }
  9999. if (mg_stat(conn, path, &file.stat)) {
  10000. /* File already exists */
  10001. conn->status_code = 200;
  10002. if (file.stat.is_directory) {
  10003. /* This is an already existing directory,
  10004. * so there is nothing to do for the server. */
  10005. rc = 0;
  10006. } else {
  10007. /* File exists and is not a directory. */
  10008. /* Can it be replaced? */
  10009. #if defined(MG_USE_OPEN_FILE)
  10010. if (file.access.membuf != NULL) {
  10011. /* This is an "in-memory" file, that can not be replaced */
  10012. mg_send_http_error(conn,
  10013. 405,
  10014. "Error: Put not possible\nReplacing %s "
  10015. "is not supported",
  10016. path);
  10017. return;
  10018. }
  10019. #endif
  10020. /* Check if the server may write this file */
  10021. if (access(path, W_OK) == 0) {
  10022. /* Access granted */
  10023. conn->status_code = 200;
  10024. rc = 1;
  10025. } else {
  10026. mg_send_http_error(
  10027. conn,
  10028. 403,
  10029. "Error: Put not possible\nReplacing %s is not allowed",
  10030. path);
  10031. return;
  10032. }
  10033. }
  10034. } else {
  10035. /* File should be created */
  10036. conn->status_code = 201;
  10037. rc = put_dir(conn, path);
  10038. }
  10039. if (rc == 0) {
  10040. /* put_dir returns 0 if path is a directory */
  10041. gmt_time_string(date, sizeof(date), &curtime);
  10042. mg_printf(conn,
  10043. "HTTP/1.1 %d %s\r\n",
  10044. conn->status_code,
  10045. mg_get_response_code_text(NULL, conn->status_code));
  10046. send_no_cache_header(conn);
  10047. send_additional_header(conn);
  10048. mg_printf(conn,
  10049. "Date: %s\r\n"
  10050. "Content-Length: 0\r\n"
  10051. "Connection: %s\r\n\r\n",
  10052. date,
  10053. suggest_connection_header(conn));
  10054. /* Request to create a directory has been fulfilled successfully.
  10055. * No need to put a file. */
  10056. return;
  10057. }
  10058. if (rc == -1) {
  10059. /* put_dir returns -1 if the path is too long */
  10060. mg_send_http_error(conn,
  10061. 414,
  10062. "Error: Path too long\nput_dir(%s): %s",
  10063. path,
  10064. strerror(ERRNO));
  10065. return;
  10066. }
  10067. if (rc == -2) {
  10068. /* put_dir returns -2 if the directory can not be created */
  10069. mg_send_http_error(conn,
  10070. 500,
  10071. "Error: Can not create directory\nput_dir(%s): %s",
  10072. path,
  10073. strerror(ERRNO));
  10074. return;
  10075. }
  10076. /* A file should be created or overwritten. */
  10077. /* Currently CivetWeb does not nead read+write access. */
  10078. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10079. || file.access.fp == NULL) {
  10080. (void)mg_fclose(&file.access);
  10081. mg_send_http_error(conn,
  10082. 500,
  10083. "Error: Can not create file\nfopen(%s): %s",
  10084. path,
  10085. strerror(ERRNO));
  10086. return;
  10087. }
  10088. fclose_on_exec(&file.access, conn);
  10089. range = mg_get_header(conn, "Content-Range");
  10090. r1 = r2 = 0;
  10091. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10092. conn->status_code = 206; /* Partial content */
  10093. fseeko(file.access.fp, r1, SEEK_SET);
  10094. }
  10095. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10096. /* forward_body_data failed.
  10097. * The error code has already been sent to the client,
  10098. * and conn->status_code is already set. */
  10099. (void)mg_fclose(&file.access);
  10100. return;
  10101. }
  10102. if (mg_fclose(&file.access) != 0) {
  10103. /* fclose failed. This might have different reasons, but a likely
  10104. * one is "no space on disk", http 507. */
  10105. conn->status_code = 507;
  10106. }
  10107. gmt_time_string(date, sizeof(date), &curtime);
  10108. mg_printf(conn,
  10109. "HTTP/1.1 %d %s\r\n",
  10110. conn->status_code,
  10111. mg_get_response_code_text(NULL, conn->status_code));
  10112. send_no_cache_header(conn);
  10113. send_additional_header(conn);
  10114. mg_printf(conn,
  10115. "Date: %s\r\n"
  10116. "Content-Length: 0\r\n"
  10117. "Connection: %s\r\n\r\n",
  10118. date,
  10119. suggest_connection_header(conn));
  10120. }
  10121. static void
  10122. delete_file(struct mg_connection *conn, const char *path)
  10123. {
  10124. struct de de;
  10125. memset(&de.file, 0, sizeof(de.file));
  10126. if (!mg_stat(conn, path, &de.file)) {
  10127. /* mg_stat returns 0 if the file does not exist */
  10128. mg_send_http_error(conn,
  10129. 404,
  10130. "Error: Cannot delete file\nFile %s not found",
  10131. path);
  10132. return;
  10133. }
  10134. #if 0 /* Ignore if a file in memory is inside a folder */
  10135. if (de.access.membuf != NULL) {
  10136. /* the file is cached in memory */
  10137. mg_send_http_error(
  10138. conn,
  10139. 405,
  10140. "Error: Delete not possible\nDeleting %s is not supported",
  10141. path);
  10142. return;
  10143. }
  10144. #endif
  10145. if (de.file.is_directory) {
  10146. if (remove_directory(conn, path)) {
  10147. /* Delete is successful: Return 204 without content. */
  10148. mg_send_http_error(conn, 204, "%s", "");
  10149. } else {
  10150. /* Delete is not successful: Return 500 (Server error). */
  10151. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10152. }
  10153. return;
  10154. }
  10155. /* This is an existing file (not a directory).
  10156. * Check if write permission is granted. */
  10157. if (access(path, W_OK) != 0) {
  10158. /* File is read only */
  10159. mg_send_http_error(
  10160. conn,
  10161. 403,
  10162. "Error: Delete not possible\nDeleting %s is not allowed",
  10163. path);
  10164. return;
  10165. }
  10166. /* Try to delete it. */
  10167. if (mg_remove(conn, path) == 0) {
  10168. /* Delete was successful: Return 204 without content. */
  10169. mg_send_http_error(conn, 204, "%s", "");
  10170. } else {
  10171. /* Delete not successful (file locked). */
  10172. mg_send_http_error(conn,
  10173. 423,
  10174. "Error: Cannot delete file\nremove(%s): %s",
  10175. path,
  10176. strerror(ERRNO));
  10177. }
  10178. }
  10179. #endif /* !NO_FILES */
  10180. #if !defined(NO_FILESYSTEMS)
  10181. static void
  10182. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10183. static void
  10184. do_ssi_include(struct mg_connection *conn,
  10185. const char *ssi,
  10186. char *tag,
  10187. int include_level)
  10188. {
  10189. char file_name[MG_BUF_LEN], path[512], *p;
  10190. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10191. size_t len;
  10192. int truncated = 0;
  10193. if (conn == NULL) {
  10194. return;
  10195. }
  10196. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10197. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10198. * always < MG_BUF_LEN. */
  10199. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10200. /* File name is relative to the webserver root */
  10201. file_name[511] = 0;
  10202. (void)mg_snprintf(conn,
  10203. &truncated,
  10204. path,
  10205. sizeof(path),
  10206. "%s/%s",
  10207. conn->dom_ctx->config[DOCUMENT_ROOT],
  10208. file_name);
  10209. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10210. /* File name is relative to the webserver working directory
  10211. * or it is absolute system path */
  10212. file_name[511] = 0;
  10213. (void)
  10214. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10215. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10216. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10217. /* File name is relative to the currect document */
  10218. file_name[511] = 0;
  10219. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10220. if (!truncated) {
  10221. if ((p = strrchr(path, '/')) != NULL) {
  10222. p[1] = '\0';
  10223. }
  10224. len = strlen(path);
  10225. (void)mg_snprintf(conn,
  10226. &truncated,
  10227. path + len,
  10228. sizeof(path) - len,
  10229. "%s",
  10230. file_name);
  10231. }
  10232. } else {
  10233. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10234. return;
  10235. }
  10236. if (truncated) {
  10237. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10238. return;
  10239. }
  10240. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10241. mg_cry_internal(conn,
  10242. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10243. tag,
  10244. path,
  10245. strerror(ERRNO));
  10246. } else {
  10247. fclose_on_exec(&file.access, conn);
  10248. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10249. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10250. path)
  10251. > 0) {
  10252. send_ssi_file(conn, path, &file, include_level + 1);
  10253. } else {
  10254. send_file_data(conn, &file, 0, INT64_MAX);
  10255. }
  10256. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10257. }
  10258. }
  10259. #if !defined(NO_POPEN)
  10260. static void
  10261. do_ssi_exec(struct mg_connection *conn, char *tag)
  10262. {
  10263. char cmd[1024] = "";
  10264. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10265. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10266. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10267. } else {
  10268. cmd[1023] = 0;
  10269. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10270. mg_cry_internal(conn,
  10271. "Cannot SSI #exec: [%s]: %s",
  10272. cmd,
  10273. strerror(ERRNO));
  10274. } else {
  10275. send_file_data(conn, &file, 0, INT64_MAX);
  10276. pclose(file.access.fp);
  10277. }
  10278. }
  10279. }
  10280. #endif /* !NO_POPEN */
  10281. static int
  10282. mg_fgetc(struct mg_file *filep, int offset)
  10283. {
  10284. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10285. if (filep == NULL) {
  10286. return EOF;
  10287. }
  10288. #if defined(MG_USE_OPEN_FILE)
  10289. if ((filep->access.membuf != NULL) && (offset >= 0)
  10290. && (((unsigned int)(offset)) < filep->stat.size)) {
  10291. return ((const unsigned char *)filep->access.membuf)[offset];
  10292. } else /* else block below */
  10293. #endif
  10294. if (filep->access.fp != NULL) {
  10295. return fgetc(filep->access.fp);
  10296. } else {
  10297. return EOF;
  10298. }
  10299. }
  10300. static void
  10301. send_ssi_file(struct mg_connection *conn,
  10302. const char *path,
  10303. struct mg_file *filep,
  10304. int include_level)
  10305. {
  10306. char buf[MG_BUF_LEN];
  10307. int ch, offset, len, in_tag, in_ssi_tag;
  10308. if (include_level > 10) {
  10309. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10310. return;
  10311. }
  10312. in_tag = in_ssi_tag = len = offset = 0;
  10313. /* Read file, byte by byte, and look for SSI include tags */
  10314. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10315. if (in_tag) {
  10316. /* We are in a tag, either SSI tag or html tag */
  10317. if (ch == '>') {
  10318. /* Tag is closing */
  10319. buf[len++] = '>';
  10320. if (in_ssi_tag) {
  10321. /* Handle SSI tag */
  10322. buf[len] = 0;
  10323. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10324. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10325. #if !defined(NO_POPEN)
  10326. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10327. do_ssi_exec(conn, buf + 9);
  10328. #endif /* !NO_POPEN */
  10329. } else {
  10330. mg_cry_internal(conn,
  10331. "%s: unknown SSI "
  10332. "command: \"%s\"",
  10333. path,
  10334. buf);
  10335. }
  10336. len = 0;
  10337. in_ssi_tag = in_tag = 0;
  10338. } else {
  10339. /* Not an SSI tag */
  10340. /* Flush buffer */
  10341. (void)mg_write(conn, buf, (size_t)len);
  10342. len = 0;
  10343. in_tag = 0;
  10344. }
  10345. } else {
  10346. /* Tag is still open */
  10347. buf[len++] = (char)(ch & 0xff);
  10348. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10349. /* All SSI tags start with <!--# */
  10350. in_ssi_tag = 1;
  10351. }
  10352. if ((len + 2) > (int)sizeof(buf)) {
  10353. /* Tag to long for buffer */
  10354. mg_cry_internal(conn, "%s: tag is too large", path);
  10355. return;
  10356. }
  10357. }
  10358. } else {
  10359. /* We are not in a tag yet. */
  10360. if (ch == '<') {
  10361. /* Tag is opening */
  10362. in_tag = 1;
  10363. if (len > 0) {
  10364. /* Flush current buffer.
  10365. * Buffer is filled with "len" bytes. */
  10366. (void)mg_write(conn, buf, (size_t)len);
  10367. }
  10368. /* Store the < */
  10369. len = 1;
  10370. buf[0] = '<';
  10371. } else {
  10372. /* No Tag */
  10373. /* Add data to buffer */
  10374. buf[len++] = (char)(ch & 0xff);
  10375. /* Flush if buffer is full */
  10376. if (len == (int)sizeof(buf)) {
  10377. mg_write(conn, buf, (size_t)len);
  10378. len = 0;
  10379. }
  10380. }
  10381. }
  10382. }
  10383. /* Send the rest of buffered data */
  10384. if (len > 0) {
  10385. mg_write(conn, buf, (size_t)len);
  10386. }
  10387. }
  10388. static void
  10389. handle_ssi_file_request(struct mg_connection *conn,
  10390. const char *path,
  10391. struct mg_file *filep)
  10392. {
  10393. char date[64];
  10394. time_t curtime = time(NULL);
  10395. const char *cors_orig_cfg;
  10396. const char *cors1, *cors2, *cors3;
  10397. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10398. return;
  10399. }
  10400. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10401. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10402. /* Cross-origin resource sharing (CORS). */
  10403. cors1 = "Access-Control-Allow-Origin: ";
  10404. cors2 = cors_orig_cfg;
  10405. cors3 = "\r\n";
  10406. } else {
  10407. cors1 = cors2 = cors3 = "";
  10408. }
  10409. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10410. /* File exists (precondition for calling this function),
  10411. * but can not be opened by the server. */
  10412. mg_send_http_error(conn,
  10413. 500,
  10414. "Error: Cannot read file\nfopen(%s): %s",
  10415. path,
  10416. strerror(ERRNO));
  10417. } else {
  10418. conn->must_close = 1;
  10419. gmt_time_string(date, sizeof(date), &curtime);
  10420. fclose_on_exec(&filep->access, conn);
  10421. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10422. send_no_cache_header(conn);
  10423. send_additional_header(conn);
  10424. mg_printf(conn,
  10425. "%s%s%s"
  10426. "Date: %s\r\n"
  10427. "Content-Type: text/html\r\n"
  10428. "Connection: %s\r\n\r\n",
  10429. cors1,
  10430. cors2,
  10431. cors3,
  10432. date,
  10433. suggest_connection_header(conn));
  10434. send_ssi_file(conn, path, filep, 0);
  10435. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10436. }
  10437. }
  10438. #endif /* NO_FILESYSTEMS */
  10439. #if !defined(NO_FILES)
  10440. static void
  10441. send_options(struct mg_connection *conn)
  10442. {
  10443. char date[64];
  10444. time_t curtime = time(NULL);
  10445. if (!conn) {
  10446. return;
  10447. }
  10448. conn->status_code = 200;
  10449. conn->must_close = 1;
  10450. gmt_time_string(date, sizeof(date), &curtime);
  10451. /* We do not set a "Cache-Control" header here, but leave the default.
  10452. * Since browsers do not send an OPTIONS request, we can not test the
  10453. * effect anyway. */
  10454. mg_printf(conn,
  10455. "HTTP/1.1 200 OK\r\n"
  10456. "Date: %s\r\n"
  10457. "Connection: %s\r\n"
  10458. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10459. "PROPFIND, MKCOL\r\n"
  10460. "DAV: 1\r\n",
  10461. date,
  10462. suggest_connection_header(conn));
  10463. send_additional_header(conn);
  10464. mg_printf(conn, "\r\n");
  10465. }
  10466. /* Writes PROPFIND properties for a collection element */
  10467. static int
  10468. print_props(struct mg_connection *conn,
  10469. const char *uri,
  10470. const char *name,
  10471. struct mg_file_stat *filep)
  10472. {
  10473. size_t href_size, i, j;
  10474. int len;
  10475. char *href, mtime[64];
  10476. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10477. return 0;
  10478. }
  10479. /* Estimate worst case size for encoding */
  10480. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10481. href = (char *)mg_malloc(href_size);
  10482. if (href == NULL) {
  10483. return 0;
  10484. }
  10485. len = mg_url_encode(uri, href, href_size);
  10486. if (len >= 0) {
  10487. /* Append an extra string */
  10488. mg_url_encode(name, href + len, href_size - (size_t)len);
  10489. }
  10490. /* Directory separator should be preserved. */
  10491. for (i = j = 0; href[i]; j++) {
  10492. if (!strncmp(href + i, "%2f", 3)) {
  10493. href[j] = '/';
  10494. i += 3;
  10495. } else {
  10496. href[j] = href[i++];
  10497. }
  10498. }
  10499. href[j] = '\0';
  10500. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10501. mg_printf(conn,
  10502. "<d:response>"
  10503. "<d:href>%s</d:href>"
  10504. "<d:propstat>"
  10505. "<d:prop>"
  10506. "<d:resourcetype>%s</d:resourcetype>"
  10507. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10508. "<d:getlastmodified>%s</d:getlastmodified>"
  10509. "</d:prop>"
  10510. "<d:status>HTTP/1.1 200 OK</d:status>"
  10511. "</d:propstat>"
  10512. "</d:response>\n",
  10513. href,
  10514. filep->is_directory ? "<d:collection/>" : "",
  10515. filep->size,
  10516. mtime);
  10517. mg_free(href);
  10518. return 1;
  10519. }
  10520. static int
  10521. print_dav_dir_entry(struct de *de, void *data)
  10522. {
  10523. struct mg_connection *conn = (struct mg_connection *)data;
  10524. if (!de || !conn
  10525. || !print_props(
  10526. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10527. return -1;
  10528. }
  10529. return 0;
  10530. }
  10531. static void
  10532. handle_propfind(struct mg_connection *conn,
  10533. const char *path,
  10534. struct mg_file_stat *filep)
  10535. {
  10536. const char *depth = mg_get_header(conn, "Depth");
  10537. char date[64];
  10538. time_t curtime = time(NULL);
  10539. gmt_time_string(date, sizeof(date), &curtime);
  10540. if (!conn || !path || !filep || !conn->dom_ctx) {
  10541. return;
  10542. }
  10543. conn->must_close = 1;
  10544. conn->status_code = 207;
  10545. mg_printf(conn,
  10546. "HTTP/1.1 207 Multi-Status\r\n"
  10547. "Date: %s\r\n",
  10548. date);
  10549. send_static_cache_header(conn);
  10550. send_additional_header(conn);
  10551. mg_printf(conn,
  10552. "Connection: %s\r\n"
  10553. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10554. suggest_connection_header(conn));
  10555. mg_printf(conn,
  10556. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10557. "<d:multistatus xmlns:d='DAV:'>\n");
  10558. /* Print properties for the requested resource itself */
  10559. print_props(conn, conn->request_info.local_uri, "", filep);
  10560. /* If it is a directory, print directory entries too if Depth is not 0
  10561. */
  10562. if (filep->is_directory
  10563. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10564. "yes")
  10565. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10566. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10567. }
  10568. mg_printf(conn, "%s\n", "</d:multistatus>");
  10569. }
  10570. #endif
  10571. void
  10572. mg_lock_connection(struct mg_connection *conn)
  10573. {
  10574. if (conn) {
  10575. (void)pthread_mutex_lock(&conn->mutex);
  10576. }
  10577. }
  10578. void
  10579. mg_unlock_connection(struct mg_connection *conn)
  10580. {
  10581. if (conn) {
  10582. (void)pthread_mutex_unlock(&conn->mutex);
  10583. }
  10584. }
  10585. void
  10586. mg_lock_context(struct mg_context *ctx)
  10587. {
  10588. if (ctx) {
  10589. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10590. }
  10591. }
  10592. void
  10593. mg_unlock_context(struct mg_context *ctx)
  10594. {
  10595. if (ctx) {
  10596. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10597. }
  10598. }
  10599. #if defined(USE_LUA)
  10600. #include "mod_lua.inl"
  10601. #endif /* USE_LUA */
  10602. #if defined(USE_DUKTAPE)
  10603. #include "mod_duktape.inl"
  10604. #endif /* USE_DUKTAPE */
  10605. #if defined(USE_WEBSOCKET)
  10606. #if !defined(NO_SSL_DL)
  10607. #define SHA_API static
  10608. #include "sha1.inl"
  10609. #endif
  10610. static int
  10611. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10612. {
  10613. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10614. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10615. SHA_CTX sha_ctx;
  10616. int truncated;
  10617. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10618. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10619. if (truncated) {
  10620. conn->must_close = 1;
  10621. return 0;
  10622. }
  10623. DEBUG_TRACE("%s", "Send websocket handshake");
  10624. SHA1_Init(&sha_ctx);
  10625. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10626. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10627. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10628. mg_printf(conn,
  10629. "HTTP/1.1 101 Switching Protocols\r\n"
  10630. "Upgrade: websocket\r\n"
  10631. "Connection: Upgrade\r\n"
  10632. "Sec-WebSocket-Accept: %s\r\n",
  10633. b64_sha);
  10634. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10635. mg_printf(conn,
  10636. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10637. conn->request_info.acceptedWebSocketSubprotocol);
  10638. } else {
  10639. mg_printf(conn, "%s", "\r\n");
  10640. }
  10641. return 1;
  10642. }
  10643. #if !defined(MG_MAX_UNANSWERED_PING)
  10644. /* Configuration of the maximum number of websocket PINGs that might
  10645. * stay unanswered before the connection is considered broken.
  10646. * Note: The name of this define may still change (until it is
  10647. * defined as a compile parameter in a documentation).
  10648. */
  10649. #define MG_MAX_UNANSWERED_PING (5)
  10650. #endif
  10651. static void
  10652. read_websocket(struct mg_connection *conn,
  10653. mg_websocket_data_handler ws_data_handler,
  10654. void *callback_data)
  10655. {
  10656. /* Pointer to the beginning of the portion of the incoming websocket
  10657. * message queue.
  10658. * The original websocket upgrade request is never removed, so the queue
  10659. * begins after it. */
  10660. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10661. int n, error, exit_by_callback;
  10662. int ret;
  10663. /* body_len is the length of the entire queue in bytes
  10664. * len is the length of the current message
  10665. * data_len is the length of the current message's data payload
  10666. * header_len is the length of the current message's header */
  10667. size_t i, len, mask_len = 0, header_len, body_len;
  10668. uint64_t data_len = 0;
  10669. /* "The masking key is a 32-bit value chosen at random by the client."
  10670. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10671. */
  10672. unsigned char mask[4];
  10673. /* data points to the place where the message is stored when passed to
  10674. * the websocket_data callback. This is either mem on the stack, or a
  10675. * dynamically allocated buffer if it is too large. */
  10676. unsigned char mem[4096];
  10677. unsigned char mop; /* mask flag and opcode */
  10678. /* Variables used for connection monitoring */
  10679. double timeout = -1.0;
  10680. int enable_ping_pong = 0;
  10681. int ping_count = 0;
  10682. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10683. enable_ping_pong =
  10684. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10685. "yes");
  10686. }
  10687. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10688. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10689. }
  10690. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10691. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10692. }
  10693. /* Enter data processing loop */
  10694. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10695. conn->request_info.remote_addr,
  10696. conn->request_info.remote_port);
  10697. conn->in_websocket_handling = 1;
  10698. mg_set_thread_name("wsock");
  10699. /* Loop continuously, reading messages from the socket, invoking the
  10700. * callback, and waiting repeatedly until an error occurs. */
  10701. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10702. header_len = 0;
  10703. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10704. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10705. len = buf[1] & 127;
  10706. mask_len = (buf[1] & 128) ? 4 : 0;
  10707. if ((len < 126) && (body_len >= mask_len)) {
  10708. /* inline 7-bit length field */
  10709. data_len = len;
  10710. header_len = 2 + mask_len;
  10711. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10712. /* 16-bit length field */
  10713. header_len = 4 + mask_len;
  10714. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10715. } else if (body_len >= (10 + mask_len)) {
  10716. /* 64-bit length field */
  10717. uint32_t l1, l2;
  10718. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10719. memcpy(&l2, &buf[6], 4);
  10720. header_len = 10 + mask_len;
  10721. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10722. if (data_len > (uint64_t)0x7FFF0000ul) {
  10723. /* no can do */
  10724. mg_cry_internal(
  10725. conn,
  10726. "%s",
  10727. "websocket out of memory; closing connection");
  10728. break;
  10729. }
  10730. }
  10731. }
  10732. if ((header_len > 0) && (body_len >= header_len)) {
  10733. /* Allocate space to hold websocket payload */
  10734. unsigned char *data = mem;
  10735. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10736. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10737. conn->phys_ctx);
  10738. if (data == NULL) {
  10739. /* Allocation failed, exit the loop and then close the
  10740. * connection */
  10741. mg_cry_internal(
  10742. conn,
  10743. "%s",
  10744. "websocket out of memory; closing connection");
  10745. break;
  10746. }
  10747. }
  10748. /* Copy the mask before we shift the queue and destroy it */
  10749. if (mask_len > 0) {
  10750. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10751. } else {
  10752. memset(mask, 0, sizeof(mask));
  10753. }
  10754. /* Read frame payload from the first message in the queue into
  10755. * data and advance the queue by moving the memory in place. */
  10756. DEBUG_ASSERT(body_len >= header_len);
  10757. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10758. mop = buf[0]; /* current mask and opcode */
  10759. /* Overflow case */
  10760. len = body_len - header_len;
  10761. memcpy(data, buf + header_len, len);
  10762. error = 0;
  10763. while ((uint64_t)len < data_len) {
  10764. n = pull_inner(NULL,
  10765. conn,
  10766. (char *)(data + len),
  10767. (int)(data_len - len),
  10768. timeout);
  10769. if (n <= -2) {
  10770. error = 1;
  10771. break;
  10772. } else if (n > 0) {
  10773. len += (size_t)n;
  10774. } else {
  10775. /* Timeout: should retry */
  10776. /* TODO: retry condition */
  10777. }
  10778. }
  10779. if (error) {
  10780. mg_cry_internal(
  10781. conn,
  10782. "%s",
  10783. "Websocket pull failed; closing connection");
  10784. if (data != mem) {
  10785. mg_free(data);
  10786. }
  10787. break;
  10788. }
  10789. conn->data_len = conn->request_len;
  10790. } else {
  10791. mop = buf[0]; /* current mask and opcode, overwritten by
  10792. * memmove() */
  10793. /* Length of the message being read at the front of the
  10794. * queue. Cast to 31 bit is OK, since we limited
  10795. * data_len before. */
  10796. len = (size_t)data_len + header_len;
  10797. /* Copy the data payload into the data pointer for the
  10798. * callback. Cast to 31 bit is OK, since we
  10799. * limited data_len */
  10800. memcpy(data, buf + header_len, (size_t)data_len);
  10801. /* Move the queue forward len bytes */
  10802. memmove(buf, buf + len, body_len - len);
  10803. /* Mark the queue as advanced */
  10804. conn->data_len -= (int)len;
  10805. }
  10806. /* Apply mask if necessary */
  10807. if (mask_len > 0) {
  10808. for (i = 0; i < (size_t)data_len; i++) {
  10809. data[i] ^= mask[i & 3];
  10810. }
  10811. }
  10812. exit_by_callback = 0;
  10813. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10814. /* filter PONG messages */
  10815. DEBUG_TRACE("PONG from %s:%u",
  10816. conn->request_info.remote_addr,
  10817. conn->request_info.remote_port);
  10818. /* No unanwered PINGs left */
  10819. ping_count = 0;
  10820. } else if (enable_ping_pong
  10821. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10822. /* reply PING messages */
  10823. DEBUG_TRACE("Reply PING from %s:%u",
  10824. conn->request_info.remote_addr,
  10825. conn->request_info.remote_port);
  10826. ret = mg_websocket_write(conn,
  10827. MG_WEBSOCKET_OPCODE_PONG,
  10828. (char *)data,
  10829. (size_t)data_len);
  10830. if (ret <= 0) {
  10831. /* Error: send failed */
  10832. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10833. break;
  10834. }
  10835. } else {
  10836. /* Exit the loop if callback signals to exit (server side),
  10837. * or "connection close" opcode received (client side). */
  10838. if ((ws_data_handler != NULL)
  10839. && !ws_data_handler(conn,
  10840. mop,
  10841. (char *)data,
  10842. (size_t)data_len,
  10843. callback_data)) {
  10844. exit_by_callback = 1;
  10845. }
  10846. }
  10847. /* It a buffer has been allocated, free it again */
  10848. if (data != mem) {
  10849. mg_free(data);
  10850. }
  10851. if (exit_by_callback) {
  10852. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10853. conn->request_info.remote_addr,
  10854. conn->request_info.remote_port);
  10855. break;
  10856. }
  10857. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10858. /* Opcode == 8, connection close */
  10859. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10860. conn->request_info.remote_addr,
  10861. conn->request_info.remote_port);
  10862. break;
  10863. }
  10864. /* Not breaking the loop, process next websocket frame. */
  10865. } else {
  10866. /* Read from the socket into the next available location in the
  10867. * message queue. */
  10868. n = pull_inner(NULL,
  10869. conn,
  10870. conn->buf + conn->data_len,
  10871. conn->buf_size - conn->data_len,
  10872. timeout);
  10873. if (n <= -2) {
  10874. /* Error, no bytes read */
  10875. DEBUG_TRACE("PULL from %s:%u failed",
  10876. conn->request_info.remote_addr,
  10877. conn->request_info.remote_port);
  10878. break;
  10879. }
  10880. if (n > 0) {
  10881. conn->data_len += n;
  10882. /* Reset open PING count */
  10883. ping_count = 0;
  10884. } else {
  10885. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10886. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10887. /* Stop sending PING */
  10888. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10889. "- closing connection",
  10890. ping_count,
  10891. conn->request_info.remote_addr,
  10892. conn->request_info.remote_port);
  10893. break;
  10894. }
  10895. if (enable_ping_pong) {
  10896. /* Send Websocket PING message */
  10897. DEBUG_TRACE("PING to %s:%u",
  10898. conn->request_info.remote_addr,
  10899. conn->request_info.remote_port);
  10900. ret = mg_websocket_write(conn,
  10901. MG_WEBSOCKET_OPCODE_PING,
  10902. NULL,
  10903. 0);
  10904. if (ret <= 0) {
  10905. /* Error: send failed */
  10906. DEBUG_TRACE("Send PING failed (%i)", ret);
  10907. break;
  10908. }
  10909. ping_count++;
  10910. }
  10911. }
  10912. /* Timeout: should retry */
  10913. /* TODO: get timeout def */
  10914. }
  10915. }
  10916. }
  10917. /* Leave data processing loop */
  10918. mg_set_thread_name("worker");
  10919. conn->in_websocket_handling = 0;
  10920. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10921. conn->request_info.remote_addr,
  10922. conn->request_info.remote_port);
  10923. }
  10924. static int
  10925. mg_websocket_write_exec(struct mg_connection *conn,
  10926. int opcode,
  10927. const char *data,
  10928. size_t dataLen,
  10929. uint32_t masking_key)
  10930. {
  10931. unsigned char header[14];
  10932. size_t headerLen;
  10933. int retval;
  10934. #if defined(GCC_DIAGNOSTIC)
  10935. /* Disable spurious conversion warning for GCC */
  10936. #pragma GCC diagnostic push
  10937. #pragma GCC diagnostic ignored "-Wconversion"
  10938. #endif
  10939. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10940. #if defined(GCC_DIAGNOSTIC)
  10941. #pragma GCC diagnostic pop
  10942. #endif
  10943. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10944. if (dataLen < 126) {
  10945. /* inline 7-bit length field */
  10946. header[1] = (unsigned char)dataLen;
  10947. headerLen = 2;
  10948. } else if (dataLen <= 0xFFFF) {
  10949. /* 16-bit length field */
  10950. uint16_t len = htons((uint16_t)dataLen);
  10951. header[1] = 126;
  10952. memcpy(header + 2, &len, 2);
  10953. headerLen = 4;
  10954. } else {
  10955. /* 64-bit length field */
  10956. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10957. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10958. header[1] = 127;
  10959. memcpy(header + 2, &len1, 4);
  10960. memcpy(header + 6, &len2, 4);
  10961. headerLen = 10;
  10962. }
  10963. if (masking_key) {
  10964. /* add mask */
  10965. header[1] |= 0x80;
  10966. memcpy(header + headerLen, &masking_key, 4);
  10967. headerLen += 4;
  10968. }
  10969. /* Note that POSIX/Winsock's send() is threadsafe
  10970. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10971. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10972. * push(), although that is only a problem if the packet is large or
  10973. * outgoing buffer is full). */
  10974. /* TODO: Check if this lock should be moved to user land.
  10975. * Currently the server sets this lock for websockets, but
  10976. * not for any other connection. It must be set for every
  10977. * conn read/written by more than one thread, no matter if
  10978. * it is a websocket or regular connection. */
  10979. (void)mg_lock_connection(conn);
  10980. retval = mg_write(conn, header, headerLen);
  10981. if (retval != (int)headerLen) {
  10982. /* Did not send complete header */
  10983. retval = -1;
  10984. } else {
  10985. if (dataLen > 0) {
  10986. retval = mg_write(conn, data, dataLen);
  10987. }
  10988. /* if dataLen == 0, the header length (2) is returned */
  10989. }
  10990. /* TODO: Remove this unlock as well, when lock is removed. */
  10991. mg_unlock_connection(conn);
  10992. return retval;
  10993. }
  10994. int
  10995. mg_websocket_write(struct mg_connection *conn,
  10996. int opcode,
  10997. const char *data,
  10998. size_t dataLen)
  10999. {
  11000. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11001. }
  11002. static void
  11003. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11004. {
  11005. size_t i = 0;
  11006. i = 0;
  11007. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11008. /* Convert in 32 bit words, if data is 4 byte aligned */
  11009. while (i < (in_len - 3)) {
  11010. *(uint32_t *)(void *)(out + i) =
  11011. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11012. i += 4;
  11013. }
  11014. }
  11015. if (i != in_len) {
  11016. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11017. while (i < in_len) {
  11018. *(uint8_t *)(void *)(out + i) =
  11019. *(uint8_t *)(void *)(in + i)
  11020. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11021. i++;
  11022. }
  11023. }
  11024. }
  11025. int
  11026. mg_websocket_client_write(struct mg_connection *conn,
  11027. int opcode,
  11028. const char *data,
  11029. size_t dataLen)
  11030. {
  11031. int retval = -1;
  11032. char *masked_data =
  11033. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11034. uint32_t masking_key = 0;
  11035. if (masked_data == NULL) {
  11036. /* Return -1 in an error case */
  11037. mg_cry_internal(conn,
  11038. "%s",
  11039. "Cannot allocate buffer for masked websocket response: "
  11040. "Out of memory");
  11041. return -1;
  11042. }
  11043. do {
  11044. /* Get a masking key - but not 0 */
  11045. masking_key = (uint32_t)get_random();
  11046. } while (masking_key == 0);
  11047. mask_data(data, dataLen, masking_key, masked_data);
  11048. retval = mg_websocket_write_exec(
  11049. conn, opcode, masked_data, dataLen, masking_key);
  11050. mg_free(masked_data);
  11051. return retval;
  11052. }
  11053. static void
  11054. handle_websocket_request(struct mg_connection *conn,
  11055. const char *path,
  11056. int is_callback_resource,
  11057. struct mg_websocket_subprotocols *subprotocols,
  11058. mg_websocket_connect_handler ws_connect_handler,
  11059. mg_websocket_ready_handler ws_ready_handler,
  11060. mg_websocket_data_handler ws_data_handler,
  11061. mg_websocket_close_handler ws_close_handler,
  11062. void *cbData)
  11063. {
  11064. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11065. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11066. ptrdiff_t lua_websock = 0;
  11067. #if !defined(USE_LUA)
  11068. (void)path;
  11069. #endif
  11070. /* Step 1: Check websocket protocol version. */
  11071. /* Step 1.1: Check Sec-WebSocket-Key. */
  11072. if (!websock_key) {
  11073. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11074. * requires a Sec-WebSocket-Key header.
  11075. */
  11076. /* It could be the hixie draft version
  11077. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11078. */
  11079. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11080. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11081. char key3[8];
  11082. if ((key1 != NULL) && (key2 != NULL)) {
  11083. /* This version uses 8 byte body data in a GET request */
  11084. conn->content_len = 8;
  11085. if (8 == mg_read(conn, key3, 8)) {
  11086. /* This is the hixie version */
  11087. mg_send_http_error(conn,
  11088. 426,
  11089. "%s",
  11090. "Protocol upgrade to RFC 6455 required");
  11091. return;
  11092. }
  11093. }
  11094. /* This is an unknown version */
  11095. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11096. return;
  11097. }
  11098. /* Step 1.2: Check websocket protocol version. */
  11099. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11100. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11101. /* Reject wrong versions */
  11102. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11103. return;
  11104. }
  11105. /* Step 1.3: Could check for "Host", but we do not really nead this
  11106. * value for anything, so just ignore it. */
  11107. /* Step 2: If a callback is responsible, call it. */
  11108. if (is_callback_resource) {
  11109. /* Step 2.1 check and select subprotocol */
  11110. const char *protocols[64]; // max 64 headers
  11111. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11112. "Sec-WebSocket-Protocol",
  11113. protocols,
  11114. 64);
  11115. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11116. int cnt = 0;
  11117. int idx;
  11118. unsigned long len;
  11119. const char *sep, *curSubProtocol,
  11120. *acceptedWebSocketSubprotocol = NULL;
  11121. /* look for matching subprotocol */
  11122. do {
  11123. const char *protocol = protocols[cnt];
  11124. do {
  11125. sep = strchr(protocol, ',');
  11126. curSubProtocol = protocol;
  11127. len = sep ? (unsigned long)(sep - protocol)
  11128. : (unsigned long)strlen(protocol);
  11129. while (sep && isspace((unsigned char)*++sep))
  11130. ; // ignore leading whitespaces
  11131. protocol = sep;
  11132. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11133. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11134. && (strncmp(curSubProtocol,
  11135. subprotocols->subprotocols[idx],
  11136. len)
  11137. == 0)) {
  11138. acceptedWebSocketSubprotocol =
  11139. subprotocols->subprotocols[idx];
  11140. break;
  11141. }
  11142. }
  11143. } while (sep && !acceptedWebSocketSubprotocol);
  11144. } while (++cnt < nbSubprotocolHeader
  11145. && !acceptedWebSocketSubprotocol);
  11146. conn->request_info.acceptedWebSocketSubprotocol =
  11147. acceptedWebSocketSubprotocol;
  11148. } else if (nbSubprotocolHeader > 0) {
  11149. /* keep legacy behavior */
  11150. const char *protocol = protocols[0];
  11151. /* The protocol is a comma separated list of names. */
  11152. /* The server must only return one value from this list. */
  11153. /* First check if it is a list or just a single value. */
  11154. const char *sep = strrchr(protocol, ',');
  11155. if (sep == NULL) {
  11156. /* Just a single protocol -> accept it. */
  11157. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11158. } else {
  11159. /* Multiple protocols -> accept the last one. */
  11160. /* This is just a quick fix if the client offers multiple
  11161. * protocols. The handler should have a list of accepted
  11162. * protocols on his own
  11163. * and use it to select one protocol among those the client
  11164. * has
  11165. * offered.
  11166. */
  11167. while (isspace((unsigned char)*++sep)) {
  11168. ; /* ignore leading whitespaces */
  11169. }
  11170. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11171. }
  11172. }
  11173. if ((ws_connect_handler != NULL)
  11174. && (ws_connect_handler(conn, cbData) != 0)) {
  11175. /* C callback has returned non-zero, do not proceed with
  11176. * handshake.
  11177. */
  11178. /* Note that C callbacks are no longer called when Lua is
  11179. * responsible, so C can no longer filter callbacks for Lua. */
  11180. return;
  11181. }
  11182. }
  11183. #if defined(USE_LUA)
  11184. /* Step 3: No callback. Check if Lua is responsible. */
  11185. else {
  11186. /* Step 3.1: Check if Lua is responsible. */
  11187. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11188. lua_websock = match_prefix(
  11189. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11190. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11191. path);
  11192. }
  11193. if (lua_websock) {
  11194. /* Step 3.2: Lua is responsible: call it. */
  11195. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11196. if (!conn->lua_websocket_state) {
  11197. /* Lua rejected the new client */
  11198. return;
  11199. }
  11200. }
  11201. }
  11202. #endif
  11203. /* Step 4: Check if there is a responsible websocket handler. */
  11204. if (!is_callback_resource && !lua_websock) {
  11205. /* There is no callback, and Lua is not responsible either. */
  11206. /* Reply with a 404 Not Found. We are still at a standard
  11207. * HTTP request here, before the websocket handshake, so
  11208. * we can still send standard HTTP error replies. */
  11209. mg_send_http_error(conn, 404, "%s", "Not found");
  11210. return;
  11211. }
  11212. /* Step 5: The websocket connection has been accepted */
  11213. if (!send_websocket_handshake(conn, websock_key)) {
  11214. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11215. return;
  11216. }
  11217. /* Step 6: Call the ready handler */
  11218. if (is_callback_resource) {
  11219. if (ws_ready_handler != NULL) {
  11220. ws_ready_handler(conn, cbData);
  11221. }
  11222. #if defined(USE_LUA)
  11223. } else if (lua_websock) {
  11224. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11225. /* the ready handler returned false */
  11226. return;
  11227. }
  11228. #endif
  11229. }
  11230. /* Step 7: Enter the read loop */
  11231. if (is_callback_resource) {
  11232. read_websocket(conn, ws_data_handler, cbData);
  11233. #if defined(USE_LUA)
  11234. } else if (lua_websock) {
  11235. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11236. #endif
  11237. }
  11238. /* Step 8: Call the close handler */
  11239. if (ws_close_handler) {
  11240. ws_close_handler(conn, cbData);
  11241. }
  11242. }
  11243. static int
  11244. is_websocket_protocol(const struct mg_connection *conn)
  11245. {
  11246. const char *upgrade, *connection;
  11247. /* A websocket protocoll has the following HTTP headers:
  11248. *
  11249. * Connection: Upgrade
  11250. * Upgrade: Websocket
  11251. */
  11252. upgrade = mg_get_header(conn, "Upgrade");
  11253. if (upgrade == NULL) {
  11254. return 0; /* fail early, don't waste time checking other header
  11255. * fields
  11256. */
  11257. }
  11258. DEBUG_TRACE("Upgrade: %s", upgrade);
  11259. if (!mg_strcasestr(upgrade, "websocket")) {
  11260. return 0;
  11261. }
  11262. connection = mg_get_header(conn, "Connection");
  11263. if (connection == NULL) {
  11264. return 0;
  11265. }
  11266. if (!mg_strcasestr(connection, "upgrade")) {
  11267. return 0;
  11268. }
  11269. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11270. * "Sec-WebSocket-Version" are also required.
  11271. * Don't check them here, since even an unsupported websocket protocol
  11272. * request still IS a websocket request (in contrast to a standard HTTP
  11273. * request). It will fail later in handle_websocket_request.
  11274. */
  11275. return 1;
  11276. }
  11277. #endif /* !USE_WEBSOCKET */
  11278. static int
  11279. isbyte(int n)
  11280. {
  11281. return (n >= 0) && (n <= 255);
  11282. }
  11283. static int
  11284. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11285. {
  11286. int n, a, b, c, d, slash = 32, len = 0;
  11287. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11288. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11289. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11290. && (slash < 33)) {
  11291. len = n;
  11292. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11293. | (uint32_t)d;
  11294. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11295. }
  11296. return len;
  11297. }
  11298. static int
  11299. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11300. {
  11301. int throttle = 0;
  11302. struct vec vec, val;
  11303. uint32_t net, mask;
  11304. char mult;
  11305. double v;
  11306. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11307. mult = ',';
  11308. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11309. || (v < 0)
  11310. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11311. && (mult != ','))) {
  11312. continue;
  11313. }
  11314. v *= (lowercase(&mult) == 'k')
  11315. ? 1024
  11316. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11317. if (vec.len == 1 && vec.ptr[0] == '*') {
  11318. throttle = (int)v;
  11319. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11320. if ((remote_ip & mask) == net) {
  11321. throttle = (int)v;
  11322. }
  11323. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11324. throttle = (int)v;
  11325. }
  11326. }
  11327. return throttle;
  11328. }
  11329. static uint32_t
  11330. get_remote_ip(const struct mg_connection *conn)
  11331. {
  11332. if (!conn) {
  11333. return 0;
  11334. }
  11335. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11336. }
  11337. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11338. #include "handle_form.inl"
  11339. #if defined(MG_LEGACY_INTERFACE)
  11340. /* Implement the deprecated mg_upload function by calling the new
  11341. * mg_handle_form_request function. While mg_upload could only handle
  11342. * HTML forms sent as POST request in multipart/form-data format
  11343. * containing only file input elements, mg_handle_form_request can
  11344. * handle all form input elements and all standard request methods. */
  11345. struct mg_upload_user_data {
  11346. struct mg_connection *conn;
  11347. const char *destination_dir;
  11348. int num_uploaded_files;
  11349. };
  11350. /* Helper function for deprecated mg_upload. */
  11351. static int
  11352. mg_upload_field_found(const char *key,
  11353. const char *filename,
  11354. char *path,
  11355. size_t pathlen,
  11356. void *user_data)
  11357. {
  11358. int truncated = 0;
  11359. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11360. (void)key;
  11361. if (!filename) {
  11362. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11363. return FORM_FIELD_STORAGE_ABORT;
  11364. }
  11365. mg_snprintf(fud->conn,
  11366. &truncated,
  11367. path,
  11368. pathlen - 1,
  11369. "%s/%s",
  11370. fud->destination_dir,
  11371. filename);
  11372. if (truncated) {
  11373. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11374. return FORM_FIELD_STORAGE_ABORT;
  11375. }
  11376. return FORM_FIELD_STORAGE_STORE;
  11377. }
  11378. /* Helper function for deprecated mg_upload. */
  11379. static int
  11380. mg_upload_field_get(const char *key,
  11381. const char *value,
  11382. size_t value_size,
  11383. void *user_data)
  11384. {
  11385. /* Function should never be called */
  11386. (void)key;
  11387. (void)value;
  11388. (void)value_size;
  11389. (void)user_data;
  11390. return 0;
  11391. }
  11392. /* Helper function for deprecated mg_upload. */
  11393. static int
  11394. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11395. {
  11396. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11397. (void)file_size;
  11398. fud->num_uploaded_files++;
  11399. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11400. return 0;
  11401. }
  11402. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11403. int
  11404. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11405. {
  11406. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11407. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11408. mg_upload_field_get,
  11409. mg_upload_field_stored,
  11410. 0};
  11411. int ret;
  11412. fdh.user_data = (void *)&fud;
  11413. ret = mg_handle_form_request(conn, &fdh);
  11414. if (ret < 0) {
  11415. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11416. }
  11417. return fud.num_uploaded_files;
  11418. }
  11419. #endif
  11420. static int
  11421. get_first_ssl_listener_index(const struct mg_context *ctx)
  11422. {
  11423. unsigned int i;
  11424. int idx = -1;
  11425. if (ctx) {
  11426. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11427. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11428. }
  11429. }
  11430. return idx;
  11431. }
  11432. /* Return host (without port) */
  11433. /* Use mg_free to free the result */
  11434. static const char *
  11435. alloc_get_host(struct mg_connection *conn)
  11436. {
  11437. char buf[1025];
  11438. size_t buflen = sizeof(buf);
  11439. const char *host_header = get_header(conn->request_info.http_headers,
  11440. conn->request_info.num_headers,
  11441. "Host");
  11442. char *host;
  11443. if (host_header != NULL) {
  11444. char *pos;
  11445. /* Create a local copy of the "Host" header, since it might be
  11446. * modified here. */
  11447. mg_strlcpy(buf, host_header, buflen);
  11448. buf[buflen - 1] = '\0';
  11449. host = buf;
  11450. while (isspace((unsigned char)*host)) {
  11451. host++;
  11452. }
  11453. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11454. * is found. */
  11455. if (*host == '[') {
  11456. pos = strchr(host, ']');
  11457. if (!pos) {
  11458. /* Malformed hostname starts with '[', but no ']' found */
  11459. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11460. return NULL;
  11461. }
  11462. /* terminate after ']' */
  11463. pos[1] = 0;
  11464. } else {
  11465. /* Otherwise, a ':' separates hostname and port number */
  11466. pos = strchr(host, ':');
  11467. if (pos != NULL) {
  11468. *pos = '\0';
  11469. }
  11470. }
  11471. if (conn->ssl) {
  11472. /* This is a HTTPS connection, maybe we have a hostname
  11473. * from SNI (set in ssl_servername_callback). */
  11474. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11475. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11476. /* We are not using the default domain */
  11477. if (mg_strcasecmp(host, sslhost)) {
  11478. /* Mismatch between SNI domain and HTTP domain */
  11479. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11480. sslhost,
  11481. host);
  11482. return NULL;
  11483. }
  11484. }
  11485. DEBUG_TRACE("HTTPS Host: %s", host);
  11486. } else {
  11487. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11488. while (dom) {
  11489. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11490. /* Found matching domain */
  11491. DEBUG_TRACE("HTTP domain %s found",
  11492. dom->config[AUTHENTICATION_DOMAIN]);
  11493. /* TODO: Check if this is a HTTP or HTTPS domain */
  11494. conn->dom_ctx = dom;
  11495. break;
  11496. }
  11497. dom = dom->next;
  11498. }
  11499. DEBUG_TRACE("HTTP Host: %s", host);
  11500. }
  11501. } else {
  11502. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11503. host = buf;
  11504. DEBUG_TRACE("IP: %s", host);
  11505. }
  11506. return mg_strdup_ctx(host, conn->phys_ctx);
  11507. }
  11508. static void
  11509. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11510. {
  11511. char target_url[MG_BUF_LEN];
  11512. int truncated = 0;
  11513. conn->must_close = 1;
  11514. /* Send host, port, uri and (if it exists) ?query_string */
  11515. if (conn->host) {
  11516. /* Use "308 Permanent Redirect" */
  11517. int redirect_code = 308;
  11518. /* Create target URL */
  11519. mg_snprintf(
  11520. conn,
  11521. &truncated,
  11522. target_url,
  11523. sizeof(target_url),
  11524. "https://%s:%d%s%s%s",
  11525. conn->host,
  11526. #if defined(USE_IPV6)
  11527. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11528. == AF_INET6)
  11529. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11530. .lsa.sin6.sin6_port)
  11531. :
  11532. #endif
  11533. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11534. .lsa.sin.sin_port),
  11535. conn->request_info.local_uri,
  11536. (conn->request_info.query_string == NULL) ? "" : "?",
  11537. (conn->request_info.query_string == NULL)
  11538. ? ""
  11539. : conn->request_info.query_string);
  11540. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11541. * is used as buffer size) */
  11542. if (truncated) {
  11543. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11544. return;
  11545. }
  11546. /* Use redirect helper function */
  11547. mg_send_http_redirect(conn, target_url, redirect_code);
  11548. }
  11549. }
  11550. static void
  11551. handler_info_acquire(struct mg_handler_info *handler_info)
  11552. {
  11553. pthread_mutex_lock(&handler_info->refcount_mutex);
  11554. handler_info->refcount++;
  11555. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11556. }
  11557. static void
  11558. handler_info_release(struct mg_handler_info *handler_info)
  11559. {
  11560. pthread_mutex_lock(&handler_info->refcount_mutex);
  11561. handler_info->refcount--;
  11562. pthread_cond_signal(&handler_info->refcount_cond);
  11563. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11564. }
  11565. static void
  11566. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11567. {
  11568. pthread_mutex_lock(&handler_info->refcount_mutex);
  11569. while (handler_info->refcount) {
  11570. pthread_cond_wait(&handler_info->refcount_cond,
  11571. &handler_info->refcount_mutex);
  11572. }
  11573. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11574. }
  11575. static void
  11576. mg_set_handler_type(struct mg_context *phys_ctx,
  11577. struct mg_domain_context *dom_ctx,
  11578. const char *uri,
  11579. int handler_type,
  11580. int is_delete_request,
  11581. mg_request_handler handler,
  11582. struct mg_websocket_subprotocols *subprotocols,
  11583. mg_websocket_connect_handler connect_handler,
  11584. mg_websocket_ready_handler ready_handler,
  11585. mg_websocket_data_handler data_handler,
  11586. mg_websocket_close_handler close_handler,
  11587. mg_authorization_handler auth_handler,
  11588. void *cbdata)
  11589. {
  11590. struct mg_handler_info *tmp_rh, **lastref;
  11591. size_t urilen = strlen(uri);
  11592. struct mg_workerTLS tls;
  11593. int is_tls_set = 0;
  11594. if (handler_type == WEBSOCKET_HANDLER) {
  11595. DEBUG_ASSERT(handler == NULL);
  11596. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11597. || ready_handler != NULL || data_handler != NULL
  11598. || close_handler != NULL);
  11599. DEBUG_ASSERT(auth_handler == NULL);
  11600. if (handler != NULL) {
  11601. return;
  11602. }
  11603. if (!is_delete_request && (connect_handler == NULL)
  11604. && (ready_handler == NULL) && (data_handler == NULL)
  11605. && (close_handler == NULL)) {
  11606. return;
  11607. }
  11608. if (auth_handler != NULL) {
  11609. return;
  11610. }
  11611. } else if (handler_type == REQUEST_HANDLER) {
  11612. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11613. && data_handler == NULL && close_handler == NULL);
  11614. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11615. DEBUG_ASSERT(auth_handler == NULL);
  11616. if ((connect_handler != NULL) || (ready_handler != NULL)
  11617. || (data_handler != NULL) || (close_handler != NULL)) {
  11618. return;
  11619. }
  11620. if (!is_delete_request && (handler == NULL)) {
  11621. return;
  11622. }
  11623. if (auth_handler != NULL) {
  11624. return;
  11625. }
  11626. } else { /* AUTH_HANDLER */
  11627. DEBUG_ASSERT(handler == NULL);
  11628. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11629. && data_handler == NULL && close_handler == NULL);
  11630. DEBUG_ASSERT(auth_handler != NULL);
  11631. if (handler != NULL) {
  11632. return;
  11633. }
  11634. if ((connect_handler != NULL) || (ready_handler != NULL)
  11635. || (data_handler != NULL) || (close_handler != NULL)) {
  11636. return;
  11637. }
  11638. if (!is_delete_request && (auth_handler == NULL)) {
  11639. return;
  11640. }
  11641. }
  11642. if (!phys_ctx || !dom_ctx) {
  11643. return;
  11644. }
  11645. /* Internal callbacks have their contexts set
  11646. * if called from non-related thread, context must be set
  11647. * since internal function assumes it exists.
  11648. * For an example see how handler_info_wait_unused()
  11649. * waits for reference to become zero
  11650. */
  11651. if (NULL == pthread_getspecific(sTlsKey)) {
  11652. is_tls_set = 1;
  11653. tls.is_master = -1;
  11654. tls.thread_idx = phys_ctx->starter_thread_idx;
  11655. #if defined(_WIN32)
  11656. tls.pthread_cond_helper_mutex = NULL;
  11657. #endif
  11658. pthread_setspecific(sTlsKey, &tls);
  11659. }
  11660. mg_lock_context(phys_ctx);
  11661. /* first try to find an existing handler */
  11662. lastref = &(dom_ctx->handlers);
  11663. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11664. if (tmp_rh->handler_type == handler_type) {
  11665. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11666. if (!is_delete_request) {
  11667. /* update existing handler */
  11668. if (handler_type == REQUEST_HANDLER) {
  11669. /* Wait for end of use before updating */
  11670. handler_info_wait_unused(tmp_rh);
  11671. /* Ok, the handler is no more use -> Update it */
  11672. tmp_rh->handler = handler;
  11673. } else if (handler_type == WEBSOCKET_HANDLER) {
  11674. tmp_rh->subprotocols = subprotocols;
  11675. tmp_rh->connect_handler = connect_handler;
  11676. tmp_rh->ready_handler = ready_handler;
  11677. tmp_rh->data_handler = data_handler;
  11678. tmp_rh->close_handler = close_handler;
  11679. } else { /* AUTH_HANDLER */
  11680. tmp_rh->auth_handler = auth_handler;
  11681. }
  11682. tmp_rh->cbdata = cbdata;
  11683. } else {
  11684. /* remove existing handler */
  11685. if (handler_type == REQUEST_HANDLER) {
  11686. /* Wait for end of use before removing */
  11687. handler_info_wait_unused(tmp_rh);
  11688. /* Ok, the handler is no more used -> Destroy resources
  11689. */
  11690. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11691. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11692. }
  11693. *lastref = tmp_rh->next;
  11694. mg_free(tmp_rh->uri);
  11695. mg_free(tmp_rh);
  11696. }
  11697. mg_unlock_context(phys_ctx);
  11698. if (is_tls_set) {
  11699. pthread_setspecific(sTlsKey, NULL);
  11700. }
  11701. return;
  11702. }
  11703. }
  11704. lastref = &(tmp_rh->next);
  11705. }
  11706. if (is_delete_request) {
  11707. /* no handler to set, this was a remove request to a non-existing
  11708. * handler */
  11709. mg_unlock_context(phys_ctx);
  11710. if (is_tls_set) {
  11711. pthread_setspecific(sTlsKey, NULL);
  11712. }
  11713. return;
  11714. }
  11715. tmp_rh =
  11716. (struct mg_handler_info *)mg_calloc_ctx(1,
  11717. sizeof(struct mg_handler_info),
  11718. phys_ctx);
  11719. if (tmp_rh == NULL) {
  11720. mg_unlock_context(phys_ctx);
  11721. mg_cry_ctx_internal(phys_ctx,
  11722. "%s",
  11723. "Cannot create new request handler struct, OOM");
  11724. if (is_tls_set) {
  11725. pthread_setspecific(sTlsKey, NULL);
  11726. }
  11727. return;
  11728. }
  11729. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11730. if (!tmp_rh->uri) {
  11731. mg_unlock_context(phys_ctx);
  11732. mg_free(tmp_rh);
  11733. mg_cry_ctx_internal(phys_ctx,
  11734. "%s",
  11735. "Cannot create new request handler struct, OOM");
  11736. if (is_tls_set) {
  11737. pthread_setspecific(sTlsKey, NULL);
  11738. }
  11739. return;
  11740. }
  11741. tmp_rh->uri_len = urilen;
  11742. if (handler_type == REQUEST_HANDLER) {
  11743. /* Init refcount mutex and condition */
  11744. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11745. mg_unlock_context(phys_ctx);
  11746. mg_free(tmp_rh);
  11747. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11748. if (is_tls_set) {
  11749. pthread_setspecific(sTlsKey, NULL);
  11750. }
  11751. return;
  11752. }
  11753. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11754. mg_unlock_context(phys_ctx);
  11755. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11756. mg_free(tmp_rh);
  11757. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11758. if (is_tls_set) {
  11759. pthread_setspecific(sTlsKey, NULL);
  11760. }
  11761. return;
  11762. }
  11763. tmp_rh->refcount = 0;
  11764. tmp_rh->handler = handler;
  11765. } else if (handler_type == WEBSOCKET_HANDLER) {
  11766. tmp_rh->subprotocols = subprotocols;
  11767. tmp_rh->connect_handler = connect_handler;
  11768. tmp_rh->ready_handler = ready_handler;
  11769. tmp_rh->data_handler = data_handler;
  11770. tmp_rh->close_handler = close_handler;
  11771. } else { /* AUTH_HANDLER */
  11772. tmp_rh->auth_handler = auth_handler;
  11773. }
  11774. tmp_rh->cbdata = cbdata;
  11775. tmp_rh->handler_type = handler_type;
  11776. tmp_rh->next = NULL;
  11777. *lastref = tmp_rh;
  11778. mg_unlock_context(phys_ctx);
  11779. if (is_tls_set) {
  11780. pthread_setspecific(sTlsKey, NULL);
  11781. }
  11782. }
  11783. void
  11784. mg_set_request_handler(struct mg_context *ctx,
  11785. const char *uri,
  11786. mg_request_handler handler,
  11787. void *cbdata)
  11788. {
  11789. mg_set_handler_type(ctx,
  11790. &(ctx->dd),
  11791. uri,
  11792. REQUEST_HANDLER,
  11793. handler == NULL,
  11794. handler,
  11795. NULL,
  11796. NULL,
  11797. NULL,
  11798. NULL,
  11799. NULL,
  11800. NULL,
  11801. cbdata);
  11802. }
  11803. void
  11804. mg_set_websocket_handler(struct mg_context *ctx,
  11805. const char *uri,
  11806. mg_websocket_connect_handler connect_handler,
  11807. mg_websocket_ready_handler ready_handler,
  11808. mg_websocket_data_handler data_handler,
  11809. mg_websocket_close_handler close_handler,
  11810. void *cbdata)
  11811. {
  11812. mg_set_websocket_handler_with_subprotocols(ctx,
  11813. uri,
  11814. NULL,
  11815. connect_handler,
  11816. ready_handler,
  11817. data_handler,
  11818. close_handler,
  11819. cbdata);
  11820. }
  11821. void
  11822. mg_set_websocket_handler_with_subprotocols(
  11823. struct mg_context *ctx,
  11824. const char *uri,
  11825. struct mg_websocket_subprotocols *subprotocols,
  11826. mg_websocket_connect_handler connect_handler,
  11827. mg_websocket_ready_handler ready_handler,
  11828. mg_websocket_data_handler data_handler,
  11829. mg_websocket_close_handler close_handler,
  11830. void *cbdata)
  11831. {
  11832. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11833. && (data_handler == NULL)
  11834. && (close_handler == NULL);
  11835. mg_set_handler_type(ctx,
  11836. &(ctx->dd),
  11837. uri,
  11838. WEBSOCKET_HANDLER,
  11839. is_delete_request,
  11840. NULL,
  11841. subprotocols,
  11842. connect_handler,
  11843. ready_handler,
  11844. data_handler,
  11845. close_handler,
  11846. NULL,
  11847. cbdata);
  11848. }
  11849. void
  11850. mg_set_auth_handler(struct mg_context *ctx,
  11851. const char *uri,
  11852. mg_authorization_handler handler,
  11853. void *cbdata)
  11854. {
  11855. mg_set_handler_type(ctx,
  11856. &(ctx->dd),
  11857. uri,
  11858. AUTH_HANDLER,
  11859. handler == NULL,
  11860. NULL,
  11861. NULL,
  11862. NULL,
  11863. NULL,
  11864. NULL,
  11865. NULL,
  11866. handler,
  11867. cbdata);
  11868. }
  11869. static int
  11870. get_request_handler(struct mg_connection *conn,
  11871. int handler_type,
  11872. mg_request_handler *handler,
  11873. struct mg_websocket_subprotocols **subprotocols,
  11874. mg_websocket_connect_handler *connect_handler,
  11875. mg_websocket_ready_handler *ready_handler,
  11876. mg_websocket_data_handler *data_handler,
  11877. mg_websocket_close_handler *close_handler,
  11878. mg_authorization_handler *auth_handler,
  11879. void **cbdata,
  11880. struct mg_handler_info **handler_info)
  11881. {
  11882. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11883. if (request_info) {
  11884. const char *uri = request_info->local_uri;
  11885. size_t urilen = strlen(uri);
  11886. struct mg_handler_info *tmp_rh;
  11887. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11888. return 0;
  11889. }
  11890. mg_lock_context(conn->phys_ctx);
  11891. /* first try for an exact match */
  11892. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11893. tmp_rh = tmp_rh->next) {
  11894. if (tmp_rh->handler_type == handler_type) {
  11895. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11896. if (handler_type == WEBSOCKET_HANDLER) {
  11897. *subprotocols = tmp_rh->subprotocols;
  11898. *connect_handler = tmp_rh->connect_handler;
  11899. *ready_handler = tmp_rh->ready_handler;
  11900. *data_handler = tmp_rh->data_handler;
  11901. *close_handler = tmp_rh->close_handler;
  11902. } else if (handler_type == REQUEST_HANDLER) {
  11903. *handler = tmp_rh->handler;
  11904. /* Acquire handler and give it back */
  11905. handler_info_acquire(tmp_rh);
  11906. *handler_info = tmp_rh;
  11907. } else { /* AUTH_HANDLER */
  11908. *auth_handler = tmp_rh->auth_handler;
  11909. }
  11910. *cbdata = tmp_rh->cbdata;
  11911. mg_unlock_context(conn->phys_ctx);
  11912. return 1;
  11913. }
  11914. }
  11915. }
  11916. /* next try for a partial match, we will accept uri/something */
  11917. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11918. tmp_rh = tmp_rh->next) {
  11919. if (tmp_rh->handler_type == handler_type) {
  11920. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11921. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11922. if (handler_type == WEBSOCKET_HANDLER) {
  11923. *subprotocols = tmp_rh->subprotocols;
  11924. *connect_handler = tmp_rh->connect_handler;
  11925. *ready_handler = tmp_rh->ready_handler;
  11926. *data_handler = tmp_rh->data_handler;
  11927. *close_handler = tmp_rh->close_handler;
  11928. } else if (handler_type == REQUEST_HANDLER) {
  11929. *handler = tmp_rh->handler;
  11930. /* Acquire handler and give it back */
  11931. handler_info_acquire(tmp_rh);
  11932. *handler_info = tmp_rh;
  11933. } else { /* AUTH_HANDLER */
  11934. *auth_handler = tmp_rh->auth_handler;
  11935. }
  11936. *cbdata = tmp_rh->cbdata;
  11937. mg_unlock_context(conn->phys_ctx);
  11938. return 1;
  11939. }
  11940. }
  11941. }
  11942. /* finally try for pattern match */
  11943. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11944. tmp_rh = tmp_rh->next) {
  11945. if (tmp_rh->handler_type == handler_type) {
  11946. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11947. if (handler_type == WEBSOCKET_HANDLER) {
  11948. *subprotocols = tmp_rh->subprotocols;
  11949. *connect_handler = tmp_rh->connect_handler;
  11950. *ready_handler = tmp_rh->ready_handler;
  11951. *data_handler = tmp_rh->data_handler;
  11952. *close_handler = tmp_rh->close_handler;
  11953. } else if (handler_type == REQUEST_HANDLER) {
  11954. *handler = tmp_rh->handler;
  11955. /* Acquire handler and give it back */
  11956. handler_info_acquire(tmp_rh);
  11957. *handler_info = tmp_rh;
  11958. } else { /* AUTH_HANDLER */
  11959. *auth_handler = tmp_rh->auth_handler;
  11960. }
  11961. *cbdata = tmp_rh->cbdata;
  11962. mg_unlock_context(conn->phys_ctx);
  11963. return 1;
  11964. }
  11965. }
  11966. }
  11967. mg_unlock_context(conn->phys_ctx);
  11968. }
  11969. return 0; /* none found */
  11970. }
  11971. /* Check if the script file is in a path, allowed for script files.
  11972. * This can be used if uploading files is possible not only for the server
  11973. * admin, and the upload mechanism does not check the file extension.
  11974. */
  11975. static int
  11976. is_in_script_path(const struct mg_connection *conn, const char *path)
  11977. {
  11978. /* TODO (Feature): Add config value for allowed script path.
  11979. * Default: All allowed. */
  11980. (void)conn;
  11981. (void)path;
  11982. return 1;
  11983. }
  11984. #if defined(USE_WEBSOCKET) \
  11985. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  11986. static int
  11987. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11988. void *cbdata)
  11989. {
  11990. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11991. if (pcallbacks->websocket_connect) {
  11992. return pcallbacks->websocket_connect(conn);
  11993. }
  11994. /* No handler set - assume "OK" */
  11995. return 0;
  11996. }
  11997. static void
  11998. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11999. {
  12000. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12001. if (pcallbacks->websocket_ready) {
  12002. pcallbacks->websocket_ready(conn);
  12003. }
  12004. }
  12005. static int
  12006. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12007. int bits,
  12008. char *data,
  12009. size_t len,
  12010. void *cbdata)
  12011. {
  12012. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12013. if (pcallbacks->websocket_data) {
  12014. return pcallbacks->websocket_data(conn, bits, data, len);
  12015. }
  12016. /* No handler set - assume "OK" */
  12017. return 1;
  12018. }
  12019. static void
  12020. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12021. void *cbdata)
  12022. {
  12023. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12024. if (pcallbacks->connection_close) {
  12025. pcallbacks->connection_close(conn);
  12026. }
  12027. }
  12028. #endif
  12029. /* This is the heart of the Civetweb's logic.
  12030. * This function is called when the request is read, parsed and validated,
  12031. * and Civetweb must decide what action to take: serve a file, or
  12032. * a directory, or call embedded function, etcetera. */
  12033. static void
  12034. handle_request(struct mg_connection *conn)
  12035. {
  12036. struct mg_request_info *ri = &conn->request_info;
  12037. char path[PATH_MAX];
  12038. int uri_len, ssl_index;
  12039. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12040. is_put_or_delete_request = 0, is_callback_resource = 0;
  12041. int i;
  12042. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12043. mg_request_handler callback_handler = NULL;
  12044. struct mg_handler_info *handler_info = NULL;
  12045. struct mg_websocket_subprotocols *subprotocols;
  12046. mg_websocket_connect_handler ws_connect_handler = NULL;
  12047. mg_websocket_ready_handler ws_ready_handler = NULL;
  12048. mg_websocket_data_handler ws_data_handler = NULL;
  12049. mg_websocket_close_handler ws_close_handler = NULL;
  12050. void *callback_data = NULL;
  12051. mg_authorization_handler auth_handler = NULL;
  12052. void *auth_callback_data = NULL;
  12053. int handler_type;
  12054. time_t curtime = time(NULL);
  12055. char date[64];
  12056. path[0] = 0;
  12057. /* 1. get the request url */
  12058. /* 1.1. split into url and query string */
  12059. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12060. != NULL) {
  12061. *((char *)conn->request_info.query_string++) = '\0';
  12062. }
  12063. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12064. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12065. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12066. if (ssl_index >= 0) {
  12067. redirect_to_https_port(conn, ssl_index);
  12068. } else {
  12069. /* A http to https forward port has been specified,
  12070. * but no https port to forward to. */
  12071. mg_send_http_error(conn,
  12072. 503,
  12073. "%s",
  12074. "Error: SSL forward not configured properly");
  12075. mg_cry_internal(conn,
  12076. "%s",
  12077. "Can not redirect to SSL, no SSL port available");
  12078. }
  12079. return;
  12080. }
  12081. uri_len = (int)strlen(ri->local_uri);
  12082. /* 1.3. decode url (if config says so) */
  12083. if (should_decode_url(conn)) {
  12084. mg_url_decode(
  12085. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12086. }
  12087. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12088. * not possible */
  12089. remove_dot_segments((char *)ri->local_uri);
  12090. /* step 1. completed, the url is known now */
  12091. uri_len = (int)strlen(ri->local_uri);
  12092. DEBUG_TRACE("URL: %s", ri->local_uri);
  12093. /* 2. if this ip has limited speed, set it for this connection */
  12094. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12095. get_remote_ip(conn),
  12096. ri->local_uri);
  12097. /* 3. call a "handle everything" callback, if registered */
  12098. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12099. /* Note that since V1.7 the "begin_request" function is called
  12100. * before an authorization check. If an authorization check is
  12101. * required, use a request_handler instead. */
  12102. i = conn->phys_ctx->callbacks.begin_request(conn);
  12103. if (i > 0) {
  12104. /* callback already processed the request. Store the
  12105. return value as a status code for the access log. */
  12106. conn->status_code = i;
  12107. if (!conn->must_close) {
  12108. discard_unread_request_data(conn);
  12109. }
  12110. return;
  12111. } else if (i == 0) {
  12112. /* civetweb should process the request */
  12113. } else {
  12114. /* unspecified - may change with the next version */
  12115. return;
  12116. }
  12117. }
  12118. /* request not yet handled by a handler or redirect, so the request
  12119. * is processed here */
  12120. /* 4. Check for CORS preflight requests and handle them (if configured).
  12121. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12122. */
  12123. if (!strcmp(ri->request_method, "OPTIONS")) {
  12124. /* Send a response to CORS preflights only if
  12125. * access_control_allow_methods is not NULL and not an empty string.
  12126. * In this case, scripts can still handle CORS. */
  12127. const char *cors_meth_cfg =
  12128. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12129. const char *cors_orig_cfg =
  12130. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12131. const char *cors_origin =
  12132. get_header(ri->http_headers, ri->num_headers, "Origin");
  12133. const char *cors_acrm = get_header(ri->http_headers,
  12134. ri->num_headers,
  12135. "Access-Control-Request-Method");
  12136. /* Todo: check if cors_origin is in cors_orig_cfg.
  12137. * Or, let the client check this. */
  12138. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12139. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12140. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12141. /* This is a valid CORS preflight, and the server is configured
  12142. * to
  12143. * handle it automatically. */
  12144. const char *cors_acrh =
  12145. get_header(ri->http_headers,
  12146. ri->num_headers,
  12147. "Access-Control-Request-Headers");
  12148. gmt_time_string(date, sizeof(date), &curtime);
  12149. mg_printf(conn,
  12150. "HTTP/1.1 200 OK\r\n"
  12151. "Date: %s\r\n"
  12152. "Access-Control-Allow-Origin: %s\r\n"
  12153. "Access-Control-Allow-Methods: %s\r\n"
  12154. "Content-Length: 0\r\n"
  12155. "Connection: %s\r\n",
  12156. date,
  12157. cors_orig_cfg,
  12158. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12159. suggest_connection_header(conn));
  12160. if (cors_acrh != NULL) {
  12161. /* CORS request is asking for additional headers */
  12162. const char *cors_hdr_cfg =
  12163. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12164. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12165. /* Allow only if access_control_allow_headers is
  12166. * not NULL and not an empty string. If this
  12167. * configuration is set to *, allow everything.
  12168. * Otherwise this configuration must be a list
  12169. * of allowed HTTP header names. */
  12170. mg_printf(conn,
  12171. "Access-Control-Allow-Headers: %s\r\n",
  12172. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12173. : cors_hdr_cfg));
  12174. }
  12175. }
  12176. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12177. mg_printf(conn, "\r\n");
  12178. return;
  12179. }
  12180. }
  12181. /* 5. interpret the url to find out how the request must be handled
  12182. */
  12183. /* 5.1. first test, if the request targets the regular http(s)://
  12184. * protocol namespace or the websocket ws(s):// protocol namespace.
  12185. */
  12186. is_websocket_request = is_websocket_protocol(conn);
  12187. #if defined(USE_WEBSOCKET)
  12188. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12189. #else
  12190. handler_type = REQUEST_HANDLER;
  12191. #endif /* defined(USE_WEBSOCKET) */
  12192. /* 5.2. check if the request will be handled by a callback */
  12193. if (get_request_handler(conn,
  12194. handler_type,
  12195. &callback_handler,
  12196. &subprotocols,
  12197. &ws_connect_handler,
  12198. &ws_ready_handler,
  12199. &ws_data_handler,
  12200. &ws_close_handler,
  12201. NULL,
  12202. &callback_data,
  12203. &handler_info)) {
  12204. /* 5.2.1. A callback will handle this request. All requests
  12205. * handled
  12206. * by a callback have to be considered as requests to a script
  12207. * resource. */
  12208. is_callback_resource = 1;
  12209. is_script_resource = 1;
  12210. is_put_or_delete_request = is_put_or_delete_method(conn);
  12211. } else {
  12212. no_callback_resource:
  12213. /* 5.2.2. No callback is responsible for this request. The URI
  12214. * addresses a file based resource (static content or Lua/cgi
  12215. * scripts in the file system). */
  12216. is_callback_resource = 0;
  12217. interpret_uri(conn,
  12218. path,
  12219. sizeof(path),
  12220. &file.stat,
  12221. &is_found,
  12222. &is_script_resource,
  12223. &is_websocket_request,
  12224. &is_put_or_delete_request);
  12225. }
  12226. /* 6. authorization check */
  12227. /* 6.1. a custom authorization handler is installed */
  12228. if (get_request_handler(conn,
  12229. AUTH_HANDLER,
  12230. NULL,
  12231. NULL,
  12232. NULL,
  12233. NULL,
  12234. NULL,
  12235. NULL,
  12236. &auth_handler,
  12237. &auth_callback_data,
  12238. NULL)) {
  12239. if (!auth_handler(conn, auth_callback_data)) {
  12240. return;
  12241. }
  12242. } else if (is_put_or_delete_request && !is_script_resource
  12243. && !is_callback_resource) {
  12244. /* 6.2. this request is a PUT/DELETE to a real file */
  12245. /* 6.2.1. thus, the server must have real files */
  12246. #if defined(NO_FILES)
  12247. if (1) {
  12248. #else
  12249. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12250. #endif
  12251. /* This server does not have any real files, thus the
  12252. * PUT/DELETE methods are not valid. */
  12253. mg_send_http_error(conn,
  12254. 405,
  12255. "%s method not allowed",
  12256. conn->request_info.request_method);
  12257. return;
  12258. }
  12259. #if !defined(NO_FILES)
  12260. /* 6.2.2. Check if put authorization for static files is
  12261. * available.
  12262. */
  12263. if (!is_authorized_for_put(conn)) {
  12264. send_authorization_request(conn, NULL);
  12265. return;
  12266. }
  12267. #endif
  12268. } else {
  12269. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12270. * or it is a PUT or DELETE request to a resource that does not
  12271. * correspond to a file. Check authorization. */
  12272. if (!check_authorization(conn, path)) {
  12273. send_authorization_request(conn, NULL);
  12274. return;
  12275. }
  12276. }
  12277. /* request is authorized or does not need authorization */
  12278. /* 7. check if there are request handlers for this uri */
  12279. if (is_callback_resource) {
  12280. if (!is_websocket_request) {
  12281. i = callback_handler(conn, callback_data);
  12282. /* Callback handler will not be used anymore. Release it */
  12283. handler_info_release(handler_info);
  12284. if (i > 0) {
  12285. /* Do nothing, callback has served the request. Store
  12286. * then return value as status code for the log and discard
  12287. * all data from the client not used by the callback. */
  12288. conn->status_code = i;
  12289. if (!conn->must_close) {
  12290. discard_unread_request_data(conn);
  12291. }
  12292. } else {
  12293. /* The handler did NOT handle the request. */
  12294. /* Some proper reactions would be:
  12295. * a) close the connections without sending anything
  12296. * b) send a 404 not found
  12297. * c) try if there is a file matching the URI
  12298. * It would be possible to do a, b or c in the callback
  12299. * implementation, and return 1 - we cannot do anything
  12300. * here, that is not possible in the callback.
  12301. *
  12302. * TODO: What would be the best reaction here?
  12303. * (Note: The reaction may change, if there is a better
  12304. *idea.)
  12305. */
  12306. /* For the moment, use option c: We look for a proper file,
  12307. * but since a file request is not always a script resource,
  12308. * the authorization check might be different. */
  12309. interpret_uri(conn,
  12310. path,
  12311. sizeof(path),
  12312. &file.stat,
  12313. &is_found,
  12314. &is_script_resource,
  12315. &is_websocket_request,
  12316. &is_put_or_delete_request);
  12317. callback_handler = NULL;
  12318. /* Here we are at a dead end:
  12319. * According to URI matching, a callback should be
  12320. * responsible for handling the request,
  12321. * we called it, but the callback declared itself
  12322. * not responsible.
  12323. * We use a goto here, to get out of this dead end,
  12324. * and continue with the default handling.
  12325. * A goto here is simpler and better to understand
  12326. * than some curious loop. */
  12327. goto no_callback_resource;
  12328. }
  12329. } else {
  12330. #if defined(USE_WEBSOCKET)
  12331. handle_websocket_request(conn,
  12332. path,
  12333. is_callback_resource,
  12334. subprotocols,
  12335. ws_connect_handler,
  12336. ws_ready_handler,
  12337. ws_data_handler,
  12338. ws_close_handler,
  12339. callback_data);
  12340. #endif
  12341. }
  12342. return;
  12343. }
  12344. /* 8. handle websocket requests */
  12345. #if defined(USE_WEBSOCKET)
  12346. if (is_websocket_request) {
  12347. if (is_script_resource) {
  12348. if (is_in_script_path(conn, path)) {
  12349. /* Websocket Lua script */
  12350. handle_websocket_request(conn,
  12351. path,
  12352. 0 /* Lua Script */,
  12353. NULL,
  12354. NULL,
  12355. NULL,
  12356. NULL,
  12357. NULL,
  12358. conn->phys_ctx->user_data);
  12359. } else {
  12360. /* Script was in an illegal path */
  12361. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12362. }
  12363. } else {
  12364. #if defined(MG_LEGACY_INTERFACE)
  12365. handle_websocket_request(
  12366. conn,
  12367. path,
  12368. !is_script_resource /* could be deprecated global callback */,
  12369. NULL,
  12370. deprecated_websocket_connect_wrapper,
  12371. deprecated_websocket_ready_wrapper,
  12372. deprecated_websocket_data_wrapper,
  12373. NULL,
  12374. conn->phys_ctx->callbacks);
  12375. #else
  12376. mg_send_http_error(conn, 404, "%s", "Not found");
  12377. #endif
  12378. }
  12379. return;
  12380. } else
  12381. #endif
  12382. #if defined(NO_FILES)
  12383. /* 9a. In case the server uses only callbacks, this uri is
  12384. * unknown.
  12385. * Then, all request handling ends here. */
  12386. mg_send_http_error(conn, 404, "%s", "Not Found");
  12387. #else
  12388. /* 9b. This request is either for a static file or resource handled
  12389. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12390. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12391. mg_send_http_error(conn, 404, "%s", "Not Found");
  12392. return;
  12393. }
  12394. /* 10. Request is handled by a script */
  12395. if (is_script_resource) {
  12396. handle_file_based_request(conn, path, &file);
  12397. return;
  12398. }
  12399. /* 11. Handle put/delete/mkcol requests */
  12400. if (is_put_or_delete_request) {
  12401. /* 11.1. PUT method */
  12402. if (!strcmp(ri->request_method, "PUT")) {
  12403. put_file(conn, path);
  12404. return;
  12405. }
  12406. /* 11.2. DELETE method */
  12407. if (!strcmp(ri->request_method, "DELETE")) {
  12408. delete_file(conn, path);
  12409. return;
  12410. }
  12411. /* 11.3. MKCOL method */
  12412. if (!strcmp(ri->request_method, "MKCOL")) {
  12413. mkcol(conn, path);
  12414. return;
  12415. }
  12416. /* 11.4. PATCH method
  12417. * This method is not supported for static resources,
  12418. * only for scripts (Lua, CGI) and callbacks. */
  12419. mg_send_http_error(conn,
  12420. 405,
  12421. "%s method not allowed",
  12422. conn->request_info.request_method);
  12423. return;
  12424. }
  12425. /* 11. File does not exist, or it was configured that it should be
  12426. * hidden */
  12427. if (!is_found || (must_hide_file(conn, path))) {
  12428. mg_send_http_error(conn, 404, "%s", "Not found");
  12429. return;
  12430. }
  12431. /* 12. Directory uris should end with a slash */
  12432. if (file.stat.is_directory && (uri_len > 0)
  12433. && (ri->local_uri[uri_len - 1] != '/')) {
  12434. gmt_time_string(date, sizeof(date), &curtime);
  12435. mg_printf(conn,
  12436. "HTTP/1.1 301 Moved Permanently\r\n"
  12437. "Location: %s/\r\n"
  12438. "Date: %s\r\n"
  12439. /* "Cache-Control: private\r\n" (= default) */
  12440. "Content-Length: 0\r\n"
  12441. "Connection: %s\r\n",
  12442. ri->request_uri,
  12443. date,
  12444. suggest_connection_header(conn));
  12445. send_additional_header(conn);
  12446. mg_printf(conn, "\r\n");
  12447. return;
  12448. }
  12449. /* 13. Handle other methods than GET/HEAD */
  12450. /* 13.1. Handle PROPFIND */
  12451. if (!strcmp(ri->request_method, "PROPFIND")) {
  12452. handle_propfind(conn, path, &file.stat);
  12453. return;
  12454. }
  12455. /* 13.2. Handle OPTIONS for files */
  12456. if (!strcmp(ri->request_method, "OPTIONS")) {
  12457. /* This standard handler is only used for real files.
  12458. * Scripts should support the OPTIONS method themselves, to allow a
  12459. * maximum flexibility.
  12460. * Lua and CGI scripts may fully support CORS this way (including
  12461. * preflights). */
  12462. send_options(conn);
  12463. return;
  12464. }
  12465. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12466. if ((0 != strcmp(ri->request_method, "GET"))
  12467. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12468. mg_send_http_error(conn,
  12469. 405,
  12470. "%s method not allowed",
  12471. conn->request_info.request_method);
  12472. return;
  12473. }
  12474. /* 14. directories */
  12475. if (file.stat.is_directory) {
  12476. /* Substitute files have already been handled above. */
  12477. /* Here we can either generate and send a directory listing,
  12478. * or send an "access denied" error. */
  12479. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12480. "yes")) {
  12481. handle_directory_request(conn, path);
  12482. } else {
  12483. mg_send_http_error(conn,
  12484. 403,
  12485. "%s",
  12486. "Error: Directory listing denied");
  12487. }
  12488. return;
  12489. }
  12490. /* 15. read a normal file with GET or HEAD */
  12491. handle_file_based_request(conn, path, &file);
  12492. #endif /* !defined(NO_FILES) */
  12493. }
  12494. #if !defined(NO_FILESYSTEMS)
  12495. static void
  12496. handle_file_based_request(struct mg_connection *conn,
  12497. const char *path,
  12498. struct mg_file *file)
  12499. {
  12500. if (!conn || !conn->dom_ctx) {
  12501. return;
  12502. }
  12503. if (0) {
  12504. #if defined(USE_LUA)
  12505. } else if (match_prefix(
  12506. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12507. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12508. path)
  12509. > 0) {
  12510. if (is_in_script_path(conn, path)) {
  12511. /* Lua server page: an SSI like page containing mostly plain
  12512. * html
  12513. * code
  12514. * plus some tags with server generated contents. */
  12515. handle_lsp_request(conn, path, file, NULL);
  12516. } else {
  12517. /* Script was in an illegal path */
  12518. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12519. }
  12520. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12521. strlen(
  12522. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12523. path)
  12524. > 0) {
  12525. if (is_in_script_path(conn, path)) {
  12526. /* Lua in-server module script: a CGI like script used to
  12527. * generate
  12528. * the
  12529. * entire reply. */
  12530. mg_exec_lua_script(conn, path, NULL);
  12531. } else {
  12532. /* Script was in an illegal path */
  12533. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12534. }
  12535. #endif
  12536. #if defined(USE_DUKTAPE)
  12537. } else if (match_prefix(
  12538. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12539. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12540. path)
  12541. > 0) {
  12542. if (is_in_script_path(conn, path)) {
  12543. /* Call duktape to generate the page */
  12544. mg_exec_duktape_script(conn, path);
  12545. } else {
  12546. /* Script was in an illegal path */
  12547. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12548. }
  12549. #endif
  12550. #if !defined(NO_CGI)
  12551. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12552. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12553. path)
  12554. > 0) {
  12555. if (is_in_script_path(conn, path)) {
  12556. /* CGI scripts may support all HTTP methods */
  12557. handle_cgi_request(conn, path);
  12558. } else {
  12559. /* Script was in an illegal path */
  12560. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12561. }
  12562. #endif /* !NO_CGI */
  12563. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12564. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12565. path)
  12566. > 0) {
  12567. if (is_in_script_path(conn, path)) {
  12568. handle_ssi_file_request(conn, path, file);
  12569. } else {
  12570. /* Script was in an illegal path */
  12571. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12572. }
  12573. #if !defined(NO_CACHING)
  12574. } else if ((!conn->in_error_handler)
  12575. && is_not_modified(conn, &file->stat)) {
  12576. /* Send 304 "Not Modified" - this must not send any body data */
  12577. handle_not_modified_static_file_request(conn, file);
  12578. #endif /* !NO_CACHING */
  12579. } else {
  12580. handle_static_file_request(conn, path, file, NULL, NULL);
  12581. }
  12582. }
  12583. #endif /* NO_FILESYSTEMS */
  12584. static void
  12585. close_all_listening_sockets(struct mg_context *ctx)
  12586. {
  12587. unsigned int i;
  12588. if (!ctx) {
  12589. return;
  12590. }
  12591. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12592. closesocket(ctx->listening_sockets[i].sock);
  12593. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12594. }
  12595. mg_free(ctx->listening_sockets);
  12596. ctx->listening_sockets = NULL;
  12597. mg_free(ctx->listening_socket_fds);
  12598. ctx->listening_socket_fds = NULL;
  12599. }
  12600. /* Valid listening port specification is: [ip_address:]port[s]
  12601. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12602. * Examples for IPv6: [::]:80, [::1]:80,
  12603. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12604. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12605. * In order to bind to both, IPv4 and IPv6, you can either add
  12606. * both ports using 8080,[::]:8080, or the short form +8080.
  12607. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12608. * one only accepting IPv4 the other only IPv6. +8080 creates
  12609. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12610. * environment, they might work differently, or might not work
  12611. * at all - it must be tested what options work best in the
  12612. * relevant network environment.
  12613. */
  12614. static int
  12615. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12616. {
  12617. unsigned int a, b, c, d, port;
  12618. int ch, len;
  12619. const char *cb;
  12620. char *endptr;
  12621. #if defined(USE_IPV6)
  12622. char buf[100] = {0};
  12623. #endif
  12624. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12625. * Also, all-zeroes in the socket address means binding to all addresses
  12626. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12627. memset(so, 0, sizeof(*so));
  12628. so->lsa.sin.sin_family = AF_INET;
  12629. *ip_version = 0;
  12630. /* Initialize port and len as invalid. */
  12631. port = 0;
  12632. len = 0;
  12633. /* Test for different ways to format this string */
  12634. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12635. == 5) {
  12636. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12637. so->lsa.sin.sin_addr.s_addr =
  12638. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12639. so->lsa.sin.sin_port = htons((uint16_t)port);
  12640. *ip_version = 4;
  12641. #if defined(USE_IPV6)
  12642. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12643. && mg_inet_pton(
  12644. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12645. /* IPv6 address, examples: see above */
  12646. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12647. */
  12648. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12649. *ip_version = 6;
  12650. #endif
  12651. } else if ((vec->ptr[0] == '+')
  12652. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12653. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12654. /* Add 1 to len for the + character we skipped before */
  12655. len++;
  12656. #if defined(USE_IPV6)
  12657. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12658. so->lsa.sin6.sin6_family = AF_INET6;
  12659. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12660. *ip_version = 4 + 6;
  12661. #else
  12662. /* Bind to IPv4 only, since IPv6 is not built in. */
  12663. so->lsa.sin.sin_port = htons((uint16_t)port);
  12664. *ip_version = 4;
  12665. #endif
  12666. } else if (is_valid_port(port = strtoul(vec->ptr, &endptr, 0))
  12667. && vec->ptr != endptr) {
  12668. len = endptr - vec->ptr;
  12669. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12670. so->lsa.sin.sin_port = htons((uint16_t)port);
  12671. *ip_version = 4;
  12672. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12673. /* String could be a hostname. This check algotithm
  12674. * will only work for RFC 952 compliant hostnames,
  12675. * starting with a letter, containing only letters,
  12676. * digits and hyphen ('-'). Newer specs may allow
  12677. * more, but this is not guaranteed here, since it
  12678. * may interfere with rules for port option lists. */
  12679. /* According to RFC 1035, hostnames are restricted to 255 characters
  12680. * in total (63 between two dots). */
  12681. char hostname[256];
  12682. size_t hostnlen = (size_t)(cb - vec->ptr);
  12683. if (hostnlen >= sizeof(hostname)) {
  12684. /* This would be invalid in any case */
  12685. *ip_version = 0;
  12686. return 0;
  12687. }
  12688. memcpy(hostname, vec->ptr, hostnlen);
  12689. hostname[hostnlen] = 0;
  12690. if (mg_inet_pton(
  12691. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12692. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12693. *ip_version = 4;
  12694. so->lsa.sin.sin_family = AF_INET;
  12695. so->lsa.sin.sin_port = htons((uint16_t)port);
  12696. len += (int)(hostnlen + 1);
  12697. } else {
  12698. port = 0;
  12699. len = 0;
  12700. }
  12701. #if defined(USE_IPV6)
  12702. } else if (mg_inet_pton(AF_INET6,
  12703. hostname,
  12704. &so->lsa.sin6,
  12705. sizeof(so->lsa.sin6))) {
  12706. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12707. *ip_version = 6;
  12708. so->lsa.sin6.sin6_family = AF_INET6;
  12709. so->lsa.sin.sin_port = htons((uint16_t)port);
  12710. len += (int)(hostnlen + 1);
  12711. } else {
  12712. port = 0;
  12713. len = 0;
  12714. }
  12715. #endif
  12716. }
  12717. } else {
  12718. /* Parsing failure. */
  12719. }
  12720. /* sscanf and the option splitting code ensure the following condition
  12721. */
  12722. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12723. *ip_version = 0;
  12724. return 0;
  12725. }
  12726. ch = vec->ptr[len]; /* Next character after the port number */
  12727. so->is_ssl = (ch == 's');
  12728. so->ssl_redir = (ch == 'r');
  12729. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12730. if (is_valid_port(port)
  12731. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12732. return 1;
  12733. }
  12734. /* Reset ip_version to 0 if there is an error */
  12735. *ip_version = 0;
  12736. return 0;
  12737. }
  12738. /* Is there any SSL port in use? */
  12739. static int
  12740. is_ssl_port_used(const char *ports)
  12741. {
  12742. if (ports) {
  12743. /* There are several different allowed syntax variants:
  12744. * - "80" for a single port using every network interface
  12745. * - "localhost:80" for a single port using only localhost
  12746. * - "80,localhost:8080" for two ports, one bound to localhost
  12747. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12748. * to IPv4 localhost, one to IPv6 localhost
  12749. * - "+80" use port 80 for IPv4 and IPv6
  12750. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12751. * for both: IPv4 and IPv4
  12752. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12753. * additionally port 8080 bound to localhost connections
  12754. *
  12755. * If we just look for 's' anywhere in the string, "localhost:80"
  12756. * will be detected as SSL (false positive).
  12757. * Looking for 's' after a digit may cause false positives in
  12758. * "my24service:8080".
  12759. * Looking from 's' backward if there are only ':' and numbers
  12760. * before will not work for "24service:8080" (non SSL, port 8080)
  12761. * or "24s" (SSL, port 24).
  12762. *
  12763. * Remark: Initially hostnames were not allowed to start with a
  12764. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12765. * Section 2.1).
  12766. *
  12767. * To get this correct, the entire string must be parsed as a whole,
  12768. * reading it as a list element for element and parsing with an
  12769. * algorithm equivalent to parse_port_string.
  12770. *
  12771. * In fact, we use local interface names here, not arbitrary hostnames,
  12772. * so in most cases the only name will be "localhost".
  12773. *
  12774. * So, for now, we use this simple algorithm, that may still return
  12775. * a false positive in bizarre cases.
  12776. */
  12777. int i;
  12778. int portslen = (int)strlen(ports);
  12779. char prevIsNumber = 0;
  12780. for (i = 0; i < portslen; i++) {
  12781. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12782. return 1;
  12783. }
  12784. if (ports[i] >= '0' && ports[i] <= '9') {
  12785. prevIsNumber = 1;
  12786. } else {
  12787. prevIsNumber = 0;
  12788. }
  12789. }
  12790. }
  12791. return 0;
  12792. }
  12793. static int
  12794. set_ports_option(struct mg_context *phys_ctx)
  12795. {
  12796. const char *list;
  12797. int on = 1;
  12798. #if defined(USE_IPV6)
  12799. int off = 0;
  12800. #endif
  12801. struct vec vec;
  12802. struct socket so, *ptr;
  12803. struct mg_pollfd *pfd;
  12804. union usa usa;
  12805. socklen_t len;
  12806. int ip_version;
  12807. int portsTotal = 0;
  12808. int portsOk = 0;
  12809. const char *opt_txt;
  12810. long opt_listen_backlog;
  12811. if (!phys_ctx) {
  12812. return 0;
  12813. }
  12814. memset(&so, 0, sizeof(so));
  12815. memset(&usa, 0, sizeof(usa));
  12816. len = sizeof(usa);
  12817. list = phys_ctx->dd.config[LISTENING_PORTS];
  12818. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12819. portsTotal++;
  12820. if (!parse_port_string(&vec, &so, &ip_version)) {
  12821. mg_cry_ctx_internal(
  12822. phys_ctx,
  12823. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12824. (int)vec.len,
  12825. vec.ptr,
  12826. portsTotal,
  12827. "[IP_ADDRESS:]PORT[s|r]");
  12828. continue;
  12829. }
  12830. #if !defined(NO_SSL)
  12831. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12832. mg_cry_ctx_internal(phys_ctx,
  12833. "Cannot add SSL socket (entry %i)",
  12834. portsTotal);
  12835. continue;
  12836. }
  12837. #endif
  12838. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12839. == INVALID_SOCKET) {
  12840. mg_cry_ctx_internal(phys_ctx,
  12841. "cannot create socket (entry %i)",
  12842. portsTotal);
  12843. continue;
  12844. }
  12845. #if defined(_WIN32)
  12846. /* Windows SO_REUSEADDR lets many procs binds to a
  12847. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12848. * if someone already has the socket -- DTL */
  12849. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12850. * Windows might need a few seconds before
  12851. * the same port can be used again in the
  12852. * same process, so a short Sleep may be
  12853. * required between mg_stop and mg_start.
  12854. */
  12855. if (setsockopt(so.sock,
  12856. SOL_SOCKET,
  12857. SO_EXCLUSIVEADDRUSE,
  12858. (SOCK_OPT_TYPE)&on,
  12859. sizeof(on))
  12860. != 0) {
  12861. /* Set reuse option, but don't abort on errors. */
  12862. mg_cry_ctx_internal(
  12863. phys_ctx,
  12864. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12865. portsTotal);
  12866. }
  12867. #else
  12868. if (setsockopt(so.sock,
  12869. SOL_SOCKET,
  12870. SO_REUSEADDR,
  12871. (SOCK_OPT_TYPE)&on,
  12872. sizeof(on))
  12873. != 0) {
  12874. /* Set reuse option, but don't abort on errors. */
  12875. mg_cry_ctx_internal(
  12876. phys_ctx,
  12877. "cannot set socket option SO_REUSEADDR (entry %i)",
  12878. portsTotal);
  12879. }
  12880. #endif
  12881. if (ip_version > 4) {
  12882. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12883. #if defined(USE_IPV6)
  12884. if (ip_version > 6) {
  12885. if (so.lsa.sa.sa_family == AF_INET6
  12886. && setsockopt(so.sock,
  12887. IPPROTO_IPV6,
  12888. IPV6_V6ONLY,
  12889. (void *)&off,
  12890. sizeof(off))
  12891. != 0) {
  12892. /* Set IPv6 only option, but don't abort on errors. */
  12893. mg_cry_ctx_internal(
  12894. phys_ctx,
  12895. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12896. portsTotal);
  12897. }
  12898. } else {
  12899. if (so.lsa.sa.sa_family == AF_INET6
  12900. && setsockopt(so.sock,
  12901. IPPROTO_IPV6,
  12902. IPV6_V6ONLY,
  12903. (void *)&on,
  12904. sizeof(on))
  12905. != 0) {
  12906. /* Set IPv6 only option, but don't abort on errors. */
  12907. mg_cry_ctx_internal(
  12908. phys_ctx,
  12909. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12910. portsTotal);
  12911. }
  12912. }
  12913. #else
  12914. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12915. closesocket(so.sock);
  12916. so.sock = INVALID_SOCKET;
  12917. continue;
  12918. #endif
  12919. }
  12920. if (so.lsa.sa.sa_family == AF_INET) {
  12921. len = sizeof(so.lsa.sin);
  12922. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12923. mg_cry_ctx_internal(phys_ctx,
  12924. "cannot bind to %.*s: %d (%s)",
  12925. (int)vec.len,
  12926. vec.ptr,
  12927. (int)ERRNO,
  12928. strerror(errno));
  12929. closesocket(so.sock);
  12930. so.sock = INVALID_SOCKET;
  12931. continue;
  12932. }
  12933. }
  12934. #if defined(USE_IPV6)
  12935. else if (so.lsa.sa.sa_family == AF_INET6) {
  12936. len = sizeof(so.lsa.sin6);
  12937. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12938. mg_cry_ctx_internal(phys_ctx,
  12939. "cannot bind to IPv6 %.*s: %d (%s)",
  12940. (int)vec.len,
  12941. vec.ptr,
  12942. (int)ERRNO,
  12943. strerror(errno));
  12944. closesocket(so.sock);
  12945. so.sock = INVALID_SOCKET;
  12946. continue;
  12947. }
  12948. }
  12949. #endif
  12950. else {
  12951. mg_cry_ctx_internal(
  12952. phys_ctx,
  12953. "cannot bind: address family not supported (entry %i)",
  12954. portsTotal);
  12955. closesocket(so.sock);
  12956. so.sock = INVALID_SOCKET;
  12957. continue;
  12958. }
  12959. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  12960. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  12961. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  12962. mg_cry_ctx_internal(phys_ctx,
  12963. "%s value \"%s\" is invalid",
  12964. config_options[LISTEN_BACKLOG_SIZE].name,
  12965. opt_txt);
  12966. continue;
  12967. }
  12968. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  12969. mg_cry_ctx_internal(phys_ctx,
  12970. "cannot listen to %.*s: %d (%s)",
  12971. (int)vec.len,
  12972. vec.ptr,
  12973. (int)ERRNO,
  12974. strerror(errno));
  12975. closesocket(so.sock);
  12976. so.sock = INVALID_SOCKET;
  12977. continue;
  12978. }
  12979. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12980. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12981. int err = (int)ERRNO;
  12982. mg_cry_ctx_internal(phys_ctx,
  12983. "call to getsockname failed %.*s: %d (%s)",
  12984. (int)vec.len,
  12985. vec.ptr,
  12986. err,
  12987. strerror(errno));
  12988. closesocket(so.sock);
  12989. so.sock = INVALID_SOCKET;
  12990. continue;
  12991. }
  12992. /* Update lsa port in case of random free ports */
  12993. #if defined(USE_IPV6)
  12994. if (so.lsa.sa.sa_family == AF_INET6) {
  12995. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12996. } else
  12997. #endif
  12998. {
  12999. so.lsa.sin.sin_port = usa.sin.sin_port;
  13000. }
  13001. if ((ptr = (struct socket *)
  13002. mg_realloc_ctx(phys_ctx->listening_sockets,
  13003. (phys_ctx->num_listening_sockets + 1)
  13004. * sizeof(phys_ctx->listening_sockets[0]),
  13005. phys_ctx))
  13006. == NULL) {
  13007. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13008. closesocket(so.sock);
  13009. so.sock = INVALID_SOCKET;
  13010. continue;
  13011. }
  13012. if ((pfd = (struct mg_pollfd *)
  13013. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13014. (phys_ctx->num_listening_sockets + 1)
  13015. * sizeof(phys_ctx->listening_socket_fds[0]),
  13016. phys_ctx))
  13017. == NULL) {
  13018. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13019. closesocket(so.sock);
  13020. so.sock = INVALID_SOCKET;
  13021. mg_free(ptr);
  13022. continue;
  13023. }
  13024. set_close_on_exec(so.sock, NULL, phys_ctx);
  13025. phys_ctx->listening_sockets = ptr;
  13026. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13027. phys_ctx->listening_socket_fds = pfd;
  13028. phys_ctx->num_listening_sockets++;
  13029. portsOk++;
  13030. }
  13031. if (portsOk != portsTotal) {
  13032. close_all_listening_sockets(phys_ctx);
  13033. portsOk = 0;
  13034. }
  13035. return portsOk;
  13036. }
  13037. static const char *
  13038. header_val(const struct mg_connection *conn, const char *header)
  13039. {
  13040. const char *header_value;
  13041. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13042. return "-";
  13043. } else {
  13044. return header_value;
  13045. }
  13046. }
  13047. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13048. static void log_access(const struct mg_connection *conn);
  13049. #include "external_log_access.inl"
  13050. #elif !defined(NO_FILESYSTEMS)
  13051. static void
  13052. log_access(const struct mg_connection *conn)
  13053. {
  13054. const struct mg_request_info *ri;
  13055. struct mg_file fi;
  13056. char date[64], src_addr[IP_ADDR_STR_LEN];
  13057. struct tm *tm;
  13058. const char *referer;
  13059. const char *user_agent;
  13060. char buf[4096];
  13061. if (!conn || !conn->dom_ctx) {
  13062. return;
  13063. }
  13064. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13065. if (mg_fopen(conn,
  13066. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13067. MG_FOPEN_MODE_APPEND,
  13068. &fi)
  13069. == 0) {
  13070. fi.access.fp = NULL;
  13071. }
  13072. } else {
  13073. fi.access.fp = NULL;
  13074. }
  13075. /* Log is written to a file and/or a callback. If both are not set,
  13076. * executing the rest of the function is pointless. */
  13077. if ((fi.access.fp == NULL)
  13078. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13079. return;
  13080. }
  13081. tm = localtime(&conn->conn_birth_time);
  13082. if (tm != NULL) {
  13083. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13084. } else {
  13085. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13086. date[sizeof(date) - 1] = '\0';
  13087. }
  13088. ri = &conn->request_info;
  13089. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13090. referer = header_val(conn, "Referer");
  13091. user_agent = header_val(conn, "User-Agent");
  13092. mg_snprintf(conn,
  13093. NULL, /* Ignore truncation in access log */
  13094. buf,
  13095. sizeof(buf),
  13096. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13097. src_addr,
  13098. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13099. date,
  13100. ri->request_method ? ri->request_method : "-",
  13101. ri->request_uri ? ri->request_uri : "-",
  13102. ri->query_string ? "?" : "",
  13103. ri->query_string ? ri->query_string : "",
  13104. ri->http_version,
  13105. conn->status_code,
  13106. conn->num_bytes_sent,
  13107. referer,
  13108. user_agent);
  13109. if (conn->phys_ctx->callbacks.log_access) {
  13110. conn->phys_ctx->callbacks.log_access(conn, buf);
  13111. }
  13112. if (fi.access.fp) {
  13113. int ok = 1;
  13114. flockfile(fi.access.fp);
  13115. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13116. ok = 0;
  13117. }
  13118. if (fflush(fi.access.fp) != 0) {
  13119. ok = 0;
  13120. }
  13121. funlockfile(fi.access.fp);
  13122. if (mg_fclose(&fi.access) != 0) {
  13123. ok = 0;
  13124. }
  13125. if (!ok) {
  13126. mg_cry_internal(conn,
  13127. "Error writing log file %s",
  13128. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13129. }
  13130. }
  13131. }
  13132. #else
  13133. #error Must either enable filesystems or provide a custom log_access implementation
  13134. #endif /* Externally provided function */
  13135. /* Verify given socket address against the ACL.
  13136. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13137. */
  13138. static int
  13139. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13140. {
  13141. int allowed, flag;
  13142. uint32_t net, mask;
  13143. struct vec vec;
  13144. if (phys_ctx) {
  13145. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13146. /* If any ACL is set, deny by default */
  13147. allowed = (list == NULL) ? '+' : '-';
  13148. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13149. flag = vec.ptr[0];
  13150. if ((flag != '+' && flag != '-')
  13151. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13152. mg_cry_ctx_internal(phys_ctx,
  13153. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13154. __func__);
  13155. return -1;
  13156. }
  13157. if (net == (remote_ip & mask)) {
  13158. allowed = flag;
  13159. }
  13160. }
  13161. return allowed == '+';
  13162. }
  13163. return -1;
  13164. }
  13165. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13166. static int
  13167. set_uid_option(struct mg_context *phys_ctx)
  13168. {
  13169. int success = 0;
  13170. if (phys_ctx) {
  13171. /* We are currently running as curr_uid. */
  13172. const uid_t curr_uid = getuid();
  13173. /* If set, we want to run as run_as_user. */
  13174. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13175. const struct passwd *to_pw = NULL;
  13176. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13177. /* run_as_user does not exist on the system. We can't proceed
  13178. * further. */
  13179. mg_cry_ctx_internal(phys_ctx,
  13180. "%s: unknown user [%s]",
  13181. __func__,
  13182. run_as_user);
  13183. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13184. /* There was either no request to change user, or we're already
  13185. * running as run_as_user. Nothing else to do.
  13186. */
  13187. success = 1;
  13188. } else {
  13189. /* Valid change request. */
  13190. if (setgid(to_pw->pw_gid) == -1) {
  13191. mg_cry_ctx_internal(phys_ctx,
  13192. "%s: setgid(%s): %s",
  13193. __func__,
  13194. run_as_user,
  13195. strerror(errno));
  13196. } else if (setgroups(0, NULL) == -1) {
  13197. mg_cry_ctx_internal(phys_ctx,
  13198. "%s: setgroups(): %s",
  13199. __func__,
  13200. strerror(errno));
  13201. } else if (setuid(to_pw->pw_uid) == -1) {
  13202. mg_cry_ctx_internal(phys_ctx,
  13203. "%s: setuid(%s): %s",
  13204. __func__,
  13205. run_as_user,
  13206. strerror(errno));
  13207. } else {
  13208. success = 1;
  13209. }
  13210. }
  13211. }
  13212. return success;
  13213. }
  13214. #endif /* !_WIN32 */
  13215. static void
  13216. tls_dtor(void *key)
  13217. {
  13218. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13219. /* key == pthread_getspecific(sTlsKey); */
  13220. if (tls) {
  13221. if (tls->is_master == 2) {
  13222. tls->is_master = -3; /* Mark memory as dead */
  13223. mg_free(tls);
  13224. }
  13225. }
  13226. pthread_setspecific(sTlsKey, NULL);
  13227. }
  13228. #if !defined(NO_SSL)
  13229. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13230. struct mg_domain_context *dom_ctx,
  13231. const char *pem,
  13232. const char *chain);
  13233. static const char *ssl_error(void);
  13234. static int
  13235. refresh_trust(struct mg_connection *conn)
  13236. {
  13237. static int reload_lock = 0;
  13238. static long int data_check = 0;
  13239. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  13240. struct stat cert_buf;
  13241. long int t;
  13242. const char *pem;
  13243. const char *chain;
  13244. int should_verify_peer;
  13245. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13246. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13247. * refresh_trust still can not work. */
  13248. return 0;
  13249. }
  13250. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13251. if (chain == NULL) {
  13252. /* pem is not NULL here */
  13253. chain = pem;
  13254. }
  13255. if (*chain == 0) {
  13256. chain = NULL;
  13257. }
  13258. t = data_check;
  13259. if (stat(pem, &cert_buf) != -1) {
  13260. t = (long int)cert_buf.st_mtime;
  13261. }
  13262. if (data_check != t) {
  13263. data_check = t;
  13264. should_verify_peer = 0;
  13265. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13266. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13267. == 0) {
  13268. should_verify_peer = 1;
  13269. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13270. "optional")
  13271. == 0) {
  13272. should_verify_peer = 1;
  13273. }
  13274. }
  13275. if (should_verify_peer) {
  13276. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13277. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13278. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13279. ca_file,
  13280. ca_path)
  13281. != 1) {
  13282. mg_cry_ctx_internal(
  13283. conn->phys_ctx,
  13284. "SSL_CTX_load_verify_locations error: %s "
  13285. "ssl_verify_peer requires setting "
  13286. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13287. "present in "
  13288. "the .conf file?",
  13289. ssl_error());
  13290. return 0;
  13291. }
  13292. }
  13293. if (1 == mg_atomic_inc(p_reload_lock)) {
  13294. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13295. == 0) {
  13296. return 0;
  13297. }
  13298. *p_reload_lock = 0;
  13299. }
  13300. }
  13301. /* lock while cert is reloading */
  13302. while (*p_reload_lock) {
  13303. sleep(1);
  13304. }
  13305. return 1;
  13306. }
  13307. #if defined(OPENSSL_API_1_1)
  13308. #else
  13309. static pthread_mutex_t *ssl_mutexes;
  13310. #endif /* OPENSSL_API_1_1 */
  13311. static int
  13312. sslize(struct mg_connection *conn,
  13313. SSL_CTX *s,
  13314. int (*func)(SSL *),
  13315. volatile int *stop_server,
  13316. const struct mg_client_options *client_options)
  13317. {
  13318. int ret, err;
  13319. int short_trust;
  13320. unsigned timeout = 1024;
  13321. unsigned i;
  13322. if (!conn) {
  13323. return 0;
  13324. }
  13325. short_trust =
  13326. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13327. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13328. if (short_trust) {
  13329. int trust_ret = refresh_trust(conn);
  13330. if (!trust_ret) {
  13331. return trust_ret;
  13332. }
  13333. }
  13334. conn->ssl = SSL_new(s);
  13335. if (conn->ssl == NULL) {
  13336. return 0;
  13337. }
  13338. SSL_set_app_data(conn->ssl, (char *)conn);
  13339. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13340. if (ret != 1) {
  13341. err = SSL_get_error(conn->ssl, ret);
  13342. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13343. SSL_free(conn->ssl);
  13344. conn->ssl = NULL;
  13345. OPENSSL_REMOVE_THREAD_STATE();
  13346. return 0;
  13347. }
  13348. if (client_options) {
  13349. if (client_options->host_name) {
  13350. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13351. }
  13352. }
  13353. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13354. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13355. /* NOTE: The loop below acts as a back-off, so we can end
  13356. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13357. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13358. }
  13359. /* SSL functions may fail and require to be called again:
  13360. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13361. * Here "func" could be SSL_connect or SSL_accept. */
  13362. for (i = 0; i <= timeout; i += 50) {
  13363. ret = func(conn->ssl);
  13364. if (ret != 1) {
  13365. err = SSL_get_error(conn->ssl, ret);
  13366. if ((err == SSL_ERROR_WANT_CONNECT)
  13367. || (err == SSL_ERROR_WANT_ACCEPT)
  13368. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13369. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13370. if (*stop_server) {
  13371. /* Don't wait if the server is going to be stopped. */
  13372. break;
  13373. }
  13374. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13375. /* Simply retry the function call. */
  13376. mg_sleep(50);
  13377. } else {
  13378. /* Need to retry the function call "later".
  13379. * See https://linux.die.net/man/3/ssl_get_error
  13380. * This is typical for non-blocking sockets. */
  13381. struct mg_pollfd pfd;
  13382. int pollres;
  13383. pfd.fd = conn->client.sock;
  13384. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13385. || (err == SSL_ERROR_WANT_WRITE))
  13386. ? POLLOUT
  13387. : POLLIN;
  13388. pollres = mg_poll(&pfd, 1, 50, stop_server);
  13389. if (pollres < 0) {
  13390. /* Break if error occured (-1)
  13391. * or server shutdown (-2) */
  13392. break;
  13393. }
  13394. }
  13395. } else if (err == SSL_ERROR_SYSCALL) {
  13396. /* This is an IO error. Look at errno. */
  13397. err = errno;
  13398. mg_cry_internal(conn, "SSL syscall error %i", err);
  13399. break;
  13400. } else {
  13401. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13402. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13403. break;
  13404. }
  13405. ERR_clear_error();
  13406. } else {
  13407. /* success */
  13408. break;
  13409. }
  13410. }
  13411. if (ret != 1) {
  13412. SSL_free(conn->ssl);
  13413. conn->ssl = NULL;
  13414. OPENSSL_REMOVE_THREAD_STATE();
  13415. return 0;
  13416. }
  13417. return 1;
  13418. }
  13419. /* Return OpenSSL error message (from CRYPTO lib) */
  13420. static const char *
  13421. ssl_error(void)
  13422. {
  13423. unsigned long err;
  13424. err = ERR_get_error();
  13425. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13426. }
  13427. static int
  13428. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13429. {
  13430. int i;
  13431. const char hexdigit[] = "0123456789abcdef";
  13432. if ((memlen <= 0) || (buflen <= 0)) {
  13433. return 0;
  13434. }
  13435. if (buflen < (3 * memlen)) {
  13436. return 0;
  13437. }
  13438. for (i = 0; i < memlen; i++) {
  13439. if (i > 0) {
  13440. buf[3 * i - 1] = ' ';
  13441. }
  13442. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13443. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13444. }
  13445. buf[3 * memlen - 1] = 0;
  13446. return 1;
  13447. }
  13448. static void
  13449. ssl_get_client_cert_info(struct mg_connection *conn)
  13450. {
  13451. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13452. if (cert) {
  13453. char str_subject[1024];
  13454. char str_issuer[1024];
  13455. char str_finger[1024];
  13456. unsigned char buf[256];
  13457. char *str_serial = NULL;
  13458. unsigned int ulen;
  13459. int ilen;
  13460. unsigned char *tmp_buf;
  13461. unsigned char *tmp_p;
  13462. /* Handle to algorithm used for fingerprint */
  13463. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13464. /* Get Subject and issuer */
  13465. X509_NAME *subj = X509_get_subject_name(cert);
  13466. X509_NAME *iss = X509_get_issuer_name(cert);
  13467. /* Get serial number */
  13468. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13469. /* Translate serial number to a hex string */
  13470. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13471. str_serial = BN_bn2hex(serial_bn);
  13472. BN_free(serial_bn);
  13473. /* Translate subject and issuer to a string */
  13474. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13475. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13476. /* Calculate SHA1 fingerprint and store as a hex string */
  13477. ulen = 0;
  13478. /* ASN1_digest is deprecated. Do the calculation manually,
  13479. * using EVP_Digest. */
  13480. ilen = i2d_X509(cert, NULL);
  13481. tmp_buf = (ilen > 0)
  13482. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13483. conn->phys_ctx)
  13484. : NULL;
  13485. if (tmp_buf) {
  13486. tmp_p = tmp_buf;
  13487. (void)i2d_X509(cert, &tmp_p);
  13488. if (!EVP_Digest(
  13489. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13490. ulen = 0;
  13491. }
  13492. mg_free(tmp_buf);
  13493. }
  13494. if (!hexdump2string(
  13495. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13496. *str_finger = 0;
  13497. }
  13498. conn->request_info.client_cert = (struct mg_client_cert *)
  13499. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13500. if (conn->request_info.client_cert) {
  13501. conn->request_info.client_cert->peer_cert = (void *)cert;
  13502. conn->request_info.client_cert->subject =
  13503. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13504. conn->request_info.client_cert->issuer =
  13505. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13506. conn->request_info.client_cert->serial =
  13507. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13508. conn->request_info.client_cert->finger =
  13509. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13510. } else {
  13511. mg_cry_internal(conn,
  13512. "%s",
  13513. "Out of memory: Cannot allocate memory for client "
  13514. "certificate");
  13515. }
  13516. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13517. * see https://linux.die.net/man/3/bn_bn2hex */
  13518. OPENSSL_free(str_serial);
  13519. }
  13520. }
  13521. #if defined(OPENSSL_API_1_1)
  13522. #else
  13523. static void
  13524. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13525. {
  13526. (void)line;
  13527. (void)file;
  13528. if (mode & 1) {
  13529. /* 1 is CRYPTO_LOCK */
  13530. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13531. } else {
  13532. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13533. }
  13534. }
  13535. #endif /* OPENSSL_API_1_1 */
  13536. #if !defined(NO_SSL_DL)
  13537. static void *
  13538. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13539. {
  13540. union {
  13541. void *p;
  13542. void (*fp)(void);
  13543. } u;
  13544. void *dll_handle;
  13545. struct ssl_func *fp;
  13546. int ok;
  13547. int truncated = 0;
  13548. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13549. mg_snprintf(NULL,
  13550. NULL, /* No truncation check for ebuf */
  13551. ebuf,
  13552. ebuf_len,
  13553. "%s: cannot load %s",
  13554. __func__,
  13555. dll_name);
  13556. return NULL;
  13557. }
  13558. ok = 1;
  13559. for (fp = sw; fp->name != NULL; fp++) {
  13560. #if defined(_WIN32)
  13561. /* GetProcAddress() returns pointer to function */
  13562. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13563. #else
  13564. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13565. * pointers to function pointers. We need to use a union to make a
  13566. * cast. */
  13567. u.p = dlsym(dll_handle, fp->name);
  13568. #endif /* _WIN32 */
  13569. if (u.fp == NULL) {
  13570. if (ok) {
  13571. mg_snprintf(NULL,
  13572. &truncated,
  13573. ebuf,
  13574. ebuf_len,
  13575. "%s: %s: cannot find %s",
  13576. __func__,
  13577. dll_name,
  13578. fp->name);
  13579. ok = 0;
  13580. } else {
  13581. size_t cur_len = strlen(ebuf);
  13582. if (!truncated) {
  13583. mg_snprintf(NULL,
  13584. &truncated,
  13585. ebuf + cur_len,
  13586. ebuf_len - cur_len - 3,
  13587. ", %s",
  13588. fp->name);
  13589. if (truncated) {
  13590. /* If truncated, add "..." */
  13591. strcat(ebuf, "...");
  13592. }
  13593. }
  13594. }
  13595. /* Debug:
  13596. * printf("Missing function: %s\n", fp->name); */
  13597. } else {
  13598. fp->ptr = u.fp;
  13599. }
  13600. }
  13601. if (!ok) {
  13602. (void)dlclose(dll_handle);
  13603. return NULL;
  13604. }
  13605. return dll_handle;
  13606. }
  13607. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13608. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13609. #endif /* NO_SSL_DL */
  13610. #if defined(SSL_ALREADY_INITIALIZED)
  13611. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13612. #else
  13613. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13614. #endif
  13615. static int
  13616. initialize_ssl(char *ebuf, size_t ebuf_len)
  13617. {
  13618. #if defined(OPENSSL_API_1_1)
  13619. if (ebuf_len > 0) {
  13620. ebuf[0] = 0;
  13621. }
  13622. #if !defined(NO_SSL_DL)
  13623. if (!cryptolib_dll_handle) {
  13624. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13625. if (!cryptolib_dll_handle) {
  13626. mg_snprintf(NULL,
  13627. NULL, /* No truncation check for ebuf */
  13628. ebuf,
  13629. ebuf_len,
  13630. "%s: error loading library %s",
  13631. __func__,
  13632. CRYPTO_LIB);
  13633. DEBUG_TRACE("%s", ebuf);
  13634. return 0;
  13635. }
  13636. }
  13637. #endif /* NO_SSL_DL */
  13638. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13639. return 1;
  13640. }
  13641. #else /* not OPENSSL_API_1_1 */
  13642. int i, num_locks;
  13643. size_t size;
  13644. if (ebuf_len > 0) {
  13645. ebuf[0] = 0;
  13646. }
  13647. #if !defined(NO_SSL_DL)
  13648. if (!cryptolib_dll_handle) {
  13649. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13650. if (!cryptolib_dll_handle) {
  13651. mg_snprintf(NULL,
  13652. NULL, /* No truncation check for ebuf */
  13653. ebuf,
  13654. ebuf_len,
  13655. "%s: error loading library %s",
  13656. __func__,
  13657. CRYPTO_LIB);
  13658. DEBUG_TRACE("%s", ebuf);
  13659. return 0;
  13660. }
  13661. }
  13662. #endif /* NO_SSL_DL */
  13663. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13664. return 1;
  13665. }
  13666. /* Initialize locking callbacks, needed for thread safety.
  13667. * http://www.openssl.org/support/faq.html#PROG1
  13668. */
  13669. num_locks = CRYPTO_num_locks();
  13670. if (num_locks < 0) {
  13671. num_locks = 0;
  13672. }
  13673. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13674. /* allocate mutex array, if required */
  13675. if (num_locks == 0) {
  13676. /* No mutex array required */
  13677. ssl_mutexes = NULL;
  13678. } else {
  13679. /* Mutex array required - allocate it */
  13680. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13681. /* Check OOM */
  13682. if (ssl_mutexes == NULL) {
  13683. mg_snprintf(NULL,
  13684. NULL, /* No truncation check for ebuf */
  13685. ebuf,
  13686. ebuf_len,
  13687. "%s: cannot allocate mutexes: %s",
  13688. __func__,
  13689. ssl_error());
  13690. DEBUG_TRACE("%s", ebuf);
  13691. return 0;
  13692. }
  13693. /* initialize mutex array */
  13694. for (i = 0; i < num_locks; i++) {
  13695. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13696. mg_snprintf(NULL,
  13697. NULL, /* No truncation check for ebuf */
  13698. ebuf,
  13699. ebuf_len,
  13700. "%s: error initializing mutex %i of %i",
  13701. __func__,
  13702. i,
  13703. num_locks);
  13704. DEBUG_TRACE("%s", ebuf);
  13705. mg_free(ssl_mutexes);
  13706. return 0;
  13707. }
  13708. }
  13709. }
  13710. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13711. CRYPTO_set_id_callback(&mg_current_thread_id);
  13712. #endif /* OPENSSL_API_1_1 */
  13713. #if !defined(NO_SSL_DL)
  13714. if (!ssllib_dll_handle) {
  13715. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13716. if (!ssllib_dll_handle) {
  13717. #if !defined(OPENSSL_API_1_1)
  13718. mg_free(ssl_mutexes);
  13719. #endif
  13720. DEBUG_TRACE("%s", ebuf);
  13721. return 0;
  13722. }
  13723. }
  13724. #endif /* NO_SSL_DL */
  13725. #if defined(OPENSSL_API_1_1)
  13726. /* Initialize SSL library */
  13727. OPENSSL_init_ssl(0, NULL);
  13728. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13729. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13730. NULL);
  13731. #else
  13732. /* Initialize SSL library */
  13733. SSL_library_init();
  13734. SSL_load_error_strings();
  13735. #endif
  13736. return 1;
  13737. }
  13738. static int
  13739. ssl_use_pem_file(struct mg_context *phys_ctx,
  13740. struct mg_domain_context *dom_ctx,
  13741. const char *pem,
  13742. const char *chain)
  13743. {
  13744. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13745. mg_cry_ctx_internal(phys_ctx,
  13746. "%s: cannot open certificate file %s: %s",
  13747. __func__,
  13748. pem,
  13749. ssl_error());
  13750. return 0;
  13751. }
  13752. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13753. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13754. mg_cry_ctx_internal(phys_ctx,
  13755. "%s: cannot open private key file %s: %s",
  13756. __func__,
  13757. pem,
  13758. ssl_error());
  13759. return 0;
  13760. }
  13761. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13762. mg_cry_ctx_internal(phys_ctx,
  13763. "%s: certificate and private key do not match: %s",
  13764. __func__,
  13765. pem);
  13766. return 0;
  13767. }
  13768. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13769. * chain files that contain private keys and certificates in
  13770. * SSL_CTX_use_certificate_chain_file.
  13771. * The CivetWeb-Server used pem-Files that contained both information.
  13772. * In order to make wolfSSL work, it is split in two files.
  13773. * One file that contains key and certificate used by the server and
  13774. * an optional chain file for the ssl stack.
  13775. */
  13776. if (chain) {
  13777. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13778. mg_cry_ctx_internal(phys_ctx,
  13779. "%s: cannot use certificate chain file %s: %s",
  13780. __func__,
  13781. chain,
  13782. ssl_error());
  13783. return 0;
  13784. }
  13785. }
  13786. return 1;
  13787. }
  13788. #if defined(OPENSSL_API_1_1)
  13789. static unsigned long
  13790. ssl_get_protocol(int version_id)
  13791. {
  13792. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13793. if (version_id > 0)
  13794. ret |= SSL_OP_NO_SSLv2;
  13795. if (version_id > 1)
  13796. ret |= SSL_OP_NO_SSLv3;
  13797. if (version_id > 2)
  13798. ret |= SSL_OP_NO_TLSv1;
  13799. if (version_id > 3)
  13800. ret |= SSL_OP_NO_TLSv1_1;
  13801. if (version_id > 4)
  13802. ret |= SSL_OP_NO_TLSv1_2;
  13803. #if defined(SSL_OP_NO_TLSv1_3)
  13804. if (version_id > 5)
  13805. ret |= SSL_OP_NO_TLSv1_3;
  13806. #endif
  13807. return ret;
  13808. }
  13809. #else
  13810. static long
  13811. ssl_get_protocol(int version_id)
  13812. {
  13813. long ret = (long)SSL_OP_ALL;
  13814. if (version_id > 0)
  13815. ret |= SSL_OP_NO_SSLv2;
  13816. if (version_id > 1)
  13817. ret |= SSL_OP_NO_SSLv3;
  13818. if (version_id > 2)
  13819. ret |= SSL_OP_NO_TLSv1;
  13820. if (version_id > 3)
  13821. ret |= SSL_OP_NO_TLSv1_1;
  13822. if (version_id > 4)
  13823. ret |= SSL_OP_NO_TLSv1_2;
  13824. #if defined(SSL_OP_NO_TLSv1_3)
  13825. if (version_id > 5)
  13826. ret |= SSL_OP_NO_TLSv1_3;
  13827. #endif
  13828. return ret;
  13829. }
  13830. #endif /* OPENSSL_API_1_1 */
  13831. /* SSL callback documentation:
  13832. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13833. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13834. * https://linux.die.net/man/3/ssl_set_info_callback */
  13835. /* Note: There is no "const" for the first argument in the documentation
  13836. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13837. * / OpenSSL compatibility layers have it. Having a different definition will
  13838. * cause a warning in C and an error in C++. Use "const SSL *", while
  13839. * automatical conversion from "SSL *" works for all compilers, but not other
  13840. * way around */
  13841. static void
  13842. ssl_info_callback(const SSL *ssl, int what, int ret)
  13843. {
  13844. (void)ret;
  13845. if (what & SSL_CB_HANDSHAKE_START) {
  13846. SSL_get_app_data(ssl);
  13847. }
  13848. if (what & SSL_CB_HANDSHAKE_DONE) {
  13849. /* TODO: check for openSSL 1.1 */
  13850. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13851. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13852. }
  13853. }
  13854. static int
  13855. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13856. {
  13857. struct mg_context *ctx = (struct mg_context *)arg;
  13858. struct mg_domain_context *dom =
  13859. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13860. #if defined(GCC_DIAGNOSTIC)
  13861. #pragma GCC diagnostic push
  13862. #pragma GCC diagnostic ignored "-Wcast-align"
  13863. #endif /* defined(GCC_DIAGNOSTIC) */
  13864. /* We used an aligned pointer in SSL_set_app_data */
  13865. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13866. #if defined(GCC_DIAGNOSTIC)
  13867. #pragma GCC diagnostic pop
  13868. #endif /* defined(GCC_DIAGNOSTIC) */
  13869. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13870. (void)ad;
  13871. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13872. DEBUG_TRACE("%s", "internal error - assertion failed");
  13873. return SSL_TLSEXT_ERR_NOACK;
  13874. }
  13875. /* Old clients (Win XP) will not support SNI. Then, there
  13876. * is no server name available in the request - we can
  13877. * only work with the default certificate.
  13878. * Multiple HTTPS hosts on one IP+port are only possible
  13879. * with a certificate containing all alternative names.
  13880. */
  13881. if ((servername == NULL) || (*servername == 0)) {
  13882. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13883. conn->dom_ctx = &(ctx->dd);
  13884. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13885. return SSL_TLSEXT_ERR_NOACK;
  13886. }
  13887. DEBUG_TRACE("TLS connection to host %s", servername);
  13888. while (dom) {
  13889. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13890. /* Found matching domain */
  13891. DEBUG_TRACE("TLS domain %s found",
  13892. dom->config[AUTHENTICATION_DOMAIN]);
  13893. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13894. conn->dom_ctx = dom;
  13895. return SSL_TLSEXT_ERR_OK;
  13896. }
  13897. dom = dom->next;
  13898. }
  13899. /* Default domain */
  13900. DEBUG_TRACE("TLS default domain %s used",
  13901. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13902. conn->dom_ctx = &(ctx->dd);
  13903. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13904. return SSL_TLSEXT_ERR_OK;
  13905. }
  13906. /* Setup SSL CTX as required by CivetWeb */
  13907. static int
  13908. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13909. struct mg_domain_context *dom_ctx,
  13910. const char *pem,
  13911. const char *chain)
  13912. {
  13913. int callback_ret;
  13914. int should_verify_peer;
  13915. int peer_certificate_optional;
  13916. const char *ca_path;
  13917. const char *ca_file;
  13918. int use_default_verify_paths;
  13919. int verify_depth;
  13920. struct timespec now_mt;
  13921. md5_byte_t ssl_context_id[16];
  13922. md5_state_t md5state;
  13923. int protocol_ver;
  13924. #if defined(OPENSSL_API_1_1)
  13925. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13926. mg_cry_ctx_internal(phys_ctx,
  13927. "SSL_CTX_new (server) error: %s",
  13928. ssl_error());
  13929. return 0;
  13930. }
  13931. #else
  13932. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13933. mg_cry_ctx_internal(phys_ctx,
  13934. "SSL_CTX_new (server) error: %s",
  13935. ssl_error());
  13936. return 0;
  13937. }
  13938. #endif /* OPENSSL_API_1_1 */
  13939. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13940. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13941. | SSL_OP_NO_TLSv1_1);
  13942. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13943. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13944. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13945. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13946. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13947. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13948. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13949. #if defined(SSL_OP_NO_RENEGOTIATION)
  13950. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13951. #endif
  13952. #if !defined(NO_SSL_DL)
  13953. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13954. #endif /* NO_SSL_DL */
  13955. /* In SSL documentation examples callback defined without const specifier
  13956. * 'void (*)(SSL *, int, int)' See:
  13957. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13958. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13959. * But in the source code const SSL is used:
  13960. * 'void (*)(const SSL *, int, int)' See:
  13961. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13962. * Problem about wrong documentation described, but not resolved:
  13963. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13964. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13965. * But when compiled with modern C++ compiler, correct const should be
  13966. * provided
  13967. */
  13968. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13969. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13970. ssl_servername_callback);
  13971. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13972. /* If a callback has been specified, call it. */
  13973. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13974. ? 0
  13975. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13976. phys_ctx->user_data));
  13977. /* If callback returns 0, civetweb sets up the SSL certificate.
  13978. * If it returns 1, civetweb assumes the calback already did this.
  13979. * If it returns -1, initializing ssl fails. */
  13980. if (callback_ret < 0) {
  13981. mg_cry_ctx_internal(phys_ctx,
  13982. "SSL callback returned error: %i",
  13983. callback_ret);
  13984. return 0;
  13985. }
  13986. if (callback_ret > 0) {
  13987. /* Callback did everything. */
  13988. return 1;
  13989. }
  13990. /* If a domain callback has been specified, call it. */
  13991. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  13992. ? 0
  13993. : (phys_ctx->callbacks.init_ssl_domain(
  13994. dom_ctx->config[AUTHENTICATION_DOMAIN],
  13995. dom_ctx->ssl_ctx,
  13996. phys_ctx->user_data));
  13997. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  13998. * If it returns 1, civetweb assumes the calback already did this.
  13999. * If it returns -1, initializing ssl fails. */
  14000. if (callback_ret < 0) {
  14001. mg_cry_ctx_internal(phys_ctx,
  14002. "Domain SSL callback returned error: %i",
  14003. callback_ret);
  14004. return 0;
  14005. }
  14006. if (callback_ret > 0) {
  14007. /* Domain callback did everything. */
  14008. return 1;
  14009. }
  14010. /* Use some combination of start time, domain and port as a SSL
  14011. * context ID. This should be unique on the current machine. */
  14012. md5_init(&md5state);
  14013. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14014. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14015. md5_append(&md5state,
  14016. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14017. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14018. md5_append(&md5state,
  14019. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14020. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14021. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14022. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14023. md5_finish(&md5state, ssl_context_id);
  14024. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14025. (unsigned char *)ssl_context_id,
  14026. sizeof(ssl_context_id));
  14027. if (pem != NULL) {
  14028. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14029. return 0;
  14030. }
  14031. }
  14032. /* Should we support client certificates? */
  14033. /* Default is "no". */
  14034. should_verify_peer = 0;
  14035. peer_certificate_optional = 0;
  14036. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14037. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14038. /* Yes, they are mandatory */
  14039. should_verify_peer = 1;
  14040. peer_certificate_optional = 0;
  14041. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14042. "optional")
  14043. == 0) {
  14044. /* Yes, they are optional */
  14045. should_verify_peer = 1;
  14046. peer_certificate_optional = 1;
  14047. }
  14048. }
  14049. use_default_verify_paths =
  14050. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14051. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14052. == 0);
  14053. if (should_verify_peer) {
  14054. ca_path = dom_ctx->config[SSL_CA_PATH];
  14055. ca_file = dom_ctx->config[SSL_CA_FILE];
  14056. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14057. != 1) {
  14058. mg_cry_ctx_internal(phys_ctx,
  14059. "SSL_CTX_load_verify_locations error: %s "
  14060. "ssl_verify_peer requires setting "
  14061. "either ssl_ca_path or ssl_ca_file. "
  14062. "Is any of them present in the "
  14063. ".conf file?",
  14064. ssl_error());
  14065. return 0;
  14066. }
  14067. if (peer_certificate_optional) {
  14068. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14069. } else {
  14070. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14071. SSL_VERIFY_PEER
  14072. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14073. NULL);
  14074. }
  14075. if (use_default_verify_paths
  14076. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14077. mg_cry_ctx_internal(phys_ctx,
  14078. "SSL_CTX_set_default_verify_paths error: %s",
  14079. ssl_error());
  14080. return 0;
  14081. }
  14082. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14083. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14084. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14085. }
  14086. }
  14087. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14088. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14089. dom_ctx->config[SSL_CIPHER_LIST])
  14090. != 1) {
  14091. mg_cry_ctx_internal(phys_ctx,
  14092. "SSL_CTX_set_cipher_list error: %s",
  14093. ssl_error());
  14094. }
  14095. }
  14096. return 1;
  14097. }
  14098. /* Check if SSL is required.
  14099. * If so, dynamically load SSL library
  14100. * and set up ctx->ssl_ctx pointer. */
  14101. static int
  14102. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14103. {
  14104. void *ssl_ctx = 0;
  14105. int callback_ret;
  14106. const char *pem;
  14107. const char *chain;
  14108. char ebuf[128];
  14109. if (!phys_ctx) {
  14110. return 0;
  14111. }
  14112. if (!dom_ctx) {
  14113. dom_ctx = &(phys_ctx->dd);
  14114. }
  14115. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14116. /* No SSL port is set. No need to setup SSL. */
  14117. return 1;
  14118. }
  14119. /* Check for external SSL_CTX */
  14120. callback_ret =
  14121. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14122. ? 0
  14123. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14124. phys_ctx->user_data));
  14125. if (callback_ret < 0) {
  14126. mg_cry_ctx_internal(phys_ctx,
  14127. "external_ssl_ctx callback returned error: %i",
  14128. callback_ret);
  14129. return 0;
  14130. } else if (callback_ret > 0) {
  14131. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14132. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14133. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14134. return 0;
  14135. }
  14136. return 1;
  14137. }
  14138. /* Check for external domain SSL_CTX */
  14139. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14140. ? 0
  14141. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14142. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14143. &ssl_ctx,
  14144. phys_ctx->user_data));
  14145. if (callback_ret < 0) {
  14146. mg_cry_ctx_internal(
  14147. phys_ctx,
  14148. "external_ssl_ctx_domain callback returned error: %i",
  14149. callback_ret);
  14150. return 0;
  14151. } else if (callback_ret > 0) {
  14152. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14153. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14154. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14155. return 0;
  14156. }
  14157. return 1;
  14158. }
  14159. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return 0,
  14160. * CivetWeb should continue initializing SSL */
  14161. /* If PEM file is not specified and the init_ssl callbacks
  14162. * are not specified, setup will fail. */
  14163. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14164. && (phys_ctx->callbacks.init_ssl == NULL)
  14165. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14166. /* No certificate and no init_ssl callbacks:
  14167. * Essential data to set up TLS is missing.
  14168. */
  14169. mg_cry_ctx_internal(phys_ctx,
  14170. "Initializing SSL failed: -%s is not set",
  14171. config_options[SSL_CERTIFICATE].name);
  14172. return 0;
  14173. }
  14174. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14175. if (chain == NULL) {
  14176. chain = pem;
  14177. }
  14178. if ((chain != NULL) && (*chain == 0)) {
  14179. chain = NULL;
  14180. }
  14181. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14182. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14183. return 0;
  14184. }
  14185. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14186. }
  14187. static void
  14188. uninitialize_ssl(void)
  14189. {
  14190. #if defined(OPENSSL_API_1_1)
  14191. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14192. /* Shutdown according to
  14193. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14194. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14195. */
  14196. CONF_modules_unload(1);
  14197. #else
  14198. int i;
  14199. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14200. /* Shutdown according to
  14201. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14202. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14203. */
  14204. CRYPTO_set_locking_callback(NULL);
  14205. CRYPTO_set_id_callback(NULL);
  14206. ENGINE_cleanup();
  14207. CONF_modules_unload(1);
  14208. ERR_free_strings();
  14209. EVP_cleanup();
  14210. CRYPTO_cleanup_all_ex_data();
  14211. OPENSSL_REMOVE_THREAD_STATE();
  14212. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14213. pthread_mutex_destroy(&ssl_mutexes[i]);
  14214. }
  14215. mg_free(ssl_mutexes);
  14216. ssl_mutexes = NULL;
  14217. #endif /* OPENSSL_API_1_1 */
  14218. }
  14219. }
  14220. #endif /* !NO_SSL */
  14221. #if !defined(NO_FILESYSTEMS)
  14222. static int
  14223. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14224. {
  14225. if (phys_ctx) {
  14226. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14227. const char *path;
  14228. struct mg_connection fc;
  14229. if (!dom_ctx) {
  14230. dom_ctx = &(phys_ctx->dd);
  14231. }
  14232. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14233. if ((path != NULL)
  14234. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14235. mg_cry_ctx_internal(phys_ctx,
  14236. "Cannot open %s: %s",
  14237. path,
  14238. strerror(ERRNO));
  14239. return 0;
  14240. }
  14241. return 1;
  14242. }
  14243. return 0;
  14244. }
  14245. #endif /* NO_FILESYSTEMS */
  14246. static int
  14247. set_acl_option(struct mg_context *phys_ctx)
  14248. {
  14249. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14250. }
  14251. static void
  14252. reset_per_request_attributes(struct mg_connection *conn)
  14253. {
  14254. if (!conn) {
  14255. return;
  14256. }
  14257. conn->connection_type =
  14258. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14259. conn->num_bytes_sent = conn->consumed_content = 0;
  14260. conn->path_info = NULL;
  14261. conn->status_code = -1;
  14262. conn->content_len = -1;
  14263. conn->is_chunked = 0;
  14264. conn->must_close = 0;
  14265. conn->request_len = 0;
  14266. conn->throttle = 0;
  14267. conn->accept_gzip = 0;
  14268. conn->response_info.content_length = conn->request_info.content_length = -1;
  14269. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14270. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14271. conn->response_info.status_text = NULL;
  14272. conn->response_info.status_code = 0;
  14273. conn->request_info.remote_user = NULL;
  14274. conn->request_info.request_method = NULL;
  14275. conn->request_info.request_uri = NULL;
  14276. conn->request_info.local_uri = NULL;
  14277. #if defined(MG_LEGACY_INTERFACE)
  14278. /* Legacy before split into local_uri and request_uri */
  14279. conn->request_info.uri = NULL;
  14280. #endif
  14281. }
  14282. static int
  14283. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14284. {
  14285. if (setsockopt(sock,
  14286. IPPROTO_TCP,
  14287. TCP_NODELAY,
  14288. (SOCK_OPT_TYPE)&nodelay_on,
  14289. sizeof(nodelay_on))
  14290. != 0) {
  14291. /* Error */
  14292. return 1;
  14293. }
  14294. /* OK */
  14295. return 0;
  14296. }
  14297. #if !defined(__ZEPHYR__)
  14298. static void
  14299. close_socket_gracefully(struct mg_connection *conn)
  14300. {
  14301. #if defined(_WIN32)
  14302. char buf[MG_BUF_LEN];
  14303. int n;
  14304. #endif
  14305. struct linger linger;
  14306. int error_code = 0;
  14307. int linger_timeout = -2;
  14308. socklen_t opt_len = sizeof(error_code);
  14309. if (!conn) {
  14310. return;
  14311. }
  14312. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14313. * "Note that enabling a nonzero timeout on a nonblocking socket
  14314. * is not recommended.", so set it to blocking now */
  14315. set_blocking_mode(conn->client.sock);
  14316. /* Send FIN to the client */
  14317. shutdown(conn->client.sock, SHUTDOWN_WR);
  14318. #if defined(_WIN32)
  14319. /* Read and discard pending incoming data. If we do not do that and
  14320. * close
  14321. * the socket, the data in the send buffer may be discarded. This
  14322. * behaviour is seen on Windows, when client keeps sending data
  14323. * when server decides to close the connection; then when client
  14324. * does recv() it gets no data back. */
  14325. do {
  14326. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14327. } while (n > 0);
  14328. #endif
  14329. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14330. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14331. }
  14332. /* Set linger option according to configuration */
  14333. if (linger_timeout >= 0) {
  14334. /* Set linger option to avoid socket hanging out after close. This
  14335. * prevent ephemeral port exhaust problem under high QPS. */
  14336. linger.l_onoff = 1;
  14337. #if defined(_MSC_VER)
  14338. #pragma warning(push)
  14339. #pragma warning(disable : 4244)
  14340. #endif
  14341. #if defined(GCC_DIAGNOSTIC)
  14342. #pragma GCC diagnostic push
  14343. #pragma GCC diagnostic ignored "-Wconversion"
  14344. #endif
  14345. /* Data type of linger structure elements may differ,
  14346. * so we don't know what cast we need here.
  14347. * Disable type conversion warnings. */
  14348. linger.l_linger = (linger_timeout + 999) / 1000;
  14349. #if defined(GCC_DIAGNOSTIC)
  14350. #pragma GCC diagnostic pop
  14351. #endif
  14352. #if defined(_MSC_VER)
  14353. #pragma warning(pop)
  14354. #endif
  14355. } else {
  14356. linger.l_onoff = 0;
  14357. linger.l_linger = 0;
  14358. }
  14359. if (linger_timeout < -1) {
  14360. /* Default: don't configure any linger */
  14361. } else if (getsockopt(conn->client.sock,
  14362. SOL_SOCKET,
  14363. SO_ERROR,
  14364. #if defined(_WIN32) /* WinSock uses different data type here */
  14365. (char *)&error_code,
  14366. #else
  14367. &error_code,
  14368. #endif
  14369. &opt_len)
  14370. != 0) {
  14371. /* Cannot determine if socket is already closed. This should
  14372. * not occur and never did in a test. Log an error message
  14373. * and continue. */
  14374. mg_cry_internal(conn,
  14375. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14376. __func__,
  14377. strerror(ERRNO));
  14378. #if defined(_WIN32)
  14379. } else if (error_code == WSAECONNRESET) {
  14380. #else
  14381. } else if (error_code == ECONNRESET) {
  14382. #endif
  14383. /* Socket already closed by client/peer, close socket without linger
  14384. */
  14385. } else {
  14386. /* Set linger timeout */
  14387. if (setsockopt(conn->client.sock,
  14388. SOL_SOCKET,
  14389. SO_LINGER,
  14390. (char *)&linger,
  14391. sizeof(linger))
  14392. != 0) {
  14393. mg_cry_internal(
  14394. conn,
  14395. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14396. __func__,
  14397. linger.l_onoff,
  14398. linger.l_linger,
  14399. strerror(ERRNO));
  14400. }
  14401. }
  14402. /* Now we know that our FIN is ACK-ed, safe to close */
  14403. closesocket(conn->client.sock);
  14404. conn->client.sock = INVALID_SOCKET;
  14405. }
  14406. #endif
  14407. static void
  14408. close_connection(struct mg_connection *conn)
  14409. {
  14410. #if defined(USE_SERVER_STATS)
  14411. conn->conn_state = 6; /* to close */
  14412. #endif
  14413. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14414. if (conn->lua_websocket_state) {
  14415. lua_websocket_close(conn, conn->lua_websocket_state);
  14416. conn->lua_websocket_state = NULL;
  14417. }
  14418. #endif
  14419. mg_lock_connection(conn);
  14420. /* Set close flag, so keep-alive loops will stop */
  14421. conn->must_close = 1;
  14422. /* call the connection_close callback if assigned */
  14423. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14424. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14425. conn->phys_ctx->callbacks.connection_close(conn);
  14426. }
  14427. }
  14428. /* Reset user data, after close callback is called.
  14429. * Do not reuse it. If the user needs a destructor,
  14430. * it must be done in the connection_close callback. */
  14431. mg_set_user_connection_data(conn, NULL);
  14432. #if defined(USE_SERVER_STATS)
  14433. conn->conn_state = 7; /* closing */
  14434. #endif
  14435. #if !defined(NO_SSL)
  14436. if (conn->ssl != NULL) {
  14437. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14438. */
  14439. SSL_shutdown(conn->ssl);
  14440. SSL_free(conn->ssl);
  14441. OPENSSL_REMOVE_THREAD_STATE();
  14442. conn->ssl = NULL;
  14443. }
  14444. #endif
  14445. if (conn->client.sock != INVALID_SOCKET) {
  14446. #if defined(__ZEPHYR__)
  14447. closesocket(conn->client.sock);
  14448. #else
  14449. close_socket_gracefully(conn);
  14450. #endif
  14451. conn->client.sock = INVALID_SOCKET;
  14452. }
  14453. if (conn->host) {
  14454. mg_free((void *)conn->host);
  14455. conn->host = NULL;
  14456. }
  14457. mg_unlock_connection(conn);
  14458. #if defined(USE_SERVER_STATS)
  14459. conn->conn_state = 8; /* closed */
  14460. #endif
  14461. }
  14462. void
  14463. mg_close_connection(struct mg_connection *conn)
  14464. {
  14465. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14466. return;
  14467. }
  14468. #if defined(USE_WEBSOCKET)
  14469. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14470. if (conn->in_websocket_handling) {
  14471. /* Set close flag, so the server thread can exit. */
  14472. conn->must_close = 1;
  14473. return;
  14474. }
  14475. }
  14476. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14477. unsigned int i;
  14478. /* client context: loops must end */
  14479. conn->phys_ctx->stop_flag = 1;
  14480. conn->must_close = 1;
  14481. /* We need to get the client thread out of the select/recv call
  14482. * here. */
  14483. /* Since we use a sleep quantum of some seconds to check for recv
  14484. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14485. /* join worker thread */
  14486. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14487. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14488. }
  14489. }
  14490. #endif /* defined(USE_WEBSOCKET) */
  14491. close_connection(conn);
  14492. #if !defined(NO_SSL)
  14493. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14494. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14495. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14496. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14497. }
  14498. #endif
  14499. #if defined(USE_WEBSOCKET)
  14500. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14501. mg_free(conn->phys_ctx->worker_threadids);
  14502. (void)pthread_mutex_destroy(&conn->mutex);
  14503. mg_free(conn);
  14504. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14505. mg_free(conn);
  14506. }
  14507. #else
  14508. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14509. mg_free(conn);
  14510. }
  14511. #endif /* defined(USE_WEBSOCKET) */
  14512. }
  14513. static struct mg_connection *
  14514. mg_connect_client_impl(const struct mg_client_options *client_options,
  14515. int use_ssl,
  14516. char *ebuf,
  14517. size_t ebuf_len)
  14518. {
  14519. struct mg_connection *conn = NULL;
  14520. SOCKET sock;
  14521. union usa sa;
  14522. struct sockaddr *psa;
  14523. socklen_t len;
  14524. unsigned max_req_size =
  14525. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14526. /* Size of structures, aligned to 8 bytes */
  14527. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14528. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14529. conn =
  14530. (struct mg_connection *)mg_calloc(1,
  14531. conn_size + ctx_size + max_req_size);
  14532. if (conn == NULL) {
  14533. mg_snprintf(NULL,
  14534. NULL, /* No truncation check for ebuf */
  14535. ebuf,
  14536. ebuf_len,
  14537. "calloc(): %s",
  14538. strerror(ERRNO));
  14539. return NULL;
  14540. }
  14541. #if defined(GCC_DIAGNOSTIC)
  14542. #pragma GCC diagnostic push
  14543. #pragma GCC diagnostic ignored "-Wcast-align"
  14544. #endif /* defined(GCC_DIAGNOSTIC) */
  14545. /* conn_size is aligned to 8 bytes */
  14546. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14547. #if defined(GCC_DIAGNOSTIC)
  14548. #pragma GCC diagnostic pop
  14549. #endif /* defined(GCC_DIAGNOSTIC) */
  14550. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14551. conn->buf_size = (int)max_req_size;
  14552. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14553. conn->dom_ctx = &(conn->phys_ctx->dd);
  14554. if (!connect_socket(conn->phys_ctx,
  14555. client_options->host,
  14556. client_options->port,
  14557. use_ssl,
  14558. ebuf,
  14559. ebuf_len,
  14560. &sock,
  14561. &sa)) {
  14562. /* ebuf is set by connect_socket,
  14563. * free all memory and return NULL; */
  14564. mg_free(conn);
  14565. return NULL;
  14566. }
  14567. #if !defined(NO_SSL)
  14568. #if defined(OPENSSL_API_1_1)
  14569. if (use_ssl
  14570. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14571. == NULL) {
  14572. mg_snprintf(NULL,
  14573. NULL, /* No truncation check for ebuf */
  14574. ebuf,
  14575. ebuf_len,
  14576. "SSL_CTX_new error: %s",
  14577. ssl_error());
  14578. closesocket(sock);
  14579. mg_free(conn);
  14580. return NULL;
  14581. }
  14582. #else
  14583. if (use_ssl
  14584. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14585. == NULL) {
  14586. mg_snprintf(NULL,
  14587. NULL, /* No truncation check for ebuf */
  14588. ebuf,
  14589. ebuf_len,
  14590. "SSL_CTX_new error: %s",
  14591. ssl_error());
  14592. closesocket(sock);
  14593. mg_free(conn);
  14594. return NULL;
  14595. }
  14596. #endif /* OPENSSL_API_1_1 */
  14597. #endif /* NO_SSL */
  14598. #if defined(USE_IPV6)
  14599. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14600. : sizeof(conn->client.rsa.sin6);
  14601. psa = (sa.sa.sa_family == AF_INET)
  14602. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14603. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14604. #else
  14605. len = sizeof(conn->client.rsa.sin);
  14606. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14607. #endif
  14608. conn->client.sock = sock;
  14609. conn->client.lsa = sa;
  14610. if (getsockname(sock, psa, &len) != 0) {
  14611. mg_cry_internal(conn,
  14612. "%s: getsockname() failed: %s",
  14613. __func__,
  14614. strerror(ERRNO));
  14615. }
  14616. conn->client.is_ssl = use_ssl ? 1 : 0;
  14617. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14618. mg_snprintf(NULL,
  14619. NULL, /* No truncation check for ebuf */
  14620. ebuf,
  14621. ebuf_len,
  14622. "Can not create mutex");
  14623. #if !defined(NO_SSL)
  14624. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14625. #endif
  14626. closesocket(sock);
  14627. mg_free(conn);
  14628. return NULL;
  14629. }
  14630. #if !defined(NO_SSL)
  14631. if (use_ssl) {
  14632. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14633. * SSL_CTX_set_verify call is needed to switch off server
  14634. * certificate checking, which is off by default in OpenSSL and
  14635. * on in yaSSL. */
  14636. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14637. * SSL_VERIFY_PEER, verify_ssl_server); */
  14638. if (client_options->client_cert) {
  14639. if (!ssl_use_pem_file(conn->phys_ctx,
  14640. conn->dom_ctx,
  14641. client_options->client_cert,
  14642. NULL)) {
  14643. mg_snprintf(NULL,
  14644. NULL, /* No truncation check for ebuf */
  14645. ebuf,
  14646. ebuf_len,
  14647. "Can not use SSL client certificate");
  14648. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14649. closesocket(sock);
  14650. mg_free(conn);
  14651. return NULL;
  14652. }
  14653. }
  14654. if (client_options->server_cert) {
  14655. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14656. client_options->server_cert,
  14657. NULL)
  14658. != 1) {
  14659. mg_cry_internal(conn,
  14660. "SSL_CTX_load_verify_locations error: %s ",
  14661. ssl_error());
  14662. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14663. closesocket(sock);
  14664. mg_free(conn);
  14665. return NULL;
  14666. }
  14667. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14668. } else {
  14669. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14670. }
  14671. if (!sslize(conn,
  14672. conn->dom_ctx->ssl_ctx,
  14673. SSL_connect,
  14674. &(conn->phys_ctx->stop_flag),
  14675. client_options)) {
  14676. mg_snprintf(NULL,
  14677. NULL, /* No truncation check for ebuf */
  14678. ebuf,
  14679. ebuf_len,
  14680. "SSL connection error");
  14681. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14682. closesocket(sock);
  14683. mg_free(conn);
  14684. return NULL;
  14685. }
  14686. }
  14687. #endif
  14688. return conn;
  14689. }
  14690. CIVETWEB_API struct mg_connection *
  14691. mg_connect_client_secure(const struct mg_client_options *client_options,
  14692. char *error_buffer,
  14693. size_t error_buffer_size)
  14694. {
  14695. return mg_connect_client_impl(client_options,
  14696. 1,
  14697. error_buffer,
  14698. error_buffer_size);
  14699. }
  14700. struct mg_connection *
  14701. mg_connect_client(const char *host,
  14702. int port,
  14703. int use_ssl,
  14704. char *error_buffer,
  14705. size_t error_buffer_size)
  14706. {
  14707. struct mg_client_options opts;
  14708. memset(&opts, 0, sizeof(opts));
  14709. opts.host = host;
  14710. opts.port = port;
  14711. return mg_connect_client_impl(&opts,
  14712. use_ssl,
  14713. error_buffer,
  14714. error_buffer_size);
  14715. }
  14716. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14717. struct mg_connection *
  14718. mg_connect_client2(const char *host,
  14719. const char *protocol,
  14720. int port,
  14721. const char *path,
  14722. struct mg_init_data *init,
  14723. struct mg_error_data *error)
  14724. {
  14725. int is_ssl, is_ws;
  14726. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14727. if (error != NULL) {
  14728. error->code = 0;
  14729. if (error->text_buffer_size > 0) {
  14730. *error->text = 0;
  14731. }
  14732. }
  14733. if ((host == NULL) || (protocol == NULL)) {
  14734. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14735. mg_snprintf(NULL,
  14736. NULL, /* No truncation check for error buffers */
  14737. error->text,
  14738. error->text_buffer_size,
  14739. "%s",
  14740. "Invalid parameters");
  14741. }
  14742. return NULL;
  14743. }
  14744. /* check all known protocolls */
  14745. if (!mg_strcasecmp(protocol, "http")) {
  14746. is_ssl = 0;
  14747. is_ws = 0;
  14748. } else if (!mg_strcasecmp(protocol, "https")) {
  14749. is_ssl = 1;
  14750. is_ws = 0;
  14751. #if defined(USE_WEBSOCKET)
  14752. } else if (!mg_strcasecmp(protocol, "ws")) {
  14753. is_ssl = 0;
  14754. is_ws = 1;
  14755. } else if (!mg_strcasecmp(protocol, "wss")) {
  14756. is_ssl = 1;
  14757. is_ws = 1;
  14758. #endif
  14759. } else {
  14760. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14761. mg_snprintf(NULL,
  14762. NULL, /* No truncation check for error buffers */
  14763. error->text,
  14764. error->text_buffer_size,
  14765. "Protocol %s not supported",
  14766. protocol);
  14767. }
  14768. return NULL;
  14769. }
  14770. /* TODO: The current implementation here just calls the old implementations,
  14771. * without using any new options. This is just a first step to test the new
  14772. * interfaces. */
  14773. #if defined(USE_WEBSOCKET)
  14774. if (is_ws) {
  14775. /* TODO: implement all options */
  14776. return mg_connect_websocket_client(host,
  14777. port,
  14778. is_ssl,
  14779. error->text,
  14780. error->text_buffer_size,
  14781. (path ? path : ""),
  14782. NULL /* TODO: origin */,
  14783. deprecated_websocket_data_wrapper,
  14784. deprecated_websocket_close_wrapper,
  14785. (void *)init->callbacks);
  14786. }
  14787. #endif
  14788. /* TODO: all additional options */
  14789. struct mg_client_options opts;
  14790. memset(&opts, 0, sizeof(opts));
  14791. opts.host = host;
  14792. opts.port = port;
  14793. return mg_connect_client_impl(&opts,
  14794. is_ssl,
  14795. ((error != NULL) ? error->text : NULL),
  14796. ((error != NULL) ? error->text_buffer_size : 0));
  14797. }
  14798. #endif
  14799. static const struct {
  14800. const char *proto;
  14801. size_t proto_len;
  14802. unsigned default_port;
  14803. } abs_uri_protocols[] = {{"http://", 7, 80},
  14804. {"https://", 8, 443},
  14805. {"ws://", 5, 80},
  14806. {"wss://", 6, 443},
  14807. {NULL, 0, 0}};
  14808. /* Check if the uri is valid.
  14809. * return 0 for invalid uri,
  14810. * return 1 for *,
  14811. * return 2 for relative uri,
  14812. * return 3 for absolute uri without port,
  14813. * return 4 for absolute uri with port */
  14814. static int
  14815. get_uri_type(const char *uri)
  14816. {
  14817. int i;
  14818. const char *hostend, *portbegin;
  14819. char *portend;
  14820. unsigned long port;
  14821. /* According to the HTTP standard
  14822. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14823. * URI can be an asterisk (*) or should start with slash (relative uri),
  14824. * or it should start with the protocol (absolute uri). */
  14825. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14826. /* asterisk */
  14827. return 1;
  14828. }
  14829. /* Valid URIs according to RFC 3986
  14830. * (https://www.ietf.org/rfc/rfc3986.txt)
  14831. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14832. * and unreserved characters A-Z a-z 0-9 and -._~
  14833. * and % encoded symbols.
  14834. */
  14835. for (i = 0; uri[i] != 0; i++) {
  14836. if (uri[i] < 33) {
  14837. /* control characters and spaces are invalid */
  14838. return 0;
  14839. }
  14840. if (uri[i] > 126) {
  14841. /* non-ascii characters must be % encoded */
  14842. return 0;
  14843. } else {
  14844. switch (uri[i]) {
  14845. case '"': /* 34 */
  14846. case '<': /* 60 */
  14847. case '>': /* 62 */
  14848. case '\\': /* 92 */
  14849. case '^': /* 94 */
  14850. case '`': /* 96 */
  14851. case '{': /* 123 */
  14852. case '|': /* 124 */
  14853. case '}': /* 125 */
  14854. return 0;
  14855. default:
  14856. /* character is ok */
  14857. break;
  14858. }
  14859. }
  14860. }
  14861. /* A relative uri starts with a / character */
  14862. if (uri[0] == '/') {
  14863. /* relative uri */
  14864. return 2;
  14865. }
  14866. /* It could be an absolute uri: */
  14867. /* This function only checks if the uri is valid, not if it is
  14868. * addressing the current server. So civetweb can also be used
  14869. * as a proxy server. */
  14870. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14871. if (mg_strncasecmp(uri,
  14872. abs_uri_protocols[i].proto,
  14873. abs_uri_protocols[i].proto_len)
  14874. == 0) {
  14875. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14876. if (!hostend) {
  14877. return 0;
  14878. }
  14879. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14880. if (!portbegin) {
  14881. return 3;
  14882. }
  14883. port = strtoul(portbegin + 1, &portend, 10);
  14884. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14885. return 0;
  14886. }
  14887. return 4;
  14888. }
  14889. }
  14890. return 0;
  14891. }
  14892. /* Return NULL or the relative uri at the current server */
  14893. static const char *
  14894. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14895. {
  14896. const char *server_domain;
  14897. size_t server_domain_len;
  14898. size_t request_domain_len = 0;
  14899. unsigned long port = 0;
  14900. int i, auth_domain_check_enabled;
  14901. const char *hostbegin = NULL;
  14902. const char *hostend = NULL;
  14903. const char *portbegin;
  14904. char *portend;
  14905. auth_domain_check_enabled =
  14906. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14907. /* DNS is case insensitive, so use case insensitive string compare here
  14908. */
  14909. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14910. if (mg_strncasecmp(uri,
  14911. abs_uri_protocols[i].proto,
  14912. abs_uri_protocols[i].proto_len)
  14913. == 0) {
  14914. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14915. hostend = strchr(hostbegin, '/');
  14916. if (!hostend) {
  14917. return 0;
  14918. }
  14919. portbegin = strchr(hostbegin, ':');
  14920. if ((!portbegin) || (portbegin > hostend)) {
  14921. port = abs_uri_protocols[i].default_port;
  14922. request_domain_len = (size_t)(hostend - hostbegin);
  14923. } else {
  14924. port = strtoul(portbegin + 1, &portend, 10);
  14925. if ((portend != hostend) || (port <= 0)
  14926. || !is_valid_port(port)) {
  14927. return 0;
  14928. }
  14929. request_domain_len = (size_t)(portbegin - hostbegin);
  14930. }
  14931. /* protocol found, port set */
  14932. break;
  14933. }
  14934. }
  14935. if (!port) {
  14936. /* port remains 0 if the protocol is not found */
  14937. return 0;
  14938. }
  14939. /* Check if the request is directed to a different server. */
  14940. /* First check if the port is the same (IPv4 and IPv6). */
  14941. #if defined(USE_IPV6)
  14942. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14943. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14944. /* Request is directed to a different port */
  14945. return 0;
  14946. }
  14947. } else
  14948. #endif
  14949. {
  14950. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14951. /* Request is directed to a different port */
  14952. return 0;
  14953. }
  14954. }
  14955. /* Finally check if the server corresponds to the authentication
  14956. * domain of the server (the server domain).
  14957. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14958. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14959. * but do not allow substrings (like
  14960. * http://notmydomain.com/path/file.ext
  14961. * or http://mydomain.com.fake/path/file.ext).
  14962. */
  14963. if (auth_domain_check_enabled) {
  14964. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14965. server_domain_len = strlen(server_domain);
  14966. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14967. return 0;
  14968. }
  14969. if ((request_domain_len == server_domain_len)
  14970. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14971. /* Request is directed to this server - full name match. */
  14972. } else {
  14973. if (request_domain_len < (server_domain_len + 2)) {
  14974. /* Request is directed to another server: The server name
  14975. * is longer than the request name.
  14976. * Drop this case here to avoid overflows in the
  14977. * following checks. */
  14978. return 0;
  14979. }
  14980. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14981. /* Request is directed to another server: It could be a
  14982. * substring
  14983. * like notmyserver.com */
  14984. return 0;
  14985. }
  14986. if (0
  14987. != memcmp(server_domain,
  14988. hostbegin + request_domain_len - server_domain_len,
  14989. server_domain_len)) {
  14990. /* Request is directed to another server:
  14991. * The server name is different. */
  14992. return 0;
  14993. }
  14994. }
  14995. }
  14996. return hostend;
  14997. }
  14998. static int
  14999. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15000. {
  15001. if (ebuf_len > 0) {
  15002. ebuf[0] = '\0';
  15003. }
  15004. *err = 0;
  15005. reset_per_request_attributes(conn);
  15006. if (!conn) {
  15007. mg_snprintf(conn,
  15008. NULL, /* No truncation check for ebuf */
  15009. ebuf,
  15010. ebuf_len,
  15011. "%s",
  15012. "Internal error");
  15013. *err = 500;
  15014. return 0;
  15015. }
  15016. /* Set the time the request was received. This value should be used for
  15017. * timeouts. */
  15018. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15019. conn->request_len =
  15020. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15021. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15022. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15023. mg_snprintf(conn,
  15024. NULL, /* No truncation check for ebuf */
  15025. ebuf,
  15026. ebuf_len,
  15027. "%s",
  15028. "Invalid message size");
  15029. *err = 500;
  15030. return 0;
  15031. }
  15032. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15033. mg_snprintf(conn,
  15034. NULL, /* No truncation check for ebuf */
  15035. ebuf,
  15036. ebuf_len,
  15037. "%s",
  15038. "Message too large");
  15039. *err = 413;
  15040. return 0;
  15041. }
  15042. if (conn->request_len <= 0) {
  15043. if (conn->data_len > 0) {
  15044. mg_snprintf(conn,
  15045. NULL, /* No truncation check for ebuf */
  15046. ebuf,
  15047. ebuf_len,
  15048. "%s",
  15049. "Malformed message");
  15050. *err = 400;
  15051. } else {
  15052. /* Server did not recv anything -> just close the connection */
  15053. conn->must_close = 1;
  15054. mg_snprintf(conn,
  15055. NULL, /* No truncation check for ebuf */
  15056. ebuf,
  15057. ebuf_len,
  15058. "%s",
  15059. "No data received");
  15060. *err = 0;
  15061. }
  15062. return 0;
  15063. }
  15064. return 1;
  15065. }
  15066. static int
  15067. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15068. {
  15069. const char *cl;
  15070. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15071. return 0;
  15072. }
  15073. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15074. <= 0) {
  15075. mg_snprintf(conn,
  15076. NULL, /* No truncation check for ebuf */
  15077. ebuf,
  15078. ebuf_len,
  15079. "%s",
  15080. "Bad request");
  15081. *err = 400;
  15082. return 0;
  15083. }
  15084. /* Message is a valid request */
  15085. /* Is there a "host" ? */
  15086. if (conn->host != NULL) {
  15087. mg_free((void *)conn->host);
  15088. }
  15089. conn->host = alloc_get_host(conn);
  15090. if (!conn->host) {
  15091. mg_snprintf(conn,
  15092. NULL, /* No truncation check for ebuf */
  15093. ebuf,
  15094. ebuf_len,
  15095. "%s",
  15096. "Bad request: Host mismatch");
  15097. *err = 400;
  15098. return 0;
  15099. }
  15100. if (((cl = get_header(conn->request_info.http_headers,
  15101. conn->request_info.num_headers,
  15102. "Transfer-Encoding"))
  15103. != NULL)
  15104. && mg_strcasecmp(cl, "identity")) {
  15105. if (mg_strcasecmp(cl, "chunked")) {
  15106. mg_snprintf(conn,
  15107. NULL, /* No truncation check for ebuf */
  15108. ebuf,
  15109. ebuf_len,
  15110. "%s",
  15111. "Bad request");
  15112. *err = 400;
  15113. return 0;
  15114. }
  15115. conn->is_chunked = 1;
  15116. conn->content_len = 0; /* not yet read */
  15117. } else if ((cl = get_header(conn->request_info.http_headers,
  15118. conn->request_info.num_headers,
  15119. "Content-Length"))
  15120. != NULL) {
  15121. /* Request has content length set */
  15122. char *endptr = NULL;
  15123. conn->content_len = strtoll(cl, &endptr, 10);
  15124. if ((endptr == cl) || (conn->content_len < 0)) {
  15125. mg_snprintf(conn,
  15126. NULL, /* No truncation check for ebuf */
  15127. ebuf,
  15128. ebuf_len,
  15129. "%s",
  15130. "Bad request");
  15131. *err = 411;
  15132. return 0;
  15133. }
  15134. /* Publish the content length back to the request info. */
  15135. conn->request_info.content_length = conn->content_len;
  15136. } else {
  15137. /* There is no exception, see RFC7230. */
  15138. conn->content_len = 0;
  15139. }
  15140. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15141. return 1;
  15142. }
  15143. /* conn is assumed to be valid in this internal function */
  15144. static int
  15145. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15146. {
  15147. const char *cl;
  15148. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15149. return 0;
  15150. }
  15151. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15152. <= 0) {
  15153. mg_snprintf(conn,
  15154. NULL, /* No truncation check for ebuf */
  15155. ebuf,
  15156. ebuf_len,
  15157. "%s",
  15158. "Bad response");
  15159. *err = 400;
  15160. return 0;
  15161. }
  15162. /* Message is a valid response */
  15163. if (((cl = get_header(conn->response_info.http_headers,
  15164. conn->response_info.num_headers,
  15165. "Transfer-Encoding"))
  15166. != NULL)
  15167. && mg_strcasecmp(cl, "identity")) {
  15168. if (mg_strcasecmp(cl, "chunked")) {
  15169. mg_snprintf(conn,
  15170. NULL, /* No truncation check for ebuf */
  15171. ebuf,
  15172. ebuf_len,
  15173. "%s",
  15174. "Bad request");
  15175. *err = 400;
  15176. return 0;
  15177. }
  15178. conn->is_chunked = 1;
  15179. conn->content_len = 0; /* not yet read */
  15180. } else if ((cl = get_header(conn->response_info.http_headers,
  15181. conn->response_info.num_headers,
  15182. "Content-Length"))
  15183. != NULL) {
  15184. char *endptr = NULL;
  15185. conn->content_len = strtoll(cl, &endptr, 10);
  15186. if ((endptr == cl) || (conn->content_len < 0)) {
  15187. mg_snprintf(conn,
  15188. NULL, /* No truncation check for ebuf */
  15189. ebuf,
  15190. ebuf_len,
  15191. "%s",
  15192. "Bad request");
  15193. *err = 411;
  15194. return 0;
  15195. }
  15196. /* Publish the content length back to the response info. */
  15197. conn->response_info.content_length = conn->content_len;
  15198. /* TODO: check if it is still used in response_info */
  15199. conn->request_info.content_length = conn->content_len;
  15200. /* TODO: we should also consider HEAD method */
  15201. if (conn->response_info.status_code == 304) {
  15202. conn->content_len = 0;
  15203. }
  15204. } else {
  15205. /* TODO: we should also consider HEAD method */
  15206. if (((conn->response_info.status_code >= 100)
  15207. && (conn->response_info.status_code <= 199))
  15208. || (conn->response_info.status_code == 204)
  15209. || (conn->response_info.status_code == 304)) {
  15210. conn->content_len = 0;
  15211. } else {
  15212. conn->content_len = -1; /* unknown content length */
  15213. }
  15214. }
  15215. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15216. return 1;
  15217. }
  15218. int
  15219. mg_get_response(struct mg_connection *conn,
  15220. char *ebuf,
  15221. size_t ebuf_len,
  15222. int timeout)
  15223. {
  15224. int err, ret;
  15225. char txt[32]; /* will not overflow */
  15226. char *save_timeout;
  15227. char *new_timeout;
  15228. if (ebuf_len > 0) {
  15229. ebuf[0] = '\0';
  15230. }
  15231. if (!conn) {
  15232. mg_snprintf(conn,
  15233. NULL, /* No truncation check for ebuf */
  15234. ebuf,
  15235. ebuf_len,
  15236. "%s",
  15237. "Parameter error");
  15238. return -1;
  15239. }
  15240. /* Reset the previous responses */
  15241. conn->data_len = 0;
  15242. /* Implementation of API function for HTTP clients */
  15243. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15244. if (timeout >= 0) {
  15245. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15246. new_timeout = txt;
  15247. } else {
  15248. new_timeout = NULL;
  15249. }
  15250. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15251. ret = get_response(conn, ebuf, ebuf_len, &err);
  15252. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15253. #if defined(MG_LEGACY_INTERFACE)
  15254. /* TODO: 1) uri is deprecated;
  15255. * 2) here, ri.uri is the http response code */
  15256. conn->request_info.uri = conn->request_info.request_uri;
  15257. #endif
  15258. conn->request_info.local_uri = conn->request_info.request_uri;
  15259. /* TODO (mid): Define proper return values - maybe return length?
  15260. * For the first test use <0 for error and >0 for OK */
  15261. return (ret == 0) ? -1 : +1;
  15262. }
  15263. struct mg_connection *
  15264. mg_download(const char *host,
  15265. int port,
  15266. int use_ssl,
  15267. char *ebuf,
  15268. size_t ebuf_len,
  15269. const char *fmt,
  15270. ...)
  15271. {
  15272. struct mg_connection *conn;
  15273. va_list ap;
  15274. int i;
  15275. int reqerr;
  15276. if (ebuf_len > 0) {
  15277. ebuf[0] = '\0';
  15278. }
  15279. va_start(ap, fmt);
  15280. /* open a connection */
  15281. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15282. if (conn != NULL) {
  15283. i = mg_vprintf(conn, fmt, ap);
  15284. if (i <= 0) {
  15285. mg_snprintf(conn,
  15286. NULL, /* No truncation check for ebuf */
  15287. ebuf,
  15288. ebuf_len,
  15289. "%s",
  15290. "Error sending request");
  15291. } else {
  15292. /* make sure the buffer is clear */
  15293. conn->data_len = 0;
  15294. get_response(conn, ebuf, ebuf_len, &reqerr);
  15295. #if defined(MG_LEGACY_INTERFACE)
  15296. /* TODO: 1) uri is deprecated;
  15297. * 2) here, ri.uri is the http response code */
  15298. conn->request_info.uri = conn->request_info.request_uri;
  15299. #endif
  15300. conn->request_info.local_uri = conn->request_info.request_uri;
  15301. }
  15302. }
  15303. /* if an error occurred, close the connection */
  15304. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15305. mg_close_connection(conn);
  15306. conn = NULL;
  15307. }
  15308. va_end(ap);
  15309. return conn;
  15310. }
  15311. struct websocket_client_thread_data {
  15312. struct mg_connection *conn;
  15313. mg_websocket_data_handler data_handler;
  15314. mg_websocket_close_handler close_handler;
  15315. void *callback_data;
  15316. };
  15317. #if defined(USE_WEBSOCKET)
  15318. #if defined(_WIN32)
  15319. static unsigned __stdcall websocket_client_thread(void *data)
  15320. #else
  15321. static void *
  15322. websocket_client_thread(void *data)
  15323. #endif
  15324. {
  15325. struct websocket_client_thread_data *cdata =
  15326. (struct websocket_client_thread_data *)data;
  15327. void *user_thread_ptr = NULL;
  15328. #if !defined(_WIN32)
  15329. struct sigaction sa;
  15330. /* Ignore SIGPIPE */
  15331. memset(&sa, 0, sizeof(sa));
  15332. sa.sa_handler = SIG_IGN;
  15333. sigaction(SIGPIPE, &sa, NULL);
  15334. #endif
  15335. mg_set_thread_name("ws-clnt");
  15336. if (cdata->conn->phys_ctx) {
  15337. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15338. /* 3 indicates a websocket client thread */
  15339. /* TODO: check if conn->phys_ctx can be set */
  15340. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15341. cdata->conn->phys_ctx, 3);
  15342. }
  15343. }
  15344. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15345. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15346. if (cdata->close_handler != NULL) {
  15347. cdata->close_handler(cdata->conn, cdata->callback_data);
  15348. }
  15349. /* The websocket_client context has only this thread. If it runs out,
  15350. set the stop_flag to 2 (= "stopped"). */
  15351. cdata->conn->phys_ctx->stop_flag = 2;
  15352. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15353. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15354. 3,
  15355. user_thread_ptr);
  15356. }
  15357. mg_free((void *)cdata);
  15358. #if defined(_WIN32)
  15359. return 0;
  15360. #else
  15361. return NULL;
  15362. #endif
  15363. }
  15364. #endif
  15365. struct mg_connection *
  15366. mg_connect_websocket_client(const char *host,
  15367. int port,
  15368. int use_ssl,
  15369. char *error_buffer,
  15370. size_t error_buffer_size,
  15371. const char *path,
  15372. const char *origin,
  15373. mg_websocket_data_handler data_func,
  15374. mg_websocket_close_handler close_func,
  15375. void *user_data)
  15376. {
  15377. struct mg_connection *conn = NULL;
  15378. #if defined(USE_WEBSOCKET)
  15379. struct websocket_client_thread_data *thread_data;
  15380. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15381. static const char *handshake_req;
  15382. if (origin != NULL) {
  15383. handshake_req = "GET %s HTTP/1.1\r\n"
  15384. "Host: %s\r\n"
  15385. "Upgrade: websocket\r\n"
  15386. "Connection: Upgrade\r\n"
  15387. "Sec-WebSocket-Key: %s\r\n"
  15388. "Sec-WebSocket-Version: 13\r\n"
  15389. "Origin: %s\r\n"
  15390. "\r\n";
  15391. } else {
  15392. handshake_req = "GET %s HTTP/1.1\r\n"
  15393. "Host: %s\r\n"
  15394. "Upgrade: websocket\r\n"
  15395. "Connection: Upgrade\r\n"
  15396. "Sec-WebSocket-Key: %s\r\n"
  15397. "Sec-WebSocket-Version: 13\r\n"
  15398. "\r\n";
  15399. }
  15400. #if defined(__clang__)
  15401. #pragma clang diagnostic push
  15402. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15403. #endif
  15404. /* Establish the client connection and request upgrade */
  15405. conn = mg_download(host,
  15406. port,
  15407. use_ssl,
  15408. error_buffer,
  15409. error_buffer_size,
  15410. handshake_req,
  15411. path,
  15412. host,
  15413. magic,
  15414. origin);
  15415. #if defined(__clang__)
  15416. #pragma clang diagnostic pop
  15417. #endif
  15418. /* Connection object will be null if something goes wrong */
  15419. if (conn == NULL) {
  15420. if (!*error_buffer) {
  15421. /* There should be already an error message */
  15422. mg_snprintf(conn,
  15423. NULL, /* No truncation check for ebuf */
  15424. error_buffer,
  15425. error_buffer_size,
  15426. "Unexpected error");
  15427. }
  15428. return NULL;
  15429. }
  15430. if (conn->response_info.status_code != 101) {
  15431. /* We sent an "upgrade" request. For a correct websocket
  15432. * protocol handshake, we expect a "101 Continue" response.
  15433. * Otherwise it is a protocol violation. Maybe the HTTP
  15434. * Server does not know websockets. */
  15435. if (!*error_buffer) {
  15436. /* set an error, if not yet set */
  15437. mg_snprintf(conn,
  15438. NULL, /* No truncation check for ebuf */
  15439. error_buffer,
  15440. error_buffer_size,
  15441. "Unexpected server reply");
  15442. }
  15443. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15444. mg_close_connection(conn);
  15445. return NULL;
  15446. }
  15447. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15448. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15449. if (!thread_data) {
  15450. DEBUG_TRACE("%s\r\n", "Out of memory");
  15451. mg_close_connection(conn);
  15452. return NULL;
  15453. }
  15454. thread_data->conn = conn;
  15455. thread_data->data_handler = data_func;
  15456. thread_data->close_handler = close_func;
  15457. thread_data->callback_data = user_data;
  15458. conn->phys_ctx->worker_threadids =
  15459. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15460. if (!conn->phys_ctx->worker_threadids) {
  15461. DEBUG_TRACE("%s\r\n", "Out of memory");
  15462. mg_free(thread_data);
  15463. mg_close_connection(conn);
  15464. return NULL;
  15465. }
  15466. /* Now upgrade to ws/wss client context */
  15467. conn->phys_ctx->user_data = user_data;
  15468. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15469. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15470. /* Start a thread to read the websocket client connection
  15471. * This thread will automatically stop when mg_disconnect is
  15472. * called on the client connection */
  15473. if (mg_start_thread_with_id(websocket_client_thread,
  15474. thread_data,
  15475. conn->phys_ctx->worker_threadids)
  15476. != 0) {
  15477. conn->phys_ctx->cfg_worker_threads = 0;
  15478. mg_free(thread_data);
  15479. mg_close_connection(conn);
  15480. conn = NULL;
  15481. DEBUG_TRACE("%s",
  15482. "Websocket client connect thread could not be started\r\n");
  15483. }
  15484. #else
  15485. /* Appease "unused parameter" warnings */
  15486. (void)host;
  15487. (void)port;
  15488. (void)use_ssl;
  15489. (void)error_buffer;
  15490. (void)error_buffer_size;
  15491. (void)path;
  15492. (void)origin;
  15493. (void)user_data;
  15494. (void)data_func;
  15495. (void)close_func;
  15496. #endif
  15497. return conn;
  15498. }
  15499. /* Prepare connection data structure */
  15500. static void
  15501. init_connection(struct mg_connection *conn)
  15502. {
  15503. /* Is keep alive allowed by the server */
  15504. int keep_alive_enabled =
  15505. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15506. if (!keep_alive_enabled) {
  15507. conn->must_close = 1;
  15508. }
  15509. /* Important: on new connection, reset the receiving buffer. Credit
  15510. * goes to crule42. */
  15511. conn->data_len = 0;
  15512. conn->handled_requests = 0;
  15513. mg_set_user_connection_data(conn, NULL);
  15514. #if defined(USE_SERVER_STATS)
  15515. conn->conn_state = 2; /* init */
  15516. #endif
  15517. /* call the init_connection callback if assigned */
  15518. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15519. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15520. void *conn_data = NULL;
  15521. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15522. mg_set_user_connection_data(conn, conn_data);
  15523. }
  15524. }
  15525. }
  15526. /* Process a connection - may handle multiple requests
  15527. * using the same connection.
  15528. * Must be called with a valid connection (conn and
  15529. * conn->phys_ctx must be valid).
  15530. */
  15531. static void
  15532. process_new_connection(struct mg_connection *conn)
  15533. {
  15534. struct mg_request_info *ri = &conn->request_info;
  15535. int keep_alive, discard_len;
  15536. char ebuf[100];
  15537. const char *hostend;
  15538. int reqerr, uri_type;
  15539. #if defined(USE_SERVER_STATS)
  15540. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15541. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15542. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15543. /* could use atomic compare exchange, but this
  15544. * seems overkill for statistics data */
  15545. conn->phys_ctx->max_active_connections = mcon;
  15546. }
  15547. #endif
  15548. init_connection(conn);
  15549. DEBUG_TRACE("Start processing connection from %s",
  15550. conn->request_info.remote_addr);
  15551. /* Loop over multiple requests sent using the same connection
  15552. * (while "keep alive"). */
  15553. do {
  15554. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15555. conn->handled_requests + 1);
  15556. #if defined(USE_SERVER_STATS)
  15557. conn->conn_state = 3; /* ready */
  15558. #endif
  15559. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15560. /* The request sent by the client could not be understood by
  15561. * the server, or it was incomplete or a timeout. Send an
  15562. * error message and close the connection. */
  15563. if (reqerr > 0) {
  15564. DEBUG_ASSERT(ebuf[0] != '\0');
  15565. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15566. }
  15567. } else if (strcmp(ri->http_version, "1.0")
  15568. && strcmp(ri->http_version, "1.1")) {
  15569. mg_snprintf(conn,
  15570. NULL, /* No truncation check for ebuf */
  15571. ebuf,
  15572. sizeof(ebuf),
  15573. "Bad HTTP version: [%s]",
  15574. ri->http_version);
  15575. mg_send_http_error(conn, 505, "%s", ebuf);
  15576. }
  15577. if (ebuf[0] == '\0') {
  15578. uri_type = get_uri_type(conn->request_info.request_uri);
  15579. switch (uri_type) {
  15580. case 1:
  15581. /* Asterisk */
  15582. conn->request_info.local_uri = NULL;
  15583. break;
  15584. case 2:
  15585. /* relative uri */
  15586. conn->request_info.local_uri = conn->request_info.request_uri;
  15587. break;
  15588. case 3:
  15589. case 4:
  15590. /* absolute uri (with/without port) */
  15591. hostend = get_rel_url_at_current_server(
  15592. conn->request_info.request_uri, conn);
  15593. if (hostend) {
  15594. conn->request_info.local_uri = hostend;
  15595. } else {
  15596. conn->request_info.local_uri = NULL;
  15597. }
  15598. break;
  15599. default:
  15600. mg_snprintf(conn,
  15601. NULL, /* No truncation check for ebuf */
  15602. ebuf,
  15603. sizeof(ebuf),
  15604. "Invalid URI");
  15605. mg_send_http_error(conn, 400, "%s", ebuf);
  15606. conn->request_info.local_uri = NULL;
  15607. break;
  15608. }
  15609. #if defined(MG_LEGACY_INTERFACE)
  15610. /* Legacy before split into local_uri and request_uri */
  15611. conn->request_info.uri = conn->request_info.local_uri;
  15612. #endif
  15613. }
  15614. DEBUG_TRACE("http: %s, error: %s",
  15615. (ri->http_version ? ri->http_version : "none"),
  15616. (ebuf[0] ? ebuf : "none"));
  15617. if (ebuf[0] == '\0') {
  15618. if (conn->request_info.local_uri) {
  15619. /* handle request to local server */
  15620. #if defined(USE_SERVER_STATS)
  15621. conn->conn_state = 4; /* processing */
  15622. #endif
  15623. handle_request(conn);
  15624. #if defined(USE_SERVER_STATS)
  15625. conn->conn_state = 5; /* processed */
  15626. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15627. conn->consumed_content);
  15628. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15629. conn->num_bytes_sent);
  15630. #endif
  15631. DEBUG_TRACE("%s", "handle_request done");
  15632. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15633. conn->phys_ctx->callbacks.end_request(conn,
  15634. conn->status_code);
  15635. DEBUG_TRACE("%s", "end_request callback done");
  15636. }
  15637. log_access(conn);
  15638. } else {
  15639. /* TODO: handle non-local request (PROXY) */
  15640. conn->must_close = 1;
  15641. }
  15642. } else {
  15643. conn->must_close = 1;
  15644. }
  15645. if (ri->remote_user != NULL) {
  15646. mg_free((void *)ri->remote_user);
  15647. /* Important! When having connections with and without auth
  15648. * would cause double free and then crash */
  15649. ri->remote_user = NULL;
  15650. }
  15651. /* NOTE(lsm): order is important here. should_keep_alive() call
  15652. * is using parsed request, which will be invalid after
  15653. * memmove's below.
  15654. * Therefore, memorize should_keep_alive() result now for later
  15655. * use in loop exit condition. */
  15656. /* Enable it only if this request is completely discardable. */
  15657. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15658. && (conn->content_len >= 0) && (conn->request_len > 0)
  15659. && ((conn->is_chunked == 4)
  15660. || (!conn->is_chunked
  15661. && ((conn->consumed_content == conn->content_len)
  15662. || ((conn->request_len + conn->content_len)
  15663. <= conn->data_len))));
  15664. if (keep_alive) {
  15665. /* Discard all buffered data for this request */
  15666. discard_len =
  15667. ((conn->request_len + conn->content_len) < conn->data_len)
  15668. ? (int)(conn->request_len + conn->content_len)
  15669. : conn->data_len;
  15670. conn->data_len -= discard_len;
  15671. if (conn->data_len > 0) {
  15672. DEBUG_TRACE("discard_len = %d", discard_len);
  15673. memmove(conn->buf,
  15674. conn->buf + discard_len,
  15675. (size_t)conn->data_len);
  15676. }
  15677. }
  15678. DEBUG_ASSERT(conn->data_len >= 0);
  15679. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15680. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15681. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15682. (long int)conn->data_len,
  15683. (long int)conn->buf_size);
  15684. break;
  15685. }
  15686. conn->handled_requests++;
  15687. } while (keep_alive);
  15688. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15689. conn->request_info.remote_addr,
  15690. difftime(time(NULL), conn->conn_birth_time));
  15691. close_connection(conn);
  15692. #if defined(USE_SERVER_STATS)
  15693. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15694. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15695. #endif
  15696. }
  15697. #if defined(ALTERNATIVE_QUEUE)
  15698. static void
  15699. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15700. {
  15701. unsigned int i;
  15702. while (!ctx->stop_flag) {
  15703. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15704. /* find a free worker slot and signal it */
  15705. if (ctx->client_socks[i].in_use == 2) {
  15706. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15707. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15708. ctx->client_socks[i] = *sp;
  15709. ctx->client_socks[i].in_use = 1;
  15710. /* socket has been moved to the consumer */
  15711. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15712. (void)event_signal(ctx->client_wait_events[i]);
  15713. return;
  15714. }
  15715. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15716. }
  15717. }
  15718. /* queue is full */
  15719. mg_sleep(1);
  15720. }
  15721. /* must consume */
  15722. set_blocking_mode(sp->sock);
  15723. closesocket(sp->sock);
  15724. }
  15725. static int
  15726. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15727. {
  15728. DEBUG_TRACE("%s", "going idle");
  15729. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15730. ctx->client_socks[thread_index].in_use = 2;
  15731. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15732. event_wait(ctx->client_wait_events[thread_index]);
  15733. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15734. *sp = ctx->client_socks[thread_index];
  15735. if (ctx->stop_flag) {
  15736. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15737. if (sp->in_use == 1) {
  15738. /* must consume */
  15739. set_blocking_mode(sp->sock);
  15740. closesocket(sp->sock);
  15741. }
  15742. return 0;
  15743. }
  15744. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15745. if (sp->in_use == 1) {
  15746. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15747. return 1;
  15748. }
  15749. /* must not reach here */
  15750. DEBUG_ASSERT(0);
  15751. return 0;
  15752. }
  15753. #else /* ALTERNATIVE_QUEUE */
  15754. /* Worker threads take accepted socket from the queue */
  15755. static int
  15756. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15757. {
  15758. (void)thread_index;
  15759. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15760. DEBUG_TRACE("%s", "going idle");
  15761. /* If the queue is empty, wait. We're idle at this point. */
  15762. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15763. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15764. }
  15765. /* If we're stopping, sq_head may be equal to sq_tail. */
  15766. if (ctx->sq_head > ctx->sq_tail) {
  15767. /* Copy socket from the queue and increment tail */
  15768. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  15769. ctx->sq_tail++;
  15770. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15771. /* Wrap pointers if needed */
  15772. while (ctx->sq_tail > ctx->sq_size) {
  15773. ctx->sq_tail -= ctx->sq_size;
  15774. ctx->sq_head -= ctx->sq_size;
  15775. }
  15776. }
  15777. (void)pthread_cond_signal(&ctx->sq_empty);
  15778. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15779. return !ctx->stop_flag;
  15780. }
  15781. /* Master thread adds accepted socket to a queue */
  15782. static void
  15783. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15784. {
  15785. int queue_filled;
  15786. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15787. queue_filled = ctx->sq_head - ctx->sq_tail;
  15788. /* If the queue is full, wait */
  15789. while ((ctx->stop_flag == 0) && (queue_filled >= ctx->sq_size)) {
  15790. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  15791. #if defined(USE_SERVER_STATS)
  15792. if (queue_filled > ctx->sq_max_fill) {
  15793. ctx->sq_max_fill = queue_filled;
  15794. }
  15795. #endif
  15796. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15797. ctx->sq_blocked = 0; /* Not blocked now */
  15798. queue_filled = ctx->sq_head - ctx->sq_tail;
  15799. }
  15800. if (queue_filled < ctx->sq_size) {
  15801. /* Copy socket to the queue and increment head */
  15802. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  15803. ctx->sq_head++;
  15804. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15805. }
  15806. queue_filled = ctx->sq_head - ctx->sq_tail;
  15807. #if defined(USE_SERVER_STATS)
  15808. if (queue_filled > ctx->sq_max_fill) {
  15809. ctx->sq_max_fill = queue_filled;
  15810. }
  15811. #endif
  15812. (void)pthread_cond_signal(&ctx->sq_full);
  15813. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15814. }
  15815. #endif /* ALTERNATIVE_QUEUE */
  15816. static void
  15817. worker_thread_run(struct mg_connection *conn)
  15818. {
  15819. struct mg_context *ctx = conn->phys_ctx;
  15820. int thread_index;
  15821. struct mg_workerTLS tls;
  15822. #if defined(MG_LEGACY_INTERFACE)
  15823. uint32_t addr;
  15824. #endif
  15825. mg_set_thread_name("worker");
  15826. tls.is_master = 0;
  15827. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15828. #if defined(_WIN32)
  15829. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15830. #endif
  15831. /* Initialize thread local storage before calling any callback */
  15832. pthread_setspecific(sTlsKey, &tls);
  15833. /* Check if there is a user callback */
  15834. if (ctx->callbacks.init_thread) {
  15835. /* call init_thread for a worker thread (type 1), and store the return
  15836. * value */
  15837. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15838. } else {
  15839. /* No callback: set user pointer to NULL */
  15840. tls.user_ptr = NULL;
  15841. }
  15842. /* Connection structure has been pre-allocated */
  15843. thread_index = (int)(conn - ctx->worker_connections);
  15844. if ((thread_index < 0)
  15845. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15846. mg_cry_ctx_internal(ctx,
  15847. "Internal error: Invalid worker index %i",
  15848. thread_index);
  15849. return;
  15850. }
  15851. /* Request buffers are not pre-allocated. They are private to the
  15852. * request and do not contain any state information that might be
  15853. * of interest to anyone observing a server status. */
  15854. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15855. if (conn->buf == NULL) {
  15856. mg_cry_ctx_internal(
  15857. ctx,
  15858. "Out of memory: Cannot allocate buffer for worker %i",
  15859. thread_index);
  15860. return;
  15861. }
  15862. conn->buf_size = (int)ctx->max_request_size;
  15863. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15864. conn->host = NULL; /* until we have more information. */
  15865. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15866. conn->request_info.user_data = ctx->user_data;
  15867. /* Allocate a mutex for this connection to allow communication both
  15868. * within the request handler and from elsewhere in the application
  15869. */
  15870. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15871. mg_free(conn->buf);
  15872. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15873. return;
  15874. }
  15875. #if defined(USE_SERVER_STATS)
  15876. conn->conn_state = 1; /* not consumed */
  15877. #endif
  15878. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15879. * signal sq_empty condvar to wake up the master waiting in
  15880. * produce_socket() */
  15881. while (consume_socket(ctx, &conn->client, thread_index)) {
  15882. #if defined(USE_SERVER_STATS)
  15883. conn->conn_close_time = 0;
  15884. #endif
  15885. conn->conn_birth_time = time(NULL);
  15886. /* Fill in IP, port info early so even if SSL setup below fails,
  15887. * error handler would have the corresponding info.
  15888. * Thanks to Johannes Winkelmann for the patch.
  15889. */
  15890. #if defined(USE_IPV6)
  15891. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15892. conn->request_info.remote_port =
  15893. ntohs(conn->client.rsa.sin6.sin6_port);
  15894. } else
  15895. #endif
  15896. {
  15897. conn->request_info.remote_port =
  15898. ntohs(conn->client.rsa.sin.sin_port);
  15899. }
  15900. sockaddr_to_string(conn->request_info.remote_addr,
  15901. sizeof(conn->request_info.remote_addr),
  15902. &conn->client.rsa);
  15903. DEBUG_TRACE("Start processing connection from %s",
  15904. conn->request_info.remote_addr);
  15905. conn->request_info.is_ssl = conn->client.is_ssl;
  15906. if (conn->client.is_ssl) {
  15907. #if !defined(NO_SSL)
  15908. /* HTTPS connection */
  15909. if (sslize(conn,
  15910. conn->dom_ctx->ssl_ctx,
  15911. SSL_accept,
  15912. &(conn->phys_ctx->stop_flag),
  15913. NULL)) {
  15914. /* conn->dom_ctx is set in get_request */
  15915. /* Get SSL client certificate information (if set) */
  15916. ssl_get_client_cert_info(conn);
  15917. /* process HTTPS connection */
  15918. process_new_connection(conn);
  15919. /* Free client certificate info */
  15920. if (conn->request_info.client_cert) {
  15921. mg_free((void *)(conn->request_info.client_cert->subject));
  15922. mg_free((void *)(conn->request_info.client_cert->issuer));
  15923. mg_free((void *)(conn->request_info.client_cert->serial));
  15924. mg_free((void *)(conn->request_info.client_cert->finger));
  15925. /* Free certificate memory */
  15926. X509_free(
  15927. (X509 *)conn->request_info.client_cert->peer_cert);
  15928. conn->request_info.client_cert->peer_cert = 0;
  15929. conn->request_info.client_cert->subject = 0;
  15930. conn->request_info.client_cert->issuer = 0;
  15931. conn->request_info.client_cert->serial = 0;
  15932. conn->request_info.client_cert->finger = 0;
  15933. mg_free(conn->request_info.client_cert);
  15934. conn->request_info.client_cert = 0;
  15935. }
  15936. } else {
  15937. /* make sure the connection is cleaned up on SSL failure */
  15938. close_connection(conn);
  15939. }
  15940. #endif
  15941. } else {
  15942. /* process HTTP connection */
  15943. process_new_connection(conn);
  15944. }
  15945. DEBUG_TRACE("%s", "Connection closed");
  15946. #if defined(USE_SERVER_STATS)
  15947. conn->conn_close_time = time(NULL);
  15948. #endif
  15949. }
  15950. /* Call exit thread user callback */
  15951. if (ctx->callbacks.exit_thread) {
  15952. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15953. }
  15954. /* delete thread local storage objects */
  15955. pthread_setspecific(sTlsKey, NULL);
  15956. #if defined(_WIN32)
  15957. CloseHandle(tls.pthread_cond_helper_mutex);
  15958. #endif
  15959. pthread_mutex_destroy(&conn->mutex);
  15960. /* Free the request buffer. */
  15961. conn->buf_size = 0;
  15962. mg_free(conn->buf);
  15963. conn->buf = NULL;
  15964. #if defined(USE_SERVER_STATS)
  15965. conn->conn_state = 9; /* done */
  15966. #endif
  15967. DEBUG_TRACE("%s", "exiting");
  15968. }
  15969. /* Threads have different return types on Windows and Unix. */
  15970. #if defined(_WIN32)
  15971. static unsigned __stdcall worker_thread(void *thread_func_param)
  15972. {
  15973. worker_thread_run((struct mg_connection *)thread_func_param);
  15974. return 0;
  15975. }
  15976. #else
  15977. static void *
  15978. worker_thread(void *thread_func_param)
  15979. {
  15980. #if !defined(__ZEPHYR__)
  15981. struct sigaction sa;
  15982. /* Ignore SIGPIPE */
  15983. memset(&sa, 0, sizeof(sa));
  15984. sa.sa_handler = SIG_IGN;
  15985. sigaction(SIGPIPE, &sa, NULL);
  15986. #endif
  15987. worker_thread_run((struct mg_connection *)thread_func_param);
  15988. return NULL;
  15989. }
  15990. #endif /* _WIN32 */
  15991. /* This is an internal function, thus all arguments are expected to be
  15992. * valid - a NULL check is not required. */
  15993. static void
  15994. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15995. {
  15996. struct socket so;
  15997. char src_addr[IP_ADDR_STR_LEN];
  15998. socklen_t len = sizeof(so.rsa);
  15999. #if !defined(__ZEPHYR__)
  16000. int on = 1;
  16001. #endif
  16002. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16003. == INVALID_SOCKET) {
  16004. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16005. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16006. mg_cry_ctx_internal(ctx,
  16007. "%s: %s is not allowed to connect",
  16008. __func__,
  16009. src_addr);
  16010. closesocket(so.sock);
  16011. } else {
  16012. /* Put so socket structure into the queue */
  16013. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16014. set_close_on_exec(so.sock, NULL, ctx);
  16015. so.is_ssl = listener->is_ssl;
  16016. so.ssl_redir = listener->ssl_redir;
  16017. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16018. mg_cry_ctx_internal(ctx,
  16019. "%s: getsockname() failed: %s",
  16020. __func__,
  16021. strerror(ERRNO));
  16022. }
  16023. #if !defined(__ZEPHYR__)
  16024. /* Set TCP keep-alive. This is needed because if HTTP-level
  16025. * keep-alive
  16026. * is enabled, and client resets the connection, server won't get
  16027. * TCP FIN or RST and will keep the connection open forever. With
  16028. * TCP keep-alive, next keep-alive handshake will figure out that
  16029. * the client is down and will close the server end.
  16030. * Thanks to Igor Klopov who suggested the patch. */
  16031. if (setsockopt(so.sock,
  16032. SOL_SOCKET,
  16033. SO_KEEPALIVE,
  16034. (SOCK_OPT_TYPE)&on,
  16035. sizeof(on))
  16036. != 0) {
  16037. mg_cry_ctx_internal(
  16038. ctx,
  16039. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16040. __func__,
  16041. strerror(ERRNO));
  16042. }
  16043. #endif
  16044. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16045. * to effectively fill up the underlying IP packet payload and
  16046. * reduce the overhead of sending lots of small buffers. However
  16047. * this hurts the server's throughput (ie. operations per second)
  16048. * when HTTP 1.1 persistent connections are used and the responses
  16049. * are relatively small (eg. less than 1400 bytes).
  16050. */
  16051. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16052. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16053. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16054. mg_cry_ctx_internal(
  16055. ctx,
  16056. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16057. __func__,
  16058. strerror(ERRNO));
  16059. }
  16060. }
  16061. /* The "non blocking" property should already be
  16062. * inherited from the parent socket. Set it for
  16063. * non-compliant socket implementations. */
  16064. set_non_blocking_mode(so.sock);
  16065. so.in_use = 0;
  16066. produce_socket(ctx, &so);
  16067. }
  16068. }
  16069. static void
  16070. master_thread_run(struct mg_context *ctx)
  16071. {
  16072. struct mg_workerTLS tls;
  16073. struct mg_pollfd *pfd;
  16074. unsigned int i;
  16075. unsigned int workerthreadcount;
  16076. if (!ctx) {
  16077. return;
  16078. }
  16079. mg_set_thread_name("master");
  16080. /* Increase priority of the master thread */
  16081. #if defined(_WIN32)
  16082. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16083. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16084. int min_prio = sched_get_priority_min(SCHED_RR);
  16085. int max_prio = sched_get_priority_max(SCHED_RR);
  16086. if ((min_prio >= 0) && (max_prio >= 0)
  16087. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16088. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16089. struct sched_param sched_param = {0};
  16090. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16091. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16092. }
  16093. #endif
  16094. /* Initialize thread local storage */
  16095. #if defined(_WIN32)
  16096. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16097. #endif
  16098. tls.is_master = 1;
  16099. pthread_setspecific(sTlsKey, &tls);
  16100. if (ctx->callbacks.init_thread) {
  16101. /* Callback for the master thread (type 0) */
  16102. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16103. } else {
  16104. tls.user_ptr = NULL;
  16105. }
  16106. /* Server starts *now* */
  16107. ctx->start_time = time(NULL);
  16108. /* Start the server */
  16109. pfd = ctx->listening_socket_fds;
  16110. while (ctx->stop_flag == 0) {
  16111. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16112. pfd[i].fd = ctx->listening_sockets[i].sock;
  16113. pfd[i].events = POLLIN;
  16114. }
  16115. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16116. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16117. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16118. * successful poll, and POLLIN is defined as
  16119. * (POLLRDNORM | POLLRDBAND)
  16120. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16121. * pfd[i].revents == POLLIN. */
  16122. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  16123. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16124. }
  16125. }
  16126. }
  16127. }
  16128. /* Here stop_flag is 1 - Initiate shutdown. */
  16129. DEBUG_TRACE("%s", "stopping workers");
  16130. /* Stop signal received: somebody called mg_stop. Quit. */
  16131. close_all_listening_sockets(ctx);
  16132. /* Wakeup workers that are waiting for connections to handle. */
  16133. #if defined(ALTERNATIVE_QUEUE)
  16134. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16135. event_signal(ctx->client_wait_events[i]);
  16136. }
  16137. #else
  16138. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16139. pthread_cond_broadcast(&ctx->sq_full);
  16140. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16141. #endif
  16142. /* Join all worker threads to avoid leaking threads. */
  16143. workerthreadcount = ctx->cfg_worker_threads;
  16144. for (i = 0; i < workerthreadcount; i++) {
  16145. if (ctx->worker_threadids[i] != 0) {
  16146. mg_join_thread(ctx->worker_threadids[i]);
  16147. }
  16148. }
  16149. #if defined(USE_LUA)
  16150. /* Free Lua state of lua background task */
  16151. if (ctx->lua_background_state) {
  16152. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16153. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16154. if (lua_istable(lstate, -1)) {
  16155. reg_boolean(lstate, "shutdown", 1);
  16156. lua_pop(lstate, 1);
  16157. mg_sleep(2);
  16158. }
  16159. lua_close(lstate);
  16160. ctx->lua_background_state = 0;
  16161. }
  16162. #endif
  16163. DEBUG_TRACE("%s", "exiting");
  16164. /* call exit thread callback */
  16165. if (ctx->callbacks.exit_thread) {
  16166. /* Callback for the master thread (type 0) */
  16167. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16168. }
  16169. #if defined(_WIN32)
  16170. CloseHandle(tls.pthread_cond_helper_mutex);
  16171. #endif
  16172. pthread_setspecific(sTlsKey, NULL);
  16173. /* Signal mg_stop() that we're done.
  16174. * WARNING: This must be the very last thing this
  16175. * thread does, as ctx becomes invalid after this line. */
  16176. ctx->stop_flag = 2;
  16177. }
  16178. /* Threads have different return types on Windows and Unix. */
  16179. #if defined(_WIN32)
  16180. static unsigned __stdcall master_thread(void *thread_func_param)
  16181. {
  16182. master_thread_run((struct mg_context *)thread_func_param);
  16183. return 0;
  16184. }
  16185. #else
  16186. static void *
  16187. master_thread(void *thread_func_param)
  16188. {
  16189. #if !defined(__ZEPHYR__)
  16190. struct sigaction sa;
  16191. /* Ignore SIGPIPE */
  16192. memset(&sa, 0, sizeof(sa));
  16193. sa.sa_handler = SIG_IGN;
  16194. sigaction(SIGPIPE, &sa, NULL);
  16195. #endif
  16196. master_thread_run((struct mg_context *)thread_func_param);
  16197. return NULL;
  16198. }
  16199. #endif /* _WIN32 */
  16200. static void
  16201. free_context(struct mg_context *ctx)
  16202. {
  16203. int i;
  16204. struct mg_handler_info *tmp_rh;
  16205. if (ctx == NULL) {
  16206. return;
  16207. }
  16208. if (ctx->callbacks.exit_context) {
  16209. ctx->callbacks.exit_context(ctx);
  16210. }
  16211. /* All threads exited, no sync is needed. Destroy thread mutex and
  16212. * condvars
  16213. */
  16214. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16215. #if defined(ALTERNATIVE_QUEUE)
  16216. mg_free(ctx->client_socks);
  16217. if (ctx->client_wait_events != NULL) {
  16218. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16219. event_destroy(ctx->client_wait_events[i]);
  16220. }
  16221. mg_free(ctx->client_wait_events);
  16222. }
  16223. #else
  16224. (void)pthread_cond_destroy(&ctx->sq_empty);
  16225. (void)pthread_cond_destroy(&ctx->sq_full);
  16226. mg_free(ctx->squeue);
  16227. #endif
  16228. /* Destroy other context global data structures mutex */
  16229. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16230. #if defined(USE_TIMERS)
  16231. timers_exit(ctx);
  16232. #endif
  16233. /* Deallocate config parameters */
  16234. for (i = 0; i < NUM_OPTIONS; i++) {
  16235. if (ctx->dd.config[i] != NULL) {
  16236. #if defined(_MSC_VER)
  16237. #pragma warning(suppress : 6001)
  16238. #endif
  16239. mg_free(ctx->dd.config[i]);
  16240. }
  16241. }
  16242. /* Deallocate request handlers */
  16243. while (ctx->dd.handlers) {
  16244. tmp_rh = ctx->dd.handlers;
  16245. ctx->dd.handlers = tmp_rh->next;
  16246. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  16247. pthread_cond_destroy(&tmp_rh->refcount_cond);
  16248. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  16249. }
  16250. mg_free(tmp_rh->uri);
  16251. mg_free(tmp_rh);
  16252. }
  16253. #if !defined(NO_SSL)
  16254. /* Deallocate SSL context */
  16255. if (ctx->dd.ssl_ctx != NULL) {
  16256. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16257. int callback_ret =
  16258. (ctx->callbacks.external_ssl_ctx == NULL)
  16259. ? 0
  16260. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16261. if (callback_ret == 0) {
  16262. SSL_CTX_free(ctx->dd.ssl_ctx);
  16263. }
  16264. /* else: ignore error and ommit SSL_CTX_free in case
  16265. * callback_ret is 1 */
  16266. }
  16267. #endif /* !NO_SSL */
  16268. /* Deallocate worker thread ID array */
  16269. mg_free(ctx->worker_threadids);
  16270. /* Deallocate worker thread ID array */
  16271. mg_free(ctx->worker_connections);
  16272. /* deallocate system name string */
  16273. mg_free(ctx->systemName);
  16274. /* Deallocate context itself */
  16275. mg_free(ctx);
  16276. }
  16277. void
  16278. mg_stop(struct mg_context *ctx)
  16279. {
  16280. pthread_t mt;
  16281. if (!ctx) {
  16282. return;
  16283. }
  16284. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16285. * two threads is not allowed. */
  16286. mt = ctx->masterthreadid;
  16287. if (mt == 0) {
  16288. return;
  16289. }
  16290. ctx->masterthreadid = 0;
  16291. /* Set stop flag, so all threads know they have to exit. */
  16292. ctx->stop_flag = 1;
  16293. /* Wait until everything has stopped. */
  16294. while (ctx->stop_flag != 2) {
  16295. (void)mg_sleep(10);
  16296. }
  16297. mg_join_thread(mt);
  16298. free_context(ctx);
  16299. #if defined(_WIN32)
  16300. (void)WSACleanup();
  16301. #endif /* _WIN32 */
  16302. }
  16303. static void
  16304. get_system_name(char **sysName)
  16305. {
  16306. #if defined(_WIN32)
  16307. #if defined(_WIN32_WCE)
  16308. *sysName = mg_strdup("WinCE");
  16309. #else
  16310. char name[128];
  16311. DWORD dwVersion = 0;
  16312. DWORD dwMajorVersion = 0;
  16313. DWORD dwMinorVersion = 0;
  16314. DWORD dwBuild = 0;
  16315. BOOL wowRet, isWoW = FALSE;
  16316. #if defined(_MSC_VER)
  16317. #pragma warning(push)
  16318. /* GetVersion was declared deprecated */
  16319. #pragma warning(disable : 4996)
  16320. #endif
  16321. dwVersion = GetVersion();
  16322. #if defined(_MSC_VER)
  16323. #pragma warning(pop)
  16324. #endif
  16325. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16326. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16327. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16328. (void)dwBuild;
  16329. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16330. sprintf(name,
  16331. "Windows %u.%u%s",
  16332. (unsigned)dwMajorVersion,
  16333. (unsigned)dwMinorVersion,
  16334. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16335. *sysName = mg_strdup(name);
  16336. #endif
  16337. #elif defined(__ZEPHYR__)
  16338. *sysName = mg_strdup("Zephyr OS");
  16339. #else
  16340. struct utsname name;
  16341. memset(&name, 0, sizeof(name));
  16342. uname(&name);
  16343. *sysName = mg_strdup(name.sysname);
  16344. #endif
  16345. }
  16346. static void
  16347. legacy_init(const char **options)
  16348. {
  16349. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16350. if (options) {
  16351. const char **run_options = options;
  16352. const char *optname = config_options[LISTENING_PORTS].name;
  16353. /* Try to find the "listening_ports" option */
  16354. while (*run_options) {
  16355. if (!strcmp(*run_options, optname)) {
  16356. ports_option = run_options[1];
  16357. }
  16358. run_options += 2;
  16359. }
  16360. }
  16361. if (is_ssl_port_used(ports_option)) {
  16362. /* Initialize with SSL support */
  16363. mg_init_library(MG_FEATURES_TLS);
  16364. } else {
  16365. /* Initialize without SSL support */
  16366. mg_init_library(MG_FEATURES_DEFAULT);
  16367. }
  16368. }
  16369. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16370. static
  16371. #endif
  16372. struct mg_context *
  16373. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16374. {
  16375. struct mg_context *ctx;
  16376. const char *name, *value, *default_value;
  16377. int idx, ok, workerthreadcount;
  16378. unsigned int i;
  16379. int itmp;
  16380. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16381. const char **options =
  16382. ((init != NULL) ? (init->configuration_options) : (NULL));
  16383. struct mg_workerTLS tls;
  16384. #if defined(_WIN32)
  16385. WSADATA data;
  16386. WSAStartup(MAKEWORD(2, 2), &data);
  16387. #endif /* _WIN32 */
  16388. if (error != NULL) {
  16389. error->code = 0;
  16390. if (error->text_buffer_size > 0) {
  16391. *error->text = 0;
  16392. }
  16393. }
  16394. if (mg_init_library_called == 0) {
  16395. /* Legacy INIT, if mg_start is called without mg_init_library.
  16396. * Note: This will cause a memory leak when unloading the library. */
  16397. legacy_init(options);
  16398. }
  16399. /* Allocate context and initialize reasonable general case defaults. */
  16400. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16401. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16402. mg_snprintf(NULL,
  16403. NULL, /* No truncation check for error buffers */
  16404. error->text,
  16405. error->text_buffer_size,
  16406. "%s",
  16407. "Out of memory");
  16408. }
  16409. return NULL;
  16410. }
  16411. /* Random number generator will initialize at the first call */
  16412. ctx->dd.auth_nonce_mask =
  16413. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16414. /* Save started thread index to reuse in other external API calls
  16415. * For the sake of thread synchronization all non-civetweb threads
  16416. * can be considered as single external thread */
  16417. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16418. tls.is_master = -1; /* Thread calling mg_start */
  16419. tls.thread_idx = ctx->starter_thread_idx;
  16420. #if defined(_WIN32)
  16421. tls.pthread_cond_helper_mutex = NULL;
  16422. #endif
  16423. pthread_setspecific(sTlsKey, &tls);
  16424. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16425. #if !defined(ALTERNATIVE_QUEUE)
  16426. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16427. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16428. ctx->sq_blocked = 0;
  16429. #endif
  16430. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16431. if (!ok) {
  16432. const char *err_msg =
  16433. "Cannot initialize thread synchronization objects";
  16434. /* Fatal error - abort start. However, this situation should never
  16435. * occur in practice. */
  16436. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16437. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16438. mg_snprintf(NULL,
  16439. NULL, /* No truncation check for error buffers */
  16440. error->text,
  16441. error->text_buffer_size,
  16442. "%s",
  16443. err_msg);
  16444. }
  16445. mg_free(ctx);
  16446. pthread_setspecific(sTlsKey, NULL);
  16447. return NULL;
  16448. }
  16449. if ((init != NULL) && (init->callbacks != NULL)) {
  16450. /* Set all callbacks except exit_context. */
  16451. ctx->callbacks = *init->callbacks;
  16452. exit_callback = init->callbacks->exit_context;
  16453. /* The exit callback is activated once the context is successfully
  16454. * created. It should not be called, if an incomplete context object is
  16455. * deleted during a failed initialization. */
  16456. ctx->callbacks.exit_context = 0;
  16457. }
  16458. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16459. ctx->dd.handlers = NULL;
  16460. ctx->dd.next = NULL;
  16461. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16462. ctx->dd.shared_lua_websockets = NULL;
  16463. #endif
  16464. /* Store options */
  16465. while (options && (name = *options++) != NULL) {
  16466. if ((idx = get_option_index(name)) == -1) {
  16467. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16468. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16469. mg_snprintf(NULL,
  16470. NULL, /* No truncation check for error buffers */
  16471. error->text,
  16472. error->text_buffer_size,
  16473. "Invalid configuration option: %s",
  16474. name);
  16475. }
  16476. free_context(ctx);
  16477. pthread_setspecific(sTlsKey, NULL);
  16478. return NULL;
  16479. } else if ((value = *options++) == NULL) {
  16480. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16481. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16482. mg_snprintf(NULL,
  16483. NULL, /* No truncation check for error buffers */
  16484. error->text,
  16485. error->text_buffer_size,
  16486. "Invalid configuration option value: %s",
  16487. name);
  16488. }
  16489. free_context(ctx);
  16490. pthread_setspecific(sTlsKey, NULL);
  16491. return NULL;
  16492. }
  16493. if (ctx->dd.config[idx] != NULL) {
  16494. /* A duplicate configuration option is not an error - the last
  16495. * option value will be used. */
  16496. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16497. mg_free(ctx->dd.config[idx]);
  16498. }
  16499. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16500. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16501. }
  16502. /* Set default value if needed */
  16503. for (i = 0; config_options[i].name != NULL; i++) {
  16504. default_value = config_options[i].default_value;
  16505. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16506. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16507. }
  16508. }
  16509. /* Request size option */
  16510. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16511. if (itmp < 1024) {
  16512. mg_cry_ctx_internal(ctx,
  16513. "%s too small",
  16514. config_options[MAX_REQUEST_SIZE].name);
  16515. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16516. mg_snprintf(NULL,
  16517. NULL, /* No truncation check for error buffers */
  16518. error->text,
  16519. error->text_buffer_size,
  16520. "Invalid configuration option value: %s",
  16521. config_options[MAX_REQUEST_SIZE].name);
  16522. }
  16523. free_context(ctx);
  16524. pthread_setspecific(sTlsKey, NULL);
  16525. return NULL;
  16526. }
  16527. ctx->max_request_size = (unsigned)itmp;
  16528. /* Queue length */
  16529. #if !defined(ALTERNATIVE_QUEUE)
  16530. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16531. if (itmp < 1) {
  16532. mg_cry_ctx_internal(ctx,
  16533. "%s too small",
  16534. config_options[CONNECTION_QUEUE_SIZE].name);
  16535. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16536. mg_snprintf(NULL,
  16537. NULL, /* No truncation check for error buffers */
  16538. error->text,
  16539. error->text_buffer_size,
  16540. "Invalid configuration option value: %s",
  16541. config_options[CONNECTION_QUEUE_SIZE].name);
  16542. }
  16543. free_context(ctx);
  16544. pthread_setspecific(sTlsKey, NULL);
  16545. return NULL;
  16546. }
  16547. ctx->squeue = (struct socket *)mg_calloc(itmp, sizeof(struct socket));
  16548. if (ctx->squeue == NULL) {
  16549. mg_cry_ctx_internal(ctx,
  16550. "Out of memory: Cannot allocate %s",
  16551. config_options[CONNECTION_QUEUE_SIZE].name);
  16552. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16553. mg_snprintf(NULL,
  16554. NULL, /* No truncation check for error buffers */
  16555. error->text,
  16556. error->text_buffer_size,
  16557. "Out of memory: Cannot allocate %s",
  16558. config_options[CONNECTION_QUEUE_SIZE].name);
  16559. }
  16560. free_context(ctx);
  16561. pthread_setspecific(sTlsKey, NULL);
  16562. return NULL;
  16563. }
  16564. ctx->sq_size = itmp;
  16565. #endif
  16566. /* Worker thread count option */
  16567. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16568. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16569. if (workerthreadcount <= 0) {
  16570. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16571. } else {
  16572. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16573. }
  16574. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16575. mg_snprintf(NULL,
  16576. NULL, /* No truncation check for error buffers */
  16577. error->text,
  16578. error->text_buffer_size,
  16579. "Invalid configuration option value: %s",
  16580. config_options[NUM_THREADS].name);
  16581. }
  16582. free_context(ctx);
  16583. pthread_setspecific(sTlsKey, NULL);
  16584. return NULL;
  16585. }
  16586. /* Document root */
  16587. #if defined(NO_FILES)
  16588. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16589. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16590. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16591. mg_snprintf(NULL,
  16592. NULL, /* No truncation check for error buffers */
  16593. error->text,
  16594. error->text_buffer_size,
  16595. "Invalid configuration option value: %s",
  16596. config_options[DOCUMENT_ROOT].name);
  16597. }
  16598. free_context(ctx);
  16599. pthread_setspecific(sTlsKey, NULL);
  16600. return NULL;
  16601. }
  16602. #endif
  16603. get_system_name(&ctx->systemName);
  16604. #if defined(USE_LUA)
  16605. /* If a Lua background script has been configured, start it. */
  16606. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16607. char ebuf[256];
  16608. struct vec opt_vec;
  16609. struct vec eq_vec;
  16610. const char *sparams;
  16611. lua_State *state = mg_prepare_lua_context_script(
  16612. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16613. if (!state) {
  16614. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16615. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16616. mg_snprintf(NULL,
  16617. NULL, /* No truncation check for error buffers */
  16618. error->text,
  16619. error->text_buffer_size,
  16620. "Error in script %s: %s",
  16621. config_options[DOCUMENT_ROOT].name,
  16622. ebuf);
  16623. }
  16624. free_context(ctx);
  16625. pthread_setspecific(sTlsKey, NULL);
  16626. return NULL;
  16627. }
  16628. ctx->lua_background_state = (void *)state;
  16629. lua_newtable(state);
  16630. reg_boolean(state, "shutdown", 0);
  16631. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16632. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16633. reg_llstring(
  16634. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16635. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16636. break;
  16637. }
  16638. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16639. } else {
  16640. ctx->lua_background_state = 0;
  16641. }
  16642. #endif
  16643. /* Step by step initialization of ctx - depending on build options */
  16644. #if !defined(NO_FILESYSTEMS)
  16645. if (!set_gpass_option(ctx, NULL)) {
  16646. const char *err_msg = "Invalid global password file";
  16647. /* Fatal error - abort start. */
  16648. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16649. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16650. mg_snprintf(NULL,
  16651. NULL, /* No truncation check for error buffers */
  16652. error->text,
  16653. error->text_buffer_size,
  16654. "%s",
  16655. err_msg);
  16656. }
  16657. free_context(ctx);
  16658. pthread_setspecific(sTlsKey, NULL);
  16659. return NULL;
  16660. }
  16661. #endif
  16662. #if !defined(NO_SSL)
  16663. if (!init_ssl_ctx(ctx, NULL)) {
  16664. const char *err_msg = "Error initializing SSL context";
  16665. /* Fatal error - abort start. */
  16666. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16667. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16668. mg_snprintf(NULL,
  16669. NULL, /* No truncation check for error buffers */
  16670. error->text,
  16671. error->text_buffer_size,
  16672. "%s",
  16673. err_msg);
  16674. }
  16675. free_context(ctx);
  16676. pthread_setspecific(sTlsKey, NULL);
  16677. return NULL;
  16678. }
  16679. #endif
  16680. if (!set_ports_option(ctx)) {
  16681. const char *err_msg = "Failed to setup server ports";
  16682. /* Fatal error - abort start. */
  16683. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16684. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16685. mg_snprintf(NULL,
  16686. NULL, /* No truncation check for error buffers */
  16687. error->text,
  16688. error->text_buffer_size,
  16689. "%s",
  16690. err_msg);
  16691. }
  16692. free_context(ctx);
  16693. pthread_setspecific(sTlsKey, NULL);
  16694. return NULL;
  16695. }
  16696. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16697. if (!set_uid_option(ctx)) {
  16698. const char *err_msg = "Failed to run as configured user";
  16699. /* Fatal error - abort start. */
  16700. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16701. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16702. mg_snprintf(NULL,
  16703. NULL, /* No truncation check for error buffers */
  16704. error->text,
  16705. error->text_buffer_size,
  16706. "%s",
  16707. err_msg);
  16708. }
  16709. free_context(ctx);
  16710. pthread_setspecific(sTlsKey, NULL);
  16711. return NULL;
  16712. }
  16713. #endif
  16714. if (!set_acl_option(ctx)) {
  16715. const char *err_msg = "Failed to setup access control list";
  16716. /* Fatal error - abort start. */
  16717. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16718. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16719. mg_snprintf(NULL,
  16720. NULL, /* No truncation check for error buffers */
  16721. error->text,
  16722. error->text_buffer_size,
  16723. "%s",
  16724. err_msg);
  16725. }
  16726. free_context(ctx);
  16727. pthread_setspecific(sTlsKey, NULL);
  16728. return NULL;
  16729. }
  16730. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16731. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16732. sizeof(pthread_t),
  16733. ctx);
  16734. if (ctx->worker_threadids == NULL) {
  16735. const char *err_msg = "Not enough memory for worker thread ID array";
  16736. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16737. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16738. mg_snprintf(NULL,
  16739. NULL, /* No truncation check for error buffers */
  16740. error->text,
  16741. error->text_buffer_size,
  16742. "%s",
  16743. err_msg);
  16744. }
  16745. free_context(ctx);
  16746. pthread_setspecific(sTlsKey, NULL);
  16747. return NULL;
  16748. }
  16749. ctx->worker_connections =
  16750. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16751. sizeof(struct mg_connection),
  16752. ctx);
  16753. if (ctx->worker_connections == NULL) {
  16754. const char *err_msg =
  16755. "Not enough memory for worker thread connection array";
  16756. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16757. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16758. mg_snprintf(NULL,
  16759. NULL, /* No truncation check for error buffers */
  16760. error->text,
  16761. error->text_buffer_size,
  16762. "%s",
  16763. err_msg);
  16764. }
  16765. free_context(ctx);
  16766. pthread_setspecific(sTlsKey, NULL);
  16767. return NULL;
  16768. }
  16769. #if defined(ALTERNATIVE_QUEUE)
  16770. ctx->client_wait_events =
  16771. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  16772. sizeof(ctx->client_wait_events[0]),
  16773. ctx);
  16774. if (ctx->client_wait_events == NULL) {
  16775. const char *err_msg = "Not enough memory for worker event array";
  16776. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16777. mg_free(ctx->worker_threadids);
  16778. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16779. mg_snprintf(NULL,
  16780. NULL, /* No truncation check for error buffers */
  16781. error->text,
  16782. error->text_buffer_size,
  16783. "%s",
  16784. err_msg);
  16785. }
  16786. free_context(ctx);
  16787. pthread_setspecific(sTlsKey, NULL);
  16788. return NULL;
  16789. }
  16790. ctx->client_socks =
  16791. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16792. sizeof(ctx->client_socks[0]),
  16793. ctx);
  16794. if (ctx->client_socks == NULL) {
  16795. const char *err_msg = "Not enough memory for worker socket array";
  16796. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16797. mg_free(ctx->client_wait_events);
  16798. mg_free(ctx->worker_threadids);
  16799. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16800. mg_snprintf(NULL,
  16801. NULL, /* No truncation check for error buffers */
  16802. error->text,
  16803. error->text_buffer_size,
  16804. "%s",
  16805. err_msg);
  16806. }
  16807. free_context(ctx);
  16808. pthread_setspecific(sTlsKey, NULL);
  16809. return NULL;
  16810. }
  16811. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16812. ctx->client_wait_events[i] = event_create();
  16813. if (ctx->client_wait_events[i] == 0) {
  16814. const char *err_msg = "Error creating worker event %i";
  16815. mg_cry_ctx_internal(ctx, err_msg, i);
  16816. while (i > 0) {
  16817. i--;
  16818. event_destroy(ctx->client_wait_events[i]);
  16819. }
  16820. mg_free(ctx->client_socks);
  16821. mg_free(ctx->client_wait_events);
  16822. mg_free(ctx->worker_threadids);
  16823. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16824. mg_snprintf(NULL,
  16825. NULL, /* No truncation check for error buffers */
  16826. error->text,
  16827. error->text_buffer_size,
  16828. err_msg,
  16829. i);
  16830. }
  16831. free_context(ctx);
  16832. pthread_setspecific(sTlsKey, NULL);
  16833. return NULL;
  16834. }
  16835. }
  16836. #endif
  16837. #if defined(USE_TIMERS)
  16838. if (timers_init(ctx) != 0) {
  16839. const char *err_msg = "Error creating timers";
  16840. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16841. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16842. mg_snprintf(NULL,
  16843. NULL, /* No truncation check for error buffers */
  16844. error->text,
  16845. error->text_buffer_size,
  16846. "%s",
  16847. err_msg);
  16848. }
  16849. free_context(ctx);
  16850. pthread_setspecific(sTlsKey, NULL);
  16851. return NULL;
  16852. }
  16853. #endif
  16854. /* Context has been created - init user libraries */
  16855. if (ctx->callbacks.init_context) {
  16856. ctx->callbacks.init_context(ctx);
  16857. }
  16858. /* From now, the context is successfully created.
  16859. * When it is destroyed, the exit callback should be called. */
  16860. ctx->callbacks.exit_context = exit_callback;
  16861. ctx->context_type = CONTEXT_SERVER; /* server context */
  16862. /* Start master (listening) thread */
  16863. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16864. /* Start worker threads */
  16865. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16866. /* worker_thread sets up the other fields */
  16867. ctx->worker_connections[i].phys_ctx = ctx;
  16868. if (mg_start_thread_with_id(worker_thread,
  16869. &ctx->worker_connections[i],
  16870. &ctx->worker_threadids[i])
  16871. != 0) {
  16872. long error_no = (long)ERRNO;
  16873. /* thread was not created */
  16874. if (i > 0) {
  16875. /* If the second, third, ... thread cannot be created, set a
  16876. * warning, but keep running. */
  16877. mg_cry_ctx_internal(ctx,
  16878. "Cannot start worker thread %i: error %ld",
  16879. i + 1,
  16880. error_no);
  16881. /* If the server initialization should stop here, all threads
  16882. * that have already been created must be stopped first, before
  16883. * any free_context(ctx) call.
  16884. */
  16885. } else {
  16886. /* If the first worker thread cannot be created, stop
  16887. * initialization and free the entire server context. */
  16888. mg_cry_ctx_internal(ctx,
  16889. "Cannot create threads: error %ld",
  16890. error_no);
  16891. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16892. mg_snprintf(
  16893. NULL,
  16894. NULL, /* No truncation check for error buffers */
  16895. error->text,
  16896. error->text_buffer_size,
  16897. "Cannot create first worker thread: error %ld",
  16898. error_no);
  16899. }
  16900. free_context(ctx);
  16901. pthread_setspecific(sTlsKey, NULL);
  16902. return NULL;
  16903. }
  16904. break;
  16905. }
  16906. }
  16907. pthread_setspecific(sTlsKey, NULL);
  16908. return ctx;
  16909. }
  16910. struct mg_context *
  16911. mg_start(const struct mg_callbacks *callbacks,
  16912. void *user_data,
  16913. const char **options)
  16914. {
  16915. struct mg_init_data init = {0};
  16916. init.callbacks = callbacks;
  16917. init.user_data = user_data;
  16918. init.configuration_options = options;
  16919. return mg_start2(&init, NULL);
  16920. }
  16921. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16922. /* Add an additional domain to an already running web server. */
  16923. int
  16924. mg_start_domain2(struct mg_context *ctx,
  16925. const char **options,
  16926. struct mg_error_data *error)
  16927. {
  16928. const char *name;
  16929. const char *value;
  16930. const char *default_value;
  16931. struct mg_domain_context *new_dom;
  16932. struct mg_domain_context *dom;
  16933. int idx, i;
  16934. if (error != NULL) {
  16935. error->code = 0;
  16936. if (error->text_buffer_size > 0) {
  16937. *error->text = 0;
  16938. }
  16939. }
  16940. if ((ctx == NULL) || (options == NULL)) {
  16941. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16942. mg_snprintf(NULL,
  16943. NULL, /* No truncation check for error buffers */
  16944. error->text,
  16945. error->text_buffer_size,
  16946. "%s",
  16947. "Invalid parameters");
  16948. }
  16949. return -1;
  16950. }
  16951. if (ctx->stop_flag != 0) {
  16952. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16953. mg_snprintf(NULL,
  16954. NULL, /* No truncation check for error buffers */
  16955. error->text,
  16956. error->text_buffer_size,
  16957. "%s",
  16958. "Server already stopped");
  16959. }
  16960. return -1;
  16961. }
  16962. new_dom = (struct mg_domain_context *)
  16963. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16964. if (!new_dom) {
  16965. /* Out of memory */
  16966. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16967. mg_snprintf(NULL,
  16968. NULL, /* No truncation check for error buffers */
  16969. error->text,
  16970. error->text_buffer_size,
  16971. "%s",
  16972. "Out or memory");
  16973. }
  16974. return -6;
  16975. }
  16976. /* Store options - TODO: unite duplicate code */
  16977. while (options && (name = *options++) != NULL) {
  16978. if ((idx = get_option_index(name)) == -1) {
  16979. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16980. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16981. mg_snprintf(NULL,
  16982. NULL, /* No truncation check for error buffers */
  16983. error->text,
  16984. error->text_buffer_size,
  16985. "Invalid option: %s",
  16986. name);
  16987. }
  16988. mg_free(new_dom);
  16989. return -2;
  16990. } else if ((value = *options++) == NULL) {
  16991. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16992. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16993. mg_snprintf(NULL,
  16994. NULL, /* No truncation check for error buffers */
  16995. error->text,
  16996. error->text_buffer_size,
  16997. "Invalid option value: %s",
  16998. name);
  16999. }
  17000. mg_free(new_dom);
  17001. return -2;
  17002. }
  17003. if (new_dom->config[idx] != NULL) {
  17004. /* Duplicate option: Later values overwrite earlier ones. */
  17005. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17006. mg_free(new_dom->config[idx]);
  17007. }
  17008. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17009. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17010. }
  17011. /* Authentication domain is mandatory */
  17012. /* TODO: Maybe use a new option hostname? */
  17013. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17014. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17015. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17016. mg_snprintf(NULL,
  17017. NULL, /* No truncation check for error buffers */
  17018. error->text,
  17019. error->text_buffer_size,
  17020. "Mandatory option %s missing",
  17021. config_options[AUTHENTICATION_DOMAIN].name);
  17022. }
  17023. mg_free(new_dom);
  17024. return -4;
  17025. }
  17026. /* Set default value if needed. Take the config value from
  17027. * ctx as a default value. */
  17028. for (i = 0; config_options[i].name != NULL; i++) {
  17029. default_value = ctx->dd.config[i];
  17030. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17031. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17032. }
  17033. }
  17034. new_dom->handlers = NULL;
  17035. new_dom->next = NULL;
  17036. new_dom->nonce_count = 0;
  17037. new_dom->auth_nonce_mask =
  17038. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17039. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17040. new_dom->shared_lua_websockets = NULL;
  17041. #endif
  17042. if (!init_ssl_ctx(ctx, new_dom)) {
  17043. /* Init SSL failed */
  17044. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17045. mg_snprintf(NULL,
  17046. NULL, /* No truncation check for error buffers */
  17047. error->text,
  17048. error->text_buffer_size,
  17049. "%s",
  17050. "Initializing SSL context failed");
  17051. }
  17052. mg_free(new_dom);
  17053. return -3;
  17054. }
  17055. /* Add element to linked list. */
  17056. mg_lock_context(ctx);
  17057. idx = 0;
  17058. dom = &(ctx->dd);
  17059. for (;;) {
  17060. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17061. dom->config[AUTHENTICATION_DOMAIN])) {
  17062. /* Domain collision */
  17063. mg_cry_ctx_internal(ctx,
  17064. "domain %s already in use",
  17065. new_dom->config[AUTHENTICATION_DOMAIN]);
  17066. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17067. mg_snprintf(NULL,
  17068. NULL, /* No truncation check for error buffers */
  17069. error->text,
  17070. error->text_buffer_size,
  17071. "Domain %s specified by %s is already in use",
  17072. new_dom->config[AUTHENTICATION_DOMAIN],
  17073. config_options[AUTHENTICATION_DOMAIN].name);
  17074. }
  17075. mg_free(new_dom);
  17076. mg_unlock_context(ctx);
  17077. return -5;
  17078. }
  17079. /* Count number of domains */
  17080. idx++;
  17081. if (dom->next == NULL) {
  17082. dom->next = new_dom;
  17083. break;
  17084. }
  17085. dom = dom->next;
  17086. }
  17087. mg_unlock_context(ctx);
  17088. /* Return domain number */
  17089. return idx;
  17090. }
  17091. int
  17092. mg_start_domain(struct mg_context *ctx, const char **options)
  17093. {
  17094. return mg_start_domain2(ctx, options, NULL);
  17095. }
  17096. #endif
  17097. /* Feature check API function */
  17098. unsigned
  17099. mg_check_feature(unsigned feature)
  17100. {
  17101. static const unsigned feature_set = 0
  17102. /* Set bits for available features according to API documentation.
  17103. * This bit mask is created at compile time, according to the active
  17104. * preprocessor defines. It is a single const value at runtime. */
  17105. #if !defined(NO_FILES)
  17106. | MG_FEATURES_FILES
  17107. #endif
  17108. #if !defined(NO_SSL)
  17109. | MG_FEATURES_SSL
  17110. #endif
  17111. #if !defined(NO_CGI)
  17112. | MG_FEATURES_CGI
  17113. #endif
  17114. #if defined(USE_IPV6)
  17115. | MG_FEATURES_IPV6
  17116. #endif
  17117. #if defined(USE_WEBSOCKET)
  17118. | MG_FEATURES_WEBSOCKET
  17119. #endif
  17120. #if defined(USE_LUA)
  17121. | MG_FEATURES_LUA
  17122. #endif
  17123. #if defined(USE_DUKTAPE)
  17124. | MG_FEATURES_SSJS
  17125. #endif
  17126. #if !defined(NO_CACHING)
  17127. | MG_FEATURES_CACHE
  17128. #endif
  17129. #if defined(USE_SERVER_STATS)
  17130. | MG_FEATURES_STATS
  17131. #endif
  17132. #if defined(USE_ZLIB)
  17133. | MG_FEATURES_COMPRESSION
  17134. #endif
  17135. /* Set some extra bits not defined in the API documentation.
  17136. * These bits may change without further notice. */
  17137. #if defined(MG_LEGACY_INTERFACE)
  17138. | 0x00008000u
  17139. #endif
  17140. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17141. | 0x00004000u
  17142. #endif
  17143. #if defined(MEMORY_DEBUGGING)
  17144. | 0x00001000u
  17145. #endif
  17146. #if defined(USE_TIMERS)
  17147. | 0x00020000u
  17148. #endif
  17149. #if !defined(NO_NONCE_CHECK)
  17150. | 0x00040000u
  17151. #endif
  17152. #if !defined(NO_POPEN)
  17153. | 0x00080000u
  17154. #endif
  17155. ;
  17156. return (feature & feature_set);
  17157. }
  17158. static size_t
  17159. mg_str_append(char **dst, char *end, const char *src)
  17160. {
  17161. size_t len = strlen(src);
  17162. if (*dst != end) {
  17163. /* Append src if enough space, or close dst. */
  17164. if ((size_t)(end - *dst) > len) {
  17165. strcpy(*dst, src);
  17166. *dst += len;
  17167. } else {
  17168. *dst = end;
  17169. }
  17170. }
  17171. return len;
  17172. }
  17173. /* Get system information. It can be printed or stored by the caller.
  17174. * Return the size of available information. */
  17175. int
  17176. mg_get_system_info(char *buffer, int buflen)
  17177. {
  17178. char *end, *append_eoobj = NULL, block[256];
  17179. size_t system_info_length = 0;
  17180. #if defined(_WIN32)
  17181. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17182. #else
  17183. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17184. #endif
  17185. if ((buffer == NULL) || (buflen < 1)) {
  17186. buflen = 0;
  17187. end = buffer;
  17188. } else {
  17189. *buffer = 0;
  17190. end = buffer + buflen;
  17191. }
  17192. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17193. /* has enough space to append eoobj */
  17194. append_eoobj = buffer;
  17195. end -= sizeof(eoobj) - 1;
  17196. }
  17197. system_info_length += mg_str_append(&buffer, end, "{");
  17198. /* Server version */
  17199. {
  17200. const char *version = mg_version();
  17201. mg_snprintf(NULL,
  17202. NULL,
  17203. block,
  17204. sizeof(block),
  17205. "%s\"version\" : \"%s\"",
  17206. eol,
  17207. version);
  17208. system_info_length += mg_str_append(&buffer, end, block);
  17209. }
  17210. /* System info */
  17211. {
  17212. #if defined(_WIN32)
  17213. DWORD dwVersion = 0;
  17214. DWORD dwMajorVersion = 0;
  17215. DWORD dwMinorVersion = 0;
  17216. SYSTEM_INFO si;
  17217. GetSystemInfo(&si);
  17218. #if defined(_MSC_VER)
  17219. #pragma warning(push)
  17220. /* GetVersion was declared deprecated */
  17221. #pragma warning(disable : 4996)
  17222. #endif
  17223. dwVersion = GetVersion();
  17224. #if defined(_MSC_VER)
  17225. #pragma warning(pop)
  17226. #endif
  17227. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17228. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17229. mg_snprintf(NULL,
  17230. NULL,
  17231. block,
  17232. sizeof(block),
  17233. ",%s\"os\" : \"Windows %u.%u\"",
  17234. eol,
  17235. (unsigned)dwMajorVersion,
  17236. (unsigned)dwMinorVersion);
  17237. system_info_length += mg_str_append(&buffer, end, block);
  17238. mg_snprintf(NULL,
  17239. NULL,
  17240. block,
  17241. sizeof(block),
  17242. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17243. eol,
  17244. (unsigned)si.wProcessorArchitecture,
  17245. (unsigned)si.dwNumberOfProcessors,
  17246. (unsigned)si.dwActiveProcessorMask);
  17247. system_info_length += mg_str_append(&buffer, end, block);
  17248. #elif defined(__ZEPHYR__)
  17249. mg_snprintf(NULL,
  17250. NULL,
  17251. block,
  17252. sizeof(block),
  17253. ",%s\"os\" : \"%s %s\"",
  17254. eol,
  17255. "Zephyr OS",
  17256. ZEPHYR_VERSION);
  17257. system_info_length += mg_str_append(&buffer, end, block);
  17258. #else
  17259. struct utsname name;
  17260. memset(&name, 0, sizeof(name));
  17261. uname(&name);
  17262. mg_snprintf(NULL,
  17263. NULL,
  17264. block,
  17265. sizeof(block),
  17266. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17267. eol,
  17268. name.sysname,
  17269. name.version,
  17270. name.release,
  17271. name.machine);
  17272. system_info_length += mg_str_append(&buffer, end, block);
  17273. #endif
  17274. }
  17275. /* Features */
  17276. {
  17277. mg_snprintf(NULL,
  17278. NULL,
  17279. block,
  17280. sizeof(block),
  17281. ",%s\"features\" : %lu"
  17282. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17283. eol,
  17284. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17285. eol,
  17286. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17287. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17288. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17289. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17290. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17291. : "",
  17292. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17293. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17294. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17295. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17296. system_info_length += mg_str_append(&buffer, end, block);
  17297. #if defined(USE_LUA)
  17298. mg_snprintf(NULL,
  17299. NULL,
  17300. block,
  17301. sizeof(block),
  17302. ",%s\"lua_version\" : \"%u (%s)\"",
  17303. eol,
  17304. (unsigned)LUA_VERSION_NUM,
  17305. LUA_RELEASE);
  17306. system_info_length += mg_str_append(&buffer, end, block);
  17307. #endif
  17308. #if defined(USE_DUKTAPE)
  17309. mg_snprintf(NULL,
  17310. NULL,
  17311. block,
  17312. sizeof(block),
  17313. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17314. eol,
  17315. (unsigned)DUK_VERSION / 10000,
  17316. ((unsigned)DUK_VERSION / 100) % 100,
  17317. (unsigned)DUK_VERSION % 100);
  17318. system_info_length += mg_str_append(&buffer, end, block);
  17319. #endif
  17320. }
  17321. /* Build date */
  17322. {
  17323. #if defined(GCC_DIAGNOSTIC)
  17324. #if GCC_VERSION >= 40900
  17325. #pragma GCC diagnostic push
  17326. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17327. #pragma GCC diagnostic ignored "-Wdate-time"
  17328. #endif
  17329. #endif
  17330. mg_snprintf(NULL,
  17331. NULL,
  17332. block,
  17333. sizeof(block),
  17334. ",%s\"build\" : \"%s\"",
  17335. eol,
  17336. __DATE__);
  17337. #if defined(GCC_DIAGNOSTIC)
  17338. #if GCC_VERSION >= 40900
  17339. #pragma GCC diagnostic pop
  17340. #endif
  17341. #endif
  17342. system_info_length += mg_str_append(&buffer, end, block);
  17343. }
  17344. /* Compiler information */
  17345. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17346. {
  17347. #if defined(_MSC_VER)
  17348. mg_snprintf(NULL,
  17349. NULL,
  17350. block,
  17351. sizeof(block),
  17352. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17353. eol,
  17354. (unsigned)_MSC_VER,
  17355. (unsigned)_MSC_FULL_VER);
  17356. system_info_length += mg_str_append(&buffer, end, block);
  17357. #elif defined(__MINGW64__)
  17358. mg_snprintf(NULL,
  17359. NULL,
  17360. block,
  17361. sizeof(block),
  17362. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17363. eol,
  17364. (unsigned)__MINGW64_VERSION_MAJOR,
  17365. (unsigned)__MINGW64_VERSION_MINOR);
  17366. system_info_length += mg_str_append(&buffer, end, block);
  17367. mg_snprintf(NULL,
  17368. NULL,
  17369. block,
  17370. sizeof(block),
  17371. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17372. eol,
  17373. (unsigned)__MINGW32_MAJOR_VERSION,
  17374. (unsigned)__MINGW32_MINOR_VERSION);
  17375. system_info_length += mg_str_append(&buffer, end, block);
  17376. #elif defined(__MINGW32__)
  17377. mg_snprintf(NULL,
  17378. NULL,
  17379. block,
  17380. sizeof(block),
  17381. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17382. eol,
  17383. (unsigned)__MINGW32_MAJOR_VERSION,
  17384. (unsigned)__MINGW32_MINOR_VERSION);
  17385. system_info_length += mg_str_append(&buffer, end, block);
  17386. #elif defined(__clang__)
  17387. mg_snprintf(NULL,
  17388. NULL,
  17389. block,
  17390. sizeof(block),
  17391. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17392. eol,
  17393. __clang_major__,
  17394. __clang_minor__,
  17395. __clang_patchlevel__,
  17396. __clang_version__);
  17397. system_info_length += mg_str_append(&buffer, end, block);
  17398. #elif defined(__GNUC__)
  17399. mg_snprintf(NULL,
  17400. NULL,
  17401. block,
  17402. sizeof(block),
  17403. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17404. eol,
  17405. (unsigned)__GNUC__,
  17406. (unsigned)__GNUC_MINOR__,
  17407. (unsigned)__GNUC_PATCHLEVEL__);
  17408. system_info_length += mg_str_append(&buffer, end, block);
  17409. #elif defined(__INTEL_COMPILER)
  17410. mg_snprintf(NULL,
  17411. NULL,
  17412. block,
  17413. sizeof(block),
  17414. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17415. eol,
  17416. (unsigned)__INTEL_COMPILER);
  17417. system_info_length += mg_str_append(&buffer, end, block);
  17418. #elif defined(__BORLANDC__)
  17419. mg_snprintf(NULL,
  17420. NULL,
  17421. block,
  17422. sizeof(block),
  17423. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17424. eol,
  17425. (unsigned)__BORLANDC__);
  17426. system_info_length += mg_str_append(&buffer, end, block);
  17427. #elif defined(__SUNPRO_C)
  17428. mg_snprintf(NULL,
  17429. NULL,
  17430. block,
  17431. sizeof(block),
  17432. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17433. eol,
  17434. (unsigned)__SUNPRO_C);
  17435. system_info_length += mg_str_append(&buffer, end, block);
  17436. #else
  17437. mg_snprintf(NULL,
  17438. NULL,
  17439. block,
  17440. sizeof(block),
  17441. ",%s\"compiler\" : \"other\"",
  17442. eol);
  17443. system_info_length += mg_str_append(&buffer, end, block);
  17444. #endif
  17445. }
  17446. /* Determine 32/64 bit data mode.
  17447. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17448. {
  17449. mg_snprintf(NULL,
  17450. NULL,
  17451. block,
  17452. sizeof(block),
  17453. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17454. "char:%u/%u, "
  17455. "ptr:%u, size:%u, time:%u\"",
  17456. eol,
  17457. (unsigned)sizeof(short),
  17458. (unsigned)sizeof(int),
  17459. (unsigned)sizeof(long),
  17460. (unsigned)sizeof(long long),
  17461. (unsigned)sizeof(float),
  17462. (unsigned)sizeof(double),
  17463. (unsigned)sizeof(long double),
  17464. (unsigned)sizeof(char),
  17465. (unsigned)sizeof(wchar_t),
  17466. (unsigned)sizeof(void *),
  17467. (unsigned)sizeof(size_t),
  17468. (unsigned)sizeof(time_t));
  17469. system_info_length += mg_str_append(&buffer, end, block);
  17470. }
  17471. /* Terminate string */
  17472. if (append_eoobj) {
  17473. strcat(append_eoobj, eoobj);
  17474. }
  17475. system_info_length += sizeof(eoobj) - 1;
  17476. return (int)system_info_length;
  17477. }
  17478. /* Get context information. It can be printed or stored by the caller.
  17479. * Return the size of available information. */
  17480. int
  17481. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17482. {
  17483. #if defined(USE_SERVER_STATS)
  17484. char *end, *append_eoobj = NULL, block[256];
  17485. size_t context_info_length = 0;
  17486. #if defined(_WIN32)
  17487. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17488. #else
  17489. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17490. #endif
  17491. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17492. if ((buffer == NULL) || (buflen < 1)) {
  17493. buflen = 0;
  17494. end = buffer;
  17495. } else {
  17496. *buffer = 0;
  17497. end = buffer + buflen;
  17498. }
  17499. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17500. /* has enough space to append eoobj */
  17501. append_eoobj = buffer;
  17502. end -= sizeof(eoobj) - 1;
  17503. }
  17504. context_info_length += mg_str_append(&buffer, end, "{");
  17505. if (ms) { /* <-- should be always true */
  17506. /* Memory information */
  17507. mg_snprintf(NULL,
  17508. NULL,
  17509. block,
  17510. sizeof(block),
  17511. "%s\"memory\" : {%s"
  17512. "\"blocks\" : %i,%s"
  17513. "\"used\" : %" INT64_FMT ",%s"
  17514. "\"maxUsed\" : %" INT64_FMT "%s"
  17515. "}",
  17516. eol,
  17517. eol,
  17518. ms->blockCount,
  17519. eol,
  17520. ms->totalMemUsed,
  17521. eol,
  17522. ms->maxMemUsed,
  17523. eol);
  17524. context_info_length += mg_str_append(&buffer, end, block);
  17525. }
  17526. if (ctx) {
  17527. /* Declare all variables at begin of the block, to comply
  17528. * with old C standards. */
  17529. char start_time_str[64] = {0};
  17530. char now_str[64] = {0};
  17531. time_t start_time = ctx->start_time;
  17532. time_t now = time(NULL);
  17533. /* Connections information */
  17534. mg_snprintf(NULL,
  17535. NULL,
  17536. block,
  17537. sizeof(block),
  17538. ",%s\"connections\" : {%s"
  17539. "\"active\" : %i,%s"
  17540. "\"maxActive\" : %i,%s"
  17541. "\"total\" : %" INT64_FMT "%s"
  17542. "}",
  17543. eol,
  17544. eol,
  17545. ctx->active_connections,
  17546. eol,
  17547. ctx->max_active_connections,
  17548. eol,
  17549. ctx->total_connections,
  17550. eol);
  17551. context_info_length += mg_str_append(&buffer, end, block);
  17552. /* Queue information */
  17553. #if !defined(ALTERNATIVE_QUEUE)
  17554. mg_snprintf(NULL,
  17555. NULL,
  17556. block,
  17557. sizeof(block),
  17558. ",%s\"queue\" : {%s"
  17559. "\"length\" : %i,%s"
  17560. "\"filled\" : %i,%s"
  17561. "\"maxFilled\" : %i,%s"
  17562. "\"full\" : %s%s"
  17563. "}",
  17564. eol,
  17565. eol,
  17566. ctx->sq_size,
  17567. eol,
  17568. ctx->sq_head - ctx->sq_tail,
  17569. eol,
  17570. ctx->sq_max_fill,
  17571. eol,
  17572. (ctx->sq_blocked ? "true" : "false"),
  17573. eol);
  17574. context_info_length += mg_str_append(&buffer, end, block);
  17575. #endif
  17576. /* Requests information */
  17577. mg_snprintf(NULL,
  17578. NULL,
  17579. block,
  17580. sizeof(block),
  17581. ",%s\"requests\" : {%s"
  17582. "\"total\" : %" INT64_FMT "%s"
  17583. "}",
  17584. eol,
  17585. eol,
  17586. ctx->total_requests,
  17587. eol);
  17588. context_info_length += mg_str_append(&buffer, end, block);
  17589. /* Data information */
  17590. mg_snprintf(NULL,
  17591. NULL,
  17592. block,
  17593. sizeof(block),
  17594. ",%s\"data\" : {%s"
  17595. "\"read\" : %" INT64_FMT ",%s"
  17596. "\"written\" : %" INT64_FMT "%s"
  17597. "}",
  17598. eol,
  17599. eol,
  17600. ctx->total_data_read,
  17601. eol,
  17602. ctx->total_data_written,
  17603. eol);
  17604. context_info_length += mg_str_append(&buffer, end, block);
  17605. /* Execution time information */
  17606. gmt_time_string(start_time_str,
  17607. sizeof(start_time_str) - 1,
  17608. &start_time);
  17609. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17610. mg_snprintf(NULL,
  17611. NULL,
  17612. block,
  17613. sizeof(block),
  17614. ",%s\"time\" : {%s"
  17615. "\"uptime\" : %.0f,%s"
  17616. "\"start\" : \"%s\",%s"
  17617. "\"now\" : \"%s\"%s"
  17618. "}",
  17619. eol,
  17620. eol,
  17621. difftime(now, start_time),
  17622. eol,
  17623. start_time_str,
  17624. eol,
  17625. now_str,
  17626. eol);
  17627. context_info_length += mg_str_append(&buffer, end, block);
  17628. }
  17629. /* Terminate string */
  17630. if (append_eoobj) {
  17631. strcat(append_eoobj, eoobj);
  17632. }
  17633. context_info_length += sizeof(eoobj) - 1;
  17634. return (int)context_info_length;
  17635. #else
  17636. (void)ctx;
  17637. if ((buffer != NULL) && (buflen > 0)) {
  17638. *buffer = 0;
  17639. }
  17640. return 0;
  17641. #endif
  17642. }
  17643. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17644. /* Get connection information. It can be printed or stored by the caller.
  17645. * Return the size of available information. */
  17646. int
  17647. mg_get_connection_info(const struct mg_context *ctx,
  17648. int idx,
  17649. char *buffer,
  17650. int buflen)
  17651. {
  17652. const struct mg_connection *conn;
  17653. const struct mg_request_info *ri;
  17654. char *end, *append_eoobj = NULL, block[256];
  17655. size_t connection_info_length = 0;
  17656. int state = 0;
  17657. const char *state_str = "unknown";
  17658. #if defined(_WIN32)
  17659. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17660. #else
  17661. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17662. #endif
  17663. if ((buffer == NULL) || (buflen < 1)) {
  17664. buflen = 0;
  17665. end = buffer;
  17666. } else {
  17667. *buffer = 0;
  17668. end = buffer + buflen;
  17669. }
  17670. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17671. /* has enough space to append eoobj */
  17672. append_eoobj = buffer;
  17673. end -= sizeof(eoobj) - 1;
  17674. }
  17675. if ((ctx == NULL) || (idx < 0)) {
  17676. /* Parameter error */
  17677. return 0;
  17678. }
  17679. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  17680. /* Out of range */
  17681. return 0;
  17682. }
  17683. /* Take connection [idx]. This connection is not locked in
  17684. * any way, so some other thread might use it. */
  17685. conn = (ctx->worker_connections) + idx;
  17686. /* Initialize output string */
  17687. connection_info_length += mg_str_append(&buffer, end, "{");
  17688. /* Init variables */
  17689. ri = &(conn->request_info);
  17690. #if defined(USE_SERVER_STATS)
  17691. state = conn->conn_state;
  17692. /* State as string */
  17693. switch (state) {
  17694. case 0:
  17695. state_str = "undefined";
  17696. break;
  17697. case 1:
  17698. state_str = "not used";
  17699. break;
  17700. case 2:
  17701. state_str = "init";
  17702. break;
  17703. case 3:
  17704. state_str = "ready";
  17705. break;
  17706. case 4:
  17707. state_str = "processing";
  17708. break;
  17709. case 5:
  17710. state_str = "processed";
  17711. break;
  17712. case 6:
  17713. state_str = "to close";
  17714. break;
  17715. case 7:
  17716. state_str = "closing";
  17717. break;
  17718. case 8:
  17719. state_str = "closed";
  17720. break;
  17721. case 9:
  17722. state_str = "done";
  17723. break;
  17724. }
  17725. #endif
  17726. /* Connection info */
  17727. if ((state >= 3) && (state < 9)) {
  17728. mg_snprintf(NULL,
  17729. NULL,
  17730. block,
  17731. sizeof(block),
  17732. "%s\"connection\" : {%s"
  17733. "\"remote\" : {%s"
  17734. "\"protocol\" : \"%s\",%s"
  17735. "\"addr\" : \"%s\",%s"
  17736. "\"port\" : %u%s"
  17737. "},%s"
  17738. "\"handled_requests\" : %u%s"
  17739. "}",
  17740. eol,
  17741. eol,
  17742. eol,
  17743. get_proto_name(conn),
  17744. eol,
  17745. ri->remote_addr,
  17746. eol,
  17747. ri->remote_port,
  17748. eol,
  17749. eol,
  17750. conn->handled_requests,
  17751. eol);
  17752. connection_info_length += mg_str_append(&buffer, end, block);
  17753. }
  17754. /* Request info */
  17755. if ((state >= 4) && (state < 6)) {
  17756. mg_snprintf(NULL,
  17757. NULL,
  17758. block,
  17759. sizeof(block),
  17760. "%s%s\"request_info\" : {%s"
  17761. "\"method\" : \"%s\",%s"
  17762. "\"uri\" : \"%s\",%s"
  17763. "\"query\" : %s%s%s%s"
  17764. "}",
  17765. (connection_info_length > 1 ? "," : ""),
  17766. eol,
  17767. eol,
  17768. ri->request_method,
  17769. eol,
  17770. ri->request_uri,
  17771. eol,
  17772. ri->query_string ? "\"" : "",
  17773. ri->query_string ? ri->query_string : "null",
  17774. ri->query_string ? "\"" : "",
  17775. eol);
  17776. connection_info_length += mg_str_append(&buffer, end, block);
  17777. }
  17778. /* Execution time information */
  17779. if ((state >= 2) && (state < 9)) {
  17780. char start_time_str[64] = {0};
  17781. char close_time_str[64] = {0};
  17782. time_t start_time = conn->conn_birth_time;
  17783. time_t close_time = conn->conn_close_time;
  17784. double time_diff;
  17785. gmt_time_string(start_time_str,
  17786. sizeof(start_time_str) - 1,
  17787. &start_time);
  17788. if (close_time != 0) {
  17789. time_diff = difftime(close_time, start_time);
  17790. gmt_time_string(close_time_str,
  17791. sizeof(close_time_str) - 1,
  17792. &close_time);
  17793. } else {
  17794. time_t now = time(NULL);
  17795. time_diff = difftime(now, start_time);
  17796. close_time_str[0] = 0; /* or use "now" ? */
  17797. }
  17798. mg_snprintf(NULL,
  17799. NULL,
  17800. block,
  17801. sizeof(block),
  17802. "%s%s\"time\" : {%s"
  17803. "\"uptime\" : %.0f,%s"
  17804. "\"start\" : \"%s\",%s"
  17805. "\"closed\" : \"%s\"%s"
  17806. "}",
  17807. (connection_info_length > 1 ? "," : ""),
  17808. eol,
  17809. eol,
  17810. time_diff,
  17811. eol,
  17812. start_time_str,
  17813. eol,
  17814. close_time_str,
  17815. eol);
  17816. connection_info_length += mg_str_append(&buffer, end, block);
  17817. }
  17818. /* Remote user name */
  17819. if ((ri->remote_user) && (state < 9)) {
  17820. mg_snprintf(NULL,
  17821. NULL,
  17822. block,
  17823. sizeof(block),
  17824. "%s%s\"user\" : {%s"
  17825. "\"name\" : \"%s\",%s"
  17826. "}",
  17827. (connection_info_length > 1 ? "," : ""),
  17828. eol,
  17829. eol,
  17830. ri->remote_user,
  17831. eol);
  17832. connection_info_length += mg_str_append(&buffer, end, block);
  17833. }
  17834. /* Data block */
  17835. if (state >= 3) {
  17836. mg_snprintf(NULL,
  17837. NULL,
  17838. block,
  17839. sizeof(block),
  17840. "%s%s\"data\" : {%s"
  17841. "\"read\" : %" INT64_FMT ",%s"
  17842. "\"written\" : %" INT64_FMT "%s"
  17843. "}",
  17844. (connection_info_length > 1 ? "," : ""),
  17845. eol,
  17846. eol,
  17847. conn->consumed_content,
  17848. eol,
  17849. conn->num_bytes_sent,
  17850. eol);
  17851. connection_info_length += mg_str_append(&buffer, end, block);
  17852. }
  17853. /* State */
  17854. mg_snprintf(NULL,
  17855. NULL,
  17856. block,
  17857. sizeof(block),
  17858. "%s%s\"state\" : \"%s\"",
  17859. (connection_info_length > 1 ? "," : ""),
  17860. eol,
  17861. state_str);
  17862. connection_info_length += mg_str_append(&buffer, end, block);
  17863. /* Terminate string */
  17864. if (append_eoobj) {
  17865. strcat(append_eoobj, eoobj);
  17866. }
  17867. connection_info_length += sizeof(eoobj) - 1;
  17868. return (int)connection_info_length;
  17869. }
  17870. #endif
  17871. /* Initialize this library. This function does not need to be thread safe.
  17872. */
  17873. unsigned
  17874. mg_init_library(unsigned features)
  17875. {
  17876. #if !defined(NO_SSL)
  17877. char ebuf[128];
  17878. #endif
  17879. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17880. unsigned features_inited = features_to_init;
  17881. if (mg_init_library_called <= 0) {
  17882. /* Not initialized yet */
  17883. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17884. return 0;
  17885. }
  17886. }
  17887. mg_global_lock();
  17888. if (mg_init_library_called <= 0) {
  17889. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17890. /* Fatal error - abort start. However, this situation should
  17891. * never occur in practice. */
  17892. mg_global_unlock();
  17893. return 0;
  17894. }
  17895. #if defined(_WIN32)
  17896. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  17897. #else
  17898. pthread_mutexattr_init(&pthread_mutex_attr);
  17899. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17900. #endif
  17901. #if defined(USE_LUA)
  17902. lua_init_optional_libraries();
  17903. #endif
  17904. }
  17905. mg_global_unlock();
  17906. #if !defined(NO_SSL)
  17907. if (features_to_init & MG_FEATURES_SSL) {
  17908. if (!mg_ssl_initialized) {
  17909. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17910. mg_ssl_initialized = 1;
  17911. } else {
  17912. (void)ebuf;
  17913. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17914. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17915. }
  17916. } else {
  17917. /* ssl already initialized */
  17918. }
  17919. }
  17920. #endif
  17921. /* Start WinSock for Windows */
  17922. mg_global_lock();
  17923. if (mg_init_library_called <= 0) {
  17924. #if defined(_WIN32)
  17925. WSADATA data;
  17926. WSAStartup(MAKEWORD(2, 2), &data);
  17927. #endif /* _WIN32 */
  17928. mg_init_library_called = 1;
  17929. } else {
  17930. mg_init_library_called++;
  17931. }
  17932. mg_global_unlock();
  17933. return features_inited;
  17934. }
  17935. /* Un-initialize this library. */
  17936. unsigned
  17937. mg_exit_library(void)
  17938. {
  17939. if (mg_init_library_called <= 0) {
  17940. return 0;
  17941. }
  17942. mg_global_lock();
  17943. mg_init_library_called--;
  17944. if (mg_init_library_called == 0) {
  17945. #if defined(_WIN32)
  17946. (void)WSACleanup();
  17947. #endif /* _WIN32 */
  17948. #if !defined(NO_SSL)
  17949. if (mg_ssl_initialized) {
  17950. uninitialize_ssl();
  17951. mg_ssl_initialized = 0;
  17952. }
  17953. #endif
  17954. #if defined(_WIN32)
  17955. (void)pthread_mutex_destroy(&global_log_file_lock);
  17956. #else
  17957. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17958. #endif
  17959. (void)pthread_key_delete(sTlsKey);
  17960. #if defined(USE_LUA)
  17961. lua_exit_optional_libraries();
  17962. #endif
  17963. mg_global_unlock();
  17964. (void)pthread_mutex_destroy(&global_lock_mutex);
  17965. return 1;
  17966. }
  17967. mg_global_unlock();
  17968. return 1;
  17969. }
  17970. /* End of civetweb.c */