civetweb.c 566 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103
  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__) || defined(__sun)
  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. #if defined(OPENSSL_API_1_1)
  495. #define SSL_LIB "libssl-1_1.dll"
  496. #else
  497. #define SSL_LIB "ssleay32.dll"
  498. #endif
  499. #endif /* SSL_LIB */
  500. #if !defined(CRYPTO_LIB)
  501. #if defined(OPENSSL_API_1_1)
  502. #define CRYPTO_LIB "libcrypto-1_1.dll"
  503. #else
  504. #define CRYPTO_LIB "libeay32.dll"
  505. #endif
  506. #endif /* CRYPTO_LIB */
  507. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  508. #define O_NONBLOCK (0)
  509. #if !defined(W_OK)
  510. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  511. #endif
  512. #define _POSIX_
  513. #define INT64_FMT "I64d"
  514. #define UINT64_FMT "I64u"
  515. #define WINCDECL __cdecl
  516. #define vsnprintf_impl _vsnprintf
  517. #define access _access
  518. #define mg_sleep(x) (Sleep(x))
  519. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  520. #if !defined(popen)
  521. #define popen(x, y) (_popen(x, y))
  522. #endif
  523. #if !defined(pclose)
  524. #define pclose(x) (_pclose(x))
  525. #endif
  526. #define close(x) (_close(x))
  527. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  528. #define RTLD_LAZY (0)
  529. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  530. #define fdopen(x, y) (_fdopen((x), (y)))
  531. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  532. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  533. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  534. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  535. #define sleep(x) (Sleep((x)*1000))
  536. #define rmdir(x) (_rmdir(x))
  537. #if defined(_WIN64) || !defined(__MINGW32__)
  538. /* Only MinGW 32 bit is missing this function */
  539. #define timegm(x) (_mkgmtime(x))
  540. #else
  541. time_t timegm(struct tm *tm);
  542. #define NEED_TIMEGM
  543. #endif
  544. #if !defined(fileno)
  545. #define fileno(x) (_fileno(x))
  546. #endif /* !fileno MINGW #defines fileno */
  547. typedef struct {
  548. CRITICAL_SECTION sec; /* Immovable */
  549. } pthread_mutex_t;
  550. typedef DWORD pthread_key_t;
  551. typedef HANDLE pthread_t;
  552. typedef struct {
  553. pthread_mutex_t threadIdSec;
  554. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  555. } pthread_cond_t;
  556. #if !defined(__clockid_t_defined)
  557. typedef DWORD clockid_t;
  558. #endif
  559. #if !defined(CLOCK_MONOTONIC)
  560. #define CLOCK_MONOTONIC (1)
  561. #endif
  562. #if !defined(CLOCK_REALTIME)
  563. #define CLOCK_REALTIME (2)
  564. #endif
  565. #if !defined(CLOCK_THREAD)
  566. #define CLOCK_THREAD (3)
  567. #endif
  568. #if !defined(CLOCK_PROCESS)
  569. #define CLOCK_PROCESS (4)
  570. #endif
  571. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  572. #define _TIMESPEC_DEFINED
  573. #endif
  574. #if !defined(_TIMESPEC_DEFINED)
  575. struct timespec {
  576. time_t tv_sec; /* seconds */
  577. long tv_nsec; /* nanoseconds */
  578. };
  579. #endif
  580. #if !defined(WIN_PTHREADS_TIME_H)
  581. #define MUST_IMPLEMENT_CLOCK_GETTIME
  582. #endif
  583. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  584. #define clock_gettime mg_clock_gettime
  585. static int
  586. clock_gettime(clockid_t clk_id, struct timespec *tp)
  587. {
  588. FILETIME ft;
  589. ULARGE_INTEGER li, li2;
  590. BOOL ok = FALSE;
  591. double d;
  592. static double perfcnt_per_sec = 0.0;
  593. static BOOL initialized = FALSE;
  594. if (!initialized) {
  595. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  596. perfcnt_per_sec = 1.0 / li.QuadPart;
  597. initialized = TRUE;
  598. }
  599. if (tp) {
  600. memset(tp, 0, sizeof(*tp));
  601. if (clk_id == CLOCK_REALTIME) {
  602. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  603. GetSystemTimeAsFileTime(&ft);
  604. li.LowPart = ft.dwLowDateTime;
  605. li.HighPart = ft.dwHighDateTime;
  606. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  607. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  608. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  609. ok = TRUE;
  610. /* END: CLOCK_REALTIME */
  611. } else if (clk_id == CLOCK_MONOTONIC) {
  612. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  613. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  614. d = li.QuadPart * perfcnt_per_sec;
  615. tp->tv_sec = (time_t)d;
  616. d -= (double)tp->tv_sec;
  617. tp->tv_nsec = (long)(d * 1.0E9);
  618. ok = TRUE;
  619. /* END: CLOCK_MONOTONIC */
  620. } else if (clk_id == CLOCK_THREAD) {
  621. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  622. FILETIME t_create, t_exit, t_kernel, t_user;
  623. if (GetThreadTimes(GetCurrentThread(),
  624. &t_create,
  625. &t_exit,
  626. &t_kernel,
  627. &t_user)) {
  628. li.LowPart = t_user.dwLowDateTime;
  629. li.HighPart = t_user.dwHighDateTime;
  630. li2.LowPart = t_kernel.dwLowDateTime;
  631. li2.HighPart = t_kernel.dwHighDateTime;
  632. li.QuadPart += li2.QuadPart;
  633. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  634. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  635. ok = TRUE;
  636. }
  637. /* END: CLOCK_THREAD */
  638. } else if (clk_id == CLOCK_PROCESS) {
  639. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  640. FILETIME t_create, t_exit, t_kernel, t_user;
  641. if (GetProcessTimes(GetCurrentProcess(),
  642. &t_create,
  643. &t_exit,
  644. &t_kernel,
  645. &t_user)) {
  646. li.LowPart = t_user.dwLowDateTime;
  647. li.HighPart = t_user.dwHighDateTime;
  648. li2.LowPart = t_kernel.dwLowDateTime;
  649. li2.HighPart = t_kernel.dwHighDateTime;
  650. li.QuadPart += li2.QuadPart;
  651. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  652. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  653. ok = TRUE;
  654. }
  655. /* END: CLOCK_PROCESS */
  656. } else {
  657. /* BEGIN: unknown clock */
  658. /* ok = FALSE; already set by init */
  659. /* END: unknown clock */
  660. }
  661. }
  662. return ok ? 0 : -1;
  663. }
  664. #endif
  665. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  666. static int pthread_mutex_lock(pthread_mutex_t *);
  667. static int pthread_mutex_unlock(pthread_mutex_t *);
  668. static void path_to_unicode(const struct mg_connection *conn,
  669. const char *path,
  670. wchar_t *wbuf,
  671. size_t wbuf_len);
  672. /* All file operations need to be rewritten to solve #246. */
  673. struct mg_file;
  674. static const char *
  675. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  676. /* POSIX dirent interface */
  677. struct dirent {
  678. char d_name[PATH_MAX];
  679. };
  680. typedef struct DIR {
  681. HANDLE handle;
  682. WIN32_FIND_DATAW info;
  683. struct dirent result;
  684. } DIR;
  685. #if defined(HAVE_POLL)
  686. #define mg_pollfd pollfd
  687. #else
  688. struct mg_pollfd {
  689. SOCKET fd;
  690. short events;
  691. short revents;
  692. };
  693. #endif
  694. /* Mark required libraries */
  695. #if defined(_MSC_VER)
  696. #pragma comment(lib, "Ws2_32.lib")
  697. #endif
  698. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  699. #include <inttypes.h>
  700. typedef const void *SOCK_OPT_TYPE;
  701. #if defined(ANDROID)
  702. typedef unsigned short int in_port_t;
  703. #endif
  704. #if !defined(__ZEPHYR__)
  705. #include <arpa/inet.h>
  706. #include <ctype.h>
  707. #include <dirent.h>
  708. #include <grp.h>
  709. #include <limits.h>
  710. #include <netdb.h>
  711. #include <netinet/in.h>
  712. #include <netinet/tcp.h>
  713. #include <pthread.h>
  714. #include <pwd.h>
  715. #include <stdarg.h>
  716. #include <stddef.h>
  717. #include <stdio.h>
  718. #include <stdlib.h>
  719. #include <string.h>
  720. #include <sys/poll.h>
  721. #include <sys/socket.h>
  722. #include <sys/time.h>
  723. #include <sys/utsname.h>
  724. #include <sys/wait.h>
  725. #include <time.h>
  726. #include <unistd.h>
  727. #endif
  728. #define vsnprintf_impl vsnprintf
  729. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  730. #include <dlfcn.h>
  731. #endif
  732. #if defined(__MACH__)
  733. #define SSL_LIB "libssl.dylib"
  734. #define CRYPTO_LIB "libcrypto.dylib"
  735. #else
  736. #if !defined(SSL_LIB)
  737. #define SSL_LIB "libssl.so"
  738. #endif
  739. #if !defined(CRYPTO_LIB)
  740. #define CRYPTO_LIB "libcrypto.so"
  741. #endif
  742. #endif
  743. #if !defined(O_BINARY)
  744. #define O_BINARY (0)
  745. #endif /* O_BINARY */
  746. #define closesocket(a) (close(a))
  747. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  748. #define mg_remove(conn, x) (remove(x))
  749. #define mg_sleep(x) (usleep((x)*1000))
  750. #define mg_opendir(conn, x) (opendir(x))
  751. #define mg_closedir(x) (closedir(x))
  752. #define mg_readdir(x) (readdir(x))
  753. #define ERRNO (errno)
  754. #define INVALID_SOCKET (-1)
  755. #define INT64_FMT PRId64
  756. #define UINT64_FMT PRIu64
  757. typedef int SOCKET;
  758. #define WINCDECL
  759. #if defined(__hpux)
  760. /* HPUX 11 does not have monotonic, fall back to realtime */
  761. #if !defined(CLOCK_MONOTONIC)
  762. #define CLOCK_MONOTONIC CLOCK_REALTIME
  763. #endif
  764. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  765. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  766. * the prototypes use int* rather than socklen_t* which matches the
  767. * actual library expectation. When called with the wrong size arg
  768. * accept() returns a zero client inet addr and check_acl() always
  769. * fails. Since socklen_t is widely used below, just force replace
  770. * their typedef with int. - DTL
  771. */
  772. #define socklen_t int
  773. #endif /* hpux */
  774. #define mg_pollfd pollfd
  775. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  776. /* In case our C library is missing "timegm", provide an implementation */
  777. #if defined(NEED_TIMEGM)
  778. static inline int
  779. is_leap(int y)
  780. {
  781. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  782. }
  783. static inline int
  784. count_leap(int y)
  785. {
  786. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  787. }
  788. time_t
  789. timegm(struct tm *tm)
  790. {
  791. static const unsigned short ydays[] = {
  792. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  793. int year = tm->tm_year + 1900;
  794. int mon = tm->tm_mon;
  795. int mday = tm->tm_mday - 1;
  796. int hour = tm->tm_hour;
  797. int min = tm->tm_min;
  798. int sec = tm->tm_sec;
  799. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  800. || (mday >= ydays[mon + 1] - ydays[mon]
  801. + (mon == 1 && is_leap(year) ? 1 : 0))
  802. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  803. return -1;
  804. time_t res = year - 1970;
  805. res *= 365;
  806. res += mday;
  807. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  808. res += count_leap(year);
  809. res *= 24;
  810. res += hour;
  811. res *= 60;
  812. res += min;
  813. res *= 60;
  814. res += sec;
  815. return res;
  816. }
  817. #endif /* NEED_TIMEGM */
  818. /* va_copy should always be a macro, C99 and C++11 - DTL */
  819. #if !defined(va_copy)
  820. #define va_copy(x, y) ((x) = (y))
  821. #endif
  822. #if defined(_WIN32)
  823. /* Create substitutes for POSIX functions in Win32. */
  824. #if defined(GCC_DIAGNOSTIC)
  825. /* Show no warning in case system functions are not used. */
  826. #pragma GCC diagnostic push
  827. #pragma GCC diagnostic ignored "-Wunused-function"
  828. #endif
  829. static pthread_mutex_t global_log_file_lock;
  830. FUNCTION_MAY_BE_UNUSED
  831. static DWORD
  832. pthread_self(void)
  833. {
  834. return GetCurrentThreadId();
  835. }
  836. FUNCTION_MAY_BE_UNUSED
  837. static int
  838. pthread_key_create(
  839. pthread_key_t *key,
  840. void (*_ignored)(void *) /* destructor not supported for Windows */
  841. )
  842. {
  843. (void)_ignored;
  844. if ((key != 0)) {
  845. *key = TlsAlloc();
  846. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  847. }
  848. return -2;
  849. }
  850. FUNCTION_MAY_BE_UNUSED
  851. static int
  852. pthread_key_delete(pthread_key_t key)
  853. {
  854. return TlsFree(key) ? 0 : 1;
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static int
  858. pthread_setspecific(pthread_key_t key, void *value)
  859. {
  860. return TlsSetValue(key, value) ? 0 : 1;
  861. }
  862. FUNCTION_MAY_BE_UNUSED
  863. static void *
  864. pthread_getspecific(pthread_key_t key)
  865. {
  866. return TlsGetValue(key);
  867. }
  868. #if defined(GCC_DIAGNOSTIC)
  869. /* Enable unused function warning again */
  870. #pragma GCC diagnostic pop
  871. #endif
  872. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  873. #else
  874. static pthread_mutexattr_t pthread_mutex_attr;
  875. #endif /* _WIN32 */
  876. #if defined(_WIN32_WCE)
  877. /* Create substitutes for POSIX functions in Win32. */
  878. #if defined(GCC_DIAGNOSTIC)
  879. /* Show no warning in case system functions are not used. */
  880. #pragma GCC diagnostic push
  881. #pragma GCC diagnostic ignored "-Wunused-function"
  882. #endif
  883. FUNCTION_MAY_BE_UNUSED
  884. static time_t
  885. time(time_t *ptime)
  886. {
  887. time_t t;
  888. SYSTEMTIME st;
  889. FILETIME ft;
  890. GetSystemTime(&st);
  891. SystemTimeToFileTime(&st, &ft);
  892. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  893. if (ptime != NULL) {
  894. *ptime = t;
  895. }
  896. return t;
  897. }
  898. FUNCTION_MAY_BE_UNUSED
  899. static struct tm *
  900. localtime_s(const time_t *ptime, struct tm *ptm)
  901. {
  902. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  903. FILETIME ft, lft;
  904. SYSTEMTIME st;
  905. TIME_ZONE_INFORMATION tzinfo;
  906. if (ptm == NULL) {
  907. return NULL;
  908. }
  909. *(int64_t *)&ft = t;
  910. FileTimeToLocalFileTime(&ft, &lft);
  911. FileTimeToSystemTime(&lft, &st);
  912. ptm->tm_year = st.wYear - 1900;
  913. ptm->tm_mon = st.wMonth - 1;
  914. ptm->tm_wday = st.wDayOfWeek;
  915. ptm->tm_mday = st.wDay;
  916. ptm->tm_hour = st.wHour;
  917. ptm->tm_min = st.wMinute;
  918. ptm->tm_sec = st.wSecond;
  919. ptm->tm_yday = 0; /* hope nobody uses this */
  920. ptm->tm_isdst =
  921. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  922. return ptm;
  923. }
  924. FUNCTION_MAY_BE_UNUSED
  925. static struct tm *
  926. gmtime_s(const time_t *ptime, struct tm *ptm)
  927. {
  928. /* FIXME(lsm): fix this. */
  929. return localtime_s(ptime, ptm);
  930. }
  931. static int mg_atomic_inc(volatile int *addr);
  932. static struct tm tm_array[MAX_WORKER_THREADS];
  933. static int tm_index = 0;
  934. FUNCTION_MAY_BE_UNUSED
  935. static struct tm *
  936. localtime(const time_t *ptime)
  937. {
  938. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  939. return localtime_s(ptime, tm_array + i);
  940. }
  941. FUNCTION_MAY_BE_UNUSED
  942. static struct tm *
  943. gmtime(const time_t *ptime)
  944. {
  945. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  946. return gmtime_s(ptime, tm_array + i);
  947. }
  948. FUNCTION_MAY_BE_UNUSED
  949. static size_t
  950. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  951. {
  952. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  953. * for WinCE"); */
  954. return 0;
  955. }
  956. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  957. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  958. #define remove(f) mg_remove(NULL, f)
  959. FUNCTION_MAY_BE_UNUSED
  960. static int
  961. rename(const char *a, const char *b)
  962. {
  963. wchar_t wa[W_PATH_MAX];
  964. wchar_t wb[W_PATH_MAX];
  965. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  966. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  967. return MoveFileW(wa, wb) ? 0 : -1;
  968. }
  969. struct stat {
  970. int64_t st_size;
  971. time_t st_mtime;
  972. };
  973. FUNCTION_MAY_BE_UNUSED
  974. static int
  975. stat(const char *name, struct stat *st)
  976. {
  977. wchar_t wbuf[W_PATH_MAX];
  978. WIN32_FILE_ATTRIBUTE_DATA attr;
  979. time_t creation_time, write_time;
  980. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  981. memset(&attr, 0, sizeof(attr));
  982. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  983. st->st_size =
  984. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  985. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  986. attr.ftLastWriteTime.dwHighDateTime);
  987. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  988. attr.ftCreationTime.dwHighDateTime);
  989. if (creation_time > write_time) {
  990. st->st_mtime = creation_time;
  991. } else {
  992. st->st_mtime = write_time;
  993. }
  994. return 0;
  995. }
  996. #define access(x, a) 1 /* not required anyway */
  997. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  998. /* Values from errno.h in Windows SDK (Visual Studio). */
  999. #define EEXIST 17
  1000. #define EACCES 13
  1001. #define ENOENT 2
  1002. #if defined(GCC_DIAGNOSTIC)
  1003. /* Enable unused function warning again */
  1004. #pragma GCC diagnostic pop
  1005. #endif
  1006. #endif /* defined(_WIN32_WCE) */
  1007. #if defined(GCC_DIAGNOSTIC)
  1008. /* Show no warning in case system functions are not used. */
  1009. #pragma GCC diagnostic push
  1010. #pragma GCC diagnostic ignored "-Wunused-function"
  1011. #endif /* defined(GCC_DIAGNOSTIC) */
  1012. #if defined(__clang__)
  1013. /* Show no warning in case system functions are not used. */
  1014. #pragma clang diagnostic push
  1015. #pragma clang diagnostic ignored "-Wunused-function"
  1016. #endif
  1017. static pthread_mutex_t global_lock_mutex;
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static void
  1020. mg_global_lock(void)
  1021. {
  1022. (void)pthread_mutex_lock(&global_lock_mutex);
  1023. }
  1024. FUNCTION_MAY_BE_UNUSED
  1025. static void
  1026. mg_global_unlock(void)
  1027. {
  1028. (void)pthread_mutex_unlock(&global_lock_mutex);
  1029. }
  1030. FUNCTION_MAY_BE_UNUSED
  1031. static int
  1032. mg_atomic_inc(volatile int *addr)
  1033. {
  1034. int ret;
  1035. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1036. /* Depending on the SDK, this function uses either
  1037. * (volatile unsigned int *) or (volatile LONG *),
  1038. * so whatever you use, the other SDK is likely to raise a warning. */
  1039. ret = InterlockedIncrement((volatile long *)addr);
  1040. #elif defined(__GNUC__) \
  1041. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1042. && !defined(NO_ATOMICS)
  1043. ret = __sync_add_and_fetch(addr, 1);
  1044. #else
  1045. mg_global_lock();
  1046. ret = (++(*addr));
  1047. mg_global_unlock();
  1048. #endif
  1049. return ret;
  1050. }
  1051. FUNCTION_MAY_BE_UNUSED
  1052. static int
  1053. mg_atomic_dec(volatile int *addr)
  1054. {
  1055. int ret;
  1056. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1057. /* Depending on the SDK, this function uses either
  1058. * (volatile unsigned int *) or (volatile LONG *),
  1059. * so whatever you use, the other SDK is likely to raise a warning. */
  1060. ret = InterlockedDecrement((volatile long *)addr);
  1061. #elif defined(__GNUC__) \
  1062. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1063. && !defined(NO_ATOMICS)
  1064. ret = __sync_sub_and_fetch(addr, 1);
  1065. #else
  1066. mg_global_lock();
  1067. ret = (--(*addr));
  1068. mg_global_unlock();
  1069. #endif
  1070. return ret;
  1071. }
  1072. #if defined(USE_SERVER_STATS)
  1073. static int64_t
  1074. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1075. {
  1076. int64_t ret;
  1077. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1078. ret = InterlockedAdd64(addr, value);
  1079. #elif defined(__GNUC__) \
  1080. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1081. && !defined(NO_ATOMICS)
  1082. ret = __sync_add_and_fetch(addr, value);
  1083. #else
  1084. mg_global_lock();
  1085. *addr += value;
  1086. ret = (*addr);
  1087. mg_global_unlock();
  1088. #endif
  1089. return ret;
  1090. }
  1091. #endif
  1092. #if defined(GCC_DIAGNOSTIC)
  1093. /* Show no warning in case system functions are not used. */
  1094. #pragma GCC diagnostic pop
  1095. #endif /* defined(GCC_DIAGNOSTIC) */
  1096. #if defined(__clang__)
  1097. /* Show no warning in case system functions are not used. */
  1098. #pragma clang diagnostic pop
  1099. #endif
  1100. #if defined(USE_SERVER_STATS)
  1101. struct mg_memory_stat {
  1102. volatile int64_t totalMemUsed;
  1103. volatile int64_t maxMemUsed;
  1104. volatile int blockCount;
  1105. };
  1106. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1107. static void *
  1108. mg_malloc_ex(size_t size,
  1109. struct mg_context *ctx,
  1110. const char *file,
  1111. unsigned line)
  1112. {
  1113. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1114. void *memory = 0;
  1115. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1116. #if defined(MEMORY_DEBUGGING)
  1117. char mallocStr[256];
  1118. #else
  1119. (void)file;
  1120. (void)line;
  1121. #endif
  1122. if (data) {
  1123. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1124. if (mmem > mstat->maxMemUsed) {
  1125. /* could use atomic compare exchange, but this
  1126. * seems overkill for statistics data */
  1127. mstat->maxMemUsed = mmem;
  1128. }
  1129. mg_atomic_inc(&mstat->blockCount);
  1130. ((uintptr_t *)data)[0] = size;
  1131. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1132. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1133. }
  1134. #if defined(MEMORY_DEBUGGING)
  1135. sprintf(mallocStr,
  1136. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1137. memory,
  1138. (unsigned long)size,
  1139. (unsigned long)mstat->totalMemUsed,
  1140. (unsigned long)mstat->blockCount,
  1141. file,
  1142. line);
  1143. #if defined(_WIN32)
  1144. OutputDebugStringA(mallocStr);
  1145. #else
  1146. DEBUG_TRACE("%s", mallocStr);
  1147. #endif
  1148. #endif
  1149. return memory;
  1150. }
  1151. static void *
  1152. mg_calloc_ex(size_t count,
  1153. size_t size,
  1154. struct mg_context *ctx,
  1155. const char *file,
  1156. unsigned line)
  1157. {
  1158. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1159. if (data) {
  1160. memset(data, 0, size * count);
  1161. }
  1162. return data;
  1163. }
  1164. static void
  1165. mg_free_ex(void *memory, const char *file, unsigned line)
  1166. {
  1167. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1168. #if defined(MEMORY_DEBUGGING)
  1169. char mallocStr[256];
  1170. #else
  1171. (void)file;
  1172. (void)line;
  1173. #endif
  1174. if (memory) {
  1175. uintptr_t size = ((uintptr_t *)data)[0];
  1176. struct mg_memory_stat *mstat =
  1177. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1178. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1179. mg_atomic_dec(&mstat->blockCount);
  1180. #if defined(MEMORY_DEBUGGING)
  1181. sprintf(mallocStr,
  1182. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1183. memory,
  1184. (unsigned long)size,
  1185. (unsigned long)mstat->totalMemUsed,
  1186. (unsigned long)mstat->blockCount,
  1187. file,
  1188. line);
  1189. #if defined(_WIN32)
  1190. OutputDebugStringA(mallocStr);
  1191. #else
  1192. DEBUG_TRACE("%s", mallocStr);
  1193. #endif
  1194. #endif
  1195. free(data);
  1196. }
  1197. }
  1198. static void *
  1199. mg_realloc_ex(void *memory,
  1200. size_t newsize,
  1201. struct mg_context *ctx,
  1202. const char *file,
  1203. unsigned line)
  1204. {
  1205. void *data;
  1206. void *_realloc;
  1207. uintptr_t oldsize;
  1208. #if defined(MEMORY_DEBUGGING)
  1209. char mallocStr[256];
  1210. #else
  1211. (void)file;
  1212. (void)line;
  1213. #endif
  1214. if (newsize) {
  1215. if (memory) {
  1216. /* Reallocate existing block */
  1217. struct mg_memory_stat *mstat;
  1218. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1219. oldsize = ((uintptr_t *)data)[0];
  1220. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1221. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1222. if (_realloc) {
  1223. data = _realloc;
  1224. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1225. #if defined(MEMORY_DEBUGGING)
  1226. sprintf(mallocStr,
  1227. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1228. memory,
  1229. (unsigned long)oldsize,
  1230. (unsigned long)mstat->totalMemUsed,
  1231. (unsigned long)mstat->blockCount,
  1232. file,
  1233. line);
  1234. #if defined(_WIN32)
  1235. OutputDebugStringA(mallocStr);
  1236. #else
  1237. DEBUG_TRACE("%s", mallocStr);
  1238. #endif
  1239. #endif
  1240. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1241. #if defined(MEMORY_DEBUGGING)
  1242. sprintf(mallocStr,
  1243. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1244. memory,
  1245. (unsigned long)newsize,
  1246. (unsigned long)mstat->totalMemUsed,
  1247. (unsigned long)mstat->blockCount,
  1248. file,
  1249. line);
  1250. #if defined(_WIN32)
  1251. OutputDebugStringA(mallocStr);
  1252. #else
  1253. DEBUG_TRACE("%s", mallocStr);
  1254. #endif
  1255. #endif
  1256. *(uintptr_t *)data = newsize;
  1257. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1258. } else {
  1259. #if defined(MEMORY_DEBUGGING)
  1260. #if defined(_WIN32)
  1261. OutputDebugStringA("MEM: realloc failed\n");
  1262. #else
  1263. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1264. #endif
  1265. #endif
  1266. return _realloc;
  1267. }
  1268. } else {
  1269. /* Allocate new block */
  1270. data = mg_malloc_ex(newsize, ctx, file, line);
  1271. }
  1272. } else {
  1273. /* Free existing block */
  1274. data = 0;
  1275. mg_free_ex(memory, file, line);
  1276. }
  1277. return data;
  1278. }
  1279. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1280. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1281. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1282. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1283. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1284. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1285. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1286. #else /* USE_SERVER_STATS */
  1287. static __inline void *
  1288. mg_malloc(size_t a)
  1289. {
  1290. return malloc(a);
  1291. }
  1292. static __inline void *
  1293. mg_calloc(size_t a, size_t b)
  1294. {
  1295. return calloc(a, b);
  1296. }
  1297. static __inline void *
  1298. mg_realloc(void *a, size_t b)
  1299. {
  1300. return realloc(a, b);
  1301. }
  1302. static __inline void
  1303. mg_free(void *a)
  1304. {
  1305. free(a);
  1306. }
  1307. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1308. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1309. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1310. #define mg_free_ctx(a, c) mg_free(a)
  1311. #endif /* USE_SERVER_STATS */
  1312. static void mg_vsnprintf(const struct mg_connection *conn,
  1313. int *truncated,
  1314. char *buf,
  1315. size_t buflen,
  1316. const char *fmt,
  1317. va_list ap);
  1318. static void mg_snprintf(const struct mg_connection *conn,
  1319. int *truncated,
  1320. char *buf,
  1321. size_t buflen,
  1322. PRINTF_FORMAT_STRING(const char *fmt),
  1323. ...) PRINTF_ARGS(5, 6);
  1324. /* This following lines are just meant as a reminder to use the mg-functions
  1325. * for memory management */
  1326. #if defined(malloc)
  1327. #undef malloc
  1328. #endif
  1329. #if defined(calloc)
  1330. #undef calloc
  1331. #endif
  1332. #if defined(realloc)
  1333. #undef realloc
  1334. #endif
  1335. #if defined(free)
  1336. #undef free
  1337. #endif
  1338. #if defined(snprintf)
  1339. #undef snprintf
  1340. #endif
  1341. #if defined(vsnprintf)
  1342. #undef vsnprintf
  1343. #endif
  1344. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1345. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1346. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1347. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1348. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1349. #if defined(_WIN32)
  1350. /* vsnprintf must not be used in any system,
  1351. * but this define only works well for Windows. */
  1352. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1353. #endif
  1354. /* mg_init_library counter */
  1355. static int mg_init_library_called = 0;
  1356. #if !defined(NO_SSL)
  1357. static int mg_ssl_initialized = 0;
  1358. #endif
  1359. static pthread_key_t sTlsKey; /* Thread local storage index */
  1360. static int thread_idx_max = 0;
  1361. #if defined(MG_LEGACY_INTERFACE)
  1362. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1363. #endif
  1364. struct mg_workerTLS {
  1365. int is_master;
  1366. unsigned long thread_idx;
  1367. void *user_ptr;
  1368. #if defined(_WIN32)
  1369. HANDLE pthread_cond_helper_mutex;
  1370. struct mg_workerTLS *next_waiting_thread;
  1371. #endif
  1372. const char *alpn_proto;
  1373. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1374. char txtbuf[4];
  1375. #endif
  1376. };
  1377. #if defined(GCC_DIAGNOSTIC)
  1378. /* Show no warning in case system functions are not used. */
  1379. #pragma GCC diagnostic push
  1380. #pragma GCC diagnostic ignored "-Wunused-function"
  1381. #endif /* defined(GCC_DIAGNOSTIC) */
  1382. #if defined(__clang__)
  1383. /* Show no warning in case system functions are not used. */
  1384. #pragma clang diagnostic push
  1385. #pragma clang diagnostic ignored "-Wunused-function"
  1386. #endif
  1387. /* Get a unique thread ID as unsigned long, independent from the data type
  1388. * of thread IDs defined by the operating system API.
  1389. * If two calls to mg_current_thread_id return the same value, they calls
  1390. * are done from the same thread. If they return different values, they are
  1391. * done from different threads. (Provided this function is used in the same
  1392. * process context and threads are not repeatedly created and deleted, but
  1393. * CivetWeb does not do that).
  1394. * This function must match the signature required for SSL id callbacks:
  1395. * CRYPTO_set_id_callback
  1396. */
  1397. FUNCTION_MAY_BE_UNUSED
  1398. static unsigned long
  1399. mg_current_thread_id(void)
  1400. {
  1401. #if defined(_WIN32)
  1402. return GetCurrentThreadId();
  1403. #else
  1404. #if defined(__clang__)
  1405. #pragma clang diagnostic push
  1406. #pragma clang diagnostic ignored "-Wunreachable-code"
  1407. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1408. * or not, so one of the two conditions will be unreachable by construction.
  1409. * Unfortunately the C standard does not define a way to check this at
  1410. * compile time, since the #if preprocessor conditions can not use the sizeof
  1411. * operator as an argument. */
  1412. #endif
  1413. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1414. /* This is the problematic case for CRYPTO_set_id_callback:
  1415. * The OS pthread_t can not be cast to unsigned long. */
  1416. struct mg_workerTLS *tls =
  1417. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1418. if (tls == NULL) {
  1419. /* SSL called from an unknown thread: Create some thread index.
  1420. */
  1421. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1422. tls->is_master = -2; /* -2 means "3rd party thread" */
  1423. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1424. pthread_setspecific(sTlsKey, tls);
  1425. }
  1426. return tls->thread_idx;
  1427. } else {
  1428. /* pthread_t may be any data type, so a simple cast to unsigned long
  1429. * can rise a warning/error, depending on the platform.
  1430. * Here memcpy is used as an anything-to-anything cast. */
  1431. unsigned long ret = 0;
  1432. pthread_t t = pthread_self();
  1433. memcpy(&ret, &t, sizeof(pthread_t));
  1434. return ret;
  1435. }
  1436. #if defined(__clang__)
  1437. #pragma clang diagnostic pop
  1438. #endif
  1439. #endif
  1440. }
  1441. FUNCTION_MAY_BE_UNUSED
  1442. static uint64_t
  1443. mg_get_current_time_ns(void)
  1444. {
  1445. struct timespec tsnow;
  1446. clock_gettime(CLOCK_REALTIME, &tsnow);
  1447. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1448. }
  1449. #if defined(GCC_DIAGNOSTIC)
  1450. /* Show no warning in case system functions are not used. */
  1451. #pragma GCC diagnostic pop
  1452. #endif /* defined(GCC_DIAGNOSTIC) */
  1453. #if defined(__clang__)
  1454. /* Show no warning in case system functions are not used. */
  1455. #pragma clang diagnostic pop
  1456. #endif
  1457. #if defined(NEED_DEBUG_TRACE_FUNC)
  1458. static void
  1459. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1460. {
  1461. va_list args;
  1462. uint64_t nsnow;
  1463. static uint64_t nslast;
  1464. struct timespec tsnow;
  1465. /* Get some operating system independent thread id */
  1466. unsigned long thread_id = mg_current_thread_id();
  1467. clock_gettime(CLOCK_REALTIME, &tsnow);
  1468. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1469. + ((uint64_t)tsnow.tv_nsec);
  1470. if (!nslast) {
  1471. nslast = nsnow;
  1472. }
  1473. flockfile(DEBUG_TRACE_STREAM);
  1474. fprintf(DEBUG_TRACE_STREAM,
  1475. "*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1476. (unsigned long)tsnow.tv_sec,
  1477. (unsigned long)tsnow.tv_nsec,
  1478. nsnow - nslast,
  1479. thread_id,
  1480. func,
  1481. line);
  1482. va_start(args, fmt);
  1483. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1484. va_end(args);
  1485. putc('\n', DEBUG_TRACE_STREAM);
  1486. fflush(DEBUG_TRACE_STREAM);
  1487. funlockfile(DEBUG_TRACE_STREAM);
  1488. nslast = nsnow;
  1489. }
  1490. #endif /* NEED_DEBUG_TRACE_FUNC */
  1491. #define MD5_STATIC static
  1492. #include "md5.inl"
  1493. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1494. #if defined(NO_SOCKLEN_T)
  1495. typedef int socklen_t;
  1496. #endif /* NO_SOCKLEN_T */
  1497. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1498. #if !defined(MSG_NOSIGNAL)
  1499. #define MSG_NOSIGNAL (0)
  1500. #endif
  1501. #if defined(NO_SSL)
  1502. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1503. typedef struct SSL_CTX SSL_CTX;
  1504. #else
  1505. #if defined(NO_SSL_DL)
  1506. #include <openssl/bn.h>
  1507. #include <openssl/conf.h>
  1508. #include <openssl/crypto.h>
  1509. #include <openssl/dh.h>
  1510. #include <openssl/engine.h>
  1511. #include <openssl/err.h>
  1512. #include <openssl/opensslv.h>
  1513. #include <openssl/pem.h>
  1514. #include <openssl/ssl.h>
  1515. #include <openssl/tls1.h>
  1516. #include <openssl/x509.h>
  1517. #if defined(WOLFSSL_VERSION)
  1518. /* Additional defines for WolfSSL, see
  1519. * https://github.com/civetweb/civetweb/issues/583 */
  1520. #include "wolfssl_extras.inl"
  1521. #endif
  1522. #if defined(OPENSSL_IS_BORINGSSL)
  1523. /* From boringssl/src/include/openssl/mem.h:
  1524. *
  1525. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1526. * However, that was written in a time before Valgrind and ASAN. Since we now
  1527. * have those tools, the OpenSSL allocation functions are simply macros around
  1528. * the standard memory functions.
  1529. *
  1530. * #define OPENSSL_free free */
  1531. #define free free
  1532. // disable for boringssl
  1533. #define CONF_modules_unload(a) ((void)0)
  1534. #define ENGINE_cleanup() ((void)0)
  1535. #endif
  1536. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1537. /* If OpenSSL headers are included, automatically select the API version */
  1538. #if !defined(OPENSSL_API_1_1)
  1539. #define OPENSSL_API_1_1
  1540. #endif
  1541. #define OPENSSL_REMOVE_THREAD_STATE()
  1542. #else
  1543. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1544. #endif
  1545. #else
  1546. /* SSL loaded dynamically from DLL.
  1547. * I put the prototypes here to be independent from OpenSSL source
  1548. * installation. */
  1549. typedef struct ssl_st SSL;
  1550. typedef struct ssl_method_st SSL_METHOD;
  1551. typedef struct ssl_ctx_st SSL_CTX;
  1552. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1553. typedef struct x509_name X509_NAME;
  1554. typedef struct asn1_integer ASN1_INTEGER;
  1555. typedef struct bignum BIGNUM;
  1556. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1557. typedef struct evp_md EVP_MD;
  1558. typedef struct x509 X509;
  1559. #define SSL_CTRL_OPTIONS (32)
  1560. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1561. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1562. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1563. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1564. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1565. #define SSL_VERIFY_NONE (0)
  1566. #define SSL_VERIFY_PEER (1)
  1567. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1568. #define SSL_VERIFY_CLIENT_ONCE (4)
  1569. #define SSL_OP_ALL (0x80000BFFul)
  1570. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1571. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1572. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1573. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1574. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1575. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1576. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1577. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1578. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1579. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1580. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1581. #define SSL_CB_HANDSHAKE_START (0x10)
  1582. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1583. #define SSL_ERROR_NONE (0)
  1584. #define SSL_ERROR_SSL (1)
  1585. #define SSL_ERROR_WANT_READ (2)
  1586. #define SSL_ERROR_WANT_WRITE (3)
  1587. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1588. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1589. #define SSL_ERROR_ZERO_RETURN (6)
  1590. #define SSL_ERROR_WANT_CONNECT (7)
  1591. #define SSL_ERROR_WANT_ACCEPT (8)
  1592. #define TLSEXT_TYPE_server_name (0)
  1593. #define TLSEXT_NAMETYPE_host_name (0)
  1594. #define SSL_TLSEXT_ERR_OK (0)
  1595. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1596. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1597. #define SSL_TLSEXT_ERR_NOACK (3)
  1598. enum ssl_func_category {
  1599. TLS_Mandatory, /* required for HTTPS */
  1600. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1601. TLS_END_OF_LIST
  1602. };
  1603. /* Check if all TLS functions/features are available */
  1604. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1605. struct ssl_func {
  1606. const char *name; /* SSL function name */
  1607. union {
  1608. enum ssl_func_category required; /* Mandatory or optional */
  1609. void (*ptr)(void); /* Function pointer */
  1610. };
  1611. };
  1612. #if defined(OPENSSL_API_1_1)
  1613. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1614. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1615. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1616. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1617. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1618. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1619. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1620. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1621. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1622. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1623. #define OPENSSL_init_ssl \
  1624. (*(int (*)(uint64_t opts, \
  1625. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1626. .ptr)
  1627. #define SSL_CTX_use_PrivateKey_file \
  1628. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1629. #define SSL_CTX_use_certificate_file \
  1630. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1631. #define SSL_CTX_set_default_passwd_cb \
  1632. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1633. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1634. #define SSL_CTX_use_certificate_chain_file \
  1635. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1636. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1637. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1638. #define SSL_CTX_set_verify \
  1639. (*(void (*)(SSL_CTX *, \
  1640. int, \
  1641. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1642. .ptr)
  1643. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1644. #define SSL_CTX_load_verify_locations \
  1645. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1646. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1647. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1648. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1649. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1650. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1651. #define SSL_CIPHER_get_name \
  1652. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1653. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1654. #define SSL_CTX_set_session_id_context \
  1655. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1656. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1657. #define SSL_CTX_set_cipher_list \
  1658. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1659. #define SSL_CTX_set_options \
  1660. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1661. #define SSL_CTX_set_info_callback \
  1662. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1663. ssl_sw[32] \
  1664. .ptr)
  1665. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1666. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1667. #define SSL_CTX_callback_ctrl \
  1668. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1669. #define SSL_get_servername \
  1670. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1671. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1672. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1673. #define SSL_CTX_set_alpn_protos \
  1674. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1675. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1676. const unsigned char **out,
  1677. unsigned char *outlen,
  1678. const unsigned char *in,
  1679. unsigned int inlen,
  1680. void *arg);
  1681. #define SSL_CTX_set_alpn_select_cb \
  1682. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1683. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1684. const unsigned char **out,
  1685. unsigned int *outlen,
  1686. void *arg);
  1687. #define SSL_CTX_set_next_protos_advertised_cb \
  1688. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1689. .ptr)
  1690. #define SSL_CTX_clear_options(ctx, op) \
  1691. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1692. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1693. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1694. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1695. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1696. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1697. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1698. SSL_CTX_callback_ctrl(ctx, \
  1699. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1700. (void (*)(void))cb)
  1701. #define SSL_set_tlsext_host_name(ctx, arg) \
  1702. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1703. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1704. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1705. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1706. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1707. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1708. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1709. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1710. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1711. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1712. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1713. #define X509_NAME_oneline \
  1714. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1715. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1716. #define EVP_get_digestbyname \
  1717. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1718. #define EVP_Digest \
  1719. (*(int (*)( \
  1720. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1721. crypto_sw[9] \
  1722. .ptr)
  1723. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1724. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1725. #define ASN1_INTEGER_to_BN \
  1726. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1727. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1728. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1729. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1730. #define OPENSSL_free(a) CRYPTO_free(a)
  1731. #define OPENSSL_REMOVE_THREAD_STATE()
  1732. /* init_ssl_ctx() function updates this array.
  1733. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1734. * of respective functions. The macros above (like SSL_connect()) are really
  1735. * just calling these functions indirectly via the pointer. */
  1736. static struct ssl_func ssl_sw[] = {
  1737. {"SSL_free", {TLS_Mandatory}},
  1738. {"SSL_accept", {TLS_Mandatory}},
  1739. {"SSL_connect", {TLS_Mandatory}},
  1740. {"SSL_read", {TLS_Mandatory}},
  1741. {"SSL_write", {TLS_Mandatory}},
  1742. {"SSL_get_error", {TLS_Mandatory}},
  1743. {"SSL_set_fd", {TLS_Mandatory}},
  1744. {"SSL_new", {TLS_Mandatory}},
  1745. {"SSL_CTX_new", {TLS_Mandatory}},
  1746. {"TLS_server_method", {TLS_Mandatory}},
  1747. {"OPENSSL_init_ssl", {TLS_Mandatory}},
  1748. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1749. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1750. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1751. {"SSL_CTX_free", {TLS_Mandatory}},
  1752. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1753. {"TLS_client_method", {TLS_Mandatory}},
  1754. {"SSL_pending", {TLS_Mandatory}},
  1755. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1756. {"SSL_shutdown", {TLS_Mandatory}},
  1757. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1758. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1759. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1760. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1761. {"SSL_get_version", {TLS_Mandatory}},
  1762. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1763. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1764. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1765. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1766. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1767. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1768. {"SSL_CTX_set_options", {TLS_Mandatory}},
  1769. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1770. {"SSL_get_ex_data", {TLS_Mandatory}},
  1771. {"SSL_set_ex_data", {TLS_Mandatory}},
  1772. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1773. {"SSL_get_servername", {TLS_Mandatory}},
  1774. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1775. {"SSL_ctrl", {TLS_Mandatory}},
  1776. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1777. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1778. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1779. {NULL, {TLS_END_OF_LIST}}};
  1780. /* Similar array as ssl_sw. These functions could be located in different
  1781. * lib. */
  1782. static struct ssl_func crypto_sw[] = {{"ERR_get_error", {TLS_Mandatory}},
  1783. {"ERR_error_string", {TLS_Mandatory}},
  1784. {"CONF_modules_unload", {TLS_Mandatory}},
  1785. {"X509_free", {TLS_Mandatory}},
  1786. {"X509_get_subject_name",
  1787. {TLS_Mandatory}},
  1788. {"X509_get_issuer_name", {TLS_Mandatory}},
  1789. {"X509_NAME_oneline", {TLS_Mandatory}},
  1790. {"X509_get_serialNumber",
  1791. {TLS_Mandatory}},
  1792. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1793. {"EVP_Digest", {TLS_Mandatory}},
  1794. {"i2d_X509", {TLS_Mandatory}},
  1795. {"BN_bn2hex", {TLS_Mandatory}},
  1796. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1797. {"BN_free", {TLS_Mandatory}},
  1798. {"CRYPTO_free", {TLS_Mandatory}},
  1799. {"ERR_clear_error", {TLS_Mandatory}},
  1800. {NULL, {TLS_END_OF_LIST}}};
  1801. #else
  1802. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1803. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1804. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1805. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1806. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1807. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1808. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1809. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1810. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1811. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1812. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1813. #define SSL_CTX_use_PrivateKey_file \
  1814. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1815. #define SSL_CTX_use_certificate_file \
  1816. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1817. #define SSL_CTX_set_default_passwd_cb \
  1818. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1819. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1820. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1821. #define SSL_CTX_use_certificate_chain_file \
  1822. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1823. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1824. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1825. #define SSL_CTX_set_verify \
  1826. (*(void (*)(SSL_CTX *, \
  1827. int, \
  1828. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1829. .ptr)
  1830. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1831. #define SSL_CTX_load_verify_locations \
  1832. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1833. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1834. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1835. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1836. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1837. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1838. #define SSL_CIPHER_get_name \
  1839. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1840. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1841. #define SSL_CTX_set_session_id_context \
  1842. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1843. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1844. #define SSL_CTX_set_cipher_list \
  1845. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1846. #define SSL_CTX_set_info_callback \
  1847. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1848. .ptr)
  1849. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1850. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1851. #define SSL_CTX_callback_ctrl \
  1852. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1853. #define SSL_get_servername \
  1854. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1855. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1856. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1857. #define SSL_CTX_set_alpn_protos \
  1858. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1859. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1860. const unsigned char **out,
  1861. unsigned char *outlen,
  1862. const unsigned char *in,
  1863. unsigned int inlen,
  1864. void *arg);
  1865. #define SSL_CTX_set_alpn_select_cb \
  1866. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1867. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1868. const unsigned char **out,
  1869. unsigned int *outlen,
  1870. void *arg);
  1871. #define SSL_CTX_set_next_protos_advertised_cb \
  1872. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1873. .ptr)
  1874. #define SSL_CTX_set_options(ctx, op) \
  1875. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1876. #define SSL_CTX_clear_options(ctx, op) \
  1877. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1878. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1879. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1880. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1881. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1882. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1883. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1884. SSL_CTX_callback_ctrl(ctx, \
  1885. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1886. (void (*)(void))cb)
  1887. #define SSL_set_tlsext_host_name(ctx, arg) \
  1888. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1889. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1890. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1891. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1892. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1893. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1894. #define CRYPTO_set_locking_callback \
  1895. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1896. #define CRYPTO_set_id_callback \
  1897. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1898. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1899. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1900. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1901. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1902. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1903. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1904. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1905. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1906. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1907. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1908. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1909. #define X509_NAME_oneline \
  1910. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1911. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1912. #define i2c_ASN1_INTEGER \
  1913. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1914. #define EVP_get_digestbyname \
  1915. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1916. #define EVP_Digest \
  1917. (*(int (*)( \
  1918. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1919. crypto_sw[18] \
  1920. .ptr)
  1921. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1922. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1923. #define ASN1_INTEGER_to_BN \
  1924. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1925. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1926. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1927. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1928. #define OPENSSL_free(a) CRYPTO_free(a)
  1929. /* use here ERR_remove_state,
  1930. * while on some platforms function is not included into library due to
  1931. * deprication */
  1932. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1933. /* init_ssl_ctx() function updates this array.
  1934. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1935. * of respective functions. The macros above (like SSL_connect()) are really
  1936. * just calling these functions indirectly via the pointer. */
  1937. static struct ssl_func ssl_sw[] = {
  1938. {"SSL_free", {TLS_Mandatory}},
  1939. {"SSL_accept", {TLS_Mandatory}},
  1940. {"SSL_connect", {TLS_Mandatory}},
  1941. {"SSL_read", {TLS_Mandatory}},
  1942. {"SSL_write", {TLS_Mandatory}},
  1943. {"SSL_get_error", {TLS_Mandatory}},
  1944. {"SSL_set_fd", {TLS_Mandatory}},
  1945. {"SSL_new", {TLS_Mandatory}},
  1946. {"SSL_CTX_new", {TLS_Mandatory}},
  1947. {"SSLv23_server_method", {TLS_Mandatory}},
  1948. {"SSL_library_init", {TLS_Mandatory}},
  1949. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1950. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1951. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1952. {"SSL_CTX_free", {TLS_Mandatory}},
  1953. {"SSL_load_error_strings", {TLS_Mandatory}},
  1954. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1955. {"SSLv23_client_method", {TLS_Mandatory}},
  1956. {"SSL_pending", {TLS_Mandatory}},
  1957. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1958. {"SSL_shutdown", {TLS_Mandatory}},
  1959. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1960. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1961. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1962. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1963. {"SSL_get_version", {TLS_Mandatory}},
  1964. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1965. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1966. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1967. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1968. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1969. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1970. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1971. {"SSL_get_ex_data", {TLS_Mandatory}},
  1972. {"SSL_set_ex_data", {TLS_Mandatory}},
  1973. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1974. {"SSL_get_servername", {TLS_Mandatory}},
  1975. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1976. {"SSL_ctrl", {TLS_Mandatory}},
  1977. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1978. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1979. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1980. {NULL, {TLS_END_OF_LIST}}};
  1981. /* Similar array as ssl_sw. These functions could be located in different
  1982. * lib. */
  1983. static struct ssl_func crypto_sw[] = {
  1984. {"CRYPTO_num_locks", {TLS_Mandatory}},
  1985. {"CRYPTO_set_locking_callback", {TLS_Mandatory}},
  1986. {"CRYPTO_set_id_callback", {TLS_Mandatory}},
  1987. {"ERR_get_error", {TLS_Mandatory}},
  1988. {"ERR_error_string", {TLS_Mandatory}},
  1989. {"ERR_remove_state", {TLS_Mandatory}},
  1990. {"ERR_free_strings", {TLS_Mandatory}},
  1991. {"ENGINE_cleanup", {TLS_Mandatory}},
  1992. {"CONF_modules_unload", {TLS_Mandatory}},
  1993. {"CRYPTO_cleanup_all_ex_data", {TLS_Mandatory}},
  1994. {"EVP_cleanup", {TLS_Mandatory}},
  1995. {"X509_free", {TLS_Mandatory}},
  1996. {"X509_get_subject_name", {TLS_Mandatory}},
  1997. {"X509_get_issuer_name", {TLS_Mandatory}},
  1998. {"X509_NAME_oneline", {TLS_Mandatory}},
  1999. {"X509_get_serialNumber", {TLS_Mandatory}},
  2000. {"i2c_ASN1_INTEGER", {TLS_Mandatory}},
  2001. {"EVP_get_digestbyname", {TLS_Mandatory}},
  2002. {"EVP_Digest", {TLS_Mandatory}},
  2003. {"i2d_X509", {TLS_Mandatory}},
  2004. {"BN_bn2hex", {TLS_Mandatory}},
  2005. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  2006. {"BN_free", {TLS_Mandatory}},
  2007. {"CRYPTO_free", {TLS_Mandatory}},
  2008. {"ERR_clear_error", {TLS_Mandatory}},
  2009. {NULL, {TLS_END_OF_LIST}}};
  2010. #endif /* OPENSSL_API_1_1 */
  2011. #endif /* NO_SSL_DL */
  2012. #endif /* NO_SSL */
  2013. #if !defined(NO_CACHING)
  2014. static const char month_names[][4] = {"Jan",
  2015. "Feb",
  2016. "Mar",
  2017. "Apr",
  2018. "May",
  2019. "Jun",
  2020. "Jul",
  2021. "Aug",
  2022. "Sep",
  2023. "Oct",
  2024. "Nov",
  2025. "Dec"};
  2026. #endif /* !NO_CACHING */
  2027. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2028. * the union u. */
  2029. union usa {
  2030. struct sockaddr sa;
  2031. struct sockaddr_in sin;
  2032. #if defined(USE_IPV6)
  2033. struct sockaddr_in6 sin6;
  2034. #endif
  2035. };
  2036. /* Describes a string (chunk of memory). */
  2037. struct vec {
  2038. const char *ptr;
  2039. size_t len;
  2040. };
  2041. struct mg_file_stat {
  2042. /* File properties filled by mg_stat: */
  2043. uint64_t size;
  2044. time_t last_modified;
  2045. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2046. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2047. * case we need a "Content-Eencoding: gzip" header */
  2048. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2049. };
  2050. struct mg_file_in_memory {
  2051. char *p;
  2052. uint32_t pos;
  2053. char mode;
  2054. };
  2055. struct mg_file_access {
  2056. /* File properties filled by mg_fopen: */
  2057. FILE *fp;
  2058. #if defined(MG_USE_OPEN_FILE)
  2059. /* TODO (low): Remove obsolete "file in memory" implementation.
  2060. * In an "early 2017" discussion at Google groups
  2061. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2062. * we decided to get rid of this feature (after some fade-out
  2063. * phase). */
  2064. const char *membuf;
  2065. #endif
  2066. };
  2067. struct mg_file {
  2068. struct mg_file_stat stat;
  2069. struct mg_file_access access;
  2070. };
  2071. #if defined(MG_USE_OPEN_FILE)
  2072. #define STRUCT_FILE_INITIALIZER \
  2073. { \
  2074. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2075. { \
  2076. (FILE *)NULL, (const char *)NULL \
  2077. } \
  2078. }
  2079. #else
  2080. #define STRUCT_FILE_INITIALIZER \
  2081. { \
  2082. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2083. { \
  2084. (FILE *)NULL \
  2085. } \
  2086. }
  2087. #endif
  2088. /* Describes listening socket, or socket which was accept()-ed by the master
  2089. * thread and queued for future handling by the worker thread. */
  2090. struct socket {
  2091. SOCKET sock; /* Listening socket */
  2092. union usa lsa; /* Local socket address */
  2093. union usa rsa; /* Remote socket address */
  2094. unsigned char is_ssl; /* Is port SSL-ed */
  2095. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2096. * port */
  2097. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2098. };
  2099. /* Enum const for all options must be in sync with
  2100. * static struct mg_option config_options[]
  2101. * This is tested in the unit test (test/private.c)
  2102. * "Private Config Options"
  2103. */
  2104. enum {
  2105. /* Once for each server */
  2106. LISTENING_PORTS,
  2107. NUM_THREADS,
  2108. RUN_AS_USER,
  2109. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2110. * socket option typedef TCP_NODELAY. */
  2111. MAX_REQUEST_SIZE,
  2112. LINGER_TIMEOUT,
  2113. CONNECTION_QUEUE_SIZE,
  2114. LISTEN_BACKLOG_SIZE,
  2115. #if defined(__linux__)
  2116. ALLOW_SENDFILE_CALL,
  2117. #endif
  2118. #if defined(_WIN32)
  2119. CASE_SENSITIVE_FILES,
  2120. #endif
  2121. THROTTLE,
  2122. ACCESS_LOG_FILE,
  2123. ERROR_LOG_FILE,
  2124. ENABLE_KEEP_ALIVE,
  2125. REQUEST_TIMEOUT,
  2126. KEEP_ALIVE_TIMEOUT,
  2127. #if defined(USE_WEBSOCKET)
  2128. WEBSOCKET_TIMEOUT,
  2129. ENABLE_WEBSOCKET_PING_PONG,
  2130. #endif
  2131. DECODE_URL,
  2132. #if defined(USE_LUA)
  2133. LUA_BACKGROUND_SCRIPT,
  2134. LUA_BACKGROUND_SCRIPT_PARAMS,
  2135. #endif
  2136. #if defined(USE_TIMERS)
  2137. CGI_TIMEOUT,
  2138. #endif
  2139. /* Once for each domain */
  2140. DOCUMENT_ROOT,
  2141. CGI_EXTENSIONS,
  2142. CGI_ENVIRONMENT,
  2143. PUT_DELETE_PASSWORDS_FILE,
  2144. CGI_INTERPRETER,
  2145. CGI_INTERPRETER_ARGS,
  2146. PROTECT_URI,
  2147. AUTHENTICATION_DOMAIN,
  2148. ENABLE_AUTH_DOMAIN_CHECK,
  2149. SSI_EXTENSIONS,
  2150. ENABLE_DIRECTORY_LISTING,
  2151. GLOBAL_PASSWORDS_FILE,
  2152. INDEX_FILES,
  2153. ACCESS_CONTROL_LIST,
  2154. EXTRA_MIME_TYPES,
  2155. SSL_CERTIFICATE,
  2156. SSL_CERTIFICATE_CHAIN,
  2157. URL_REWRITE_PATTERN,
  2158. HIDE_FILES,
  2159. SSL_DO_VERIFY_PEER,
  2160. SSL_CA_PATH,
  2161. SSL_CA_FILE,
  2162. SSL_VERIFY_DEPTH,
  2163. SSL_DEFAULT_VERIFY_PATHS,
  2164. SSL_CIPHER_LIST,
  2165. SSL_PROTOCOL_VERSION,
  2166. SSL_SHORT_TRUST,
  2167. #if defined(USE_LUA)
  2168. LUA_PRELOAD_FILE,
  2169. LUA_SCRIPT_EXTENSIONS,
  2170. LUA_SERVER_PAGE_EXTENSIONS,
  2171. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2172. LUA_DEBUG_PARAMS,
  2173. #endif
  2174. #endif
  2175. #if defined(USE_DUKTAPE)
  2176. DUKTAPE_SCRIPT_EXTENSIONS,
  2177. #endif
  2178. #if defined(USE_WEBSOCKET)
  2179. WEBSOCKET_ROOT,
  2180. #endif
  2181. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2182. LUA_WEBSOCKET_EXTENSIONS,
  2183. #endif
  2184. ACCESS_CONTROL_ALLOW_ORIGIN,
  2185. ACCESS_CONTROL_ALLOW_METHODS,
  2186. ACCESS_CONTROL_ALLOW_HEADERS,
  2187. ERROR_PAGES,
  2188. #if !defined(NO_CACHING)
  2189. STATIC_FILE_MAX_AGE,
  2190. STATIC_FILE_CACHE_CONTROL,
  2191. #endif
  2192. #if !defined(NO_SSL)
  2193. STRICT_HTTPS_MAX_AGE,
  2194. #endif
  2195. ADDITIONAL_HEADER,
  2196. ALLOW_INDEX_SCRIPT_SUB_RES,
  2197. #if defined(DAEMONIZE)
  2198. ENABLE_DAEMONIZE,
  2199. #endif
  2200. NUM_OPTIONS
  2201. };
  2202. /* Config option name, config types, default value.
  2203. * Must be in the same order as the enum const above.
  2204. */
  2205. static const struct mg_option config_options[] = {
  2206. /* Once for each server */
  2207. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2208. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2209. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2210. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2211. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2212. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2213. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2214. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2215. #if defined(__linux__)
  2216. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2217. #endif
  2218. #if defined(_WIN32)
  2219. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2220. #endif
  2221. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2222. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2223. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2224. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2225. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2226. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2227. #if defined(USE_WEBSOCKET)
  2228. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2229. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2230. #endif
  2231. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2232. #if defined(USE_LUA)
  2233. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2234. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2235. #endif
  2236. #if defined(USE_TIMERS)
  2237. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2238. #endif
  2239. /* Once for each domain */
  2240. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2241. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2242. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2243. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2244. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2245. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2246. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2247. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2248. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2249. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2250. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2251. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2252. {"index_files",
  2253. MG_CONFIG_TYPE_STRING_LIST,
  2254. #if defined(USE_LUA)
  2255. "index.xhtml,index.html,index.htm,"
  2256. "index.lp,index.lsp,index.lua,index.cgi,"
  2257. "index.shtml,index.php"},
  2258. #else
  2259. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2260. #endif
  2261. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2262. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2263. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2264. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2265. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2266. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2267. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2268. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2269. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2270. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2271. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2272. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2273. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2274. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2275. #if defined(USE_LUA)
  2276. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2277. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2278. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2279. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2280. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2281. #endif
  2282. #endif
  2283. #if defined(USE_DUKTAPE)
  2284. /* The support for duktape is still in alpha version state.
  2285. * The name of this config option might change. */
  2286. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2287. #endif
  2288. #if defined(USE_WEBSOCKET)
  2289. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2290. #endif
  2291. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2292. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2293. #endif
  2294. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2295. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2296. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2297. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2298. #if !defined(NO_CACHING)
  2299. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2300. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2301. #endif
  2302. #if !defined(NO_SSL)
  2303. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2304. #endif
  2305. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2306. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2307. #if defined(DAEMONIZE)
  2308. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2309. #endif
  2310. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2311. /* Check if the config_options and the corresponding enum have compatible
  2312. * sizes. */
  2313. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2314. == (NUM_OPTIONS + 1),
  2315. "config_options and enum not sync");
  2316. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2317. struct mg_handler_info {
  2318. /* Name/Pattern of the URI. */
  2319. char *uri;
  2320. size_t uri_len;
  2321. /* handler type */
  2322. int handler_type;
  2323. /* Handler for http/https or authorization requests. */
  2324. mg_request_handler handler;
  2325. unsigned int refcount;
  2326. int removing;
  2327. /* Handler for ws/wss (websocket) requests. */
  2328. mg_websocket_connect_handler connect_handler;
  2329. mg_websocket_ready_handler ready_handler;
  2330. mg_websocket_data_handler data_handler;
  2331. mg_websocket_close_handler close_handler;
  2332. /* accepted subprotocols for ws/wss requests. */
  2333. struct mg_websocket_subprotocols *subprotocols;
  2334. /* Handler for authorization requests */
  2335. mg_authorization_handler auth_handler;
  2336. /* User supplied argument for the handler function. */
  2337. void *cbdata;
  2338. /* next handler in a linked list */
  2339. struct mg_handler_info *next;
  2340. };
  2341. enum {
  2342. CONTEXT_INVALID,
  2343. CONTEXT_SERVER,
  2344. CONTEXT_HTTP_CLIENT,
  2345. CONTEXT_WS_CLIENT
  2346. };
  2347. struct mg_domain_context {
  2348. SSL_CTX *ssl_ctx; /* SSL context */
  2349. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2350. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2351. int64_t ssl_cert_last_mtime;
  2352. /* Server nonce */
  2353. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2354. unsigned long nonce_count; /* Used nonces, used for authentication */
  2355. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2356. /* linked list of shared lua websockets */
  2357. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2358. #endif
  2359. /* Linked list of domains */
  2360. struct mg_domain_context *next;
  2361. };
  2362. /* Stop flag can be "volatile" or require a lock */
  2363. typedef int volatile stop_flag_t;
  2364. #ifdef STOP_FLAG_NEEDS_LOCK
  2365. static int
  2366. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2367. {
  2368. int r;
  2369. mg_global_lock();
  2370. r = ((*f) == 0);
  2371. mg_global_unlock();
  2372. return r;
  2373. }
  2374. static int
  2375. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2376. {
  2377. int r;
  2378. mg_global_lock();
  2379. r = ((*f) == 2);
  2380. mg_global_unlock();
  2381. return r;
  2382. }
  2383. static void
  2384. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2385. {
  2386. mg_global_lock();
  2387. (*f) = v;
  2388. mg_global_unlock();
  2389. }
  2390. #else /* STOP_FLAG_NEEDS_LOCK */
  2391. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2392. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2393. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2394. #endif /* STOP_FLAG_NEEDS_LOCK */
  2395. struct mg_context {
  2396. /* Part 1 - Physical context:
  2397. * This holds threads, ports, timeouts, ...
  2398. * set for the entire server, independent from the
  2399. * addressed hostname.
  2400. */
  2401. /* Connection related */
  2402. int context_type; /* See CONTEXT_* above */
  2403. struct socket *listening_sockets;
  2404. struct mg_pollfd *listening_socket_fds;
  2405. unsigned int num_listening_sockets;
  2406. struct mg_connection *worker_connections; /* The connection struct, pre-
  2407. * allocated for each worker */
  2408. #if defined(USE_SERVER_STATS)
  2409. int active_connections;
  2410. int max_active_connections;
  2411. int64_t total_connections;
  2412. int64_t total_requests;
  2413. int64_t total_data_read;
  2414. int64_t total_data_written;
  2415. #endif
  2416. /* Thread related */
  2417. stop_flag_t stop_flag; /* Should we stop event loop */
  2418. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2419. pthread_t masterthreadid; /* The master thread ID */
  2420. unsigned int
  2421. cfg_worker_threads; /* The number of configured worker threads. */
  2422. pthread_t *worker_threadids; /* The worker thread IDs */
  2423. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2424. /* Connection to thread dispatching */
  2425. #if defined(ALTERNATIVE_QUEUE)
  2426. struct socket *client_socks;
  2427. void **client_wait_events;
  2428. #else
  2429. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2430. worker thread */
  2431. volatile int sq_head; /* Head of the socket queue */
  2432. volatile int sq_tail; /* Tail of the socket queue */
  2433. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2434. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2435. volatile int sq_blocked; /* Status information: sq is full */
  2436. int sq_size; /* No of elements in socket queue */
  2437. #if defined(USE_SERVER_STATS)
  2438. int sq_max_fill;
  2439. #endif /* USE_SERVER_STATS */
  2440. #endif /* ALTERNATIVE_QUEUE */
  2441. /* Memory related */
  2442. unsigned int max_request_size; /* The max request size */
  2443. #if defined(USE_SERVER_STATS)
  2444. struct mg_memory_stat ctx_memory;
  2445. #endif
  2446. /* Operating system related */
  2447. char *systemName; /* What operating system is running */
  2448. time_t start_time; /* Server start time, used for authentication
  2449. * and for diagnstics. */
  2450. #if defined(USE_TIMERS)
  2451. struct ttimers *timers;
  2452. #endif
  2453. /* Lua specific: Background operations and shared websockets */
  2454. #if defined(USE_LUA)
  2455. void *lua_background_state;
  2456. #endif
  2457. /* Server nonce */
  2458. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2459. * ssl_cert_last_mtime, nonce_count, and
  2460. * next (linked list) */
  2461. /* Server callbacks */
  2462. struct mg_callbacks callbacks; /* User-defined callback function */
  2463. void *user_data; /* User-defined data */
  2464. /* Part 2 - Logical domain:
  2465. * This holds hostname, TLS certificate, document root, ...
  2466. * set for a domain hosted at the server.
  2467. * There may be multiple domains hosted at one physical server.
  2468. * The default domain "dd" is the first element of a list of
  2469. * domains.
  2470. */
  2471. struct mg_domain_context dd; /* default domain */
  2472. };
  2473. #if defined(USE_SERVER_STATS)
  2474. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2475. static struct mg_memory_stat *
  2476. get_memory_stat(struct mg_context *ctx)
  2477. {
  2478. if (ctx) {
  2479. return &(ctx->ctx_memory);
  2480. }
  2481. return &mg_common_memory;
  2482. }
  2483. #endif
  2484. enum {
  2485. CONNECTION_TYPE_INVALID,
  2486. CONNECTION_TYPE_REQUEST,
  2487. CONNECTION_TYPE_RESPONSE
  2488. };
  2489. enum {
  2490. PROTOCOL_TYPE_HTTP1 = 0,
  2491. PROTOCOL_TYPE_WEBSOCKET = 1,
  2492. PROTOCOL_TYPE_HTTP2 = 2
  2493. };
  2494. struct mg_connection {
  2495. int connection_type; /* see CONNECTION_TYPE_* above */
  2496. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2497. struct mg_request_info request_info;
  2498. struct mg_response_info response_info;
  2499. struct mg_context *phys_ctx;
  2500. struct mg_domain_context *dom_ctx;
  2501. #if defined(USE_SERVER_STATS)
  2502. int conn_state; /* 0 = undef, numerical value may change in different
  2503. * versions. For the current definition, see
  2504. * mg_get_connection_info_impl */
  2505. #endif
  2506. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2507. SSL *ssl; /* SSL descriptor */
  2508. struct socket client; /* Connected client */
  2509. time_t conn_birth_time; /* Time (wall clock) when connection was
  2510. * established */
  2511. #if defined(USE_SERVER_STATS)
  2512. time_t conn_close_time; /* Time (wall clock) when connection was
  2513. * closed (or 0 if still open) */
  2514. #endif
  2515. struct timespec req_time; /* Time (since system start) when the request
  2516. * was received */
  2517. int64_t num_bytes_sent; /* Total bytes sent to client */
  2518. int64_t content_len; /* How many bytes of content can be read
  2519. * !is_chunked: Content-Length header value
  2520. * or -1 (until connection closed,
  2521. * not allowed for a request)
  2522. * is_chunked: >= 0, appended gradually
  2523. */
  2524. int64_t consumed_content; /* How many bytes of content have been read */
  2525. int is_chunked; /* Transfer-Encoding is chunked:
  2526. * 0 = not chunked,
  2527. * 1 = chunked, not yet, or some data read,
  2528. * 2 = chunked, has error,
  2529. * 3 = chunked, all data read except trailer,
  2530. * 4 = chunked, all data read
  2531. */
  2532. char *buf; /* Buffer for received data */
  2533. char *path_info; /* PATH_INFO part of the URL */
  2534. int must_close; /* 1 if connection must be closed */
  2535. int accept_gzip; /* 1 if gzip encoding is accepted */
  2536. int in_error_handler; /* 1 if in handler for user defined error
  2537. * pages */
  2538. #if defined(USE_WEBSOCKET)
  2539. int in_websocket_handling; /* 1 if in read_websocket */
  2540. #endif
  2541. int handled_requests; /* Number of requests handled by this connection
  2542. */
  2543. int buf_size; /* Buffer size */
  2544. int request_len; /* Size of the request + headers in a buffer */
  2545. int data_len; /* Total size of data in a buffer */
  2546. int status_code; /* HTTP reply status code, e.g. 200 */
  2547. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2548. * throttle */
  2549. time_t last_throttle_time; /* Last time throttled data was sent */
  2550. int last_throttle_bytes; /* Bytes sent this second */
  2551. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2552. * atomic transmissions for websockets */
  2553. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2554. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2555. #endif
  2556. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2557. * for quick access */
  2558. };
  2559. /* Directory entry */
  2560. struct de {
  2561. struct mg_connection *conn;
  2562. char *file_name;
  2563. struct mg_file_stat file;
  2564. };
  2565. #define mg_cry_internal(conn, fmt, ...) \
  2566. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2567. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2568. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2569. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2570. struct mg_context *ctx,
  2571. const char *func,
  2572. unsigned line,
  2573. const char *fmt,
  2574. ...) PRINTF_ARGS(5, 6);
  2575. #if !defined(NO_THREAD_NAME)
  2576. #if defined(_WIN32) && defined(_MSC_VER)
  2577. /* Set the thread name for debugging purposes in Visual Studio
  2578. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2579. */
  2580. #pragma pack(push, 8)
  2581. typedef struct tagTHREADNAME_INFO {
  2582. DWORD dwType; /* Must be 0x1000. */
  2583. LPCSTR szName; /* Pointer to name (in user addr space). */
  2584. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2585. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2586. } THREADNAME_INFO;
  2587. #pragma pack(pop)
  2588. #elif defined(__linux__)
  2589. #include <sys/prctl.h>
  2590. #include <sys/sendfile.h>
  2591. #if defined(ALTERNATIVE_QUEUE)
  2592. #include <sys/eventfd.h>
  2593. #endif /* ALTERNATIVE_QUEUE */
  2594. #if defined(ALTERNATIVE_QUEUE)
  2595. static void *
  2596. event_create(void)
  2597. {
  2598. int evhdl = eventfd(0, EFD_CLOEXEC);
  2599. int *ret;
  2600. if (evhdl == -1) {
  2601. /* Linux uses -1 on error, Windows NULL. */
  2602. /* However, Linux does not return 0 on success either. */
  2603. return 0;
  2604. }
  2605. ret = (int *)mg_malloc(sizeof(int));
  2606. if (ret) {
  2607. *ret = evhdl;
  2608. } else {
  2609. (void)close(evhdl);
  2610. }
  2611. return (void *)ret;
  2612. }
  2613. static int
  2614. event_wait(void *eventhdl)
  2615. {
  2616. uint64_t u;
  2617. int evhdl, s;
  2618. if (!eventhdl) {
  2619. /* error */
  2620. return 0;
  2621. }
  2622. evhdl = *(int *)eventhdl;
  2623. s = (int)read(evhdl, &u, sizeof(u));
  2624. if (s != sizeof(u)) {
  2625. /* error */
  2626. return 0;
  2627. }
  2628. (void)u; /* the value is not required */
  2629. return 1;
  2630. }
  2631. static int
  2632. event_signal(void *eventhdl)
  2633. {
  2634. uint64_t u = 1;
  2635. int evhdl, s;
  2636. if (!eventhdl) {
  2637. /* error */
  2638. return 0;
  2639. }
  2640. evhdl = *(int *)eventhdl;
  2641. s = (int)write(evhdl, &u, sizeof(u));
  2642. if (s != sizeof(u)) {
  2643. /* error */
  2644. return 0;
  2645. }
  2646. return 1;
  2647. }
  2648. static void
  2649. event_destroy(void *eventhdl)
  2650. {
  2651. int evhdl;
  2652. if (!eventhdl) {
  2653. /* error */
  2654. return;
  2655. }
  2656. evhdl = *(int *)eventhdl;
  2657. close(evhdl);
  2658. mg_free(eventhdl);
  2659. }
  2660. #endif
  2661. #endif
  2662. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2663. struct posix_event {
  2664. pthread_mutex_t mutex;
  2665. pthread_cond_t cond;
  2666. int signaled;
  2667. };
  2668. static void *
  2669. event_create(void)
  2670. {
  2671. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2672. if (ret == 0) {
  2673. /* out of memory */
  2674. return 0;
  2675. }
  2676. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2677. /* pthread mutex not available */
  2678. mg_free(ret);
  2679. return 0;
  2680. }
  2681. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2682. /* pthread cond not available */
  2683. pthread_mutex_destroy(&(ret->mutex));
  2684. mg_free(ret);
  2685. return 0;
  2686. }
  2687. ret->signaled = 0;
  2688. return (void *)ret;
  2689. }
  2690. static int
  2691. event_wait(void *eventhdl)
  2692. {
  2693. struct posix_event *ev = (struct posix_event *)eventhdl;
  2694. pthread_mutex_lock(&(ev->mutex));
  2695. while (!ev->signaled) {
  2696. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2697. }
  2698. ev->signaled = 0;
  2699. pthread_mutex_unlock(&(ev->mutex));
  2700. return 1;
  2701. }
  2702. static int
  2703. event_signal(void *eventhdl)
  2704. {
  2705. struct posix_event *ev = (struct posix_event *)eventhdl;
  2706. pthread_mutex_lock(&(ev->mutex));
  2707. pthread_cond_signal(&(ev->cond));
  2708. ev->signaled = 1;
  2709. pthread_mutex_unlock(&(ev->mutex));
  2710. return 1;
  2711. }
  2712. static void
  2713. event_destroy(void *eventhdl)
  2714. {
  2715. struct posix_event *ev = (struct posix_event *)eventhdl;
  2716. pthread_cond_destroy(&(ev->cond));
  2717. pthread_mutex_destroy(&(ev->mutex));
  2718. mg_free(ev);
  2719. }
  2720. #endif
  2721. static void
  2722. mg_set_thread_name(const char *name)
  2723. {
  2724. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2725. mg_snprintf(
  2726. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2727. #if defined(_WIN32)
  2728. #if defined(_MSC_VER)
  2729. /* Windows and Visual Studio Compiler */
  2730. __try {
  2731. THREADNAME_INFO info;
  2732. info.dwType = 0x1000;
  2733. info.szName = threadName;
  2734. info.dwThreadID = ~0U;
  2735. info.dwFlags = 0;
  2736. RaiseException(0x406D1388,
  2737. 0,
  2738. sizeof(info) / sizeof(ULONG_PTR),
  2739. (ULONG_PTR *)&info);
  2740. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2741. }
  2742. #elif defined(__MINGW32__)
  2743. /* No option known to set thread name for MinGW known */
  2744. #endif
  2745. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2746. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2747. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2748. #if defined(__MACH__)
  2749. /* OS X only current thread name can be changed */
  2750. (void)pthread_setname_np(threadName);
  2751. #else
  2752. (void)pthread_setname_np(pthread_self(), threadName);
  2753. #endif
  2754. #elif defined(__linux__)
  2755. /* On Linux we can use the prctl function.
  2756. * When building for Linux Standard Base (LSB) use
  2757. * NO_THREAD_NAME. However, thread names are a big
  2758. * help for debugging, so the stadard is to set them.
  2759. */
  2760. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2761. #endif
  2762. }
  2763. #else /* !defined(NO_THREAD_NAME) */
  2764. void
  2765. mg_set_thread_name(const char *threadName)
  2766. {
  2767. }
  2768. #endif
  2769. #if defined(MG_LEGACY_INTERFACE)
  2770. const char **
  2771. mg_get_valid_option_names(void)
  2772. {
  2773. /* This function is deprecated. Use mg_get_valid_options instead. */
  2774. static const char
  2775. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2776. int i;
  2777. for (i = 0; config_options[i].name != NULL; i++) {
  2778. data[i * 2] = config_options[i].name;
  2779. data[i * 2 + 1] = config_options[i].default_value;
  2780. }
  2781. return data;
  2782. }
  2783. #endif
  2784. const struct mg_option *
  2785. mg_get_valid_options(void)
  2786. {
  2787. return config_options;
  2788. }
  2789. /* Do not open file (used in is_file_in_memory) */
  2790. #define MG_FOPEN_MODE_NONE (0)
  2791. /* Open file for read only access */
  2792. #define MG_FOPEN_MODE_READ (1)
  2793. /* Open file for writing, create and overwrite */
  2794. #define MG_FOPEN_MODE_WRITE (2)
  2795. /* Open file for writing, create and append */
  2796. #define MG_FOPEN_MODE_APPEND (4)
  2797. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2798. * output filep and return 1, otherwise return 0 and don't modify anything.
  2799. */
  2800. static int
  2801. open_file_in_memory(const struct mg_connection *conn,
  2802. const char *path,
  2803. struct mg_file *filep,
  2804. int mode)
  2805. {
  2806. #if defined(MG_USE_OPEN_FILE)
  2807. size_t size = 0;
  2808. const char *buf = NULL;
  2809. if (!conn) {
  2810. return 0;
  2811. }
  2812. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2813. return 0;
  2814. }
  2815. if (conn->phys_ctx->callbacks.open_file) {
  2816. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2817. if (buf != NULL) {
  2818. if (filep == NULL) {
  2819. /* This is a file in memory, but we cannot store the
  2820. * properties
  2821. * now.
  2822. * Called from "is_file_in_memory" function. */
  2823. return 1;
  2824. }
  2825. /* NOTE: override filep->size only on success. Otherwise, it
  2826. * might
  2827. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2828. filep->access.membuf = buf;
  2829. filep->access.fp = NULL;
  2830. /* Size was set by the callback */
  2831. filep->stat.size = size;
  2832. /* Assume the data may change during runtime by setting
  2833. * last_modified = now */
  2834. filep->stat.last_modified = time(NULL);
  2835. filep->stat.is_directory = 0;
  2836. filep->stat.is_gzipped = 0;
  2837. }
  2838. }
  2839. return (buf != NULL);
  2840. #else
  2841. (void)conn;
  2842. (void)path;
  2843. (void)filep;
  2844. (void)mode;
  2845. return 0;
  2846. #endif
  2847. }
  2848. static int
  2849. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2850. {
  2851. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2852. }
  2853. static int
  2854. is_file_opened(const struct mg_file_access *fileacc)
  2855. {
  2856. if (!fileacc) {
  2857. return 0;
  2858. }
  2859. #if defined(MG_USE_OPEN_FILE)
  2860. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2861. #else
  2862. return (fileacc->fp != NULL);
  2863. #endif
  2864. }
  2865. #if !defined(NO_FILESYSTEMS)
  2866. static int mg_stat(const struct mg_connection *conn,
  2867. const char *path,
  2868. struct mg_file_stat *filep);
  2869. /* mg_fopen will open a file either in memory or on the disk.
  2870. * The input parameter path is a string in UTF-8 encoding.
  2871. * The input parameter mode is MG_FOPEN_MODE_*
  2872. * On success, either fp or membuf will be set in the output
  2873. * struct file. All status members will also be set.
  2874. * The function returns 1 on success, 0 on error. */
  2875. static int
  2876. mg_fopen(const struct mg_connection *conn,
  2877. const char *path,
  2878. int mode,
  2879. struct mg_file *filep)
  2880. {
  2881. int found;
  2882. if (!filep) {
  2883. return 0;
  2884. }
  2885. filep->access.fp = NULL;
  2886. #if defined(MG_USE_OPEN_FILE)
  2887. filep->access.membuf = NULL;
  2888. #endif
  2889. if (!is_file_in_memory(conn, path)) {
  2890. /* filep is initialized in mg_stat: all fields with memset to,
  2891. * some fields like size and modification date with values */
  2892. found = mg_stat(conn, path, &(filep->stat));
  2893. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2894. /* file does not exist and will not be created */
  2895. return 0;
  2896. }
  2897. #if defined(_WIN32)
  2898. {
  2899. wchar_t wbuf[W_PATH_MAX];
  2900. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2901. switch (mode) {
  2902. case MG_FOPEN_MODE_READ:
  2903. filep->access.fp = _wfopen(wbuf, L"rb");
  2904. break;
  2905. case MG_FOPEN_MODE_WRITE:
  2906. filep->access.fp = _wfopen(wbuf, L"wb");
  2907. break;
  2908. case MG_FOPEN_MODE_APPEND:
  2909. filep->access.fp = _wfopen(wbuf, L"ab");
  2910. break;
  2911. }
  2912. }
  2913. #else
  2914. /* Linux et al already use unicode. No need to convert. */
  2915. switch (mode) {
  2916. case MG_FOPEN_MODE_READ:
  2917. filep->access.fp = fopen(path, "r");
  2918. break;
  2919. case MG_FOPEN_MODE_WRITE:
  2920. filep->access.fp = fopen(path, "w");
  2921. break;
  2922. case MG_FOPEN_MODE_APPEND:
  2923. filep->access.fp = fopen(path, "a");
  2924. break;
  2925. }
  2926. #endif
  2927. if (!found) {
  2928. /* File did not exist before fopen was called.
  2929. * Maybe it has been created now. Get stat info
  2930. * like creation time now. */
  2931. found = mg_stat(conn, path, &(filep->stat));
  2932. (void)found;
  2933. }
  2934. /* file is on disk */
  2935. return (filep->access.fp != NULL);
  2936. } else {
  2937. #if defined(MG_USE_OPEN_FILE)
  2938. /* is_file_in_memory returned true */
  2939. if (open_file_in_memory(conn, path, filep, mode)) {
  2940. /* file is in memory */
  2941. return (filep->access.membuf != NULL);
  2942. }
  2943. #endif
  2944. }
  2945. /* Open failed */
  2946. return 0;
  2947. }
  2948. /* return 0 on success, just like fclose */
  2949. static int
  2950. mg_fclose(struct mg_file_access *fileacc)
  2951. {
  2952. int ret = -1;
  2953. if (fileacc != NULL) {
  2954. if (fileacc->fp != NULL) {
  2955. ret = fclose(fileacc->fp);
  2956. #if defined(MG_USE_OPEN_FILE)
  2957. } else if (fileacc->membuf != NULL) {
  2958. ret = 0;
  2959. #endif
  2960. }
  2961. /* reset all members of fileacc */
  2962. memset(fileacc, 0, sizeof(*fileacc));
  2963. }
  2964. return ret;
  2965. }
  2966. #endif /* NO_FILESYSTEMS */
  2967. static void
  2968. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2969. {
  2970. for (; *src != '\0' && n > 1; n--) {
  2971. *dst++ = *src++;
  2972. }
  2973. *dst = '\0';
  2974. }
  2975. static int
  2976. lowercase(const char *s)
  2977. {
  2978. return tolower((unsigned char)*s);
  2979. }
  2980. int
  2981. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2982. {
  2983. int diff = 0;
  2984. if (len > 0) {
  2985. do {
  2986. diff = lowercase(s1++) - lowercase(s2++);
  2987. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2988. }
  2989. return diff;
  2990. }
  2991. int
  2992. mg_strcasecmp(const char *s1, const char *s2)
  2993. {
  2994. int diff;
  2995. do {
  2996. diff = lowercase(s1++) - lowercase(s2++);
  2997. } while (diff == 0 && s1[-1] != '\0');
  2998. return diff;
  2999. }
  3000. static char *
  3001. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3002. {
  3003. char *p;
  3004. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3005. * defined */
  3006. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3007. mg_strlcpy(p, ptr, len + 1);
  3008. }
  3009. return p;
  3010. }
  3011. static char *
  3012. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3013. {
  3014. return mg_strndup_ctx(str, strlen(str), ctx);
  3015. }
  3016. static char *
  3017. mg_strdup(const char *str)
  3018. {
  3019. return mg_strndup_ctx(str, strlen(str), NULL);
  3020. }
  3021. static const char *
  3022. mg_strcasestr(const char *big_str, const char *small_str)
  3023. {
  3024. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3025. if (big_len >= small_len) {
  3026. for (i = 0; i <= (big_len - small_len); i++) {
  3027. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3028. return big_str + i;
  3029. }
  3030. }
  3031. }
  3032. return NULL;
  3033. }
  3034. /* Return null terminated string of given maximum length.
  3035. * Report errors if length is exceeded. */
  3036. static void
  3037. mg_vsnprintf(const struct mg_connection *conn,
  3038. int *truncated,
  3039. char *buf,
  3040. size_t buflen,
  3041. const char *fmt,
  3042. va_list ap)
  3043. {
  3044. int n, ok;
  3045. if (buflen == 0) {
  3046. if (truncated) {
  3047. *truncated = 1;
  3048. }
  3049. return;
  3050. }
  3051. #if defined(__clang__)
  3052. #pragma clang diagnostic push
  3053. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3054. /* Using fmt as a non-literal is intended here, since it is mostly called
  3055. * indirectly by mg_snprintf */
  3056. #endif
  3057. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3058. ok = (n >= 0) && ((size_t)n < buflen);
  3059. #if defined(__clang__)
  3060. #pragma clang diagnostic pop
  3061. #endif
  3062. if (ok) {
  3063. if (truncated) {
  3064. *truncated = 0;
  3065. }
  3066. } else {
  3067. if (truncated) {
  3068. *truncated = 1;
  3069. }
  3070. mg_cry_internal(conn,
  3071. "truncating vsnprintf buffer: [%.*s]",
  3072. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3073. buf);
  3074. n = (int)buflen - 1;
  3075. }
  3076. buf[n] = '\0';
  3077. }
  3078. static void
  3079. mg_snprintf(const struct mg_connection *conn,
  3080. int *truncated,
  3081. char *buf,
  3082. size_t buflen,
  3083. const char *fmt,
  3084. ...)
  3085. {
  3086. va_list ap;
  3087. va_start(ap, fmt);
  3088. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3089. va_end(ap);
  3090. }
  3091. static int
  3092. get_option_index(const char *name)
  3093. {
  3094. int i;
  3095. for (i = 0; config_options[i].name != NULL; i++) {
  3096. if (strcmp(config_options[i].name, name) == 0) {
  3097. return i;
  3098. }
  3099. }
  3100. return -1;
  3101. }
  3102. const char *
  3103. mg_get_option(const struct mg_context *ctx, const char *name)
  3104. {
  3105. int i;
  3106. if ((i = get_option_index(name)) == -1) {
  3107. return NULL;
  3108. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3109. return "";
  3110. } else {
  3111. return ctx->dd.config[i];
  3112. }
  3113. }
  3114. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3115. struct mg_context *
  3116. mg_get_context(const struct mg_connection *conn)
  3117. {
  3118. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3119. }
  3120. void *
  3121. mg_get_user_data(const struct mg_context *ctx)
  3122. {
  3123. return (ctx == NULL) ? NULL : ctx->user_data;
  3124. }
  3125. void *
  3126. mg_get_user_context_data(const struct mg_connection *conn)
  3127. {
  3128. return mg_get_user_data(mg_get_context(conn));
  3129. }
  3130. void *
  3131. mg_get_thread_pointer(const struct mg_connection *conn)
  3132. {
  3133. /* both methods should return the same pointer */
  3134. if (conn) {
  3135. /* quick access, in case conn is known */
  3136. return conn->tls_user_ptr;
  3137. } else {
  3138. /* otherwise get pointer from thread local storage (TLS) */
  3139. struct mg_workerTLS *tls =
  3140. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3141. return tls->user_ptr;
  3142. }
  3143. }
  3144. void
  3145. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3146. {
  3147. if (conn != NULL) {
  3148. conn->request_info.conn_data = data;
  3149. }
  3150. }
  3151. void *
  3152. mg_get_user_connection_data(const struct mg_connection *conn)
  3153. {
  3154. if (conn != NULL) {
  3155. return conn->request_info.conn_data;
  3156. }
  3157. return NULL;
  3158. }
  3159. #if defined(MG_LEGACY_INTERFACE)
  3160. /* Deprecated: Use mg_get_server_ports instead. */
  3161. size_t
  3162. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3163. {
  3164. size_t i;
  3165. if (!ctx) {
  3166. return 0;
  3167. }
  3168. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3169. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3170. ports[i] =
  3171. #if defined(USE_IPV6)
  3172. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3173. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3174. :
  3175. #endif
  3176. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3177. }
  3178. return i;
  3179. }
  3180. #endif
  3181. int
  3182. mg_get_server_ports(const struct mg_context *ctx,
  3183. int size,
  3184. struct mg_server_port *ports)
  3185. {
  3186. int i, cnt = 0;
  3187. if (size <= 0) {
  3188. return -1;
  3189. }
  3190. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3191. if (!ctx) {
  3192. return -1;
  3193. }
  3194. if (!ctx->listening_sockets) {
  3195. return -1;
  3196. }
  3197. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3198. ports[cnt].port =
  3199. #if defined(USE_IPV6)
  3200. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3201. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3202. :
  3203. #endif
  3204. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3205. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3206. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3207. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3208. /* IPv4 */
  3209. ports[cnt].protocol = 1;
  3210. cnt++;
  3211. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3212. /* IPv6 */
  3213. ports[cnt].protocol = 3;
  3214. cnt++;
  3215. }
  3216. }
  3217. return cnt;
  3218. }
  3219. static void
  3220. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3221. {
  3222. buf[0] = '\0';
  3223. if (!usa) {
  3224. return;
  3225. }
  3226. if (usa->sa.sa_family == AF_INET) {
  3227. getnameinfo(&usa->sa,
  3228. sizeof(usa->sin),
  3229. buf,
  3230. (unsigned)len,
  3231. NULL,
  3232. 0,
  3233. NI_NUMERICHOST);
  3234. }
  3235. #if defined(USE_IPV6)
  3236. else if (usa->sa.sa_family == AF_INET6) {
  3237. getnameinfo(&usa->sa,
  3238. sizeof(usa->sin6),
  3239. buf,
  3240. (unsigned)len,
  3241. NULL,
  3242. 0,
  3243. NI_NUMERICHOST);
  3244. }
  3245. #endif
  3246. }
  3247. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3248. * included in all responses other than 100, 101, 5xx. */
  3249. static void
  3250. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3251. {
  3252. #if !defined(REENTRANT_TIME)
  3253. struct tm *tm;
  3254. tm = ((t != NULL) ? gmtime(t) : NULL);
  3255. if (tm != NULL) {
  3256. #else
  3257. struct tm _tm;
  3258. struct tm *tm = &_tm;
  3259. if (t != NULL) {
  3260. gmtime_r(t, tm);
  3261. #endif
  3262. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3263. } else {
  3264. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3265. buf[buf_len - 1] = '\0';
  3266. }
  3267. }
  3268. /* difftime for struct timespec. Return value is in seconds. */
  3269. static double
  3270. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3271. {
  3272. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3273. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3274. }
  3275. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3276. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3277. const char *func,
  3278. unsigned line,
  3279. const char *fmt,
  3280. va_list ap);
  3281. #include "external_mg_cry_internal_impl.inl"
  3282. #elif !defined(NO_FILESYSTEMS)
  3283. /* Print error message to the opened error log stream. */
  3284. static void
  3285. mg_cry_internal_impl(const struct mg_connection *conn,
  3286. const char *func,
  3287. unsigned line,
  3288. const char *fmt,
  3289. va_list ap)
  3290. {
  3291. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3292. struct mg_file fi;
  3293. time_t timestamp;
  3294. /* Unused, in the RELEASE build */
  3295. (void)func;
  3296. (void)line;
  3297. #if defined(GCC_DIAGNOSTIC)
  3298. #pragma GCC diagnostic push
  3299. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3300. #endif
  3301. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3302. #if defined(GCC_DIAGNOSTIC)
  3303. #pragma GCC diagnostic pop
  3304. #endif
  3305. buf[sizeof(buf) - 1] = 0;
  3306. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3307. if (!conn) {
  3308. puts(buf);
  3309. return;
  3310. }
  3311. /* Do not lock when getting the callback value, here and below.
  3312. * I suppose this is fine, since function cannot disappear in the
  3313. * same way string option can. */
  3314. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3315. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3316. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3317. if (mg_fopen(conn,
  3318. conn->dom_ctx->config[ERROR_LOG_FILE],
  3319. MG_FOPEN_MODE_APPEND,
  3320. &fi)
  3321. == 0) {
  3322. fi.access.fp = NULL;
  3323. }
  3324. } else {
  3325. fi.access.fp = NULL;
  3326. }
  3327. if (fi.access.fp != NULL) {
  3328. flockfile(fi.access.fp);
  3329. timestamp = time(NULL);
  3330. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3331. fprintf(fi.access.fp,
  3332. "[%010lu] [error] [client %s] ",
  3333. (unsigned long)timestamp,
  3334. src_addr);
  3335. if (conn->request_info.request_method != NULL) {
  3336. fprintf(fi.access.fp,
  3337. "%s %s: ",
  3338. conn->request_info.request_method,
  3339. conn->request_info.request_uri
  3340. ? conn->request_info.request_uri
  3341. : "");
  3342. }
  3343. fprintf(fi.access.fp, "%s", buf);
  3344. fputc('\n', fi.access.fp);
  3345. fflush(fi.access.fp);
  3346. funlockfile(fi.access.fp);
  3347. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3348. * mg_cry here anyway ;-) */
  3349. }
  3350. }
  3351. }
  3352. #else
  3353. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3354. #endif /* Externally provided function */
  3355. /* Construct fake connection structure. Used for logging, if connection
  3356. * is not applicable at the moment of logging. */
  3357. static struct mg_connection *
  3358. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3359. {
  3360. static const struct mg_connection conn_zero = {0};
  3361. *fc = conn_zero;
  3362. fc->phys_ctx = ctx;
  3363. fc->dom_ctx = &(ctx->dd);
  3364. return fc;
  3365. }
  3366. static void
  3367. mg_cry_internal_wrap(const struct mg_connection *conn,
  3368. struct mg_context *ctx,
  3369. const char *func,
  3370. unsigned line,
  3371. const char *fmt,
  3372. ...)
  3373. {
  3374. va_list ap;
  3375. va_start(ap, fmt);
  3376. if (!conn && ctx) {
  3377. struct mg_connection fc;
  3378. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3379. } else {
  3380. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3381. }
  3382. va_end(ap);
  3383. }
  3384. void
  3385. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3386. {
  3387. va_list ap;
  3388. va_start(ap, fmt);
  3389. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3390. va_end(ap);
  3391. }
  3392. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3393. const char *
  3394. mg_version(void)
  3395. {
  3396. return CIVETWEB_VERSION;
  3397. }
  3398. const struct mg_request_info *
  3399. mg_get_request_info(const struct mg_connection *conn)
  3400. {
  3401. if (!conn) {
  3402. return NULL;
  3403. }
  3404. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3405. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3406. char txt[16];
  3407. struct mg_workerTLS *tls =
  3408. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3409. sprintf(txt, "%03i", conn->response_info.status_code);
  3410. if (strlen(txt) == 3) {
  3411. memcpy(tls->txtbuf, txt, 4);
  3412. } else {
  3413. strcpy(tls->txtbuf, "ERR");
  3414. }
  3415. ((struct mg_connection *)conn)->request_info.local_uri =
  3416. ((struct mg_connection *)conn)->request_info.request_uri =
  3417. tls->txtbuf; /* use thread safe buffer */
  3418. ((struct mg_connection *)conn)->request_info.num_headers =
  3419. conn->response_info.num_headers;
  3420. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3421. conn->response_info.http_headers,
  3422. sizeof(conn->response_info.http_headers));
  3423. } else
  3424. #endif
  3425. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3426. return NULL;
  3427. }
  3428. return &conn->request_info;
  3429. }
  3430. const struct mg_response_info *
  3431. mg_get_response_info(const struct mg_connection *conn)
  3432. {
  3433. if (!conn) {
  3434. return NULL;
  3435. }
  3436. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3437. return NULL;
  3438. }
  3439. return &conn->response_info;
  3440. }
  3441. static const char *
  3442. get_proto_name(const struct mg_connection *conn)
  3443. {
  3444. #if defined(__clang__)
  3445. #pragma clang diagnostic push
  3446. #pragma clang diagnostic ignored "-Wunreachable-code"
  3447. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3448. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3449. * unreachable, but splitting into four different #ifdef clauses here is more
  3450. * complicated.
  3451. */
  3452. #endif
  3453. const struct mg_request_info *ri = &conn->request_info;
  3454. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3455. ? (ri->is_ssl ? "wss" : "ws")
  3456. : (ri->is_ssl ? "https" : "http"));
  3457. return proto;
  3458. #if defined(__clang__)
  3459. #pragma clang diagnostic pop
  3460. #endif
  3461. }
  3462. int
  3463. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3464. {
  3465. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3466. return -1;
  3467. } else {
  3468. int truncated = 0;
  3469. const struct mg_request_info *ri = &conn->request_info;
  3470. const char *proto = get_proto_name(conn);
  3471. if (ri->local_uri == NULL) {
  3472. return -1;
  3473. }
  3474. if ((ri->request_uri != NULL)
  3475. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3476. /* The request uri is different from the local uri.
  3477. * This is usually if an absolute URI, including server
  3478. * name has been provided. */
  3479. mg_snprintf(conn,
  3480. &truncated,
  3481. buf,
  3482. buflen,
  3483. "%s://%s",
  3484. proto,
  3485. ri->request_uri);
  3486. if (truncated) {
  3487. return -1;
  3488. }
  3489. return 0;
  3490. } else {
  3491. /* The common case is a relative URI, so we have to
  3492. * construct an absolute URI from server name and port */
  3493. #if defined(USE_IPV6)
  3494. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3495. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3496. : htons(conn->client.lsa.sin.sin_port);
  3497. #else
  3498. int port = htons(conn->client.lsa.sin.sin_port);
  3499. #endif
  3500. int def_port = ri->is_ssl ? 443 : 80;
  3501. int auth_domain_check_enabled =
  3502. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3503. && (!mg_strcasecmp(
  3504. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3505. const char *server_domain =
  3506. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3507. char portstr[16];
  3508. char server_ip[48];
  3509. if (port != def_port) {
  3510. sprintf(portstr, ":%u", (unsigned)port);
  3511. } else {
  3512. portstr[0] = 0;
  3513. }
  3514. if (!auth_domain_check_enabled || !server_domain) {
  3515. sockaddr_to_string(server_ip,
  3516. sizeof(server_ip),
  3517. &conn->client.lsa);
  3518. server_domain = server_ip;
  3519. }
  3520. mg_snprintf(conn,
  3521. &truncated,
  3522. buf,
  3523. buflen,
  3524. "%s://%s%s%s",
  3525. proto,
  3526. server_domain,
  3527. portstr,
  3528. ri->local_uri);
  3529. if (truncated) {
  3530. return -1;
  3531. }
  3532. return 0;
  3533. }
  3534. }
  3535. }
  3536. /* Skip the characters until one of the delimiters characters found.
  3537. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3538. * Advance pointer to buffer to the next word. Return found 0-terminated
  3539. * word.
  3540. * Delimiters can be quoted with quotechar. */
  3541. static char *
  3542. skip_quoted(char **buf,
  3543. const char *delimiters,
  3544. const char *whitespace,
  3545. char quotechar)
  3546. {
  3547. char *p, *begin_word, *end_word, *end_whitespace;
  3548. begin_word = *buf;
  3549. end_word = begin_word + strcspn(begin_word, delimiters);
  3550. /* Check for quotechar */
  3551. if (end_word > begin_word) {
  3552. p = end_word - 1;
  3553. while (*p == quotechar) {
  3554. /* While the delimiter is quoted, look for the next delimiter.
  3555. */
  3556. /* This happens, e.g., in calls from parse_auth_header,
  3557. * if the user name contains a " character. */
  3558. /* If there is anything beyond end_word, copy it. */
  3559. if (*end_word != '\0') {
  3560. size_t end_off = strcspn(end_word + 1, delimiters);
  3561. memmove(p, end_word, end_off + 1);
  3562. p += end_off; /* p must correspond to end_word - 1 */
  3563. end_word += end_off + 1;
  3564. } else {
  3565. *p = '\0';
  3566. break;
  3567. }
  3568. }
  3569. for (p++; p < end_word; p++) {
  3570. *p = '\0';
  3571. }
  3572. }
  3573. if (*end_word == '\0') {
  3574. *buf = end_word;
  3575. } else {
  3576. #if defined(GCC_DIAGNOSTIC)
  3577. /* Disable spurious conversion warning for GCC */
  3578. #pragma GCC diagnostic push
  3579. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3580. #endif /* defined(GCC_DIAGNOSTIC) */
  3581. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3582. #if defined(GCC_DIAGNOSTIC)
  3583. #pragma GCC diagnostic pop
  3584. #endif /* defined(GCC_DIAGNOSTIC) */
  3585. for (p = end_word; p < end_whitespace; p++) {
  3586. *p = '\0';
  3587. }
  3588. *buf = end_whitespace;
  3589. }
  3590. return begin_word;
  3591. }
  3592. /* Return HTTP header value, or NULL if not found. */
  3593. static const char *
  3594. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3595. {
  3596. int i;
  3597. for (i = 0; i < num_hdr; i++) {
  3598. if (!mg_strcasecmp(name, hdr[i].name)) {
  3599. return hdr[i].value;
  3600. }
  3601. }
  3602. return NULL;
  3603. }
  3604. #if defined(USE_WEBSOCKET)
  3605. /* Retrieve requested HTTP header multiple values, and return the number of
  3606. * found occurrences */
  3607. static int
  3608. get_req_headers(const struct mg_request_info *ri,
  3609. const char *name,
  3610. const char **output,
  3611. int output_max_size)
  3612. {
  3613. int i;
  3614. int cnt = 0;
  3615. if (ri) {
  3616. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3617. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3618. output[cnt++] = ri->http_headers[i].value;
  3619. }
  3620. }
  3621. }
  3622. return cnt;
  3623. }
  3624. #endif
  3625. const char *
  3626. mg_get_header(const struct mg_connection *conn, const char *name)
  3627. {
  3628. if (!conn) {
  3629. return NULL;
  3630. }
  3631. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3632. return get_header(conn->request_info.http_headers,
  3633. conn->request_info.num_headers,
  3634. name);
  3635. }
  3636. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3637. return get_header(conn->response_info.http_headers,
  3638. conn->response_info.num_headers,
  3639. name);
  3640. }
  3641. return NULL;
  3642. }
  3643. static const char *
  3644. get_http_version(const struct mg_connection *conn)
  3645. {
  3646. if (!conn) {
  3647. return NULL;
  3648. }
  3649. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3650. return conn->request_info.http_version;
  3651. }
  3652. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3653. return conn->response_info.http_version;
  3654. }
  3655. return NULL;
  3656. }
  3657. /* A helper function for traversing a comma separated list of values.
  3658. * It returns a list pointer shifted to the next value, or NULL if the end
  3659. * of the list found.
  3660. * Value is stored in val vector. If value has form "x=y", then eq_val
  3661. * vector is initialized to point to the "y" part, and val vector length
  3662. * is adjusted to point only to "x". */
  3663. static const char *
  3664. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3665. {
  3666. int end;
  3667. reparse:
  3668. if (val == NULL || list == NULL || *list == '\0') {
  3669. /* End of the list */
  3670. return NULL;
  3671. }
  3672. /* Skip over leading LWS */
  3673. while (*list == ' ' || *list == '\t')
  3674. list++;
  3675. val->ptr = list;
  3676. if ((list = strchr(val->ptr, ',')) != NULL) {
  3677. /* Comma found. Store length and shift the list ptr */
  3678. val->len = ((size_t)(list - val->ptr));
  3679. list++;
  3680. } else {
  3681. /* This value is the last one */
  3682. list = val->ptr + strlen(val->ptr);
  3683. val->len = ((size_t)(list - val->ptr));
  3684. }
  3685. /* Adjust length for trailing LWS */
  3686. end = (int)val->len - 1;
  3687. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3688. end--;
  3689. val->len = (size_t)(end) + (size_t)(1);
  3690. if (val->len == 0) {
  3691. /* Ignore any empty entries. */
  3692. goto reparse;
  3693. }
  3694. if (eq_val != NULL) {
  3695. /* Value has form "x=y", adjust pointers and lengths
  3696. * so that val points to "x", and eq_val points to "y". */
  3697. eq_val->len = 0;
  3698. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3699. if (eq_val->ptr != NULL) {
  3700. eq_val->ptr++; /* Skip over '=' character */
  3701. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3702. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3703. }
  3704. }
  3705. return list;
  3706. }
  3707. /* A helper function for checking if a comma separated list of values
  3708. * contains
  3709. * the given option (case insensitvely).
  3710. * 'header' can be NULL, in which case false is returned. */
  3711. static int
  3712. header_has_option(const char *header, const char *option)
  3713. {
  3714. struct vec opt_vec;
  3715. struct vec eq_vec;
  3716. DEBUG_ASSERT(option != NULL);
  3717. DEBUG_ASSERT(option[0] != '\0');
  3718. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3719. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3720. return 1;
  3721. }
  3722. return 0;
  3723. }
  3724. /* Perform case-insensitive match of string against pattern */
  3725. static ptrdiff_t
  3726. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3727. {
  3728. const char *or_str;
  3729. ptrdiff_t i, j, len, res;
  3730. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3731. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3732. return (res > 0) ? res
  3733. : match_prefix(or_str + 1,
  3734. (size_t)((pattern + pattern_len)
  3735. - (or_str + 1)),
  3736. str);
  3737. }
  3738. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3739. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3740. continue;
  3741. } else if (pattern[i] == '$') {
  3742. return (str[j] == '\0') ? j : -1;
  3743. } else if (pattern[i] == '*') {
  3744. i++;
  3745. if (pattern[i] == '*') {
  3746. i++;
  3747. len = (ptrdiff_t)strlen(str + j);
  3748. } else {
  3749. len = (ptrdiff_t)strcspn(str + j, "/");
  3750. }
  3751. if (i == (ptrdiff_t)pattern_len) {
  3752. return j + len;
  3753. }
  3754. do {
  3755. res = match_prefix(pattern + i,
  3756. (pattern_len - (size_t)i),
  3757. str + j + len);
  3758. } while (res == -1 && len-- > 0);
  3759. return (res == -1) ? -1 : j + res + len;
  3760. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3761. return -1;
  3762. }
  3763. }
  3764. return (ptrdiff_t)j;
  3765. }
  3766. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3767. * This function must tolerate situations when connection info is not
  3768. * set up, for example if request parsing failed. */
  3769. static int
  3770. should_keep_alive(const struct mg_connection *conn)
  3771. {
  3772. const char *http_version;
  3773. const char *header;
  3774. /* First satisfy needs of the server */
  3775. if ((conn == NULL) || conn->must_close) {
  3776. /* Close, if civetweb framework needs to close */
  3777. return 0;
  3778. }
  3779. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3780. /* Close, if keep alive is not enabled */
  3781. return 0;
  3782. }
  3783. /* Check explicit wish of the client */
  3784. header = mg_get_header(conn, "Connection");
  3785. if (header) {
  3786. /* If there is a connection header from the client, obey */
  3787. if (header_has_option(header, "keep-alive")) {
  3788. return 1;
  3789. }
  3790. return 0;
  3791. }
  3792. /* Use default of the standard */
  3793. http_version = get_http_version(conn);
  3794. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3795. /* HTTP 1.1 default is keep alive */
  3796. return 1;
  3797. }
  3798. /* HTTP 1.0 (and earlier) default is to close the connection */
  3799. return 0;
  3800. }
  3801. static int
  3802. should_decode_url(const struct mg_connection *conn)
  3803. {
  3804. if (!conn || !conn->dom_ctx) {
  3805. return 0;
  3806. }
  3807. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3808. }
  3809. static const char *
  3810. suggest_connection_header(const struct mg_connection *conn)
  3811. {
  3812. return should_keep_alive(conn) ? "keep-alive" : "close";
  3813. }
  3814. static int
  3815. send_no_cache_header(struct mg_connection *conn)
  3816. {
  3817. /* Send all current and obsolete cache opt-out directives. */
  3818. return mg_printf(conn,
  3819. "Cache-Control: no-cache, no-store, "
  3820. "must-revalidate, private, max-age=0\r\n"
  3821. "Pragma: no-cache\r\n"
  3822. "Expires: 0\r\n");
  3823. }
  3824. static int
  3825. send_static_cache_header(struct mg_connection *conn)
  3826. {
  3827. #if !defined(NO_CACHING)
  3828. int max_age;
  3829. const char *cache_control =
  3830. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3831. if (cache_control != NULL) {
  3832. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3833. }
  3834. /* Read the server config to check how long a file may be cached.
  3835. * The configuration is in seconds. */
  3836. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3837. if (max_age <= 0) {
  3838. /* 0 means "do not cache". All values <0 are reserved
  3839. * and may be used differently in the future. */
  3840. /* If a file should not be cached, do not only send
  3841. * max-age=0, but also pragmas and Expires headers. */
  3842. return send_no_cache_header(conn);
  3843. }
  3844. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3845. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3846. /* See also https://www.mnot.net/cache_docs/ */
  3847. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3848. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3849. * leap
  3850. * year to 31622400 seconds. For the moment, we just send whatever has
  3851. * been configured, still the behavior for >1 year should be considered
  3852. * as undefined. */
  3853. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3854. #else /* NO_CACHING */
  3855. return send_no_cache_header(conn);
  3856. #endif /* !NO_CACHING */
  3857. }
  3858. static int
  3859. send_additional_header(struct mg_connection *conn)
  3860. {
  3861. int i = 0;
  3862. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3863. #if !defined(NO_SSL)
  3864. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3865. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3866. if (max_age >= 0) {
  3867. i += mg_printf(conn,
  3868. "Strict-Transport-Security: max-age=%u\r\n",
  3869. (unsigned)max_age);
  3870. }
  3871. }
  3872. #endif
  3873. if (header && header[0]) {
  3874. i += mg_printf(conn, "%s\r\n", header);
  3875. }
  3876. return i;
  3877. }
  3878. #if !defined(NO_FILESYSTEMS)
  3879. static void handle_file_based_request(struct mg_connection *conn,
  3880. const char *path,
  3881. struct mg_file *filep);
  3882. #endif /* NO_FILESYSTEMS */
  3883. const char *
  3884. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3885. {
  3886. /* See IANA HTTP status code assignment:
  3887. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3888. */
  3889. switch (response_code) {
  3890. /* RFC2616 Section 10.1 - Informational 1xx */
  3891. case 100:
  3892. return "Continue"; /* RFC2616 Section 10.1.1 */
  3893. case 101:
  3894. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3895. case 102:
  3896. return "Processing"; /* RFC2518 Section 10.1 */
  3897. /* RFC2616 Section 10.2 - Successful 2xx */
  3898. case 200:
  3899. return "OK"; /* RFC2616 Section 10.2.1 */
  3900. case 201:
  3901. return "Created"; /* RFC2616 Section 10.2.2 */
  3902. case 202:
  3903. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3904. case 203:
  3905. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3906. case 204:
  3907. return "No Content"; /* RFC2616 Section 10.2.5 */
  3908. case 205:
  3909. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3910. case 206:
  3911. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3912. case 207:
  3913. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3914. */
  3915. case 208:
  3916. return "Already Reported"; /* RFC5842 Section 7.1 */
  3917. case 226:
  3918. return "IM used"; /* RFC3229 Section 10.4.1 */
  3919. /* RFC2616 Section 10.3 - Redirection 3xx */
  3920. case 300:
  3921. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3922. case 301:
  3923. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3924. case 302:
  3925. return "Found"; /* RFC2616 Section 10.3.3 */
  3926. case 303:
  3927. return "See Other"; /* RFC2616 Section 10.3.4 */
  3928. case 304:
  3929. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3930. case 305:
  3931. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3932. case 307:
  3933. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3934. case 308:
  3935. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3936. /* RFC2616 Section 10.4 - Client Error 4xx */
  3937. case 400:
  3938. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3939. case 401:
  3940. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3941. case 402:
  3942. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3943. case 403:
  3944. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3945. case 404:
  3946. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3947. case 405:
  3948. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3949. case 406:
  3950. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3951. case 407:
  3952. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3953. case 408:
  3954. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3955. case 409:
  3956. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3957. case 410:
  3958. return "Gone"; /* RFC2616 Section 10.4.11 */
  3959. case 411:
  3960. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3961. case 412:
  3962. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3963. case 413:
  3964. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3965. case 414:
  3966. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3967. case 415:
  3968. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3969. case 416:
  3970. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3971. */
  3972. case 417:
  3973. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3974. case 421:
  3975. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3976. case 422:
  3977. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3978. * Section 11.2 */
  3979. case 423:
  3980. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3981. case 424:
  3982. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3983. * Section 11.4 */
  3984. case 426:
  3985. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3986. case 428:
  3987. return "Precondition Required"; /* RFC 6585, Section 3 */
  3988. case 429:
  3989. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3990. case 431:
  3991. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3992. case 451:
  3993. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3994. * Section 3 */
  3995. /* RFC2616 Section 10.5 - Server Error 5xx */
  3996. case 500:
  3997. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3998. case 501:
  3999. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  4000. case 502:
  4001. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4002. case 503:
  4003. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4004. case 504:
  4005. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4006. case 505:
  4007. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4008. case 506:
  4009. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4010. case 507:
  4011. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4012. * Section 11.5 */
  4013. case 508:
  4014. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4015. case 510:
  4016. return "Not Extended"; /* RFC 2774, Section 7 */
  4017. case 511:
  4018. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4019. /* Other status codes, not shown in the IANA HTTP status code
  4020. * assignment.
  4021. * E.g., "de facto" standards due to common use, ... */
  4022. case 418:
  4023. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4024. case 419:
  4025. return "Authentication Timeout"; /* common use */
  4026. case 420:
  4027. return "Enhance Your Calm"; /* common use */
  4028. case 440:
  4029. return "Login Timeout"; /* common use */
  4030. case 509:
  4031. return "Bandwidth Limit Exceeded"; /* common use */
  4032. default:
  4033. /* This error code is unknown. This should not happen. */
  4034. if (conn) {
  4035. mg_cry_internal(conn,
  4036. "Unknown HTTP response code: %u",
  4037. response_code);
  4038. }
  4039. /* Return at least a category according to RFC 2616 Section 10. */
  4040. if (response_code >= 100 && response_code < 200) {
  4041. /* Unknown informational status code */
  4042. return "Information";
  4043. }
  4044. if (response_code >= 200 && response_code < 300) {
  4045. /* Unknown success code */
  4046. return "Success";
  4047. }
  4048. if (response_code >= 300 && response_code < 400) {
  4049. /* Unknown redirection code */
  4050. return "Redirection";
  4051. }
  4052. if (response_code >= 400 && response_code < 500) {
  4053. /* Unknown request error code */
  4054. return "Client Error";
  4055. }
  4056. if (response_code >= 500 && response_code < 600) {
  4057. /* Unknown server error code */
  4058. return "Server Error";
  4059. }
  4060. /* Response code not even within reasonable range */
  4061. return "";
  4062. }
  4063. }
  4064. static int
  4065. mg_send_http_error_impl(struct mg_connection *conn,
  4066. int status,
  4067. const char *fmt,
  4068. va_list args)
  4069. {
  4070. char errmsg_buf[MG_BUF_LEN];
  4071. va_list ap;
  4072. int has_body;
  4073. char date[64];
  4074. time_t curtime = time(NULL);
  4075. #if !defined(NO_FILESYSTEMS)
  4076. char path_buf[PATH_MAX];
  4077. int len, i, page_handler_found, scope, truncated;
  4078. const char *error_handler = NULL;
  4079. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4080. const char *error_page_file_ext, *tstr;
  4081. #endif /* NO_FILESYSTEMS */
  4082. int handled_by_callback = 0;
  4083. const char *status_text = mg_get_response_code_text(conn, status);
  4084. if ((conn == NULL) || (fmt == NULL)) {
  4085. return -2;
  4086. }
  4087. /* Set status (for log) */
  4088. conn->status_code = status;
  4089. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4090. has_body = ((status > 199) && (status != 204) && (status != 304));
  4091. /* Prepare message in buf, if required */
  4092. if (has_body
  4093. || (!conn->in_error_handler
  4094. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4095. /* Store error message in errmsg_buf */
  4096. va_copy(ap, args);
  4097. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4098. va_end(ap);
  4099. /* In a debug build, print all html errors */
  4100. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4101. }
  4102. /* If there is a http_error callback, call it.
  4103. * But don't do it recursively, if callback calls mg_send_http_error again.
  4104. */
  4105. if (!conn->in_error_handler
  4106. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4107. /* Mark in_error_handler to avoid recursion and call user callback. */
  4108. conn->in_error_handler = 1;
  4109. handled_by_callback =
  4110. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4111. == 0);
  4112. conn->in_error_handler = 0;
  4113. }
  4114. if (!handled_by_callback) {
  4115. /* Check for recursion */
  4116. if (conn->in_error_handler) {
  4117. DEBUG_TRACE(
  4118. "Recursion when handling error %u - fall back to default",
  4119. status);
  4120. #if !defined(NO_FILESYSTEMS)
  4121. } else {
  4122. /* Send user defined error pages, if defined */
  4123. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4124. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4125. page_handler_found = 0;
  4126. if (error_handler != NULL) {
  4127. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4128. switch (scope) {
  4129. case 1: /* Handler for specific error, e.g. 404 error */
  4130. mg_snprintf(conn,
  4131. &truncated,
  4132. path_buf,
  4133. sizeof(path_buf) - 32,
  4134. "%serror%03u.",
  4135. error_handler,
  4136. status);
  4137. break;
  4138. case 2: /* Handler for error group, e.g., 5xx error
  4139. * handler
  4140. * for all server errors (500-599) */
  4141. mg_snprintf(conn,
  4142. &truncated,
  4143. path_buf,
  4144. sizeof(path_buf) - 32,
  4145. "%serror%01uxx.",
  4146. error_handler,
  4147. status / 100);
  4148. break;
  4149. default: /* Handler for all errors */
  4150. mg_snprintf(conn,
  4151. &truncated,
  4152. path_buf,
  4153. sizeof(path_buf) - 32,
  4154. "%serror.",
  4155. error_handler);
  4156. break;
  4157. }
  4158. /* String truncation in buf may only occur if
  4159. * error_handler is too long. This string is
  4160. * from the config, not from a client. */
  4161. (void)truncated;
  4162. /* The following code is redundant, but it should avoid
  4163. * false positives in static source code analyzers and
  4164. * vulnerability scanners.
  4165. */
  4166. path_buf[sizeof(path_buf) - 32] = 0;
  4167. len = (int)strlen(path_buf);
  4168. if (len > (int)sizeof(path_buf) - 32) {
  4169. len = (int)sizeof(path_buf) - 32;
  4170. }
  4171. /* Start with the file extenstion from the configuration. */
  4172. tstr = strchr(error_page_file_ext, '.');
  4173. while (tstr) {
  4174. for (i = 1;
  4175. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4176. i++) {
  4177. /* buffer overrun is not possible here, since
  4178. * (i < 32) && (len < sizeof(path_buf) - 32)
  4179. * ==> (i + len) < sizeof(path_buf) */
  4180. path_buf[len + i - 1] = tstr[i];
  4181. }
  4182. /* buffer overrun is not possible here, since
  4183. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4184. * ==> (i + len) <= sizeof(path_buf) */
  4185. path_buf[len + i - 1] = 0;
  4186. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4187. DEBUG_TRACE("Check error page %s - found",
  4188. path_buf);
  4189. page_handler_found = 1;
  4190. break;
  4191. }
  4192. DEBUG_TRACE("Check error page %s - not found",
  4193. path_buf);
  4194. /* Continue with the next file extenstion from the
  4195. * configuration (if there is a next one). */
  4196. tstr = strchr(tstr + i, '.');
  4197. }
  4198. }
  4199. }
  4200. if (page_handler_found) {
  4201. conn->in_error_handler = 1;
  4202. handle_file_based_request(conn, path_buf, &error_page_file);
  4203. conn->in_error_handler = 0;
  4204. return 0;
  4205. }
  4206. #endif /* NO_FILESYSTEMS */
  4207. }
  4208. /* No custom error page. Send default error page. */
  4209. gmt_time_string(date, sizeof(date), &curtime);
  4210. conn->must_close = 1;
  4211. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4212. send_no_cache_header(conn);
  4213. send_additional_header(conn);
  4214. if (has_body) {
  4215. mg_printf(conn,
  4216. "%s",
  4217. "Content-Type: text/plain; charset=utf-8\r\n");
  4218. }
  4219. mg_printf(conn,
  4220. "Date: %s\r\n"
  4221. "Connection: close\r\n\r\n",
  4222. date);
  4223. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4224. if (has_body) {
  4225. /* For other errors, send a generic error message. */
  4226. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4227. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4228. } else {
  4229. /* No body allowed. Close the connection. */
  4230. DEBUG_TRACE("Error %i", status);
  4231. }
  4232. }
  4233. return 0;
  4234. }
  4235. int
  4236. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4237. {
  4238. va_list ap;
  4239. int ret;
  4240. va_start(ap, fmt);
  4241. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4242. va_end(ap);
  4243. return ret;
  4244. }
  4245. int
  4246. mg_send_http_ok(struct mg_connection *conn,
  4247. const char *mime_type,
  4248. long long content_length)
  4249. {
  4250. char date[64];
  4251. time_t curtime = time(NULL);
  4252. if ((mime_type == NULL) || (*mime_type == 0)) {
  4253. /* No content type defined: default to text/html */
  4254. mime_type = "text/html";
  4255. }
  4256. gmt_time_string(date, sizeof(date), &curtime);
  4257. mg_printf(conn,
  4258. "HTTP/1.1 200 OK\r\n"
  4259. "Content-Type: %s\r\n"
  4260. "Date: %s\r\n"
  4261. "Connection: %s\r\n",
  4262. mime_type,
  4263. date,
  4264. suggest_connection_header(conn));
  4265. send_no_cache_header(conn);
  4266. send_additional_header(conn);
  4267. if (content_length < 0) {
  4268. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4269. } else {
  4270. mg_printf(conn,
  4271. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4272. (uint64_t)content_length);
  4273. }
  4274. return 0;
  4275. }
  4276. int
  4277. mg_send_http_redirect(struct mg_connection *conn,
  4278. const char *target_url,
  4279. int redirect_code)
  4280. {
  4281. /* Send a 30x redirect response.
  4282. *
  4283. * Redirect types (status codes):
  4284. *
  4285. * Status | Perm/Temp | Method | Version
  4286. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4287. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4288. * 303 | temporary | always use GET | HTTP/1.1
  4289. * 307 | temporary | always keep method | HTTP/1.1
  4290. * 308 | permanent | always keep method | HTTP/1.1
  4291. */
  4292. const char *redirect_text;
  4293. int ret;
  4294. size_t content_len = 0;
  4295. char reply[MG_BUF_LEN];
  4296. /* In case redirect_code=0, use 307. */
  4297. if (redirect_code == 0) {
  4298. redirect_code = 307;
  4299. }
  4300. /* In case redirect_code is none of the above, return error. */
  4301. if ((redirect_code != 301) && (redirect_code != 302)
  4302. && (redirect_code != 303) && (redirect_code != 307)
  4303. && (redirect_code != 308)) {
  4304. /* Parameter error */
  4305. return -2;
  4306. }
  4307. /* Get proper text for response code */
  4308. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4309. /* If target_url is not defined, redirect to "/". */
  4310. if ((target_url == NULL) || (*target_url == 0)) {
  4311. target_url = "/";
  4312. }
  4313. #if defined(MG_SEND_REDIRECT_BODY)
  4314. /* TODO: condition name? */
  4315. /* Prepare a response body with a hyperlink.
  4316. *
  4317. * According to RFC2616 (and RFC1945 before):
  4318. * Unless the request method was HEAD, the entity of the
  4319. * response SHOULD contain a short hypertext note with a hyperlink to
  4320. * the new URI(s).
  4321. *
  4322. * However, this response body is not useful in M2M communication.
  4323. * Probably the original reason in the RFC was, clients not supporting
  4324. * a 30x HTTP redirect could still show the HTML page and let the user
  4325. * press the link. Since current browsers support 30x HTTP, the additional
  4326. * HTML body does not seem to make sense anymore.
  4327. *
  4328. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4329. * but it only notes:
  4330. * The server's response payload usually contains a short
  4331. * hypertext note with a hyperlink to the new URI(s).
  4332. *
  4333. * Deactivated by default. If you need the 30x body, set the define.
  4334. */
  4335. mg_snprintf(
  4336. conn,
  4337. NULL /* ignore truncation */,
  4338. reply,
  4339. sizeof(reply),
  4340. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4341. redirect_text,
  4342. target_url,
  4343. target_url);
  4344. content_len = strlen(reply);
  4345. #else
  4346. reply[0] = 0;
  4347. #endif
  4348. /* Do not send any additional header. For all other options,
  4349. * including caching, there are suitable defaults. */
  4350. ret = mg_printf(conn,
  4351. "HTTP/1.1 %i %s\r\n"
  4352. "Location: %s\r\n"
  4353. "Content-Length: %u\r\n"
  4354. "Connection: %s\r\n\r\n",
  4355. redirect_code,
  4356. redirect_text,
  4357. target_url,
  4358. (unsigned int)content_len,
  4359. suggest_connection_header(conn));
  4360. /* Send response body */
  4361. if (ret > 0) {
  4362. /* ... unless it is a HEAD request */
  4363. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4364. ret = mg_write(conn, reply, content_len);
  4365. }
  4366. }
  4367. return (ret > 0) ? ret : -1;
  4368. }
  4369. #if defined(_WIN32)
  4370. /* Create substitutes for POSIX functions in Win32. */
  4371. #if defined(GCC_DIAGNOSTIC)
  4372. /* Show no warning in case system functions are not used. */
  4373. #pragma GCC diagnostic push
  4374. #pragma GCC diagnostic ignored "-Wunused-function"
  4375. #endif
  4376. static int
  4377. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4378. {
  4379. (void)unused;
  4380. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4381. InitializeCriticalSection(&mutex->sec);
  4382. return 0;
  4383. }
  4384. static int
  4385. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4386. {
  4387. DeleteCriticalSection(&mutex->sec);
  4388. return 0;
  4389. }
  4390. static int
  4391. pthread_mutex_lock(pthread_mutex_t *mutex)
  4392. {
  4393. EnterCriticalSection(&mutex->sec);
  4394. return 0;
  4395. }
  4396. static int
  4397. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4398. {
  4399. LeaveCriticalSection(&mutex->sec);
  4400. return 0;
  4401. }
  4402. FUNCTION_MAY_BE_UNUSED
  4403. static int
  4404. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4405. {
  4406. (void)unused;
  4407. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4408. cv->waiting_thread = NULL;
  4409. return 0;
  4410. }
  4411. FUNCTION_MAY_BE_UNUSED
  4412. static int
  4413. pthread_cond_timedwait(pthread_cond_t *cv,
  4414. pthread_mutex_t *mutex,
  4415. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4416. {
  4417. struct mg_workerTLS **ptls,
  4418. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4419. int ok;
  4420. int64_t nsnow, nswaitabs, nswaitrel;
  4421. DWORD mswaitrel;
  4422. pthread_mutex_lock(&cv->threadIdSec);
  4423. /* Add this thread to cv's waiting list */
  4424. ptls = &cv->waiting_thread;
  4425. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4426. ;
  4427. tls->next_waiting_thread = NULL;
  4428. *ptls = tls;
  4429. pthread_mutex_unlock(&cv->threadIdSec);
  4430. if (abstime) {
  4431. nsnow = mg_get_current_time_ns();
  4432. nswaitabs =
  4433. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4434. nswaitrel = nswaitabs - nsnow;
  4435. if (nswaitrel < 0) {
  4436. nswaitrel = 0;
  4437. }
  4438. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4439. } else {
  4440. mswaitrel = (DWORD)INFINITE;
  4441. }
  4442. pthread_mutex_unlock(mutex);
  4443. ok = (WAIT_OBJECT_0
  4444. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4445. if (!ok) {
  4446. ok = 1;
  4447. pthread_mutex_lock(&cv->threadIdSec);
  4448. ptls = &cv->waiting_thread;
  4449. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4450. if (*ptls == tls) {
  4451. *ptls = tls->next_waiting_thread;
  4452. ok = 0;
  4453. break;
  4454. }
  4455. }
  4456. pthread_mutex_unlock(&cv->threadIdSec);
  4457. if (ok) {
  4458. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4459. (DWORD)INFINITE);
  4460. }
  4461. }
  4462. /* This thread has been removed from cv's waiting list */
  4463. pthread_mutex_lock(mutex);
  4464. return ok ? 0 : -1;
  4465. }
  4466. FUNCTION_MAY_BE_UNUSED
  4467. static int
  4468. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4469. {
  4470. return pthread_cond_timedwait(cv, mutex, NULL);
  4471. }
  4472. FUNCTION_MAY_BE_UNUSED
  4473. static int
  4474. pthread_cond_signal(pthread_cond_t *cv)
  4475. {
  4476. HANDLE wkup = NULL;
  4477. BOOL ok = FALSE;
  4478. pthread_mutex_lock(&cv->threadIdSec);
  4479. if (cv->waiting_thread) {
  4480. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4481. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4482. ok = SetEvent(wkup);
  4483. DEBUG_ASSERT(ok);
  4484. }
  4485. pthread_mutex_unlock(&cv->threadIdSec);
  4486. return ok ? 0 : 1;
  4487. }
  4488. FUNCTION_MAY_BE_UNUSED
  4489. static int
  4490. pthread_cond_broadcast(pthread_cond_t *cv)
  4491. {
  4492. pthread_mutex_lock(&cv->threadIdSec);
  4493. while (cv->waiting_thread) {
  4494. pthread_cond_signal(cv);
  4495. }
  4496. pthread_mutex_unlock(&cv->threadIdSec);
  4497. return 0;
  4498. }
  4499. FUNCTION_MAY_BE_UNUSED
  4500. static int
  4501. pthread_cond_destroy(pthread_cond_t *cv)
  4502. {
  4503. pthread_mutex_lock(&cv->threadIdSec);
  4504. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4505. pthread_mutex_unlock(&cv->threadIdSec);
  4506. pthread_mutex_destroy(&cv->threadIdSec);
  4507. return 0;
  4508. }
  4509. #if defined(ALTERNATIVE_QUEUE)
  4510. FUNCTION_MAY_BE_UNUSED
  4511. static void *
  4512. event_create(void)
  4513. {
  4514. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4515. }
  4516. FUNCTION_MAY_BE_UNUSED
  4517. static int
  4518. event_wait(void *eventhdl)
  4519. {
  4520. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4521. return (res == WAIT_OBJECT_0);
  4522. }
  4523. FUNCTION_MAY_BE_UNUSED
  4524. static int
  4525. event_signal(void *eventhdl)
  4526. {
  4527. return (int)SetEvent((HANDLE)eventhdl);
  4528. }
  4529. FUNCTION_MAY_BE_UNUSED
  4530. static void
  4531. event_destroy(void *eventhdl)
  4532. {
  4533. CloseHandle((HANDLE)eventhdl);
  4534. }
  4535. #endif
  4536. #if defined(GCC_DIAGNOSTIC)
  4537. /* Enable unused function warning again */
  4538. #pragma GCC diagnostic pop
  4539. #endif
  4540. /* For Windows, change all slashes to backslashes in path names. */
  4541. static void
  4542. change_slashes_to_backslashes(char *path)
  4543. {
  4544. int i;
  4545. for (i = 0; path[i] != '\0'; i++) {
  4546. if (path[i] == '/') {
  4547. path[i] = '\\';
  4548. }
  4549. /* remove double backslash (check i > 0 to preserve UNC paths,
  4550. * like \\server\file.txt) */
  4551. if ((i > 0) && (path[i] == '\\')) {
  4552. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4553. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4554. }
  4555. }
  4556. }
  4557. }
  4558. static int
  4559. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4560. {
  4561. int diff;
  4562. do {
  4563. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4564. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4565. s1++;
  4566. s2++;
  4567. } while ((diff == 0) && (s1[-1] != L'\0'));
  4568. return diff;
  4569. }
  4570. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4571. * wbuf and wbuf_len is a target buffer and its length. */
  4572. static void
  4573. path_to_unicode(const struct mg_connection *conn,
  4574. const char *path,
  4575. wchar_t *wbuf,
  4576. size_t wbuf_len)
  4577. {
  4578. char buf[PATH_MAX], buf2[PATH_MAX];
  4579. wchar_t wbuf2[W_PATH_MAX + 1];
  4580. DWORD long_len, err;
  4581. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4582. mg_strlcpy(buf, path, sizeof(buf));
  4583. change_slashes_to_backslashes(buf);
  4584. /* Convert to Unicode and back. If doubly-converted string does not
  4585. * match the original, something is fishy, reject. */
  4586. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4587. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4588. WideCharToMultiByte(
  4589. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4590. if (strcmp(buf, buf2) != 0) {
  4591. wbuf[0] = L'\0';
  4592. }
  4593. /* Windows file systems are not case sensitive, but you can still use
  4594. * uppercase and lowercase letters (on all modern file systems).
  4595. * The server can check if the URI uses the same upper/lowercase
  4596. * letters an the file system, effectively making Windows servers
  4597. * case sensitive (like Linux servers are). It is still not possible
  4598. * to use two files with the same name in different cases on Windows
  4599. * (like /a and /A) - this would be possible in Linux.
  4600. * As a default, Windows is not case sensitive, but the case sensitive
  4601. * file name check can be activated by an additional configuration. */
  4602. if (conn) {
  4603. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4604. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4605. "yes")) {
  4606. /* Use case sensitive compare function */
  4607. fcompare = wcscmp;
  4608. }
  4609. }
  4610. (void)conn; /* conn is currently unused */
  4611. #if !defined(_WIN32_WCE)
  4612. /* Only accept a full file path, not a Windows short (8.3) path. */
  4613. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4614. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4615. if (long_len == 0) {
  4616. err = GetLastError();
  4617. if (err == ERROR_FILE_NOT_FOUND) {
  4618. /* File does not exist. This is not always a problem here. */
  4619. return;
  4620. }
  4621. }
  4622. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4623. /* Short name is used. */
  4624. wbuf[0] = L'\0';
  4625. }
  4626. #else
  4627. (void)long_len;
  4628. (void)wbuf2;
  4629. (void)err;
  4630. if (strchr(path, '~')) {
  4631. wbuf[0] = L'\0';
  4632. }
  4633. #endif
  4634. }
  4635. #if !defined(NO_FILESYSTEMS)
  4636. static int
  4637. mg_stat(const struct mg_connection *conn,
  4638. const char *path,
  4639. struct mg_file_stat *filep)
  4640. {
  4641. wchar_t wbuf[W_PATH_MAX];
  4642. WIN32_FILE_ATTRIBUTE_DATA info;
  4643. time_t creation_time;
  4644. size_t len;
  4645. if (!filep) {
  4646. return 0;
  4647. }
  4648. memset(filep, 0, sizeof(*filep));
  4649. if (conn && is_file_in_memory(conn, path)) {
  4650. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4651. * memset */
  4652. /* Quick fix (for 1.9.x): */
  4653. /* mg_stat must fill all fields, also for files in memory */
  4654. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4655. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4656. filep->size = tmp_file.stat.size;
  4657. filep->location = 2;
  4658. /* TODO: for 1.10: restructure how files in memory are handled */
  4659. /* The "file in memory" feature is a candidate for deletion.
  4660. * Please join the discussion at
  4661. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4662. */
  4663. filep->last_modified = time(NULL); /* TODO */
  4664. /* last_modified = now ... assumes the file may change during
  4665. * runtime,
  4666. * so every mg_fopen call may return different data */
  4667. /* last_modified = conn->phys_ctx.start_time;
  4668. * May be used it the data does not change during runtime. This
  4669. * allows
  4670. * browser caching. Since we do not know, we have to assume the file
  4671. * in memory may change. */
  4672. return 1;
  4673. }
  4674. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4675. /* Windows happily opens files with some garbage at the end of file name.
  4676. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4677. * "a.cgi", despite one would expect an error back. */
  4678. len = strlen(path);
  4679. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4680. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4681. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4682. filep->last_modified =
  4683. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4684. info.ftLastWriteTime.dwHighDateTime);
  4685. /* On Windows, the file creation time can be higher than the
  4686. * modification time, e.g. when a file is copied.
  4687. * Since the Last-Modified timestamp is used for caching
  4688. * it should be based on the most recent timestamp. */
  4689. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4690. info.ftCreationTime.dwHighDateTime);
  4691. if (creation_time > filep->last_modified) {
  4692. filep->last_modified = creation_time;
  4693. }
  4694. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4695. return 1;
  4696. }
  4697. return 0;
  4698. }
  4699. #endif
  4700. static int
  4701. mg_remove(const struct mg_connection *conn, const char *path)
  4702. {
  4703. wchar_t wbuf[W_PATH_MAX];
  4704. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4705. return DeleteFileW(wbuf) ? 0 : -1;
  4706. }
  4707. static int
  4708. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4709. {
  4710. wchar_t wbuf[W_PATH_MAX];
  4711. (void)mode;
  4712. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4713. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4714. }
  4715. /* Create substitutes for POSIX functions in Win32. */
  4716. #if defined(GCC_DIAGNOSTIC)
  4717. /* Show no warning in case system functions are not used. */
  4718. #pragma GCC diagnostic push
  4719. #pragma GCC diagnostic ignored "-Wunused-function"
  4720. #endif
  4721. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4722. FUNCTION_MAY_BE_UNUSED
  4723. static DIR *
  4724. mg_opendir(const struct mg_connection *conn, const char *name)
  4725. {
  4726. DIR *dir = NULL;
  4727. wchar_t wpath[W_PATH_MAX];
  4728. DWORD attrs;
  4729. if (name == NULL) {
  4730. SetLastError(ERROR_BAD_ARGUMENTS);
  4731. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4732. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4733. } else {
  4734. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4735. attrs = GetFileAttributesW(wpath);
  4736. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4737. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4738. (void)wcscat(wpath, L"\\*");
  4739. dir->handle = FindFirstFileW(wpath, &dir->info);
  4740. dir->result.d_name[0] = '\0';
  4741. } else {
  4742. mg_free(dir);
  4743. dir = NULL;
  4744. }
  4745. }
  4746. return dir;
  4747. }
  4748. FUNCTION_MAY_BE_UNUSED
  4749. static int
  4750. mg_closedir(DIR *dir)
  4751. {
  4752. int result = 0;
  4753. if (dir != NULL) {
  4754. if (dir->handle != INVALID_HANDLE_VALUE)
  4755. result = FindClose(dir->handle) ? 0 : -1;
  4756. mg_free(dir);
  4757. } else {
  4758. result = -1;
  4759. SetLastError(ERROR_BAD_ARGUMENTS);
  4760. }
  4761. return result;
  4762. }
  4763. FUNCTION_MAY_BE_UNUSED
  4764. static struct dirent *
  4765. mg_readdir(DIR *dir)
  4766. {
  4767. struct dirent *result = 0;
  4768. if (dir) {
  4769. if (dir->handle != INVALID_HANDLE_VALUE) {
  4770. result = &dir->result;
  4771. (void)WideCharToMultiByte(CP_UTF8,
  4772. 0,
  4773. dir->info.cFileName,
  4774. -1,
  4775. result->d_name,
  4776. sizeof(result->d_name),
  4777. NULL,
  4778. NULL);
  4779. if (!FindNextFileW(dir->handle, &dir->info)) {
  4780. (void)FindClose(dir->handle);
  4781. dir->handle = INVALID_HANDLE_VALUE;
  4782. }
  4783. } else {
  4784. SetLastError(ERROR_FILE_NOT_FOUND);
  4785. }
  4786. } else {
  4787. SetLastError(ERROR_BAD_ARGUMENTS);
  4788. }
  4789. return result;
  4790. }
  4791. #if !defined(HAVE_POLL)
  4792. #undef POLLIN
  4793. #undef POLLPRI
  4794. #undef POLLOUT
  4795. #define POLLIN (1) /* Data ready - read will not block. */
  4796. #define POLLPRI (2) /* Priority data ready. */
  4797. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4798. FUNCTION_MAY_BE_UNUSED
  4799. static int
  4800. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4801. {
  4802. struct timeval tv;
  4803. fd_set rset;
  4804. fd_set wset;
  4805. unsigned int i;
  4806. int result;
  4807. SOCKET maxfd = 0;
  4808. memset(&tv, 0, sizeof(tv));
  4809. tv.tv_sec = milliseconds / 1000;
  4810. tv.tv_usec = (milliseconds % 1000) * 1000;
  4811. FD_ZERO(&rset);
  4812. FD_ZERO(&wset);
  4813. for (i = 0; i < n; i++) {
  4814. if (pfd[i].events & POLLIN) {
  4815. FD_SET(pfd[i].fd, &rset);
  4816. }
  4817. if (pfd[i].events & POLLOUT) {
  4818. FD_SET(pfd[i].fd, &wset);
  4819. }
  4820. pfd[i].revents = 0;
  4821. if (pfd[i].fd > maxfd) {
  4822. maxfd = pfd[i].fd;
  4823. }
  4824. }
  4825. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4826. for (i = 0; i < n; i++) {
  4827. if (FD_ISSET(pfd[i].fd, &rset)) {
  4828. pfd[i].revents |= POLLIN;
  4829. }
  4830. if (FD_ISSET(pfd[i].fd, &wset)) {
  4831. pfd[i].revents |= POLLOUT;
  4832. }
  4833. }
  4834. }
  4835. /* We should subtract the time used in select from remaining
  4836. * "milliseconds", in particular if called from mg_poll with a
  4837. * timeout quantum.
  4838. * Unfortunately, the remaining time is not stored in "tv" in all
  4839. * implementations, so the result in "tv" must be considered undefined.
  4840. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4841. return result;
  4842. }
  4843. #endif /* HAVE_POLL */
  4844. #if defined(GCC_DIAGNOSTIC)
  4845. /* Enable unused function warning again */
  4846. #pragma GCC diagnostic pop
  4847. #endif
  4848. static void
  4849. set_close_on_exec(SOCKET sock,
  4850. const struct mg_connection *conn /* may be null */,
  4851. struct mg_context *ctx /* may be null */)
  4852. {
  4853. (void)conn; /* Unused. */
  4854. (void)ctx;
  4855. #if defined(_WIN32_WCE)
  4856. (void)sock;
  4857. #else
  4858. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4859. #endif
  4860. }
  4861. int
  4862. mg_start_thread(mg_thread_func_t f, void *p)
  4863. {
  4864. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4865. /* Compile-time option to control stack size, e.g.
  4866. * -DUSE_STACK_SIZE=16384
  4867. */
  4868. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4869. == ((uintptr_t)(-1L)))
  4870. ? -1
  4871. : 0);
  4872. #else
  4873. return (
  4874. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4875. ? -1
  4876. : 0);
  4877. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4878. }
  4879. /* Start a thread storing the thread context. */
  4880. static int
  4881. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4882. void *p,
  4883. pthread_t *threadidptr)
  4884. {
  4885. uintptr_t uip;
  4886. HANDLE threadhandle;
  4887. int result = -1;
  4888. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4889. threadhandle = (HANDLE)uip;
  4890. if ((uip != 0) && (threadidptr != NULL)) {
  4891. *threadidptr = threadhandle;
  4892. result = 0;
  4893. }
  4894. return result;
  4895. }
  4896. /* Wait for a thread to finish. */
  4897. static int
  4898. mg_join_thread(pthread_t threadid)
  4899. {
  4900. int result;
  4901. DWORD dwevent;
  4902. result = -1;
  4903. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4904. if (dwevent == WAIT_FAILED) {
  4905. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4906. } else {
  4907. if (dwevent == WAIT_OBJECT_0) {
  4908. CloseHandle(threadid);
  4909. result = 0;
  4910. }
  4911. }
  4912. return result;
  4913. }
  4914. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4915. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4916. /* Create substitutes for POSIX functions in Win32. */
  4917. #if defined(GCC_DIAGNOSTIC)
  4918. /* Show no warning in case system functions are not used. */
  4919. #pragma GCC diagnostic push
  4920. #pragma GCC diagnostic ignored "-Wunused-function"
  4921. #endif
  4922. FUNCTION_MAY_BE_UNUSED
  4923. static HANDLE
  4924. dlopen(const char *dll_name, int flags)
  4925. {
  4926. wchar_t wbuf[W_PATH_MAX];
  4927. (void)flags;
  4928. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4929. return LoadLibraryW(wbuf);
  4930. }
  4931. FUNCTION_MAY_BE_UNUSED
  4932. static int
  4933. dlclose(void *handle)
  4934. {
  4935. int result;
  4936. if (FreeLibrary((HMODULE)handle) != 0) {
  4937. result = 0;
  4938. } else {
  4939. result = -1;
  4940. }
  4941. return result;
  4942. }
  4943. #if defined(GCC_DIAGNOSTIC)
  4944. /* Enable unused function warning again */
  4945. #pragma GCC diagnostic pop
  4946. #endif
  4947. #endif
  4948. #if !defined(NO_CGI)
  4949. #define SIGKILL (0)
  4950. static int
  4951. kill(pid_t pid, int sig_num)
  4952. {
  4953. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4954. (void)CloseHandle((HANDLE)pid);
  4955. return 0;
  4956. }
  4957. #if !defined(WNOHANG)
  4958. #define WNOHANG (1)
  4959. #endif
  4960. static pid_t
  4961. waitpid(pid_t pid, int *status, int flags)
  4962. {
  4963. DWORD timeout = INFINITE;
  4964. DWORD waitres;
  4965. (void)status; /* Currently not used by any client here */
  4966. if ((flags | WNOHANG) == WNOHANG) {
  4967. timeout = 0;
  4968. }
  4969. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4970. if (waitres == WAIT_OBJECT_0) {
  4971. return pid;
  4972. }
  4973. if (waitres == WAIT_TIMEOUT) {
  4974. return 0;
  4975. }
  4976. return (pid_t)-1;
  4977. }
  4978. static void
  4979. trim_trailing_whitespaces(char *s)
  4980. {
  4981. char *e = s + strlen(s);
  4982. while ((e > s) && isspace((unsigned char)e[-1])) {
  4983. *(--e) = '\0';
  4984. }
  4985. }
  4986. static pid_t
  4987. spawn_process(struct mg_connection *conn,
  4988. const char *prog,
  4989. char *envblk,
  4990. char *envp[],
  4991. int fdin[2],
  4992. int fdout[2],
  4993. int fderr[2],
  4994. const char *dir)
  4995. {
  4996. HANDLE me;
  4997. char *p, *interp;
  4998. char *interp_arg = 0;
  4999. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  5000. buf[PATH_MAX];
  5001. int truncated;
  5002. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5003. STARTUPINFOA si;
  5004. PROCESS_INFORMATION pi = {0};
  5005. (void)envp;
  5006. memset(&si, 0, sizeof(si));
  5007. si.cb = sizeof(si);
  5008. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5009. si.wShowWindow = SW_HIDE;
  5010. me = GetCurrentProcess();
  5011. DuplicateHandle(me,
  5012. (HANDLE)_get_osfhandle(fdin[0]),
  5013. me,
  5014. &si.hStdInput,
  5015. 0,
  5016. TRUE,
  5017. DUPLICATE_SAME_ACCESS);
  5018. DuplicateHandle(me,
  5019. (HANDLE)_get_osfhandle(fdout[1]),
  5020. me,
  5021. &si.hStdOutput,
  5022. 0,
  5023. TRUE,
  5024. DUPLICATE_SAME_ACCESS);
  5025. DuplicateHandle(me,
  5026. (HANDLE)_get_osfhandle(fderr[1]),
  5027. me,
  5028. &si.hStdError,
  5029. 0,
  5030. TRUE,
  5031. DUPLICATE_SAME_ACCESS);
  5032. /* Mark handles that should not be inherited. See
  5033. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5034. */
  5035. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5036. HANDLE_FLAG_INHERIT,
  5037. 0);
  5038. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5039. HANDLE_FLAG_INHERIT,
  5040. 0);
  5041. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5042. HANDLE_FLAG_INHERIT,
  5043. 0);
  5044. /* First check, if there is a CGI interpreter configured for all CGI
  5045. * scripts. */
  5046. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5047. if (interp != NULL) {
  5048. /* If there is a configured interpreter, check for additional arguments
  5049. */
  5050. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5051. } else {
  5052. /* Otherwise, the interpreter must be stated in the first line of the
  5053. * CGI script file, after a #! (shebang) mark. */
  5054. buf[0] = buf[1] = '\0';
  5055. /* Get the full script path */
  5056. mg_snprintf(
  5057. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5058. if (truncated) {
  5059. pi.hProcess = (pid_t)-1;
  5060. goto spawn_cleanup;
  5061. }
  5062. /* Open the script file, to read the first line */
  5063. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5064. #if defined(MG_USE_OPEN_FILE)
  5065. p = (char *)file.access.membuf;
  5066. #else
  5067. p = (char *)NULL;
  5068. #endif
  5069. /* Read the first line of the script into the buffer */
  5070. mg_fgets(buf, sizeof(buf), &file, &p);
  5071. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5072. buf[sizeof(buf) - 1] = '\0';
  5073. }
  5074. if ((buf[0] == '#') && (buf[1] == '!')) {
  5075. trim_trailing_whitespaces(buf + 2);
  5076. } else {
  5077. buf[2] = '\0';
  5078. }
  5079. interp = buf + 2;
  5080. }
  5081. if (interp[0] != '\0') {
  5082. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5083. interp = full_interp;
  5084. }
  5085. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5086. if (interp[0] != '\0') {
  5087. /* This is an interpreted script file. We must call the interpreter. */
  5088. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5089. mg_snprintf(conn,
  5090. &truncated,
  5091. cmdline,
  5092. sizeof(cmdline),
  5093. "\"%s\" %s \"%s\\%s\"",
  5094. interp,
  5095. interp_arg,
  5096. full_dir,
  5097. prog);
  5098. } else {
  5099. mg_snprintf(conn,
  5100. &truncated,
  5101. cmdline,
  5102. sizeof(cmdline),
  5103. "\"%s\" \"%s\\%s\"",
  5104. interp,
  5105. full_dir,
  5106. prog);
  5107. }
  5108. } else {
  5109. /* This is (probably) a compiled program. We call it directly. */
  5110. mg_snprintf(conn,
  5111. &truncated,
  5112. cmdline,
  5113. sizeof(cmdline),
  5114. "\"%s\\%s\"",
  5115. full_dir,
  5116. prog);
  5117. }
  5118. if (truncated) {
  5119. pi.hProcess = (pid_t)-1;
  5120. goto spawn_cleanup;
  5121. }
  5122. DEBUG_TRACE("Running [%s]", cmdline);
  5123. if (CreateProcessA(NULL,
  5124. cmdline,
  5125. NULL,
  5126. NULL,
  5127. TRUE,
  5128. CREATE_NEW_PROCESS_GROUP,
  5129. envblk,
  5130. NULL,
  5131. &si,
  5132. &pi)
  5133. == 0) {
  5134. mg_cry_internal(
  5135. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5136. pi.hProcess = (pid_t)-1;
  5137. /* goto spawn_cleanup; */
  5138. }
  5139. spawn_cleanup:
  5140. (void)CloseHandle(si.hStdOutput);
  5141. (void)CloseHandle(si.hStdError);
  5142. (void)CloseHandle(si.hStdInput);
  5143. if (pi.hThread != NULL) {
  5144. (void)CloseHandle(pi.hThread);
  5145. }
  5146. return (pid_t)pi.hProcess;
  5147. }
  5148. #endif /* !NO_CGI */
  5149. static int
  5150. set_blocking_mode(SOCKET sock)
  5151. {
  5152. unsigned long non_blocking = 0;
  5153. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5154. }
  5155. static int
  5156. set_non_blocking_mode(SOCKET sock)
  5157. {
  5158. unsigned long non_blocking = 1;
  5159. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5160. }
  5161. #else
  5162. #if !defined(NO_FILESYSTEMS)
  5163. static int
  5164. mg_stat(const struct mg_connection *conn,
  5165. const char *path,
  5166. struct mg_file_stat *filep)
  5167. {
  5168. struct stat st;
  5169. if (!filep) {
  5170. return 0;
  5171. }
  5172. memset(filep, 0, sizeof(*filep));
  5173. if (conn && is_file_in_memory(conn, path)) {
  5174. /* Quick fix (for 1.9.x): */
  5175. /* mg_stat must fill all fields, also for files in memory */
  5176. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5177. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5178. filep->size = tmp_file.stat.size;
  5179. filep->last_modified = time(NULL);
  5180. filep->location = 2;
  5181. /* TODO: remove legacy "files in memory" feature */
  5182. return 1;
  5183. }
  5184. if (0 == stat(path, &st)) {
  5185. filep->size = (uint64_t)(st.st_size);
  5186. filep->last_modified = st.st_mtime;
  5187. filep->is_directory = S_ISDIR(st.st_mode);
  5188. return 1;
  5189. }
  5190. return 0;
  5191. }
  5192. #endif /* NO_FILESYSTEMS */
  5193. static void
  5194. set_close_on_exec(int fd,
  5195. const struct mg_connection *conn /* may be null */,
  5196. struct mg_context *ctx /* may be null */)
  5197. {
  5198. #if defined(__ZEPHYR__)
  5199. (void)fd;
  5200. (void)conn;
  5201. (void)ctx;
  5202. #else
  5203. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5204. if (conn || ctx) {
  5205. struct mg_connection fc;
  5206. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5207. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5208. __func__,
  5209. strerror(ERRNO));
  5210. }
  5211. }
  5212. #endif
  5213. }
  5214. int
  5215. mg_start_thread(mg_thread_func_t func, void *param)
  5216. {
  5217. pthread_t thread_id;
  5218. pthread_attr_t attr;
  5219. int result;
  5220. (void)pthread_attr_init(&attr);
  5221. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5222. #if defined(__ZEPHYR__)
  5223. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5224. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5225. /* Compile-time option to control stack size,
  5226. * e.g. -DUSE_STACK_SIZE=16384 */
  5227. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5228. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5229. result = pthread_create(&thread_id, &attr, func, param);
  5230. pthread_attr_destroy(&attr);
  5231. return result;
  5232. }
  5233. /* Start a thread storing the thread context. */
  5234. static int
  5235. mg_start_thread_with_id(mg_thread_func_t func,
  5236. void *param,
  5237. pthread_t *threadidptr)
  5238. {
  5239. pthread_t thread_id;
  5240. pthread_attr_t attr;
  5241. int result;
  5242. (void)pthread_attr_init(&attr);
  5243. #if defined(__ZEPHYR__)
  5244. pthread_attr_setstack(&attr,
  5245. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5246. ZEPHYR_STACK_SIZE);
  5247. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5248. /* Compile-time option to control stack size,
  5249. * e.g. -DUSE_STACK_SIZE=16384 */
  5250. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5251. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5252. result = pthread_create(&thread_id, &attr, func, param);
  5253. pthread_attr_destroy(&attr);
  5254. if ((result == 0) && (threadidptr != NULL)) {
  5255. *threadidptr = thread_id;
  5256. }
  5257. return result;
  5258. }
  5259. /* Wait for a thread to finish. */
  5260. static int
  5261. mg_join_thread(pthread_t threadid)
  5262. {
  5263. int result;
  5264. result = pthread_join(threadid, NULL);
  5265. return result;
  5266. }
  5267. #if !defined(NO_CGI)
  5268. static pid_t
  5269. spawn_process(struct mg_connection *conn,
  5270. const char *prog,
  5271. char *envblk,
  5272. char *envp[],
  5273. int fdin[2],
  5274. int fdout[2],
  5275. int fderr[2],
  5276. const char *dir)
  5277. {
  5278. pid_t pid;
  5279. const char *interp;
  5280. (void)envblk;
  5281. if ((pid = fork()) == -1) {
  5282. /* Parent */
  5283. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5284. } else if (pid != 0) {
  5285. /* Make sure children close parent-side descriptors.
  5286. * The caller will close the child-side immediately. */
  5287. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5288. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5289. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5290. } else {
  5291. /* Child */
  5292. if (chdir(dir) != 0) {
  5293. mg_cry_internal(
  5294. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5295. } else if (dup2(fdin[0], 0) == -1) {
  5296. mg_cry_internal(conn,
  5297. "%s: dup2(%d, 0): %s",
  5298. __func__,
  5299. fdin[0],
  5300. strerror(ERRNO));
  5301. } else if (dup2(fdout[1], 1) == -1) {
  5302. mg_cry_internal(conn,
  5303. "%s: dup2(%d, 1): %s",
  5304. __func__,
  5305. fdout[1],
  5306. strerror(ERRNO));
  5307. } else if (dup2(fderr[1], 2) == -1) {
  5308. mg_cry_internal(conn,
  5309. "%s: dup2(%d, 2): %s",
  5310. __func__,
  5311. fderr[1],
  5312. strerror(ERRNO));
  5313. } else {
  5314. struct sigaction sa;
  5315. /* Keep stderr and stdout in two different pipes.
  5316. * Stdout will be sent back to the client,
  5317. * stderr should go into a server error log. */
  5318. (void)close(fdin[0]);
  5319. (void)close(fdout[1]);
  5320. (void)close(fderr[1]);
  5321. /* Close write end fdin and read end fdout and fderr */
  5322. (void)close(fdin[1]);
  5323. (void)close(fdout[0]);
  5324. (void)close(fderr[0]);
  5325. /* After exec, all signal handlers are restored to their default
  5326. * values, with one exception of SIGCHLD. According to
  5327. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5328. * will leave unchanged after exec if it was set to be ignored.
  5329. * Restore it to default action. */
  5330. memset(&sa, 0, sizeof(sa));
  5331. sa.sa_handler = SIG_DFL;
  5332. sigaction(SIGCHLD, &sa, NULL);
  5333. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5334. if (interp == NULL) {
  5335. /* no interpreter configured, call the programm directly */
  5336. (void)execle(prog, prog, NULL, envp);
  5337. mg_cry_internal(conn,
  5338. "%s: execle(%s): %s",
  5339. __func__,
  5340. prog,
  5341. strerror(ERRNO));
  5342. } else {
  5343. /* call the configured interpreter */
  5344. const char *interp_args =
  5345. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5346. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5347. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5348. } else {
  5349. (void)execle(interp, interp, prog, NULL, envp);
  5350. }
  5351. mg_cry_internal(conn,
  5352. "%s: execle(%s %s): %s",
  5353. __func__,
  5354. interp,
  5355. prog,
  5356. strerror(ERRNO));
  5357. }
  5358. }
  5359. exit(EXIT_FAILURE);
  5360. }
  5361. return pid;
  5362. }
  5363. #endif /* !NO_CGI */
  5364. static int
  5365. set_non_blocking_mode(SOCKET sock)
  5366. {
  5367. int flags = fcntl(sock, F_GETFL, 0);
  5368. if (flags < 0) {
  5369. return -1;
  5370. }
  5371. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5372. return -1;
  5373. }
  5374. return 0;
  5375. }
  5376. static int
  5377. set_blocking_mode(SOCKET sock)
  5378. {
  5379. int flags = fcntl(sock, F_GETFL, 0);
  5380. if (flags < 0) {
  5381. return -1;
  5382. }
  5383. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5384. return -1;
  5385. }
  5386. return 0;
  5387. }
  5388. #endif /* _WIN32 / else */
  5389. /* End of initial operating system specific define block. */
  5390. /* Get a random number (independent of C rand function) */
  5391. static uint64_t
  5392. get_random(void)
  5393. {
  5394. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5395. static uint64_t lcg = 0; /* Linear congruential generator */
  5396. uint64_t now = mg_get_current_time_ns();
  5397. if (lfsr == 0) {
  5398. /* lfsr will be only 0 if has not been initialized,
  5399. * so this code is called only once. */
  5400. lfsr = mg_get_current_time_ns();
  5401. lcg = mg_get_current_time_ns();
  5402. } else {
  5403. /* Get the next step of both random number generators. */
  5404. lfsr = (lfsr >> 1)
  5405. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5406. << 63);
  5407. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5408. }
  5409. /* Combining two pseudo-random number generators and a high resolution
  5410. * part
  5411. * of the current server time will make it hard (impossible?) to guess
  5412. * the
  5413. * next number. */
  5414. return (lfsr ^ lcg ^ now);
  5415. }
  5416. static int
  5417. mg_poll(struct mg_pollfd *pfd,
  5418. unsigned int n,
  5419. int milliseconds,
  5420. stop_flag_t *stop_flag)
  5421. {
  5422. /* Call poll, but only for a maximum time of a few seconds.
  5423. * This will allow to stop the server after some seconds, instead
  5424. * of having to wait for a long socket timeout. */
  5425. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5426. do {
  5427. int result;
  5428. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5429. /* Shut down signal */
  5430. return -2;
  5431. }
  5432. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5433. ms_now = milliseconds;
  5434. }
  5435. result = poll(pfd, n, ms_now);
  5436. if (result != 0) {
  5437. /* Poll returned either success (1) or error (-1).
  5438. * Forward both to the caller. */
  5439. return result;
  5440. }
  5441. /* Poll returned timeout (0). */
  5442. if (milliseconds > 0) {
  5443. milliseconds -= ms_now;
  5444. }
  5445. } while (milliseconds != 0);
  5446. /* timeout: return 0 */
  5447. return 0;
  5448. }
  5449. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5450. * descriptor.
  5451. * Return value:
  5452. * >=0 .. number of bytes successfully written
  5453. * -1 .. timeout
  5454. * -2 .. error
  5455. */
  5456. static int
  5457. push_inner(struct mg_context *ctx,
  5458. FILE *fp,
  5459. SOCKET sock,
  5460. SSL *ssl,
  5461. const char *buf,
  5462. int len,
  5463. double timeout)
  5464. {
  5465. uint64_t start = 0, now = 0, timeout_ns = 0;
  5466. int n, err;
  5467. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5468. #if defined(_WIN32)
  5469. typedef int len_t;
  5470. #else
  5471. typedef size_t len_t;
  5472. #endif
  5473. if (timeout > 0) {
  5474. now = mg_get_current_time_ns();
  5475. start = now;
  5476. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5477. }
  5478. if (ctx == NULL) {
  5479. return -2;
  5480. }
  5481. #if defined(NO_SSL)
  5482. if (ssl) {
  5483. return -2;
  5484. }
  5485. #endif
  5486. /* Try to read until it succeeds, fails, times out, or the server
  5487. * shuts down. */
  5488. for (;;) {
  5489. #if !defined(NO_SSL)
  5490. if (ssl != NULL) {
  5491. ERR_clear_error();
  5492. n = SSL_write(ssl, buf, len);
  5493. if (n <= 0) {
  5494. err = SSL_get_error(ssl, n);
  5495. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5496. err = ERRNO;
  5497. } else if ((err == SSL_ERROR_WANT_READ)
  5498. || (err == SSL_ERROR_WANT_WRITE)) {
  5499. n = 0;
  5500. } else {
  5501. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5502. ERR_clear_error();
  5503. return -2;
  5504. }
  5505. ERR_clear_error();
  5506. } else {
  5507. err = 0;
  5508. }
  5509. } else
  5510. #endif
  5511. if (fp != NULL) {
  5512. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5513. if (ferror(fp)) {
  5514. n = -1;
  5515. err = ERRNO;
  5516. } else {
  5517. err = 0;
  5518. }
  5519. } else {
  5520. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5521. err = (n < 0) ? ERRNO : 0;
  5522. #if defined(_WIN32)
  5523. if (err == WSAEWOULDBLOCK) {
  5524. err = 0;
  5525. n = 0;
  5526. }
  5527. #else
  5528. if (err == EWOULDBLOCK) {
  5529. err = 0;
  5530. n = 0;
  5531. }
  5532. #endif
  5533. if (n < 0) {
  5534. /* shutdown of the socket at client side */
  5535. return -2;
  5536. }
  5537. }
  5538. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5539. return -2;
  5540. }
  5541. if ((n > 0) || ((n == 0) && (len == 0))) {
  5542. /* some data has been read, or no data was requested */
  5543. return n;
  5544. }
  5545. if (n < 0) {
  5546. /* socket error - check errno */
  5547. DEBUG_TRACE("send() failed, error %d", err);
  5548. /* TODO (mid): error handling depending on the error code.
  5549. * These codes are different between Windows and Linux.
  5550. * Currently there is no problem with failing send calls,
  5551. * if there is a reproducible situation, it should be
  5552. * investigated in detail.
  5553. */
  5554. return -2;
  5555. }
  5556. /* Only in case n=0 (timeout), repeat calling the write function */
  5557. /* If send failed, wait before retry */
  5558. if (fp != NULL) {
  5559. /* For files, just wait a fixed time.
  5560. * Maybe it helps, maybe not. */
  5561. mg_sleep(5);
  5562. } else {
  5563. /* For sockets, wait for the socket using poll */
  5564. struct mg_pollfd pfd[1];
  5565. int pollres;
  5566. pfd[0].fd = sock;
  5567. pfd[0].events = POLLOUT;
  5568. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5569. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5570. return -2;
  5571. }
  5572. if (pollres > 0) {
  5573. continue;
  5574. }
  5575. }
  5576. if (timeout > 0) {
  5577. now = mg_get_current_time_ns();
  5578. if ((now - start) > timeout_ns) {
  5579. /* Timeout */
  5580. break;
  5581. }
  5582. }
  5583. }
  5584. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5585. used */
  5586. return -1;
  5587. }
  5588. static int
  5589. push_all(struct mg_context *ctx,
  5590. FILE *fp,
  5591. SOCKET sock,
  5592. SSL *ssl,
  5593. const char *buf,
  5594. int len)
  5595. {
  5596. double timeout = -1.0;
  5597. int n, nwritten = 0;
  5598. if (ctx == NULL) {
  5599. return -1;
  5600. }
  5601. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5602. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5603. }
  5604. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5605. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5606. if (n < 0) {
  5607. if (nwritten == 0) {
  5608. nwritten = -1; /* Propagate the error */
  5609. }
  5610. break;
  5611. } else if (n == 0) {
  5612. break; /* No more data to write */
  5613. } else {
  5614. nwritten += n;
  5615. len -= n;
  5616. }
  5617. }
  5618. return nwritten;
  5619. }
  5620. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5621. * Return value:
  5622. * >=0 .. number of bytes successfully read
  5623. * -1 .. timeout
  5624. * -2 .. error
  5625. */
  5626. static int
  5627. pull_inner(FILE *fp,
  5628. struct mg_connection *conn,
  5629. char *buf,
  5630. int len,
  5631. double timeout)
  5632. {
  5633. int nread, err = 0;
  5634. #if defined(_WIN32)
  5635. typedef int len_t;
  5636. #else
  5637. typedef size_t len_t;
  5638. #endif
  5639. /* We need an additional wait loop around this, because in some cases
  5640. * with TLSwe may get data from the socket but not from SSL_read.
  5641. * In this case we need to repeat at least once.
  5642. */
  5643. if (fp != NULL) {
  5644. #if !defined(_WIN32_WCE)
  5645. /* Use read() instead of fread(), because if we're reading from the
  5646. * CGI pipe, fread() may block until IO buffer is filled up. We
  5647. * cannot afford to block and must pass all read bytes immediately
  5648. * to the client. */
  5649. nread = (int)read(fileno(fp), buf, (size_t)len);
  5650. #else
  5651. /* WinCE does not support CGI pipes */
  5652. nread = (int)fread(buf, 1, (size_t)len, fp);
  5653. #endif
  5654. err = (nread < 0) ? ERRNO : 0;
  5655. if ((nread == 0) && (len > 0)) {
  5656. /* Should get data, but got EOL */
  5657. return -2;
  5658. }
  5659. #if !defined(NO_SSL)
  5660. } else if (conn->ssl != NULL) {
  5661. int ssl_pending;
  5662. struct mg_pollfd pfd[1];
  5663. int pollres;
  5664. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5665. /* We already know there is no more data buffered in conn->buf
  5666. * but there is more available in the SSL layer. So don't poll
  5667. * conn->client.sock yet. */
  5668. if (ssl_pending > len) {
  5669. ssl_pending = len;
  5670. }
  5671. pollres = 1;
  5672. } else {
  5673. pfd[0].fd = conn->client.sock;
  5674. pfd[0].events = POLLIN;
  5675. pollres = mg_poll(pfd,
  5676. 1,
  5677. (int)(timeout * 1000.0),
  5678. &(conn->phys_ctx->stop_flag));
  5679. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5680. return -2;
  5681. }
  5682. }
  5683. if (pollres > 0) {
  5684. ERR_clear_error();
  5685. nread = SSL_read(conn->ssl, buf,
  5686. (ssl_pending > 0) ? ssl_pending : len);
  5687. if (nread <= 0) {
  5688. err = SSL_get_error(conn->ssl, nread);
  5689. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5690. err = ERRNO;
  5691. } else if ((err == SSL_ERROR_WANT_READ)
  5692. || (err == SSL_ERROR_WANT_WRITE)) {
  5693. nread = 0;
  5694. } else {
  5695. /* All errors should return -2 */
  5696. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5697. ERR_clear_error();
  5698. return -2;
  5699. }
  5700. ERR_clear_error();
  5701. } else {
  5702. err = 0;
  5703. }
  5704. } else if (pollres < 0) {
  5705. /* Error */
  5706. return -2;
  5707. } else {
  5708. /* pollres = 0 means timeout */
  5709. nread = 0;
  5710. }
  5711. #endif
  5712. } else {
  5713. struct mg_pollfd pfd[1];
  5714. int pollres;
  5715. pfd[0].fd = conn->client.sock;
  5716. pfd[0].events = POLLIN;
  5717. pollres = mg_poll(pfd,
  5718. 1,
  5719. (int)(timeout * 1000.0),
  5720. &(conn->phys_ctx->stop_flag));
  5721. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5722. return -2;
  5723. }
  5724. if (pollres > 0) {
  5725. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5726. err = (nread < 0) ? ERRNO : 0;
  5727. if (nread <= 0) {
  5728. /* shutdown of the socket at client side */
  5729. return -2;
  5730. }
  5731. } else if (pollres < 0) {
  5732. /* error callint poll */
  5733. return -2;
  5734. } else {
  5735. /* pollres = 0 means timeout */
  5736. nread = 0;
  5737. }
  5738. }
  5739. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5740. return -2;
  5741. }
  5742. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5743. /* some data has been read, or no data was requested */
  5744. return nread;
  5745. }
  5746. if (nread < 0) {
  5747. /* socket error - check errno */
  5748. #if defined(_WIN32)
  5749. if (err == WSAEWOULDBLOCK) {
  5750. /* TODO (low): check if this is still required */
  5751. /* standard case if called from close_socket_gracefully */
  5752. return -2;
  5753. } else if (err == WSAETIMEDOUT) {
  5754. /* TODO (low): check if this is still required */
  5755. /* timeout is handled by the while loop */
  5756. return 0;
  5757. } else if (err == WSAECONNABORTED) {
  5758. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5759. return -2;
  5760. } else {
  5761. DEBUG_TRACE("recv() failed, error %d", err);
  5762. return -2;
  5763. }
  5764. #else
  5765. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5766. * if the timeout is reached and if the socket was set to non-
  5767. * blocking in close_socket_gracefully, so we can not distinguish
  5768. * here. We have to wait for the timeout in both cases for now.
  5769. */
  5770. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5771. /* TODO (low): check if this is still required */
  5772. /* EAGAIN/EWOULDBLOCK:
  5773. * standard case if called from close_socket_gracefully
  5774. * => should return -1 */
  5775. /* or timeout occurred
  5776. * => the code must stay in the while loop */
  5777. /* EINTR can be generated on a socket with a timeout set even
  5778. * when SA_RESTART is effective for all relevant signals
  5779. * (see signal(7)).
  5780. * => stay in the while loop */
  5781. } else {
  5782. DEBUG_TRACE("recv() failed, error %d", err);
  5783. return -2;
  5784. }
  5785. #endif
  5786. }
  5787. /* Timeout occurred, but no data available. */
  5788. return -1;
  5789. }
  5790. static int
  5791. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5792. {
  5793. int n, nread = 0;
  5794. double timeout = -1.0;
  5795. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5796. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5797. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5798. }
  5799. if (timeout >= 0.0) {
  5800. start_time = mg_get_current_time_ns();
  5801. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5802. }
  5803. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5804. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5805. if (n == -2) {
  5806. if (nread == 0) {
  5807. nread = -1; /* Propagate the error */
  5808. }
  5809. break;
  5810. } else if (n == -1) {
  5811. /* timeout */
  5812. if (timeout >= 0.0) {
  5813. now = mg_get_current_time_ns();
  5814. if ((now - start_time) <= timeout_ns) {
  5815. continue;
  5816. }
  5817. }
  5818. break;
  5819. } else if (n == 0) {
  5820. break; /* No more data to read */
  5821. } else {
  5822. nread += n;
  5823. len -= n;
  5824. }
  5825. }
  5826. return nread;
  5827. }
  5828. static void
  5829. discard_unread_request_data(struct mg_connection *conn)
  5830. {
  5831. char buf[MG_BUF_LEN];
  5832. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5833. ;
  5834. }
  5835. static int
  5836. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5837. {
  5838. int64_t content_len, n, buffered_len, nread;
  5839. int64_t len64 =
  5840. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5841. * int, we may not read more
  5842. * bytes */
  5843. const char *body;
  5844. if (conn == NULL) {
  5845. return 0;
  5846. }
  5847. /* If Content-Length is not set for a response with body data,
  5848. * we do not know in advance how much data should be read. */
  5849. content_len = conn->content_len;
  5850. if (content_len < 0) {
  5851. /* The body data is completed when the connection is closed. */
  5852. content_len = INT64_MAX;
  5853. }
  5854. nread = 0;
  5855. if (conn->consumed_content < content_len) {
  5856. /* Adjust number of bytes to read. */
  5857. int64_t left_to_read = content_len - conn->consumed_content;
  5858. if (left_to_read < len64) {
  5859. /* Do not read more than the total content length of the
  5860. * request.
  5861. */
  5862. len64 = left_to_read;
  5863. }
  5864. /* Return buffered data */
  5865. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5866. - conn->consumed_content;
  5867. if (buffered_len > 0) {
  5868. if (len64 < buffered_len) {
  5869. buffered_len = len64;
  5870. }
  5871. body = conn->buf + conn->request_len + conn->consumed_content;
  5872. memcpy(buf, body, (size_t)buffered_len);
  5873. len64 -= buffered_len;
  5874. conn->consumed_content += buffered_len;
  5875. nread += buffered_len;
  5876. buf = (char *)buf + buffered_len;
  5877. }
  5878. /* We have returned all buffered data. Read new data from the remote
  5879. * socket.
  5880. */
  5881. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5882. conn->consumed_content += n;
  5883. nread += n;
  5884. } else {
  5885. nread = ((nread > 0) ? nread : n);
  5886. }
  5887. }
  5888. return (int)nread;
  5889. }
  5890. int
  5891. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5892. {
  5893. if (len > INT_MAX) {
  5894. len = INT_MAX;
  5895. }
  5896. if (conn == NULL) {
  5897. return 0;
  5898. }
  5899. if (conn->is_chunked) {
  5900. size_t all_read = 0;
  5901. while (len > 0) {
  5902. if (conn->is_chunked >= 3) {
  5903. /* No more data left to read */
  5904. return 0;
  5905. }
  5906. if (conn->is_chunked != 1) {
  5907. /* Has error */
  5908. return -1;
  5909. }
  5910. if (conn->consumed_content != conn->content_len) {
  5911. /* copy from the current chunk */
  5912. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5913. if (read_ret < 1) {
  5914. /* read error */
  5915. conn->is_chunked = 2;
  5916. return -1;
  5917. }
  5918. all_read += (size_t)read_ret;
  5919. len -= (size_t)read_ret;
  5920. if (conn->consumed_content == conn->content_len) {
  5921. /* Add data bytes in the current chunk have been read,
  5922. * so we are expecting \r\n now. */
  5923. char x[2];
  5924. conn->content_len += 2;
  5925. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5926. || (x[1] != '\n')) {
  5927. /* Protocol violation */
  5928. conn->is_chunked = 2;
  5929. return -1;
  5930. }
  5931. }
  5932. } else {
  5933. /* fetch a new chunk */
  5934. size_t i;
  5935. char lenbuf[64];
  5936. char *end = NULL;
  5937. unsigned long chunkSize = 0;
  5938. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5939. conn->content_len++;
  5940. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5941. lenbuf[i] = 0;
  5942. }
  5943. if ((i > 0) && (lenbuf[i] == '\r')
  5944. && (lenbuf[i - 1] != '\r')) {
  5945. continue;
  5946. }
  5947. if ((i > 1) && (lenbuf[i] == '\n')
  5948. && (lenbuf[i - 1] == '\r')) {
  5949. lenbuf[i + 1] = 0;
  5950. chunkSize = strtoul(lenbuf, &end, 16);
  5951. if (chunkSize == 0) {
  5952. /* regular end of content */
  5953. conn->is_chunked = 3;
  5954. }
  5955. break;
  5956. }
  5957. if (!isxdigit((unsigned char)lenbuf[i])) {
  5958. /* illegal character for chunk length */
  5959. conn->is_chunked = 2;
  5960. return -1;
  5961. }
  5962. }
  5963. if ((end == NULL) || (*end != '\r')) {
  5964. /* chunksize not set correctly */
  5965. conn->is_chunked = 2;
  5966. return -1;
  5967. }
  5968. if (chunkSize == 0) {
  5969. /* try discarding trailer for keep-alive */
  5970. conn->content_len += 2;
  5971. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5972. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5973. conn->is_chunked = 4;
  5974. }
  5975. break;
  5976. }
  5977. /* append a new chunk */
  5978. conn->content_len += (int64_t)chunkSize;
  5979. }
  5980. }
  5981. return (int)all_read;
  5982. }
  5983. return mg_read_inner(conn, buf, len);
  5984. }
  5985. int
  5986. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5987. {
  5988. time_t now;
  5989. int n, total, allowed;
  5990. if (conn == NULL) {
  5991. return 0;
  5992. }
  5993. if (len > INT_MAX) {
  5994. return -1;
  5995. }
  5996. if (conn->throttle > 0) {
  5997. if ((now = time(NULL)) != conn->last_throttle_time) {
  5998. conn->last_throttle_time = now;
  5999. conn->last_throttle_bytes = 0;
  6000. }
  6001. allowed = conn->throttle - conn->last_throttle_bytes;
  6002. if (allowed > (int)len) {
  6003. allowed = (int)len;
  6004. }
  6005. if ((total = push_all(conn->phys_ctx,
  6006. NULL,
  6007. conn->client.sock,
  6008. conn->ssl,
  6009. (const char *)buf,
  6010. allowed))
  6011. == allowed) {
  6012. buf = (const char *)buf + total;
  6013. conn->last_throttle_bytes += total;
  6014. while ((total < (int)len)
  6015. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6016. allowed = (conn->throttle > ((int)len - total))
  6017. ? (int)len - total
  6018. : conn->throttle;
  6019. if ((n = push_all(conn->phys_ctx,
  6020. NULL,
  6021. conn->client.sock,
  6022. conn->ssl,
  6023. (const char *)buf,
  6024. allowed))
  6025. != allowed) {
  6026. break;
  6027. }
  6028. sleep(1);
  6029. conn->last_throttle_bytes = allowed;
  6030. conn->last_throttle_time = time(NULL);
  6031. buf = (const char *)buf + n;
  6032. total += n;
  6033. }
  6034. }
  6035. } else {
  6036. total = push_all(conn->phys_ctx,
  6037. NULL,
  6038. conn->client.sock,
  6039. conn->ssl,
  6040. (const char *)buf,
  6041. (int)len);
  6042. }
  6043. if (total > 0) {
  6044. conn->num_bytes_sent += total;
  6045. }
  6046. return total;
  6047. }
  6048. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6049. int
  6050. mg_send_chunk(struct mg_connection *conn,
  6051. const char *chunk,
  6052. unsigned int chunk_len)
  6053. {
  6054. char lenbuf[16];
  6055. size_t lenbuf_len;
  6056. int ret;
  6057. int t;
  6058. /* First store the length information in a text buffer. */
  6059. sprintf(lenbuf, "%x\r\n", chunk_len);
  6060. lenbuf_len = strlen(lenbuf);
  6061. /* Then send length information, chunk and terminating \r\n. */
  6062. ret = mg_write(conn, lenbuf, lenbuf_len);
  6063. if (ret != (int)lenbuf_len) {
  6064. return -1;
  6065. }
  6066. t = ret;
  6067. ret = mg_write(conn, chunk, chunk_len);
  6068. if (ret != (int)chunk_len) {
  6069. return -1;
  6070. }
  6071. t += ret;
  6072. ret = mg_write(conn, "\r\n", 2);
  6073. if (ret != 2) {
  6074. return -1;
  6075. }
  6076. t += ret;
  6077. return t;
  6078. }
  6079. #if defined(GCC_DIAGNOSTIC)
  6080. /* This block forwards format strings to printf implementations,
  6081. * so we need to disable the format-nonliteral warning. */
  6082. #pragma GCC diagnostic push
  6083. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6084. #endif
  6085. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6086. static int
  6087. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6088. {
  6089. va_list ap_copy;
  6090. size_t size = MG_BUF_LEN / 4;
  6091. int len = -1;
  6092. *buf = NULL;
  6093. while (len < 0) {
  6094. if (*buf) {
  6095. mg_free(*buf);
  6096. }
  6097. size *= 4;
  6098. *buf = (char *)mg_malloc(size);
  6099. if (!*buf) {
  6100. break;
  6101. }
  6102. va_copy(ap_copy, ap);
  6103. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6104. va_end(ap_copy);
  6105. (*buf)[size - 1] = 0;
  6106. }
  6107. return len;
  6108. }
  6109. /* Print message to buffer. If buffer is large enough to hold the message,
  6110. * return buffer. If buffer is to small, allocate large enough buffer on
  6111. * heap,
  6112. * and return allocated buffer. */
  6113. static int
  6114. alloc_vprintf(char **out_buf,
  6115. char *prealloc_buf,
  6116. size_t prealloc_size,
  6117. const char *fmt,
  6118. va_list ap)
  6119. {
  6120. va_list ap_copy;
  6121. int len;
  6122. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6123. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6124. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6125. * Therefore, we make two passes: on first pass, get required message
  6126. * length.
  6127. * On second pass, actually print the message. */
  6128. va_copy(ap_copy, ap);
  6129. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6130. va_end(ap_copy);
  6131. if (len < 0) {
  6132. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6133. * Switch to alternative code path that uses incremental
  6134. * allocations.
  6135. */
  6136. va_copy(ap_copy, ap);
  6137. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6138. va_end(ap_copy);
  6139. } else if ((size_t)(len) >= prealloc_size) {
  6140. /* The pre-allocated buffer not large enough. */
  6141. /* Allocate a new buffer. */
  6142. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6143. if (!*out_buf) {
  6144. /* Allocation failed. Return -1 as "out of memory" error. */
  6145. return -1;
  6146. }
  6147. /* Buffer allocation successful. Store the string there. */
  6148. va_copy(ap_copy, ap);
  6149. IGNORE_UNUSED_RESULT(
  6150. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6151. va_end(ap_copy);
  6152. } else {
  6153. /* The pre-allocated buffer is large enough.
  6154. * Use it to store the string and return the address. */
  6155. va_copy(ap_copy, ap);
  6156. IGNORE_UNUSED_RESULT(
  6157. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6158. va_end(ap_copy);
  6159. *out_buf = prealloc_buf;
  6160. }
  6161. return len;
  6162. }
  6163. #if defined(GCC_DIAGNOSTIC)
  6164. /* Enable format-nonliteral warning again. */
  6165. #pragma GCC diagnostic pop
  6166. #endif
  6167. static int
  6168. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6169. {
  6170. char mem[MG_BUF_LEN];
  6171. char *buf = NULL;
  6172. int len;
  6173. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6174. len = mg_write(conn, buf, (size_t)len);
  6175. }
  6176. if (buf != mem) {
  6177. mg_free(buf);
  6178. }
  6179. return len;
  6180. }
  6181. int
  6182. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6183. {
  6184. va_list ap;
  6185. int result;
  6186. va_start(ap, fmt);
  6187. result = mg_vprintf(conn, fmt, ap);
  6188. va_end(ap);
  6189. return result;
  6190. }
  6191. int
  6192. mg_url_decode(const char *src,
  6193. int src_len,
  6194. char *dst,
  6195. int dst_len,
  6196. int is_form_url_encoded)
  6197. {
  6198. int i, j, a, b;
  6199. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6200. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6201. if ((i < src_len - 2) && (src[i] == '%')
  6202. && isxdigit((unsigned char)src[i + 1])
  6203. && isxdigit((unsigned char)src[i + 2])) {
  6204. a = tolower((unsigned char)src[i + 1]);
  6205. b = tolower((unsigned char)src[i + 2]);
  6206. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6207. i += 2;
  6208. } else if (is_form_url_encoded && (src[i] == '+')) {
  6209. dst[j] = ' ';
  6210. } else {
  6211. dst[j] = src[i];
  6212. }
  6213. }
  6214. dst[j] = '\0'; /* Null-terminate the destination */
  6215. return (i >= src_len) ? j : -1;
  6216. }
  6217. /* form url decoding of an entire string */
  6218. static void
  6219. url_decode_in_place(char *buf)
  6220. {
  6221. int len = (int)strlen(buf);
  6222. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6223. }
  6224. int
  6225. mg_get_var(const char *data,
  6226. size_t data_len,
  6227. const char *name,
  6228. char *dst,
  6229. size_t dst_len)
  6230. {
  6231. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6232. }
  6233. int
  6234. mg_get_var2(const char *data,
  6235. size_t data_len,
  6236. const char *name,
  6237. char *dst,
  6238. size_t dst_len,
  6239. size_t occurrence)
  6240. {
  6241. const char *p, *e, *s;
  6242. size_t name_len;
  6243. int len;
  6244. if ((dst == NULL) || (dst_len == 0)) {
  6245. len = -2;
  6246. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6247. len = -1;
  6248. dst[0] = '\0';
  6249. } else {
  6250. name_len = strlen(name);
  6251. e = data + data_len;
  6252. len = -1;
  6253. dst[0] = '\0';
  6254. /* data is "var1=val1&var2=val2...". Find variable first */
  6255. for (p = data; p + name_len < e; p++) {
  6256. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6257. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6258. /* Point p to variable value */
  6259. p += name_len + 1;
  6260. /* Point s to the end of the value */
  6261. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6262. if (s == NULL) {
  6263. s = e;
  6264. }
  6265. DEBUG_ASSERT(s >= p);
  6266. if (s < p) {
  6267. return -3;
  6268. }
  6269. /* Decode variable into destination buffer */
  6270. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6271. /* Redirect error code from -1 to -2 (destination buffer too
  6272. * small). */
  6273. if (len == -1) {
  6274. len = -2;
  6275. }
  6276. break;
  6277. }
  6278. }
  6279. }
  6280. return len;
  6281. }
  6282. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6283. int
  6284. mg_split_form_urlencoded(char *data,
  6285. struct mg_header *form_fields,
  6286. unsigned num_form_fields)
  6287. {
  6288. char *b;
  6289. int i;
  6290. int num = 0;
  6291. if (data == NULL) {
  6292. /* parameter error */
  6293. return -1;
  6294. }
  6295. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6296. /* determine the number of expected fields */
  6297. if (data[0] == 0) {
  6298. return 0;
  6299. }
  6300. /* count number of & to return the number of key-value-pairs */
  6301. num = 1;
  6302. while (*data) {
  6303. if (*data == '&') {
  6304. num++;
  6305. }
  6306. data++;
  6307. }
  6308. return num;
  6309. }
  6310. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6311. /* parameter error */
  6312. return -1;
  6313. }
  6314. for (i = 0; i < (int)num_form_fields; i++) {
  6315. /* extract key-value pairs from input data */
  6316. while ((*data == ' ') || (*data == '\t')) {
  6317. /* skip initial spaces */
  6318. data++;
  6319. }
  6320. if (*data == 0) {
  6321. /* end of string reached */
  6322. break;
  6323. }
  6324. form_fields[num].name = data;
  6325. /* find & or = */
  6326. b = data;
  6327. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6328. b++;
  6329. }
  6330. if (*b == 0) {
  6331. /* last key without value */
  6332. form_fields[num].value = NULL;
  6333. } else if (*b == '&') {
  6334. /* mid key without value */
  6335. form_fields[num].value = NULL;
  6336. } else {
  6337. /* terminate string */
  6338. *b = 0;
  6339. /* value starts after '=' */
  6340. data = b + 1;
  6341. form_fields[num].value = data;
  6342. }
  6343. /* new field is stored */
  6344. num++;
  6345. /* find a next key */
  6346. b = strchr(data, '&');
  6347. if (b == 0) {
  6348. /* no more data */
  6349. break;
  6350. } else {
  6351. /* terminate value of last field at '&' */
  6352. *b = 0;
  6353. /* next key-value-pairs starts after '&' */
  6354. data = b + 1;
  6355. }
  6356. }
  6357. /* Decode all values */
  6358. for (i = 0; i < num; i++) {
  6359. if (form_fields[i].name) {
  6360. url_decode_in_place((char *)form_fields[i].name);
  6361. }
  6362. if (form_fields[i].value) {
  6363. url_decode_in_place((char *)form_fields[i].value);
  6364. }
  6365. }
  6366. /* return number of fields found */
  6367. return num;
  6368. }
  6369. /* HCP24: some changes to compare hole var_name */
  6370. int
  6371. mg_get_cookie(const char *cookie_header,
  6372. const char *var_name,
  6373. char *dst,
  6374. size_t dst_size)
  6375. {
  6376. const char *s, *p, *end;
  6377. int name_len, len = -1;
  6378. if ((dst == NULL) || (dst_size == 0)) {
  6379. return -2;
  6380. }
  6381. dst[0] = '\0';
  6382. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6383. return -1;
  6384. }
  6385. name_len = (int)strlen(var_name);
  6386. end = s + strlen(s);
  6387. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6388. if (s[name_len] == '=') {
  6389. /* HCP24: now check is it a substring or a full cookie name */
  6390. if ((s == cookie_header) || (s[-1] == ' ')) {
  6391. s += name_len + 1;
  6392. if ((p = strchr(s, ' ')) == NULL) {
  6393. p = end;
  6394. }
  6395. if (p[-1] == ';') {
  6396. p--;
  6397. }
  6398. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6399. s++;
  6400. p--;
  6401. }
  6402. if ((size_t)(p - s) < dst_size) {
  6403. len = (int)(p - s);
  6404. mg_strlcpy(dst, s, (size_t)len + 1);
  6405. } else {
  6406. len = -3;
  6407. }
  6408. break;
  6409. }
  6410. }
  6411. }
  6412. return len;
  6413. }
  6414. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6415. static void
  6416. base64_encode(const unsigned char *src, int src_len, char *dst)
  6417. {
  6418. static const char *b64 =
  6419. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6420. int i, j, a, b, c;
  6421. for (i = j = 0; i < src_len; i += 3) {
  6422. a = src[i];
  6423. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6424. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6425. dst[j++] = b64[a >> 2];
  6426. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6427. if (i + 1 < src_len) {
  6428. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6429. }
  6430. if (i + 2 < src_len) {
  6431. dst[j++] = b64[c & 63];
  6432. }
  6433. }
  6434. while (j % 4 != 0) {
  6435. dst[j++] = '=';
  6436. }
  6437. dst[j++] = '\0';
  6438. }
  6439. #endif
  6440. #if defined(USE_LUA)
  6441. static unsigned char
  6442. b64reverse(char letter)
  6443. {
  6444. if ((letter >= 'A') && (letter <= 'Z')) {
  6445. return letter - 'A';
  6446. }
  6447. if ((letter >= 'a') && (letter <= 'z')) {
  6448. return letter - 'a' + 26;
  6449. }
  6450. if ((letter >= '0') && (letter <= '9')) {
  6451. return letter - '0' + 52;
  6452. }
  6453. if (letter == '+') {
  6454. return 62;
  6455. }
  6456. if (letter == '/') {
  6457. return 63;
  6458. }
  6459. if (letter == '=') {
  6460. return 255; /* normal end */
  6461. }
  6462. return 254; /* error */
  6463. }
  6464. static int
  6465. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6466. {
  6467. int i;
  6468. unsigned char a, b, c, d;
  6469. *dst_len = 0;
  6470. for (i = 0; i < src_len; i += 4) {
  6471. a = b64reverse(src[i]);
  6472. if (a >= 254) {
  6473. return i;
  6474. }
  6475. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6476. if (b >= 254) {
  6477. return i + 1;
  6478. }
  6479. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6480. if (c == 254) {
  6481. return i + 2;
  6482. }
  6483. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6484. if (d == 254) {
  6485. return i + 3;
  6486. }
  6487. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6488. if (c != 255) {
  6489. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6490. if (d != 255) {
  6491. dst[(*dst_len)++] = (c << 6) + d;
  6492. }
  6493. }
  6494. }
  6495. return -1;
  6496. }
  6497. #endif
  6498. static int
  6499. is_put_or_delete_method(const struct mg_connection *conn)
  6500. {
  6501. if (conn) {
  6502. const char *s = conn->request_info.request_method;
  6503. return (s != NULL)
  6504. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6505. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6506. }
  6507. return 0;
  6508. }
  6509. #if !defined(NO_FILES)
  6510. static int
  6511. extention_matches_script(
  6512. struct mg_connection *conn, /* in: request (must be valid) */
  6513. const char *filename /* in: filename (must be valid) */
  6514. )
  6515. {
  6516. #if !defined(NO_CGI)
  6517. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6518. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6519. filename)
  6520. > 0) {
  6521. return 1;
  6522. }
  6523. #endif
  6524. #if defined(USE_LUA)
  6525. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6526. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6527. filename)
  6528. > 0) {
  6529. return 1;
  6530. }
  6531. #endif
  6532. #if defined(USE_DUKTAPE)
  6533. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6534. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6535. filename)
  6536. > 0) {
  6537. return 1;
  6538. }
  6539. #endif
  6540. /* filename and conn could be unused, if all preocessor conditions
  6541. * are false (no script language supported). */
  6542. (void)filename;
  6543. (void)conn;
  6544. return 0;
  6545. }
  6546. /* For given directory path, substitute it to valid index file.
  6547. * Return 1 if index file has been found, 0 if not found.
  6548. * If the file is found, it's stats is returned in stp. */
  6549. static int
  6550. substitute_index_file(struct mg_connection *conn,
  6551. char *path,
  6552. size_t path_len,
  6553. struct mg_file_stat *filestat)
  6554. {
  6555. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6556. struct vec filename_vec;
  6557. size_t n = strlen(path);
  6558. int found = 0;
  6559. /* The 'path' given to us points to the directory. Remove all trailing
  6560. * directory separator characters from the end of the path, and
  6561. * then append single directory separator character. */
  6562. while ((n > 0) && (path[n - 1] == '/')) {
  6563. n--;
  6564. }
  6565. path[n] = '/';
  6566. /* Traverse index files list. For each entry, append it to the given
  6567. * path and see if the file exists. If it exists, break the loop */
  6568. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6569. /* Ignore too long entries that may overflow path buffer */
  6570. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6571. continue;
  6572. }
  6573. /* Prepare full path to the index file */
  6574. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6575. /* Does it exist? */
  6576. if (mg_stat(conn, path, filestat)) {
  6577. /* Yes it does, break the loop */
  6578. found = 1;
  6579. break;
  6580. }
  6581. }
  6582. /* If no index file exists, restore directory path */
  6583. if (!found) {
  6584. path[n] = '\0';
  6585. }
  6586. return found;
  6587. }
  6588. #endif
  6589. static void
  6590. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6591. char *filename, /* out: filename */
  6592. size_t filename_buf_len, /* in: size of filename buffer */
  6593. struct mg_file_stat *filestat, /* out: file status structure */
  6594. int *is_found, /* out: file found (directly) */
  6595. int *is_script_resource, /* out: handled by a script? */
  6596. int *is_websocket_request, /* out: websocket connetion? */
  6597. int *is_put_or_delete_request /* out: put/delete a file? */
  6598. )
  6599. {
  6600. char const *accept_encoding;
  6601. #if !defined(NO_FILES)
  6602. const char *uri = conn->request_info.local_uri;
  6603. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6604. const char *rewrite;
  6605. struct vec a, b;
  6606. ptrdiff_t match_len;
  6607. char gz_path[PATH_MAX];
  6608. int truncated;
  6609. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6610. char *tmp_str;
  6611. size_t tmp_str_len, sep_pos;
  6612. int allow_substitute_script_subresources;
  6613. #endif
  6614. #else
  6615. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6616. #endif
  6617. /* Step 1: Set all initially unknown outputs to zero */
  6618. memset(filestat, 0, sizeof(*filestat));
  6619. *filename = 0;
  6620. *is_found = 0;
  6621. *is_script_resource = 0;
  6622. /* Step 2: Check if the request attempts to modify the file system */
  6623. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6624. /* Step 3: Check if it is a websocket request, and modify the document
  6625. * root if required */
  6626. #if defined(USE_WEBSOCKET)
  6627. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6628. #if !defined(NO_FILES)
  6629. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6630. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6631. }
  6632. #endif /* !NO_FILES */
  6633. #else /* USE_WEBSOCKET */
  6634. *is_websocket_request = 0;
  6635. #endif /* USE_WEBSOCKET */
  6636. /* Step 4: Check if gzip encoded response is allowed */
  6637. conn->accept_gzip = 0;
  6638. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6639. if (strstr(accept_encoding, "gzip") != NULL) {
  6640. conn->accept_gzip = 1;
  6641. }
  6642. }
  6643. #if !defined(NO_FILES)
  6644. /* Step 5: If there is no root directory, don't look for files. */
  6645. /* Note that root == NULL is a regular use case here. This occurs,
  6646. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6647. * config is not required. */
  6648. if (root == NULL) {
  6649. /* all file related outputs have already been set to 0, just return
  6650. */
  6651. return;
  6652. }
  6653. /* Step 6: Determine the local file path from the root path and the
  6654. * request uri. */
  6655. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6656. * part of the path one byte on the right. */
  6657. mg_snprintf(
  6658. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6659. if (truncated) {
  6660. goto interpret_cleanup;
  6661. }
  6662. /* Step 7: URI rewriting */
  6663. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6664. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6665. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6666. mg_snprintf(conn,
  6667. &truncated,
  6668. filename,
  6669. filename_buf_len - 1,
  6670. "%.*s%s",
  6671. (int)b.len,
  6672. b.ptr,
  6673. uri + match_len);
  6674. break;
  6675. }
  6676. }
  6677. if (truncated) {
  6678. goto interpret_cleanup;
  6679. }
  6680. /* Step 8: Check if the file exists at the server */
  6681. /* Local file path and name, corresponding to requested URI
  6682. * is now stored in "filename" variable. */
  6683. if (mg_stat(conn, filename, filestat)) {
  6684. int uri_len = (int)strlen(uri);
  6685. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6686. /* 8.1: File exists. */
  6687. *is_found = 1;
  6688. /* 8.2: Check if it is a script type. */
  6689. if (extention_matches_script(conn, filename)) {
  6690. /* The request addresses a CGI resource, Lua script or
  6691. * server-side javascript.
  6692. * The URI corresponds to the script itself (like
  6693. * /path/script.cgi), and there is no additional resource
  6694. * path (like /path/script.cgi/something).
  6695. * Requests that modify (replace or delete) a resource, like
  6696. * PUT and DELETE requests, should replace/delete the script
  6697. * file.
  6698. * Requests that read or write from/to a resource, like GET and
  6699. * POST requests, should call the script and return the
  6700. * generated response. */
  6701. *is_script_resource = (!*is_put_or_delete_request);
  6702. }
  6703. /* 8.3: If the request target is a directory, there could be
  6704. * a substitute file (index.html, index.cgi, ...). */
  6705. if (filestat->is_directory && is_uri_end_slash) {
  6706. /* Use a local copy here, since substitute_index_file will
  6707. * change the content of the file status */
  6708. struct mg_file_stat tmp_filestat;
  6709. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6710. if (substitute_index_file(
  6711. conn, filename, filename_buf_len, &tmp_filestat)) {
  6712. /* Substitute file found. Copy stat to the output, then
  6713. * check if the file is a script file */
  6714. *filestat = tmp_filestat;
  6715. if (extention_matches_script(conn, filename)) {
  6716. /* Substitute file is a script file */
  6717. *is_script_resource = 1;
  6718. } else {
  6719. /* Substitute file is a regular file */
  6720. *is_script_resource = 0;
  6721. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6722. }
  6723. }
  6724. /* If there is no substitute file, the server could return
  6725. * a directory listing in a later step */
  6726. }
  6727. return;
  6728. }
  6729. /* Step 9: Check for zipped files: */
  6730. /* If we can't find the actual file, look for the file
  6731. * with the same name but a .gz extension. If we find it,
  6732. * use that and set the gzipped flag in the file struct
  6733. * to indicate that the response need to have the content-
  6734. * encoding: gzip header.
  6735. * We can only do this if the browser declares support. */
  6736. if (conn->accept_gzip) {
  6737. mg_snprintf(
  6738. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6739. if (truncated) {
  6740. goto interpret_cleanup;
  6741. }
  6742. if (mg_stat(conn, gz_path, filestat)) {
  6743. if (filestat) {
  6744. filestat->is_gzipped = 1;
  6745. *is_found = 1;
  6746. }
  6747. /* Currently gz files can not be scripts. */
  6748. return;
  6749. }
  6750. }
  6751. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6752. /* Step 10: Script resources may handle sub-resources */
  6753. /* Support PATH_INFO for CGI scripts. */
  6754. tmp_str_len = strlen(filename);
  6755. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6756. if (!tmp_str) {
  6757. /* Out of memory */
  6758. goto interpret_cleanup;
  6759. }
  6760. memcpy(tmp_str, filename, tmp_str_len + 1);
  6761. /* Check config, if index scripts may have sub-resources */
  6762. allow_substitute_script_subresources =
  6763. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6764. "yes");
  6765. sep_pos = tmp_str_len;
  6766. while (sep_pos > 0) {
  6767. sep_pos--;
  6768. if (tmp_str[sep_pos] == '/') {
  6769. int is_script = 0, does_exist = 0;
  6770. tmp_str[sep_pos] = 0;
  6771. if (tmp_str[0]) {
  6772. is_script = extention_matches_script(conn, tmp_str);
  6773. does_exist = mg_stat(conn, tmp_str, filestat);
  6774. }
  6775. if (does_exist && is_script) {
  6776. filename[sep_pos] = 0;
  6777. memmove(filename + sep_pos + 2,
  6778. filename + sep_pos + 1,
  6779. strlen(filename + sep_pos + 1) + 1);
  6780. conn->path_info = filename + sep_pos + 1;
  6781. filename[sep_pos + 1] = '/';
  6782. *is_script_resource = 1;
  6783. *is_found = 1;
  6784. break;
  6785. }
  6786. if (allow_substitute_script_subresources) {
  6787. if (substitute_index_file(
  6788. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6789. /* some intermediate directory has an index file */
  6790. if (extention_matches_script(conn, tmp_str)) {
  6791. DEBUG_TRACE("Substitute script %s serving path %s",
  6792. tmp_str,
  6793. filename);
  6794. /* this index file is a script */
  6795. mg_snprintf(conn,
  6796. &truncated,
  6797. filename,
  6798. filename_buf_len,
  6799. "%s//%s",
  6800. tmp_str,
  6801. filename + sep_pos + 1);
  6802. if (truncated) {
  6803. mg_free(tmp_str);
  6804. goto interpret_cleanup;
  6805. }
  6806. sep_pos = strlen(tmp_str);
  6807. filename[sep_pos] = 0;
  6808. conn->path_info = filename + sep_pos + 1;
  6809. *is_script_resource = 1;
  6810. *is_found = 1;
  6811. break;
  6812. } else {
  6813. DEBUG_TRACE("Substitute file %s serving path %s",
  6814. tmp_str,
  6815. filename);
  6816. /* non-script files will not have sub-resources */
  6817. filename[sep_pos] = 0;
  6818. conn->path_info = 0;
  6819. *is_script_resource = 0;
  6820. *is_found = 0;
  6821. break;
  6822. }
  6823. }
  6824. }
  6825. tmp_str[sep_pos] = '/';
  6826. }
  6827. }
  6828. mg_free(tmp_str);
  6829. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6830. #endif /* !defined(NO_FILES) */
  6831. return;
  6832. #if !defined(NO_FILES)
  6833. /* Reset all outputs */
  6834. interpret_cleanup:
  6835. memset(filestat, 0, sizeof(*filestat));
  6836. *filename = 0;
  6837. *is_found = 0;
  6838. *is_script_resource = 0;
  6839. *is_websocket_request = 0;
  6840. *is_put_or_delete_request = 0;
  6841. #endif /* !defined(NO_FILES) */
  6842. }
  6843. /* Check whether full request is buffered. Return:
  6844. * -1 if request or response is malformed
  6845. * 0 if request or response is not yet fully buffered
  6846. * >0 actual request length, including last \r\n\r\n */
  6847. static int
  6848. get_http_header_len(const char *buf, int buflen)
  6849. {
  6850. int i;
  6851. for (i = 0; i < buflen; i++) {
  6852. /* Do an unsigned comparison in some conditions below */
  6853. const unsigned char c = (unsigned char)buf[i];
  6854. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6855. && !isprint(c)) {
  6856. /* abort scan as soon as one malformed character is found */
  6857. return -1;
  6858. }
  6859. if (i < buflen - 1) {
  6860. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6861. /* Two newline, no carriage return - not standard compliant,
  6862. * but it should be accepted */
  6863. return i + 2;
  6864. }
  6865. }
  6866. if (i < buflen - 3) {
  6867. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6868. && (buf[i + 3] == '\n')) {
  6869. /* Two \r\n - standard compliant */
  6870. return i + 4;
  6871. }
  6872. }
  6873. }
  6874. return 0;
  6875. }
  6876. #if !defined(NO_CACHING)
  6877. /* Convert month to the month number. Return -1 on error, or month number */
  6878. static int
  6879. get_month_index(const char *s)
  6880. {
  6881. size_t i;
  6882. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6883. if (!strcmp(s, month_names[i])) {
  6884. return (int)i;
  6885. }
  6886. }
  6887. return -1;
  6888. }
  6889. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6890. static time_t
  6891. parse_date_string(const char *datetime)
  6892. {
  6893. char month_str[32] = {0};
  6894. int second, minute, hour, day, month, year;
  6895. time_t result = (time_t)0;
  6896. struct tm tm;
  6897. if ((sscanf(datetime,
  6898. "%d/%3s/%d %d:%d:%d",
  6899. &day,
  6900. month_str,
  6901. &year,
  6902. &hour,
  6903. &minute,
  6904. &second)
  6905. == 6)
  6906. || (sscanf(datetime,
  6907. "%d %3s %d %d:%d:%d",
  6908. &day,
  6909. month_str,
  6910. &year,
  6911. &hour,
  6912. &minute,
  6913. &second)
  6914. == 6)
  6915. || (sscanf(datetime,
  6916. "%*3s, %d %3s %d %d:%d:%d",
  6917. &day,
  6918. month_str,
  6919. &year,
  6920. &hour,
  6921. &minute,
  6922. &second)
  6923. == 6)
  6924. || (sscanf(datetime,
  6925. "%d-%3s-%d %d:%d:%d",
  6926. &day,
  6927. month_str,
  6928. &year,
  6929. &hour,
  6930. &minute,
  6931. &second)
  6932. == 6)) {
  6933. month = get_month_index(month_str);
  6934. if ((month >= 0) && (year >= 1970)) {
  6935. memset(&tm, 0, sizeof(tm));
  6936. tm.tm_year = year - 1900;
  6937. tm.tm_mon = month;
  6938. tm.tm_mday = day;
  6939. tm.tm_hour = hour;
  6940. tm.tm_min = minute;
  6941. tm.tm_sec = second;
  6942. result = timegm(&tm);
  6943. }
  6944. }
  6945. return result;
  6946. }
  6947. #endif /* !NO_CACHING */
  6948. /* Pre-process URIs according to RFC + protect against directory disclosure
  6949. * attacks by removing '..', excessive '/' and '\' characters */
  6950. static void
  6951. remove_dot_segments(char *inout)
  6952. {
  6953. /* Windows backend protection
  6954. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6955. * in URI by slash */
  6956. char *out_end = inout;
  6957. char *in = inout;
  6958. if (!in) {
  6959. /* Param error. */
  6960. return;
  6961. }
  6962. while (*in) {
  6963. if (*in == '\\') {
  6964. *in = '/';
  6965. }
  6966. in++;
  6967. }
  6968. /* Algorithm "remove_dot_segments" from
  6969. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6970. /* Step 1:
  6971. * The input buffer is initialized.
  6972. * The output buffer is initialized to the empty string.
  6973. */
  6974. in = inout;
  6975. /* Step 2:
  6976. * While the input buffer is not empty, loop as follows:
  6977. */
  6978. /* Less than out_end of the inout buffer is used as output, so keep
  6979. * condition: out_end <= in */
  6980. while (*in) {
  6981. /* Step 2a:
  6982. * If the input buffer begins with a prefix of "../" or "./",
  6983. * then remove that prefix from the input buffer;
  6984. */
  6985. if (!strncmp(in, "../", 3)) {
  6986. in += 3;
  6987. } else if (!strncmp(in, "./", 2)) {
  6988. in += 2;
  6989. }
  6990. /* otherwise */
  6991. /* Step 2b:
  6992. * if the input buffer begins with a prefix of "/./" or "/.",
  6993. * where "." is a complete path segment, then replace that
  6994. * prefix with "/" in the input buffer;
  6995. */
  6996. else if (!strncmp(in, "/./", 3)) {
  6997. in += 2;
  6998. } else if (!strcmp(in, "/.")) {
  6999. in[1] = 0;
  7000. }
  7001. /* otherwise */
  7002. /* Step 2c:
  7003. * if the input buffer begins with a prefix of "/../" or "/..",
  7004. * where ".." is a complete path segment, then replace that
  7005. * prefix with "/" in the input buffer and remove the last
  7006. * segment and its preceding "/" (if any) from the output
  7007. * buffer;
  7008. */
  7009. else if (!strncmp(in, "/../", 4)) {
  7010. in += 3;
  7011. if (inout != out_end) {
  7012. /* remove last segment */
  7013. do {
  7014. out_end--;
  7015. } while ((inout != out_end) && (*out_end != '/'));
  7016. }
  7017. } else if (!strcmp(in, "/..")) {
  7018. in[1] = 0;
  7019. if (inout != out_end) {
  7020. /* remove last segment */
  7021. do {
  7022. out_end--;
  7023. } while ((inout != out_end) && (*out_end != '/'));
  7024. }
  7025. }
  7026. /* otherwise */
  7027. /* Step 2d:
  7028. * if the input buffer consists only of "." or "..", then remove
  7029. * that from the input buffer;
  7030. */
  7031. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7032. *in = 0;
  7033. }
  7034. /* otherwise */
  7035. /* Step 2e:
  7036. * move the first path segment in the input buffer to the end of
  7037. * the output buffer, including the initial "/" character (if
  7038. * any) and any subsequent characters up to, but not including,
  7039. * the next "/" character or the end of the input buffer.
  7040. */
  7041. else {
  7042. do {
  7043. *out_end = *in;
  7044. out_end++;
  7045. in++;
  7046. } while ((*in != 0) && (*in != '/'));
  7047. }
  7048. }
  7049. /* Step 3:
  7050. * Finally, the output buffer is returned as the result of
  7051. * remove_dot_segments.
  7052. */
  7053. /* Terminate output */
  7054. *out_end = 0;
  7055. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7056. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7057. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7058. * or "//" anymore.
  7059. */
  7060. out_end = in = inout;
  7061. while (*in) {
  7062. if (*in == '.') {
  7063. /* remove . at the end or preceding of / */
  7064. char *in_ahead = in;
  7065. do {
  7066. in_ahead++;
  7067. } while (*in_ahead == '.');
  7068. if (*in_ahead == '/') {
  7069. in = in_ahead;
  7070. if ((out_end != inout) && (out_end[-1] == '/')) {
  7071. /* remove generated // */
  7072. out_end--;
  7073. }
  7074. } else if (*in_ahead == 0) {
  7075. in = in_ahead;
  7076. } else {
  7077. do {
  7078. *out_end++ = '.';
  7079. in++;
  7080. } while (in != in_ahead);
  7081. }
  7082. } else if (*in == '/') {
  7083. /* replace // by / */
  7084. *out_end++ = '/';
  7085. do {
  7086. in++;
  7087. } while (*in == '/');
  7088. } else {
  7089. *out_end++ = *in;
  7090. in++;
  7091. }
  7092. }
  7093. *out_end = 0;
  7094. }
  7095. static const struct {
  7096. const char *extension;
  7097. size_t ext_len;
  7098. const char *mime_type;
  7099. } builtin_mime_types[] = {
  7100. /* IANA registered MIME types
  7101. * (http://www.iana.org/assignments/media-types)
  7102. * application types */
  7103. {".doc", 4, "application/msword"},
  7104. {".eps", 4, "application/postscript"},
  7105. {".exe", 4, "application/octet-stream"},
  7106. {".js", 3, "application/javascript"},
  7107. {".json", 5, "application/json"},
  7108. {".pdf", 4, "application/pdf"},
  7109. {".ps", 3, "application/postscript"},
  7110. {".rtf", 4, "application/rtf"},
  7111. {".xhtml", 6, "application/xhtml+xml"},
  7112. {".xsl", 4, "application/xml"},
  7113. {".xslt", 5, "application/xml"},
  7114. /* fonts */
  7115. {".ttf", 4, "application/font-sfnt"},
  7116. {".cff", 4, "application/font-sfnt"},
  7117. {".otf", 4, "application/font-sfnt"},
  7118. {".aat", 4, "application/font-sfnt"},
  7119. {".sil", 4, "application/font-sfnt"},
  7120. {".pfr", 4, "application/font-tdpfr"},
  7121. {".woff", 5, "application/font-woff"},
  7122. /* audio */
  7123. {".mp3", 4, "audio/mpeg"},
  7124. {".oga", 4, "audio/ogg"},
  7125. {".ogg", 4, "audio/ogg"},
  7126. /* image */
  7127. {".gif", 4, "image/gif"},
  7128. {".ief", 4, "image/ief"},
  7129. {".jpeg", 5, "image/jpeg"},
  7130. {".jpg", 4, "image/jpeg"},
  7131. {".jpm", 4, "image/jpm"},
  7132. {".jpx", 4, "image/jpx"},
  7133. {".png", 4, "image/png"},
  7134. {".svg", 4, "image/svg+xml"},
  7135. {".tif", 4, "image/tiff"},
  7136. {".tiff", 5, "image/tiff"},
  7137. /* model */
  7138. {".wrl", 4, "model/vrml"},
  7139. /* text */
  7140. {".css", 4, "text/css"},
  7141. {".csv", 4, "text/csv"},
  7142. {".htm", 4, "text/html"},
  7143. {".html", 5, "text/html"},
  7144. {".sgm", 4, "text/sgml"},
  7145. {".shtm", 5, "text/html"},
  7146. {".shtml", 6, "text/html"},
  7147. {".txt", 4, "text/plain"},
  7148. {".xml", 4, "text/xml"},
  7149. /* video */
  7150. {".mov", 4, "video/quicktime"},
  7151. {".mp4", 4, "video/mp4"},
  7152. {".mpeg", 5, "video/mpeg"},
  7153. {".mpg", 4, "video/mpeg"},
  7154. {".ogv", 4, "video/ogg"},
  7155. {".qt", 3, "video/quicktime"},
  7156. /* not registered types
  7157. * (http://reference.sitepoint.com/html/mime-types-full,
  7158. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7159. {".arj", 4, "application/x-arj-compressed"},
  7160. {".gz", 3, "application/x-gunzip"},
  7161. {".rar", 4, "application/x-arj-compressed"},
  7162. {".swf", 4, "application/x-shockwave-flash"},
  7163. {".tar", 4, "application/x-tar"},
  7164. {".tgz", 4, "application/x-tar-gz"},
  7165. {".torrent", 8, "application/x-bittorrent"},
  7166. {".ppt", 4, "application/x-mspowerpoint"},
  7167. {".xls", 4, "application/x-msexcel"},
  7168. {".zip", 4, "application/x-zip-compressed"},
  7169. {".aac",
  7170. 4,
  7171. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7172. {".aif", 4, "audio/x-aif"},
  7173. {".m3u", 4, "audio/x-mpegurl"},
  7174. {".mid", 4, "audio/x-midi"},
  7175. {".ra", 3, "audio/x-pn-realaudio"},
  7176. {".ram", 4, "audio/x-pn-realaudio"},
  7177. {".wav", 4, "audio/x-wav"},
  7178. {".bmp", 4, "image/bmp"},
  7179. {".ico", 4, "image/x-icon"},
  7180. {".pct", 4, "image/x-pct"},
  7181. {".pict", 5, "image/pict"},
  7182. {".rgb", 4, "image/x-rgb"},
  7183. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7184. {".asf", 4, "video/x-ms-asf"},
  7185. {".avi", 4, "video/x-msvideo"},
  7186. {".m4v", 4, "video/x-m4v"},
  7187. {NULL, 0, NULL}};
  7188. const char *
  7189. mg_get_builtin_mime_type(const char *path)
  7190. {
  7191. const char *ext;
  7192. size_t i, path_len;
  7193. path_len = strlen(path);
  7194. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7195. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7196. if ((path_len > builtin_mime_types[i].ext_len)
  7197. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7198. return builtin_mime_types[i].mime_type;
  7199. }
  7200. }
  7201. return "text/plain";
  7202. }
  7203. /* Look at the "path" extension and figure what mime type it has.
  7204. * Store mime type in the vector. */
  7205. static void
  7206. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7207. {
  7208. struct vec ext_vec, mime_vec;
  7209. const char *list, *ext;
  7210. size_t path_len;
  7211. path_len = strlen(path);
  7212. if ((conn == NULL) || (vec == NULL)) {
  7213. if (vec != NULL) {
  7214. memset(vec, '\0', sizeof(struct vec));
  7215. }
  7216. return;
  7217. }
  7218. /* Scan user-defined mime types first, in case user wants to
  7219. * override default mime types. */
  7220. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7221. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7222. /* ext now points to the path suffix */
  7223. ext = path + path_len - ext_vec.len;
  7224. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7225. *vec = mime_vec;
  7226. return;
  7227. }
  7228. }
  7229. vec->ptr = mg_get_builtin_mime_type(path);
  7230. vec->len = strlen(vec->ptr);
  7231. }
  7232. /* Stringify binary data. Output buffer must be twice as big as input,
  7233. * because each byte takes 2 bytes in string representation */
  7234. static void
  7235. bin2str(char *to, const unsigned char *p, size_t len)
  7236. {
  7237. static const char *hex = "0123456789abcdef";
  7238. for (; len--; p++) {
  7239. *to++ = hex[p[0] >> 4];
  7240. *to++ = hex[p[0] & 0x0f];
  7241. }
  7242. *to = '\0';
  7243. }
  7244. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7245. */
  7246. char *
  7247. mg_md5(char buf[33], ...)
  7248. {
  7249. md5_byte_t hash[16];
  7250. const char *p;
  7251. va_list ap;
  7252. md5_state_t ctx;
  7253. md5_init(&ctx);
  7254. va_start(ap, buf);
  7255. while ((p = va_arg(ap, const char *)) != NULL) {
  7256. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7257. }
  7258. va_end(ap);
  7259. md5_finish(&ctx, hash);
  7260. bin2str(buf, hash, sizeof(hash));
  7261. return buf;
  7262. }
  7263. /* Check the user's password, return 1 if OK */
  7264. static int
  7265. check_password(const char *method,
  7266. const char *ha1,
  7267. const char *uri,
  7268. const char *nonce,
  7269. const char *nc,
  7270. const char *cnonce,
  7271. const char *qop,
  7272. const char *response)
  7273. {
  7274. char ha2[32 + 1], expected_response[32 + 1];
  7275. /* Some of the parameters may be NULL */
  7276. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7277. || (qop == NULL) || (response == NULL)) {
  7278. return 0;
  7279. }
  7280. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7281. if (strlen(response) != 32) {
  7282. return 0;
  7283. }
  7284. mg_md5(ha2, method, ":", uri, NULL);
  7285. mg_md5(expected_response,
  7286. ha1,
  7287. ":",
  7288. nonce,
  7289. ":",
  7290. nc,
  7291. ":",
  7292. cnonce,
  7293. ":",
  7294. qop,
  7295. ":",
  7296. ha2,
  7297. NULL);
  7298. return mg_strcasecmp(response, expected_response) == 0;
  7299. }
  7300. #if !defined(NO_FILESYSTEMS)
  7301. /* Use the global passwords file, if specified by auth_gpass option,
  7302. * or search for .htpasswd in the requested directory. */
  7303. static void
  7304. open_auth_file(struct mg_connection *conn,
  7305. const char *path,
  7306. struct mg_file *filep)
  7307. {
  7308. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7309. char name[PATH_MAX];
  7310. const char *p, *e,
  7311. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7312. int truncated;
  7313. if (gpass != NULL) {
  7314. /* Use global passwords file */
  7315. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7316. #if defined(DEBUG)
  7317. /* Use mg_cry_internal here, since gpass has been
  7318. * configured. */
  7319. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7320. #endif
  7321. }
  7322. /* Important: using local struct mg_file to test path for
  7323. * is_directory flag. If filep is used, mg_stat() makes it
  7324. * appear as if auth file was opened.
  7325. * TODO(mid): Check if this is still required after rewriting
  7326. * mg_stat */
  7327. } else if (mg_stat(conn, path, &filep->stat)
  7328. && filep->stat.is_directory) {
  7329. mg_snprintf(conn,
  7330. &truncated,
  7331. name,
  7332. sizeof(name),
  7333. "%s/%s",
  7334. path,
  7335. PASSWORDS_FILE_NAME);
  7336. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7337. #if defined(DEBUG)
  7338. /* Don't use mg_cry_internal here, but only a trace, since
  7339. * this is a typical case. It will occur for every directory
  7340. * without a password file. */
  7341. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7342. #endif
  7343. }
  7344. } else {
  7345. /* Try to find .htpasswd in requested directory. */
  7346. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7347. if (e[0] == '/') {
  7348. break;
  7349. }
  7350. }
  7351. mg_snprintf(conn,
  7352. &truncated,
  7353. name,
  7354. sizeof(name),
  7355. "%.*s/%s",
  7356. (int)(e - p),
  7357. p,
  7358. PASSWORDS_FILE_NAME);
  7359. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7360. #if defined(DEBUG)
  7361. /* Don't use mg_cry_internal here, but only a trace, since
  7362. * this is a typical case. It will occur for every directory
  7363. * without a password file. */
  7364. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7365. #endif
  7366. }
  7367. }
  7368. }
  7369. }
  7370. #endif /* NO_FILESYSTEMS */
  7371. /* Parsed Authorization header */
  7372. struct ah {
  7373. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7374. };
  7375. /* Return 1 on success. Always initializes the ah structure. */
  7376. static int
  7377. parse_auth_header(struct mg_connection *conn,
  7378. char *buf,
  7379. size_t buf_size,
  7380. struct ah *ah)
  7381. {
  7382. char *name, *value, *s;
  7383. const char *auth_header;
  7384. uint64_t nonce;
  7385. if (!ah || !conn) {
  7386. return 0;
  7387. }
  7388. (void)memset(ah, 0, sizeof(*ah));
  7389. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7390. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7391. return 0;
  7392. }
  7393. /* Make modifiable copy of the auth header */
  7394. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7395. s = buf;
  7396. /* Parse authorization header */
  7397. for (;;) {
  7398. /* Gobble initial spaces */
  7399. while (isspace((unsigned char)*s)) {
  7400. s++;
  7401. }
  7402. name = skip_quoted(&s, "=", " ", 0);
  7403. /* Value is either quote-delimited, or ends at first comma or space.
  7404. */
  7405. if (s[0] == '\"') {
  7406. s++;
  7407. value = skip_quoted(&s, "\"", " ", '\\');
  7408. if (s[0] == ',') {
  7409. s++;
  7410. }
  7411. } else {
  7412. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7413. * uses spaces */
  7414. }
  7415. if (*name == '\0') {
  7416. break;
  7417. }
  7418. if (!strcmp(name, "username")) {
  7419. ah->user = value;
  7420. } else if (!strcmp(name, "cnonce")) {
  7421. ah->cnonce = value;
  7422. } else if (!strcmp(name, "response")) {
  7423. ah->response = value;
  7424. } else if (!strcmp(name, "uri")) {
  7425. ah->uri = value;
  7426. } else if (!strcmp(name, "qop")) {
  7427. ah->qop = value;
  7428. } else if (!strcmp(name, "nc")) {
  7429. ah->nc = value;
  7430. } else if (!strcmp(name, "nonce")) {
  7431. ah->nonce = value;
  7432. }
  7433. }
  7434. #if !defined(NO_NONCE_CHECK)
  7435. /* Read the nonce from the response. */
  7436. if (ah->nonce == NULL) {
  7437. return 0;
  7438. }
  7439. s = NULL;
  7440. nonce = strtoull(ah->nonce, &s, 10);
  7441. if ((s == NULL) || (*s != 0)) {
  7442. return 0;
  7443. }
  7444. /* Convert the nonce from the client to a number. */
  7445. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7446. /* The converted number corresponds to the time the nounce has been
  7447. * created. This should not be earlier than the server start. */
  7448. /* Server side nonce check is valuable in all situations but one:
  7449. * if the server restarts frequently, but the client should not see
  7450. * that, so the server should accept nonces from previous starts. */
  7451. /* However, the reasonable default is to not accept a nonce from a
  7452. * previous start, so if anyone changed the access rights between
  7453. * two restarts, a new login is required. */
  7454. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7455. /* nonce is from a previous start of the server and no longer valid
  7456. * (replay attack?) */
  7457. return 0;
  7458. }
  7459. /* Check if the nonce is too high, so it has not (yet) been used by the
  7460. * server. */
  7461. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7462. + conn->dom_ctx->nonce_count)) {
  7463. return 0;
  7464. }
  7465. #else
  7466. (void)nonce;
  7467. #endif
  7468. /* CGI needs it as REMOTE_USER */
  7469. if (ah->user != NULL) {
  7470. conn->request_info.remote_user =
  7471. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7472. } else {
  7473. return 0;
  7474. }
  7475. return 1;
  7476. }
  7477. static const char *
  7478. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7479. {
  7480. #if defined(MG_USE_OPEN_FILE)
  7481. const char *eof;
  7482. size_t len;
  7483. const char *memend;
  7484. #else
  7485. (void)p; /* parameter is unused */
  7486. #endif
  7487. if (!filep) {
  7488. return NULL;
  7489. }
  7490. #if defined(MG_USE_OPEN_FILE)
  7491. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7492. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7493. /* Search for \n from p till the end of stream */
  7494. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7495. if (eof != NULL) {
  7496. eof += 1; /* Include \n */
  7497. } else {
  7498. eof = memend; /* Copy remaining data */
  7499. }
  7500. len =
  7501. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7502. memcpy(buf, *p, len);
  7503. buf[len] = '\0';
  7504. *p += len;
  7505. return len ? eof : NULL;
  7506. } else /* filep->access.fp block below */
  7507. #endif
  7508. if (filep->access.fp != NULL) {
  7509. return fgets(buf, (int)size, filep->access.fp);
  7510. } else {
  7511. return NULL;
  7512. }
  7513. }
  7514. /* Define the initial recursion depth for procesesing htpasswd files that
  7515. * include other htpasswd
  7516. * (or even the same) files. It is not difficult to provide a file or files
  7517. * s.t. they force civetweb
  7518. * to infinitely recurse and then crash.
  7519. */
  7520. #define INITIAL_DEPTH 9
  7521. #if INITIAL_DEPTH <= 0
  7522. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7523. #endif
  7524. #if !defined(NO_FILESYSTEMS)
  7525. struct read_auth_file_struct {
  7526. struct mg_connection *conn;
  7527. struct ah ah;
  7528. const char *domain;
  7529. char buf[256 + 256 + 40];
  7530. const char *f_user;
  7531. const char *f_domain;
  7532. const char *f_ha1;
  7533. };
  7534. static int
  7535. read_auth_file(struct mg_file *filep,
  7536. struct read_auth_file_struct *workdata,
  7537. int depth)
  7538. {
  7539. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7540. int is_authorized = 0;
  7541. struct mg_file fp;
  7542. size_t l;
  7543. if (!filep || !workdata || (0 == depth)) {
  7544. return 0;
  7545. }
  7546. /* Loop over passwords file */
  7547. #if defined(MG_USE_OPEN_FILE)
  7548. p = (char *)filep->access.membuf;
  7549. #endif
  7550. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7551. l = strlen(workdata->buf);
  7552. while (l > 0) {
  7553. if (isspace((unsigned char)workdata->buf[l - 1])
  7554. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7555. l--;
  7556. workdata->buf[l] = 0;
  7557. } else
  7558. break;
  7559. }
  7560. if (l < 1) {
  7561. continue;
  7562. }
  7563. workdata->f_user = workdata->buf;
  7564. if (workdata->f_user[0] == ':') {
  7565. /* user names may not contain a ':' and may not be empty,
  7566. * so lines starting with ':' may be used for a special purpose
  7567. */
  7568. if (workdata->f_user[1] == '#') {
  7569. /* :# is a comment */
  7570. continue;
  7571. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7572. if (mg_fopen(workdata->conn,
  7573. workdata->f_user + 9,
  7574. MG_FOPEN_MODE_READ,
  7575. &fp)) {
  7576. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7577. (void)mg_fclose(
  7578. &fp.access); /* ignore error on read only file */
  7579. /* No need to continue processing files once we have a
  7580. * match, since nothing will reset it back
  7581. * to 0.
  7582. */
  7583. if (is_authorized) {
  7584. return is_authorized;
  7585. }
  7586. } else {
  7587. mg_cry_internal(workdata->conn,
  7588. "%s: cannot open authorization file: %s",
  7589. __func__,
  7590. workdata->buf);
  7591. }
  7592. continue;
  7593. }
  7594. /* everything is invalid for the moment (might change in the
  7595. * future) */
  7596. mg_cry_internal(workdata->conn,
  7597. "%s: syntax error in authorization file: %s",
  7598. __func__,
  7599. workdata->buf);
  7600. continue;
  7601. }
  7602. workdata->f_domain = strchr(workdata->f_user, ':');
  7603. if (workdata->f_domain == NULL) {
  7604. mg_cry_internal(workdata->conn,
  7605. "%s: syntax error in authorization file: %s",
  7606. __func__,
  7607. workdata->buf);
  7608. continue;
  7609. }
  7610. *(char *)(workdata->f_domain) = 0;
  7611. (workdata->f_domain)++;
  7612. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7613. if (workdata->f_ha1 == NULL) {
  7614. mg_cry_internal(workdata->conn,
  7615. "%s: syntax error in authorization file: %s",
  7616. __func__,
  7617. workdata->buf);
  7618. continue;
  7619. }
  7620. *(char *)(workdata->f_ha1) = 0;
  7621. (workdata->f_ha1)++;
  7622. if (!strcmp(workdata->ah.user, workdata->f_user)
  7623. && !strcmp(workdata->domain, workdata->f_domain)) {
  7624. return check_password(workdata->conn->request_info.request_method,
  7625. workdata->f_ha1,
  7626. workdata->ah.uri,
  7627. workdata->ah.nonce,
  7628. workdata->ah.nc,
  7629. workdata->ah.cnonce,
  7630. workdata->ah.qop,
  7631. workdata->ah.response);
  7632. }
  7633. }
  7634. return is_authorized;
  7635. }
  7636. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7637. static int
  7638. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7639. {
  7640. struct read_auth_file_struct workdata;
  7641. char buf[MG_BUF_LEN];
  7642. if (!conn || !conn->dom_ctx) {
  7643. return 0;
  7644. }
  7645. memset(&workdata, 0, sizeof(workdata));
  7646. workdata.conn = conn;
  7647. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7648. return 0;
  7649. }
  7650. if (realm) {
  7651. workdata.domain = realm;
  7652. } else {
  7653. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7654. }
  7655. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7656. }
  7657. /* Public function to check http digest authentication header */
  7658. int
  7659. mg_check_digest_access_authentication(struct mg_connection *conn,
  7660. const char *realm,
  7661. const char *filename)
  7662. {
  7663. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7664. int auth;
  7665. if (!conn || !filename) {
  7666. return -1;
  7667. }
  7668. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7669. return -2;
  7670. }
  7671. auth = authorize(conn, &file, realm);
  7672. mg_fclose(&file.access);
  7673. return auth;
  7674. }
  7675. #endif /* NO_FILESYSTEMS */
  7676. /* Return 1 if request is authorised, 0 otherwise. */
  7677. static int
  7678. check_authorization(struct mg_connection *conn, const char *path)
  7679. {
  7680. #if !defined(NO_FILESYSTEMS)
  7681. char fname[PATH_MAX];
  7682. struct vec uri_vec, filename_vec;
  7683. const char *list;
  7684. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7685. int authorized = 1, truncated;
  7686. if (!conn || !conn->dom_ctx) {
  7687. return 0;
  7688. }
  7689. list = conn->dom_ctx->config[PROTECT_URI];
  7690. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7691. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7692. mg_snprintf(conn,
  7693. &truncated,
  7694. fname,
  7695. sizeof(fname),
  7696. "%.*s",
  7697. (int)filename_vec.len,
  7698. filename_vec.ptr);
  7699. if (truncated
  7700. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7701. mg_cry_internal(conn,
  7702. "%s: cannot open %s: %s",
  7703. __func__,
  7704. fname,
  7705. strerror(errno));
  7706. }
  7707. break;
  7708. }
  7709. }
  7710. if (!is_file_opened(&file.access)) {
  7711. open_auth_file(conn, path, &file);
  7712. }
  7713. if (is_file_opened(&file.access)) {
  7714. authorized = authorize(conn, &file, NULL);
  7715. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7716. }
  7717. return authorized;
  7718. #else
  7719. (void)conn;
  7720. (void)path;
  7721. return 1;
  7722. #endif /* NO_FILESYSTEMS */
  7723. }
  7724. /* Internal function. Assumes conn is valid */
  7725. static void
  7726. send_authorization_request(struct mg_connection *conn, const char *realm)
  7727. {
  7728. char date[64];
  7729. time_t curtime = time(NULL);
  7730. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7731. if (!realm) {
  7732. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7733. }
  7734. mg_lock_context(conn->phys_ctx);
  7735. nonce += conn->dom_ctx->nonce_count;
  7736. ++conn->dom_ctx->nonce_count;
  7737. mg_unlock_context(conn->phys_ctx);
  7738. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7739. conn->status_code = 401;
  7740. conn->must_close = 1;
  7741. gmt_time_string(date, sizeof(date), &curtime);
  7742. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7743. send_no_cache_header(conn);
  7744. send_additional_header(conn);
  7745. mg_printf(conn,
  7746. "Date: %s\r\n"
  7747. "Connection: %s\r\n"
  7748. "Content-Length: 0\r\n"
  7749. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7750. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7751. date,
  7752. suggest_connection_header(conn),
  7753. realm,
  7754. nonce);
  7755. }
  7756. /* Interface function. Parameters are provided by the user, so do
  7757. * at least some basic checks.
  7758. */
  7759. int
  7760. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7761. const char *realm)
  7762. {
  7763. if (conn && conn->dom_ctx) {
  7764. send_authorization_request(conn, realm);
  7765. return 0;
  7766. }
  7767. return -1;
  7768. }
  7769. #if !defined(NO_FILES)
  7770. static int
  7771. is_authorized_for_put(struct mg_connection *conn)
  7772. {
  7773. if (conn) {
  7774. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7775. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7776. int ret = 0;
  7777. if (passfile != NULL
  7778. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7779. ret = authorize(conn, &file, NULL);
  7780. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7781. }
  7782. return ret;
  7783. }
  7784. return 0;
  7785. }
  7786. #endif
  7787. int
  7788. mg_modify_passwords_file(const char *fname,
  7789. const char *domain,
  7790. const char *user,
  7791. const char *pass)
  7792. {
  7793. int found, i;
  7794. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7795. FILE *fp, *fp2;
  7796. found = 0;
  7797. fp = fp2 = NULL;
  7798. /* Regard empty password as no password - remove user record. */
  7799. if ((pass != NULL) && (pass[0] == '\0')) {
  7800. pass = NULL;
  7801. }
  7802. /* Other arguments must not be empty */
  7803. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7804. return 0;
  7805. }
  7806. /* Using the given file format, user name and domain must not contain
  7807. * ':'
  7808. */
  7809. if (strchr(user, ':') != NULL) {
  7810. return 0;
  7811. }
  7812. if (strchr(domain, ':') != NULL) {
  7813. return 0;
  7814. }
  7815. /* Do not allow control characters like newline in user name and domain.
  7816. * Do not allow excessively long names either. */
  7817. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7818. if (iscntrl((unsigned char)user[i])) {
  7819. return 0;
  7820. }
  7821. }
  7822. if (user[i]) {
  7823. return 0;
  7824. }
  7825. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7826. if (iscntrl((unsigned char)domain[i])) {
  7827. return 0;
  7828. }
  7829. }
  7830. if (domain[i]) {
  7831. return 0;
  7832. }
  7833. /* The maximum length of the path to the password file is limited */
  7834. if ((strlen(fname) + 4) >= PATH_MAX) {
  7835. return 0;
  7836. }
  7837. /* Create a temporary file name. Length has been checked before. */
  7838. strcpy(tmp, fname);
  7839. strcat(tmp, ".tmp");
  7840. /* Create the file if does not exist */
  7841. /* Use of fopen here is OK, since fname is only ASCII */
  7842. if ((fp = fopen(fname, "a+")) != NULL) {
  7843. (void)fclose(fp);
  7844. }
  7845. /* Open the given file and temporary file */
  7846. if ((fp = fopen(fname, "r")) == NULL) {
  7847. return 0;
  7848. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7849. fclose(fp);
  7850. return 0;
  7851. }
  7852. /* Copy the stuff to temporary file */
  7853. while (fgets(line, sizeof(line), fp) != NULL) {
  7854. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7855. continue;
  7856. }
  7857. u[255] = 0;
  7858. d[255] = 0;
  7859. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7860. found++;
  7861. if (pass != NULL) {
  7862. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7863. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7864. }
  7865. } else {
  7866. fprintf(fp2, "%s", line);
  7867. }
  7868. }
  7869. /* If new user, just add it */
  7870. if (!found && (pass != NULL)) {
  7871. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7872. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7873. }
  7874. /* Close files */
  7875. fclose(fp);
  7876. fclose(fp2);
  7877. /* Put the temp file in place of real file */
  7878. IGNORE_UNUSED_RESULT(remove(fname));
  7879. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7880. return 1;
  7881. }
  7882. static int
  7883. is_valid_port(unsigned long port)
  7884. {
  7885. return (port <= 0xffff);
  7886. }
  7887. static int
  7888. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7889. {
  7890. struct addrinfo hints, *res, *ressave;
  7891. int func_ret = 0;
  7892. int gai_ret;
  7893. memset(&hints, 0, sizeof(struct addrinfo));
  7894. hints.ai_family = af;
  7895. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7896. if (gai_ret != 0) {
  7897. /* gai_strerror could be used to convert gai_ret to a string */
  7898. /* POSIX return values: see
  7899. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7900. */
  7901. /* Windows return values: see
  7902. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7903. */
  7904. return 0;
  7905. }
  7906. ressave = res;
  7907. while (res) {
  7908. if (dstlen >= (size_t)res->ai_addrlen) {
  7909. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7910. func_ret = 1;
  7911. }
  7912. res = res->ai_next;
  7913. }
  7914. freeaddrinfo(ressave);
  7915. return func_ret;
  7916. }
  7917. static int
  7918. connect_socket(struct mg_context *ctx /* may be NULL */,
  7919. const char *host,
  7920. int port,
  7921. int use_ssl,
  7922. char *ebuf,
  7923. size_t ebuf_len,
  7924. SOCKET *sock /* output: socket, must not be NULL */,
  7925. union usa *sa /* output: socket address, must not be NULL */
  7926. )
  7927. {
  7928. int ip_ver = 0;
  7929. int conn_ret = -1;
  7930. int sockerr = 0;
  7931. *sock = INVALID_SOCKET;
  7932. memset(sa, 0, sizeof(*sa));
  7933. if (ebuf_len > 0) {
  7934. *ebuf = 0;
  7935. }
  7936. if (host == NULL) {
  7937. mg_snprintf(NULL,
  7938. NULL, /* No truncation check for ebuf */
  7939. ebuf,
  7940. ebuf_len,
  7941. "%s",
  7942. "NULL host");
  7943. return 0;
  7944. }
  7945. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7946. mg_snprintf(NULL,
  7947. NULL, /* No truncation check for ebuf */
  7948. ebuf,
  7949. ebuf_len,
  7950. "%s",
  7951. "invalid port");
  7952. return 0;
  7953. }
  7954. #if !defined(NO_SSL)
  7955. #if !defined(NO_SSL_DL)
  7956. #if defined(OPENSSL_API_1_1)
  7957. if (use_ssl && (TLS_client_method == NULL)) {
  7958. mg_snprintf(NULL,
  7959. NULL, /* No truncation check for ebuf */
  7960. ebuf,
  7961. ebuf_len,
  7962. "%s",
  7963. "SSL is not initialized");
  7964. return 0;
  7965. }
  7966. #else
  7967. if (use_ssl && (SSLv23_client_method == NULL)) {
  7968. mg_snprintf(NULL,
  7969. NULL, /* No truncation check for ebuf */
  7970. ebuf,
  7971. ebuf_len,
  7972. "%s",
  7973. "SSL is not initialized");
  7974. return 0;
  7975. }
  7976. #endif /* OPENSSL_API_1_1 */
  7977. #else
  7978. (void)use_ssl;
  7979. #endif /* NO_SSL_DL */
  7980. #else
  7981. (void)use_ssl;
  7982. #endif /* !defined(NO_SSL) */
  7983. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7984. sa->sin.sin_family = AF_INET;
  7985. sa->sin.sin_port = htons((uint16_t)port);
  7986. ip_ver = 4;
  7987. #if defined(USE_IPV6)
  7988. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7989. sa->sin6.sin6_family = AF_INET6;
  7990. sa->sin6.sin6_port = htons((uint16_t)port);
  7991. ip_ver = 6;
  7992. } else if (host[0] == '[') {
  7993. /* While getaddrinfo on Windows will work with [::1],
  7994. * getaddrinfo on Linux only works with ::1 (without []). */
  7995. size_t l = strlen(host + 1);
  7996. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7997. if (h) {
  7998. h[l - 1] = 0;
  7999. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  8000. sa->sin6.sin6_family = AF_INET6;
  8001. sa->sin6.sin6_port = htons((uint16_t)port);
  8002. ip_ver = 6;
  8003. }
  8004. mg_free(h);
  8005. }
  8006. #endif
  8007. }
  8008. if (ip_ver == 0) {
  8009. mg_snprintf(NULL,
  8010. NULL, /* No truncation check for ebuf */
  8011. ebuf,
  8012. ebuf_len,
  8013. "%s",
  8014. "host not found");
  8015. return 0;
  8016. }
  8017. if (ip_ver == 4) {
  8018. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8019. }
  8020. #if defined(USE_IPV6)
  8021. else if (ip_ver == 6) {
  8022. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8023. }
  8024. #endif
  8025. if (*sock == INVALID_SOCKET) {
  8026. mg_snprintf(NULL,
  8027. NULL, /* No truncation check for ebuf */
  8028. ebuf,
  8029. ebuf_len,
  8030. "socket(): %s",
  8031. strerror(ERRNO));
  8032. return 0;
  8033. }
  8034. if (0 != set_non_blocking_mode(*sock)) {
  8035. mg_snprintf(NULL,
  8036. NULL, /* No truncation check for ebuf */
  8037. ebuf,
  8038. ebuf_len,
  8039. "Cannot set socket to non-blocking: %s",
  8040. strerror(ERRNO));
  8041. closesocket(*sock);
  8042. *sock = INVALID_SOCKET;
  8043. return 0;
  8044. }
  8045. set_close_on_exec(*sock, NULL, ctx);
  8046. if (ip_ver == 4) {
  8047. /* connected with IPv4 */
  8048. conn_ret = connect(*sock,
  8049. (struct sockaddr *)((void *)&sa->sin),
  8050. sizeof(sa->sin));
  8051. }
  8052. #if defined(USE_IPV6)
  8053. else if (ip_ver == 6) {
  8054. /* connected with IPv6 */
  8055. conn_ret = connect(*sock,
  8056. (struct sockaddr *)((void *)&sa->sin6),
  8057. sizeof(sa->sin6));
  8058. }
  8059. #endif
  8060. if (conn_ret != 0) {
  8061. sockerr = ERRNO;
  8062. }
  8063. #if defined(_WIN32)
  8064. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8065. #else
  8066. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8067. #endif
  8068. /* Data for getsockopt */
  8069. void *psockerr = &sockerr;
  8070. int ret;
  8071. #if defined(_WIN32)
  8072. int len = (int)sizeof(sockerr);
  8073. #else
  8074. socklen_t len = (socklen_t)sizeof(sockerr);
  8075. #endif
  8076. /* Data for poll */
  8077. struct mg_pollfd pfd[1];
  8078. int pollres;
  8079. int ms_wait = 10000; /* 10 second timeout */
  8080. stop_flag_t nonstop;
  8081. STOP_FLAG_ASSIGN(&nonstop, 0);
  8082. /* For a non-blocking socket, the connect sequence is:
  8083. * 1) call connect (will not block)
  8084. * 2) wait until the socket is ready for writing (select or poll)
  8085. * 3) check connection state with getsockopt
  8086. */
  8087. pfd[0].fd = *sock;
  8088. pfd[0].events = POLLOUT;
  8089. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8090. if (pollres != 1) {
  8091. /* Not connected */
  8092. mg_snprintf(NULL,
  8093. NULL, /* No truncation check for ebuf */
  8094. ebuf,
  8095. ebuf_len,
  8096. "connect(%s:%d): timeout",
  8097. host,
  8098. port);
  8099. closesocket(*sock);
  8100. *sock = INVALID_SOCKET;
  8101. return 0;
  8102. }
  8103. #if defined(_WIN32)
  8104. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8105. #else
  8106. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8107. #endif
  8108. if ((ret == 0) && (sockerr == 0)) {
  8109. conn_ret = 0;
  8110. }
  8111. }
  8112. if (conn_ret != 0) {
  8113. /* Not connected */
  8114. mg_snprintf(NULL,
  8115. NULL, /* No truncation check for ebuf */
  8116. ebuf,
  8117. ebuf_len,
  8118. "connect(%s:%d): error %s",
  8119. host,
  8120. port,
  8121. strerror(sockerr));
  8122. closesocket(*sock);
  8123. *sock = INVALID_SOCKET;
  8124. return 0;
  8125. }
  8126. return 1;
  8127. }
  8128. int
  8129. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8130. {
  8131. static const char *dont_escape = "._-$,;~()";
  8132. static const char *hex = "0123456789abcdef";
  8133. char *pos = dst;
  8134. const char *end = dst + dst_len - 1;
  8135. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8136. if (isalnum((unsigned char)*src)
  8137. || (strchr(dont_escape, *src) != NULL)) {
  8138. *pos = *src;
  8139. } else if (pos + 2 < end) {
  8140. pos[0] = '%';
  8141. pos[1] = hex[(unsigned char)*src >> 4];
  8142. pos[2] = hex[(unsigned char)*src & 0xf];
  8143. pos += 2;
  8144. } else {
  8145. break;
  8146. }
  8147. }
  8148. *pos = '\0';
  8149. return (*src == '\0') ? (int)(pos - dst) : -1;
  8150. }
  8151. /* Return 0 on success, non-zero if an error occurs. */
  8152. static int
  8153. print_dir_entry(struct de *de)
  8154. {
  8155. size_t namesize, escsize, i;
  8156. char *href, *esc, *p;
  8157. char size[64], mod[64];
  8158. #if defined(REENTRANT_TIME)
  8159. struct tm _tm;
  8160. struct tm *tm = &_tm;
  8161. #else
  8162. struct tm *tm;
  8163. #endif
  8164. /* Estimate worst case size for encoding and escaping */
  8165. namesize = strlen(de->file_name) + 1;
  8166. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8167. href = (char *)mg_malloc(namesize * 3 + escsize);
  8168. if (href == NULL) {
  8169. return -1;
  8170. }
  8171. mg_url_encode(de->file_name, href, namesize * 3);
  8172. esc = NULL;
  8173. if (escsize > 0) {
  8174. /* HTML escaping needed */
  8175. esc = href + namesize * 3;
  8176. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8177. mg_strlcpy(p, de->file_name + i, 2);
  8178. if (*p == '&') {
  8179. strcpy(p, "&amp;");
  8180. } else if (*p == '<') {
  8181. strcpy(p, "&lt;");
  8182. } else if (*p == '>') {
  8183. strcpy(p, "&gt;");
  8184. }
  8185. }
  8186. }
  8187. if (de->file.is_directory) {
  8188. mg_snprintf(de->conn,
  8189. NULL, /* Buffer is big enough */
  8190. size,
  8191. sizeof(size),
  8192. "%s",
  8193. "[DIRECTORY]");
  8194. } else {
  8195. /* We use (signed) cast below because MSVC 6 compiler cannot
  8196. * convert unsigned __int64 to double. Sigh. */
  8197. if (de->file.size < 1024) {
  8198. mg_snprintf(de->conn,
  8199. NULL, /* Buffer is big enough */
  8200. size,
  8201. sizeof(size),
  8202. "%d",
  8203. (int)de->file.size);
  8204. } else if (de->file.size < 0x100000) {
  8205. mg_snprintf(de->conn,
  8206. NULL, /* Buffer is big enough */
  8207. size,
  8208. sizeof(size),
  8209. "%.1fk",
  8210. (double)de->file.size / 1024.0);
  8211. } else if (de->file.size < 0x40000000) {
  8212. mg_snprintf(de->conn,
  8213. NULL, /* Buffer is big enough */
  8214. size,
  8215. sizeof(size),
  8216. "%.1fM",
  8217. (double)de->file.size / 1048576);
  8218. } else {
  8219. mg_snprintf(de->conn,
  8220. NULL, /* Buffer is big enough */
  8221. size,
  8222. sizeof(size),
  8223. "%.1fG",
  8224. (double)de->file.size / 1073741824);
  8225. }
  8226. }
  8227. /* Note: mg_snprintf will not cause a buffer overflow above.
  8228. * So, string truncation checks are not required here. */
  8229. #if defined(REENTRANT_TIME)
  8230. localtime_r(&de->file.last_modified, tm);
  8231. #else
  8232. tm = localtime(&de->file.last_modified);
  8233. #endif
  8234. if (tm != NULL) {
  8235. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8236. } else {
  8237. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8238. mod[sizeof(mod) - 1] = '\0';
  8239. }
  8240. mg_printf(de->conn,
  8241. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8242. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8243. href,
  8244. de->file.is_directory ? "/" : "",
  8245. esc ? esc : de->file_name,
  8246. de->file.is_directory ? "/" : "",
  8247. mod,
  8248. size);
  8249. mg_free(href);
  8250. return 0;
  8251. }
  8252. /* This function is called from send_directory() and used for
  8253. * sorting directory entries by size, or name, or modification time.
  8254. * On windows, __cdecl specification is needed in case if project is built
  8255. * with __stdcall convention. qsort always requires __cdels callback. */
  8256. static int WINCDECL
  8257. compare_dir_entries(const void *p1, const void *p2)
  8258. {
  8259. if (p1 && p2) {
  8260. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8261. const char *query_string = a->conn->request_info.query_string;
  8262. int cmp_result = 0;
  8263. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8264. query_string = "n";
  8265. }
  8266. if (a->file.is_directory && !b->file.is_directory) {
  8267. return -1; /* Always put directories on top */
  8268. } else if (!a->file.is_directory && b->file.is_directory) {
  8269. return 1; /* Always put directories on top */
  8270. } else if (*query_string == 'n') {
  8271. cmp_result = strcmp(a->file_name, b->file_name);
  8272. } else if (*query_string == 's') {
  8273. cmp_result = (a->file.size == b->file.size)
  8274. ? 0
  8275. : ((a->file.size > b->file.size) ? 1 : -1);
  8276. } else if (*query_string == 'd') {
  8277. cmp_result =
  8278. (a->file.last_modified == b->file.last_modified)
  8279. ? 0
  8280. : ((a->file.last_modified > b->file.last_modified) ? 1
  8281. : -1);
  8282. }
  8283. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8284. }
  8285. return 0;
  8286. }
  8287. static int
  8288. must_hide_file(struct mg_connection *conn, const char *path)
  8289. {
  8290. if (conn && conn->dom_ctx) {
  8291. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8292. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8293. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8294. || ((pattern != NULL)
  8295. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8296. }
  8297. return 0;
  8298. }
  8299. #if !defined(NO_FILESYSTEMS)
  8300. static int
  8301. scan_directory(struct mg_connection *conn,
  8302. const char *dir,
  8303. void *data,
  8304. int (*cb)(struct de *, void *))
  8305. {
  8306. char path[PATH_MAX];
  8307. struct dirent *dp;
  8308. DIR *dirp;
  8309. struct de de;
  8310. int truncated;
  8311. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8312. return 0;
  8313. } else {
  8314. de.conn = conn;
  8315. while ((dp = mg_readdir(dirp)) != NULL) {
  8316. /* Do not show current dir and hidden files */
  8317. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8318. || must_hide_file(conn, dp->d_name)) {
  8319. continue;
  8320. }
  8321. mg_snprintf(
  8322. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8323. /* If we don't memset stat structure to zero, mtime will have
  8324. * garbage and strftime() will segfault later on in
  8325. * print_dir_entry(). memset is required only if mg_stat()
  8326. * fails. For more details, see
  8327. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8328. memset(&de.file, 0, sizeof(de.file));
  8329. if (truncated) {
  8330. /* If the path is not complete, skip processing. */
  8331. continue;
  8332. }
  8333. if (!mg_stat(conn, path, &de.file)) {
  8334. mg_cry_internal(conn,
  8335. "%s: mg_stat(%s) failed: %s",
  8336. __func__,
  8337. path,
  8338. strerror(ERRNO));
  8339. }
  8340. de.file_name = dp->d_name;
  8341. cb(&de, data);
  8342. }
  8343. (void)mg_closedir(dirp);
  8344. }
  8345. return 1;
  8346. }
  8347. #endif /* NO_FILESYSTEMS */
  8348. #if !defined(NO_FILES)
  8349. static int
  8350. remove_directory(struct mg_connection *conn, const char *dir)
  8351. {
  8352. char path[PATH_MAX];
  8353. struct dirent *dp;
  8354. DIR *dirp;
  8355. struct de de;
  8356. int truncated;
  8357. int ok = 1;
  8358. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8359. return 0;
  8360. } else {
  8361. de.conn = conn;
  8362. while ((dp = mg_readdir(dirp)) != NULL) {
  8363. /* Do not show current dir (but show hidden files as they will
  8364. * also be removed) */
  8365. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8366. continue;
  8367. }
  8368. mg_snprintf(
  8369. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8370. /* If we don't memset stat structure to zero, mtime will have
  8371. * garbage and strftime() will segfault later on in
  8372. * print_dir_entry(). memset is required only if mg_stat()
  8373. * fails. For more details, see
  8374. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8375. memset(&de.file, 0, sizeof(de.file));
  8376. if (truncated) {
  8377. /* Do not delete anything shorter */
  8378. ok = 0;
  8379. continue;
  8380. }
  8381. if (!mg_stat(conn, path, &de.file)) {
  8382. mg_cry_internal(conn,
  8383. "%s: mg_stat(%s) failed: %s",
  8384. __func__,
  8385. path,
  8386. strerror(ERRNO));
  8387. ok = 0;
  8388. }
  8389. if (de.file.is_directory) {
  8390. if (remove_directory(conn, path) == 0) {
  8391. ok = 0;
  8392. }
  8393. } else {
  8394. /* This will fail file is the file is in memory */
  8395. if (mg_remove(conn, path) == 0) {
  8396. ok = 0;
  8397. }
  8398. }
  8399. }
  8400. (void)mg_closedir(dirp);
  8401. IGNORE_UNUSED_RESULT(rmdir(dir));
  8402. }
  8403. return ok;
  8404. }
  8405. #endif
  8406. struct dir_scan_data {
  8407. struct de *entries;
  8408. unsigned int num_entries;
  8409. unsigned int arr_size;
  8410. };
  8411. /* Behaves like realloc(), but frees original pointer on failure */
  8412. static void *
  8413. realloc2(void *ptr, size_t size)
  8414. {
  8415. void *new_ptr = mg_realloc(ptr, size);
  8416. if ((new_ptr == NULL) && (size > 0)) {
  8417. mg_free(ptr);
  8418. }
  8419. return new_ptr;
  8420. }
  8421. #if !defined(NO_FILESYSTEMS)
  8422. static int
  8423. dir_scan_callback(struct de *de, void *data)
  8424. {
  8425. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8426. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8427. dsd->arr_size *= 2;
  8428. dsd->entries =
  8429. (struct de *)realloc2(dsd->entries,
  8430. dsd->arr_size * sizeof(dsd->entries[0]));
  8431. }
  8432. if (dsd->entries == NULL) {
  8433. /* TODO(lsm, low): propagate an error to the caller */
  8434. dsd->num_entries = 0;
  8435. } else {
  8436. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8437. dsd->entries[dsd->num_entries].file = de->file;
  8438. dsd->entries[dsd->num_entries].conn = de->conn;
  8439. dsd->num_entries++;
  8440. }
  8441. return 0;
  8442. }
  8443. static void
  8444. handle_directory_request(struct mg_connection *conn, const char *dir)
  8445. {
  8446. unsigned int i;
  8447. int sort_direction;
  8448. struct dir_scan_data data = {NULL, 0, 128};
  8449. char date[64], *esc, *p;
  8450. const char *title;
  8451. time_t curtime = time(NULL);
  8452. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8453. mg_send_http_error(conn,
  8454. 500,
  8455. "Error: Cannot open directory\nopendir(%s): %s",
  8456. dir,
  8457. strerror(ERRNO));
  8458. return;
  8459. }
  8460. gmt_time_string(date, sizeof(date), &curtime);
  8461. if (!conn) {
  8462. return;
  8463. }
  8464. esc = NULL;
  8465. title = conn->request_info.local_uri;
  8466. if (title[strcspn(title, "&<>")]) {
  8467. /* HTML escaping needed */
  8468. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8469. if (esc) {
  8470. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8471. mg_strlcpy(p, title + i, 2);
  8472. if (*p == '&') {
  8473. strcpy(p, "&amp;");
  8474. } else if (*p == '<') {
  8475. strcpy(p, "&lt;");
  8476. } else if (*p == '>') {
  8477. strcpy(p, "&gt;");
  8478. }
  8479. }
  8480. } else {
  8481. title = "";
  8482. }
  8483. }
  8484. sort_direction = ((conn->request_info.query_string != NULL)
  8485. && (conn->request_info.query_string[0] != '\0')
  8486. && (conn->request_info.query_string[1] == 'd'))
  8487. ? 'a'
  8488. : 'd';
  8489. conn->must_close = 1;
  8490. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8491. send_static_cache_header(conn);
  8492. send_additional_header(conn);
  8493. mg_printf(conn,
  8494. "Date: %s\r\n"
  8495. "Connection: close\r\n"
  8496. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8497. date);
  8498. mg_printf(conn,
  8499. "<html><head><title>Index of %s</title>"
  8500. "<style>th {text-align: left;}</style></head>"
  8501. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8502. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8503. "<th><a href=\"?d%c\">Modified</a></th>"
  8504. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8505. "<tr><td colspan=\"3\"><hr></td></tr>",
  8506. esc ? esc : title,
  8507. esc ? esc : title,
  8508. sort_direction,
  8509. sort_direction,
  8510. sort_direction);
  8511. mg_free(esc);
  8512. /* Print first entry - link to a parent directory */
  8513. mg_printf(conn,
  8514. "<tr><td><a href=\"%s\">%s</a></td>"
  8515. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8516. "..",
  8517. "Parent directory",
  8518. "-",
  8519. "-");
  8520. /* Sort and print directory entries */
  8521. if (data.entries != NULL) {
  8522. qsort(data.entries,
  8523. (size_t)data.num_entries,
  8524. sizeof(data.entries[0]),
  8525. compare_dir_entries);
  8526. for (i = 0; i < data.num_entries; i++) {
  8527. print_dir_entry(&data.entries[i]);
  8528. mg_free(data.entries[i].file_name);
  8529. }
  8530. mg_free(data.entries);
  8531. }
  8532. mg_printf(conn, "%s", "</table></pre></body></html>");
  8533. conn->status_code = 200;
  8534. }
  8535. #endif /* NO_FILESYSTEMS */
  8536. /* Send len bytes from the opened file to the client. */
  8537. static void
  8538. send_file_data(struct mg_connection *conn,
  8539. struct mg_file *filep,
  8540. int64_t offset,
  8541. int64_t len)
  8542. {
  8543. char buf[MG_BUF_LEN];
  8544. int to_read, num_read, num_written;
  8545. int64_t size;
  8546. if (!filep || !conn) {
  8547. return;
  8548. }
  8549. /* Sanity check the offset */
  8550. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8551. : (int64_t)(filep->stat.size);
  8552. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8553. #if defined(MG_USE_OPEN_FILE)
  8554. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8555. /* file stored in memory */
  8556. if (len > size - offset) {
  8557. len = size - offset;
  8558. }
  8559. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8560. } else /* else block below */
  8561. #endif
  8562. if (len > 0 && filep->access.fp != NULL) {
  8563. /* file stored on disk */
  8564. #if defined(__linux__)
  8565. /* sendfile is only available for Linux */
  8566. if ((conn->ssl == 0) && (conn->throttle == 0)
  8567. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8568. "yes"))) {
  8569. off_t sf_offs = (off_t)offset;
  8570. ssize_t sf_sent;
  8571. int sf_file = fileno(filep->access.fp);
  8572. int loop_cnt = 0;
  8573. do {
  8574. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8575. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8576. size_t sf_tosend =
  8577. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8578. sf_sent =
  8579. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8580. if (sf_sent > 0) {
  8581. len -= sf_sent;
  8582. offset += sf_sent;
  8583. } else if (loop_cnt == 0) {
  8584. /* This file can not be sent using sendfile.
  8585. * This might be the case for pseudo-files in the
  8586. * /sys/ and /proc/ file system.
  8587. * Use the regular user mode copy code instead. */
  8588. break;
  8589. } else if (sf_sent == 0) {
  8590. /* No error, but 0 bytes sent. May be EOF? */
  8591. return;
  8592. }
  8593. loop_cnt++;
  8594. } while ((len > 0) && (sf_sent >= 0));
  8595. if (sf_sent > 0) {
  8596. return; /* OK */
  8597. }
  8598. /* sf_sent<0 means error, thus fall back to the classic way */
  8599. /* This is always the case, if sf_file is not a "normal" file,
  8600. * e.g., for sending data from the output of a CGI process. */
  8601. offset = (int64_t)sf_offs;
  8602. }
  8603. #endif
  8604. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8605. mg_cry_internal(conn,
  8606. "%s: fseeko() failed: %s",
  8607. __func__,
  8608. strerror(ERRNO));
  8609. mg_send_http_error(
  8610. conn,
  8611. 500,
  8612. "%s",
  8613. "Error: Unable to access file at requested position.");
  8614. } else {
  8615. while (len > 0) {
  8616. /* Calculate how much to read from the file in the buffer */
  8617. to_read = sizeof(buf);
  8618. if ((int64_t)to_read > len) {
  8619. to_read = (int)len;
  8620. }
  8621. /* Read from file, exit the loop on error */
  8622. if ((num_read =
  8623. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8624. <= 0) {
  8625. break;
  8626. }
  8627. /* Send read bytes to the client, exit the loop on error */
  8628. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8629. != num_read) {
  8630. break;
  8631. }
  8632. /* Both read and were successful, adjust counters */
  8633. len -= num_written;
  8634. }
  8635. }
  8636. }
  8637. }
  8638. static int
  8639. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8640. {
  8641. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8642. }
  8643. static void
  8644. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8645. {
  8646. if ((filestat != NULL) && (buf != NULL)) {
  8647. mg_snprintf(NULL,
  8648. NULL, /* All calls to construct_etag use 64 byte buffer */
  8649. buf,
  8650. buf_len,
  8651. "\"%lx.%" INT64_FMT "\"",
  8652. (unsigned long)filestat->last_modified,
  8653. filestat->size);
  8654. }
  8655. }
  8656. static void
  8657. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8658. {
  8659. if (filep != NULL && filep->fp != NULL) {
  8660. #if defined(_WIN32)
  8661. (void)conn; /* Unused. */
  8662. #else
  8663. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8664. mg_cry_internal(conn,
  8665. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8666. __func__,
  8667. strerror(ERRNO));
  8668. }
  8669. #endif
  8670. }
  8671. }
  8672. #if defined(USE_ZLIB)
  8673. #include "mod_zlib.inl"
  8674. #endif
  8675. #if !defined(NO_FILESYSTEMS)
  8676. static void
  8677. handle_static_file_request(struct mg_connection *conn,
  8678. const char *path,
  8679. struct mg_file *filep,
  8680. const char *mime_type,
  8681. const char *additional_headers)
  8682. {
  8683. char date[64], lm[64], etag[64];
  8684. char range[128]; /* large enough, so there will be no overflow */
  8685. const char *msg = "OK";
  8686. const char *range_hdr;
  8687. time_t curtime = time(NULL);
  8688. int64_t cl, r1, r2;
  8689. struct vec mime_vec;
  8690. int n, truncated;
  8691. char gz_path[PATH_MAX];
  8692. const char *encoding = "";
  8693. const char *origin_hdr;
  8694. const char *cors_orig_cfg;
  8695. const char *cors1, *cors2, *cors3;
  8696. int is_head_request;
  8697. #if defined(USE_ZLIB)
  8698. /* Compression is allowed, unless there is a reason not to use
  8699. * compression. If the file is already compressed, too small or a
  8700. * "range" request was made, on the fly compression is not possible. */
  8701. int allow_on_the_fly_compression = 1;
  8702. #endif
  8703. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8704. return;
  8705. }
  8706. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8707. if (mime_type == NULL) {
  8708. get_mime_type(conn, path, &mime_vec);
  8709. } else {
  8710. mime_vec.ptr = mime_type;
  8711. mime_vec.len = strlen(mime_type);
  8712. }
  8713. if (filep->stat.size > INT64_MAX) {
  8714. mg_send_http_error(conn,
  8715. 500,
  8716. "Error: File size is too large to send\n%" INT64_FMT,
  8717. filep->stat.size);
  8718. return;
  8719. }
  8720. cl = (int64_t)filep->stat.size;
  8721. conn->status_code = 200;
  8722. range[0] = '\0';
  8723. #if defined(USE_ZLIB)
  8724. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8725. * it's important to rewrite the filename after resolving
  8726. * the mime type from it, to preserve the actual file's type */
  8727. if (!conn->accept_gzip) {
  8728. allow_on_the_fly_compression = 0;
  8729. }
  8730. #endif
  8731. /* Check if there is a range header */
  8732. range_hdr = mg_get_header(conn, "Range");
  8733. /* For gzipped files, add *.gz */
  8734. if (filep->stat.is_gzipped) {
  8735. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8736. if (truncated) {
  8737. mg_send_http_error(conn,
  8738. 500,
  8739. "Error: Path of zipped file too long (%s)",
  8740. path);
  8741. return;
  8742. }
  8743. path = gz_path;
  8744. encoding = "Content-Encoding: gzip\r\n";
  8745. #if defined(USE_ZLIB)
  8746. /* File is already compressed. No "on the fly" compression. */
  8747. allow_on_the_fly_compression = 0;
  8748. #endif
  8749. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8750. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8751. struct mg_file_stat file_stat;
  8752. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8753. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8754. && !file_stat.is_directory) {
  8755. file_stat.is_gzipped = 1;
  8756. filep->stat = file_stat;
  8757. cl = (int64_t)filep->stat.size;
  8758. path = gz_path;
  8759. encoding = "Content-Encoding: gzip\r\n";
  8760. #if defined(USE_ZLIB)
  8761. /* File is already compressed. No "on the fly" compression. */
  8762. allow_on_the_fly_compression = 0;
  8763. #endif
  8764. }
  8765. }
  8766. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8767. mg_send_http_error(conn,
  8768. 500,
  8769. "Error: Cannot open file\nfopen(%s): %s",
  8770. path,
  8771. strerror(ERRNO));
  8772. return;
  8773. }
  8774. fclose_on_exec(&filep->access, conn);
  8775. /* If "Range" request was made: parse header, send only selected part
  8776. * of the file. */
  8777. r1 = r2 = 0;
  8778. if ((range_hdr != NULL)
  8779. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8780. && (r2 >= 0)) {
  8781. /* actually, range requests don't play well with a pre-gzipped
  8782. * file (since the range is specified in the uncompressed space) */
  8783. if (filep->stat.is_gzipped) {
  8784. mg_send_http_error(
  8785. conn,
  8786. 416, /* 416 = Range Not Satisfiable */
  8787. "%s",
  8788. "Error: Range requests in gzipped files are not supported");
  8789. (void)mg_fclose(
  8790. &filep->access); /* ignore error on read only file */
  8791. return;
  8792. }
  8793. conn->status_code = 206;
  8794. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8795. mg_snprintf(conn,
  8796. NULL, /* range buffer is big enough */
  8797. range,
  8798. sizeof(range),
  8799. "Content-Range: bytes "
  8800. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8801. r1,
  8802. r1 + cl - 1,
  8803. filep->stat.size);
  8804. msg = "Partial Content";
  8805. #if defined(USE_ZLIB)
  8806. /* Do not compress ranges. */
  8807. allow_on_the_fly_compression = 0;
  8808. #endif
  8809. }
  8810. /* Do not compress small files. Small files do not benefit from file
  8811. * compression, but there is still some overhead. */
  8812. #if defined(USE_ZLIB)
  8813. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8814. /* File is below the size limit. */
  8815. allow_on_the_fly_compression = 0;
  8816. }
  8817. #endif
  8818. /* Standard CORS header */
  8819. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8820. origin_hdr = mg_get_header(conn, "Origin");
  8821. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8822. /* Cross-origin resource sharing (CORS), see
  8823. * http://www.html5rocks.com/en/tutorials/cors/,
  8824. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8825. * -
  8826. * preflight is not supported for files. */
  8827. cors1 = "Access-Control-Allow-Origin: ";
  8828. cors2 = cors_orig_cfg;
  8829. cors3 = "\r\n";
  8830. } else {
  8831. cors1 = cors2 = cors3 = "";
  8832. }
  8833. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8834. * according to
  8835. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8836. gmt_time_string(date, sizeof(date), &curtime);
  8837. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8838. construct_etag(etag, sizeof(etag), &filep->stat);
  8839. /* Send header */
  8840. (void)mg_printf(conn,
  8841. "HTTP/1.1 %d %s\r\n"
  8842. "%s%s%s" /* CORS */
  8843. "Date: %s\r\n"
  8844. "Last-Modified: %s\r\n"
  8845. "Etag: %s\r\n"
  8846. "Content-Type: %.*s\r\n"
  8847. "Connection: %s\r\n",
  8848. conn->status_code,
  8849. msg,
  8850. cors1,
  8851. cors2,
  8852. cors3,
  8853. date,
  8854. lm,
  8855. etag,
  8856. (int)mime_vec.len,
  8857. mime_vec.ptr,
  8858. suggest_connection_header(conn));
  8859. send_static_cache_header(conn);
  8860. send_additional_header(conn);
  8861. #if defined(USE_ZLIB)
  8862. /* On the fly compression allowed */
  8863. if (allow_on_the_fly_compression) {
  8864. /* For on the fly compression, we don't know the content size in
  8865. * advance, so we have to use chunked encoding */
  8866. (void)mg_printf(conn,
  8867. "Content-Encoding: gzip\r\n"
  8868. "Transfer-Encoding: chunked\r\n");
  8869. } else
  8870. #endif
  8871. {
  8872. /* Without on-the-fly compression, we know the content-length
  8873. * and we can use ranges (with on-the-fly compression we cannot).
  8874. * So we send these response headers only in this case. */
  8875. (void)mg_printf(conn,
  8876. "Content-Length: %" INT64_FMT "\r\n"
  8877. "Accept-Ranges: bytes\r\n"
  8878. "%s" /* range */
  8879. "%s" /* encoding */,
  8880. cl,
  8881. range,
  8882. encoding);
  8883. }
  8884. /* The previous code must not add any header starting with X- to make
  8885. * sure no one of the additional_headers is included twice */
  8886. if (additional_headers != NULL) {
  8887. (void)mg_printf(conn,
  8888. "%.*s\r\n\r\n",
  8889. (int)strlen(additional_headers),
  8890. additional_headers);
  8891. } else {
  8892. (void)mg_printf(conn, "\r\n");
  8893. }
  8894. if (!is_head_request) {
  8895. #if defined(USE_ZLIB)
  8896. if (allow_on_the_fly_compression) {
  8897. /* Compress and send */
  8898. send_compressed_data(conn, filep);
  8899. } else
  8900. #endif
  8901. {
  8902. /* Send file directly */
  8903. send_file_data(conn, filep, r1, cl);
  8904. }
  8905. }
  8906. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8907. }
  8908. int
  8909. mg_send_file_body(struct mg_connection *conn, const char *path)
  8910. {
  8911. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8912. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8913. return -1;
  8914. }
  8915. fclose_on_exec(&file.access, conn);
  8916. send_file_data(conn, &file, 0, INT64_MAX);
  8917. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8918. return 0; /* >= 0 for OK */
  8919. }
  8920. #endif /* NO_FILESYSTEMS */
  8921. #if !defined(NO_CACHING)
  8922. /* Return True if we should reply 304 Not Modified. */
  8923. static int
  8924. is_not_modified(const struct mg_connection *conn,
  8925. const struct mg_file_stat *filestat)
  8926. {
  8927. char etag[64];
  8928. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8929. const char *inm = mg_get_header(conn, "If-None-Match");
  8930. construct_etag(etag, sizeof(etag), filestat);
  8931. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8932. || ((ims != NULL)
  8933. && (filestat->last_modified <= parse_date_string(ims)));
  8934. }
  8935. static void
  8936. handle_not_modified_static_file_request(struct mg_connection *conn,
  8937. struct mg_file *filep)
  8938. {
  8939. char date[64], lm[64], etag[64];
  8940. time_t curtime = time(NULL);
  8941. if ((conn == NULL) || (filep == NULL)) {
  8942. return;
  8943. }
  8944. conn->status_code = 304;
  8945. gmt_time_string(date, sizeof(date), &curtime);
  8946. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8947. construct_etag(etag, sizeof(etag), &filep->stat);
  8948. (void)mg_printf(conn,
  8949. "HTTP/1.1 %d %s\r\n"
  8950. "Date: %s\r\n",
  8951. conn->status_code,
  8952. mg_get_response_code_text(conn, conn->status_code),
  8953. date);
  8954. send_static_cache_header(conn);
  8955. send_additional_header(conn);
  8956. (void)mg_printf(conn,
  8957. "Last-Modified: %s\r\n"
  8958. "Etag: %s\r\n"
  8959. "Connection: %s\r\n"
  8960. "\r\n",
  8961. lm,
  8962. etag,
  8963. suggest_connection_header(conn));
  8964. }
  8965. #endif
  8966. #if !defined(NO_FILESYSTEMS)
  8967. void
  8968. mg_send_file(struct mg_connection *conn, const char *path)
  8969. {
  8970. mg_send_mime_file2(conn, path, NULL, NULL);
  8971. }
  8972. void
  8973. mg_send_mime_file(struct mg_connection *conn,
  8974. const char *path,
  8975. const char *mime_type)
  8976. {
  8977. mg_send_mime_file2(conn, path, mime_type, NULL);
  8978. }
  8979. void
  8980. mg_send_mime_file2(struct mg_connection *conn,
  8981. const char *path,
  8982. const char *mime_type,
  8983. const char *additional_headers)
  8984. {
  8985. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8986. if (!conn) {
  8987. /* No conn */
  8988. return;
  8989. }
  8990. if (mg_stat(conn, path, &file.stat)) {
  8991. #if !defined(NO_CACHING)
  8992. if (is_not_modified(conn, &file.stat)) {
  8993. /* Send 304 "Not Modified" - this must not send any body data */
  8994. handle_not_modified_static_file_request(conn, &file);
  8995. } else
  8996. #endif /* NO_CACHING */
  8997. if (file.stat.is_directory) {
  8998. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8999. "yes")) {
  9000. handle_directory_request(conn, path);
  9001. } else {
  9002. mg_send_http_error(conn,
  9003. 403,
  9004. "%s",
  9005. "Error: Directory listing denied");
  9006. }
  9007. } else {
  9008. handle_static_file_request(
  9009. conn, path, &file, mime_type, additional_headers);
  9010. }
  9011. } else {
  9012. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9013. }
  9014. }
  9015. /* For a given PUT path, create all intermediate subdirectories.
  9016. * Return 0 if the path itself is a directory.
  9017. * Return 1 if the path leads to a file.
  9018. * Return -1 for if the path is too long.
  9019. * Return -2 if path can not be created.
  9020. */
  9021. static int
  9022. put_dir(struct mg_connection *conn, const char *path)
  9023. {
  9024. char buf[PATH_MAX];
  9025. const char *s, *p;
  9026. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9027. size_t len;
  9028. int res = 1;
  9029. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9030. len = (size_t)(p - path);
  9031. if (len >= sizeof(buf)) {
  9032. /* path too long */
  9033. res = -1;
  9034. break;
  9035. }
  9036. memcpy(buf, path, len);
  9037. buf[len] = '\0';
  9038. /* Try to create intermediate directory */
  9039. DEBUG_TRACE("mkdir(%s)", buf);
  9040. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9041. /* path does not exixt and can not be created */
  9042. res = -2;
  9043. break;
  9044. }
  9045. /* Is path itself a directory? */
  9046. if (p[1] == '\0') {
  9047. res = 0;
  9048. }
  9049. }
  9050. return res;
  9051. }
  9052. static void
  9053. remove_bad_file(const struct mg_connection *conn, const char *path)
  9054. {
  9055. int r = mg_remove(conn, path);
  9056. if (r != 0) {
  9057. mg_cry_internal(conn,
  9058. "%s: Cannot remove invalid file %s",
  9059. __func__,
  9060. path);
  9061. }
  9062. }
  9063. long long
  9064. mg_store_body(struct mg_connection *conn, const char *path)
  9065. {
  9066. char buf[MG_BUF_LEN];
  9067. long long len = 0;
  9068. int ret, n;
  9069. struct mg_file fi;
  9070. if (conn->consumed_content != 0) {
  9071. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9072. return -11;
  9073. }
  9074. ret = put_dir(conn, path);
  9075. if (ret < 0) {
  9076. /* -1 for path too long,
  9077. * -2 for path can not be created. */
  9078. return ret;
  9079. }
  9080. if (ret != 1) {
  9081. /* Return 0 means, path itself is a directory. */
  9082. return 0;
  9083. }
  9084. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9085. return -12;
  9086. }
  9087. ret = mg_read(conn, buf, sizeof(buf));
  9088. while (ret > 0) {
  9089. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9090. if (n != ret) {
  9091. (void)mg_fclose(
  9092. &fi.access); /* File is bad and will be removed anyway. */
  9093. remove_bad_file(conn, path);
  9094. return -13;
  9095. }
  9096. len += ret;
  9097. ret = mg_read(conn, buf, sizeof(buf));
  9098. }
  9099. /* File is open for writing. If fclose fails, there was probably an
  9100. * error flushing the buffer to disk, so the file on disk might be
  9101. * broken. Delete it and return an error to the caller. */
  9102. if (mg_fclose(&fi.access) != 0) {
  9103. remove_bad_file(conn, path);
  9104. return -14;
  9105. }
  9106. return len;
  9107. }
  9108. #endif /* NO_FILESYSTEMS */
  9109. /* Parse a buffer:
  9110. * Forward the string pointer till the end of a word, then
  9111. * terminate it and forward till the begin of the next word.
  9112. */
  9113. static int
  9114. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9115. {
  9116. /* Forward until a space is found - use isgraph here */
  9117. /* See http://www.cplusplus.com/reference/cctype/ */
  9118. while (isgraph((unsigned char)**ppw)) {
  9119. (*ppw)++;
  9120. }
  9121. /* Check end of word */
  9122. if (eol) {
  9123. /* must be a end of line */
  9124. if ((**ppw != '\r') && (**ppw != '\n')) {
  9125. return -1;
  9126. }
  9127. } else {
  9128. /* must be a end of a word, but not a line */
  9129. if (**ppw != ' ') {
  9130. return -1;
  9131. }
  9132. }
  9133. /* Terminate and forward to the next word */
  9134. do {
  9135. **ppw = 0;
  9136. (*ppw)++;
  9137. } while (isspace((unsigned char)**ppw));
  9138. /* Check after term */
  9139. if (!eol) {
  9140. /* if it's not the end of line, there must be a next word */
  9141. if (!isgraph((unsigned char)**ppw)) {
  9142. return -1;
  9143. }
  9144. }
  9145. /* ok */
  9146. return 1;
  9147. }
  9148. /* Parse HTTP headers from the given buffer, advance buf pointer
  9149. * to the point where parsing stopped.
  9150. * All parameters must be valid pointers (not NULL).
  9151. * Return <0 on error. */
  9152. static int
  9153. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9154. {
  9155. int i;
  9156. int num_headers = 0;
  9157. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9158. char *dp = *buf;
  9159. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9160. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9161. dp++;
  9162. }
  9163. if (dp == *buf) {
  9164. /* End of headers reached. */
  9165. break;
  9166. }
  9167. if (*dp != ':') {
  9168. /* This is not a valid field. */
  9169. return -1;
  9170. }
  9171. /* End of header key (*dp == ':') */
  9172. /* Truncate here and set the key name */
  9173. *dp = 0;
  9174. hdr[i].name = *buf;
  9175. /* Skip all spaces */
  9176. do {
  9177. dp++;
  9178. } while ((*dp == ' ') || (*dp == '\t'));
  9179. /* The rest of the line is the value */
  9180. hdr[i].value = dp;
  9181. /* Find end of line */
  9182. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9183. dp++;
  9184. };
  9185. /* eliminate \r */
  9186. if (*dp == '\r') {
  9187. *dp = 0;
  9188. dp++;
  9189. if (*dp != '\n') {
  9190. /* This is not a valid line. */
  9191. return -1;
  9192. }
  9193. }
  9194. /* here *dp is either 0 or '\n' */
  9195. /* in any case, we have a new header */
  9196. num_headers = i + 1;
  9197. if (*dp) {
  9198. *dp = 0;
  9199. dp++;
  9200. *buf = dp;
  9201. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9202. /* This is the end of the header */
  9203. break;
  9204. }
  9205. } else {
  9206. *buf = dp;
  9207. break;
  9208. }
  9209. }
  9210. return num_headers;
  9211. }
  9212. struct mg_http_method_info {
  9213. const char *name;
  9214. int request_has_body;
  9215. int response_has_body;
  9216. int is_safe;
  9217. int is_idempotent;
  9218. int is_cacheable;
  9219. };
  9220. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9221. static const struct mg_http_method_info http_methods[] = {
  9222. /* HTTP (RFC 2616) */
  9223. {"GET", 0, 1, 1, 1, 1},
  9224. {"POST", 1, 1, 0, 0, 0},
  9225. {"PUT", 1, 0, 0, 1, 0},
  9226. {"DELETE", 0, 0, 0, 1, 0},
  9227. {"HEAD", 0, 0, 1, 1, 1},
  9228. {"OPTIONS", 0, 0, 1, 1, 0},
  9229. {"CONNECT", 1, 1, 0, 0, 0},
  9230. /* TRACE method (RFC 2616) is not supported for security reasons */
  9231. /* PATCH method (RFC 5789) */
  9232. {"PATCH", 1, 0, 0, 0, 0},
  9233. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9234. /* WEBDAV (RFC 2518) */
  9235. {"PROPFIND", 0, 1, 1, 1, 0},
  9236. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9237. * Some PROPFIND results MAY be cached, with care,
  9238. * as there is no cache validation mechanism for
  9239. * most properties. This method is both safe and
  9240. * idempotent (see Section 9.1 of [RFC2616]). */
  9241. {"MKCOL", 0, 0, 0, 1, 0},
  9242. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9243. * When MKCOL is invoked without a request body,
  9244. * the newly created collection SHOULD have no
  9245. * members. A MKCOL request message may contain
  9246. * a message body. The precise behavior of a MKCOL
  9247. * request when the body is present is undefined,
  9248. * ... ==> We do not support MKCOL with body data.
  9249. * This method is idempotent, but not safe (see
  9250. * Section 9.1 of [RFC2616]). Responses to this
  9251. * method MUST NOT be cached. */
  9252. /* Unsupported WEBDAV Methods: */
  9253. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9254. /* + 11 methods from RFC 3253 */
  9255. /* ORDERPATCH (RFC 3648) */
  9256. /* ACL (RFC 3744) */
  9257. /* SEARCH (RFC 5323) */
  9258. /* + MicroSoft extensions
  9259. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9260. /* REPORT method (RFC 3253) */
  9261. {"REPORT", 1, 1, 1, 1, 1},
  9262. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9263. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9264. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9265. * to be useful for REST in case a "GET request with body" is
  9266. * required. */
  9267. {NULL, 0, 0, 0, 0, 0}
  9268. /* end of list */
  9269. };
  9270. static const struct mg_http_method_info *
  9271. get_http_method_info(const char *method)
  9272. {
  9273. /* Check if the method is known to the server. The list of all known
  9274. * HTTP methods can be found here at
  9275. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9276. */
  9277. const struct mg_http_method_info *m = http_methods;
  9278. while (m->name) {
  9279. if (!strcmp(m->name, method)) {
  9280. return m;
  9281. }
  9282. m++;
  9283. }
  9284. return NULL;
  9285. }
  9286. static int
  9287. is_valid_http_method(const char *method)
  9288. {
  9289. return (get_http_method_info(method) != NULL);
  9290. }
  9291. /* Parse HTTP request, fill in mg_request_info structure.
  9292. * This function modifies the buffer by NUL-terminating
  9293. * HTTP request components, header names and header values.
  9294. * Parameters:
  9295. * buf (in/out): pointer to the HTTP header to parse and split
  9296. * len (in): length of HTTP header buffer
  9297. * re (out): parsed header as mg_request_info
  9298. * buf and ri must be valid pointers (not NULL), len>0.
  9299. * Returns <0 on error. */
  9300. static int
  9301. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9302. {
  9303. int request_length;
  9304. int init_skip = 0;
  9305. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9306. * remote_port */
  9307. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9308. NULL;
  9309. ri->num_headers = 0;
  9310. /* RFC says that all initial whitespaces should be ingored */
  9311. /* This included all leading \r and \n (isspace) */
  9312. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9313. while ((len > 0) && isspace((unsigned char)*buf)) {
  9314. buf++;
  9315. len--;
  9316. init_skip++;
  9317. }
  9318. if (len == 0) {
  9319. /* Incomplete request */
  9320. return 0;
  9321. }
  9322. /* Control characters are not allowed, including zero */
  9323. if (iscntrl((unsigned char)*buf)) {
  9324. return -1;
  9325. }
  9326. /* Find end of HTTP header */
  9327. request_length = get_http_header_len(buf, len);
  9328. if (request_length <= 0) {
  9329. return request_length;
  9330. }
  9331. buf[request_length - 1] = '\0';
  9332. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9333. return -1;
  9334. }
  9335. /* The first word has to be the HTTP method */
  9336. ri->request_method = buf;
  9337. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9338. return -1;
  9339. }
  9340. /* Check for a valid http method */
  9341. if (!is_valid_http_method(ri->request_method)) {
  9342. return -1;
  9343. }
  9344. /* The second word is the URI */
  9345. ri->request_uri = buf;
  9346. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9347. return -1;
  9348. }
  9349. /* Next would be the HTTP version */
  9350. ri->http_version = buf;
  9351. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9352. return -1;
  9353. }
  9354. /* Check for a valid HTTP version key */
  9355. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9356. /* Invalid request */
  9357. return -1;
  9358. }
  9359. ri->http_version += 5;
  9360. /* Parse all HTTP headers */
  9361. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9362. if (ri->num_headers < 0) {
  9363. /* Error while parsing headers */
  9364. return -1;
  9365. }
  9366. return request_length + init_skip;
  9367. }
  9368. static int
  9369. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9370. {
  9371. int response_length;
  9372. int init_skip = 0;
  9373. char *tmp, *tmp2;
  9374. long l;
  9375. /* Initialize elements. */
  9376. ri->http_version = ri->status_text = NULL;
  9377. ri->num_headers = ri->status_code = 0;
  9378. /* RFC says that all initial whitespaces should be ingored */
  9379. /* This included all leading \r and \n (isspace) */
  9380. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9381. while ((len > 0) && isspace((unsigned char)*buf)) {
  9382. buf++;
  9383. len--;
  9384. init_skip++;
  9385. }
  9386. if (len == 0) {
  9387. /* Incomplete request */
  9388. return 0;
  9389. }
  9390. /* Control characters are not allowed, including zero */
  9391. if (iscntrl((unsigned char)*buf)) {
  9392. return -1;
  9393. }
  9394. /* Find end of HTTP header */
  9395. response_length = get_http_header_len(buf, len);
  9396. if (response_length <= 0) {
  9397. return response_length;
  9398. }
  9399. buf[response_length - 1] = '\0';
  9400. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9401. return -1;
  9402. }
  9403. /* The first word is the HTTP version */
  9404. /* Check for a valid HTTP version key */
  9405. if (strncmp(buf, "HTTP/", 5) != 0) {
  9406. /* Invalid request */
  9407. return -1;
  9408. }
  9409. buf += 5;
  9410. if (!isgraph((unsigned char)buf[0])) {
  9411. /* Invalid request */
  9412. return -1;
  9413. }
  9414. ri->http_version = buf;
  9415. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9416. return -1;
  9417. }
  9418. /* The second word is the status as a number */
  9419. tmp = buf;
  9420. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9421. return -1;
  9422. }
  9423. l = strtol(tmp, &tmp2, 10);
  9424. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9425. /* Everything else but a 3 digit code is invalid */
  9426. return -1;
  9427. }
  9428. ri->status_code = (int)l;
  9429. /* The rest of the line is the status text */
  9430. ri->status_text = buf;
  9431. /* Find end of status text */
  9432. /* isgraph or isspace = isprint */
  9433. while (isprint((unsigned char)*buf)) {
  9434. buf++;
  9435. }
  9436. if ((*buf != '\r') && (*buf != '\n')) {
  9437. return -1;
  9438. }
  9439. /* Terminate string and forward buf to next line */
  9440. do {
  9441. *buf = 0;
  9442. buf++;
  9443. } while (isspace((unsigned char)*buf));
  9444. /* Parse all HTTP headers */
  9445. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9446. if (ri->num_headers < 0) {
  9447. /* Error while parsing headers */
  9448. return -1;
  9449. }
  9450. return response_length + init_skip;
  9451. }
  9452. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9453. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9454. * buffer (which marks the end of HTTP request). Buffer buf may already
  9455. * have some data. The length of the data is stored in nread.
  9456. * Upon every read operation, increase nread by the number of bytes read. */
  9457. static int
  9458. read_message(FILE *fp,
  9459. struct mg_connection *conn,
  9460. char *buf,
  9461. int bufsiz,
  9462. int *nread)
  9463. {
  9464. int request_len, n = 0;
  9465. struct timespec last_action_time;
  9466. double request_timeout;
  9467. if (!conn) {
  9468. return 0;
  9469. }
  9470. memset(&last_action_time, 0, sizeof(last_action_time));
  9471. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9472. /* value of request_timeout is in seconds, config in milliseconds */
  9473. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9474. } else {
  9475. request_timeout = -1.0;
  9476. }
  9477. if (conn->handled_requests > 0) {
  9478. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9479. request_timeout =
  9480. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9481. }
  9482. }
  9483. request_len = get_http_header_len(buf, *nread);
  9484. while (request_len == 0) {
  9485. /* Full request not yet received */
  9486. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9487. /* Server is to be stopped. */
  9488. return -1;
  9489. }
  9490. if (*nread >= bufsiz) {
  9491. /* Request too long */
  9492. return -2;
  9493. }
  9494. n = pull_inner(
  9495. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9496. if (n == -2) {
  9497. /* Receive error */
  9498. return -1;
  9499. }
  9500. /* update clock after every read request */
  9501. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9502. if (n > 0) {
  9503. *nread += n;
  9504. request_len = get_http_header_len(buf, *nread);
  9505. }
  9506. if ((request_len == 0) && (request_timeout >= 0)) {
  9507. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9508. > request_timeout) {
  9509. /* Timeout */
  9510. return -1;
  9511. }
  9512. }
  9513. }
  9514. return request_len;
  9515. }
  9516. #if !defined(NO_CGI) || !defined(NO_FILES)
  9517. static int
  9518. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9519. {
  9520. const char *expect;
  9521. char buf[MG_BUF_LEN];
  9522. int success = 0;
  9523. if (!conn) {
  9524. return 0;
  9525. }
  9526. expect = mg_get_header(conn, "Expect");
  9527. DEBUG_ASSERT(fp != NULL);
  9528. if (!fp) {
  9529. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9530. return 0;
  9531. }
  9532. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9533. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9534. */
  9535. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9536. } else {
  9537. if (expect != NULL) {
  9538. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9539. conn->status_code = 100;
  9540. } else {
  9541. conn->status_code = 200;
  9542. }
  9543. DEBUG_ASSERT(conn->consumed_content == 0);
  9544. if (conn->consumed_content != 0) {
  9545. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9546. return 0;
  9547. }
  9548. for (;;) {
  9549. int nread = mg_read(conn, buf, sizeof(buf));
  9550. if (nread <= 0) {
  9551. success = (nread == 0);
  9552. break;
  9553. }
  9554. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9555. break;
  9556. }
  9557. }
  9558. /* Each error code path in this function must send an error */
  9559. if (!success) {
  9560. /* NOTE: Maybe some data has already been sent. */
  9561. /* TODO (low): If some data has been sent, a correct error
  9562. * reply can no longer be sent, so just close the connection */
  9563. mg_send_http_error(conn, 500, "%s", "");
  9564. }
  9565. }
  9566. return success;
  9567. }
  9568. #endif
  9569. #if defined(USE_TIMERS)
  9570. #define TIMER_API static
  9571. #include "timer.inl"
  9572. #endif /* USE_TIMERS */
  9573. #if !defined(NO_CGI)
  9574. /* This structure helps to create an environment for the spawned CGI
  9575. * program.
  9576. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9577. * last element must be NULL.
  9578. * However, on Windows there is a requirement that all these
  9579. * VARIABLE=VALUE\0
  9580. * strings must reside in a contiguous buffer. The end of the buffer is
  9581. * marked by two '\0' characters.
  9582. * We satisfy both worlds: we create an envp array (which is vars), all
  9583. * entries are actually pointers inside buf. */
  9584. struct cgi_environment {
  9585. struct mg_connection *conn;
  9586. /* Data block */
  9587. char *buf; /* Environment buffer */
  9588. size_t buflen; /* Space available in buf */
  9589. size_t bufused; /* Space taken in buf */
  9590. /* Index block */
  9591. char **var; /* char **envp */
  9592. size_t varlen; /* Number of variables available in var */
  9593. size_t varused; /* Number of variables stored in var */
  9594. };
  9595. static void addenv(struct cgi_environment *env,
  9596. PRINTF_FORMAT_STRING(const char *fmt),
  9597. ...) PRINTF_ARGS(2, 3);
  9598. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9599. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9600. static void
  9601. addenv(struct cgi_environment *env, const char *fmt, ...)
  9602. {
  9603. size_t i, n, space;
  9604. int truncated = 0;
  9605. char *added;
  9606. va_list ap;
  9607. if ((env->varlen - env->varused) < 2) {
  9608. mg_cry_internal(env->conn,
  9609. "%s: Cannot register CGI variable [%s]",
  9610. __func__,
  9611. fmt);
  9612. return;
  9613. }
  9614. /* Calculate how much space is left in the buffer */
  9615. space = (env->buflen - env->bufused);
  9616. do {
  9617. /* Space for "\0\0" is always needed. */
  9618. if (space <= 2) {
  9619. /* Allocate new buffer */
  9620. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9621. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9622. if (!added) {
  9623. /* Out of memory */
  9624. mg_cry_internal(
  9625. env->conn,
  9626. "%s: Cannot allocate memory for CGI variable [%s]",
  9627. __func__,
  9628. fmt);
  9629. return;
  9630. }
  9631. /* Retarget pointers */
  9632. env->buf = added;
  9633. env->buflen = n;
  9634. for (i = 0, n = 0; i < env->varused; i++) {
  9635. env->var[i] = added + n;
  9636. n += strlen(added + n) + 1;
  9637. }
  9638. space = (env->buflen - env->bufused);
  9639. }
  9640. /* Make a pointer to the free space int the buffer */
  9641. added = env->buf + env->bufused;
  9642. /* Copy VARIABLE=VALUE\0 string into the free space */
  9643. va_start(ap, fmt);
  9644. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9645. va_end(ap);
  9646. /* Do not add truncated strings to the environment */
  9647. if (truncated) {
  9648. /* Reallocate the buffer */
  9649. space = 0;
  9650. }
  9651. } while (truncated);
  9652. /* Calculate number of bytes added to the environment */
  9653. n = strlen(added) + 1;
  9654. env->bufused += n;
  9655. /* Append a pointer to the added string into the envp array */
  9656. env->var[env->varused] = added;
  9657. env->varused++;
  9658. }
  9659. /* Return 0 on success, non-zero if an error occurs. */
  9660. static int
  9661. prepare_cgi_environment(struct mg_connection *conn,
  9662. const char *prog,
  9663. struct cgi_environment *env)
  9664. {
  9665. const char *s;
  9666. struct vec var_vec;
  9667. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9668. int i, truncated, uri_len;
  9669. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9670. return -1;
  9671. }
  9672. env->conn = conn;
  9673. env->buflen = CGI_ENVIRONMENT_SIZE;
  9674. env->bufused = 0;
  9675. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9676. if (env->buf == NULL) {
  9677. mg_cry_internal(conn,
  9678. "%s: Not enough memory for environmental buffer",
  9679. __func__);
  9680. return -1;
  9681. }
  9682. env->varlen = MAX_CGI_ENVIR_VARS;
  9683. env->varused = 0;
  9684. env->var =
  9685. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9686. if (env->var == NULL) {
  9687. mg_cry_internal(conn,
  9688. "%s: Not enough memory for environmental variables",
  9689. __func__);
  9690. mg_free(env->buf);
  9691. return -1;
  9692. }
  9693. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9694. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9695. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9696. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9697. /* Prepare the environment block */
  9698. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9699. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9700. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9701. #if defined(USE_IPV6)
  9702. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9703. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9704. } else
  9705. #endif
  9706. {
  9707. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9708. }
  9709. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9710. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9711. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9712. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9713. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9714. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9715. /* SCRIPT_NAME */
  9716. uri_len = (int)strlen(conn->request_info.local_uri);
  9717. if (conn->path_info == NULL) {
  9718. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9719. /* URI: /path_to_script/script.cgi */
  9720. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9721. } else {
  9722. /* URI: /path_to_script/ ... using index.cgi */
  9723. const char *index_file = strrchr(prog, '/');
  9724. if (index_file) {
  9725. addenv(env,
  9726. "SCRIPT_NAME=%s%s",
  9727. conn->request_info.local_uri,
  9728. index_file + 1);
  9729. }
  9730. }
  9731. } else {
  9732. /* URI: /path_to_script/script.cgi/path_info */
  9733. addenv(env,
  9734. "SCRIPT_NAME=%.*s",
  9735. uri_len - (int)strlen(conn->path_info),
  9736. conn->request_info.local_uri);
  9737. }
  9738. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9739. if (conn->path_info == NULL) {
  9740. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9741. } else {
  9742. addenv(env,
  9743. "PATH_TRANSLATED=%s%s",
  9744. conn->dom_ctx->config[DOCUMENT_ROOT],
  9745. conn->path_info);
  9746. }
  9747. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9748. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9749. addenv(env, "CONTENT_TYPE=%s", s);
  9750. }
  9751. if (conn->request_info.query_string != NULL) {
  9752. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9753. }
  9754. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9755. addenv(env, "CONTENT_LENGTH=%s", s);
  9756. }
  9757. if ((s = getenv("PATH")) != NULL) {
  9758. addenv(env, "PATH=%s", s);
  9759. }
  9760. if (conn->path_info != NULL) {
  9761. addenv(env, "PATH_INFO=%s", conn->path_info);
  9762. }
  9763. if (conn->status_code > 0) {
  9764. /* CGI error handler should show the status code */
  9765. addenv(env, "STATUS=%d", conn->status_code);
  9766. }
  9767. #if defined(_WIN32)
  9768. if ((s = getenv("COMSPEC")) != NULL) {
  9769. addenv(env, "COMSPEC=%s", s);
  9770. }
  9771. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9772. addenv(env, "SYSTEMROOT=%s", s);
  9773. }
  9774. if ((s = getenv("SystemDrive")) != NULL) {
  9775. addenv(env, "SystemDrive=%s", s);
  9776. }
  9777. if ((s = getenv("ProgramFiles")) != NULL) {
  9778. addenv(env, "ProgramFiles=%s", s);
  9779. }
  9780. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9781. addenv(env, "ProgramFiles(x86)=%s", s);
  9782. }
  9783. #else
  9784. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9785. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9786. }
  9787. #endif /* _WIN32 */
  9788. if ((s = getenv("PERLLIB")) != NULL) {
  9789. addenv(env, "PERLLIB=%s", s);
  9790. }
  9791. if (conn->request_info.remote_user != NULL) {
  9792. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9793. addenv(env, "%s", "AUTH_TYPE=Digest");
  9794. }
  9795. /* Add all headers as HTTP_* variables */
  9796. for (i = 0; i < conn->request_info.num_headers; i++) {
  9797. (void)mg_snprintf(conn,
  9798. &truncated,
  9799. http_var_name,
  9800. sizeof(http_var_name),
  9801. "HTTP_%s",
  9802. conn->request_info.http_headers[i].name);
  9803. if (truncated) {
  9804. mg_cry_internal(conn,
  9805. "%s: HTTP header variable too long [%s]",
  9806. __func__,
  9807. conn->request_info.http_headers[i].name);
  9808. continue;
  9809. }
  9810. /* Convert variable name into uppercase, and change - to _ */
  9811. for (p = http_var_name; *p != '\0'; p++) {
  9812. if (*p == '-') {
  9813. *p = '_';
  9814. }
  9815. *p = (char)toupper((unsigned char)*p);
  9816. }
  9817. addenv(env,
  9818. "%s=%s",
  9819. http_var_name,
  9820. conn->request_info.http_headers[i].value);
  9821. }
  9822. /* Add user-specified variables */
  9823. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9824. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9825. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9826. }
  9827. env->var[env->varused] = NULL;
  9828. env->buf[env->bufused] = '\0';
  9829. return 0;
  9830. }
  9831. /* Data for CGI process control: PID and number of references */
  9832. struct process_control_data {
  9833. pid_t pid;
  9834. int references;
  9835. };
  9836. static int
  9837. abort_process(void *data)
  9838. {
  9839. /* Waitpid checks for child status and won't work for a pid that does
  9840. * not identify a child of the current process. Thus, if the pid is
  9841. * reused, we will not affect a different process. */
  9842. struct process_control_data *proc = (struct process_control_data *)data;
  9843. int status = 0;
  9844. int refs;
  9845. pid_t ret_pid;
  9846. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9847. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9848. /* Stop child process */
  9849. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9850. kill(proc->pid, SIGABRT);
  9851. /* Wait until process is terminated (don't leave zombies) */
  9852. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9853. ;
  9854. } else {
  9855. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9856. }
  9857. /* Dec reference counter */
  9858. refs = mg_atomic_dec(&proc->references);
  9859. if (refs == 0) {
  9860. /* no more references - free data */
  9861. mg_free(data);
  9862. }
  9863. return 0;
  9864. }
  9865. /* Local (static) function assumes all arguments are valid. */
  9866. static void
  9867. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9868. {
  9869. char *buf;
  9870. size_t buflen;
  9871. int headers_len, data_len, i, truncated;
  9872. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9873. const char *status, *status_text, *connection_state;
  9874. char *pbuf, dir[PATH_MAX], *p;
  9875. struct mg_request_info ri;
  9876. struct cgi_environment blk;
  9877. FILE *in = NULL, *out = NULL, *err = NULL;
  9878. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9879. pid_t pid = (pid_t)-1;
  9880. struct process_control_data *proc = NULL;
  9881. #if defined(USE_TIMERS)
  9882. double cgi_timeout = -1.0;
  9883. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9884. /* Get timeout in seconds */
  9885. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9886. }
  9887. #endif
  9888. buf = NULL;
  9889. buflen = conn->phys_ctx->max_request_size;
  9890. i = prepare_cgi_environment(conn, prog, &blk);
  9891. if (i != 0) {
  9892. blk.buf = NULL;
  9893. blk.var = NULL;
  9894. goto done;
  9895. }
  9896. /* CGI must be executed in its own directory. 'dir' must point to the
  9897. * directory containing executable program, 'p' must point to the
  9898. * executable program name relative to 'dir'. */
  9899. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9900. if (truncated) {
  9901. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9902. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9903. goto done;
  9904. }
  9905. if ((p = strrchr(dir, '/')) != NULL) {
  9906. *p++ = '\0';
  9907. } else {
  9908. dir[0] = '.';
  9909. dir[1] = '\0';
  9910. p = (char *)prog;
  9911. }
  9912. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9913. status = strerror(ERRNO);
  9914. mg_cry_internal(
  9915. conn,
  9916. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9917. prog,
  9918. status);
  9919. mg_send_http_error(conn,
  9920. 500,
  9921. "Error: Cannot create CGI pipe: %s",
  9922. status);
  9923. goto done;
  9924. }
  9925. proc = (struct process_control_data *)
  9926. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9927. if (proc == NULL) {
  9928. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9929. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9930. goto done;
  9931. }
  9932. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9933. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9934. if (pid == (pid_t)-1) {
  9935. status = strerror(ERRNO);
  9936. mg_cry_internal(
  9937. conn,
  9938. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9939. prog,
  9940. status);
  9941. mg_send_http_error(conn,
  9942. 500,
  9943. "Error: Cannot spawn CGI process [%s]: %s",
  9944. prog,
  9945. status);
  9946. mg_free(proc);
  9947. proc = NULL;
  9948. goto done;
  9949. }
  9950. /* Store data in shared process_control_data */
  9951. proc->pid = pid;
  9952. proc->references = 1;
  9953. #if defined(USE_TIMERS)
  9954. if (cgi_timeout > 0.0) {
  9955. proc->references = 2;
  9956. // Start a timer for CGI
  9957. timer_add(conn->phys_ctx,
  9958. cgi_timeout /* in seconds */,
  9959. 0.0,
  9960. 1,
  9961. abort_process,
  9962. (void *)proc);
  9963. }
  9964. #endif
  9965. /* Parent closes only one side of the pipes.
  9966. * If we don't mark them as closed, close() attempt before
  9967. * return from this function throws an exception on Windows.
  9968. * Windows does not like when closed descriptor is closed again. */
  9969. (void)close(fdin[0]);
  9970. (void)close(fdout[1]);
  9971. (void)close(fderr[1]);
  9972. fdin[0] = fdout[1] = fderr[1] = -1;
  9973. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9974. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9975. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9976. status = strerror(ERRNO);
  9977. mg_cry_internal(conn,
  9978. "Error: CGI program \"%s\": Can not open fd: %s",
  9979. prog,
  9980. status);
  9981. mg_send_http_error(conn,
  9982. 500,
  9983. "Error: CGI can not open fd\nfdopen: %s",
  9984. status);
  9985. goto done;
  9986. }
  9987. setbuf(in, NULL);
  9988. setbuf(out, NULL);
  9989. setbuf(err, NULL);
  9990. fout.access.fp = out;
  9991. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9992. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9993. conn->content_len);
  9994. /* This is a POST/PUT request, or another request with body data. */
  9995. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9996. /* Error sending the body data */
  9997. mg_cry_internal(
  9998. conn,
  9999. "Error: CGI program \"%s\": Forward body data failed",
  10000. prog);
  10001. goto done;
  10002. }
  10003. }
  10004. /* Close so child gets an EOF. */
  10005. fclose(in);
  10006. in = NULL;
  10007. fdin[1] = -1;
  10008. /* Now read CGI reply into a buffer. We need to set correct
  10009. * status code, thus we need to see all HTTP headers first.
  10010. * Do not send anything back to client, until we buffer in all
  10011. * HTTP headers. */
  10012. data_len = 0;
  10013. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10014. if (buf == NULL) {
  10015. mg_send_http_error(conn,
  10016. 500,
  10017. "Error: Not enough memory for CGI buffer (%u bytes)",
  10018. (unsigned int)buflen);
  10019. mg_cry_internal(
  10020. conn,
  10021. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10022. "bytes)",
  10023. prog,
  10024. (unsigned int)buflen);
  10025. goto done;
  10026. }
  10027. DEBUG_TRACE("CGI: %s", "wait for response");
  10028. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10029. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10030. if (headers_len <= 0) {
  10031. /* Could not parse the CGI response. Check if some error message on
  10032. * stderr. */
  10033. i = pull_all(err, conn, buf, (int)buflen);
  10034. if (i > 0) {
  10035. /* CGI program explicitly sent an error */
  10036. /* Write the error message to the internal log */
  10037. mg_cry_internal(conn,
  10038. "Error: CGI program \"%s\" sent error "
  10039. "message: [%.*s]",
  10040. prog,
  10041. i,
  10042. buf);
  10043. /* Don't send the error message back to the client */
  10044. mg_send_http_error(conn,
  10045. 500,
  10046. "Error: CGI program \"%s\" failed.",
  10047. prog);
  10048. } else {
  10049. /* CGI program did not explicitly send an error, but a broken
  10050. * respon header */
  10051. mg_cry_internal(conn,
  10052. "Error: CGI program sent malformed or too big "
  10053. "(>%u bytes) HTTP headers: [%.*s]",
  10054. (unsigned)buflen,
  10055. data_len,
  10056. buf);
  10057. mg_send_http_error(conn,
  10058. 500,
  10059. "Error: CGI program sent malformed or too big "
  10060. "(>%u bytes) HTTP headers: [%.*s]",
  10061. (unsigned)buflen,
  10062. data_len,
  10063. buf);
  10064. }
  10065. /* in both cases, abort processing CGI */
  10066. goto done;
  10067. }
  10068. pbuf = buf;
  10069. buf[headers_len - 1] = '\0';
  10070. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10071. /* Make up and send the status line */
  10072. status_text = "OK";
  10073. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10074. != NULL) {
  10075. conn->status_code = atoi(status);
  10076. status_text = status;
  10077. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10078. status_text++;
  10079. }
  10080. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10081. != NULL) {
  10082. conn->status_code = 307;
  10083. } else {
  10084. conn->status_code = 200;
  10085. }
  10086. connection_state =
  10087. get_header(ri.http_headers, ri.num_headers, "Connection");
  10088. if (!header_has_option(connection_state, "keep-alive")) {
  10089. conn->must_close = 1;
  10090. }
  10091. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10092. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10093. /* Send headers */
  10094. for (i = 0; i < ri.num_headers; i++) {
  10095. DEBUG_TRACE("CGI header: %s: %s",
  10096. ri.http_headers[i].name,
  10097. ri.http_headers[i].value);
  10098. mg_printf(conn,
  10099. "%s: %s\r\n",
  10100. ri.http_headers[i].name,
  10101. ri.http_headers[i].value);
  10102. }
  10103. mg_write(conn, "\r\n", 2);
  10104. /* Send chunk of data that may have been read after the headers */
  10105. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10106. /* Read the rest of CGI output and send to the client */
  10107. DEBUG_TRACE("CGI: %s", "forward all data");
  10108. send_file_data(conn, &fout, 0, INT64_MAX);
  10109. DEBUG_TRACE("CGI: %s", "all data sent");
  10110. done:
  10111. mg_free(blk.var);
  10112. mg_free(blk.buf);
  10113. if (pid != (pid_t)-1) {
  10114. abort_process((void *)proc);
  10115. }
  10116. if (fdin[0] != -1) {
  10117. close(fdin[0]);
  10118. }
  10119. if (fdout[1] != -1) {
  10120. close(fdout[1]);
  10121. }
  10122. if (fderr[1] != -1) {
  10123. close(fderr[1]);
  10124. }
  10125. if (in != NULL) {
  10126. fclose(in);
  10127. } else if (fdin[1] != -1) {
  10128. close(fdin[1]);
  10129. }
  10130. if (out != NULL) {
  10131. fclose(out);
  10132. } else if (fdout[0] != -1) {
  10133. close(fdout[0]);
  10134. }
  10135. if (err != NULL) {
  10136. fclose(err);
  10137. } else if (fderr[0] != -1) {
  10138. close(fderr[0]);
  10139. }
  10140. mg_free(buf);
  10141. }
  10142. #endif /* !NO_CGI */
  10143. #if !defined(NO_FILES)
  10144. static void
  10145. mkcol(struct mg_connection *conn, const char *path)
  10146. {
  10147. int rc, body_len;
  10148. struct de de;
  10149. char date[64];
  10150. time_t curtime = time(NULL);
  10151. if (conn == NULL) {
  10152. return;
  10153. }
  10154. /* TODO (mid): Check the mg_send_http_error situations in this function
  10155. */
  10156. memset(&de.file, 0, sizeof(de.file));
  10157. if (!mg_stat(conn, path, &de.file)) {
  10158. mg_cry_internal(conn,
  10159. "%s: mg_stat(%s) failed: %s",
  10160. __func__,
  10161. path,
  10162. strerror(ERRNO));
  10163. }
  10164. if (de.file.last_modified) {
  10165. /* TODO (mid): This check does not seem to make any sense ! */
  10166. /* TODO (mid): Add a webdav unit test first, before changing
  10167. * anything here. */
  10168. mg_send_http_error(
  10169. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10170. return;
  10171. }
  10172. body_len = conn->data_len - conn->request_len;
  10173. if (body_len > 0) {
  10174. mg_send_http_error(
  10175. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10176. return;
  10177. }
  10178. rc = mg_mkdir(conn, path, 0755);
  10179. if (rc == 0) {
  10180. conn->status_code = 201;
  10181. gmt_time_string(date, sizeof(date), &curtime);
  10182. mg_printf(conn,
  10183. "HTTP/1.1 %d Created\r\n"
  10184. "Date: %s\r\n",
  10185. conn->status_code,
  10186. date);
  10187. send_static_cache_header(conn);
  10188. send_additional_header(conn);
  10189. mg_printf(conn,
  10190. "Content-Length: 0\r\n"
  10191. "Connection: %s\r\n\r\n",
  10192. suggest_connection_header(conn));
  10193. } else {
  10194. if (errno == EEXIST) {
  10195. mg_send_http_error(
  10196. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10197. } else if (errno == EACCES) {
  10198. mg_send_http_error(
  10199. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10200. } else if (errno == ENOENT) {
  10201. mg_send_http_error(
  10202. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10203. } else {
  10204. mg_send_http_error(
  10205. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10206. }
  10207. }
  10208. }
  10209. static void
  10210. put_file(struct mg_connection *conn, const char *path)
  10211. {
  10212. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10213. const char *range;
  10214. int64_t r1, r2;
  10215. int rc;
  10216. char date[64];
  10217. time_t curtime = time(NULL);
  10218. if (conn == NULL) {
  10219. return;
  10220. }
  10221. if (mg_stat(conn, path, &file.stat)) {
  10222. /* File already exists */
  10223. conn->status_code = 200;
  10224. if (file.stat.is_directory) {
  10225. /* This is an already existing directory,
  10226. * so there is nothing to do for the server. */
  10227. rc = 0;
  10228. } else {
  10229. /* File exists and is not a directory. */
  10230. /* Can it be replaced? */
  10231. #if defined(MG_USE_OPEN_FILE)
  10232. if (file.access.membuf != NULL) {
  10233. /* This is an "in-memory" file, that can not be replaced */
  10234. mg_send_http_error(conn,
  10235. 405,
  10236. "Error: Put not possible\nReplacing %s "
  10237. "is not supported",
  10238. path);
  10239. return;
  10240. }
  10241. #endif
  10242. /* Check if the server may write this file */
  10243. if (access(path, W_OK) == 0) {
  10244. /* Access granted */
  10245. rc = 1;
  10246. } else {
  10247. mg_send_http_error(
  10248. conn,
  10249. 403,
  10250. "Error: Put not possible\nReplacing %s is not allowed",
  10251. path);
  10252. return;
  10253. }
  10254. }
  10255. } else {
  10256. /* File should be created */
  10257. conn->status_code = 201;
  10258. rc = put_dir(conn, path);
  10259. }
  10260. if (rc == 0) {
  10261. /* put_dir returns 0 if path is a directory */
  10262. gmt_time_string(date, sizeof(date), &curtime);
  10263. mg_printf(conn,
  10264. "HTTP/1.1 %d %s\r\n",
  10265. conn->status_code,
  10266. mg_get_response_code_text(NULL, conn->status_code));
  10267. send_no_cache_header(conn);
  10268. send_additional_header(conn);
  10269. mg_printf(conn,
  10270. "Date: %s\r\n"
  10271. "Content-Length: 0\r\n"
  10272. "Connection: %s\r\n\r\n",
  10273. date,
  10274. suggest_connection_header(conn));
  10275. /* Request to create a directory has been fulfilled successfully.
  10276. * No need to put a file. */
  10277. return;
  10278. }
  10279. if (rc == -1) {
  10280. /* put_dir returns -1 if the path is too long */
  10281. mg_send_http_error(conn,
  10282. 414,
  10283. "Error: Path too long\nput_dir(%s): %s",
  10284. path,
  10285. strerror(ERRNO));
  10286. return;
  10287. }
  10288. if (rc == -2) {
  10289. /* put_dir returns -2 if the directory can not be created */
  10290. mg_send_http_error(conn,
  10291. 500,
  10292. "Error: Can not create directory\nput_dir(%s): %s",
  10293. path,
  10294. strerror(ERRNO));
  10295. return;
  10296. }
  10297. /* A file should be created or overwritten. */
  10298. /* Currently CivetWeb does not nead read+write access. */
  10299. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10300. || file.access.fp == NULL) {
  10301. (void)mg_fclose(&file.access);
  10302. mg_send_http_error(conn,
  10303. 500,
  10304. "Error: Can not create file\nfopen(%s): %s",
  10305. path,
  10306. strerror(ERRNO));
  10307. return;
  10308. }
  10309. fclose_on_exec(&file.access, conn);
  10310. range = mg_get_header(conn, "Content-Range");
  10311. r1 = r2 = 0;
  10312. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10313. conn->status_code = 206; /* Partial content */
  10314. fseeko(file.access.fp, r1, SEEK_SET);
  10315. }
  10316. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10317. /* forward_body_data failed.
  10318. * The error code has already been sent to the client,
  10319. * and conn->status_code is already set. */
  10320. (void)mg_fclose(&file.access);
  10321. return;
  10322. }
  10323. if (mg_fclose(&file.access) != 0) {
  10324. /* fclose failed. This might have different reasons, but a likely
  10325. * one is "no space on disk", http 507. */
  10326. conn->status_code = 507;
  10327. }
  10328. gmt_time_string(date, sizeof(date), &curtime);
  10329. mg_printf(conn,
  10330. "HTTP/1.1 %d %s\r\n",
  10331. conn->status_code,
  10332. mg_get_response_code_text(NULL, conn->status_code));
  10333. send_no_cache_header(conn);
  10334. send_additional_header(conn);
  10335. mg_printf(conn,
  10336. "Date: %s\r\n"
  10337. "Content-Length: 0\r\n"
  10338. "Connection: %s\r\n\r\n",
  10339. date,
  10340. suggest_connection_header(conn));
  10341. }
  10342. static void
  10343. delete_file(struct mg_connection *conn, const char *path)
  10344. {
  10345. struct de de;
  10346. memset(&de.file, 0, sizeof(de.file));
  10347. if (!mg_stat(conn, path, &de.file)) {
  10348. /* mg_stat returns 0 if the file does not exist */
  10349. mg_send_http_error(conn,
  10350. 404,
  10351. "Error: Cannot delete file\nFile %s not found",
  10352. path);
  10353. return;
  10354. }
  10355. #if 0 /* Ignore if a file in memory is inside a folder */
  10356. if (de.access.membuf != NULL) {
  10357. /* the file is cached in memory */
  10358. mg_send_http_error(
  10359. conn,
  10360. 405,
  10361. "Error: Delete not possible\nDeleting %s is not supported",
  10362. path);
  10363. return;
  10364. }
  10365. #endif
  10366. if (de.file.is_directory) {
  10367. if (remove_directory(conn, path)) {
  10368. /* Delete is successful: Return 204 without content. */
  10369. mg_send_http_error(conn, 204, "%s", "");
  10370. } else {
  10371. /* Delete is not successful: Return 500 (Server error). */
  10372. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10373. }
  10374. return;
  10375. }
  10376. /* This is an existing file (not a directory).
  10377. * Check if write permission is granted. */
  10378. if (access(path, W_OK) != 0) {
  10379. /* File is read only */
  10380. mg_send_http_error(
  10381. conn,
  10382. 403,
  10383. "Error: Delete not possible\nDeleting %s is not allowed",
  10384. path);
  10385. return;
  10386. }
  10387. /* Try to delete it. */
  10388. if (mg_remove(conn, path) == 0) {
  10389. /* Delete was successful: Return 204 without content. */
  10390. mg_send_http_error(conn, 204, "%s", "");
  10391. } else {
  10392. /* Delete not successful (file locked). */
  10393. mg_send_http_error(conn,
  10394. 423,
  10395. "Error: Cannot delete file\nremove(%s): %s",
  10396. path,
  10397. strerror(ERRNO));
  10398. }
  10399. }
  10400. #endif /* !NO_FILES */
  10401. #if !defined(NO_FILESYSTEMS)
  10402. static void
  10403. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10404. static void
  10405. do_ssi_include(struct mg_connection *conn,
  10406. const char *ssi,
  10407. char *tag,
  10408. int include_level)
  10409. {
  10410. char file_name[MG_BUF_LEN], path[512], *p;
  10411. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10412. size_t len;
  10413. int truncated = 0;
  10414. if (conn == NULL) {
  10415. return;
  10416. }
  10417. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10418. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10419. * always < MG_BUF_LEN. */
  10420. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10421. /* File name is relative to the webserver root */
  10422. file_name[511] = 0;
  10423. (void)mg_snprintf(conn,
  10424. &truncated,
  10425. path,
  10426. sizeof(path),
  10427. "%s/%s",
  10428. conn->dom_ctx->config[DOCUMENT_ROOT],
  10429. file_name);
  10430. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10431. /* File name is relative to the webserver working directory
  10432. * or it is absolute system path */
  10433. file_name[511] = 0;
  10434. (void)
  10435. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10436. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10437. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10438. /* File name is relative to the currect document */
  10439. file_name[511] = 0;
  10440. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10441. if (!truncated) {
  10442. if ((p = strrchr(path, '/')) != NULL) {
  10443. p[1] = '\0';
  10444. }
  10445. len = strlen(path);
  10446. (void)mg_snprintf(conn,
  10447. &truncated,
  10448. path + len,
  10449. sizeof(path) - len,
  10450. "%s",
  10451. file_name);
  10452. }
  10453. } else {
  10454. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10455. return;
  10456. }
  10457. if (truncated) {
  10458. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10459. return;
  10460. }
  10461. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10462. mg_cry_internal(conn,
  10463. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10464. tag,
  10465. path,
  10466. strerror(ERRNO));
  10467. } else {
  10468. fclose_on_exec(&file.access, conn);
  10469. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10470. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10471. path)
  10472. > 0) {
  10473. send_ssi_file(conn, path, &file, include_level + 1);
  10474. } else {
  10475. send_file_data(conn, &file, 0, INT64_MAX);
  10476. }
  10477. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10478. }
  10479. }
  10480. #if !defined(NO_POPEN)
  10481. static void
  10482. do_ssi_exec(struct mg_connection *conn, char *tag)
  10483. {
  10484. char cmd[1024] = "";
  10485. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10486. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10487. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10488. } else {
  10489. cmd[1023] = 0;
  10490. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10491. mg_cry_internal(conn,
  10492. "Cannot SSI #exec: [%s]: %s",
  10493. cmd,
  10494. strerror(ERRNO));
  10495. } else {
  10496. send_file_data(conn, &file, 0, INT64_MAX);
  10497. pclose(file.access.fp);
  10498. }
  10499. }
  10500. }
  10501. #endif /* !NO_POPEN */
  10502. static int
  10503. mg_fgetc(struct mg_file *filep, int offset)
  10504. {
  10505. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10506. if (filep == NULL) {
  10507. return EOF;
  10508. }
  10509. #if defined(MG_USE_OPEN_FILE)
  10510. if ((filep->access.membuf != NULL) && (offset >= 0)
  10511. && (((unsigned int)(offset)) < filep->stat.size)) {
  10512. return ((const unsigned char *)filep->access.membuf)[offset];
  10513. } else /* else block below */
  10514. #endif
  10515. if (filep->access.fp != NULL) {
  10516. return fgetc(filep->access.fp);
  10517. } else {
  10518. return EOF;
  10519. }
  10520. }
  10521. static void
  10522. send_ssi_file(struct mg_connection *conn,
  10523. const char *path,
  10524. struct mg_file *filep,
  10525. int include_level)
  10526. {
  10527. char buf[MG_BUF_LEN];
  10528. int ch, offset, len, in_tag, in_ssi_tag;
  10529. if (include_level > 10) {
  10530. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10531. return;
  10532. }
  10533. in_tag = in_ssi_tag = len = offset = 0;
  10534. /* Read file, byte by byte, and look for SSI include tags */
  10535. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10536. if (in_tag) {
  10537. /* We are in a tag, either SSI tag or html tag */
  10538. if (ch == '>') {
  10539. /* Tag is closing */
  10540. buf[len++] = '>';
  10541. if (in_ssi_tag) {
  10542. /* Handle SSI tag */
  10543. buf[len] = 0;
  10544. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10545. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10546. #if !defined(NO_POPEN)
  10547. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10548. do_ssi_exec(conn, buf + 9);
  10549. #endif /* !NO_POPEN */
  10550. } else {
  10551. mg_cry_internal(conn,
  10552. "%s: unknown SSI "
  10553. "command: \"%s\"",
  10554. path,
  10555. buf);
  10556. }
  10557. len = 0;
  10558. in_ssi_tag = in_tag = 0;
  10559. } else {
  10560. /* Not an SSI tag */
  10561. /* Flush buffer */
  10562. (void)mg_write(conn, buf, (size_t)len);
  10563. len = 0;
  10564. in_tag = 0;
  10565. }
  10566. } else {
  10567. /* Tag is still open */
  10568. buf[len++] = (char)(ch & 0xff);
  10569. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10570. /* All SSI tags start with <!--# */
  10571. in_ssi_tag = 1;
  10572. }
  10573. if ((len + 2) > (int)sizeof(buf)) {
  10574. /* Tag to long for buffer */
  10575. mg_cry_internal(conn, "%s: tag is too large", path);
  10576. return;
  10577. }
  10578. }
  10579. } else {
  10580. /* We are not in a tag yet. */
  10581. if (ch == '<') {
  10582. /* Tag is opening */
  10583. in_tag = 1;
  10584. if (len > 0) {
  10585. /* Flush current buffer.
  10586. * Buffer is filled with "len" bytes. */
  10587. (void)mg_write(conn, buf, (size_t)len);
  10588. }
  10589. /* Store the < */
  10590. len = 1;
  10591. buf[0] = '<';
  10592. } else {
  10593. /* No Tag */
  10594. /* Add data to buffer */
  10595. buf[len++] = (char)(ch & 0xff);
  10596. /* Flush if buffer is full */
  10597. if (len == (int)sizeof(buf)) {
  10598. mg_write(conn, buf, (size_t)len);
  10599. len = 0;
  10600. }
  10601. }
  10602. }
  10603. }
  10604. /* Send the rest of buffered data */
  10605. if (len > 0) {
  10606. mg_write(conn, buf, (size_t)len);
  10607. }
  10608. }
  10609. static void
  10610. handle_ssi_file_request(struct mg_connection *conn,
  10611. const char *path,
  10612. struct mg_file *filep)
  10613. {
  10614. char date[64];
  10615. time_t curtime = time(NULL);
  10616. const char *cors_orig_cfg;
  10617. const char *cors1, *cors2, *cors3;
  10618. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10619. return;
  10620. }
  10621. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10622. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10623. /* Cross-origin resource sharing (CORS). */
  10624. cors1 = "Access-Control-Allow-Origin: ";
  10625. cors2 = cors_orig_cfg;
  10626. cors3 = "\r\n";
  10627. } else {
  10628. cors1 = cors2 = cors3 = "";
  10629. }
  10630. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10631. /* File exists (precondition for calling this function),
  10632. * but can not be opened by the server. */
  10633. mg_send_http_error(conn,
  10634. 500,
  10635. "Error: Cannot read file\nfopen(%s): %s",
  10636. path,
  10637. strerror(ERRNO));
  10638. } else {
  10639. conn->must_close = 1;
  10640. gmt_time_string(date, sizeof(date), &curtime);
  10641. fclose_on_exec(&filep->access, conn);
  10642. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10643. send_no_cache_header(conn);
  10644. send_additional_header(conn);
  10645. mg_printf(conn,
  10646. "%s%s%s"
  10647. "Date: %s\r\n"
  10648. "Content-Type: text/html\r\n"
  10649. "Connection: %s\r\n\r\n",
  10650. cors1,
  10651. cors2,
  10652. cors3,
  10653. date,
  10654. suggest_connection_header(conn));
  10655. send_ssi_file(conn, path, filep, 0);
  10656. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10657. }
  10658. }
  10659. #endif /* NO_FILESYSTEMS */
  10660. #if !defined(NO_FILES)
  10661. static void
  10662. send_options(struct mg_connection *conn)
  10663. {
  10664. char date[64];
  10665. time_t curtime = time(NULL);
  10666. if (!conn) {
  10667. return;
  10668. }
  10669. conn->status_code = 200;
  10670. conn->must_close = 1;
  10671. gmt_time_string(date, sizeof(date), &curtime);
  10672. /* We do not set a "Cache-Control" header here, but leave the default.
  10673. * Since browsers do not send an OPTIONS request, we can not test the
  10674. * effect anyway. */
  10675. mg_printf(conn,
  10676. "HTTP/1.1 200 OK\r\n"
  10677. "Date: %s\r\n"
  10678. "Connection: %s\r\n"
  10679. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10680. "PROPFIND, MKCOL\r\n"
  10681. "DAV: 1\r\n",
  10682. date,
  10683. suggest_connection_header(conn));
  10684. send_additional_header(conn);
  10685. mg_printf(conn, "\r\n");
  10686. }
  10687. /* Writes PROPFIND properties for a collection element */
  10688. static int
  10689. print_props(struct mg_connection *conn,
  10690. const char *uri,
  10691. const char *name,
  10692. struct mg_file_stat *filep)
  10693. {
  10694. size_t href_size, i, j;
  10695. int len;
  10696. char *href, mtime[64];
  10697. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10698. return 0;
  10699. }
  10700. /* Estimate worst case size for encoding */
  10701. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10702. href = (char *)mg_malloc(href_size);
  10703. if (href == NULL) {
  10704. return 0;
  10705. }
  10706. len = mg_url_encode(uri, href, href_size);
  10707. if (len >= 0) {
  10708. /* Append an extra string */
  10709. mg_url_encode(name, href + len, href_size - (size_t)len);
  10710. }
  10711. /* Directory separator should be preserved. */
  10712. for (i = j = 0; href[i]; j++) {
  10713. if (!strncmp(href + i, "%2f", 3)) {
  10714. href[j] = '/';
  10715. i += 3;
  10716. } else {
  10717. href[j] = href[i++];
  10718. }
  10719. }
  10720. href[j] = '\0';
  10721. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10722. mg_printf(conn,
  10723. "<d:response>"
  10724. "<d:href>%s</d:href>"
  10725. "<d:propstat>"
  10726. "<d:prop>"
  10727. "<d:resourcetype>%s</d:resourcetype>"
  10728. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10729. "<d:getlastmodified>%s</d:getlastmodified>"
  10730. "</d:prop>"
  10731. "<d:status>HTTP/1.1 200 OK</d:status>"
  10732. "</d:propstat>"
  10733. "</d:response>\n",
  10734. href,
  10735. filep->is_directory ? "<d:collection/>" : "",
  10736. filep->size,
  10737. mtime);
  10738. mg_free(href);
  10739. return 1;
  10740. }
  10741. static int
  10742. print_dav_dir_entry(struct de *de, void *data)
  10743. {
  10744. struct mg_connection *conn = (struct mg_connection *)data;
  10745. if (!de || !conn
  10746. || !print_props(
  10747. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10748. return -1;
  10749. }
  10750. return 0;
  10751. }
  10752. static void
  10753. handle_propfind(struct mg_connection *conn,
  10754. const char *path,
  10755. struct mg_file_stat *filep)
  10756. {
  10757. const char *depth = mg_get_header(conn, "Depth");
  10758. char date[64];
  10759. time_t curtime = time(NULL);
  10760. gmt_time_string(date, sizeof(date), &curtime);
  10761. if (!conn || !path || !filep || !conn->dom_ctx) {
  10762. return;
  10763. }
  10764. conn->must_close = 1;
  10765. conn->status_code = 207;
  10766. mg_printf(conn,
  10767. "HTTP/1.1 207 Multi-Status\r\n"
  10768. "Date: %s\r\n",
  10769. date);
  10770. send_static_cache_header(conn);
  10771. send_additional_header(conn);
  10772. mg_printf(conn,
  10773. "Connection: %s\r\n"
  10774. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10775. suggest_connection_header(conn));
  10776. mg_printf(conn,
  10777. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10778. "<d:multistatus xmlns:d='DAV:'>\n");
  10779. /* Print properties for the requested resource itself */
  10780. print_props(conn, conn->request_info.local_uri, "", filep);
  10781. /* If it is a directory, print directory entries too if Depth is not 0
  10782. */
  10783. if (filep->is_directory
  10784. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10785. "yes")
  10786. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10787. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10788. }
  10789. mg_printf(conn, "%s\n", "</d:multistatus>");
  10790. }
  10791. #endif
  10792. void
  10793. mg_lock_connection(struct mg_connection *conn)
  10794. {
  10795. if (conn) {
  10796. (void)pthread_mutex_lock(&conn->mutex);
  10797. }
  10798. }
  10799. void
  10800. mg_unlock_connection(struct mg_connection *conn)
  10801. {
  10802. if (conn) {
  10803. (void)pthread_mutex_unlock(&conn->mutex);
  10804. }
  10805. }
  10806. void
  10807. mg_lock_context(struct mg_context *ctx)
  10808. {
  10809. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10810. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10811. }
  10812. }
  10813. void
  10814. mg_unlock_context(struct mg_context *ctx)
  10815. {
  10816. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10817. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10818. }
  10819. }
  10820. #if defined(USE_LUA)
  10821. #include "mod_lua.inl"
  10822. #endif /* USE_LUA */
  10823. #if defined(USE_DUKTAPE)
  10824. #include "mod_duktape.inl"
  10825. #endif /* USE_DUKTAPE */
  10826. #if defined(USE_WEBSOCKET)
  10827. #if !defined(NO_SSL_DL)
  10828. #define SHA_API static
  10829. #include "sha1.inl"
  10830. #endif
  10831. static int
  10832. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10833. {
  10834. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10835. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10836. SHA_CTX sha_ctx;
  10837. int truncated;
  10838. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10839. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10840. if (truncated) {
  10841. conn->must_close = 1;
  10842. return 0;
  10843. }
  10844. DEBUG_TRACE("%s", "Send websocket handshake");
  10845. SHA1_Init(&sha_ctx);
  10846. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10847. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10848. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10849. mg_printf(conn,
  10850. "HTTP/1.1 101 Switching Protocols\r\n"
  10851. "Upgrade: websocket\r\n"
  10852. "Connection: Upgrade\r\n"
  10853. "Sec-WebSocket-Accept: %s\r\n",
  10854. b64_sha);
  10855. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10856. mg_printf(conn,
  10857. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10858. conn->request_info.acceptedWebSocketSubprotocol);
  10859. } else {
  10860. mg_printf(conn, "%s", "\r\n");
  10861. }
  10862. return 1;
  10863. }
  10864. #if !defined(MG_MAX_UNANSWERED_PING)
  10865. /* Configuration of the maximum number of websocket PINGs that might
  10866. * stay unanswered before the connection is considered broken.
  10867. * Note: The name of this define may still change (until it is
  10868. * defined as a compile parameter in a documentation).
  10869. */
  10870. #define MG_MAX_UNANSWERED_PING (5)
  10871. #endif
  10872. static void
  10873. read_websocket(struct mg_connection *conn,
  10874. mg_websocket_data_handler ws_data_handler,
  10875. void *callback_data)
  10876. {
  10877. /* Pointer to the beginning of the portion of the incoming websocket
  10878. * message queue.
  10879. * The original websocket upgrade request is never removed, so the queue
  10880. * begins after it. */
  10881. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10882. int n, error, exit_by_callback;
  10883. int ret;
  10884. /* body_len is the length of the entire queue in bytes
  10885. * len is the length of the current message
  10886. * data_len is the length of the current message's data payload
  10887. * header_len is the length of the current message's header */
  10888. size_t i, len, mask_len = 0, header_len, body_len;
  10889. uint64_t data_len = 0;
  10890. /* "The masking key is a 32-bit value chosen at random by the client."
  10891. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10892. */
  10893. unsigned char mask[4];
  10894. /* data points to the place where the message is stored when passed to
  10895. * the websocket_data callback. This is either mem on the stack, or a
  10896. * dynamically allocated buffer if it is too large. */
  10897. unsigned char mem[4096];
  10898. unsigned char mop; /* mask flag and opcode */
  10899. /* Variables used for connection monitoring */
  10900. double timeout = -1.0;
  10901. int enable_ping_pong = 0;
  10902. int ping_count = 0;
  10903. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10904. enable_ping_pong =
  10905. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10906. "yes");
  10907. }
  10908. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10909. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10910. }
  10911. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10912. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10913. }
  10914. /* Enter data processing loop */
  10915. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10916. conn->request_info.remote_addr,
  10917. conn->request_info.remote_port);
  10918. conn->in_websocket_handling = 1;
  10919. mg_set_thread_name("wsock");
  10920. /* Loop continuously, reading messages from the socket, invoking the
  10921. * callback, and waiting repeatedly until an error occurs. */
  10922. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10923. && (!conn->must_close)) {
  10924. header_len = 0;
  10925. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10926. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10927. len = buf[1] & 127;
  10928. mask_len = (buf[1] & 128) ? 4 : 0;
  10929. if ((len < 126) && (body_len >= mask_len)) {
  10930. /* inline 7-bit length field */
  10931. data_len = len;
  10932. header_len = 2 + mask_len;
  10933. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10934. /* 16-bit length field */
  10935. header_len = 4 + mask_len;
  10936. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10937. } else if (body_len >= (10 + mask_len)) {
  10938. /* 64-bit length field */
  10939. uint32_t l1, l2;
  10940. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10941. memcpy(&l2, &buf[6], 4);
  10942. header_len = 10 + mask_len;
  10943. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10944. if (data_len > (uint64_t)0x7FFF0000ul) {
  10945. /* no can do */
  10946. mg_cry_internal(
  10947. conn,
  10948. "%s",
  10949. "websocket out of memory; closing connection");
  10950. break;
  10951. }
  10952. }
  10953. }
  10954. if ((header_len > 0) && (body_len >= header_len)) {
  10955. /* Allocate space to hold websocket payload */
  10956. unsigned char *data = mem;
  10957. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10958. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10959. conn->phys_ctx);
  10960. if (data == NULL) {
  10961. /* Allocation failed, exit the loop and then close the
  10962. * connection */
  10963. mg_cry_internal(
  10964. conn,
  10965. "%s",
  10966. "websocket out of memory; closing connection");
  10967. break;
  10968. }
  10969. }
  10970. /* Copy the mask before we shift the queue and destroy it */
  10971. if (mask_len > 0) {
  10972. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10973. } else {
  10974. memset(mask, 0, sizeof(mask));
  10975. }
  10976. /* Read frame payload from the first message in the queue into
  10977. * data and advance the queue by moving the memory in place. */
  10978. DEBUG_ASSERT(body_len >= header_len);
  10979. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10980. mop = buf[0]; /* current mask and opcode */
  10981. /* Overflow case */
  10982. len = body_len - header_len;
  10983. memcpy(data, buf + header_len, len);
  10984. error = 0;
  10985. while ((uint64_t)len < data_len) {
  10986. n = pull_inner(NULL,
  10987. conn,
  10988. (char *)(data + len),
  10989. (int)(data_len - len),
  10990. timeout);
  10991. if (n <= -2) {
  10992. error = 1;
  10993. break;
  10994. } else if (n > 0) {
  10995. len += (size_t)n;
  10996. } else {
  10997. /* Timeout: should retry */
  10998. /* TODO: retry condition */
  10999. }
  11000. }
  11001. if (error) {
  11002. mg_cry_internal(
  11003. conn,
  11004. "%s",
  11005. "Websocket pull failed; closing connection");
  11006. if (data != mem) {
  11007. mg_free(data);
  11008. }
  11009. break;
  11010. }
  11011. conn->data_len = conn->request_len;
  11012. } else {
  11013. mop = buf[0]; /* current mask and opcode, overwritten by
  11014. * memmove() */
  11015. /* Length of the message being read at the front of the
  11016. * queue. Cast to 31 bit is OK, since we limited
  11017. * data_len before. */
  11018. len = (size_t)data_len + header_len;
  11019. /* Copy the data payload into the data pointer for the
  11020. * callback. Cast to 31 bit is OK, since we
  11021. * limited data_len */
  11022. memcpy(data, buf + header_len, (size_t)data_len);
  11023. /* Move the queue forward len bytes */
  11024. memmove(buf, buf + len, body_len - len);
  11025. /* Mark the queue as advanced */
  11026. conn->data_len -= (int)len;
  11027. }
  11028. /* Apply mask if necessary */
  11029. if (mask_len > 0) {
  11030. for (i = 0; i < (size_t)data_len; i++) {
  11031. data[i] ^= mask[i & 3];
  11032. }
  11033. }
  11034. exit_by_callback = 0;
  11035. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11036. /* filter PONG messages */
  11037. DEBUG_TRACE("PONG from %s:%u",
  11038. conn->request_info.remote_addr,
  11039. conn->request_info.remote_port);
  11040. /* No unanwered PINGs left */
  11041. ping_count = 0;
  11042. } else if (enable_ping_pong
  11043. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11044. /* reply PING messages */
  11045. DEBUG_TRACE("Reply PING from %s:%u",
  11046. conn->request_info.remote_addr,
  11047. conn->request_info.remote_port);
  11048. ret = mg_websocket_write(conn,
  11049. MG_WEBSOCKET_OPCODE_PONG,
  11050. (char *)data,
  11051. (size_t)data_len);
  11052. if (ret <= 0) {
  11053. /* Error: send failed */
  11054. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11055. break;
  11056. }
  11057. } else {
  11058. /* Exit the loop if callback signals to exit (server side),
  11059. * or "connection close" opcode received (client side). */
  11060. if ((ws_data_handler != NULL)
  11061. && !ws_data_handler(conn,
  11062. mop,
  11063. (char *)data,
  11064. (size_t)data_len,
  11065. callback_data)) {
  11066. exit_by_callback = 1;
  11067. }
  11068. }
  11069. /* It a buffer has been allocated, free it again */
  11070. if (data != mem) {
  11071. mg_free(data);
  11072. }
  11073. if (exit_by_callback) {
  11074. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11075. conn->request_info.remote_addr,
  11076. conn->request_info.remote_port);
  11077. break;
  11078. }
  11079. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11080. /* Opcode == 8, connection close */
  11081. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11082. conn->request_info.remote_addr,
  11083. conn->request_info.remote_port);
  11084. break;
  11085. }
  11086. /* Not breaking the loop, process next websocket frame. */
  11087. } else {
  11088. /* Read from the socket into the next available location in the
  11089. * message queue. */
  11090. n = pull_inner(NULL,
  11091. conn,
  11092. conn->buf + conn->data_len,
  11093. conn->buf_size - conn->data_len,
  11094. timeout);
  11095. if (n <= -2) {
  11096. /* Error, no bytes read */
  11097. DEBUG_TRACE("PULL from %s:%u failed",
  11098. conn->request_info.remote_addr,
  11099. conn->request_info.remote_port);
  11100. break;
  11101. }
  11102. if (n > 0) {
  11103. conn->data_len += n;
  11104. /* Reset open PING count */
  11105. ping_count = 0;
  11106. } else {
  11107. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11108. && (!conn->must_close)) {
  11109. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11110. /* Stop sending PING */
  11111. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11112. "- closing connection",
  11113. ping_count,
  11114. conn->request_info.remote_addr,
  11115. conn->request_info.remote_port);
  11116. break;
  11117. }
  11118. if (enable_ping_pong) {
  11119. /* Send Websocket PING message */
  11120. DEBUG_TRACE("PING to %s:%u",
  11121. conn->request_info.remote_addr,
  11122. conn->request_info.remote_port);
  11123. ret = mg_websocket_write(conn,
  11124. MG_WEBSOCKET_OPCODE_PING,
  11125. NULL,
  11126. 0);
  11127. if (ret <= 0) {
  11128. /* Error: send failed */
  11129. DEBUG_TRACE("Send PING failed (%i)", ret);
  11130. break;
  11131. }
  11132. ping_count++;
  11133. }
  11134. }
  11135. /* Timeout: should retry */
  11136. /* TODO: get timeout def */
  11137. }
  11138. }
  11139. }
  11140. /* Leave data processing loop */
  11141. mg_set_thread_name("worker");
  11142. conn->in_websocket_handling = 0;
  11143. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11144. conn->request_info.remote_addr,
  11145. conn->request_info.remote_port);
  11146. }
  11147. static int
  11148. mg_websocket_write_exec(struct mg_connection *conn,
  11149. int opcode,
  11150. const char *data,
  11151. size_t dataLen,
  11152. uint32_t masking_key)
  11153. {
  11154. unsigned char header[14];
  11155. size_t headerLen;
  11156. int retval;
  11157. #if defined(GCC_DIAGNOSTIC)
  11158. /* Disable spurious conversion warning for GCC */
  11159. #pragma GCC diagnostic push
  11160. #pragma GCC diagnostic ignored "-Wconversion"
  11161. #endif
  11162. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11163. #if defined(GCC_DIAGNOSTIC)
  11164. #pragma GCC diagnostic pop
  11165. #endif
  11166. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11167. if (dataLen < 126) {
  11168. /* inline 7-bit length field */
  11169. header[1] = (unsigned char)dataLen;
  11170. headerLen = 2;
  11171. } else if (dataLen <= 0xFFFF) {
  11172. /* 16-bit length field */
  11173. uint16_t len = htons((uint16_t)dataLen);
  11174. header[1] = 126;
  11175. memcpy(header + 2, &len, 2);
  11176. headerLen = 4;
  11177. } else {
  11178. /* 64-bit length field */
  11179. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11180. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11181. header[1] = 127;
  11182. memcpy(header + 2, &len1, 4);
  11183. memcpy(header + 6, &len2, 4);
  11184. headerLen = 10;
  11185. }
  11186. if (masking_key) {
  11187. /* add mask */
  11188. header[1] |= 0x80;
  11189. memcpy(header + headerLen, &masking_key, 4);
  11190. headerLen += 4;
  11191. }
  11192. /* Note that POSIX/Winsock's send() is threadsafe
  11193. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11194. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11195. * push(), although that is only a problem if the packet is large or
  11196. * outgoing buffer is full). */
  11197. /* TODO: Check if this lock should be moved to user land.
  11198. * Currently the server sets this lock for websockets, but
  11199. * not for any other connection. It must be set for every
  11200. * conn read/written by more than one thread, no matter if
  11201. * it is a websocket or regular connection. */
  11202. (void)mg_lock_connection(conn);
  11203. retval = mg_write(conn, header, headerLen);
  11204. if (retval != (int)headerLen) {
  11205. /* Did not send complete header */
  11206. retval = -1;
  11207. } else {
  11208. if (dataLen > 0) {
  11209. retval = mg_write(conn, data, dataLen);
  11210. }
  11211. /* if dataLen == 0, the header length (2) is returned */
  11212. }
  11213. /* TODO: Remove this unlock as well, when lock is removed. */
  11214. mg_unlock_connection(conn);
  11215. return retval;
  11216. }
  11217. int
  11218. mg_websocket_write(struct mg_connection *conn,
  11219. int opcode,
  11220. const char *data,
  11221. size_t dataLen)
  11222. {
  11223. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11224. }
  11225. static void
  11226. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11227. {
  11228. size_t i = 0;
  11229. i = 0;
  11230. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11231. /* Convert in 32 bit words, if data is 4 byte aligned */
  11232. while (i < (in_len - 3)) {
  11233. *(uint32_t *)(void *)(out + i) =
  11234. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11235. i += 4;
  11236. }
  11237. }
  11238. if (i != in_len) {
  11239. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11240. while (i < in_len) {
  11241. *(uint8_t *)(void *)(out + i) =
  11242. *(uint8_t *)(void *)(in + i)
  11243. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11244. i++;
  11245. }
  11246. }
  11247. }
  11248. int
  11249. mg_websocket_client_write(struct mg_connection *conn,
  11250. int opcode,
  11251. const char *data,
  11252. size_t dataLen)
  11253. {
  11254. int retval = -1;
  11255. char *masked_data =
  11256. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11257. uint32_t masking_key = 0;
  11258. if (masked_data == NULL) {
  11259. /* Return -1 in an error case */
  11260. mg_cry_internal(conn,
  11261. "%s",
  11262. "Cannot allocate buffer for masked websocket response: "
  11263. "Out of memory");
  11264. return -1;
  11265. }
  11266. do {
  11267. /* Get a masking key - but not 0 */
  11268. masking_key = (uint32_t)get_random();
  11269. } while (masking_key == 0);
  11270. mask_data(data, dataLen, masking_key, masked_data);
  11271. retval = mg_websocket_write_exec(
  11272. conn, opcode, masked_data, dataLen, masking_key);
  11273. mg_free(masked_data);
  11274. return retval;
  11275. }
  11276. static void
  11277. handle_websocket_request(struct mg_connection *conn,
  11278. const char *path,
  11279. int is_callback_resource,
  11280. struct mg_websocket_subprotocols *subprotocols,
  11281. mg_websocket_connect_handler ws_connect_handler,
  11282. mg_websocket_ready_handler ws_ready_handler,
  11283. mg_websocket_data_handler ws_data_handler,
  11284. mg_websocket_close_handler ws_close_handler,
  11285. void *cbData)
  11286. {
  11287. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11288. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11289. ptrdiff_t lua_websock = 0;
  11290. #if !defined(USE_LUA)
  11291. (void)path;
  11292. #endif
  11293. /* Step 1: Check websocket protocol version. */
  11294. /* Step 1.1: Check Sec-WebSocket-Key. */
  11295. if (!websock_key) {
  11296. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11297. * requires a Sec-WebSocket-Key header.
  11298. */
  11299. /* It could be the hixie draft version
  11300. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11301. */
  11302. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11303. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11304. char key3[8];
  11305. if ((key1 != NULL) && (key2 != NULL)) {
  11306. /* This version uses 8 byte body data in a GET request */
  11307. conn->content_len = 8;
  11308. if (8 == mg_read(conn, key3, 8)) {
  11309. /* This is the hixie version */
  11310. mg_send_http_error(conn,
  11311. 426,
  11312. "%s",
  11313. "Protocol upgrade to RFC 6455 required");
  11314. return;
  11315. }
  11316. }
  11317. /* This is an unknown version */
  11318. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11319. return;
  11320. }
  11321. /* Step 1.2: Check websocket protocol version. */
  11322. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11323. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11324. /* Reject wrong versions */
  11325. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11326. return;
  11327. }
  11328. /* Step 1.3: Could check for "Host", but we do not really nead this
  11329. * value for anything, so just ignore it. */
  11330. /* Step 2: If a callback is responsible, call it. */
  11331. if (is_callback_resource) {
  11332. /* Step 2.1 check and select subprotocol */
  11333. const char *protocols[64]; // max 64 headers
  11334. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11335. "Sec-WebSocket-Protocol",
  11336. protocols,
  11337. 64);
  11338. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11339. int cnt = 0;
  11340. int idx;
  11341. unsigned long len;
  11342. const char *sep, *curSubProtocol,
  11343. *acceptedWebSocketSubprotocol = NULL;
  11344. /* look for matching subprotocol */
  11345. do {
  11346. const char *protocol = protocols[cnt];
  11347. do {
  11348. sep = strchr(protocol, ',');
  11349. curSubProtocol = protocol;
  11350. len = sep ? (unsigned long)(sep - protocol)
  11351. : (unsigned long)strlen(protocol);
  11352. while (sep && isspace((unsigned char)*++sep))
  11353. ; // ignore leading whitespaces
  11354. protocol = sep;
  11355. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11356. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11357. && (strncmp(curSubProtocol,
  11358. subprotocols->subprotocols[idx],
  11359. len)
  11360. == 0)) {
  11361. acceptedWebSocketSubprotocol =
  11362. subprotocols->subprotocols[idx];
  11363. break;
  11364. }
  11365. }
  11366. } while (sep && !acceptedWebSocketSubprotocol);
  11367. } while (++cnt < nbSubprotocolHeader
  11368. && !acceptedWebSocketSubprotocol);
  11369. conn->request_info.acceptedWebSocketSubprotocol =
  11370. acceptedWebSocketSubprotocol;
  11371. } else if (nbSubprotocolHeader > 0) {
  11372. /* keep legacy behavior */
  11373. const char *protocol = protocols[0];
  11374. /* The protocol is a comma separated list of names. */
  11375. /* The server must only return one value from this list. */
  11376. /* First check if it is a list or just a single value. */
  11377. const char *sep = strrchr(protocol, ',');
  11378. if (sep == NULL) {
  11379. /* Just a single protocol -> accept it. */
  11380. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11381. } else {
  11382. /* Multiple protocols -> accept the last one. */
  11383. /* This is just a quick fix if the client offers multiple
  11384. * protocols. The handler should have a list of accepted
  11385. * protocols on his own
  11386. * and use it to select one protocol among those the client
  11387. * has
  11388. * offered.
  11389. */
  11390. while (isspace((unsigned char)*++sep)) {
  11391. ; /* ignore leading whitespaces */
  11392. }
  11393. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11394. }
  11395. }
  11396. if ((ws_connect_handler != NULL)
  11397. && (ws_connect_handler(conn, cbData) != 0)) {
  11398. /* C callback has returned non-zero, do not proceed with
  11399. * handshake.
  11400. */
  11401. /* Note that C callbacks are no longer called when Lua is
  11402. * responsible, so C can no longer filter callbacks for Lua. */
  11403. return;
  11404. }
  11405. }
  11406. #if defined(USE_LUA)
  11407. /* Step 3: No callback. Check if Lua is responsible. */
  11408. else {
  11409. /* Step 3.1: Check if Lua is responsible. */
  11410. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11411. lua_websock = match_prefix(
  11412. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11413. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11414. path);
  11415. }
  11416. if (lua_websock) {
  11417. /* Step 3.2: Lua is responsible: call it. */
  11418. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11419. if (!conn->lua_websocket_state) {
  11420. /* Lua rejected the new client */
  11421. return;
  11422. }
  11423. }
  11424. }
  11425. #endif
  11426. /* Step 4: Check if there is a responsible websocket handler. */
  11427. if (!is_callback_resource && !lua_websock) {
  11428. /* There is no callback, and Lua is not responsible either. */
  11429. /* Reply with a 404 Not Found. We are still at a standard
  11430. * HTTP request here, before the websocket handshake, so
  11431. * we can still send standard HTTP error replies. */
  11432. mg_send_http_error(conn, 404, "%s", "Not found");
  11433. return;
  11434. }
  11435. /* Step 5: The websocket connection has been accepted */
  11436. if (!send_websocket_handshake(conn, websock_key)) {
  11437. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11438. return;
  11439. }
  11440. /* Step 6: Call the ready handler */
  11441. if (is_callback_resource) {
  11442. if (ws_ready_handler != NULL) {
  11443. ws_ready_handler(conn, cbData);
  11444. }
  11445. #if defined(USE_LUA)
  11446. } else if (lua_websock) {
  11447. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11448. /* the ready handler returned false */
  11449. return;
  11450. }
  11451. #endif
  11452. }
  11453. /* Step 7: Enter the read loop */
  11454. if (is_callback_resource) {
  11455. read_websocket(conn, ws_data_handler, cbData);
  11456. #if defined(USE_LUA)
  11457. } else if (lua_websock) {
  11458. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11459. #endif
  11460. }
  11461. /* Step 8: Call the close handler */
  11462. if (ws_close_handler) {
  11463. ws_close_handler(conn, cbData);
  11464. }
  11465. }
  11466. #endif /* !USE_WEBSOCKET */
  11467. /* Is upgrade request:
  11468. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11469. * 1 = upgrade to websocket
  11470. * 2 = upgrade to HTTP/2
  11471. * -1 = upgrade to unknown protocol
  11472. */
  11473. static int
  11474. should_switch_to_protocol(const struct mg_connection *conn)
  11475. {
  11476. const char *upgrade, *connection;
  11477. /* A websocket protocoll has the following HTTP headers:
  11478. *
  11479. * Connection: Upgrade
  11480. * Upgrade: Websocket
  11481. */
  11482. connection = mg_get_header(conn, "Connection");
  11483. if (connection == NULL) {
  11484. return PROTOCOL_TYPE_HTTP1;
  11485. }
  11486. if (!mg_strcasestr(connection, "upgrade")) {
  11487. return PROTOCOL_TYPE_HTTP1;
  11488. }
  11489. upgrade = mg_get_header(conn, "Upgrade");
  11490. if (upgrade == NULL) {
  11491. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11492. return -1;
  11493. }
  11494. /* Upgrade to ... */
  11495. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11496. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11497. * "Sec-WebSocket-Version" are also required.
  11498. * Don't check them here, since even an unsupported websocket protocol
  11499. * request still IS a websocket request (in contrast to a standard HTTP
  11500. * request). It will fail later in handle_websocket_request.
  11501. */
  11502. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11503. }
  11504. if (0 != mg_strcasestr(upgrade, "h2")) {
  11505. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11506. }
  11507. /* Upgrade to another protocol */
  11508. return -1;
  11509. }
  11510. static int
  11511. isbyte(int n)
  11512. {
  11513. return (n >= 0) && (n <= 255);
  11514. }
  11515. static int
  11516. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11517. {
  11518. int n, a, b, c, d, slash = 32, len = 0;
  11519. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11520. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11521. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11522. && (slash < 33)) {
  11523. len = n;
  11524. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11525. | (uint32_t)d;
  11526. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11527. }
  11528. return len;
  11529. }
  11530. static int
  11531. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11532. {
  11533. int throttle = 0;
  11534. struct vec vec, val;
  11535. uint32_t net, mask;
  11536. char mult;
  11537. double v;
  11538. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11539. mult = ',';
  11540. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11541. || (v < 0)
  11542. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11543. && (mult != ','))) {
  11544. continue;
  11545. }
  11546. v *= (lowercase(&mult) == 'k')
  11547. ? 1024
  11548. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11549. if (vec.len == 1 && vec.ptr[0] == '*') {
  11550. throttle = (int)v;
  11551. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11552. if ((remote_ip & mask) == net) {
  11553. throttle = (int)v;
  11554. }
  11555. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11556. throttle = (int)v;
  11557. }
  11558. }
  11559. return throttle;
  11560. }
  11561. static uint32_t
  11562. get_remote_ip(const struct mg_connection *conn)
  11563. {
  11564. if (!conn) {
  11565. return 0;
  11566. }
  11567. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11568. }
  11569. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11570. #include "handle_form.inl"
  11571. #if defined(MG_LEGACY_INTERFACE)
  11572. /* Implement the deprecated mg_upload function by calling the new
  11573. * mg_handle_form_request function. While mg_upload could only handle
  11574. * HTML forms sent as POST request in multipart/form-data format
  11575. * containing only file input elements, mg_handle_form_request can
  11576. * handle all form input elements and all standard request methods. */
  11577. struct mg_upload_user_data {
  11578. struct mg_connection *conn;
  11579. const char *destination_dir;
  11580. int num_uploaded_files;
  11581. };
  11582. /* Helper function for deprecated mg_upload. */
  11583. static int
  11584. mg_upload_field_found(const char *key,
  11585. const char *filename,
  11586. char *path,
  11587. size_t pathlen,
  11588. void *user_data)
  11589. {
  11590. int truncated = 0;
  11591. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11592. (void)key;
  11593. if (!filename) {
  11594. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11595. return FORM_FIELD_STORAGE_ABORT;
  11596. }
  11597. mg_snprintf(fud->conn,
  11598. &truncated,
  11599. path,
  11600. pathlen - 1,
  11601. "%s/%s",
  11602. fud->destination_dir,
  11603. filename);
  11604. if (truncated) {
  11605. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11606. return FORM_FIELD_STORAGE_ABORT;
  11607. }
  11608. return FORM_FIELD_STORAGE_STORE;
  11609. }
  11610. /* Helper function for deprecated mg_upload. */
  11611. static int
  11612. mg_upload_field_get(const char *key,
  11613. const char *value,
  11614. size_t value_size,
  11615. void *user_data)
  11616. {
  11617. /* Function should never be called */
  11618. (void)key;
  11619. (void)value;
  11620. (void)value_size;
  11621. (void)user_data;
  11622. return 0;
  11623. }
  11624. /* Helper function for deprecated mg_upload. */
  11625. static int
  11626. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11627. {
  11628. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11629. (void)file_size;
  11630. fud->num_uploaded_files++;
  11631. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11632. return 0;
  11633. }
  11634. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11635. int
  11636. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11637. {
  11638. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11639. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11640. mg_upload_field_get,
  11641. mg_upload_field_stored,
  11642. 0};
  11643. int ret;
  11644. fdh.user_data = (void *)&fud;
  11645. ret = mg_handle_form_request(conn, &fdh);
  11646. if (ret < 0) {
  11647. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11648. }
  11649. return fud.num_uploaded_files;
  11650. }
  11651. #endif
  11652. static int
  11653. get_first_ssl_listener_index(const struct mg_context *ctx)
  11654. {
  11655. unsigned int i;
  11656. int idx = -1;
  11657. if (ctx) {
  11658. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11659. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11660. }
  11661. }
  11662. return idx;
  11663. }
  11664. /* Return host (without port) */
  11665. /* Use mg_free to free the result */
  11666. static const char *
  11667. alloc_get_host(struct mg_connection *conn)
  11668. {
  11669. char buf[1025];
  11670. size_t buflen = sizeof(buf);
  11671. const char *host_header = get_header(conn->request_info.http_headers,
  11672. conn->request_info.num_headers,
  11673. "Host");
  11674. char *host;
  11675. if (host_header != NULL) {
  11676. char *pos;
  11677. /* Create a local copy of the "Host" header, since it might be
  11678. * modified here. */
  11679. mg_strlcpy(buf, host_header, buflen);
  11680. buf[buflen - 1] = '\0';
  11681. host = buf;
  11682. while (isspace((unsigned char)*host)) {
  11683. host++;
  11684. }
  11685. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11686. * is found. */
  11687. if (*host == '[') {
  11688. pos = strchr(host, ']');
  11689. if (!pos) {
  11690. /* Malformed hostname starts with '[', but no ']' found */
  11691. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11692. return NULL;
  11693. }
  11694. /* terminate after ']' */
  11695. pos[1] = 0;
  11696. } else {
  11697. /* Otherwise, a ':' separates hostname and port number */
  11698. pos = strchr(host, ':');
  11699. if (pos != NULL) {
  11700. *pos = '\0';
  11701. }
  11702. }
  11703. if (conn->ssl) {
  11704. /* This is a HTTPS connection, maybe we have a hostname
  11705. * from SNI (set in ssl_servername_callback). */
  11706. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11707. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11708. /* We are not using the default domain */
  11709. if (mg_strcasecmp(host, sslhost)) {
  11710. /* Mismatch between SNI domain and HTTP domain */
  11711. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11712. sslhost,
  11713. host);
  11714. return NULL;
  11715. }
  11716. }
  11717. DEBUG_TRACE("HTTPS Host: %s", host);
  11718. } else {
  11719. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11720. while (dom) {
  11721. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11722. /* Found matching domain */
  11723. DEBUG_TRACE("HTTP domain %s found",
  11724. dom->config[AUTHENTICATION_DOMAIN]);
  11725. /* TODO: Check if this is a HTTP or HTTPS domain */
  11726. conn->dom_ctx = dom;
  11727. break;
  11728. }
  11729. mg_lock_context(conn->phys_ctx);
  11730. dom = dom->next;
  11731. mg_unlock_context(conn->phys_ctx);
  11732. }
  11733. DEBUG_TRACE("HTTP Host: %s", host);
  11734. }
  11735. } else {
  11736. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11737. host = buf;
  11738. DEBUG_TRACE("IP: %s", host);
  11739. }
  11740. return mg_strdup_ctx(host, conn->phys_ctx);
  11741. }
  11742. static void
  11743. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11744. {
  11745. char target_url[MG_BUF_LEN];
  11746. int truncated = 0;
  11747. conn->must_close = 1;
  11748. /* Send host, port, uri and (if it exists) ?query_string */
  11749. if (conn->host) {
  11750. /* Use "308 Permanent Redirect" */
  11751. int redirect_code = 308;
  11752. /* Create target URL */
  11753. mg_snprintf(
  11754. conn,
  11755. &truncated,
  11756. target_url,
  11757. sizeof(target_url),
  11758. "https://%s:%d%s%s%s",
  11759. conn->host,
  11760. #if defined(USE_IPV6)
  11761. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11762. == AF_INET6)
  11763. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11764. .lsa.sin6.sin6_port)
  11765. :
  11766. #endif
  11767. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11768. .lsa.sin.sin_port),
  11769. conn->request_info.local_uri,
  11770. (conn->request_info.query_string == NULL) ? "" : "?",
  11771. (conn->request_info.query_string == NULL)
  11772. ? ""
  11773. : conn->request_info.query_string);
  11774. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11775. * is used as buffer size) */
  11776. if (truncated) {
  11777. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11778. return;
  11779. }
  11780. /* Use redirect helper function */
  11781. mg_send_http_redirect(conn, target_url, redirect_code);
  11782. }
  11783. }
  11784. static void
  11785. mg_set_handler_type(struct mg_context *phys_ctx,
  11786. struct mg_domain_context *dom_ctx,
  11787. const char *uri,
  11788. int handler_type,
  11789. int is_delete_request,
  11790. mg_request_handler handler,
  11791. struct mg_websocket_subprotocols *subprotocols,
  11792. mg_websocket_connect_handler connect_handler,
  11793. mg_websocket_ready_handler ready_handler,
  11794. mg_websocket_data_handler data_handler,
  11795. mg_websocket_close_handler close_handler,
  11796. mg_authorization_handler auth_handler,
  11797. void *cbdata)
  11798. {
  11799. struct mg_handler_info *tmp_rh, **lastref;
  11800. size_t urilen = strlen(uri);
  11801. if (handler_type == WEBSOCKET_HANDLER) {
  11802. DEBUG_ASSERT(handler == NULL);
  11803. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11804. || ready_handler != NULL || data_handler != NULL
  11805. || close_handler != NULL);
  11806. DEBUG_ASSERT(auth_handler == NULL);
  11807. if (handler != NULL) {
  11808. return;
  11809. }
  11810. if (!is_delete_request && (connect_handler == NULL)
  11811. && (ready_handler == NULL) && (data_handler == NULL)
  11812. && (close_handler == NULL)) {
  11813. return;
  11814. }
  11815. if (auth_handler != NULL) {
  11816. return;
  11817. }
  11818. } else if (handler_type == REQUEST_HANDLER) {
  11819. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11820. && data_handler == NULL && close_handler == NULL);
  11821. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11822. DEBUG_ASSERT(auth_handler == NULL);
  11823. if ((connect_handler != NULL) || (ready_handler != NULL)
  11824. || (data_handler != NULL) || (close_handler != NULL)) {
  11825. return;
  11826. }
  11827. if (!is_delete_request && (handler == NULL)) {
  11828. return;
  11829. }
  11830. if (auth_handler != NULL) {
  11831. return;
  11832. }
  11833. } else { /* AUTH_HANDLER */
  11834. DEBUG_ASSERT(handler == NULL);
  11835. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11836. && data_handler == NULL && close_handler == NULL);
  11837. DEBUG_ASSERT(auth_handler != NULL);
  11838. if (handler != NULL) {
  11839. return;
  11840. }
  11841. if ((connect_handler != NULL) || (ready_handler != NULL)
  11842. || (data_handler != NULL) || (close_handler != NULL)) {
  11843. return;
  11844. }
  11845. if (!is_delete_request && (auth_handler == NULL)) {
  11846. return;
  11847. }
  11848. }
  11849. if (!phys_ctx || !dom_ctx) {
  11850. return;
  11851. }
  11852. mg_lock_context(phys_ctx);
  11853. /* first try to find an existing handler */
  11854. do {
  11855. lastref = &(dom_ctx->handlers);
  11856. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11857. if (tmp_rh->handler_type == handler_type
  11858. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11859. if (!is_delete_request) {
  11860. /* update existing handler */
  11861. if (handler_type == REQUEST_HANDLER) {
  11862. /* Wait for end of use before updating */
  11863. if (tmp_rh->refcount) {
  11864. mg_unlock_context(phys_ctx);
  11865. mg_sleep(1);
  11866. mg_lock_context(phys_ctx);
  11867. /* tmp_rh might have been freed, search again. */
  11868. break;
  11869. }
  11870. /* Ok, the handler is no more use -> Update it */
  11871. tmp_rh->handler = handler;
  11872. } else if (handler_type == WEBSOCKET_HANDLER) {
  11873. tmp_rh->subprotocols = subprotocols;
  11874. tmp_rh->connect_handler = connect_handler;
  11875. tmp_rh->ready_handler = ready_handler;
  11876. tmp_rh->data_handler = data_handler;
  11877. tmp_rh->close_handler = close_handler;
  11878. } else { /* AUTH_HANDLER */
  11879. tmp_rh->auth_handler = auth_handler;
  11880. }
  11881. tmp_rh->cbdata = cbdata;
  11882. } else {
  11883. /* remove existing handler */
  11884. if (handler_type == REQUEST_HANDLER) {
  11885. /* Wait for end of use before removing */
  11886. if (tmp_rh->refcount) {
  11887. tmp_rh->removing = 1;
  11888. mg_unlock_context(phys_ctx);
  11889. mg_sleep(1);
  11890. mg_lock_context(phys_ctx);
  11891. /* tmp_rh might have been freed, search again. */
  11892. break;
  11893. }
  11894. /* Ok, the handler is no more used */
  11895. }
  11896. *lastref = tmp_rh->next;
  11897. mg_free(tmp_rh->uri);
  11898. mg_free(tmp_rh);
  11899. }
  11900. mg_unlock_context(phys_ctx);
  11901. return;
  11902. }
  11903. lastref = &(tmp_rh->next);
  11904. }
  11905. } while (tmp_rh != NULL);
  11906. if (is_delete_request) {
  11907. /* no handler to set, this was a remove request to a non-existing
  11908. * handler */
  11909. mg_unlock_context(phys_ctx);
  11910. return;
  11911. }
  11912. tmp_rh =
  11913. (struct mg_handler_info *)mg_calloc_ctx(1,
  11914. sizeof(struct mg_handler_info),
  11915. phys_ctx);
  11916. if (tmp_rh == NULL) {
  11917. mg_unlock_context(phys_ctx);
  11918. mg_cry_ctx_internal(phys_ctx,
  11919. "%s",
  11920. "Cannot create new request handler struct, OOM");
  11921. return;
  11922. }
  11923. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11924. if (!tmp_rh->uri) {
  11925. mg_unlock_context(phys_ctx);
  11926. mg_free(tmp_rh);
  11927. mg_cry_ctx_internal(phys_ctx,
  11928. "%s",
  11929. "Cannot create new request handler struct, OOM");
  11930. return;
  11931. }
  11932. tmp_rh->uri_len = urilen;
  11933. if (handler_type == REQUEST_HANDLER) {
  11934. tmp_rh->refcount = 0;
  11935. tmp_rh->removing = 0;
  11936. tmp_rh->handler = handler;
  11937. } else if (handler_type == WEBSOCKET_HANDLER) {
  11938. tmp_rh->subprotocols = subprotocols;
  11939. tmp_rh->connect_handler = connect_handler;
  11940. tmp_rh->ready_handler = ready_handler;
  11941. tmp_rh->data_handler = data_handler;
  11942. tmp_rh->close_handler = close_handler;
  11943. } else { /* AUTH_HANDLER */
  11944. tmp_rh->auth_handler = auth_handler;
  11945. }
  11946. tmp_rh->cbdata = cbdata;
  11947. tmp_rh->handler_type = handler_type;
  11948. tmp_rh->next = NULL;
  11949. *lastref = tmp_rh;
  11950. mg_unlock_context(phys_ctx);
  11951. }
  11952. void
  11953. mg_set_request_handler(struct mg_context *ctx,
  11954. const char *uri,
  11955. mg_request_handler handler,
  11956. void *cbdata)
  11957. {
  11958. mg_set_handler_type(ctx,
  11959. &(ctx->dd),
  11960. uri,
  11961. REQUEST_HANDLER,
  11962. handler == NULL,
  11963. handler,
  11964. NULL,
  11965. NULL,
  11966. NULL,
  11967. NULL,
  11968. NULL,
  11969. NULL,
  11970. cbdata);
  11971. }
  11972. void
  11973. mg_set_websocket_handler(struct mg_context *ctx,
  11974. const char *uri,
  11975. mg_websocket_connect_handler connect_handler,
  11976. mg_websocket_ready_handler ready_handler,
  11977. mg_websocket_data_handler data_handler,
  11978. mg_websocket_close_handler close_handler,
  11979. void *cbdata)
  11980. {
  11981. mg_set_websocket_handler_with_subprotocols(ctx,
  11982. uri,
  11983. NULL,
  11984. connect_handler,
  11985. ready_handler,
  11986. data_handler,
  11987. close_handler,
  11988. cbdata);
  11989. }
  11990. void
  11991. mg_set_websocket_handler_with_subprotocols(
  11992. struct mg_context *ctx,
  11993. const char *uri,
  11994. struct mg_websocket_subprotocols *subprotocols,
  11995. mg_websocket_connect_handler connect_handler,
  11996. mg_websocket_ready_handler ready_handler,
  11997. mg_websocket_data_handler data_handler,
  11998. mg_websocket_close_handler close_handler,
  11999. void *cbdata)
  12000. {
  12001. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12002. && (data_handler == NULL)
  12003. && (close_handler == NULL);
  12004. mg_set_handler_type(ctx,
  12005. &(ctx->dd),
  12006. uri,
  12007. WEBSOCKET_HANDLER,
  12008. is_delete_request,
  12009. NULL,
  12010. subprotocols,
  12011. connect_handler,
  12012. ready_handler,
  12013. data_handler,
  12014. close_handler,
  12015. NULL,
  12016. cbdata);
  12017. }
  12018. void
  12019. mg_set_auth_handler(struct mg_context *ctx,
  12020. const char *uri,
  12021. mg_authorization_handler handler,
  12022. void *cbdata)
  12023. {
  12024. mg_set_handler_type(ctx,
  12025. &(ctx->dd),
  12026. uri,
  12027. AUTH_HANDLER,
  12028. handler == NULL,
  12029. NULL,
  12030. NULL,
  12031. NULL,
  12032. NULL,
  12033. NULL,
  12034. NULL,
  12035. handler,
  12036. cbdata);
  12037. }
  12038. static int
  12039. get_request_handler(struct mg_connection *conn,
  12040. int handler_type,
  12041. mg_request_handler *handler,
  12042. struct mg_websocket_subprotocols **subprotocols,
  12043. mg_websocket_connect_handler *connect_handler,
  12044. mg_websocket_ready_handler *ready_handler,
  12045. mg_websocket_data_handler *data_handler,
  12046. mg_websocket_close_handler *close_handler,
  12047. mg_authorization_handler *auth_handler,
  12048. void **cbdata,
  12049. struct mg_handler_info **handler_info)
  12050. {
  12051. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12052. if (request_info) {
  12053. const char *uri = request_info->local_uri;
  12054. size_t urilen = strlen(uri);
  12055. struct mg_handler_info *tmp_rh;
  12056. int step, matched;
  12057. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12058. return 0;
  12059. }
  12060. mg_lock_context(conn->phys_ctx);
  12061. for (step = 0; step < 3; step++) {
  12062. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12063. tmp_rh = tmp_rh->next) {
  12064. if (tmp_rh->handler_type != handler_type) {
  12065. continue;
  12066. }
  12067. if (step == 0) {
  12068. /* first try for an exact match */
  12069. matched = (tmp_rh->uri_len == urilen)
  12070. && (strcmp(tmp_rh->uri, uri) == 0);
  12071. } else if (step == 1) {
  12072. /* next try for a partial match, we will accept
  12073. uri/something */
  12074. matched = (tmp_rh->uri_len < urilen)
  12075. && (uri[tmp_rh->uri_len] == '/')
  12076. && (memcmp(tmp_rh->uri, uri,
  12077. tmp_rh->uri_len) == 0);
  12078. } else {
  12079. /* finally try for pattern match */
  12080. matched = match_prefix(tmp_rh->uri,
  12081. tmp_rh->uri_len, uri) > 0;
  12082. }
  12083. if (matched) {
  12084. if (handler_type == WEBSOCKET_HANDLER) {
  12085. *subprotocols = tmp_rh->subprotocols;
  12086. *connect_handler = tmp_rh->connect_handler;
  12087. *ready_handler = tmp_rh->ready_handler;
  12088. *data_handler = tmp_rh->data_handler;
  12089. *close_handler = tmp_rh->close_handler;
  12090. } else if (handler_type == REQUEST_HANDLER) {
  12091. if (tmp_rh->removing) {
  12092. /* Treat as none found */
  12093. step = 2;
  12094. break;
  12095. }
  12096. *handler = tmp_rh->handler;
  12097. /* Acquire handler and give it back */
  12098. tmp_rh->refcount++;
  12099. *handler_info = tmp_rh;
  12100. } else { /* AUTH_HANDLER */
  12101. *auth_handler = tmp_rh->auth_handler;
  12102. }
  12103. *cbdata = tmp_rh->cbdata;
  12104. mg_unlock_context(conn->phys_ctx);
  12105. return 1;
  12106. }
  12107. }
  12108. }
  12109. mg_unlock_context(conn->phys_ctx);
  12110. }
  12111. return 0; /* none found */
  12112. }
  12113. /* Check if the script file is in a path, allowed for script files.
  12114. * This can be used if uploading files is possible not only for the server
  12115. * admin, and the upload mechanism does not check the file extension.
  12116. */
  12117. static int
  12118. is_in_script_path(const struct mg_connection *conn, const char *path)
  12119. {
  12120. /* TODO (Feature): Add config value for allowed script path.
  12121. * Default: All allowed. */
  12122. (void)conn;
  12123. (void)path;
  12124. return 1;
  12125. }
  12126. #if defined(USE_WEBSOCKET) \
  12127. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12128. static int
  12129. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12130. void *cbdata)
  12131. {
  12132. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12133. if (pcallbacks->websocket_connect) {
  12134. return pcallbacks->websocket_connect(conn);
  12135. }
  12136. /* No handler set - assume "OK" */
  12137. return 0;
  12138. }
  12139. static void
  12140. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12141. {
  12142. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12143. if (pcallbacks->websocket_ready) {
  12144. pcallbacks->websocket_ready(conn);
  12145. }
  12146. }
  12147. static int
  12148. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12149. int bits,
  12150. char *data,
  12151. size_t len,
  12152. void *cbdata)
  12153. {
  12154. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12155. if (pcallbacks->websocket_data) {
  12156. return pcallbacks->websocket_data(conn, bits, data, len);
  12157. }
  12158. /* No handler set - assume "OK" */
  12159. return 1;
  12160. }
  12161. static void
  12162. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12163. void *cbdata)
  12164. {
  12165. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12166. if (pcallbacks->connection_close) {
  12167. pcallbacks->connection_close(conn);
  12168. }
  12169. }
  12170. #endif
  12171. /* This is the heart of the Civetweb's logic.
  12172. * This function is called when the request is read, parsed and validated,
  12173. * and Civetweb must decide what action to take: serve a file, or
  12174. * a directory, or call embedded function, etcetera. */
  12175. static void
  12176. handle_request(struct mg_connection *conn)
  12177. {
  12178. struct mg_request_info *ri = &conn->request_info;
  12179. char path[PATH_MAX];
  12180. int uri_len, ssl_index;
  12181. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12182. is_put_or_delete_request = 0, is_callback_resource = 0;
  12183. int i;
  12184. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12185. mg_request_handler callback_handler = NULL;
  12186. struct mg_handler_info *handler_info = NULL;
  12187. struct mg_websocket_subprotocols *subprotocols;
  12188. mg_websocket_connect_handler ws_connect_handler = NULL;
  12189. mg_websocket_ready_handler ws_ready_handler = NULL;
  12190. mg_websocket_data_handler ws_data_handler = NULL;
  12191. mg_websocket_close_handler ws_close_handler = NULL;
  12192. void *callback_data = NULL;
  12193. mg_authorization_handler auth_handler = NULL;
  12194. void *auth_callback_data = NULL;
  12195. int handler_type;
  12196. time_t curtime = time(NULL);
  12197. char date[64];
  12198. path[0] = 0;
  12199. /* 1. get the request url */
  12200. /* 1.1. split into url and query string */
  12201. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12202. != NULL) {
  12203. *((char *)conn->request_info.query_string++) = '\0';
  12204. }
  12205. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12206. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12207. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12208. if (ssl_index >= 0) {
  12209. redirect_to_https_port(conn, ssl_index);
  12210. } else {
  12211. /* A http to https forward port has been specified,
  12212. * but no https port to forward to. */
  12213. mg_send_http_error(conn,
  12214. 503,
  12215. "%s",
  12216. "Error: SSL forward not configured properly");
  12217. mg_cry_internal(conn,
  12218. "%s",
  12219. "Can not redirect to SSL, no SSL port available");
  12220. }
  12221. return;
  12222. }
  12223. uri_len = (int)strlen(ri->local_uri);
  12224. /* 1.3. decode url (if config says so) */
  12225. if (should_decode_url(conn)) {
  12226. mg_url_decode(
  12227. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12228. }
  12229. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12230. * not possible */
  12231. remove_dot_segments((char *)ri->local_uri);
  12232. /* step 1. completed, the url is known now */
  12233. uri_len = (int)strlen(ri->local_uri);
  12234. DEBUG_TRACE("URL: %s", ri->local_uri);
  12235. /* 2. if this ip has limited speed, set it for this connection */
  12236. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12237. get_remote_ip(conn),
  12238. ri->local_uri);
  12239. /* 3. call a "handle everything" callback, if registered */
  12240. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12241. /* Note that since V1.7 the "begin_request" function is called
  12242. * before an authorization check. If an authorization check is
  12243. * required, use a request_handler instead. */
  12244. i = conn->phys_ctx->callbacks.begin_request(conn);
  12245. if (i > 0) {
  12246. /* callback already processed the request. Store the
  12247. return value as a status code for the access log. */
  12248. conn->status_code = i;
  12249. if (!conn->must_close) {
  12250. discard_unread_request_data(conn);
  12251. }
  12252. return;
  12253. } else if (i == 0) {
  12254. /* civetweb should process the request */
  12255. } else {
  12256. /* unspecified - may change with the next version */
  12257. return;
  12258. }
  12259. }
  12260. /* request not yet handled by a handler or redirect, so the request
  12261. * is processed here */
  12262. /* 4. Check for CORS preflight requests and handle them (if configured).
  12263. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12264. */
  12265. if (!strcmp(ri->request_method, "OPTIONS")) {
  12266. /* Send a response to CORS preflights only if
  12267. * access_control_allow_methods is not NULL and not an empty string.
  12268. * In this case, scripts can still handle CORS. */
  12269. const char *cors_meth_cfg =
  12270. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12271. const char *cors_orig_cfg =
  12272. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12273. const char *cors_origin =
  12274. get_header(ri->http_headers, ri->num_headers, "Origin");
  12275. const char *cors_acrm = get_header(ri->http_headers,
  12276. ri->num_headers,
  12277. "Access-Control-Request-Method");
  12278. /* Todo: check if cors_origin is in cors_orig_cfg.
  12279. * Or, let the client check this. */
  12280. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12281. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12282. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12283. /* This is a valid CORS preflight, and the server is configured
  12284. * to
  12285. * handle it automatically. */
  12286. const char *cors_acrh =
  12287. get_header(ri->http_headers,
  12288. ri->num_headers,
  12289. "Access-Control-Request-Headers");
  12290. gmt_time_string(date, sizeof(date), &curtime);
  12291. mg_printf(conn,
  12292. "HTTP/1.1 200 OK\r\n"
  12293. "Date: %s\r\n"
  12294. "Access-Control-Allow-Origin: %s\r\n"
  12295. "Access-Control-Allow-Methods: %s\r\n"
  12296. "Content-Length: 0\r\n"
  12297. "Connection: %s\r\n",
  12298. date,
  12299. cors_orig_cfg,
  12300. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12301. suggest_connection_header(conn));
  12302. if (cors_acrh != NULL) {
  12303. /* CORS request is asking for additional headers */
  12304. const char *cors_hdr_cfg =
  12305. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12306. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12307. /* Allow only if access_control_allow_headers is
  12308. * not NULL and not an empty string. If this
  12309. * configuration is set to *, allow everything.
  12310. * Otherwise this configuration must be a list
  12311. * of allowed HTTP header names. */
  12312. mg_printf(conn,
  12313. "Access-Control-Allow-Headers: %s\r\n",
  12314. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12315. : cors_hdr_cfg));
  12316. }
  12317. }
  12318. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12319. mg_printf(conn, "\r\n");
  12320. return;
  12321. }
  12322. }
  12323. /* 5. interpret the url to find out how the request must be handled
  12324. */
  12325. /* 5.1. first test, if the request targets the regular http(s)://
  12326. * protocol namespace or the websocket ws(s):// protocol namespace.
  12327. */
  12328. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12329. #if defined(USE_WEBSOCKET)
  12330. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12331. #else
  12332. handler_type = REQUEST_HANDLER;
  12333. #endif /* defined(USE_WEBSOCKET) */
  12334. /* 5.2. check if the request will be handled by a callback */
  12335. if (get_request_handler(conn,
  12336. handler_type,
  12337. &callback_handler,
  12338. &subprotocols,
  12339. &ws_connect_handler,
  12340. &ws_ready_handler,
  12341. &ws_data_handler,
  12342. &ws_close_handler,
  12343. NULL,
  12344. &callback_data,
  12345. &handler_info)) {
  12346. /* 5.2.1. A callback will handle this request. All requests
  12347. * handled
  12348. * by a callback have to be considered as requests to a script
  12349. * resource. */
  12350. is_callback_resource = 1;
  12351. is_script_resource = 1;
  12352. is_put_or_delete_request = is_put_or_delete_method(conn);
  12353. } else {
  12354. no_callback_resource:
  12355. /* 5.2.2. No callback is responsible for this request. The URI
  12356. * addresses a file based resource (static content or Lua/cgi
  12357. * scripts in the file system). */
  12358. is_callback_resource = 0;
  12359. interpret_uri(conn,
  12360. path,
  12361. sizeof(path),
  12362. &file.stat,
  12363. &is_found,
  12364. &is_script_resource,
  12365. &is_websocket_request,
  12366. &is_put_or_delete_request);
  12367. }
  12368. /* 6. authorization check */
  12369. /* 6.1. a custom authorization handler is installed */
  12370. if (get_request_handler(conn,
  12371. AUTH_HANDLER,
  12372. NULL,
  12373. NULL,
  12374. NULL,
  12375. NULL,
  12376. NULL,
  12377. NULL,
  12378. &auth_handler,
  12379. &auth_callback_data,
  12380. NULL)) {
  12381. if (!auth_handler(conn, auth_callback_data)) {
  12382. return;
  12383. }
  12384. } else if (is_put_or_delete_request && !is_script_resource
  12385. && !is_callback_resource) {
  12386. /* 6.2. this request is a PUT/DELETE to a real file */
  12387. /* 6.2.1. thus, the server must have real files */
  12388. #if defined(NO_FILES)
  12389. if (1) {
  12390. #else
  12391. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12392. #endif
  12393. /* This server does not have any real files, thus the
  12394. * PUT/DELETE methods are not valid. */
  12395. mg_send_http_error(conn,
  12396. 405,
  12397. "%s method not allowed",
  12398. conn->request_info.request_method);
  12399. return;
  12400. }
  12401. #if !defined(NO_FILES)
  12402. /* 6.2.2. Check if put authorization for static files is
  12403. * available.
  12404. */
  12405. if (!is_authorized_for_put(conn)) {
  12406. send_authorization_request(conn, NULL);
  12407. return;
  12408. }
  12409. #endif
  12410. } else {
  12411. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12412. * or it is a PUT or DELETE request to a resource that does not
  12413. * correspond to a file. Check authorization. */
  12414. if (!check_authorization(conn, path)) {
  12415. send_authorization_request(conn, NULL);
  12416. return;
  12417. }
  12418. }
  12419. /* request is authorized or does not need authorization */
  12420. /* 7. check if there are request handlers for this uri */
  12421. if (is_callback_resource) {
  12422. if (!is_websocket_request) {
  12423. i = callback_handler(conn, callback_data);
  12424. /* Callback handler will not be used anymore. Release it */
  12425. mg_lock_context(conn->phys_ctx);
  12426. handler_info->refcount--;
  12427. mg_unlock_context(conn->phys_ctx);
  12428. if (i > 0) {
  12429. /* Do nothing, callback has served the request. Store
  12430. * then return value as status code for the log and discard
  12431. * all data from the client not used by the callback. */
  12432. conn->status_code = i;
  12433. if (!conn->must_close) {
  12434. discard_unread_request_data(conn);
  12435. }
  12436. } else {
  12437. /* The handler did NOT handle the request. */
  12438. /* Some proper reactions would be:
  12439. * a) close the connections without sending anything
  12440. * b) send a 404 not found
  12441. * c) try if there is a file matching the URI
  12442. * It would be possible to do a, b or c in the callback
  12443. * implementation, and return 1 - we cannot do anything
  12444. * here, that is not possible in the callback.
  12445. *
  12446. * TODO: What would be the best reaction here?
  12447. * (Note: The reaction may change, if there is a better
  12448. *idea.)
  12449. */
  12450. /* For the moment, use option c: We look for a proper file,
  12451. * but since a file request is not always a script resource,
  12452. * the authorization check might be different. */
  12453. interpret_uri(conn,
  12454. path,
  12455. sizeof(path),
  12456. &file.stat,
  12457. &is_found,
  12458. &is_script_resource,
  12459. &is_websocket_request,
  12460. &is_put_or_delete_request);
  12461. callback_handler = NULL;
  12462. /* Here we are at a dead end:
  12463. * According to URI matching, a callback should be
  12464. * responsible for handling the request,
  12465. * we called it, but the callback declared itself
  12466. * not responsible.
  12467. * We use a goto here, to get out of this dead end,
  12468. * and continue with the default handling.
  12469. * A goto here is simpler and better to understand
  12470. * than some curious loop. */
  12471. goto no_callback_resource;
  12472. }
  12473. } else {
  12474. #if defined(USE_WEBSOCKET)
  12475. handle_websocket_request(conn,
  12476. path,
  12477. is_callback_resource,
  12478. subprotocols,
  12479. ws_connect_handler,
  12480. ws_ready_handler,
  12481. ws_data_handler,
  12482. ws_close_handler,
  12483. callback_data);
  12484. #endif
  12485. }
  12486. return;
  12487. }
  12488. /* 8. handle websocket requests */
  12489. #if defined(USE_WEBSOCKET)
  12490. if (is_websocket_request) {
  12491. if (is_script_resource) {
  12492. if (is_in_script_path(conn, path)) {
  12493. /* Websocket Lua script */
  12494. handle_websocket_request(conn,
  12495. path,
  12496. 0 /* Lua Script */,
  12497. NULL,
  12498. NULL,
  12499. NULL,
  12500. NULL,
  12501. NULL,
  12502. conn->phys_ctx->user_data);
  12503. } else {
  12504. /* Script was in an illegal path */
  12505. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12506. }
  12507. } else {
  12508. #if defined(MG_LEGACY_INTERFACE)
  12509. handle_websocket_request(
  12510. conn,
  12511. path,
  12512. !is_script_resource /* could be deprecated global callback
  12513. */
  12514. ,
  12515. NULL,
  12516. deprecated_websocket_connect_wrapper,
  12517. deprecated_websocket_ready_wrapper,
  12518. deprecated_websocket_data_wrapper,
  12519. NULL,
  12520. conn->phys_ctx->callbacks);
  12521. #else
  12522. mg_send_http_error(conn, 404, "%s", "Not found");
  12523. #endif
  12524. }
  12525. return;
  12526. } else
  12527. #endif
  12528. #if defined(NO_FILES)
  12529. /* 9a. In case the server uses only callbacks, this uri is
  12530. * unknown.
  12531. * Then, all request handling ends here. */
  12532. mg_send_http_error(conn, 404, "%s", "Not Found");
  12533. #else
  12534. /* 9b. This request is either for a static file or resource handled
  12535. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12536. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12537. mg_send_http_error(conn, 404, "%s", "Not Found");
  12538. return;
  12539. }
  12540. /* 10. Request is handled by a script */
  12541. if (is_script_resource) {
  12542. handle_file_based_request(conn, path, &file);
  12543. return;
  12544. }
  12545. /* 11. Handle put/delete/mkcol requests */
  12546. if (is_put_or_delete_request) {
  12547. /* 11.1. PUT method */
  12548. if (!strcmp(ri->request_method, "PUT")) {
  12549. put_file(conn, path);
  12550. return;
  12551. }
  12552. /* 11.2. DELETE method */
  12553. if (!strcmp(ri->request_method, "DELETE")) {
  12554. delete_file(conn, path);
  12555. return;
  12556. }
  12557. /* 11.3. MKCOL method */
  12558. if (!strcmp(ri->request_method, "MKCOL")) {
  12559. mkcol(conn, path);
  12560. return;
  12561. }
  12562. /* 11.4. PATCH method
  12563. * This method is not supported for static resources,
  12564. * only for scripts (Lua, CGI) and callbacks. */
  12565. mg_send_http_error(conn,
  12566. 405,
  12567. "%s method not allowed",
  12568. conn->request_info.request_method);
  12569. return;
  12570. }
  12571. /* 11. File does not exist, or it was configured that it should be
  12572. * hidden */
  12573. if (!is_found || (must_hide_file(conn, path))) {
  12574. mg_send_http_error(conn, 404, "%s", "Not found");
  12575. return;
  12576. }
  12577. /* 12. Directory uris should end with a slash */
  12578. if (file.stat.is_directory && (uri_len > 0)
  12579. && (ri->local_uri[uri_len - 1] != '/')) {
  12580. gmt_time_string(date, sizeof(date), &curtime);
  12581. mg_printf(conn,
  12582. "HTTP/1.1 301 Moved Permanently\r\n"
  12583. "Location: %s/\r\n"
  12584. "Date: %s\r\n"
  12585. /* "Cache-Control: private\r\n" (= default) */
  12586. "Content-Length: 0\r\n"
  12587. "Connection: %s\r\n",
  12588. ri->request_uri,
  12589. date,
  12590. suggest_connection_header(conn));
  12591. send_additional_header(conn);
  12592. mg_printf(conn, "\r\n");
  12593. return;
  12594. }
  12595. /* 13. Handle other methods than GET/HEAD */
  12596. /* 13.1. Handle PROPFIND */
  12597. if (!strcmp(ri->request_method, "PROPFIND")) {
  12598. handle_propfind(conn, path, &file.stat);
  12599. return;
  12600. }
  12601. /* 13.2. Handle OPTIONS for files */
  12602. if (!strcmp(ri->request_method, "OPTIONS")) {
  12603. /* This standard handler is only used for real files.
  12604. * Scripts should support the OPTIONS method themselves, to allow a
  12605. * maximum flexibility.
  12606. * Lua and CGI scripts may fully support CORS this way (including
  12607. * preflights). */
  12608. send_options(conn);
  12609. return;
  12610. }
  12611. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12612. if ((0 != strcmp(ri->request_method, "GET"))
  12613. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12614. mg_send_http_error(conn,
  12615. 405,
  12616. "%s method not allowed",
  12617. conn->request_info.request_method);
  12618. return;
  12619. }
  12620. /* 14. directories */
  12621. if (file.stat.is_directory) {
  12622. /* Substitute files have already been handled above. */
  12623. /* Here we can either generate and send a directory listing,
  12624. * or send an "access denied" error. */
  12625. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12626. "yes")) {
  12627. handle_directory_request(conn, path);
  12628. } else {
  12629. mg_send_http_error(conn,
  12630. 403,
  12631. "%s",
  12632. "Error: Directory listing denied");
  12633. }
  12634. return;
  12635. }
  12636. /* 15. read a normal file with GET or HEAD */
  12637. handle_file_based_request(conn, path, &file);
  12638. #endif /* !defined(NO_FILES) */
  12639. }
  12640. /* Include HTTP/2 modules */
  12641. #ifdef USE_HTTP2
  12642. #if defined(NO_SSL)
  12643. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  12644. #endif
  12645. #include "mod_http2.inl"
  12646. #endif
  12647. #if !defined(NO_FILESYSTEMS)
  12648. static void
  12649. handle_file_based_request(struct mg_connection *conn,
  12650. const char *path,
  12651. struct mg_file *file)
  12652. {
  12653. if (!conn || !conn->dom_ctx) {
  12654. return;
  12655. }
  12656. if (0) {
  12657. #if defined(USE_LUA)
  12658. } else if (match_prefix(
  12659. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12660. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12661. path)
  12662. > 0) {
  12663. if (is_in_script_path(conn, path)) {
  12664. /* Lua server page: an SSI like page containing mostly plain
  12665. * html
  12666. * code
  12667. * plus some tags with server generated contents. */
  12668. handle_lsp_request(conn, path, file, NULL);
  12669. } else {
  12670. /* Script was in an illegal path */
  12671. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12672. }
  12673. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12674. strlen(
  12675. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12676. path)
  12677. > 0) {
  12678. if (is_in_script_path(conn, path)) {
  12679. /* Lua in-server module script: a CGI like script used to
  12680. * generate
  12681. * the
  12682. * entire reply. */
  12683. mg_exec_lua_script(conn, path, NULL);
  12684. } else {
  12685. /* Script was in an illegal path */
  12686. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12687. }
  12688. #endif
  12689. #if defined(USE_DUKTAPE)
  12690. } else if (match_prefix(
  12691. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12692. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12693. path)
  12694. > 0) {
  12695. if (is_in_script_path(conn, path)) {
  12696. /* Call duktape to generate the page */
  12697. mg_exec_duktape_script(conn, path);
  12698. } else {
  12699. /* Script was in an illegal path */
  12700. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12701. }
  12702. #endif
  12703. #if !defined(NO_CGI)
  12704. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12705. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12706. path)
  12707. > 0) {
  12708. if (is_in_script_path(conn, path)) {
  12709. /* CGI scripts may support all HTTP methods */
  12710. handle_cgi_request(conn, path);
  12711. } else {
  12712. /* Script was in an illegal path */
  12713. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12714. }
  12715. #endif /* !NO_CGI */
  12716. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12717. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12718. path)
  12719. > 0) {
  12720. if (is_in_script_path(conn, path)) {
  12721. handle_ssi_file_request(conn, path, file);
  12722. } else {
  12723. /* Script was in an illegal path */
  12724. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12725. }
  12726. #if !defined(NO_CACHING)
  12727. } else if ((!conn->in_error_handler)
  12728. && is_not_modified(conn, &file->stat)) {
  12729. /* Send 304 "Not Modified" - this must not send any body data */
  12730. handle_not_modified_static_file_request(conn, file);
  12731. #endif /* !NO_CACHING */
  12732. } else {
  12733. handle_static_file_request(conn, path, file, NULL, NULL);
  12734. }
  12735. }
  12736. #endif /* NO_FILESYSTEMS */
  12737. static void
  12738. close_all_listening_sockets(struct mg_context *ctx)
  12739. {
  12740. unsigned int i;
  12741. if (!ctx) {
  12742. return;
  12743. }
  12744. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12745. closesocket(ctx->listening_sockets[i].sock);
  12746. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12747. }
  12748. mg_free(ctx->listening_sockets);
  12749. ctx->listening_sockets = NULL;
  12750. mg_free(ctx->listening_socket_fds);
  12751. ctx->listening_socket_fds = NULL;
  12752. }
  12753. /* Valid listening port specification is: [ip_address:]port[s]
  12754. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12755. * Examples for IPv6: [::]:80, [::1]:80,
  12756. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12757. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12758. * In order to bind to both, IPv4 and IPv6, you can either add
  12759. * both ports using 8080,[::]:8080, or the short form +8080.
  12760. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12761. * one only accepting IPv4 the other only IPv6. +8080 creates
  12762. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12763. * environment, they might work differently, or might not work
  12764. * at all - it must be tested what options work best in the
  12765. * relevant network environment.
  12766. */
  12767. static int
  12768. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12769. {
  12770. unsigned int a, b, c, d;
  12771. unsigned port;
  12772. unsigned long portUL;
  12773. int ch, len;
  12774. const char *cb;
  12775. char *endptr;
  12776. #if defined(USE_IPV6)
  12777. char buf[100] = {0};
  12778. #endif
  12779. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12780. * Also, all-zeroes in the socket address means binding to all addresses
  12781. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12782. memset(so, 0, sizeof(*so));
  12783. so->lsa.sin.sin_family = AF_INET;
  12784. *ip_version = 0;
  12785. /* Initialize port and len as invalid. */
  12786. port = 0;
  12787. len = 0;
  12788. /* Test for different ways to format this string */
  12789. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12790. == 5) {
  12791. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12792. so->lsa.sin.sin_addr.s_addr =
  12793. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12794. so->lsa.sin.sin_port = htons((uint16_t)port);
  12795. *ip_version = 4;
  12796. #if defined(USE_IPV6)
  12797. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12798. && mg_inet_pton(
  12799. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12800. /* IPv6 address, examples: see above */
  12801. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12802. */
  12803. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12804. *ip_version = 6;
  12805. #endif
  12806. } else if ((vec->ptr[0] == '+')
  12807. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12808. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12809. /* Add 1 to len for the + character we skipped before */
  12810. len++;
  12811. #if defined(USE_IPV6)
  12812. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12813. so->lsa.sin6.sin6_family = AF_INET6;
  12814. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12815. *ip_version = 4 + 6;
  12816. #else
  12817. /* Bind to IPv4 only, since IPv6 is not built in. */
  12818. so->lsa.sin.sin_port = htons((uint16_t)port);
  12819. *ip_version = 4;
  12820. #endif
  12821. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12822. && (vec->ptr != endptr)) {
  12823. len = (int)(endptr - vec->ptr);
  12824. port = (uint16_t)portUL;
  12825. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12826. so->lsa.sin.sin_port = htons((uint16_t)port);
  12827. *ip_version = 4;
  12828. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12829. /* String could be a hostname. This check algotithm
  12830. * will only work for RFC 952 compliant hostnames,
  12831. * starting with a letter, containing only letters,
  12832. * digits and hyphen ('-'). Newer specs may allow
  12833. * more, but this is not guaranteed here, since it
  12834. * may interfere with rules for port option lists. */
  12835. /* According to RFC 1035, hostnames are restricted to 255 characters
  12836. * in total (63 between two dots). */
  12837. char hostname[256];
  12838. size_t hostnlen = (size_t)(cb - vec->ptr);
  12839. if (hostnlen >= sizeof(hostname)) {
  12840. /* This would be invalid in any case */
  12841. *ip_version = 0;
  12842. return 0;
  12843. }
  12844. memcpy(hostname, vec->ptr, hostnlen);
  12845. hostname[hostnlen] = 0;
  12846. if (mg_inet_pton(
  12847. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12848. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12849. *ip_version = 4;
  12850. so->lsa.sin.sin_family = AF_INET;
  12851. so->lsa.sin.sin_port = htons((uint16_t)port);
  12852. len += (int)(hostnlen + 1);
  12853. } else {
  12854. port = 0;
  12855. len = 0;
  12856. }
  12857. #if defined(USE_IPV6)
  12858. } else if (mg_inet_pton(AF_INET6,
  12859. hostname,
  12860. &so->lsa.sin6,
  12861. sizeof(so->lsa.sin6))) {
  12862. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12863. *ip_version = 6;
  12864. so->lsa.sin6.sin6_family = AF_INET6;
  12865. so->lsa.sin.sin_port = htons((uint16_t)port);
  12866. len += (int)(hostnlen + 1);
  12867. } else {
  12868. port = 0;
  12869. len = 0;
  12870. }
  12871. #endif
  12872. }
  12873. } else {
  12874. /* Parsing failure. */
  12875. }
  12876. /* sscanf and the option splitting code ensure the following condition
  12877. */
  12878. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12879. *ip_version = 0;
  12880. return 0;
  12881. }
  12882. ch = vec->ptr[len]; /* Next character after the port number */
  12883. so->is_ssl = (ch == 's');
  12884. so->ssl_redir = (ch == 'r');
  12885. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12886. if (is_valid_port(port)
  12887. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12888. return 1;
  12889. }
  12890. /* Reset ip_version to 0 if there is an error */
  12891. *ip_version = 0;
  12892. return 0;
  12893. }
  12894. /* Is there any SSL port in use? */
  12895. static int
  12896. is_ssl_port_used(const char *ports)
  12897. {
  12898. if (ports) {
  12899. /* There are several different allowed syntax variants:
  12900. * - "80" for a single port using every network interface
  12901. * - "localhost:80" for a single port using only localhost
  12902. * - "80,localhost:8080" for two ports, one bound to localhost
  12903. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12904. * to IPv4 localhost, one to IPv6 localhost
  12905. * - "+80" use port 80 for IPv4 and IPv6
  12906. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12907. * for both: IPv4 and IPv4
  12908. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12909. * additionally port 8080 bound to localhost connections
  12910. *
  12911. * If we just look for 's' anywhere in the string, "localhost:80"
  12912. * will be detected as SSL (false positive).
  12913. * Looking for 's' after a digit may cause false positives in
  12914. * "my24service:8080".
  12915. * Looking from 's' backward if there are only ':' and numbers
  12916. * before will not work for "24service:8080" (non SSL, port 8080)
  12917. * or "24s" (SSL, port 24).
  12918. *
  12919. * Remark: Initially hostnames were not allowed to start with a
  12920. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12921. * Section 2.1).
  12922. *
  12923. * To get this correct, the entire string must be parsed as a whole,
  12924. * reading it as a list element for element and parsing with an
  12925. * algorithm equivalent to parse_port_string.
  12926. *
  12927. * In fact, we use local interface names here, not arbitrary
  12928. * hostnames, so in most cases the only name will be "localhost".
  12929. *
  12930. * So, for now, we use this simple algorithm, that may still return
  12931. * a false positive in bizarre cases.
  12932. */
  12933. int i;
  12934. int portslen = (int)strlen(ports);
  12935. char prevIsNumber = 0;
  12936. for (i = 0; i < portslen; i++) {
  12937. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12938. return 1;
  12939. }
  12940. if (ports[i] >= '0' && ports[i] <= '9') {
  12941. prevIsNumber = 1;
  12942. } else {
  12943. prevIsNumber = 0;
  12944. }
  12945. }
  12946. }
  12947. return 0;
  12948. }
  12949. static int
  12950. set_ports_option(struct mg_context *phys_ctx)
  12951. {
  12952. const char *list;
  12953. int on = 1;
  12954. #if defined(USE_IPV6)
  12955. int off = 0;
  12956. #endif
  12957. struct vec vec;
  12958. struct socket so, *ptr;
  12959. struct mg_pollfd *pfd;
  12960. union usa usa;
  12961. socklen_t len;
  12962. int ip_version;
  12963. int portsTotal = 0;
  12964. int portsOk = 0;
  12965. const char *opt_txt;
  12966. long opt_listen_backlog;
  12967. if (!phys_ctx) {
  12968. return 0;
  12969. }
  12970. memset(&so, 0, sizeof(so));
  12971. memset(&usa, 0, sizeof(usa));
  12972. len = sizeof(usa);
  12973. list = phys_ctx->dd.config[LISTENING_PORTS];
  12974. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12975. portsTotal++;
  12976. if (!parse_port_string(&vec, &so, &ip_version)) {
  12977. mg_cry_ctx_internal(
  12978. phys_ctx,
  12979. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12980. (int)vec.len,
  12981. vec.ptr,
  12982. portsTotal,
  12983. "[IP_ADDRESS:]PORT[s|r]");
  12984. continue;
  12985. }
  12986. #if !defined(NO_SSL)
  12987. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12988. mg_cry_ctx_internal(phys_ctx,
  12989. "Cannot add SSL socket (entry %i)",
  12990. portsTotal);
  12991. continue;
  12992. }
  12993. #endif
  12994. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12995. == INVALID_SOCKET) {
  12996. mg_cry_ctx_internal(phys_ctx,
  12997. "cannot create socket (entry %i)",
  12998. portsTotal);
  12999. continue;
  13000. }
  13001. #if defined(_WIN32)
  13002. /* Windows SO_REUSEADDR lets many procs binds to a
  13003. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13004. * if someone already has the socket -- DTL */
  13005. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13006. * Windows might need a few seconds before
  13007. * the same port can be used again in the
  13008. * same process, so a short Sleep may be
  13009. * required between mg_stop and mg_start.
  13010. */
  13011. if (setsockopt(so.sock,
  13012. SOL_SOCKET,
  13013. SO_EXCLUSIVEADDRUSE,
  13014. (SOCK_OPT_TYPE)&on,
  13015. sizeof(on))
  13016. != 0) {
  13017. /* Set reuse option, but don't abort on errors. */
  13018. mg_cry_ctx_internal(
  13019. phys_ctx,
  13020. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13021. portsTotal);
  13022. }
  13023. #else
  13024. if (setsockopt(so.sock,
  13025. SOL_SOCKET,
  13026. SO_REUSEADDR,
  13027. (SOCK_OPT_TYPE)&on,
  13028. sizeof(on))
  13029. != 0) {
  13030. /* Set reuse option, but don't abort on errors. */
  13031. mg_cry_ctx_internal(
  13032. phys_ctx,
  13033. "cannot set socket option SO_REUSEADDR (entry %i)",
  13034. portsTotal);
  13035. }
  13036. #endif
  13037. if (ip_version > 4) {
  13038. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13039. #if defined(USE_IPV6)
  13040. if (ip_version > 6) {
  13041. if (so.lsa.sa.sa_family == AF_INET6
  13042. && setsockopt(so.sock,
  13043. IPPROTO_IPV6,
  13044. IPV6_V6ONLY,
  13045. (void *)&off,
  13046. sizeof(off))
  13047. != 0) {
  13048. /* Set IPv6 only option, but don't abort on errors. */
  13049. mg_cry_ctx_internal(phys_ctx,
  13050. "cannot set socket option "
  13051. "IPV6_V6ONLY=off (entry %i)",
  13052. portsTotal);
  13053. }
  13054. } else {
  13055. if (so.lsa.sa.sa_family == AF_INET6
  13056. && setsockopt(so.sock,
  13057. IPPROTO_IPV6,
  13058. IPV6_V6ONLY,
  13059. (void *)&on,
  13060. sizeof(on))
  13061. != 0) {
  13062. /* Set IPv6 only option, but don't abort on errors. */
  13063. mg_cry_ctx_internal(phys_ctx,
  13064. "cannot set socket option "
  13065. "IPV6_V6ONLY=on (entry %i)",
  13066. portsTotal);
  13067. }
  13068. }
  13069. #else
  13070. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13071. closesocket(so.sock);
  13072. so.sock = INVALID_SOCKET;
  13073. continue;
  13074. #endif
  13075. }
  13076. if (so.lsa.sa.sa_family == AF_INET) {
  13077. len = sizeof(so.lsa.sin);
  13078. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13079. mg_cry_ctx_internal(phys_ctx,
  13080. "cannot bind to %.*s: %d (%s)",
  13081. (int)vec.len,
  13082. vec.ptr,
  13083. (int)ERRNO,
  13084. strerror(errno));
  13085. closesocket(so.sock);
  13086. so.sock = INVALID_SOCKET;
  13087. continue;
  13088. }
  13089. }
  13090. #if defined(USE_IPV6)
  13091. else if (so.lsa.sa.sa_family == AF_INET6) {
  13092. len = sizeof(so.lsa.sin6);
  13093. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13094. mg_cry_ctx_internal(phys_ctx,
  13095. "cannot bind to IPv6 %.*s: %d (%s)",
  13096. (int)vec.len,
  13097. vec.ptr,
  13098. (int)ERRNO,
  13099. strerror(errno));
  13100. closesocket(so.sock);
  13101. so.sock = INVALID_SOCKET;
  13102. continue;
  13103. }
  13104. }
  13105. #endif
  13106. else {
  13107. mg_cry_ctx_internal(
  13108. phys_ctx,
  13109. "cannot bind: address family not supported (entry %i)",
  13110. portsTotal);
  13111. closesocket(so.sock);
  13112. so.sock = INVALID_SOCKET;
  13113. continue;
  13114. }
  13115. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13116. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13117. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13118. mg_cry_ctx_internal(phys_ctx,
  13119. "%s value \"%s\" is invalid",
  13120. config_options[LISTEN_BACKLOG_SIZE].name,
  13121. opt_txt);
  13122. closesocket(so.sock);
  13123. so.sock = INVALID_SOCKET;
  13124. continue;
  13125. }
  13126. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13127. mg_cry_ctx_internal(phys_ctx,
  13128. "cannot listen to %.*s: %d (%s)",
  13129. (int)vec.len,
  13130. vec.ptr,
  13131. (int)ERRNO,
  13132. strerror(errno));
  13133. closesocket(so.sock);
  13134. so.sock = INVALID_SOCKET;
  13135. continue;
  13136. }
  13137. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13138. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13139. int err = (int)ERRNO;
  13140. mg_cry_ctx_internal(phys_ctx,
  13141. "call to getsockname failed %.*s: %d (%s)",
  13142. (int)vec.len,
  13143. vec.ptr,
  13144. err,
  13145. strerror(errno));
  13146. closesocket(so.sock);
  13147. so.sock = INVALID_SOCKET;
  13148. continue;
  13149. }
  13150. /* Update lsa port in case of random free ports */
  13151. #if defined(USE_IPV6)
  13152. if (so.lsa.sa.sa_family == AF_INET6) {
  13153. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13154. } else
  13155. #endif
  13156. {
  13157. so.lsa.sin.sin_port = usa.sin.sin_port;
  13158. }
  13159. if ((ptr = (struct socket *)
  13160. mg_realloc_ctx(phys_ctx->listening_sockets,
  13161. (phys_ctx->num_listening_sockets + 1)
  13162. * sizeof(phys_ctx->listening_sockets[0]),
  13163. phys_ctx))
  13164. == NULL) {
  13165. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13166. closesocket(so.sock);
  13167. so.sock = INVALID_SOCKET;
  13168. continue;
  13169. }
  13170. if ((pfd = (struct mg_pollfd *)
  13171. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13172. (phys_ctx->num_listening_sockets + 1)
  13173. * sizeof(phys_ctx->listening_socket_fds[0]),
  13174. phys_ctx))
  13175. == NULL) {
  13176. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13177. closesocket(so.sock);
  13178. so.sock = INVALID_SOCKET;
  13179. mg_free(ptr);
  13180. continue;
  13181. }
  13182. set_close_on_exec(so.sock, NULL, phys_ctx);
  13183. phys_ctx->listening_sockets = ptr;
  13184. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13185. phys_ctx->listening_socket_fds = pfd;
  13186. phys_ctx->num_listening_sockets++;
  13187. portsOk++;
  13188. }
  13189. if (portsOk != portsTotal) {
  13190. close_all_listening_sockets(phys_ctx);
  13191. portsOk = 0;
  13192. }
  13193. return portsOk;
  13194. }
  13195. static const char *
  13196. header_val(const struct mg_connection *conn, const char *header)
  13197. {
  13198. const char *header_value;
  13199. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13200. return "-";
  13201. } else {
  13202. return header_value;
  13203. }
  13204. }
  13205. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13206. static void log_access(const struct mg_connection *conn);
  13207. #include "external_log_access.inl"
  13208. #elif !defined(NO_FILESYSTEMS)
  13209. static void
  13210. log_access(const struct mg_connection *conn)
  13211. {
  13212. const struct mg_request_info *ri;
  13213. struct mg_file fi;
  13214. char date[64], src_addr[IP_ADDR_STR_LEN];
  13215. struct tm *tm;
  13216. const char *referer;
  13217. const char *user_agent;
  13218. char buf[4096];
  13219. if (!conn || !conn->dom_ctx) {
  13220. return;
  13221. }
  13222. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13223. if (mg_fopen(conn,
  13224. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13225. MG_FOPEN_MODE_APPEND,
  13226. &fi)
  13227. == 0) {
  13228. fi.access.fp = NULL;
  13229. }
  13230. } else {
  13231. fi.access.fp = NULL;
  13232. }
  13233. /* Log is written to a file and/or a callback. If both are not set,
  13234. * executing the rest of the function is pointless. */
  13235. if ((fi.access.fp == NULL)
  13236. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13237. return;
  13238. }
  13239. tm = localtime(&conn->conn_birth_time);
  13240. if (tm != NULL) {
  13241. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13242. } else {
  13243. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13244. date[sizeof(date) - 1] = '\0';
  13245. }
  13246. ri = &conn->request_info;
  13247. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13248. referer = header_val(conn, "Referer");
  13249. user_agent = header_val(conn, "User-Agent");
  13250. mg_snprintf(conn,
  13251. NULL, /* Ignore truncation in access log */
  13252. buf,
  13253. sizeof(buf),
  13254. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13255. src_addr,
  13256. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13257. date,
  13258. ri->request_method ? ri->request_method : "-",
  13259. ri->request_uri ? ri->request_uri : "-",
  13260. ri->query_string ? "?" : "",
  13261. ri->query_string ? ri->query_string : "",
  13262. ri->http_version,
  13263. conn->status_code,
  13264. conn->num_bytes_sent,
  13265. referer,
  13266. user_agent);
  13267. if (conn->phys_ctx->callbacks.log_access) {
  13268. conn->phys_ctx->callbacks.log_access(conn, buf);
  13269. }
  13270. if (fi.access.fp) {
  13271. int ok = 1;
  13272. flockfile(fi.access.fp);
  13273. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13274. ok = 0;
  13275. }
  13276. if (fflush(fi.access.fp) != 0) {
  13277. ok = 0;
  13278. }
  13279. funlockfile(fi.access.fp);
  13280. if (mg_fclose(&fi.access) != 0) {
  13281. ok = 0;
  13282. }
  13283. if (!ok) {
  13284. mg_cry_internal(conn,
  13285. "Error writing log file %s",
  13286. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13287. }
  13288. }
  13289. }
  13290. #else
  13291. #error Must either enable filesystems or provide a custom log_access implementation
  13292. #endif /* Externally provided function */
  13293. /* Verify given socket address against the ACL.
  13294. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13295. */
  13296. static int
  13297. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13298. {
  13299. int allowed, flag;
  13300. uint32_t net, mask;
  13301. struct vec vec;
  13302. if (phys_ctx) {
  13303. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13304. /* If any ACL is set, deny by default */
  13305. allowed = (list == NULL) ? '+' : '-';
  13306. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13307. flag = vec.ptr[0];
  13308. if ((flag != '+' && flag != '-')
  13309. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13310. mg_cry_ctx_internal(phys_ctx,
  13311. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13312. __func__);
  13313. return -1;
  13314. }
  13315. if (net == (remote_ip & mask)) {
  13316. allowed = flag;
  13317. }
  13318. }
  13319. return allowed == '+';
  13320. }
  13321. return -1;
  13322. }
  13323. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13324. static int
  13325. set_uid_option(struct mg_context *phys_ctx)
  13326. {
  13327. int success = 0;
  13328. if (phys_ctx) {
  13329. /* We are currently running as curr_uid. */
  13330. const uid_t curr_uid = getuid();
  13331. /* If set, we want to run as run_as_user. */
  13332. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13333. const struct passwd *to_pw = NULL;
  13334. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13335. /* run_as_user does not exist on the system. We can't proceed
  13336. * further. */
  13337. mg_cry_ctx_internal(phys_ctx,
  13338. "%s: unknown user [%s]",
  13339. __func__,
  13340. run_as_user);
  13341. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13342. /* There was either no request to change user, or we're already
  13343. * running as run_as_user. Nothing else to do.
  13344. */
  13345. success = 1;
  13346. } else {
  13347. /* Valid change request. */
  13348. if (setgid(to_pw->pw_gid) == -1) {
  13349. mg_cry_ctx_internal(phys_ctx,
  13350. "%s: setgid(%s): %s",
  13351. __func__,
  13352. run_as_user,
  13353. strerror(errno));
  13354. } else if (setgroups(0, NULL) == -1) {
  13355. mg_cry_ctx_internal(phys_ctx,
  13356. "%s: setgroups(): %s",
  13357. __func__,
  13358. strerror(errno));
  13359. } else if (setuid(to_pw->pw_uid) == -1) {
  13360. mg_cry_ctx_internal(phys_ctx,
  13361. "%s: setuid(%s): %s",
  13362. __func__,
  13363. run_as_user,
  13364. strerror(errno));
  13365. } else {
  13366. success = 1;
  13367. }
  13368. }
  13369. }
  13370. return success;
  13371. }
  13372. #endif /* !_WIN32 */
  13373. static void
  13374. tls_dtor(void *key)
  13375. {
  13376. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13377. /* key == pthread_getspecific(sTlsKey); */
  13378. if (tls) {
  13379. if (tls->is_master == 2) {
  13380. tls->is_master = -3; /* Mark memory as dead */
  13381. mg_free(tls);
  13382. }
  13383. }
  13384. pthread_setspecific(sTlsKey, NULL);
  13385. }
  13386. #if !defined(NO_SSL)
  13387. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13388. struct mg_domain_context *dom_ctx,
  13389. const char *pem,
  13390. const char *chain);
  13391. static const char *ssl_error(void);
  13392. static int
  13393. refresh_trust(struct mg_connection *conn)
  13394. {
  13395. struct stat cert_buf;
  13396. int64_t t = 0;
  13397. const char *pem;
  13398. const char *chain;
  13399. int should_verify_peer;
  13400. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13401. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13402. * refresh_trust still can not work. */
  13403. return 0;
  13404. }
  13405. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13406. if (chain == NULL) {
  13407. /* pem is not NULL here */
  13408. chain = pem;
  13409. }
  13410. if (*chain == 0) {
  13411. chain = NULL;
  13412. }
  13413. if (stat(pem, &cert_buf) != -1) {
  13414. t = (int64_t)cert_buf.st_mtime;
  13415. }
  13416. mg_lock_context(conn->phys_ctx);
  13417. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13418. conn->dom_ctx->ssl_cert_last_mtime = t;
  13419. should_verify_peer = 0;
  13420. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13421. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13422. == 0) {
  13423. should_verify_peer = 1;
  13424. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13425. "optional")
  13426. == 0) {
  13427. should_verify_peer = 1;
  13428. }
  13429. }
  13430. if (should_verify_peer) {
  13431. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13432. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13433. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13434. ca_file,
  13435. ca_path)
  13436. != 1) {
  13437. mg_unlock_context(conn->phys_ctx);
  13438. mg_cry_ctx_internal(
  13439. conn->phys_ctx,
  13440. "SSL_CTX_load_verify_locations error: %s "
  13441. "ssl_verify_peer requires setting "
  13442. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13443. "present in "
  13444. "the .conf file?",
  13445. ssl_error());
  13446. return 0;
  13447. }
  13448. }
  13449. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13450. == 0) {
  13451. mg_unlock_context(conn->phys_ctx);
  13452. return 0;
  13453. }
  13454. }
  13455. mg_unlock_context(conn->phys_ctx);
  13456. return 1;
  13457. }
  13458. #if defined(OPENSSL_API_1_1)
  13459. #else
  13460. static pthread_mutex_t *ssl_mutexes;
  13461. #endif /* OPENSSL_API_1_1 */
  13462. static int
  13463. sslize(struct mg_connection *conn,
  13464. int (*func)(SSL *),
  13465. const struct mg_client_options *client_options)
  13466. {
  13467. int ret, err;
  13468. int short_trust;
  13469. unsigned timeout = 1024;
  13470. unsigned i;
  13471. if (!conn) {
  13472. return 0;
  13473. }
  13474. short_trust =
  13475. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13476. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13477. if (short_trust) {
  13478. int trust_ret = refresh_trust(conn);
  13479. if (!trust_ret) {
  13480. return trust_ret;
  13481. }
  13482. }
  13483. mg_lock_context(conn->phys_ctx);
  13484. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13485. mg_unlock_context(conn->phys_ctx);
  13486. if (conn->ssl == NULL) {
  13487. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13488. OPENSSL_REMOVE_THREAD_STATE();
  13489. return 0;
  13490. }
  13491. SSL_set_app_data(conn->ssl, (char *)conn);
  13492. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13493. if (ret != 1) {
  13494. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13495. SSL_free(conn->ssl);
  13496. conn->ssl = NULL;
  13497. OPENSSL_REMOVE_THREAD_STATE();
  13498. return 0;
  13499. }
  13500. if (client_options) {
  13501. if (client_options->host_name) {
  13502. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13503. }
  13504. }
  13505. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13506. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13507. /* NOTE: The loop below acts as a back-off, so we can end
  13508. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13509. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13510. if (to >= 0) {
  13511. timeout = (unsigned)to;
  13512. }
  13513. }
  13514. /* SSL functions may fail and require to be called again:
  13515. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13516. * Here "func" could be SSL_connect or SSL_accept. */
  13517. for (i = 0; i <= timeout; i += 50) {
  13518. ERR_clear_error();
  13519. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13520. ret = func(conn->ssl);
  13521. if (ret != 1) {
  13522. err = SSL_get_error(conn->ssl, ret);
  13523. if ((err == SSL_ERROR_WANT_CONNECT)
  13524. || (err == SSL_ERROR_WANT_ACCEPT)
  13525. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13526. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13527. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13528. /* Don't wait if the server is going to be stopped. */
  13529. break;
  13530. }
  13531. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13532. /* Simply retry the function call. */
  13533. mg_sleep(50);
  13534. } else {
  13535. /* Need to retry the function call "later".
  13536. * See https://linux.die.net/man/3/ssl_get_error
  13537. * This is typical for non-blocking sockets. */
  13538. struct mg_pollfd pfd;
  13539. int pollres;
  13540. pfd.fd = conn->client.sock;
  13541. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13542. || (err == SSL_ERROR_WANT_WRITE))
  13543. ? POLLOUT
  13544. : POLLIN;
  13545. pollres = mg_poll(&pfd, 1, 50,
  13546. &(conn->phys_ctx->stop_flag));
  13547. if (pollres < 0) {
  13548. /* Break if error occured (-1)
  13549. * or server shutdown (-2) */
  13550. break;
  13551. }
  13552. }
  13553. } else if (err == SSL_ERROR_SYSCALL) {
  13554. /* This is an IO error. Look at errno. */
  13555. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13556. break;
  13557. } else {
  13558. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13559. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13560. break;
  13561. }
  13562. } else {
  13563. /* success */
  13564. break;
  13565. }
  13566. }
  13567. ERR_clear_error();
  13568. if (ret != 1) {
  13569. SSL_free(conn->ssl);
  13570. conn->ssl = NULL;
  13571. OPENSSL_REMOVE_THREAD_STATE();
  13572. return 0;
  13573. }
  13574. return 1;
  13575. }
  13576. /* Return OpenSSL error message (from CRYPTO lib) */
  13577. static const char *
  13578. ssl_error(void)
  13579. {
  13580. unsigned long err;
  13581. err = ERR_get_error();
  13582. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13583. }
  13584. static int
  13585. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13586. {
  13587. int i;
  13588. const char hexdigit[] = "0123456789abcdef";
  13589. if ((memlen <= 0) || (buflen <= 0)) {
  13590. return 0;
  13591. }
  13592. if (buflen < (3 * memlen)) {
  13593. return 0;
  13594. }
  13595. for (i = 0; i < memlen; i++) {
  13596. if (i > 0) {
  13597. buf[3 * i - 1] = ' ';
  13598. }
  13599. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13600. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13601. }
  13602. buf[3 * memlen - 1] = 0;
  13603. return 1;
  13604. }
  13605. static int
  13606. ssl_get_client_cert_info(const struct mg_connection *conn,
  13607. struct mg_client_cert *client_cert)
  13608. {
  13609. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13610. if (cert) {
  13611. char str_buf[1024];
  13612. unsigned char buf[256];
  13613. char *str_serial = NULL;
  13614. unsigned int ulen;
  13615. int ilen;
  13616. unsigned char *tmp_buf;
  13617. unsigned char *tmp_p;
  13618. /* Handle to algorithm used for fingerprint */
  13619. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13620. /* Get Subject and issuer */
  13621. X509_NAME *subj = X509_get_subject_name(cert);
  13622. X509_NAME *iss = X509_get_issuer_name(cert);
  13623. /* Get serial number */
  13624. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13625. /* Translate serial number to a hex string */
  13626. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13627. if (serial_bn) {
  13628. str_serial = BN_bn2hex(serial_bn);
  13629. BN_free(serial_bn);
  13630. }
  13631. client_cert->serial =
  13632. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13633. /* Translate subject and issuer to a string */
  13634. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13635. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13636. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13637. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13638. /* Calculate SHA1 fingerprint and store as a hex string */
  13639. ulen = 0;
  13640. /* ASN1_digest is deprecated. Do the calculation manually,
  13641. * using EVP_Digest. */
  13642. ilen = i2d_X509(cert, NULL);
  13643. tmp_buf = (ilen > 0)
  13644. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13645. conn->phys_ctx)
  13646. : NULL;
  13647. if (tmp_buf) {
  13648. tmp_p = tmp_buf;
  13649. (void)i2d_X509(cert, &tmp_p);
  13650. if (!EVP_Digest(
  13651. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13652. ulen = 0;
  13653. }
  13654. mg_free(tmp_buf);
  13655. }
  13656. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13657. *str_buf = 0;
  13658. }
  13659. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13660. client_cert->peer_cert = (void *)cert;
  13661. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13662. * see https://linux.die.net/man/3/bn_bn2hex */
  13663. OPENSSL_free(str_serial);
  13664. return 1;
  13665. }
  13666. return 0;
  13667. }
  13668. #if defined(OPENSSL_API_1_1)
  13669. #else
  13670. static void
  13671. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13672. {
  13673. (void)line;
  13674. (void)file;
  13675. if (mode & 1) {
  13676. /* 1 is CRYPTO_LOCK */
  13677. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13678. } else {
  13679. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13680. }
  13681. }
  13682. #endif /* OPENSSL_API_1_1 */
  13683. #if !defined(NO_SSL_DL)
  13684. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13685. static void *
  13686. load_tls_dll(char *ebuf,
  13687. size_t ebuf_len,
  13688. const char *dll_name,
  13689. struct ssl_func *sw)
  13690. {
  13691. union {
  13692. void *p;
  13693. void (*fp)(void);
  13694. } u;
  13695. void *dll_handle;
  13696. struct ssl_func *fp;
  13697. int ok;
  13698. int truncated = 0;
  13699. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13700. mg_snprintf(NULL,
  13701. NULL, /* No truncation check for ebuf */
  13702. ebuf,
  13703. ebuf_len,
  13704. "%s: cannot load %s",
  13705. __func__,
  13706. dll_name);
  13707. return NULL;
  13708. }
  13709. ok = 1;
  13710. for (fp = sw; fp->name != NULL; fp++) {
  13711. enum ssl_func_category req = fp->required;
  13712. #if defined(_WIN32)
  13713. /* GetProcAddress() returns pointer to function */
  13714. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13715. #else
  13716. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13717. * pointers to function pointers. We need to use a union to make a
  13718. * cast. */
  13719. u.p = dlsym(dll_handle, fp->name);
  13720. #endif /* _WIN32 */
  13721. /* Set pointer (might be NULL) */
  13722. fp->ptr = u.fp;
  13723. if (u.fp == NULL) {
  13724. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13725. tls_feature_missing[req]++;
  13726. if (req == TLS_Mandatory) {
  13727. /* Mandatory function is missing */
  13728. if (ok) {
  13729. /* This is the first missing function.
  13730. * Create a new error message. */
  13731. mg_snprintf(NULL,
  13732. &truncated,
  13733. ebuf,
  13734. ebuf_len,
  13735. "%s: %s: cannot find %s",
  13736. __func__,
  13737. dll_name,
  13738. fp->name);
  13739. ok = 0;
  13740. } else {
  13741. /* This is yet anothermissing function.
  13742. * Append existing error message. */
  13743. size_t cur_len = strlen(ebuf);
  13744. if (!truncated) {
  13745. mg_snprintf(NULL,
  13746. &truncated,
  13747. ebuf + cur_len,
  13748. ebuf_len - cur_len - 3,
  13749. ", %s",
  13750. fp->name);
  13751. if (truncated) {
  13752. /* If truncated, add "..." */
  13753. strcat(ebuf, "...");
  13754. }
  13755. }
  13756. }
  13757. }
  13758. }
  13759. }
  13760. if (!ok) {
  13761. (void)dlclose(dll_handle);
  13762. return NULL;
  13763. }
  13764. return dll_handle;
  13765. }
  13766. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13767. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13768. #endif /* NO_SSL_DL */
  13769. #if defined(SSL_ALREADY_INITIALIZED)
  13770. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13771. #else
  13772. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13773. #endif
  13774. static int
  13775. initialize_ssl(char *ebuf, size_t ebuf_len)
  13776. {
  13777. #if defined(OPENSSL_API_1_1)
  13778. if (ebuf_len > 0) {
  13779. ebuf[0] = 0;
  13780. }
  13781. #if !defined(NO_SSL_DL)
  13782. if (!cryptolib_dll_handle) {
  13783. cryptolib_dll_handle =
  13784. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13785. if (!cryptolib_dll_handle) {
  13786. mg_snprintf(NULL,
  13787. NULL, /* No truncation check for ebuf */
  13788. ebuf,
  13789. ebuf_len,
  13790. "%s: error loading library %s",
  13791. __func__,
  13792. CRYPTO_LIB);
  13793. DEBUG_TRACE("%s", ebuf);
  13794. return 0;
  13795. }
  13796. }
  13797. #endif /* NO_SSL_DL */
  13798. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13799. return 1;
  13800. }
  13801. #else /* not OPENSSL_API_1_1 */
  13802. int i, num_locks;
  13803. size_t size;
  13804. if (ebuf_len > 0) {
  13805. ebuf[0] = 0;
  13806. }
  13807. #if !defined(NO_SSL_DL)
  13808. if (!cryptolib_dll_handle) {
  13809. cryptolib_dll_handle =
  13810. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13811. if (!cryptolib_dll_handle) {
  13812. mg_snprintf(NULL,
  13813. NULL, /* No truncation check for ebuf */
  13814. ebuf,
  13815. ebuf_len,
  13816. "%s: error loading library %s",
  13817. __func__,
  13818. CRYPTO_LIB);
  13819. DEBUG_TRACE("%s", ebuf);
  13820. return 0;
  13821. }
  13822. }
  13823. #endif /* NO_SSL_DL */
  13824. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13825. return 1;
  13826. }
  13827. /* Initialize locking callbacks, needed for thread safety.
  13828. * http://www.openssl.org/support/faq.html#PROG1
  13829. */
  13830. num_locks = CRYPTO_num_locks();
  13831. if (num_locks < 0) {
  13832. num_locks = 0;
  13833. }
  13834. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13835. /* allocate mutex array, if required */
  13836. if (num_locks == 0) {
  13837. /* No mutex array required */
  13838. ssl_mutexes = NULL;
  13839. } else {
  13840. /* Mutex array required - allocate it */
  13841. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13842. /* Check OOM */
  13843. if (ssl_mutexes == NULL) {
  13844. mg_snprintf(NULL,
  13845. NULL, /* No truncation check for ebuf */
  13846. ebuf,
  13847. ebuf_len,
  13848. "%s: cannot allocate mutexes: %s",
  13849. __func__,
  13850. ssl_error());
  13851. DEBUG_TRACE("%s", ebuf);
  13852. return 0;
  13853. }
  13854. /* initialize mutex array */
  13855. for (i = 0; i < num_locks; i++) {
  13856. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13857. mg_snprintf(NULL,
  13858. NULL, /* No truncation check for ebuf */
  13859. ebuf,
  13860. ebuf_len,
  13861. "%s: error initializing mutex %i of %i",
  13862. __func__,
  13863. i,
  13864. num_locks);
  13865. DEBUG_TRACE("%s", ebuf);
  13866. mg_free(ssl_mutexes);
  13867. return 0;
  13868. }
  13869. }
  13870. }
  13871. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13872. CRYPTO_set_id_callback(&mg_current_thread_id);
  13873. #endif /* OPENSSL_API_1_1 */
  13874. #if !defined(NO_SSL_DL)
  13875. if (!ssllib_dll_handle) {
  13876. ssllib_dll_handle = load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13877. if (!ssllib_dll_handle) {
  13878. #if !defined(OPENSSL_API_1_1)
  13879. mg_free(ssl_mutexes);
  13880. #endif
  13881. DEBUG_TRACE("%s", ebuf);
  13882. return 0;
  13883. }
  13884. }
  13885. #endif /* NO_SSL_DL */
  13886. #if defined(OPENSSL_API_1_1)
  13887. /* Initialize SSL library */
  13888. OPENSSL_init_ssl(0, NULL);
  13889. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13890. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13891. NULL);
  13892. #else
  13893. /* Initialize SSL library */
  13894. SSL_library_init();
  13895. SSL_load_error_strings();
  13896. #endif
  13897. return 1;
  13898. }
  13899. static int
  13900. ssl_use_pem_file(struct mg_context *phys_ctx,
  13901. struct mg_domain_context *dom_ctx,
  13902. const char *pem,
  13903. const char *chain)
  13904. {
  13905. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13906. mg_cry_ctx_internal(phys_ctx,
  13907. "%s: cannot open certificate file %s: %s",
  13908. __func__,
  13909. pem,
  13910. ssl_error());
  13911. return 0;
  13912. }
  13913. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13914. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13915. mg_cry_ctx_internal(phys_ctx,
  13916. "%s: cannot open private key file %s: %s",
  13917. __func__,
  13918. pem,
  13919. ssl_error());
  13920. return 0;
  13921. }
  13922. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13923. mg_cry_ctx_internal(phys_ctx,
  13924. "%s: certificate and private key do not match: %s",
  13925. __func__,
  13926. pem);
  13927. return 0;
  13928. }
  13929. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13930. * chain files that contain private keys and certificates in
  13931. * SSL_CTX_use_certificate_chain_file.
  13932. * The CivetWeb-Server used pem-Files that contained both information.
  13933. * In order to make wolfSSL work, it is split in two files.
  13934. * One file that contains key and certificate used by the server and
  13935. * an optional chain file for the ssl stack.
  13936. */
  13937. if (chain) {
  13938. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13939. mg_cry_ctx_internal(phys_ctx,
  13940. "%s: cannot use certificate chain file %s: %s",
  13941. __func__,
  13942. chain,
  13943. ssl_error());
  13944. return 0;
  13945. }
  13946. }
  13947. return 1;
  13948. }
  13949. #if defined(OPENSSL_API_1_1)
  13950. static unsigned long
  13951. ssl_get_protocol(int version_id)
  13952. {
  13953. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13954. if (version_id > 0)
  13955. ret |= SSL_OP_NO_SSLv2;
  13956. if (version_id > 1)
  13957. ret |= SSL_OP_NO_SSLv3;
  13958. if (version_id > 2)
  13959. ret |= SSL_OP_NO_TLSv1;
  13960. if (version_id > 3)
  13961. ret |= SSL_OP_NO_TLSv1_1;
  13962. if (version_id > 4)
  13963. ret |= SSL_OP_NO_TLSv1_2;
  13964. #if defined(SSL_OP_NO_TLSv1_3)
  13965. if (version_id > 5)
  13966. ret |= SSL_OP_NO_TLSv1_3;
  13967. #endif
  13968. return ret;
  13969. }
  13970. #else
  13971. static long
  13972. ssl_get_protocol(int version_id)
  13973. {
  13974. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13975. if (version_id > 0)
  13976. ret |= SSL_OP_NO_SSLv2;
  13977. if (version_id > 1)
  13978. ret |= SSL_OP_NO_SSLv3;
  13979. if (version_id > 2)
  13980. ret |= SSL_OP_NO_TLSv1;
  13981. if (version_id > 3)
  13982. ret |= SSL_OP_NO_TLSv1_1;
  13983. if (version_id > 4)
  13984. ret |= SSL_OP_NO_TLSv1_2;
  13985. #if defined(SSL_OP_NO_TLSv1_3)
  13986. if (version_id > 5)
  13987. ret |= SSL_OP_NO_TLSv1_3;
  13988. #endif
  13989. return (long)ret;
  13990. }
  13991. #endif /* OPENSSL_API_1_1 */
  13992. /* SSL callback documentation:
  13993. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13994. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13995. * https://linux.die.net/man/3/ssl_set_info_callback */
  13996. /* Note: There is no "const" for the first argument in the documentation
  13997. * examples, however some (maybe most, but not all) headers of OpenSSL
  13998. * versions / OpenSSL compatibility layers have it. Having a different
  13999. * definition will cause a warning in C and an error in C++. Use "const SSL
  14000. * *", while automatical conversion from "SSL *" works for all compilers,
  14001. * but not other way around */
  14002. static void
  14003. ssl_info_callback(const SSL *ssl, int what, int ret)
  14004. {
  14005. (void)ret;
  14006. if (what & SSL_CB_HANDSHAKE_START) {
  14007. SSL_get_app_data(ssl);
  14008. }
  14009. if (what & SSL_CB_HANDSHAKE_DONE) {
  14010. /* TODO: check for openSSL 1.1 */
  14011. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14012. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14013. }
  14014. }
  14015. static int
  14016. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14017. {
  14018. #if defined(GCC_DIAGNOSTIC)
  14019. #pragma GCC diagnostic push
  14020. #pragma GCC diagnostic ignored "-Wcast-align"
  14021. #endif /* defined(GCC_DIAGNOSTIC) */
  14022. /* We used an aligned pointer in SSL_set_app_data */
  14023. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14024. #if defined(GCC_DIAGNOSTIC)
  14025. #pragma GCC diagnostic pop
  14026. #endif /* defined(GCC_DIAGNOSTIC) */
  14027. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14028. (void)ad;
  14029. (void)arg;
  14030. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14031. DEBUG_ASSERT(0);
  14032. return SSL_TLSEXT_ERR_NOACK;
  14033. }
  14034. conn->dom_ctx = &(conn->phys_ctx->dd);
  14035. /* Old clients (Win XP) will not support SNI. Then, there
  14036. * is no server name available in the request - we can
  14037. * only work with the default certificate.
  14038. * Multiple HTTPS hosts on one IP+port are only possible
  14039. * with a certificate containing all alternative names.
  14040. */
  14041. if ((servername == NULL) || (*servername == 0)) {
  14042. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14043. mg_lock_context(conn->phys_ctx);
  14044. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14045. mg_unlock_context(conn->phys_ctx);
  14046. return SSL_TLSEXT_ERR_NOACK;
  14047. }
  14048. DEBUG_TRACE("TLS connection to host %s", servername);
  14049. while (conn->dom_ctx) {
  14050. if (!mg_strcasecmp(servername,
  14051. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14052. /* Found matching domain */
  14053. DEBUG_TRACE("TLS domain %s found",
  14054. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14055. break;
  14056. }
  14057. mg_lock_context(conn->phys_ctx);
  14058. conn->dom_ctx = conn->dom_ctx->next;
  14059. mg_unlock_context(conn->phys_ctx);
  14060. }
  14061. if (conn->dom_ctx == NULL) {
  14062. /* Default domain */
  14063. DEBUG_TRACE("TLS default domain %s used",
  14064. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14065. conn->dom_ctx = &(conn->phys_ctx->dd);
  14066. }
  14067. mg_lock_context(conn->phys_ctx);
  14068. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14069. mg_unlock_context(conn->phys_ctx);
  14070. return SSL_TLSEXT_ERR_OK;
  14071. }
  14072. #if defined(USE_HTTP2)
  14073. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14074. static const char *alpn_proto_order[] = {alpn_proto_list,
  14075. alpn_proto_list + 3,
  14076. alpn_proto_list + 3 + 8,
  14077. NULL};
  14078. #else
  14079. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14080. static const char *alpn_proto_order[] = {alpn_proto_list,
  14081. alpn_proto_list + 8,
  14082. NULL};
  14083. #endif
  14084. static int
  14085. alpn_select_cb(SSL *ssl,
  14086. const unsigned char **out,
  14087. unsigned char *outlen,
  14088. const unsigned char *in,
  14089. unsigned int inlen,
  14090. void *arg)
  14091. {
  14092. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14093. unsigned int i, j;
  14094. struct mg_workerTLS *tls =
  14095. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14096. (void)ssl;
  14097. (void)dom_ctx;
  14098. if (tls == NULL) {
  14099. /* Need to store protocol in Thread Local Storage */
  14100. /* If there is no Thread Local Storage, don't use ALPN */
  14101. return SSL_TLSEXT_ERR_NOACK;
  14102. }
  14103. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14104. /* check all accepted protocols in this order */
  14105. const char *alpn_proto = alpn_proto_order[j];
  14106. /* search input for matching protocol */
  14107. for (i = 0; i < inlen; i++) {
  14108. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14109. *out = in + i + 1;
  14110. *outlen = in[i];
  14111. tls->alpn_proto = alpn_proto;
  14112. return SSL_TLSEXT_ERR_OK;
  14113. }
  14114. }
  14115. }
  14116. /* Nothing found */
  14117. return SSL_TLSEXT_ERR_NOACK;
  14118. }
  14119. static int
  14120. next_protos_advertised_cb(SSL *ssl,
  14121. const unsigned char **data,
  14122. unsigned int *len,
  14123. void *arg)
  14124. {
  14125. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14126. *data = (const unsigned char *)alpn_proto_list;
  14127. *len = (unsigned int)strlen((const char *)data);
  14128. (void)ssl;
  14129. (void)dom_ctx;
  14130. return SSL_TLSEXT_ERR_OK;
  14131. }
  14132. static int
  14133. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14134. {
  14135. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14136. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14137. (const unsigned char *)alpn_proto_list,
  14138. alpn_len);
  14139. if (ret != 0) {
  14140. mg_cry_ctx_internal(phys_ctx,
  14141. "SSL_CTX_set_alpn_protos error: %s",
  14142. ssl_error());
  14143. }
  14144. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14145. alpn_select_cb,
  14146. (void *)dom_ctx);
  14147. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14148. next_protos_advertised_cb,
  14149. (void *)dom_ctx);
  14150. return ret;
  14151. }
  14152. /* Setup SSL CTX as required by CivetWeb */
  14153. static int
  14154. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14155. struct mg_domain_context *dom_ctx,
  14156. const char *pem,
  14157. const char *chain)
  14158. {
  14159. int callback_ret;
  14160. int should_verify_peer;
  14161. int peer_certificate_optional;
  14162. const char *ca_path;
  14163. const char *ca_file;
  14164. int use_default_verify_paths;
  14165. int verify_depth;
  14166. struct timespec now_mt;
  14167. md5_byte_t ssl_context_id[16];
  14168. md5_state_t md5state;
  14169. int protocol_ver;
  14170. #if defined(OPENSSL_API_1_1)
  14171. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14172. mg_cry_ctx_internal(phys_ctx,
  14173. "SSL_CTX_new (server) error: %s",
  14174. ssl_error());
  14175. return 0;
  14176. }
  14177. #else
  14178. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14179. mg_cry_ctx_internal(phys_ctx,
  14180. "SSL_CTX_new (server) error: %s",
  14181. ssl_error());
  14182. return 0;
  14183. }
  14184. #endif /* OPENSSL_API_1_1 */
  14185. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14186. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14187. | SSL_OP_NO_TLSv1_1);
  14188. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14189. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14190. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14191. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14192. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14193. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14194. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14195. #if defined(SSL_OP_NO_RENEGOTIATION)
  14196. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14197. #endif
  14198. #if !defined(NO_SSL_DL)
  14199. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14200. #endif /* NO_SSL_DL */
  14201. /* In SSL documentation examples callback defined without const
  14202. * specifier 'void (*)(SSL *, int, int)' See:
  14203. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14204. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14205. * But in the source code const SSL is used:
  14206. * 'void (*)(const SSL *, int, int)' See:
  14207. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14208. * Problem about wrong documentation described, but not resolved:
  14209. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14210. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14211. * But when compiled with modern C++ compiler, correct const should be
  14212. * provided
  14213. */
  14214. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14215. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14216. ssl_servername_callback);
  14217. /* If a callback has been specified, call it. */
  14218. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14219. ? 0
  14220. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14221. phys_ctx->user_data));
  14222. /* If callback returns 0, civetweb sets up the SSL certificate.
  14223. * If it returns 1, civetweb assumes the calback already did this.
  14224. * If it returns -1, initializing ssl fails. */
  14225. if (callback_ret < 0) {
  14226. mg_cry_ctx_internal(phys_ctx,
  14227. "SSL callback returned error: %i",
  14228. callback_ret);
  14229. return 0;
  14230. }
  14231. if (callback_ret > 0) {
  14232. /* Callback did everything. */
  14233. return 1;
  14234. }
  14235. /* If a domain callback has been specified, call it. */
  14236. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14237. ? 0
  14238. : (phys_ctx->callbacks.init_ssl_domain(
  14239. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14240. dom_ctx->ssl_ctx,
  14241. phys_ctx->user_data));
  14242. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14243. * If it returns 1, civetweb assumes the calback already did this.
  14244. * If it returns -1, initializing ssl fails. */
  14245. if (callback_ret < 0) {
  14246. mg_cry_ctx_internal(phys_ctx,
  14247. "Domain SSL callback returned error: %i",
  14248. callback_ret);
  14249. return 0;
  14250. }
  14251. if (callback_ret > 0) {
  14252. /* Domain callback did everything. */
  14253. return 1;
  14254. }
  14255. /* Use some combination of start time, domain and port as a SSL
  14256. * context ID. This should be unique on the current machine. */
  14257. md5_init(&md5state);
  14258. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14259. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14260. md5_append(&md5state,
  14261. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14262. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14263. md5_append(&md5state,
  14264. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14265. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14266. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14267. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14268. md5_finish(&md5state, ssl_context_id);
  14269. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14270. (unsigned char *)ssl_context_id,
  14271. sizeof(ssl_context_id));
  14272. if (pem != NULL) {
  14273. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14274. return 0;
  14275. }
  14276. }
  14277. /* Should we support client certificates? */
  14278. /* Default is "no". */
  14279. should_verify_peer = 0;
  14280. peer_certificate_optional = 0;
  14281. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14282. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14283. /* Yes, they are mandatory */
  14284. should_verify_peer = 1;
  14285. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14286. "optional")
  14287. == 0) {
  14288. /* Yes, they are optional */
  14289. should_verify_peer = 1;
  14290. peer_certificate_optional = 1;
  14291. }
  14292. }
  14293. use_default_verify_paths =
  14294. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14295. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14296. == 0);
  14297. if (should_verify_peer) {
  14298. ca_path = dom_ctx->config[SSL_CA_PATH];
  14299. ca_file = dom_ctx->config[SSL_CA_FILE];
  14300. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14301. != 1) {
  14302. mg_cry_ctx_internal(phys_ctx,
  14303. "SSL_CTX_load_verify_locations error: %s "
  14304. "ssl_verify_peer requires setting "
  14305. "either ssl_ca_path or ssl_ca_file. "
  14306. "Is any of them present in the "
  14307. ".conf file?",
  14308. ssl_error());
  14309. return 0;
  14310. }
  14311. if (peer_certificate_optional) {
  14312. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14313. } else {
  14314. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14315. SSL_VERIFY_PEER
  14316. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14317. NULL);
  14318. }
  14319. if (use_default_verify_paths
  14320. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14321. mg_cry_ctx_internal(phys_ctx,
  14322. "SSL_CTX_set_default_verify_paths error: %s",
  14323. ssl_error());
  14324. return 0;
  14325. }
  14326. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14327. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14328. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14329. }
  14330. }
  14331. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14332. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14333. dom_ctx->config[SSL_CIPHER_LIST])
  14334. != 1) {
  14335. mg_cry_ctx_internal(phys_ctx,
  14336. "SSL_CTX_set_cipher_list error: %s",
  14337. ssl_error());
  14338. }
  14339. }
  14340. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14341. #if !defined(NO_SSL_DL)
  14342. if (!tls_feature_missing[TLS_ALPN])
  14343. #endif
  14344. {
  14345. init_alpn(phys_ctx, dom_ctx);
  14346. }
  14347. return 1;
  14348. }
  14349. /* Check if SSL is required.
  14350. * If so, dynamically load SSL library
  14351. * and set up ctx->ssl_ctx pointer. */
  14352. static int
  14353. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14354. {
  14355. void *ssl_ctx = 0;
  14356. int callback_ret;
  14357. const char *pem;
  14358. const char *chain;
  14359. char ebuf[128];
  14360. if (!phys_ctx) {
  14361. return 0;
  14362. }
  14363. if (!dom_ctx) {
  14364. dom_ctx = &(phys_ctx->dd);
  14365. }
  14366. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14367. /* No SSL port is set. No need to setup SSL. */
  14368. return 1;
  14369. }
  14370. /* Check for external SSL_CTX */
  14371. callback_ret =
  14372. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14373. ? 0
  14374. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14375. phys_ctx->user_data));
  14376. if (callback_ret < 0) {
  14377. mg_cry_ctx_internal(phys_ctx,
  14378. "external_ssl_ctx callback returned error: %i",
  14379. callback_ret);
  14380. return 0;
  14381. } else if (callback_ret > 0) {
  14382. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14383. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14384. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14385. return 0;
  14386. }
  14387. return 1;
  14388. }
  14389. /* Check for external domain SSL_CTX */
  14390. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14391. ? 0
  14392. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14393. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14394. &ssl_ctx,
  14395. phys_ctx->user_data));
  14396. if (callback_ret < 0) {
  14397. mg_cry_ctx_internal(
  14398. phys_ctx,
  14399. "external_ssl_ctx_domain callback returned error: %i",
  14400. callback_ret);
  14401. return 0;
  14402. } else if (callback_ret > 0) {
  14403. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14404. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14405. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14406. return 0;
  14407. }
  14408. return 1;
  14409. }
  14410. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14411. * 0, CivetWeb should continue initializing SSL */
  14412. /* If PEM file is not specified and the init_ssl callbacks
  14413. * are not specified, setup will fail. */
  14414. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14415. && (phys_ctx->callbacks.init_ssl == NULL)
  14416. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14417. /* No certificate and no init_ssl callbacks:
  14418. * Essential data to set up TLS is missing.
  14419. */
  14420. mg_cry_ctx_internal(phys_ctx,
  14421. "Initializing SSL failed: -%s is not set",
  14422. config_options[SSL_CERTIFICATE].name);
  14423. return 0;
  14424. }
  14425. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14426. if (chain == NULL) {
  14427. chain = pem;
  14428. }
  14429. if ((chain != NULL) && (*chain == 0)) {
  14430. chain = NULL;
  14431. }
  14432. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14433. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14434. return 0;
  14435. }
  14436. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14437. }
  14438. static void
  14439. uninitialize_ssl(void)
  14440. {
  14441. #if defined(OPENSSL_API_1_1)
  14442. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14443. /* Shutdown according to
  14444. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14445. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14446. */
  14447. CONF_modules_unload(1);
  14448. #else
  14449. int i;
  14450. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14451. /* Shutdown according to
  14452. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14453. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14454. */
  14455. CRYPTO_set_locking_callback(NULL);
  14456. CRYPTO_set_id_callback(NULL);
  14457. ENGINE_cleanup();
  14458. CONF_modules_unload(1);
  14459. ERR_free_strings();
  14460. EVP_cleanup();
  14461. CRYPTO_cleanup_all_ex_data();
  14462. OPENSSL_REMOVE_THREAD_STATE();
  14463. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14464. pthread_mutex_destroy(&ssl_mutexes[i]);
  14465. }
  14466. mg_free(ssl_mutexes);
  14467. ssl_mutexes = NULL;
  14468. #endif /* OPENSSL_API_1_1 */
  14469. }
  14470. }
  14471. #endif /* !NO_SSL */
  14472. #if !defined(NO_FILESYSTEMS)
  14473. static int
  14474. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14475. {
  14476. if (phys_ctx) {
  14477. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14478. const char *path;
  14479. struct mg_connection fc;
  14480. if (!dom_ctx) {
  14481. dom_ctx = &(phys_ctx->dd);
  14482. }
  14483. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14484. if ((path != NULL)
  14485. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14486. mg_cry_ctx_internal(phys_ctx,
  14487. "Cannot open %s: %s",
  14488. path,
  14489. strerror(ERRNO));
  14490. return 0;
  14491. }
  14492. return 1;
  14493. }
  14494. return 0;
  14495. }
  14496. #endif /* NO_FILESYSTEMS */
  14497. static int
  14498. set_acl_option(struct mg_context *phys_ctx)
  14499. {
  14500. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14501. }
  14502. static void
  14503. reset_per_request_attributes(struct mg_connection *conn)
  14504. {
  14505. if (!conn) {
  14506. return;
  14507. }
  14508. conn->connection_type =
  14509. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14510. conn->num_bytes_sent = conn->consumed_content = 0;
  14511. conn->path_info = NULL;
  14512. conn->status_code = -1;
  14513. conn->content_len = -1;
  14514. conn->is_chunked = 0;
  14515. conn->must_close = 0;
  14516. conn->request_len = 0;
  14517. conn->throttle = 0;
  14518. conn->accept_gzip = 0;
  14519. conn->response_info.content_length = conn->request_info.content_length = -1;
  14520. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14521. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14522. conn->response_info.status_text = NULL;
  14523. conn->response_info.status_code = 0;
  14524. conn->request_info.remote_user = NULL;
  14525. conn->request_info.request_method = NULL;
  14526. conn->request_info.request_uri = NULL;
  14527. conn->request_info.local_uri = NULL;
  14528. #if defined(MG_LEGACY_INTERFACE)
  14529. /* Legacy before split into local_uri and request_uri */
  14530. conn->request_info.uri = NULL;
  14531. #endif
  14532. }
  14533. static int
  14534. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14535. {
  14536. if (setsockopt(sock,
  14537. IPPROTO_TCP,
  14538. TCP_NODELAY,
  14539. (SOCK_OPT_TYPE)&nodelay_on,
  14540. sizeof(nodelay_on))
  14541. != 0) {
  14542. /* Error */
  14543. return 1;
  14544. }
  14545. /* OK */
  14546. return 0;
  14547. }
  14548. #if !defined(__ZEPHYR__)
  14549. static void
  14550. close_socket_gracefully(struct mg_connection *conn)
  14551. {
  14552. #if defined(_WIN32)
  14553. char buf[MG_BUF_LEN];
  14554. int n;
  14555. #endif
  14556. struct linger linger;
  14557. int error_code = 0;
  14558. int linger_timeout = -2;
  14559. socklen_t opt_len = sizeof(error_code);
  14560. if (!conn) {
  14561. return;
  14562. }
  14563. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14564. * "Note that enabling a nonzero timeout on a nonblocking socket
  14565. * is not recommended.", so set it to blocking now */
  14566. set_blocking_mode(conn->client.sock);
  14567. /* Send FIN to the client */
  14568. shutdown(conn->client.sock, SHUTDOWN_WR);
  14569. #if defined(_WIN32)
  14570. /* Read and discard pending incoming data. If we do not do that and
  14571. * close
  14572. * the socket, the data in the send buffer may be discarded. This
  14573. * behaviour is seen on Windows, when client keeps sending data
  14574. * when server decides to close the connection; then when client
  14575. * does recv() it gets no data back. */
  14576. do {
  14577. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14578. } while (n > 0);
  14579. #endif
  14580. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14581. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14582. }
  14583. /* Set linger option according to configuration */
  14584. if (linger_timeout >= 0) {
  14585. /* Set linger option to avoid socket hanging out after close. This
  14586. * prevent ephemeral port exhaust problem under high QPS. */
  14587. linger.l_onoff = 1;
  14588. #if defined(_MSC_VER)
  14589. #pragma warning(push)
  14590. #pragma warning(disable : 4244)
  14591. #endif
  14592. #if defined(GCC_DIAGNOSTIC)
  14593. #pragma GCC diagnostic push
  14594. #pragma GCC diagnostic ignored "-Wconversion"
  14595. #endif
  14596. /* Data type of linger structure elements may differ,
  14597. * so we don't know what cast we need here.
  14598. * Disable type conversion warnings. */
  14599. linger.l_linger = (linger_timeout + 999) / 1000;
  14600. #if defined(GCC_DIAGNOSTIC)
  14601. #pragma GCC diagnostic pop
  14602. #endif
  14603. #if defined(_MSC_VER)
  14604. #pragma warning(pop)
  14605. #endif
  14606. } else {
  14607. linger.l_onoff = 0;
  14608. linger.l_linger = 0;
  14609. }
  14610. if (linger_timeout < -1) {
  14611. /* Default: don't configure any linger */
  14612. } else if (getsockopt(conn->client.sock,
  14613. SOL_SOCKET,
  14614. SO_ERROR,
  14615. #if defined(_WIN32) /* WinSock uses different data type here */
  14616. (char *)&error_code,
  14617. #else
  14618. &error_code,
  14619. #endif
  14620. &opt_len)
  14621. != 0) {
  14622. /* Cannot determine if socket is already closed. This should
  14623. * not occur and never did in a test. Log an error message
  14624. * and continue. */
  14625. mg_cry_internal(conn,
  14626. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14627. __func__,
  14628. strerror(ERRNO));
  14629. #if defined(_WIN32)
  14630. } else if (error_code == WSAECONNRESET) {
  14631. #else
  14632. } else if (error_code == ECONNRESET) {
  14633. #endif
  14634. /* Socket already closed by client/peer, close socket without linger
  14635. */
  14636. } else {
  14637. /* Set linger timeout */
  14638. if (setsockopt(conn->client.sock,
  14639. SOL_SOCKET,
  14640. SO_LINGER,
  14641. (char *)&linger,
  14642. sizeof(linger))
  14643. != 0) {
  14644. mg_cry_internal(
  14645. conn,
  14646. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14647. __func__,
  14648. linger.l_onoff,
  14649. linger.l_linger,
  14650. strerror(ERRNO));
  14651. }
  14652. }
  14653. /* Now we know that our FIN is ACK-ed, safe to close */
  14654. closesocket(conn->client.sock);
  14655. conn->client.sock = INVALID_SOCKET;
  14656. }
  14657. #endif
  14658. static void
  14659. close_connection(struct mg_connection *conn)
  14660. {
  14661. #if defined(USE_SERVER_STATS)
  14662. conn->conn_state = 6; /* to close */
  14663. #endif
  14664. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14665. if (conn->lua_websocket_state) {
  14666. lua_websocket_close(conn, conn->lua_websocket_state);
  14667. conn->lua_websocket_state = NULL;
  14668. }
  14669. #endif
  14670. mg_lock_connection(conn);
  14671. /* Set close flag, so keep-alive loops will stop */
  14672. conn->must_close = 1;
  14673. /* call the connection_close callback if assigned */
  14674. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14675. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14676. conn->phys_ctx->callbacks.connection_close(conn);
  14677. }
  14678. }
  14679. /* Reset user data, after close callback is called.
  14680. * Do not reuse it. If the user needs a destructor,
  14681. * it must be done in the connection_close callback. */
  14682. mg_set_user_connection_data(conn, NULL);
  14683. #if defined(USE_SERVER_STATS)
  14684. conn->conn_state = 7; /* closing */
  14685. #endif
  14686. #if !defined(NO_SSL)
  14687. if (conn->ssl != NULL) {
  14688. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14689. */
  14690. SSL_shutdown(conn->ssl);
  14691. SSL_free(conn->ssl);
  14692. OPENSSL_REMOVE_THREAD_STATE();
  14693. conn->ssl = NULL;
  14694. }
  14695. #endif
  14696. if (conn->client.sock != INVALID_SOCKET) {
  14697. #if defined(__ZEPHYR__)
  14698. closesocket(conn->client.sock);
  14699. #else
  14700. close_socket_gracefully(conn);
  14701. #endif
  14702. conn->client.sock = INVALID_SOCKET;
  14703. }
  14704. if (conn->host) {
  14705. mg_free((void *)conn->host);
  14706. conn->host = NULL;
  14707. }
  14708. mg_unlock_connection(conn);
  14709. #if defined(USE_SERVER_STATS)
  14710. conn->conn_state = 8; /* closed */
  14711. #endif
  14712. }
  14713. void
  14714. mg_close_connection(struct mg_connection *conn)
  14715. {
  14716. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14717. return;
  14718. }
  14719. #if defined(USE_WEBSOCKET)
  14720. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14721. if (conn->in_websocket_handling) {
  14722. /* Set close flag, so the server thread can exit. */
  14723. conn->must_close = 1;
  14724. return;
  14725. }
  14726. }
  14727. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14728. unsigned int i;
  14729. /* client context: loops must end */
  14730. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14731. conn->must_close = 1;
  14732. /* We need to get the client thread out of the select/recv call
  14733. * here. */
  14734. /* Since we use a sleep quantum of some seconds to check for recv
  14735. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14736. /* join worker thread */
  14737. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14738. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14739. }
  14740. }
  14741. #endif /* defined(USE_WEBSOCKET) */
  14742. close_connection(conn);
  14743. #if !defined(NO_SSL)
  14744. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14745. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14746. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14747. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14748. }
  14749. #endif
  14750. #if defined(USE_WEBSOCKET)
  14751. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14752. mg_free(conn->phys_ctx->worker_threadids);
  14753. (void)pthread_mutex_destroy(&conn->mutex);
  14754. mg_free(conn);
  14755. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14756. mg_free(conn);
  14757. }
  14758. #else
  14759. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14760. mg_free(conn);
  14761. }
  14762. #endif /* defined(USE_WEBSOCKET) */
  14763. }
  14764. static struct mg_connection *
  14765. mg_connect_client_impl(const struct mg_client_options *client_options,
  14766. int use_ssl,
  14767. char *ebuf,
  14768. size_t ebuf_len)
  14769. {
  14770. struct mg_connection *conn = NULL;
  14771. SOCKET sock;
  14772. union usa sa;
  14773. struct sockaddr *psa;
  14774. socklen_t len;
  14775. unsigned max_req_size =
  14776. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14777. /* Size of structures, aligned to 8 bytes */
  14778. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14779. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14780. conn =
  14781. (struct mg_connection *)mg_calloc(1,
  14782. conn_size + ctx_size + max_req_size);
  14783. if (conn == NULL) {
  14784. mg_snprintf(NULL,
  14785. NULL, /* No truncation check for ebuf */
  14786. ebuf,
  14787. ebuf_len,
  14788. "calloc(): %s",
  14789. strerror(ERRNO));
  14790. return NULL;
  14791. }
  14792. #if defined(GCC_DIAGNOSTIC)
  14793. #pragma GCC diagnostic push
  14794. #pragma GCC diagnostic ignored "-Wcast-align"
  14795. #endif /* defined(GCC_DIAGNOSTIC) */
  14796. /* conn_size is aligned to 8 bytes */
  14797. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14798. #if defined(GCC_DIAGNOSTIC)
  14799. #pragma GCC diagnostic pop
  14800. #endif /* defined(GCC_DIAGNOSTIC) */
  14801. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14802. conn->buf_size = (int)max_req_size;
  14803. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14804. conn->dom_ctx = &(conn->phys_ctx->dd);
  14805. if (!connect_socket(conn->phys_ctx,
  14806. client_options->host,
  14807. client_options->port,
  14808. use_ssl,
  14809. ebuf,
  14810. ebuf_len,
  14811. &sock,
  14812. &sa)) {
  14813. /* ebuf is set by connect_socket,
  14814. * free all memory and return NULL; */
  14815. mg_free(conn);
  14816. return NULL;
  14817. }
  14818. #if !defined(NO_SSL)
  14819. #if defined(OPENSSL_API_1_1)
  14820. if (use_ssl
  14821. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14822. == NULL) {
  14823. mg_snprintf(NULL,
  14824. NULL, /* No truncation check for ebuf */
  14825. ebuf,
  14826. ebuf_len,
  14827. "SSL_CTX_new error: %s",
  14828. ssl_error());
  14829. closesocket(sock);
  14830. mg_free(conn);
  14831. return NULL;
  14832. }
  14833. #else
  14834. if (use_ssl
  14835. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14836. == NULL) {
  14837. mg_snprintf(NULL,
  14838. NULL, /* No truncation check for ebuf */
  14839. ebuf,
  14840. ebuf_len,
  14841. "SSL_CTX_new error: %s",
  14842. ssl_error());
  14843. closesocket(sock);
  14844. mg_free(conn);
  14845. return NULL;
  14846. }
  14847. #endif /* OPENSSL_API_1_1 */
  14848. #endif /* NO_SSL */
  14849. #if defined(USE_IPV6)
  14850. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14851. : sizeof(conn->client.rsa.sin6);
  14852. psa = (sa.sa.sa_family == AF_INET)
  14853. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14854. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14855. #else
  14856. len = sizeof(conn->client.rsa.sin);
  14857. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14858. #endif
  14859. conn->client.sock = sock;
  14860. conn->client.lsa = sa;
  14861. if (getsockname(sock, psa, &len) != 0) {
  14862. mg_cry_internal(conn,
  14863. "%s: getsockname() failed: %s",
  14864. __func__,
  14865. strerror(ERRNO));
  14866. }
  14867. conn->client.is_ssl = use_ssl ? 1 : 0;
  14868. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14869. mg_snprintf(NULL,
  14870. NULL, /* No truncation check for ebuf */
  14871. ebuf,
  14872. ebuf_len,
  14873. "Can not create mutex");
  14874. #if !defined(NO_SSL)
  14875. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14876. #endif
  14877. closesocket(sock);
  14878. mg_free(conn);
  14879. return NULL;
  14880. }
  14881. #if !defined(NO_SSL)
  14882. if (use_ssl) {
  14883. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14884. * SSL_CTX_set_verify call is needed to switch off server
  14885. * certificate checking, which is off by default in OpenSSL and
  14886. * on in yaSSL. */
  14887. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14888. * SSL_VERIFY_PEER, verify_ssl_server); */
  14889. if (client_options->client_cert) {
  14890. if (!ssl_use_pem_file(conn->phys_ctx,
  14891. conn->dom_ctx,
  14892. client_options->client_cert,
  14893. NULL)) {
  14894. mg_snprintf(NULL,
  14895. NULL, /* No truncation check for ebuf */
  14896. ebuf,
  14897. ebuf_len,
  14898. "Can not use SSL client certificate");
  14899. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14900. closesocket(sock);
  14901. mg_free(conn);
  14902. return NULL;
  14903. }
  14904. }
  14905. if (client_options->server_cert) {
  14906. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14907. client_options->server_cert,
  14908. NULL)
  14909. != 1) {
  14910. mg_cry_internal(conn,
  14911. "SSL_CTX_load_verify_locations error: %s ",
  14912. ssl_error());
  14913. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14914. closesocket(sock);
  14915. mg_free(conn);
  14916. return NULL;
  14917. }
  14918. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14919. } else {
  14920. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14921. }
  14922. if (!sslize(conn,
  14923. SSL_connect,
  14924. client_options)) {
  14925. mg_snprintf(NULL,
  14926. NULL, /* No truncation check for ebuf */
  14927. ebuf,
  14928. ebuf_len,
  14929. "SSL connection error");
  14930. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14931. closesocket(sock);
  14932. mg_free(conn);
  14933. return NULL;
  14934. }
  14935. }
  14936. #endif
  14937. return conn;
  14938. }
  14939. CIVETWEB_API struct mg_connection *
  14940. mg_connect_client_secure(const struct mg_client_options *client_options,
  14941. char *error_buffer,
  14942. size_t error_buffer_size)
  14943. {
  14944. return mg_connect_client_impl(client_options,
  14945. 1,
  14946. error_buffer,
  14947. error_buffer_size);
  14948. }
  14949. struct mg_connection *
  14950. mg_connect_client(const char *host,
  14951. int port,
  14952. int use_ssl,
  14953. char *error_buffer,
  14954. size_t error_buffer_size)
  14955. {
  14956. struct mg_client_options opts;
  14957. memset(&opts, 0, sizeof(opts));
  14958. opts.host = host;
  14959. opts.port = port;
  14960. return mg_connect_client_impl(&opts,
  14961. use_ssl,
  14962. error_buffer,
  14963. error_buffer_size);
  14964. }
  14965. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14966. struct mg_connection *
  14967. mg_connect_client2(const char *host,
  14968. const char *protocol,
  14969. int port,
  14970. const char *path,
  14971. struct mg_init_data *init,
  14972. struct mg_error_data *error)
  14973. {
  14974. int is_ssl, is_ws;
  14975. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14976. if (error != NULL) {
  14977. error->code = 0;
  14978. if (error->text_buffer_size > 0) {
  14979. *error->text = 0;
  14980. }
  14981. }
  14982. if ((host == NULL) || (protocol == NULL)) {
  14983. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14984. mg_snprintf(NULL,
  14985. NULL, /* No truncation check for error buffers */
  14986. error->text,
  14987. error->text_buffer_size,
  14988. "%s",
  14989. "Invalid parameters");
  14990. }
  14991. return NULL;
  14992. }
  14993. /* check all known protocolls */
  14994. if (!mg_strcasecmp(protocol, "http")) {
  14995. is_ssl = 0;
  14996. is_ws = 0;
  14997. } else if (!mg_strcasecmp(protocol, "https")) {
  14998. is_ssl = 1;
  14999. is_ws = 0;
  15000. #if defined(USE_WEBSOCKET)
  15001. } else if (!mg_strcasecmp(protocol, "ws")) {
  15002. is_ssl = 0;
  15003. is_ws = 1;
  15004. } else if (!mg_strcasecmp(protocol, "wss")) {
  15005. is_ssl = 1;
  15006. is_ws = 1;
  15007. #endif
  15008. } else {
  15009. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15010. mg_snprintf(NULL,
  15011. NULL, /* No truncation check for error buffers */
  15012. error->text,
  15013. error->text_buffer_size,
  15014. "Protocol %s not supported",
  15015. protocol);
  15016. }
  15017. return NULL;
  15018. }
  15019. /* TODO: The current implementation here just calls the old
  15020. * implementations, without using any new options. This is just a first
  15021. * step to test the new interfaces. */
  15022. #if defined(USE_WEBSOCKET)
  15023. if (is_ws) {
  15024. /* TODO: implement all options */
  15025. return mg_connect_websocket_client(
  15026. host,
  15027. port,
  15028. is_ssl,
  15029. ((error != NULL) ? error->text : NULL),
  15030. ((error != NULL) ? error->text_buffer_size : 0),
  15031. (path ? path : ""),
  15032. NULL /* TODO: origin */,
  15033. deprecated_websocket_data_wrapper,
  15034. deprecated_websocket_close_wrapper,
  15035. (void *)init->callbacks);
  15036. }
  15037. #endif
  15038. /* TODO: all additional options */
  15039. struct mg_client_options opts;
  15040. memset(&opts, 0, sizeof(opts));
  15041. opts.host = host;
  15042. opts.port = port;
  15043. return mg_connect_client_impl(&opts,
  15044. is_ssl,
  15045. ((error != NULL) ? error->text : NULL),
  15046. ((error != NULL) ? error->text_buffer_size
  15047. : 0));
  15048. }
  15049. #endif
  15050. static const struct {
  15051. const char *proto;
  15052. size_t proto_len;
  15053. unsigned default_port;
  15054. } abs_uri_protocols[] = {{"http://", 7, 80},
  15055. {"https://", 8, 443},
  15056. {"ws://", 5, 80},
  15057. {"wss://", 6, 443},
  15058. {NULL, 0, 0}};
  15059. /* Check if the uri is valid.
  15060. * return 0 for invalid uri,
  15061. * return 1 for *,
  15062. * return 2 for relative uri,
  15063. * return 3 for absolute uri without port,
  15064. * return 4 for absolute uri with port */
  15065. static int
  15066. get_uri_type(const char *uri)
  15067. {
  15068. int i;
  15069. const char *hostend, *portbegin;
  15070. char *portend;
  15071. unsigned long port;
  15072. /* According to the HTTP standard
  15073. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15074. * URI can be an asterisk (*) or should start with slash (relative uri),
  15075. * or it should start with the protocol (absolute uri). */
  15076. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15077. /* asterisk */
  15078. return 1;
  15079. }
  15080. /* Valid URIs according to RFC 3986
  15081. * (https://www.ietf.org/rfc/rfc3986.txt)
  15082. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15083. * and unreserved characters A-Z a-z 0-9 and -._~
  15084. * and % encoded symbols.
  15085. */
  15086. for (i = 0; uri[i] != 0; i++) {
  15087. if (uri[i] < 33) {
  15088. /* control characters and spaces are invalid */
  15089. return 0;
  15090. }
  15091. if (uri[i] > 126) {
  15092. /* non-ascii characters must be % encoded */
  15093. return 0;
  15094. } else {
  15095. switch (uri[i]) {
  15096. case '"': /* 34 */
  15097. case '<': /* 60 */
  15098. case '>': /* 62 */
  15099. case '\\': /* 92 */
  15100. case '^': /* 94 */
  15101. case '`': /* 96 */
  15102. case '{': /* 123 */
  15103. case '|': /* 124 */
  15104. case '}': /* 125 */
  15105. return 0;
  15106. default:
  15107. /* character is ok */
  15108. break;
  15109. }
  15110. }
  15111. }
  15112. /* A relative uri starts with a / character */
  15113. if (uri[0] == '/') {
  15114. /* relative uri */
  15115. return 2;
  15116. }
  15117. /* It could be an absolute uri: */
  15118. /* This function only checks if the uri is valid, not if it is
  15119. * addressing the current server. So civetweb can also be used
  15120. * as a proxy server. */
  15121. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15122. if (mg_strncasecmp(uri,
  15123. abs_uri_protocols[i].proto,
  15124. abs_uri_protocols[i].proto_len)
  15125. == 0) {
  15126. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15127. if (!hostend) {
  15128. return 0;
  15129. }
  15130. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15131. if (!portbegin) {
  15132. return 3;
  15133. }
  15134. port = strtoul(portbegin + 1, &portend, 10);
  15135. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15136. return 0;
  15137. }
  15138. return 4;
  15139. }
  15140. }
  15141. return 0;
  15142. }
  15143. /* Return NULL or the relative uri at the current server */
  15144. static const char *
  15145. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15146. {
  15147. const char *server_domain;
  15148. size_t server_domain_len;
  15149. size_t request_domain_len = 0;
  15150. unsigned long port = 0;
  15151. int i, auth_domain_check_enabled;
  15152. const char *hostbegin = NULL;
  15153. const char *hostend = NULL;
  15154. const char *portbegin;
  15155. char *portend;
  15156. auth_domain_check_enabled =
  15157. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15158. /* DNS is case insensitive, so use case insensitive string compare here
  15159. */
  15160. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15161. if (mg_strncasecmp(uri,
  15162. abs_uri_protocols[i].proto,
  15163. abs_uri_protocols[i].proto_len)
  15164. == 0) {
  15165. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15166. hostend = strchr(hostbegin, '/');
  15167. if (!hostend) {
  15168. return 0;
  15169. }
  15170. portbegin = strchr(hostbegin, ':');
  15171. if ((!portbegin) || (portbegin > hostend)) {
  15172. port = abs_uri_protocols[i].default_port;
  15173. request_domain_len = (size_t)(hostend - hostbegin);
  15174. } else {
  15175. port = strtoul(portbegin + 1, &portend, 10);
  15176. if ((portend != hostend) || (port <= 0)
  15177. || !is_valid_port(port)) {
  15178. return 0;
  15179. }
  15180. request_domain_len = (size_t)(portbegin - hostbegin);
  15181. }
  15182. /* protocol found, port set */
  15183. break;
  15184. }
  15185. }
  15186. if (!port) {
  15187. /* port remains 0 if the protocol is not found */
  15188. return 0;
  15189. }
  15190. /* Check if the request is directed to a different server. */
  15191. /* First check if the port is the same (IPv4 and IPv6). */
  15192. #if defined(USE_IPV6)
  15193. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  15194. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  15195. /* Request is directed to a different port */
  15196. return 0;
  15197. }
  15198. } else
  15199. #endif
  15200. {
  15201. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  15202. /* Request is directed to a different port */
  15203. return 0;
  15204. }
  15205. }
  15206. /* Finally check if the server corresponds to the authentication
  15207. * domain of the server (the server domain).
  15208. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15209. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15210. * but do not allow substrings (like
  15211. * http://notmydomain.com/path/file.ext
  15212. * or http://mydomain.com.fake/path/file.ext).
  15213. */
  15214. if (auth_domain_check_enabled) {
  15215. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15216. server_domain_len = strlen(server_domain);
  15217. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15218. return 0;
  15219. }
  15220. if ((request_domain_len == server_domain_len)
  15221. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15222. /* Request is directed to this server - full name match. */
  15223. } else {
  15224. if (request_domain_len < (server_domain_len + 2)) {
  15225. /* Request is directed to another server: The server name
  15226. * is longer than the request name.
  15227. * Drop this case here to avoid overflows in the
  15228. * following checks. */
  15229. return 0;
  15230. }
  15231. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15232. /* Request is directed to another server: It could be a
  15233. * substring
  15234. * like notmyserver.com */
  15235. return 0;
  15236. }
  15237. if (0
  15238. != memcmp(server_domain,
  15239. hostbegin + request_domain_len - server_domain_len,
  15240. server_domain_len)) {
  15241. /* Request is directed to another server:
  15242. * The server name is different. */
  15243. return 0;
  15244. }
  15245. }
  15246. }
  15247. return hostend;
  15248. }
  15249. static int
  15250. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15251. {
  15252. if (ebuf_len > 0) {
  15253. ebuf[0] = '\0';
  15254. }
  15255. *err = 0;
  15256. reset_per_request_attributes(conn);
  15257. if (!conn) {
  15258. mg_snprintf(conn,
  15259. NULL, /* No truncation check for ebuf */
  15260. ebuf,
  15261. ebuf_len,
  15262. "%s",
  15263. "Internal error");
  15264. *err = 500;
  15265. return 0;
  15266. }
  15267. /* Set the time the request was received. This value should be used for
  15268. * timeouts. */
  15269. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15270. conn->request_len =
  15271. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15272. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15273. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15274. mg_snprintf(conn,
  15275. NULL, /* No truncation check for ebuf */
  15276. ebuf,
  15277. ebuf_len,
  15278. "%s",
  15279. "Invalid message size");
  15280. *err = 500;
  15281. return 0;
  15282. }
  15283. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15284. mg_snprintf(conn,
  15285. NULL, /* No truncation check for ebuf */
  15286. ebuf,
  15287. ebuf_len,
  15288. "%s",
  15289. "Message too large");
  15290. *err = 413;
  15291. return 0;
  15292. }
  15293. if (conn->request_len <= 0) {
  15294. if (conn->data_len > 0) {
  15295. mg_snprintf(conn,
  15296. NULL, /* No truncation check for ebuf */
  15297. ebuf,
  15298. ebuf_len,
  15299. "%s",
  15300. "Malformed message");
  15301. *err = 400;
  15302. } else {
  15303. /* Server did not recv anything -> just close the connection */
  15304. conn->must_close = 1;
  15305. mg_snprintf(conn,
  15306. NULL, /* No truncation check for ebuf */
  15307. ebuf,
  15308. ebuf_len,
  15309. "%s",
  15310. "No data received");
  15311. *err = 0;
  15312. }
  15313. return 0;
  15314. }
  15315. return 1;
  15316. }
  15317. static int
  15318. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15319. {
  15320. const char *cl;
  15321. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15322. return 0;
  15323. }
  15324. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15325. <= 0) {
  15326. mg_snprintf(conn,
  15327. NULL, /* No truncation check for ebuf */
  15328. ebuf,
  15329. ebuf_len,
  15330. "%s",
  15331. "Bad request");
  15332. *err = 400;
  15333. return 0;
  15334. }
  15335. /* Message is a valid request */
  15336. /* Is there a "host" ? */
  15337. if (conn->host != NULL) {
  15338. mg_free((void *)conn->host);
  15339. }
  15340. conn->host = alloc_get_host(conn);
  15341. if (!conn->host) {
  15342. mg_snprintf(conn,
  15343. NULL, /* No truncation check for ebuf */
  15344. ebuf,
  15345. ebuf_len,
  15346. "%s",
  15347. "Bad request: Host mismatch");
  15348. *err = 400;
  15349. return 0;
  15350. }
  15351. if (((cl = get_header(conn->request_info.http_headers,
  15352. conn->request_info.num_headers,
  15353. "Transfer-Encoding"))
  15354. != NULL)
  15355. && mg_strcasecmp(cl, "identity")) {
  15356. if (mg_strcasecmp(cl, "chunked")) {
  15357. mg_snprintf(conn,
  15358. NULL, /* No truncation check for ebuf */
  15359. ebuf,
  15360. ebuf_len,
  15361. "%s",
  15362. "Bad request");
  15363. *err = 400;
  15364. return 0;
  15365. }
  15366. conn->is_chunked = 1;
  15367. conn->content_len = 0; /* not yet read */
  15368. } else if ((cl = get_header(conn->request_info.http_headers,
  15369. conn->request_info.num_headers,
  15370. "Content-Length"))
  15371. != NULL) {
  15372. /* Request has content length set */
  15373. char *endptr = NULL;
  15374. conn->content_len = strtoll(cl, &endptr, 10);
  15375. if ((endptr == cl) || (conn->content_len < 0)) {
  15376. mg_snprintf(conn,
  15377. NULL, /* No truncation check for ebuf */
  15378. ebuf,
  15379. ebuf_len,
  15380. "%s",
  15381. "Bad request");
  15382. *err = 411;
  15383. return 0;
  15384. }
  15385. /* Publish the content length back to the request info. */
  15386. conn->request_info.content_length = conn->content_len;
  15387. } else {
  15388. /* There is no exception, see RFC7230. */
  15389. conn->content_len = 0;
  15390. }
  15391. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15392. return 1;
  15393. }
  15394. /* conn is assumed to be valid in this internal function */
  15395. static int
  15396. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15397. {
  15398. const char *cl;
  15399. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15400. return 0;
  15401. }
  15402. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15403. <= 0) {
  15404. mg_snprintf(conn,
  15405. NULL, /* No truncation check for ebuf */
  15406. ebuf,
  15407. ebuf_len,
  15408. "%s",
  15409. "Bad response");
  15410. *err = 400;
  15411. return 0;
  15412. }
  15413. /* Message is a valid response */
  15414. if (((cl = get_header(conn->response_info.http_headers,
  15415. conn->response_info.num_headers,
  15416. "Transfer-Encoding"))
  15417. != NULL)
  15418. && mg_strcasecmp(cl, "identity")) {
  15419. if (mg_strcasecmp(cl, "chunked")) {
  15420. mg_snprintf(conn,
  15421. NULL, /* No truncation check for ebuf */
  15422. ebuf,
  15423. ebuf_len,
  15424. "%s",
  15425. "Bad request");
  15426. *err = 400;
  15427. return 0;
  15428. }
  15429. conn->is_chunked = 1;
  15430. conn->content_len = 0; /* not yet read */
  15431. } else if ((cl = get_header(conn->response_info.http_headers,
  15432. conn->response_info.num_headers,
  15433. "Content-Length"))
  15434. != NULL) {
  15435. char *endptr = NULL;
  15436. conn->content_len = strtoll(cl, &endptr, 10);
  15437. if ((endptr == cl) || (conn->content_len < 0)) {
  15438. mg_snprintf(conn,
  15439. NULL, /* No truncation check for ebuf */
  15440. ebuf,
  15441. ebuf_len,
  15442. "%s",
  15443. "Bad request");
  15444. *err = 411;
  15445. return 0;
  15446. }
  15447. /* Publish the content length back to the response info. */
  15448. conn->response_info.content_length = conn->content_len;
  15449. /* TODO: check if it is still used in response_info */
  15450. conn->request_info.content_length = conn->content_len;
  15451. /* TODO: we should also consider HEAD method */
  15452. if (conn->response_info.status_code == 304) {
  15453. conn->content_len = 0;
  15454. }
  15455. } else {
  15456. /* TODO: we should also consider HEAD method */
  15457. if (((conn->response_info.status_code >= 100)
  15458. && (conn->response_info.status_code <= 199))
  15459. || (conn->response_info.status_code == 204)
  15460. || (conn->response_info.status_code == 304)) {
  15461. conn->content_len = 0;
  15462. } else {
  15463. conn->content_len = -1; /* unknown content length */
  15464. }
  15465. }
  15466. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15467. return 1;
  15468. }
  15469. int
  15470. mg_get_response(struct mg_connection *conn,
  15471. char *ebuf,
  15472. size_t ebuf_len,
  15473. int timeout)
  15474. {
  15475. int err, ret;
  15476. char txt[32]; /* will not overflow */
  15477. char *save_timeout;
  15478. char *new_timeout;
  15479. if (ebuf_len > 0) {
  15480. ebuf[0] = '\0';
  15481. }
  15482. if (!conn) {
  15483. mg_snprintf(conn,
  15484. NULL, /* No truncation check for ebuf */
  15485. ebuf,
  15486. ebuf_len,
  15487. "%s",
  15488. "Parameter error");
  15489. return -1;
  15490. }
  15491. /* Reset the previous responses */
  15492. conn->data_len = 0;
  15493. /* Implementation of API function for HTTP clients */
  15494. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15495. if (timeout >= 0) {
  15496. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15497. new_timeout = txt;
  15498. } else {
  15499. new_timeout = NULL;
  15500. }
  15501. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15502. ret = get_response(conn, ebuf, ebuf_len, &err);
  15503. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15504. #if defined(MG_LEGACY_INTERFACE)
  15505. /* TODO: 1) uri is deprecated;
  15506. * 2) here, ri.uri is the http response code */
  15507. conn->request_info.uri = conn->request_info.request_uri;
  15508. #endif
  15509. conn->request_info.local_uri = conn->request_info.request_uri;
  15510. /* TODO (mid): Define proper return values - maybe return length?
  15511. * For the first test use <0 for error and >0 for OK */
  15512. return (ret == 0) ? -1 : +1;
  15513. }
  15514. struct mg_connection *
  15515. mg_download(const char *host,
  15516. int port,
  15517. int use_ssl,
  15518. char *ebuf,
  15519. size_t ebuf_len,
  15520. const char *fmt,
  15521. ...)
  15522. {
  15523. struct mg_connection *conn;
  15524. va_list ap;
  15525. int i;
  15526. int reqerr;
  15527. if (ebuf_len > 0) {
  15528. ebuf[0] = '\0';
  15529. }
  15530. va_start(ap, fmt);
  15531. /* open a connection */
  15532. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15533. if (conn != NULL) {
  15534. i = mg_vprintf(conn, fmt, ap);
  15535. if (i <= 0) {
  15536. mg_snprintf(conn,
  15537. NULL, /* No truncation check for ebuf */
  15538. ebuf,
  15539. ebuf_len,
  15540. "%s",
  15541. "Error sending request");
  15542. } else {
  15543. /* make sure the buffer is clear */
  15544. conn->data_len = 0;
  15545. get_response(conn, ebuf, ebuf_len, &reqerr);
  15546. #if defined(MG_LEGACY_INTERFACE)
  15547. /* TODO: 1) uri is deprecated;
  15548. * 2) here, ri.uri is the http response code */
  15549. conn->request_info.uri = conn->request_info.request_uri;
  15550. #endif
  15551. conn->request_info.local_uri = conn->request_info.request_uri;
  15552. }
  15553. }
  15554. /* if an error occurred, close the connection */
  15555. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15556. mg_close_connection(conn);
  15557. conn = NULL;
  15558. }
  15559. va_end(ap);
  15560. return conn;
  15561. }
  15562. struct websocket_client_thread_data {
  15563. struct mg_connection *conn;
  15564. mg_websocket_data_handler data_handler;
  15565. mg_websocket_close_handler close_handler;
  15566. void *callback_data;
  15567. };
  15568. #if defined(USE_WEBSOCKET)
  15569. #if defined(_WIN32)
  15570. static unsigned __stdcall websocket_client_thread(void *data)
  15571. #else
  15572. static void *
  15573. websocket_client_thread(void *data)
  15574. #endif
  15575. {
  15576. struct websocket_client_thread_data *cdata =
  15577. (struct websocket_client_thread_data *)data;
  15578. void *user_thread_ptr = NULL;
  15579. #if !defined(_WIN32)
  15580. struct sigaction sa;
  15581. /* Ignore SIGPIPE */
  15582. memset(&sa, 0, sizeof(sa));
  15583. sa.sa_handler = SIG_IGN;
  15584. sigaction(SIGPIPE, &sa, NULL);
  15585. #endif
  15586. mg_set_thread_name("ws-clnt");
  15587. if (cdata->conn->phys_ctx) {
  15588. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15589. /* 3 indicates a websocket client thread */
  15590. /* TODO: check if conn->phys_ctx can be set */
  15591. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15592. cdata->conn->phys_ctx, 3);
  15593. }
  15594. }
  15595. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15596. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15597. if (cdata->close_handler != NULL) {
  15598. cdata->close_handler(cdata->conn, cdata->callback_data);
  15599. }
  15600. /* The websocket_client context has only this thread. If it runs out,
  15601. set the stop_flag to 2 (= "stopped"). */
  15602. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15603. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15604. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15605. 3,
  15606. user_thread_ptr);
  15607. }
  15608. mg_free((void *)cdata);
  15609. #if defined(_WIN32)
  15610. return 0;
  15611. #else
  15612. return NULL;
  15613. #endif
  15614. }
  15615. #endif
  15616. static struct mg_connection *
  15617. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15618. int use_ssl,
  15619. char *error_buffer,
  15620. size_t error_buffer_size,
  15621. const char *path,
  15622. const char *origin,
  15623. mg_websocket_data_handler data_func,
  15624. mg_websocket_close_handler close_func,
  15625. void *user_data)
  15626. {
  15627. struct mg_connection *conn = NULL;
  15628. #if defined(USE_WEBSOCKET)
  15629. struct websocket_client_thread_data *thread_data;
  15630. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15631. const char *handshake_req;
  15632. int port = client_options->port;
  15633. const char *host = client_options->host;
  15634. int i;
  15635. if (origin != NULL) {
  15636. handshake_req = "GET %s HTTP/1.1\r\n"
  15637. "Host: %s\r\n"
  15638. "Upgrade: websocket\r\n"
  15639. "Connection: Upgrade\r\n"
  15640. "Sec-WebSocket-Key: %s\r\n"
  15641. "Sec-WebSocket-Version: 13\r\n"
  15642. "Origin: %s\r\n"
  15643. "\r\n";
  15644. } else {
  15645. handshake_req = "GET %s HTTP/1.1\r\n"
  15646. "Host: %s\r\n"
  15647. "Upgrade: websocket\r\n"
  15648. "Connection: Upgrade\r\n"
  15649. "Sec-WebSocket-Key: %s\r\n"
  15650. "Sec-WebSocket-Version: 13\r\n"
  15651. "\r\n";
  15652. }
  15653. #if defined(__clang__)
  15654. #pragma clang diagnostic push
  15655. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15656. #endif
  15657. /* Establish the client connection and request upgrade */
  15658. conn =
  15659. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15660. if (conn == NULL) {
  15661. /* error_buffer already filled */
  15662. return NULL;
  15663. }
  15664. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15665. if (i <= 0) {
  15666. mg_snprintf(conn,
  15667. NULL, /* No truncation check for ebuf */
  15668. error_buffer,
  15669. error_buffer_size,
  15670. "%s",
  15671. "Error sending request");
  15672. mg_close_connection(conn);
  15673. return NULL;
  15674. }
  15675. conn->data_len = 0;
  15676. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15677. mg_close_connection(conn);
  15678. return NULL;
  15679. }
  15680. conn->request_info.local_uri = conn->request_info.request_uri;
  15681. #if defined(__clang__)
  15682. #pragma clang diagnostic pop
  15683. #endif
  15684. /* Connection object will be null if something goes wrong */
  15685. if (conn == NULL) {
  15686. if (!*error_buffer) {
  15687. /* There should be already an error message */
  15688. mg_snprintf(conn,
  15689. NULL, /* No truncation check for ebuf */
  15690. error_buffer,
  15691. error_buffer_size,
  15692. "Unexpected error");
  15693. }
  15694. return NULL;
  15695. }
  15696. if (conn->response_info.status_code != 101) {
  15697. /* We sent an "upgrade" request. For a correct websocket
  15698. * protocol handshake, we expect a "101 Continue" response.
  15699. * Otherwise it is a protocol violation. Maybe the HTTP
  15700. * Server does not know websockets. */
  15701. if (!*error_buffer) {
  15702. /* set an error, if not yet set */
  15703. mg_snprintf(conn,
  15704. NULL, /* No truncation check for ebuf */
  15705. error_buffer,
  15706. error_buffer_size,
  15707. "Unexpected server reply");
  15708. }
  15709. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15710. mg_close_connection(conn);
  15711. return NULL;
  15712. }
  15713. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15714. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15715. if (!thread_data) {
  15716. DEBUG_TRACE("%s\r\n", "Out of memory");
  15717. mg_close_connection(conn);
  15718. return NULL;
  15719. }
  15720. thread_data->conn = conn;
  15721. thread_data->data_handler = data_func;
  15722. thread_data->close_handler = close_func;
  15723. thread_data->callback_data = user_data;
  15724. conn->phys_ctx->worker_threadids =
  15725. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15726. if (!conn->phys_ctx->worker_threadids) {
  15727. DEBUG_TRACE("%s\r\n", "Out of memory");
  15728. mg_free(thread_data);
  15729. mg_close_connection(conn);
  15730. return NULL;
  15731. }
  15732. /* Now upgrade to ws/wss client context */
  15733. conn->phys_ctx->user_data = user_data;
  15734. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15735. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15736. /* Start a thread to read the websocket client connection
  15737. * This thread will automatically stop when mg_disconnect is
  15738. * called on the client connection */
  15739. if (mg_start_thread_with_id(websocket_client_thread,
  15740. thread_data,
  15741. conn->phys_ctx->worker_threadids)
  15742. != 0) {
  15743. conn->phys_ctx->cfg_worker_threads = 0;
  15744. mg_free(thread_data);
  15745. mg_close_connection(conn);
  15746. conn = NULL;
  15747. DEBUG_TRACE("%s",
  15748. "Websocket client connect thread could not be started\r\n");
  15749. }
  15750. #else
  15751. /* Appease "unused parameter" warnings */
  15752. (void)client_options;
  15753. (void)use_ssl;
  15754. (void)error_buffer;
  15755. (void)error_buffer_size;
  15756. (void)path;
  15757. (void)origin;
  15758. (void)user_data;
  15759. (void)data_func;
  15760. (void)close_func;
  15761. #endif
  15762. return conn;
  15763. }
  15764. struct mg_connection *
  15765. mg_connect_websocket_client(const char *host,
  15766. int port,
  15767. int use_ssl,
  15768. char *error_buffer,
  15769. size_t error_buffer_size,
  15770. const char *path,
  15771. const char *origin,
  15772. mg_websocket_data_handler data_func,
  15773. mg_websocket_close_handler close_func,
  15774. void *user_data)
  15775. {
  15776. struct mg_client_options client_options;
  15777. memset(&client_options, 0, sizeof(client_options));
  15778. client_options.host = host;
  15779. client_options.port = port;
  15780. return mg_connect_websocket_client_impl(&client_options,
  15781. use_ssl,
  15782. error_buffer,
  15783. error_buffer_size,
  15784. path,
  15785. origin,
  15786. data_func,
  15787. close_func,
  15788. user_data);
  15789. }
  15790. struct mg_connection *
  15791. mg_connect_websocket_client_secure(
  15792. const struct mg_client_options *client_options,
  15793. char *error_buffer,
  15794. size_t error_buffer_size,
  15795. const char *path,
  15796. const char *origin,
  15797. mg_websocket_data_handler data_func,
  15798. mg_websocket_close_handler close_func,
  15799. void *user_data)
  15800. {
  15801. if (!client_options) {
  15802. return NULL;
  15803. }
  15804. return mg_connect_websocket_client_impl(client_options,
  15805. 1,
  15806. error_buffer,
  15807. error_buffer_size,
  15808. path,
  15809. origin,
  15810. data_func,
  15811. close_func,
  15812. user_data);
  15813. }
  15814. /* Prepare connection data structure */
  15815. static void
  15816. init_connection(struct mg_connection *conn)
  15817. {
  15818. /* Is keep alive allowed by the server */
  15819. int keep_alive_enabled =
  15820. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15821. if (!keep_alive_enabled) {
  15822. conn->must_close = 1;
  15823. }
  15824. /* Important: on new connection, reset the receiving buffer. Credit
  15825. * goes to crule42. */
  15826. conn->data_len = 0;
  15827. conn->handled_requests = 0;
  15828. mg_set_user_connection_data(conn, NULL);
  15829. #if defined(USE_SERVER_STATS)
  15830. conn->conn_state = 2; /* init */
  15831. #endif
  15832. /* call the init_connection callback if assigned */
  15833. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15834. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15835. void *conn_data = NULL;
  15836. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15837. mg_set_user_connection_data(conn, conn_data);
  15838. }
  15839. }
  15840. }
  15841. /* Process a connection - may handle multiple requests
  15842. * using the same connection.
  15843. * Must be called with a valid connection (conn and
  15844. * conn->phys_ctx must be valid).
  15845. */
  15846. static void
  15847. process_new_connection(struct mg_connection *conn)
  15848. {
  15849. struct mg_request_info *ri = &conn->request_info;
  15850. int keep_alive, discard_len;
  15851. char ebuf[100];
  15852. const char *hostend;
  15853. int reqerr, uri_type;
  15854. #if defined(USE_SERVER_STATS)
  15855. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15856. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15857. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15858. /* could use atomic compare exchange, but this
  15859. * seems overkill for statistics data */
  15860. conn->phys_ctx->max_active_connections = mcon;
  15861. }
  15862. #endif
  15863. init_connection(conn);
  15864. DEBUG_TRACE("Start processing connection from %s",
  15865. conn->request_info.remote_addr);
  15866. /* Loop over multiple requests sent using the same connection
  15867. * (while "keep alive"). */
  15868. do {
  15869. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15870. conn->handled_requests + 1);
  15871. #if defined(USE_SERVER_STATS)
  15872. conn->conn_state = 3; /* ready */
  15873. #endif
  15874. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15875. /* The request sent by the client could not be understood by
  15876. * the server, or it was incomplete or a timeout. Send an
  15877. * error message and close the connection. */
  15878. if (reqerr > 0) {
  15879. DEBUG_ASSERT(ebuf[0] != '\0');
  15880. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15881. }
  15882. } else if (strcmp(ri->http_version, "1.0")
  15883. && strcmp(ri->http_version, "1.1")) {
  15884. /* HTTP/2 is not allowed here */
  15885. mg_snprintf(conn,
  15886. NULL, /* No truncation check for ebuf */
  15887. ebuf,
  15888. sizeof(ebuf),
  15889. "Bad HTTP version: [%s]",
  15890. ri->http_version);
  15891. mg_send_http_error(conn, 505, "%s", ebuf);
  15892. }
  15893. if (ebuf[0] == '\0') {
  15894. uri_type = get_uri_type(conn->request_info.request_uri);
  15895. switch (uri_type) {
  15896. case 1:
  15897. /* Asterisk */
  15898. conn->request_info.local_uri = 0;
  15899. /* TODO: Deal with '*'. */
  15900. break;
  15901. case 2:
  15902. /* relative uri */
  15903. conn->request_info.local_uri = conn->request_info.request_uri;
  15904. break;
  15905. case 3:
  15906. case 4:
  15907. /* absolute uri (with/without port) */
  15908. hostend = get_rel_url_at_current_server(
  15909. conn->request_info.request_uri, conn);
  15910. if (hostend) {
  15911. conn->request_info.local_uri = hostend;
  15912. } else {
  15913. conn->request_info.local_uri = NULL;
  15914. }
  15915. break;
  15916. default:
  15917. mg_snprintf(conn,
  15918. NULL, /* No truncation check for ebuf */
  15919. ebuf,
  15920. sizeof(ebuf),
  15921. "Invalid URI");
  15922. mg_send_http_error(conn, 400, "%s", ebuf);
  15923. conn->request_info.local_uri = NULL;
  15924. break;
  15925. }
  15926. #if defined(MG_LEGACY_INTERFACE)
  15927. /* Legacy before split into local_uri and request_uri */
  15928. conn->request_info.uri = conn->request_info.local_uri;
  15929. #endif
  15930. }
  15931. if (ebuf[0] != '\0') {
  15932. conn->protocol_type = -1;
  15933. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  15934. /* HTTP/1 allows protocol upgrade */
  15935. conn->protocol_type = should_switch_to_protocol(conn);
  15936. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15937. /* This will occur, if a HTTP/1.1 request should be upgraded
  15938. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15939. * Since most (all?) major browsers only support HTTP/2 using
  15940. * ALPN, this is hard to test and very low priority.
  15941. * Deactivate it (at least for now).
  15942. */
  15943. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15944. }
  15945. }
  15946. DEBUG_TRACE("http: %s, error: %s",
  15947. (ri->http_version ? ri->http_version : "none"),
  15948. (ebuf[0] ? ebuf : "none"));
  15949. if (ebuf[0] == '\0') {
  15950. if (conn->request_info.local_uri) {
  15951. /* handle request to local server */
  15952. #if defined(USE_SERVER_STATS)
  15953. conn->conn_state = 4; /* processing */
  15954. #endif
  15955. handle_request(conn);
  15956. #if defined(USE_SERVER_STATS)
  15957. conn->conn_state = 5; /* processed */
  15958. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15959. conn->consumed_content);
  15960. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15961. conn->num_bytes_sent);
  15962. #endif
  15963. DEBUG_TRACE("%s", "handle_request done");
  15964. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15965. conn->phys_ctx->callbacks.end_request(conn,
  15966. conn->status_code);
  15967. DEBUG_TRACE("%s", "end_request callback done");
  15968. }
  15969. log_access(conn);
  15970. } else {
  15971. /* TODO: handle non-local request (PROXY) */
  15972. conn->must_close = 1;
  15973. }
  15974. } else {
  15975. conn->must_close = 1;
  15976. }
  15977. if (ri->remote_user != NULL) {
  15978. mg_free((void *)ri->remote_user);
  15979. /* Important! When having connections with and without auth
  15980. * would cause double free and then crash */
  15981. ri->remote_user = NULL;
  15982. }
  15983. /* NOTE(lsm): order is important here. should_keep_alive() call
  15984. * is using parsed request, which will be invalid after
  15985. * memmove's below.
  15986. * Therefore, memorize should_keep_alive() result now for later
  15987. * use in loop exit condition. */
  15988. /* Enable it only if this request is completely discardable. */
  15989. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  15990. && should_keep_alive(conn) && (conn->content_len >= 0)
  15991. && (conn->request_len > 0)
  15992. && ((conn->is_chunked == 4)
  15993. || (!conn->is_chunked
  15994. && ((conn->consumed_content == conn->content_len)
  15995. || ((conn->request_len + conn->content_len)
  15996. <= conn->data_len))))
  15997. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  15998. if (keep_alive) {
  15999. /* Discard all buffered data for this request */
  16000. discard_len =
  16001. ((conn->request_len + conn->content_len) < conn->data_len)
  16002. ? (int)(conn->request_len + conn->content_len)
  16003. : conn->data_len;
  16004. conn->data_len -= discard_len;
  16005. if (conn->data_len > 0) {
  16006. DEBUG_TRACE("discard_len = %d", discard_len);
  16007. memmove(conn->buf,
  16008. conn->buf + discard_len,
  16009. (size_t)conn->data_len);
  16010. }
  16011. }
  16012. DEBUG_ASSERT(conn->data_len >= 0);
  16013. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16014. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16015. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16016. (long int)conn->data_len,
  16017. (long int)conn->buf_size);
  16018. break;
  16019. }
  16020. conn->handled_requests++;
  16021. } while (keep_alive);
  16022. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16023. conn->request_info.remote_addr,
  16024. difftime(time(NULL), conn->conn_birth_time));
  16025. close_connection(conn);
  16026. #if defined(USE_SERVER_STATS)
  16027. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16028. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16029. #endif
  16030. }
  16031. #if defined(ALTERNATIVE_QUEUE)
  16032. static void
  16033. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16034. {
  16035. unsigned int i;
  16036. while (!ctx->stop_flag) {
  16037. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16038. /* find a free worker slot and signal it */
  16039. if (ctx->client_socks[i].in_use == 2) {
  16040. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16041. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16042. ctx->client_socks[i] = *sp;
  16043. ctx->client_socks[i].in_use = 1;
  16044. /* socket has been moved to the consumer */
  16045. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16046. (void)event_signal(ctx->client_wait_events[i]);
  16047. return;
  16048. }
  16049. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16050. }
  16051. }
  16052. /* queue is full */
  16053. mg_sleep(1);
  16054. }
  16055. /* must consume */
  16056. set_blocking_mode(sp->sock);
  16057. closesocket(sp->sock);
  16058. }
  16059. static int
  16060. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16061. {
  16062. DEBUG_TRACE("%s", "going idle");
  16063. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16064. ctx->client_socks[thread_index].in_use = 2;
  16065. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16066. event_wait(ctx->client_wait_events[thread_index]);
  16067. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16068. *sp = ctx->client_socks[thread_index];
  16069. if (ctx->stop_flag) {
  16070. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16071. if (sp->in_use == 1) {
  16072. /* must consume */
  16073. set_blocking_mode(sp->sock);
  16074. closesocket(sp->sock);
  16075. }
  16076. return 0;
  16077. }
  16078. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16079. if (sp->in_use == 1) {
  16080. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16081. return 1;
  16082. }
  16083. /* must not reach here */
  16084. DEBUG_ASSERT(0);
  16085. return 0;
  16086. }
  16087. #else /* ALTERNATIVE_QUEUE */
  16088. /* Worker threads take accepted socket from the queue */
  16089. static int
  16090. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16091. {
  16092. (void)thread_index;
  16093. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16094. DEBUG_TRACE("%s", "going idle");
  16095. /* If the queue is empty, wait. We're idle at this point. */
  16096. while ((ctx->sq_head == ctx->sq_tail)
  16097. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16098. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16099. }
  16100. /* If we're stopping, sq_head may be equal to sq_tail. */
  16101. if (ctx->sq_head > ctx->sq_tail) {
  16102. /* Copy socket from the queue and increment tail */
  16103. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16104. ctx->sq_tail++;
  16105. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16106. /* Wrap pointers if needed */
  16107. while (ctx->sq_tail > ctx->sq_size) {
  16108. ctx->sq_tail -= ctx->sq_size;
  16109. ctx->sq_head -= ctx->sq_size;
  16110. }
  16111. }
  16112. (void)pthread_cond_signal(&ctx->sq_empty);
  16113. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16114. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16115. }
  16116. /* Master thread adds accepted socket to a queue */
  16117. static void
  16118. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16119. {
  16120. int queue_filled;
  16121. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16122. queue_filled = ctx->sq_head - ctx->sq_tail;
  16123. /* If the queue is full, wait */
  16124. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16125. && (queue_filled >= ctx->sq_size)) {
  16126. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16127. #if defined(USE_SERVER_STATS)
  16128. if (queue_filled > ctx->sq_max_fill) {
  16129. ctx->sq_max_fill = queue_filled;
  16130. }
  16131. #endif
  16132. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16133. ctx->sq_blocked = 0; /* Not blocked now */
  16134. queue_filled = ctx->sq_head - ctx->sq_tail;
  16135. }
  16136. if (queue_filled < ctx->sq_size) {
  16137. /* Copy socket to the queue and increment head */
  16138. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16139. ctx->sq_head++;
  16140. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16141. }
  16142. queue_filled = ctx->sq_head - ctx->sq_tail;
  16143. #if defined(USE_SERVER_STATS)
  16144. if (queue_filled > ctx->sq_max_fill) {
  16145. ctx->sq_max_fill = queue_filled;
  16146. }
  16147. #endif
  16148. (void)pthread_cond_signal(&ctx->sq_full);
  16149. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16150. }
  16151. #endif /* ALTERNATIVE_QUEUE */
  16152. static void
  16153. worker_thread_run(struct mg_connection *conn)
  16154. {
  16155. struct mg_context *ctx = conn->phys_ctx;
  16156. int thread_index;
  16157. struct mg_workerTLS tls;
  16158. #if defined(MG_LEGACY_INTERFACE)
  16159. uint32_t addr;
  16160. #endif
  16161. mg_set_thread_name("worker");
  16162. tls.is_master = 0;
  16163. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16164. #if defined(_WIN32)
  16165. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16166. #endif
  16167. /* Initialize thread local storage before calling any callback */
  16168. pthread_setspecific(sTlsKey, &tls);
  16169. /* Check if there is a user callback */
  16170. if (ctx->callbacks.init_thread) {
  16171. /* call init_thread for a worker thread (type 1), and store the
  16172. * return value */
  16173. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16174. } else {
  16175. /* No callback: set user pointer to NULL */
  16176. tls.user_ptr = NULL;
  16177. }
  16178. /* Connection structure has been pre-allocated */
  16179. thread_index = (int)(conn - ctx->worker_connections);
  16180. if ((thread_index < 0)
  16181. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16182. mg_cry_ctx_internal(ctx,
  16183. "Internal error: Invalid worker index %i",
  16184. thread_index);
  16185. return;
  16186. }
  16187. /* Request buffers are not pre-allocated. They are private to the
  16188. * request and do not contain any state information that might be
  16189. * of interest to anyone observing a server status. */
  16190. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16191. if (conn->buf == NULL) {
  16192. mg_cry_ctx_internal(
  16193. ctx,
  16194. "Out of memory: Cannot allocate buffer for worker %i",
  16195. thread_index);
  16196. return;
  16197. }
  16198. conn->buf_size = (int)ctx->max_request_size;
  16199. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16200. conn->host = NULL; /* until we have more information. */
  16201. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16202. conn->request_info.user_data = ctx->user_data;
  16203. /* Allocate a mutex for this connection to allow communication both
  16204. * within the request handler and from elsewhere in the application
  16205. */
  16206. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16207. mg_free(conn->buf);
  16208. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16209. return;
  16210. }
  16211. #if defined(USE_SERVER_STATS)
  16212. conn->conn_state = 1; /* not consumed */
  16213. #endif
  16214. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16215. * signal sq_empty condvar to wake up the master waiting in
  16216. * produce_socket() */
  16217. while (consume_socket(ctx, &conn->client, thread_index)) {
  16218. /* New connections must start with new protocol negotiation */
  16219. tls.alpn_proto = NULL;
  16220. #if defined(USE_SERVER_STATS)
  16221. conn->conn_close_time = 0;
  16222. #endif
  16223. conn->conn_birth_time = time(NULL);
  16224. /* Fill in IP, port info early so even if SSL setup below fails,
  16225. * error handler would have the corresponding info.
  16226. * Thanks to Johannes Winkelmann for the patch.
  16227. */
  16228. #if defined(USE_IPV6)
  16229. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  16230. conn->request_info.remote_port =
  16231. ntohs(conn->client.rsa.sin6.sin6_port);
  16232. } else
  16233. #endif
  16234. {
  16235. conn->request_info.remote_port =
  16236. ntohs(conn->client.rsa.sin.sin_port);
  16237. }
  16238. sockaddr_to_string(conn->request_info.remote_addr,
  16239. sizeof(conn->request_info.remote_addr),
  16240. &conn->client.rsa);
  16241. DEBUG_TRACE("Start processing connection from %s",
  16242. conn->request_info.remote_addr);
  16243. conn->request_info.is_ssl = conn->client.is_ssl;
  16244. if (conn->client.is_ssl) {
  16245. #if !defined(NO_SSL)
  16246. /* HTTPS connection */
  16247. if (sslize(conn,
  16248. SSL_accept,
  16249. NULL)) {
  16250. /* conn->dom_ctx is set in get_request */
  16251. /* Get SSL client certificate information (if set) */
  16252. struct mg_client_cert client_cert;
  16253. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16254. conn->request_info.client_cert = &client_cert;
  16255. }
  16256. /* process HTTPS connection */
  16257. #if defined(USE_HTTP2)
  16258. if ((tls.alpn_proto != NULL)
  16259. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16260. /* process HTTPS/2 connection */
  16261. init_connection(conn);
  16262. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16263. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16264. conn->content_len = -1;
  16265. conn->is_chunked = 0;
  16266. process_new_http2_connection(conn);
  16267. } else
  16268. #endif
  16269. {
  16270. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16271. process_new_connection(conn);
  16272. }
  16273. /* Free client certificate info */
  16274. if (conn->request_info.client_cert) {
  16275. mg_free((void *)(conn->request_info.client_cert->subject));
  16276. mg_free((void *)(conn->request_info.client_cert->issuer));
  16277. mg_free((void *)(conn->request_info.client_cert->serial));
  16278. mg_free((void *)(conn->request_info.client_cert->finger));
  16279. /* Free certificate memory */
  16280. X509_free(
  16281. (X509 *)conn->request_info.client_cert->peer_cert);
  16282. conn->request_info.client_cert->peer_cert = 0;
  16283. conn->request_info.client_cert->subject = 0;
  16284. conn->request_info.client_cert->issuer = 0;
  16285. conn->request_info.client_cert->serial = 0;
  16286. conn->request_info.client_cert->finger = 0;
  16287. conn->request_info.client_cert = 0;
  16288. }
  16289. } else {
  16290. /* make sure the connection is cleaned up on SSL failure */
  16291. close_connection(conn);
  16292. }
  16293. #endif
  16294. } else {
  16295. /* process HTTP connection */
  16296. process_new_connection(conn);
  16297. }
  16298. DEBUG_TRACE("%s", "Connection closed");
  16299. #if defined(USE_SERVER_STATS)
  16300. conn->conn_close_time = time(NULL);
  16301. #endif
  16302. }
  16303. /* Call exit thread user callback */
  16304. if (ctx->callbacks.exit_thread) {
  16305. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16306. }
  16307. /* delete thread local storage objects */
  16308. pthread_setspecific(sTlsKey, NULL);
  16309. #if defined(_WIN32)
  16310. CloseHandle(tls.pthread_cond_helper_mutex);
  16311. #endif
  16312. pthread_mutex_destroy(&conn->mutex);
  16313. /* Free the request buffer. */
  16314. conn->buf_size = 0;
  16315. mg_free(conn->buf);
  16316. conn->buf = NULL;
  16317. #if defined(USE_SERVER_STATS)
  16318. conn->conn_state = 9; /* done */
  16319. #endif
  16320. DEBUG_TRACE("%s", "exiting");
  16321. }
  16322. /* Threads have different return types on Windows and Unix. */
  16323. #if defined(_WIN32)
  16324. static unsigned __stdcall worker_thread(void *thread_func_param)
  16325. {
  16326. worker_thread_run((struct mg_connection *)thread_func_param);
  16327. return 0;
  16328. }
  16329. #else
  16330. static void *
  16331. worker_thread(void *thread_func_param)
  16332. {
  16333. #if !defined(__ZEPHYR__)
  16334. struct sigaction sa;
  16335. /* Ignore SIGPIPE */
  16336. memset(&sa, 0, sizeof(sa));
  16337. sa.sa_handler = SIG_IGN;
  16338. sigaction(SIGPIPE, &sa, NULL);
  16339. #endif
  16340. worker_thread_run((struct mg_connection *)thread_func_param);
  16341. return NULL;
  16342. }
  16343. #endif /* _WIN32 */
  16344. /* This is an internal function, thus all arguments are expected to be
  16345. * valid - a NULL check is not required. */
  16346. static void
  16347. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16348. {
  16349. struct socket so;
  16350. char src_addr[IP_ADDR_STR_LEN];
  16351. socklen_t len = sizeof(so.rsa);
  16352. #if !defined(__ZEPHYR__)
  16353. int on = 1;
  16354. #endif
  16355. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16356. == INVALID_SOCKET) {
  16357. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16358. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16359. mg_cry_ctx_internal(ctx,
  16360. "%s: %s is not allowed to connect",
  16361. __func__,
  16362. src_addr);
  16363. closesocket(so.sock);
  16364. } else {
  16365. /* Put so socket structure into the queue */
  16366. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16367. set_close_on_exec(so.sock, NULL, ctx);
  16368. so.is_ssl = listener->is_ssl;
  16369. so.ssl_redir = listener->ssl_redir;
  16370. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16371. mg_cry_ctx_internal(ctx,
  16372. "%s: getsockname() failed: %s",
  16373. __func__,
  16374. strerror(ERRNO));
  16375. }
  16376. #if !defined(__ZEPHYR__)
  16377. /* Set TCP keep-alive. This is needed because if HTTP-level
  16378. * keep-alive
  16379. * is enabled, and client resets the connection, server won't get
  16380. * TCP FIN or RST and will keep the connection open forever. With
  16381. * TCP keep-alive, next keep-alive handshake will figure out that
  16382. * the client is down and will close the server end.
  16383. * Thanks to Igor Klopov who suggested the patch. */
  16384. if (setsockopt(so.sock,
  16385. SOL_SOCKET,
  16386. SO_KEEPALIVE,
  16387. (SOCK_OPT_TYPE)&on,
  16388. sizeof(on))
  16389. != 0) {
  16390. mg_cry_ctx_internal(
  16391. ctx,
  16392. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16393. __func__,
  16394. strerror(ERRNO));
  16395. }
  16396. #endif
  16397. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16398. * to effectively fill up the underlying IP packet payload and
  16399. * reduce the overhead of sending lots of small buffers. However
  16400. * this hurts the server's throughput (ie. operations per second)
  16401. * when HTTP 1.1 persistent connections are used and the responses
  16402. * are relatively small (eg. less than 1400 bytes).
  16403. */
  16404. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16405. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16406. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16407. mg_cry_ctx_internal(
  16408. ctx,
  16409. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16410. __func__,
  16411. strerror(ERRNO));
  16412. }
  16413. }
  16414. /* The "non blocking" property should already be
  16415. * inherited from the parent socket. Set it for
  16416. * non-compliant socket implementations. */
  16417. set_non_blocking_mode(so.sock);
  16418. so.in_use = 0;
  16419. produce_socket(ctx, &so);
  16420. }
  16421. }
  16422. static void
  16423. master_thread_run(struct mg_context *ctx)
  16424. {
  16425. struct mg_workerTLS tls;
  16426. struct mg_pollfd *pfd;
  16427. unsigned int i;
  16428. unsigned int workerthreadcount;
  16429. if (!ctx) {
  16430. return;
  16431. }
  16432. mg_set_thread_name("master");
  16433. /* Increase priority of the master thread */
  16434. #if defined(_WIN32)
  16435. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16436. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16437. int min_prio = sched_get_priority_min(SCHED_RR);
  16438. int max_prio = sched_get_priority_max(SCHED_RR);
  16439. if ((min_prio >= 0) && (max_prio >= 0)
  16440. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16441. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16442. struct sched_param sched_param = {0};
  16443. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16444. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16445. }
  16446. #endif
  16447. /* Initialize thread local storage */
  16448. #if defined(_WIN32)
  16449. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16450. #endif
  16451. tls.is_master = 1;
  16452. pthread_setspecific(sTlsKey, &tls);
  16453. if (ctx->callbacks.init_thread) {
  16454. /* Callback for the master thread (type 0) */
  16455. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16456. } else {
  16457. tls.user_ptr = NULL;
  16458. }
  16459. /* Server starts *now* */
  16460. ctx->start_time = time(NULL);
  16461. /* Start the server */
  16462. pfd = ctx->listening_socket_fds;
  16463. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16464. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16465. pfd[i].fd = ctx->listening_sockets[i].sock;
  16466. pfd[i].events = POLLIN;
  16467. }
  16468. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16469. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16470. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16471. * successful poll, and POLLIN is defined as
  16472. * (POLLRDNORM | POLLRDBAND)
  16473. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16474. * pfd[i].revents == POLLIN. */
  16475. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16476. && (pfd[i].revents & POLLIN)) {
  16477. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16478. }
  16479. }
  16480. }
  16481. }
  16482. /* Here stop_flag is 1 - Initiate shutdown. */
  16483. DEBUG_TRACE("%s", "stopping workers");
  16484. /* Stop signal received: somebody called mg_stop. Quit. */
  16485. close_all_listening_sockets(ctx);
  16486. /* Wakeup workers that are waiting for connections to handle. */
  16487. #if defined(ALTERNATIVE_QUEUE)
  16488. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16489. event_signal(ctx->client_wait_events[i]);
  16490. }
  16491. #else
  16492. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16493. pthread_cond_broadcast(&ctx->sq_full);
  16494. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16495. #endif
  16496. /* Join all worker threads to avoid leaking threads. */
  16497. workerthreadcount = ctx->cfg_worker_threads;
  16498. for (i = 0; i < workerthreadcount; i++) {
  16499. if (ctx->worker_threadids[i] != 0) {
  16500. mg_join_thread(ctx->worker_threadids[i]);
  16501. }
  16502. }
  16503. #if defined(USE_LUA)
  16504. /* Free Lua state of lua background task */
  16505. if (ctx->lua_background_state) {
  16506. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16507. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16508. if (lua_istable(lstate, -1)) {
  16509. reg_boolean(lstate, "shutdown", 1);
  16510. lua_pop(lstate, 1);
  16511. mg_sleep(2);
  16512. }
  16513. lua_close(lstate);
  16514. ctx->lua_background_state = 0;
  16515. }
  16516. #endif
  16517. DEBUG_TRACE("%s", "exiting");
  16518. /* call exit thread callback */
  16519. if (ctx->callbacks.exit_thread) {
  16520. /* Callback for the master thread (type 0) */
  16521. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16522. }
  16523. #if defined(_WIN32)
  16524. CloseHandle(tls.pthread_cond_helper_mutex);
  16525. #endif
  16526. pthread_setspecific(sTlsKey, NULL);
  16527. /* Signal mg_stop() that we're done.
  16528. * WARNING: This must be the very last thing this
  16529. * thread does, as ctx becomes invalid after this line. */
  16530. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16531. }
  16532. /* Threads have different return types on Windows and Unix. */
  16533. #if defined(_WIN32)
  16534. static unsigned __stdcall master_thread(void *thread_func_param)
  16535. {
  16536. master_thread_run((struct mg_context *)thread_func_param);
  16537. return 0;
  16538. }
  16539. #else
  16540. static void *
  16541. master_thread(void *thread_func_param)
  16542. {
  16543. #if !defined(__ZEPHYR__)
  16544. struct sigaction sa;
  16545. /* Ignore SIGPIPE */
  16546. memset(&sa, 0, sizeof(sa));
  16547. sa.sa_handler = SIG_IGN;
  16548. sigaction(SIGPIPE, &sa, NULL);
  16549. #endif
  16550. master_thread_run((struct mg_context *)thread_func_param);
  16551. return NULL;
  16552. }
  16553. #endif /* _WIN32 */
  16554. static void
  16555. free_context(struct mg_context *ctx)
  16556. {
  16557. int i;
  16558. struct mg_handler_info *tmp_rh;
  16559. if (ctx == NULL) {
  16560. return;
  16561. }
  16562. if (ctx->callbacks.exit_context) {
  16563. ctx->callbacks.exit_context(ctx);
  16564. }
  16565. /* All threads exited, no sync is needed. Destroy thread mutex and
  16566. * condvars
  16567. */
  16568. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16569. #if defined(ALTERNATIVE_QUEUE)
  16570. mg_free(ctx->client_socks);
  16571. if (ctx->client_wait_events != NULL) {
  16572. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16573. event_destroy(ctx->client_wait_events[i]);
  16574. }
  16575. mg_free(ctx->client_wait_events);
  16576. }
  16577. #else
  16578. (void)pthread_cond_destroy(&ctx->sq_empty);
  16579. (void)pthread_cond_destroy(&ctx->sq_full);
  16580. mg_free(ctx->squeue);
  16581. #endif
  16582. /* Destroy other context global data structures mutex */
  16583. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16584. #if defined(USE_TIMERS)
  16585. timers_exit(ctx);
  16586. #endif
  16587. /* Deallocate config parameters */
  16588. for (i = 0; i < NUM_OPTIONS; i++) {
  16589. if (ctx->dd.config[i] != NULL) {
  16590. #if defined(_MSC_VER)
  16591. #pragma warning(suppress : 6001)
  16592. #endif
  16593. mg_free(ctx->dd.config[i]);
  16594. }
  16595. }
  16596. /* Deallocate request handlers */
  16597. while (ctx->dd.handlers) {
  16598. tmp_rh = ctx->dd.handlers;
  16599. ctx->dd.handlers = tmp_rh->next;
  16600. mg_free(tmp_rh->uri);
  16601. mg_free(tmp_rh);
  16602. }
  16603. #if !defined(NO_SSL)
  16604. /* Deallocate SSL context */
  16605. if (ctx->dd.ssl_ctx != NULL) {
  16606. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16607. int callback_ret =
  16608. (ctx->callbacks.external_ssl_ctx == NULL)
  16609. ? 0
  16610. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16611. if (callback_ret == 0) {
  16612. SSL_CTX_free(ctx->dd.ssl_ctx);
  16613. }
  16614. /* else: ignore error and ommit SSL_CTX_free in case
  16615. * callback_ret is 1 */
  16616. }
  16617. #endif /* !NO_SSL */
  16618. /* Deallocate worker thread ID array */
  16619. mg_free(ctx->worker_threadids);
  16620. /* Deallocate worker thread ID array */
  16621. mg_free(ctx->worker_connections);
  16622. /* deallocate system name string */
  16623. mg_free(ctx->systemName);
  16624. /* Deallocate context itself */
  16625. mg_free(ctx);
  16626. }
  16627. void
  16628. mg_stop(struct mg_context *ctx)
  16629. {
  16630. pthread_t mt;
  16631. if (!ctx) {
  16632. return;
  16633. }
  16634. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16635. * two threads is not allowed. */
  16636. mt = ctx->masterthreadid;
  16637. if (mt == 0) {
  16638. return;
  16639. }
  16640. ctx->masterthreadid = 0;
  16641. /* Set stop flag, so all threads know they have to exit. */
  16642. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16643. /* Wait until everything has stopped. */
  16644. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16645. (void)mg_sleep(10);
  16646. }
  16647. mg_join_thread(mt);
  16648. free_context(ctx);
  16649. #if defined(_WIN32)
  16650. (void)WSACleanup();
  16651. #endif /* _WIN32 */
  16652. }
  16653. static void
  16654. get_system_name(char **sysName)
  16655. {
  16656. #if defined(_WIN32)
  16657. #if defined(_WIN32_WCE)
  16658. *sysName = mg_strdup("WinCE");
  16659. #else
  16660. char name[128];
  16661. DWORD dwVersion = 0;
  16662. DWORD dwMajorVersion = 0;
  16663. DWORD dwMinorVersion = 0;
  16664. DWORD dwBuild = 0;
  16665. BOOL wowRet, isWoW = FALSE;
  16666. #if defined(_MSC_VER)
  16667. #pragma warning(push)
  16668. /* GetVersion was declared deprecated */
  16669. #pragma warning(disable : 4996)
  16670. #endif
  16671. dwVersion = GetVersion();
  16672. #if defined(_MSC_VER)
  16673. #pragma warning(pop)
  16674. #endif
  16675. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16676. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16677. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16678. (void)dwBuild;
  16679. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16680. sprintf(name,
  16681. "Windows %u.%u%s",
  16682. (unsigned)dwMajorVersion,
  16683. (unsigned)dwMinorVersion,
  16684. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16685. *sysName = mg_strdup(name);
  16686. #endif
  16687. #elif defined(__ZEPHYR__)
  16688. *sysName = mg_strdup("Zephyr OS");
  16689. #else
  16690. struct utsname name;
  16691. memset(&name, 0, sizeof(name));
  16692. uname(&name);
  16693. *sysName = mg_strdup(name.sysname);
  16694. #endif
  16695. }
  16696. static void
  16697. legacy_init(const char **options)
  16698. {
  16699. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16700. if (options) {
  16701. const char **run_options = options;
  16702. const char *optname = config_options[LISTENING_PORTS].name;
  16703. /* Try to find the "listening_ports" option */
  16704. while (*run_options) {
  16705. if (!strcmp(*run_options, optname)) {
  16706. ports_option = run_options[1];
  16707. }
  16708. run_options += 2;
  16709. }
  16710. }
  16711. if (is_ssl_port_used(ports_option)) {
  16712. /* Initialize with SSL support */
  16713. mg_init_library(MG_FEATURES_TLS);
  16714. } else {
  16715. /* Initialize without SSL support */
  16716. mg_init_library(MG_FEATURES_DEFAULT);
  16717. }
  16718. }
  16719. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16720. static
  16721. #endif
  16722. struct mg_context *
  16723. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16724. {
  16725. struct mg_context *ctx;
  16726. const char *name, *value, *default_value;
  16727. int idx, ok, workerthreadcount;
  16728. unsigned int i;
  16729. int itmp;
  16730. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16731. const char **options =
  16732. ((init != NULL) ? (init->configuration_options) : (NULL));
  16733. struct mg_workerTLS tls;
  16734. #if defined(_WIN32)
  16735. WSADATA data;
  16736. WSAStartup(MAKEWORD(2, 2), &data);
  16737. #endif /* _WIN32 */
  16738. if (error != NULL) {
  16739. error->code = 0;
  16740. if (error->text_buffer_size > 0) {
  16741. *error->text = 0;
  16742. }
  16743. }
  16744. if (mg_init_library_called == 0) {
  16745. /* Legacy INIT, if mg_start is called without mg_init_library.
  16746. * Note: This will cause a memory leak when unloading the library.
  16747. */
  16748. legacy_init(options);
  16749. }
  16750. /* Allocate context and initialize reasonable general case defaults. */
  16751. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16752. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16753. mg_snprintf(NULL,
  16754. NULL, /* No truncation check for error buffers */
  16755. error->text,
  16756. error->text_buffer_size,
  16757. "%s",
  16758. "Out of memory");
  16759. }
  16760. return NULL;
  16761. }
  16762. /* Random number generator will initialize at the first call */
  16763. ctx->dd.auth_nonce_mask =
  16764. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16765. /* Save started thread index to reuse in other external API calls
  16766. * For the sake of thread synchronization all non-civetweb threads
  16767. * can be considered as single external thread */
  16768. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16769. tls.is_master = -1; /* Thread calling mg_start */
  16770. tls.thread_idx = ctx->starter_thread_idx;
  16771. #if defined(_WIN32)
  16772. tls.pthread_cond_helper_mutex = NULL;
  16773. #endif
  16774. pthread_setspecific(sTlsKey, &tls);
  16775. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16776. #if !defined(ALTERNATIVE_QUEUE)
  16777. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16778. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16779. ctx->sq_blocked = 0;
  16780. #endif
  16781. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16782. if (!ok) {
  16783. const char *err_msg =
  16784. "Cannot initialize thread synchronization objects";
  16785. /* Fatal error - abort start. However, this situation should never
  16786. * occur in practice. */
  16787. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16788. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16789. mg_snprintf(NULL,
  16790. NULL, /* No truncation check for error buffers */
  16791. error->text,
  16792. error->text_buffer_size,
  16793. "%s",
  16794. err_msg);
  16795. }
  16796. mg_free(ctx);
  16797. pthread_setspecific(sTlsKey, NULL);
  16798. return NULL;
  16799. }
  16800. if ((init != NULL) && (init->callbacks != NULL)) {
  16801. /* Set all callbacks except exit_context. */
  16802. ctx->callbacks = *init->callbacks;
  16803. exit_callback = init->callbacks->exit_context;
  16804. /* The exit callback is activated once the context is successfully
  16805. * created. It should not be called, if an incomplete context object
  16806. * is deleted during a failed initialization. */
  16807. ctx->callbacks.exit_context = 0;
  16808. }
  16809. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16810. ctx->dd.handlers = NULL;
  16811. ctx->dd.next = NULL;
  16812. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16813. ctx->dd.shared_lua_websockets = NULL;
  16814. #endif
  16815. /* Store options */
  16816. while (options && (name = *options++) != NULL) {
  16817. if ((idx = get_option_index(name)) == -1) {
  16818. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16819. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16820. mg_snprintf(NULL,
  16821. NULL, /* No truncation check for error buffers */
  16822. error->text,
  16823. error->text_buffer_size,
  16824. "Invalid configuration option: %s",
  16825. name);
  16826. }
  16827. free_context(ctx);
  16828. pthread_setspecific(sTlsKey, NULL);
  16829. return NULL;
  16830. } else if ((value = *options++) == NULL) {
  16831. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16832. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16833. mg_snprintf(NULL,
  16834. NULL, /* No truncation check for error buffers */
  16835. error->text,
  16836. error->text_buffer_size,
  16837. "Invalid configuration option value: %s",
  16838. name);
  16839. }
  16840. free_context(ctx);
  16841. pthread_setspecific(sTlsKey, NULL);
  16842. return NULL;
  16843. }
  16844. if (ctx->dd.config[idx] != NULL) {
  16845. /* A duplicate configuration option is not an error - the last
  16846. * option value will be used. */
  16847. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16848. mg_free(ctx->dd.config[idx]);
  16849. }
  16850. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16851. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16852. }
  16853. /* Set default value if needed */
  16854. for (i = 0; config_options[i].name != NULL; i++) {
  16855. default_value = config_options[i].default_value;
  16856. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16857. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16858. }
  16859. }
  16860. /* Request size option */
  16861. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16862. if (itmp < 1024) {
  16863. mg_cry_ctx_internal(ctx,
  16864. "%s too small",
  16865. config_options[MAX_REQUEST_SIZE].name);
  16866. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16867. mg_snprintf(NULL,
  16868. NULL, /* No truncation check for error buffers */
  16869. error->text,
  16870. error->text_buffer_size,
  16871. "Invalid configuration option value: %s",
  16872. config_options[MAX_REQUEST_SIZE].name);
  16873. }
  16874. free_context(ctx);
  16875. pthread_setspecific(sTlsKey, NULL);
  16876. return NULL;
  16877. }
  16878. ctx->max_request_size = (unsigned)itmp;
  16879. /* Queue length */
  16880. #if !defined(ALTERNATIVE_QUEUE)
  16881. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16882. if (itmp < 1) {
  16883. mg_cry_ctx_internal(ctx,
  16884. "%s too small",
  16885. config_options[CONNECTION_QUEUE_SIZE].name);
  16886. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16887. mg_snprintf(NULL,
  16888. NULL, /* No truncation check for error buffers */
  16889. error->text,
  16890. error->text_buffer_size,
  16891. "Invalid configuration option value: %s",
  16892. config_options[CONNECTION_QUEUE_SIZE].name);
  16893. }
  16894. free_context(ctx);
  16895. pthread_setspecific(sTlsKey, NULL);
  16896. return NULL;
  16897. }
  16898. ctx->squeue =
  16899. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16900. if (ctx->squeue == NULL) {
  16901. mg_cry_ctx_internal(ctx,
  16902. "Out of memory: Cannot allocate %s",
  16903. config_options[CONNECTION_QUEUE_SIZE].name);
  16904. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16905. mg_snprintf(NULL,
  16906. NULL, /* No truncation check for error buffers */
  16907. error->text,
  16908. error->text_buffer_size,
  16909. "Out of memory: Cannot allocate %s",
  16910. config_options[CONNECTION_QUEUE_SIZE].name);
  16911. }
  16912. free_context(ctx);
  16913. pthread_setspecific(sTlsKey, NULL);
  16914. return NULL;
  16915. }
  16916. ctx->sq_size = itmp;
  16917. #endif
  16918. /* Worker thread count option */
  16919. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16920. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16921. if (workerthreadcount <= 0) {
  16922. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16923. } else {
  16924. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16925. }
  16926. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16927. mg_snprintf(NULL,
  16928. NULL, /* No truncation check for error buffers */
  16929. error->text,
  16930. error->text_buffer_size,
  16931. "Invalid configuration option value: %s",
  16932. config_options[NUM_THREADS].name);
  16933. }
  16934. free_context(ctx);
  16935. pthread_setspecific(sTlsKey, NULL);
  16936. return NULL;
  16937. }
  16938. /* Document root */
  16939. #if defined(NO_FILES)
  16940. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16941. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16942. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16943. mg_snprintf(NULL,
  16944. NULL, /* No truncation check for error buffers */
  16945. error->text,
  16946. error->text_buffer_size,
  16947. "Invalid configuration option value: %s",
  16948. config_options[DOCUMENT_ROOT].name);
  16949. }
  16950. free_context(ctx);
  16951. pthread_setspecific(sTlsKey, NULL);
  16952. return NULL;
  16953. }
  16954. #endif
  16955. get_system_name(&ctx->systemName);
  16956. #if defined(USE_LUA)
  16957. /* If a Lua background script has been configured, start it. */
  16958. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16959. char ebuf[256];
  16960. struct vec opt_vec;
  16961. struct vec eq_vec;
  16962. const char *sparams;
  16963. lua_State *state = mg_prepare_lua_context_script(
  16964. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16965. if (!state) {
  16966. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16967. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16968. mg_snprintf(NULL,
  16969. NULL, /* No truncation check for error buffers */
  16970. error->text,
  16971. error->text_buffer_size,
  16972. "Error in script %s: %s",
  16973. config_options[DOCUMENT_ROOT].name,
  16974. ebuf);
  16975. }
  16976. free_context(ctx);
  16977. pthread_setspecific(sTlsKey, NULL);
  16978. return NULL;
  16979. }
  16980. ctx->lua_background_state = (void *)state;
  16981. lua_newtable(state);
  16982. reg_boolean(state, "shutdown", 0);
  16983. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16984. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16985. reg_llstring(
  16986. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16987. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16988. break;
  16989. }
  16990. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16991. } else {
  16992. ctx->lua_background_state = 0;
  16993. }
  16994. #endif
  16995. /* Step by step initialization of ctx - depending on build options */
  16996. #if !defined(NO_FILESYSTEMS)
  16997. if (!set_gpass_option(ctx, NULL)) {
  16998. const char *err_msg = "Invalid global password file";
  16999. /* Fatal error - abort start. */
  17000. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17001. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17002. mg_snprintf(NULL,
  17003. NULL, /* No truncation check for error buffers */
  17004. error->text,
  17005. error->text_buffer_size,
  17006. "%s",
  17007. err_msg);
  17008. }
  17009. free_context(ctx);
  17010. pthread_setspecific(sTlsKey, NULL);
  17011. return NULL;
  17012. }
  17013. #endif
  17014. #if !defined(NO_SSL)
  17015. if (!init_ssl_ctx(ctx, NULL)) {
  17016. const char *err_msg = "Error initializing SSL context";
  17017. /* Fatal error - abort start. */
  17018. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17019. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17020. mg_snprintf(NULL,
  17021. NULL, /* No truncation check for error buffers */
  17022. error->text,
  17023. error->text_buffer_size,
  17024. "%s",
  17025. err_msg);
  17026. }
  17027. free_context(ctx);
  17028. pthread_setspecific(sTlsKey, NULL);
  17029. return NULL;
  17030. }
  17031. #endif
  17032. if (!set_ports_option(ctx)) {
  17033. const char *err_msg = "Failed to setup server ports";
  17034. /* Fatal error - abort start. */
  17035. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17036. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17037. mg_snprintf(NULL,
  17038. NULL, /* No truncation check for error buffers */
  17039. error->text,
  17040. error->text_buffer_size,
  17041. "%s",
  17042. err_msg);
  17043. }
  17044. free_context(ctx);
  17045. pthread_setspecific(sTlsKey, NULL);
  17046. return NULL;
  17047. }
  17048. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17049. if (!set_uid_option(ctx)) {
  17050. const char *err_msg = "Failed to run as configured user";
  17051. /* Fatal error - abort start. */
  17052. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17053. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17054. mg_snprintf(NULL,
  17055. NULL, /* No truncation check for error buffers */
  17056. error->text,
  17057. error->text_buffer_size,
  17058. "%s",
  17059. err_msg);
  17060. }
  17061. free_context(ctx);
  17062. pthread_setspecific(sTlsKey, NULL);
  17063. return NULL;
  17064. }
  17065. #endif
  17066. if (!set_acl_option(ctx)) {
  17067. const char *err_msg = "Failed to setup access control list";
  17068. /* Fatal error - abort start. */
  17069. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17070. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17071. mg_snprintf(NULL,
  17072. NULL, /* No truncation check for error buffers */
  17073. error->text,
  17074. error->text_buffer_size,
  17075. "%s",
  17076. err_msg);
  17077. }
  17078. free_context(ctx);
  17079. pthread_setspecific(sTlsKey, NULL);
  17080. return NULL;
  17081. }
  17082. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17083. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17084. sizeof(pthread_t),
  17085. ctx);
  17086. if (ctx->worker_threadids == NULL) {
  17087. const char *err_msg = "Not enough memory for worker thread ID array";
  17088. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17089. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17090. mg_snprintf(NULL,
  17091. NULL, /* No truncation check for error buffers */
  17092. error->text,
  17093. error->text_buffer_size,
  17094. "%s",
  17095. err_msg);
  17096. }
  17097. free_context(ctx);
  17098. pthread_setspecific(sTlsKey, NULL);
  17099. return NULL;
  17100. }
  17101. ctx->worker_connections =
  17102. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17103. sizeof(struct mg_connection),
  17104. ctx);
  17105. if (ctx->worker_connections == NULL) {
  17106. const char *err_msg =
  17107. "Not enough memory for worker thread connection array";
  17108. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17109. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17110. mg_snprintf(NULL,
  17111. NULL, /* No truncation check for error buffers */
  17112. error->text,
  17113. error->text_buffer_size,
  17114. "%s",
  17115. err_msg);
  17116. }
  17117. free_context(ctx);
  17118. pthread_setspecific(sTlsKey, NULL);
  17119. return NULL;
  17120. }
  17121. #if defined(ALTERNATIVE_QUEUE)
  17122. ctx->client_wait_events =
  17123. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17124. sizeof(ctx->client_wait_events[0]),
  17125. ctx);
  17126. if (ctx->client_wait_events == NULL) {
  17127. const char *err_msg = "Not enough memory for worker event array";
  17128. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17129. mg_free(ctx->worker_threadids);
  17130. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17131. mg_snprintf(NULL,
  17132. NULL, /* No truncation check for error buffers */
  17133. error->text,
  17134. error->text_buffer_size,
  17135. "%s",
  17136. err_msg);
  17137. }
  17138. free_context(ctx);
  17139. pthread_setspecific(sTlsKey, NULL);
  17140. return NULL;
  17141. }
  17142. ctx->client_socks =
  17143. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17144. sizeof(ctx->client_socks[0]),
  17145. ctx);
  17146. if (ctx->client_socks == NULL) {
  17147. const char *err_msg = "Not enough memory for worker socket array";
  17148. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17149. mg_free(ctx->client_wait_events);
  17150. mg_free(ctx->worker_threadids);
  17151. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17152. mg_snprintf(NULL,
  17153. NULL, /* No truncation check for error buffers */
  17154. error->text,
  17155. error->text_buffer_size,
  17156. "%s",
  17157. err_msg);
  17158. }
  17159. free_context(ctx);
  17160. pthread_setspecific(sTlsKey, NULL);
  17161. return NULL;
  17162. }
  17163. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17164. ctx->client_wait_events[i] = event_create();
  17165. if (ctx->client_wait_events[i] == 0) {
  17166. const char *err_msg = "Error creating worker event %i";
  17167. mg_cry_ctx_internal(ctx, err_msg, i);
  17168. while (i > 0) {
  17169. i--;
  17170. event_destroy(ctx->client_wait_events[i]);
  17171. }
  17172. mg_free(ctx->client_socks);
  17173. mg_free(ctx->client_wait_events);
  17174. mg_free(ctx->worker_threadids);
  17175. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17176. mg_snprintf(NULL,
  17177. NULL, /* No truncation check for error buffers */
  17178. error->text,
  17179. error->text_buffer_size,
  17180. err_msg,
  17181. i);
  17182. }
  17183. free_context(ctx);
  17184. pthread_setspecific(sTlsKey, NULL);
  17185. return NULL;
  17186. }
  17187. }
  17188. #endif
  17189. #if defined(USE_TIMERS)
  17190. if (timers_init(ctx) != 0) {
  17191. const char *err_msg = "Error creating timers";
  17192. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17193. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17194. mg_snprintf(NULL,
  17195. NULL, /* No truncation check for error buffers */
  17196. error->text,
  17197. error->text_buffer_size,
  17198. "%s",
  17199. err_msg);
  17200. }
  17201. free_context(ctx);
  17202. pthread_setspecific(sTlsKey, NULL);
  17203. return NULL;
  17204. }
  17205. #endif
  17206. /* Context has been created - init user libraries */
  17207. if (ctx->callbacks.init_context) {
  17208. ctx->callbacks.init_context(ctx);
  17209. }
  17210. /* From now, the context is successfully created.
  17211. * When it is destroyed, the exit callback should be called. */
  17212. ctx->callbacks.exit_context = exit_callback;
  17213. ctx->context_type = CONTEXT_SERVER; /* server context */
  17214. /* Start worker threads */
  17215. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17216. /* worker_thread sets up the other fields */
  17217. ctx->worker_connections[i].phys_ctx = ctx;
  17218. if (mg_start_thread_with_id(worker_thread,
  17219. &ctx->worker_connections[i],
  17220. &ctx->worker_threadids[i])
  17221. != 0) {
  17222. long error_no = (long)ERRNO;
  17223. /* thread was not created */
  17224. if (i > 0) {
  17225. /* If the second, third, ... thread cannot be created, set a
  17226. * warning, but keep running. */
  17227. mg_cry_ctx_internal(ctx,
  17228. "Cannot start worker thread %i: error %ld",
  17229. i + 1,
  17230. error_no);
  17231. /* If the server initialization should stop here, all
  17232. * threads that have already been created must be stopped
  17233. * first, before any free_context(ctx) call.
  17234. */
  17235. } else {
  17236. /* If the first worker thread cannot be created, stop
  17237. * initialization and free the entire server context. */
  17238. mg_cry_ctx_internal(ctx,
  17239. "Cannot create threads: error %ld",
  17240. error_no);
  17241. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17242. mg_snprintf(
  17243. NULL,
  17244. NULL, /* No truncation check for error buffers */
  17245. error->text,
  17246. error->text_buffer_size,
  17247. "Cannot create first worker thread: error %ld",
  17248. error_no);
  17249. }
  17250. free_context(ctx);
  17251. pthread_setspecific(sTlsKey, NULL);
  17252. return NULL;
  17253. }
  17254. break;
  17255. }
  17256. }
  17257. /* Start master (listening) thread */
  17258. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17259. pthread_setspecific(sTlsKey, NULL);
  17260. return ctx;
  17261. }
  17262. struct mg_context *
  17263. mg_start(const struct mg_callbacks *callbacks,
  17264. void *user_data,
  17265. const char **options)
  17266. {
  17267. struct mg_init_data init = {0};
  17268. init.callbacks = callbacks;
  17269. init.user_data = user_data;
  17270. init.configuration_options = options;
  17271. return mg_start2(&init, NULL);
  17272. }
  17273. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17274. /* Add an additional domain to an already running web server. */
  17275. int
  17276. mg_start_domain2(struct mg_context *ctx,
  17277. const char **options,
  17278. struct mg_error_data *error)
  17279. {
  17280. const char *name;
  17281. const char *value;
  17282. const char *default_value;
  17283. struct mg_domain_context *new_dom;
  17284. struct mg_domain_context *dom;
  17285. int idx, i;
  17286. if (error != NULL) {
  17287. error->code = 0;
  17288. if (error->text_buffer_size > 0) {
  17289. *error->text = 0;
  17290. }
  17291. }
  17292. if ((ctx == NULL) || (options == NULL)) {
  17293. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17294. mg_snprintf(NULL,
  17295. NULL, /* No truncation check for error buffers */
  17296. error->text,
  17297. error->text_buffer_size,
  17298. "%s",
  17299. "Invalid parameters");
  17300. }
  17301. return -1;
  17302. }
  17303. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17304. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17305. mg_snprintf(NULL,
  17306. NULL, /* No truncation check for error buffers */
  17307. error->text,
  17308. error->text_buffer_size,
  17309. "%s",
  17310. "Server already stopped");
  17311. }
  17312. return -1;
  17313. }
  17314. new_dom = (struct mg_domain_context *)
  17315. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17316. if (!new_dom) {
  17317. /* Out of memory */
  17318. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17319. mg_snprintf(NULL,
  17320. NULL, /* No truncation check for error buffers */
  17321. error->text,
  17322. error->text_buffer_size,
  17323. "%s",
  17324. "Out or memory");
  17325. }
  17326. return -6;
  17327. }
  17328. /* Store options - TODO: unite duplicate code */
  17329. while (options && (name = *options++) != NULL) {
  17330. if ((idx = get_option_index(name)) == -1) {
  17331. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17332. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17333. mg_snprintf(NULL,
  17334. NULL, /* No truncation check for error buffers */
  17335. error->text,
  17336. error->text_buffer_size,
  17337. "Invalid option: %s",
  17338. name);
  17339. }
  17340. mg_free(new_dom);
  17341. return -2;
  17342. } else if ((value = *options++) == NULL) {
  17343. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17344. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17345. mg_snprintf(NULL,
  17346. NULL, /* No truncation check for error buffers */
  17347. error->text,
  17348. error->text_buffer_size,
  17349. "Invalid option value: %s",
  17350. name);
  17351. }
  17352. mg_free(new_dom);
  17353. return -2;
  17354. }
  17355. if (new_dom->config[idx] != NULL) {
  17356. /* Duplicate option: Later values overwrite earlier ones. */
  17357. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17358. mg_free(new_dom->config[idx]);
  17359. }
  17360. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17361. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17362. }
  17363. /* Authentication domain is mandatory */
  17364. /* TODO: Maybe use a new option hostname? */
  17365. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17366. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17367. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17368. mg_snprintf(NULL,
  17369. NULL, /* No truncation check for error buffers */
  17370. error->text,
  17371. error->text_buffer_size,
  17372. "Mandatory option %s missing",
  17373. config_options[AUTHENTICATION_DOMAIN].name);
  17374. }
  17375. mg_free(new_dom);
  17376. return -4;
  17377. }
  17378. /* Set default value if needed. Take the config value from
  17379. * ctx as a default value. */
  17380. for (i = 0; config_options[i].name != NULL; i++) {
  17381. default_value = ctx->dd.config[i];
  17382. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17383. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17384. }
  17385. }
  17386. new_dom->handlers = NULL;
  17387. new_dom->next = NULL;
  17388. new_dom->nonce_count = 0;
  17389. new_dom->auth_nonce_mask =
  17390. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17391. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17392. new_dom->shared_lua_websockets = NULL;
  17393. #endif
  17394. if (!init_ssl_ctx(ctx, new_dom)) {
  17395. /* Init SSL failed */
  17396. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17397. mg_snprintf(NULL,
  17398. NULL, /* No truncation check for error buffers */
  17399. error->text,
  17400. error->text_buffer_size,
  17401. "%s",
  17402. "Initializing SSL context failed");
  17403. }
  17404. mg_free(new_dom);
  17405. return -3;
  17406. }
  17407. /* Add element to linked list. */
  17408. mg_lock_context(ctx);
  17409. idx = 0;
  17410. dom = &(ctx->dd);
  17411. for (;;) {
  17412. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17413. dom->config[AUTHENTICATION_DOMAIN])) {
  17414. /* Domain collision */
  17415. mg_cry_ctx_internal(ctx,
  17416. "domain %s already in use",
  17417. new_dom->config[AUTHENTICATION_DOMAIN]);
  17418. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17419. mg_snprintf(NULL,
  17420. NULL, /* No truncation check for error buffers */
  17421. error->text,
  17422. error->text_buffer_size,
  17423. "Domain %s specified by %s is already in use",
  17424. new_dom->config[AUTHENTICATION_DOMAIN],
  17425. config_options[AUTHENTICATION_DOMAIN].name);
  17426. }
  17427. mg_free(new_dom);
  17428. mg_unlock_context(ctx);
  17429. return -5;
  17430. }
  17431. /* Count number of domains */
  17432. idx++;
  17433. if (dom->next == NULL) {
  17434. dom->next = new_dom;
  17435. break;
  17436. }
  17437. dom = dom->next;
  17438. }
  17439. mg_unlock_context(ctx);
  17440. /* Return domain number */
  17441. return idx;
  17442. }
  17443. int
  17444. mg_start_domain(struct mg_context *ctx, const char **options)
  17445. {
  17446. return mg_start_domain2(ctx, options, NULL);
  17447. }
  17448. #endif
  17449. /* Feature check API function */
  17450. unsigned
  17451. mg_check_feature(unsigned feature)
  17452. {
  17453. static const unsigned feature_set = 0
  17454. /* Set bits for available features according to API documentation.
  17455. * This bit mask is created at compile time, according to the active
  17456. * preprocessor defines. It is a single const value at runtime. */
  17457. #if !defined(NO_FILES)
  17458. | MG_FEATURES_FILES
  17459. #endif
  17460. #if !defined(NO_SSL)
  17461. | MG_FEATURES_SSL
  17462. #endif
  17463. #if !defined(NO_CGI)
  17464. | MG_FEATURES_CGI
  17465. #endif
  17466. #if defined(USE_IPV6)
  17467. | MG_FEATURES_IPV6
  17468. #endif
  17469. #if defined(USE_WEBSOCKET)
  17470. | MG_FEATURES_WEBSOCKET
  17471. #endif
  17472. #if defined(USE_LUA)
  17473. | MG_FEATURES_LUA
  17474. #endif
  17475. #if defined(USE_DUKTAPE)
  17476. | MG_FEATURES_SSJS
  17477. #endif
  17478. #if !defined(NO_CACHING)
  17479. | MG_FEATURES_CACHE
  17480. #endif
  17481. #if defined(USE_SERVER_STATS)
  17482. | MG_FEATURES_STATS
  17483. #endif
  17484. #if defined(USE_ZLIB)
  17485. | MG_FEATURES_COMPRESSION
  17486. #endif
  17487. /* Set some extra bits not defined in the API documentation.
  17488. * These bits may change without further notice. */
  17489. #if defined(MG_LEGACY_INTERFACE)
  17490. | 0x00008000u
  17491. #endif
  17492. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17493. | 0x00004000u
  17494. #endif
  17495. #if defined(MEMORY_DEBUGGING)
  17496. | 0x00001000u
  17497. #endif
  17498. #if defined(USE_TIMERS)
  17499. | 0x00020000u
  17500. #endif
  17501. #if !defined(NO_NONCE_CHECK)
  17502. | 0x00040000u
  17503. #endif
  17504. #if !defined(NO_POPEN)
  17505. | 0x00080000u
  17506. #endif
  17507. ;
  17508. return (feature & feature_set);
  17509. }
  17510. static size_t
  17511. mg_str_append(char **dst, char *end, const char *src)
  17512. {
  17513. size_t len = strlen(src);
  17514. if (*dst != end) {
  17515. /* Append src if enough space, or close dst. */
  17516. if ((size_t)(end - *dst) > len) {
  17517. strcpy(*dst, src);
  17518. *dst += len;
  17519. } else {
  17520. *dst = end;
  17521. }
  17522. }
  17523. return len;
  17524. }
  17525. /* Get system information. It can be printed or stored by the caller.
  17526. * Return the size of available information. */
  17527. int
  17528. mg_get_system_info(char *buffer, int buflen)
  17529. {
  17530. char *end, *append_eoobj = NULL, block[256];
  17531. size_t system_info_length = 0;
  17532. #if defined(_WIN32)
  17533. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17534. #else
  17535. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17536. #endif
  17537. if ((buffer == NULL) || (buflen < 1)) {
  17538. buflen = 0;
  17539. end = buffer;
  17540. } else {
  17541. *buffer = 0;
  17542. end = buffer + buflen;
  17543. }
  17544. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17545. /* has enough space to append eoobj */
  17546. append_eoobj = buffer;
  17547. if (end) {
  17548. end -= sizeof(eoobj) - 1;
  17549. }
  17550. }
  17551. system_info_length += mg_str_append(&buffer, end, "{");
  17552. /* Server version */
  17553. {
  17554. const char *version = mg_version();
  17555. mg_snprintf(NULL,
  17556. NULL,
  17557. block,
  17558. sizeof(block),
  17559. "%s\"version\" : \"%s\"",
  17560. eol,
  17561. version);
  17562. system_info_length += mg_str_append(&buffer, end, block);
  17563. }
  17564. /* System info */
  17565. {
  17566. #if defined(_WIN32)
  17567. DWORD dwVersion = 0;
  17568. DWORD dwMajorVersion = 0;
  17569. DWORD dwMinorVersion = 0;
  17570. SYSTEM_INFO si;
  17571. GetSystemInfo(&si);
  17572. #if defined(_MSC_VER)
  17573. #pragma warning(push)
  17574. /* GetVersion was declared deprecated */
  17575. #pragma warning(disable : 4996)
  17576. #endif
  17577. dwVersion = GetVersion();
  17578. #if defined(_MSC_VER)
  17579. #pragma warning(pop)
  17580. #endif
  17581. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17582. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17583. mg_snprintf(NULL,
  17584. NULL,
  17585. block,
  17586. sizeof(block),
  17587. ",%s\"os\" : \"Windows %u.%u\"",
  17588. eol,
  17589. (unsigned)dwMajorVersion,
  17590. (unsigned)dwMinorVersion);
  17591. system_info_length += mg_str_append(&buffer, end, block);
  17592. mg_snprintf(NULL,
  17593. NULL,
  17594. block,
  17595. sizeof(block),
  17596. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17597. eol,
  17598. (unsigned)si.wProcessorArchitecture,
  17599. (unsigned)si.dwNumberOfProcessors,
  17600. (unsigned)si.dwActiveProcessorMask);
  17601. system_info_length += mg_str_append(&buffer, end, block);
  17602. #elif defined(__ZEPHYR__)
  17603. mg_snprintf(NULL,
  17604. NULL,
  17605. block,
  17606. sizeof(block),
  17607. ",%s\"os\" : \"%s %s\"",
  17608. eol,
  17609. "Zephyr OS",
  17610. ZEPHYR_VERSION);
  17611. system_info_length += mg_str_append(&buffer, end, block);
  17612. #else
  17613. struct utsname name;
  17614. memset(&name, 0, sizeof(name));
  17615. uname(&name);
  17616. mg_snprintf(NULL,
  17617. NULL,
  17618. block,
  17619. sizeof(block),
  17620. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17621. eol,
  17622. name.sysname,
  17623. name.version,
  17624. name.release,
  17625. name.machine);
  17626. system_info_length += mg_str_append(&buffer, end, block);
  17627. #endif
  17628. }
  17629. /* Features */
  17630. {
  17631. mg_snprintf(NULL,
  17632. NULL,
  17633. block,
  17634. sizeof(block),
  17635. ",%s\"features\" : %lu"
  17636. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17637. eol,
  17638. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17639. eol,
  17640. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17641. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17642. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17643. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17644. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17645. : "",
  17646. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17647. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17648. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17649. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17650. system_info_length += mg_str_append(&buffer, end, block);
  17651. #if defined(USE_LUA)
  17652. mg_snprintf(NULL,
  17653. NULL,
  17654. block,
  17655. sizeof(block),
  17656. ",%s\"lua_version\" : \"%u (%s)\"",
  17657. eol,
  17658. (unsigned)LUA_VERSION_NUM,
  17659. LUA_RELEASE);
  17660. system_info_length += mg_str_append(&buffer, end, block);
  17661. #endif
  17662. #if defined(USE_DUKTAPE)
  17663. mg_snprintf(NULL,
  17664. NULL,
  17665. block,
  17666. sizeof(block),
  17667. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17668. eol,
  17669. (unsigned)DUK_VERSION / 10000,
  17670. ((unsigned)DUK_VERSION / 100) % 100,
  17671. (unsigned)DUK_VERSION % 100);
  17672. system_info_length += mg_str_append(&buffer, end, block);
  17673. #endif
  17674. }
  17675. /* Build date */
  17676. {
  17677. #if defined(GCC_DIAGNOSTIC)
  17678. #if GCC_VERSION >= 40900
  17679. #pragma GCC diagnostic push
  17680. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17681. #pragma GCC diagnostic ignored "-Wdate-time"
  17682. #endif
  17683. #endif
  17684. mg_snprintf(NULL,
  17685. NULL,
  17686. block,
  17687. sizeof(block),
  17688. ",%s\"build\" : \"%s\"",
  17689. eol,
  17690. __DATE__);
  17691. #if defined(GCC_DIAGNOSTIC)
  17692. #if GCC_VERSION >= 40900
  17693. #pragma GCC diagnostic pop
  17694. #endif
  17695. #endif
  17696. system_info_length += mg_str_append(&buffer, end, block);
  17697. }
  17698. /* Compiler information */
  17699. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17700. {
  17701. #if defined(_MSC_VER)
  17702. mg_snprintf(NULL,
  17703. NULL,
  17704. block,
  17705. sizeof(block),
  17706. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17707. eol,
  17708. (unsigned)_MSC_VER,
  17709. (unsigned)_MSC_FULL_VER);
  17710. system_info_length += mg_str_append(&buffer, end, block);
  17711. #elif defined(__MINGW64__)
  17712. mg_snprintf(NULL,
  17713. NULL,
  17714. block,
  17715. sizeof(block),
  17716. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17717. eol,
  17718. (unsigned)__MINGW64_VERSION_MAJOR,
  17719. (unsigned)__MINGW64_VERSION_MINOR);
  17720. system_info_length += mg_str_append(&buffer, end, block);
  17721. mg_snprintf(NULL,
  17722. NULL,
  17723. block,
  17724. sizeof(block),
  17725. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17726. eol,
  17727. (unsigned)__MINGW32_MAJOR_VERSION,
  17728. (unsigned)__MINGW32_MINOR_VERSION);
  17729. system_info_length += mg_str_append(&buffer, end, block);
  17730. #elif defined(__MINGW32__)
  17731. mg_snprintf(NULL,
  17732. NULL,
  17733. block,
  17734. sizeof(block),
  17735. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17736. eol,
  17737. (unsigned)__MINGW32_MAJOR_VERSION,
  17738. (unsigned)__MINGW32_MINOR_VERSION);
  17739. system_info_length += mg_str_append(&buffer, end, block);
  17740. #elif defined(__clang__)
  17741. mg_snprintf(NULL,
  17742. NULL,
  17743. block,
  17744. sizeof(block),
  17745. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17746. eol,
  17747. __clang_major__,
  17748. __clang_minor__,
  17749. __clang_patchlevel__,
  17750. __clang_version__);
  17751. system_info_length += mg_str_append(&buffer, end, block);
  17752. #elif defined(__GNUC__)
  17753. mg_snprintf(NULL,
  17754. NULL,
  17755. block,
  17756. sizeof(block),
  17757. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17758. eol,
  17759. (unsigned)__GNUC__,
  17760. (unsigned)__GNUC_MINOR__,
  17761. (unsigned)__GNUC_PATCHLEVEL__);
  17762. system_info_length += mg_str_append(&buffer, end, block);
  17763. #elif defined(__INTEL_COMPILER)
  17764. mg_snprintf(NULL,
  17765. NULL,
  17766. block,
  17767. sizeof(block),
  17768. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17769. eol,
  17770. (unsigned)__INTEL_COMPILER);
  17771. system_info_length += mg_str_append(&buffer, end, block);
  17772. #elif defined(__BORLANDC__)
  17773. mg_snprintf(NULL,
  17774. NULL,
  17775. block,
  17776. sizeof(block),
  17777. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17778. eol,
  17779. (unsigned)__BORLANDC__);
  17780. system_info_length += mg_str_append(&buffer, end, block);
  17781. #elif defined(__SUNPRO_C)
  17782. mg_snprintf(NULL,
  17783. NULL,
  17784. block,
  17785. sizeof(block),
  17786. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17787. eol,
  17788. (unsigned)__SUNPRO_C);
  17789. system_info_length += mg_str_append(&buffer, end, block);
  17790. #else
  17791. mg_snprintf(NULL,
  17792. NULL,
  17793. block,
  17794. sizeof(block),
  17795. ",%s\"compiler\" : \"other\"",
  17796. eol);
  17797. system_info_length += mg_str_append(&buffer, end, block);
  17798. #endif
  17799. }
  17800. /* Determine 32/64 bit data mode.
  17801. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17802. {
  17803. mg_snprintf(NULL,
  17804. NULL,
  17805. block,
  17806. sizeof(block),
  17807. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17808. "char:%u/%u, "
  17809. "ptr:%u, size:%u, time:%u\"",
  17810. eol,
  17811. (unsigned)sizeof(short),
  17812. (unsigned)sizeof(int),
  17813. (unsigned)sizeof(long),
  17814. (unsigned)sizeof(long long),
  17815. (unsigned)sizeof(float),
  17816. (unsigned)sizeof(double),
  17817. (unsigned)sizeof(long double),
  17818. (unsigned)sizeof(char),
  17819. (unsigned)sizeof(wchar_t),
  17820. (unsigned)sizeof(void *),
  17821. (unsigned)sizeof(size_t),
  17822. (unsigned)sizeof(time_t));
  17823. system_info_length += mg_str_append(&buffer, end, block);
  17824. }
  17825. /* Terminate string */
  17826. if (append_eoobj) {
  17827. strcat(append_eoobj, eoobj);
  17828. }
  17829. system_info_length += sizeof(eoobj) - 1;
  17830. return (int)system_info_length;
  17831. }
  17832. /* Get context information. It can be printed or stored by the caller.
  17833. * Return the size of available information. */
  17834. int
  17835. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17836. {
  17837. #if defined(USE_SERVER_STATS)
  17838. char *end, *append_eoobj = NULL, block[256];
  17839. size_t context_info_length = 0;
  17840. #if defined(_WIN32)
  17841. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17842. #else
  17843. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17844. #endif
  17845. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17846. if ((buffer == NULL) || (buflen < 1)) {
  17847. buflen = 0;
  17848. end = buffer;
  17849. } else {
  17850. *buffer = 0;
  17851. end = buffer + buflen;
  17852. }
  17853. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17854. /* has enough space to append eoobj */
  17855. append_eoobj = buffer;
  17856. end -= sizeof(eoobj) - 1;
  17857. }
  17858. context_info_length += mg_str_append(&buffer, end, "{");
  17859. if (ms) { /* <-- should be always true */
  17860. /* Memory information */
  17861. mg_snprintf(NULL,
  17862. NULL,
  17863. block,
  17864. sizeof(block),
  17865. "%s\"memory\" : {%s"
  17866. "\"blocks\" : %i,%s"
  17867. "\"used\" : %" INT64_FMT ",%s"
  17868. "\"maxUsed\" : %" INT64_FMT "%s"
  17869. "}",
  17870. eol,
  17871. eol,
  17872. ms->blockCount,
  17873. eol,
  17874. ms->totalMemUsed,
  17875. eol,
  17876. ms->maxMemUsed,
  17877. eol);
  17878. context_info_length += mg_str_append(&buffer, end, block);
  17879. }
  17880. if (ctx) {
  17881. /* Declare all variables at begin of the block, to comply
  17882. * with old C standards. */
  17883. char start_time_str[64] = {0};
  17884. char now_str[64] = {0};
  17885. time_t start_time = ctx->start_time;
  17886. time_t now = time(NULL);
  17887. /* Connections information */
  17888. mg_snprintf(NULL,
  17889. NULL,
  17890. block,
  17891. sizeof(block),
  17892. ",%s\"connections\" : {%s"
  17893. "\"active\" : %i,%s"
  17894. "\"maxActive\" : %i,%s"
  17895. "\"total\" : %" INT64_FMT "%s"
  17896. "}",
  17897. eol,
  17898. eol,
  17899. ctx->active_connections,
  17900. eol,
  17901. ctx->max_active_connections,
  17902. eol,
  17903. ctx->total_connections,
  17904. eol);
  17905. context_info_length += mg_str_append(&buffer, end, block);
  17906. /* Queue information */
  17907. #if !defined(ALTERNATIVE_QUEUE)
  17908. mg_snprintf(NULL,
  17909. NULL,
  17910. block,
  17911. sizeof(block),
  17912. ",%s\"queue\" : {%s"
  17913. "\"length\" : %i,%s"
  17914. "\"filled\" : %i,%s"
  17915. "\"maxFilled\" : %i,%s"
  17916. "\"full\" : %s%s"
  17917. "}",
  17918. eol,
  17919. eol,
  17920. ctx->sq_size,
  17921. eol,
  17922. ctx->sq_head - ctx->sq_tail,
  17923. eol,
  17924. ctx->sq_max_fill,
  17925. eol,
  17926. (ctx->sq_blocked ? "true" : "false"),
  17927. eol);
  17928. context_info_length += mg_str_append(&buffer, end, block);
  17929. #endif
  17930. /* Requests information */
  17931. mg_snprintf(NULL,
  17932. NULL,
  17933. block,
  17934. sizeof(block),
  17935. ",%s\"requests\" : {%s"
  17936. "\"total\" : %" INT64_FMT "%s"
  17937. "}",
  17938. eol,
  17939. eol,
  17940. ctx->total_requests,
  17941. eol);
  17942. context_info_length += mg_str_append(&buffer, end, block);
  17943. /* Data information */
  17944. mg_snprintf(NULL,
  17945. NULL,
  17946. block,
  17947. sizeof(block),
  17948. ",%s\"data\" : {%s"
  17949. "\"read\" : %" INT64_FMT ",%s"
  17950. "\"written\" : %" INT64_FMT "%s"
  17951. "}",
  17952. eol,
  17953. eol,
  17954. ctx->total_data_read,
  17955. eol,
  17956. ctx->total_data_written,
  17957. eol);
  17958. context_info_length += mg_str_append(&buffer, end, block);
  17959. /* Execution time information */
  17960. gmt_time_string(start_time_str,
  17961. sizeof(start_time_str) - 1,
  17962. &start_time);
  17963. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17964. mg_snprintf(NULL,
  17965. NULL,
  17966. block,
  17967. sizeof(block),
  17968. ",%s\"time\" : {%s"
  17969. "\"uptime\" : %.0f,%s"
  17970. "\"start\" : \"%s\",%s"
  17971. "\"now\" : \"%s\"%s"
  17972. "}",
  17973. eol,
  17974. eol,
  17975. difftime(now, start_time),
  17976. eol,
  17977. start_time_str,
  17978. eol,
  17979. now_str,
  17980. eol);
  17981. context_info_length += mg_str_append(&buffer, end, block);
  17982. }
  17983. /* Terminate string */
  17984. if (append_eoobj) {
  17985. strcat(append_eoobj, eoobj);
  17986. }
  17987. context_info_length += sizeof(eoobj) - 1;
  17988. return (int)context_info_length;
  17989. #else
  17990. (void)ctx;
  17991. if ((buffer != NULL) && (buflen > 0)) {
  17992. *buffer = 0;
  17993. }
  17994. return 0;
  17995. #endif
  17996. }
  17997. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17998. /* Get connection information. It can be printed or stored by the caller.
  17999. * Return the size of available information. */
  18000. int
  18001. mg_get_connection_info(const struct mg_context *ctx,
  18002. int idx,
  18003. char *buffer,
  18004. int buflen)
  18005. {
  18006. const struct mg_connection *conn;
  18007. const struct mg_request_info *ri;
  18008. char *end, *append_eoobj = NULL, block[256];
  18009. size_t connection_info_length = 0;
  18010. int state = 0;
  18011. const char *state_str = "unknown";
  18012. #if defined(_WIN32)
  18013. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18014. #else
  18015. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18016. #endif
  18017. if ((buffer == NULL) || (buflen < 1)) {
  18018. buflen = 0;
  18019. end = buffer;
  18020. } else {
  18021. *buffer = 0;
  18022. end = buffer + buflen;
  18023. }
  18024. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18025. /* has enough space to append eoobj */
  18026. append_eoobj = buffer;
  18027. end -= sizeof(eoobj) - 1;
  18028. }
  18029. if ((ctx == NULL) || (idx < 0)) {
  18030. /* Parameter error */
  18031. return 0;
  18032. }
  18033. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18034. /* Out of range */
  18035. return 0;
  18036. }
  18037. /* Take connection [idx]. This connection is not locked in
  18038. * any way, so some other thread might use it. */
  18039. conn = (ctx->worker_connections) + idx;
  18040. /* Initialize output string */
  18041. connection_info_length += mg_str_append(&buffer, end, "{");
  18042. /* Init variables */
  18043. ri = &(conn->request_info);
  18044. #if defined(USE_SERVER_STATS)
  18045. state = conn->conn_state;
  18046. /* State as string */
  18047. switch (state) {
  18048. case 0:
  18049. state_str = "undefined";
  18050. break;
  18051. case 1:
  18052. state_str = "not used";
  18053. break;
  18054. case 2:
  18055. state_str = "init";
  18056. break;
  18057. case 3:
  18058. state_str = "ready";
  18059. break;
  18060. case 4:
  18061. state_str = "processing";
  18062. break;
  18063. case 5:
  18064. state_str = "processed";
  18065. break;
  18066. case 6:
  18067. state_str = "to close";
  18068. break;
  18069. case 7:
  18070. state_str = "closing";
  18071. break;
  18072. case 8:
  18073. state_str = "closed";
  18074. break;
  18075. case 9:
  18076. state_str = "done";
  18077. break;
  18078. }
  18079. #endif
  18080. /* Connection info */
  18081. if ((state >= 3) && (state < 9)) {
  18082. mg_snprintf(NULL,
  18083. NULL,
  18084. block,
  18085. sizeof(block),
  18086. "%s\"connection\" : {%s"
  18087. "\"remote\" : {%s"
  18088. "\"protocol\" : \"%s\",%s"
  18089. "\"addr\" : \"%s\",%s"
  18090. "\"port\" : %u%s"
  18091. "},%s"
  18092. "\"handled_requests\" : %u%s"
  18093. "}",
  18094. eol,
  18095. eol,
  18096. eol,
  18097. get_proto_name(conn),
  18098. eol,
  18099. ri->remote_addr,
  18100. eol,
  18101. ri->remote_port,
  18102. eol,
  18103. eol,
  18104. conn->handled_requests,
  18105. eol);
  18106. connection_info_length += mg_str_append(&buffer, end, block);
  18107. }
  18108. /* Request info */
  18109. if ((state >= 4) && (state < 6)) {
  18110. mg_snprintf(NULL,
  18111. NULL,
  18112. block,
  18113. sizeof(block),
  18114. "%s%s\"request_info\" : {%s"
  18115. "\"method\" : \"%s\",%s"
  18116. "\"uri\" : \"%s\",%s"
  18117. "\"query\" : %s%s%s%s"
  18118. "}",
  18119. (connection_info_length > 1 ? "," : ""),
  18120. eol,
  18121. eol,
  18122. ri->request_method,
  18123. eol,
  18124. ri->request_uri,
  18125. eol,
  18126. ri->query_string ? "\"" : "",
  18127. ri->query_string ? ri->query_string : "null",
  18128. ri->query_string ? "\"" : "",
  18129. eol);
  18130. connection_info_length += mg_str_append(&buffer, end, block);
  18131. }
  18132. /* Execution time information */
  18133. if ((state >= 2) && (state < 9)) {
  18134. char start_time_str[64] = {0};
  18135. char close_time_str[64] = {0};
  18136. time_t start_time = conn->conn_birth_time;
  18137. time_t close_time = conn->conn_close_time;
  18138. double time_diff;
  18139. gmt_time_string(start_time_str,
  18140. sizeof(start_time_str) - 1,
  18141. &start_time);
  18142. if (close_time != 0) {
  18143. time_diff = difftime(close_time, start_time);
  18144. gmt_time_string(close_time_str,
  18145. sizeof(close_time_str) - 1,
  18146. &close_time);
  18147. } else {
  18148. time_t now = time(NULL);
  18149. time_diff = difftime(now, start_time);
  18150. close_time_str[0] = 0; /* or use "now" ? */
  18151. }
  18152. mg_snprintf(NULL,
  18153. NULL,
  18154. block,
  18155. sizeof(block),
  18156. "%s%s\"time\" : {%s"
  18157. "\"uptime\" : %.0f,%s"
  18158. "\"start\" : \"%s\",%s"
  18159. "\"closed\" : \"%s\"%s"
  18160. "}",
  18161. (connection_info_length > 1 ? "," : ""),
  18162. eol,
  18163. eol,
  18164. time_diff,
  18165. eol,
  18166. start_time_str,
  18167. eol,
  18168. close_time_str,
  18169. eol);
  18170. connection_info_length += mg_str_append(&buffer, end, block);
  18171. }
  18172. /* Remote user name */
  18173. if ((ri->remote_user) && (state < 9)) {
  18174. mg_snprintf(NULL,
  18175. NULL,
  18176. block,
  18177. sizeof(block),
  18178. "%s%s\"user\" : {%s"
  18179. "\"name\" : \"%s\",%s"
  18180. "}",
  18181. (connection_info_length > 1 ? "," : ""),
  18182. eol,
  18183. eol,
  18184. ri->remote_user,
  18185. eol);
  18186. connection_info_length += mg_str_append(&buffer, end, block);
  18187. }
  18188. /* Data block */
  18189. if (state >= 3) {
  18190. mg_snprintf(NULL,
  18191. NULL,
  18192. block,
  18193. sizeof(block),
  18194. "%s%s\"data\" : {%s"
  18195. "\"read\" : %" INT64_FMT ",%s"
  18196. "\"written\" : %" INT64_FMT "%s"
  18197. "}",
  18198. (connection_info_length > 1 ? "," : ""),
  18199. eol,
  18200. eol,
  18201. conn->consumed_content,
  18202. eol,
  18203. conn->num_bytes_sent,
  18204. eol);
  18205. connection_info_length += mg_str_append(&buffer, end, block);
  18206. }
  18207. /* State */
  18208. mg_snprintf(NULL,
  18209. NULL,
  18210. block,
  18211. sizeof(block),
  18212. "%s%s\"state\" : \"%s\"",
  18213. (connection_info_length > 1 ? "," : ""),
  18214. eol,
  18215. state_str);
  18216. connection_info_length += mg_str_append(&buffer, end, block);
  18217. /* Terminate string */
  18218. if (append_eoobj) {
  18219. strcat(append_eoobj, eoobj);
  18220. }
  18221. connection_info_length += sizeof(eoobj) - 1;
  18222. return (int)connection_info_length;
  18223. }
  18224. #endif
  18225. /* Initialize this library. This function does not need to be thread safe.
  18226. */
  18227. unsigned
  18228. mg_init_library(unsigned features)
  18229. {
  18230. #if !defined(NO_SSL)
  18231. char ebuf[128];
  18232. #endif
  18233. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18234. unsigned features_inited = features_to_init;
  18235. if (mg_init_library_called <= 0) {
  18236. /* Not initialized yet */
  18237. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18238. return 0;
  18239. }
  18240. }
  18241. mg_global_lock();
  18242. if (mg_init_library_called <= 0) {
  18243. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  18244. /* Fatal error - abort start. However, this situation should
  18245. * never occur in practice. */
  18246. mg_global_unlock();
  18247. return 0;
  18248. }
  18249. #if defined(_WIN32)
  18250. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18251. #else
  18252. pthread_mutexattr_init(&pthread_mutex_attr);
  18253. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  18254. #endif
  18255. #if defined(USE_LUA)
  18256. lua_init_optional_libraries();
  18257. #endif
  18258. }
  18259. mg_global_unlock();
  18260. #if !defined(NO_SSL)
  18261. if (features_to_init & MG_FEATURES_SSL) {
  18262. if (!mg_ssl_initialized) {
  18263. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18264. mg_ssl_initialized = 1;
  18265. } else {
  18266. (void)ebuf;
  18267. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18268. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18269. }
  18270. } else {
  18271. /* ssl already initialized */
  18272. }
  18273. }
  18274. #endif
  18275. /* Start WinSock for Windows */
  18276. mg_global_lock();
  18277. if (mg_init_library_called <= 0) {
  18278. #if defined(_WIN32)
  18279. WSADATA data;
  18280. WSAStartup(MAKEWORD(2, 2), &data);
  18281. #endif /* _WIN32 */
  18282. mg_init_library_called = 1;
  18283. } else {
  18284. mg_init_library_called++;
  18285. }
  18286. mg_global_unlock();
  18287. return features_inited;
  18288. }
  18289. /* Un-initialize this library. */
  18290. unsigned
  18291. mg_exit_library(void)
  18292. {
  18293. if (mg_init_library_called <= 0) {
  18294. return 0;
  18295. }
  18296. mg_global_lock();
  18297. mg_init_library_called--;
  18298. if (mg_init_library_called == 0) {
  18299. #if defined(_WIN32)
  18300. (void)WSACleanup();
  18301. #endif /* _WIN32 */
  18302. #if !defined(NO_SSL)
  18303. if (mg_ssl_initialized) {
  18304. uninitialize_ssl();
  18305. mg_ssl_initialized = 0;
  18306. }
  18307. #endif
  18308. #if defined(_WIN32)
  18309. (void)pthread_mutex_destroy(&global_log_file_lock);
  18310. #else
  18311. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18312. #endif
  18313. (void)pthread_key_delete(sTlsKey);
  18314. #if defined(USE_LUA)
  18315. lua_exit_optional_libraries();
  18316. #endif
  18317. mg_global_unlock();
  18318. (void)pthread_mutex_destroy(&global_lock_mutex);
  18319. return 1;
  18320. }
  18321. mg_global_unlock();
  18322. return 1;
  18323. }
  18324. /* End of civetweb.c */