civetweb.c 566 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102
  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 0x0502
  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. #if !defined(_WIN32)
  369. /* Unix might return different error codes indicating to try again.
  370. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  371. * decades ago, but better check both and let the compile optimize it. */
  372. #define ERROR_TRY_AGAIN(err) \
  373. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  374. #endif
  375. /********************************************************************/
  376. /* CivetWeb configuration defines */
  377. /********************************************************************/
  378. /* Maximum number of threads that can be configured.
  379. * The number of threads actually created depends on the "num_threads"
  380. * configuration parameter, but this is the upper limit. */
  381. #if !defined(MAX_WORKER_THREADS)
  382. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  383. #endif
  384. /* Timeout interval for select/poll calls.
  385. * The timeouts depend on "*_timeout_ms" configuration values, but long
  386. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  387. * This reduces the time required to stop the server. */
  388. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  389. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  390. #endif
  391. /* Do not try to compress files smaller than this limit. */
  392. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  393. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  394. #endif
  395. #if !defined(PASSWORDS_FILE_NAME)
  396. #define PASSWORDS_FILE_NAME ".htpasswd"
  397. #endif
  398. /* Initial buffer size for all CGI environment variables. In case there is
  399. * not enough space, another block is allocated. */
  400. #if !defined(CGI_ENVIRONMENT_SIZE)
  401. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  402. #endif
  403. /* Maximum number of environment variables. */
  404. #if !defined(MAX_CGI_ENVIR_VARS)
  405. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  406. #endif
  407. /* General purpose buffer size. */
  408. #if !defined(MG_BUF_LEN) /* in bytes */
  409. #define MG_BUF_LEN (1024 * 8)
  410. #endif
  411. /********************************************************************/
  412. /* Helper makros */
  413. #if !defined(ARRAY_SIZE)
  414. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  415. #endif
  416. #include <stdint.h>
  417. /* Standard defines */
  418. #if !defined(INT64_MAX)
  419. #define INT64_MAX (9223372036854775807)
  420. #endif
  421. #define SHUTDOWN_RD (0)
  422. #define SHUTDOWN_WR (1)
  423. #define SHUTDOWN_BOTH (2)
  424. mg_static_assert(MAX_WORKER_THREADS >= 1,
  425. "worker threads must be a positive number");
  426. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  427. "size_t data type size check");
  428. #if defined(_WIN32) /* WINDOWS include block */
  429. #include <malloc.h> /* *alloc( */
  430. #include <stdlib.h> /* *alloc( */
  431. #include <time.h> /* struct timespec */
  432. #include <windows.h>
  433. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  434. #include <ws2tcpip.h>
  435. typedef const char *SOCK_OPT_TYPE;
  436. #if !defined(PATH_MAX)
  437. #define W_PATH_MAX (MAX_PATH)
  438. /* at most three UTF-8 chars per wchar_t */
  439. #define PATH_MAX (W_PATH_MAX * 3)
  440. #else
  441. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  442. #endif
  443. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  444. #if !defined(_IN_PORT_T)
  445. #if !defined(in_port_t)
  446. #define in_port_t u_short
  447. #endif
  448. #endif
  449. #if !defined(_WIN32_WCE)
  450. #include <direct.h>
  451. #include <io.h>
  452. #include <process.h>
  453. #else /* _WIN32_WCE */
  454. #define NO_CGI /* WinCE has no pipes */
  455. #define NO_POPEN /* WinCE has no popen */
  456. typedef long off_t;
  457. #define errno ((int)(GetLastError()))
  458. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  459. #endif /* _WIN32_WCE */
  460. #define MAKEUQUAD(lo, hi) \
  461. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  462. #define RATE_DIFF (10000000) /* 100 nsecs */
  463. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  464. #define SYS2UNIX_TIME(lo, hi) \
  465. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  466. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  467. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  468. * Also use _strtoui64 on modern M$ compilers */
  469. #if defined(_MSC_VER)
  470. #if (_MSC_VER < 1300)
  471. #define STRX(x) #x
  472. #define STR(x) STRX(x)
  473. #define __func__ __FILE__ ":" STR(__LINE__)
  474. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  475. #define strtoll(x, y, z) (_atoi64(x))
  476. #else
  477. #define __func__ __FUNCTION__
  478. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  479. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  480. #endif
  481. #endif /* _MSC_VER */
  482. #define ERRNO ((int)(GetLastError()))
  483. #define NO_SOCKLEN_T
  484. #if defined(_WIN64) || defined(__MINGW64__)
  485. #if !defined(SSL_LIB)
  486. #if defined(OPENSSL_API_1_1)
  487. #define SSL_LIB "libssl-1_1-x64.dll"
  488. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  489. #endif /* OPENSSL_API_1_1 */
  490. #if defined(OPENSSL_API_1_0)
  491. #define SSL_LIB "ssleay64.dll"
  492. #define CRYPTO_LIB "libeay64.dll"
  493. #endif /* OPENSSL_API_1_0 */
  494. #endif
  495. #else /* defined(_WIN64) || defined(__MINGW64__) */
  496. #if !defined(SSL_LIB)
  497. #if defined(OPENSSL_API_1_1)
  498. #define SSL_LIB "libssl-1_1.dll"
  499. #define CRYPTO_LIB "libcrypto-1_1.dll"
  500. #endif /* OPENSSL_API_1_1 */
  501. #if defined(OPENSSL_API_1_0)
  502. #define SSL_LIB "ssleay32.dll"
  503. #define CRYPTO_LIB "libeay32.dll"
  504. #endif /* OPENSSL_API_1_0 */
  505. #endif /* SSL_LIB */
  506. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  507. #define O_NONBLOCK (0)
  508. #if !defined(W_OK)
  509. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  510. #endif
  511. #define _POSIX_
  512. #define INT64_FMT "I64d"
  513. #define UINT64_FMT "I64u"
  514. #define WINCDECL __cdecl
  515. #define vsnprintf_impl _vsnprintf
  516. #define access _access
  517. #define mg_sleep(x) (Sleep(x))
  518. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  519. #if !defined(popen)
  520. #define popen(x, y) (_popen(x, y))
  521. #endif
  522. #if !defined(pclose)
  523. #define pclose(x) (_pclose(x))
  524. #endif
  525. #define close(x) (_close(x))
  526. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  527. #define RTLD_LAZY (0)
  528. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  529. #define fdopen(x, y) (_fdopen((x), (y)))
  530. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  531. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  532. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  533. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  534. #define sleep(x) (Sleep((x)*1000))
  535. #define rmdir(x) (_rmdir(x))
  536. #if defined(_WIN64) || !defined(__MINGW32__)
  537. /* Only MinGW 32 bit is missing this function */
  538. #define timegm(x) (_mkgmtime(x))
  539. #else
  540. time_t timegm(struct tm *tm);
  541. #define NEED_TIMEGM
  542. #endif
  543. #if !defined(fileno)
  544. #define fileno(x) (_fileno(x))
  545. #endif /* !fileno MINGW #defines fileno */
  546. typedef struct {
  547. CRITICAL_SECTION sec; /* Immovable */
  548. } pthread_mutex_t;
  549. typedef DWORD pthread_key_t;
  550. typedef HANDLE pthread_t;
  551. typedef struct {
  552. pthread_mutex_t threadIdSec;
  553. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  554. } pthread_cond_t;
  555. #if !defined(__clockid_t_defined)
  556. typedef DWORD clockid_t;
  557. #endif
  558. #if !defined(CLOCK_MONOTONIC)
  559. #define CLOCK_MONOTONIC (1)
  560. #endif
  561. #if !defined(CLOCK_REALTIME)
  562. #define CLOCK_REALTIME (2)
  563. #endif
  564. #if !defined(CLOCK_THREAD)
  565. #define CLOCK_THREAD (3)
  566. #endif
  567. #if !defined(CLOCK_PROCESS)
  568. #define CLOCK_PROCESS (4)
  569. #endif
  570. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  571. #define _TIMESPEC_DEFINED
  572. #endif
  573. #if !defined(_TIMESPEC_DEFINED)
  574. struct timespec {
  575. time_t tv_sec; /* seconds */
  576. long tv_nsec; /* nanoseconds */
  577. };
  578. #endif
  579. #if !defined(WIN_PTHREADS_TIME_H)
  580. #define MUST_IMPLEMENT_CLOCK_GETTIME
  581. #endif
  582. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  583. #define clock_gettime mg_clock_gettime
  584. static int
  585. clock_gettime(clockid_t clk_id, struct timespec *tp)
  586. {
  587. FILETIME ft;
  588. ULARGE_INTEGER li, li2;
  589. BOOL ok = FALSE;
  590. double d;
  591. static double perfcnt_per_sec = 0.0;
  592. static BOOL initialized = FALSE;
  593. if (!initialized) {
  594. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  595. perfcnt_per_sec = 1.0 / li.QuadPart;
  596. initialized = TRUE;
  597. }
  598. if (tp) {
  599. memset(tp, 0, sizeof(*tp));
  600. if (clk_id == CLOCK_REALTIME) {
  601. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  602. GetSystemTimeAsFileTime(&ft);
  603. li.LowPart = ft.dwLowDateTime;
  604. li.HighPart = ft.dwHighDateTime;
  605. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  606. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  607. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  608. ok = TRUE;
  609. /* END: CLOCK_REALTIME */
  610. } else if (clk_id == CLOCK_MONOTONIC) {
  611. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  612. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  613. d = li.QuadPart * perfcnt_per_sec;
  614. tp->tv_sec = (time_t)d;
  615. d -= (double)tp->tv_sec;
  616. tp->tv_nsec = (long)(d * 1.0E9);
  617. ok = TRUE;
  618. /* END: CLOCK_MONOTONIC */
  619. } else if (clk_id == CLOCK_THREAD) {
  620. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  621. FILETIME t_create, t_exit, t_kernel, t_user;
  622. if (GetThreadTimes(GetCurrentThread(),
  623. &t_create,
  624. &t_exit,
  625. &t_kernel,
  626. &t_user)) {
  627. li.LowPart = t_user.dwLowDateTime;
  628. li.HighPart = t_user.dwHighDateTime;
  629. li2.LowPart = t_kernel.dwLowDateTime;
  630. li2.HighPart = t_kernel.dwHighDateTime;
  631. li.QuadPart += li2.QuadPart;
  632. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  633. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  634. ok = TRUE;
  635. }
  636. /* END: CLOCK_THREAD */
  637. } else if (clk_id == CLOCK_PROCESS) {
  638. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  639. FILETIME t_create, t_exit, t_kernel, t_user;
  640. if (GetProcessTimes(GetCurrentProcess(),
  641. &t_create,
  642. &t_exit,
  643. &t_kernel,
  644. &t_user)) {
  645. li.LowPart = t_user.dwLowDateTime;
  646. li.HighPart = t_user.dwHighDateTime;
  647. li2.LowPart = t_kernel.dwLowDateTime;
  648. li2.HighPart = t_kernel.dwHighDateTime;
  649. li.QuadPart += li2.QuadPart;
  650. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  651. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  652. ok = TRUE;
  653. }
  654. /* END: CLOCK_PROCESS */
  655. } else {
  656. /* BEGIN: unknown clock */
  657. /* ok = FALSE; already set by init */
  658. /* END: unknown clock */
  659. }
  660. }
  661. return ok ? 0 : -1;
  662. }
  663. #endif
  664. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  665. static int pthread_mutex_lock(pthread_mutex_t *);
  666. static int pthread_mutex_unlock(pthread_mutex_t *);
  667. static void path_to_unicode(const struct mg_connection *conn,
  668. const char *path,
  669. wchar_t *wbuf,
  670. size_t wbuf_len);
  671. /* All file operations need to be rewritten to solve #246. */
  672. struct mg_file;
  673. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  674. /* POSIX dirent interface */
  675. struct dirent {
  676. char d_name[PATH_MAX];
  677. };
  678. typedef struct DIR {
  679. HANDLE handle;
  680. WIN32_FIND_DATAW info;
  681. struct dirent result;
  682. } DIR;
  683. #if defined(HAVE_POLL)
  684. #define mg_pollfd pollfd
  685. #else
  686. struct mg_pollfd {
  687. SOCKET fd;
  688. short events;
  689. short revents;
  690. };
  691. #endif
  692. /* Mark required libraries */
  693. #if defined(_MSC_VER)
  694. #pragma comment(lib, "Ws2_32.lib")
  695. #endif
  696. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  697. #include <inttypes.h>
  698. typedef const void *SOCK_OPT_TYPE;
  699. #if defined(ANDROID)
  700. typedef unsigned short int in_port_t;
  701. #endif
  702. #if !defined(__ZEPHYR__)
  703. #include <arpa/inet.h>
  704. #include <ctype.h>
  705. #include <dirent.h>
  706. #include <grp.h>
  707. #include <limits.h>
  708. #include <netdb.h>
  709. #include <netinet/in.h>
  710. #include <netinet/tcp.h>
  711. #include <pthread.h>
  712. #include <pwd.h>
  713. #include <stdarg.h>
  714. #include <stddef.h>
  715. #include <stdio.h>
  716. #include <stdlib.h>
  717. #include <string.h>
  718. #include <sys/poll.h>
  719. #include <sys/socket.h>
  720. #include <sys/time.h>
  721. #include <sys/utsname.h>
  722. #include <sys/wait.h>
  723. #include <time.h>
  724. #include <unistd.h>
  725. #endif
  726. #define vsnprintf_impl vsnprintf
  727. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  728. #include <dlfcn.h>
  729. #endif
  730. #if defined(__MACH__)
  731. #define SSL_LIB "libssl.dylib"
  732. #define CRYPTO_LIB "libcrypto.dylib"
  733. #else
  734. #if !defined(SSL_LIB)
  735. #define SSL_LIB "libssl.so"
  736. #endif
  737. #if !defined(CRYPTO_LIB)
  738. #define CRYPTO_LIB "libcrypto.so"
  739. #endif
  740. #endif
  741. #if !defined(O_BINARY)
  742. #define O_BINARY (0)
  743. #endif /* O_BINARY */
  744. #define closesocket(a) (close(a))
  745. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  746. #define mg_remove(conn, x) (remove(x))
  747. #define mg_sleep(x) (usleep((x)*1000))
  748. #define mg_opendir(conn, x) (opendir(x))
  749. #define mg_closedir(x) (closedir(x))
  750. #define mg_readdir(x) (readdir(x))
  751. #define ERRNO (errno)
  752. #define INVALID_SOCKET (-1)
  753. #define INT64_FMT PRId64
  754. #define UINT64_FMT PRIu64
  755. typedef int SOCKET;
  756. #define WINCDECL
  757. #if defined(__hpux)
  758. /* HPUX 11 does not have monotonic, fall back to realtime */
  759. #if !defined(CLOCK_MONOTONIC)
  760. #define CLOCK_MONOTONIC CLOCK_REALTIME
  761. #endif
  762. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  763. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  764. * the prototypes use int* rather than socklen_t* which matches the
  765. * actual library expectation. When called with the wrong size arg
  766. * accept() returns a zero client inet addr and check_acl() always
  767. * fails. Since socklen_t is widely used below, just force replace
  768. * their typedef with int. - DTL
  769. */
  770. #define socklen_t int
  771. #endif /* hpux */
  772. #define mg_pollfd pollfd
  773. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  774. /* In case our C library is missing "timegm", provide an implementation */
  775. #if defined(NEED_TIMEGM)
  776. static inline int
  777. is_leap(int y)
  778. {
  779. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  780. }
  781. static inline int
  782. count_leap(int y)
  783. {
  784. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  785. }
  786. time_t
  787. timegm(struct tm *tm)
  788. {
  789. static const unsigned short ydays[] = {
  790. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  791. int year = tm->tm_year + 1900;
  792. int mon = tm->tm_mon;
  793. int mday = tm->tm_mday - 1;
  794. int hour = tm->tm_hour;
  795. int min = tm->tm_min;
  796. int sec = tm->tm_sec;
  797. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  798. || (mday >= ydays[mon + 1] - ydays[mon]
  799. + (mon == 1 && is_leap(year) ? 1 : 0))
  800. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  801. return -1;
  802. time_t res = year - 1970;
  803. res *= 365;
  804. res += mday;
  805. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  806. res += count_leap(year);
  807. res *= 24;
  808. res += hour;
  809. res *= 60;
  810. res += min;
  811. res *= 60;
  812. res += sec;
  813. return res;
  814. }
  815. #endif /* NEED_TIMEGM */
  816. /* va_copy should always be a macro, C99 and C++11 - DTL */
  817. #if !defined(va_copy)
  818. #define va_copy(x, y) ((x) = (y))
  819. #endif
  820. #if defined(_WIN32)
  821. /* Create substitutes for POSIX functions in Win32. */
  822. #if defined(GCC_DIAGNOSTIC)
  823. /* Show no warning in case system functions are not used. */
  824. #pragma GCC diagnostic push
  825. #pragma GCC diagnostic ignored "-Wunused-function"
  826. #endif
  827. static pthread_mutex_t global_log_file_lock;
  828. FUNCTION_MAY_BE_UNUSED
  829. static DWORD
  830. pthread_self(void)
  831. {
  832. return GetCurrentThreadId();
  833. }
  834. FUNCTION_MAY_BE_UNUSED
  835. static int
  836. pthread_key_create(
  837. pthread_key_t *key,
  838. void (*_ignored)(void *) /* destructor not supported for Windows */
  839. )
  840. {
  841. (void)_ignored;
  842. if ((key != 0)) {
  843. *key = TlsAlloc();
  844. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  845. }
  846. return -2;
  847. }
  848. FUNCTION_MAY_BE_UNUSED
  849. static int
  850. pthread_key_delete(pthread_key_t key)
  851. {
  852. return TlsFree(key) ? 0 : 1;
  853. }
  854. FUNCTION_MAY_BE_UNUSED
  855. static int
  856. pthread_setspecific(pthread_key_t key, void *value)
  857. {
  858. return TlsSetValue(key, value) ? 0 : 1;
  859. }
  860. FUNCTION_MAY_BE_UNUSED
  861. static void *
  862. pthread_getspecific(pthread_key_t key)
  863. {
  864. return TlsGetValue(key);
  865. }
  866. #if defined(GCC_DIAGNOSTIC)
  867. /* Enable unused function warning again */
  868. #pragma GCC diagnostic pop
  869. #endif
  870. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  871. #else
  872. static pthread_mutexattr_t pthread_mutex_attr;
  873. #endif /* _WIN32 */
  874. #if defined(_WIN32_WCE)
  875. /* Create substitutes for POSIX functions in Win32. */
  876. #if defined(GCC_DIAGNOSTIC)
  877. /* Show no warning in case system functions are not used. */
  878. #pragma GCC diagnostic push
  879. #pragma GCC diagnostic ignored "-Wunused-function"
  880. #endif
  881. FUNCTION_MAY_BE_UNUSED
  882. static time_t
  883. time(time_t *ptime)
  884. {
  885. time_t t;
  886. SYSTEMTIME st;
  887. FILETIME ft;
  888. GetSystemTime(&st);
  889. SystemTimeToFileTime(&st, &ft);
  890. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  891. if (ptime != NULL) {
  892. *ptime = t;
  893. }
  894. return t;
  895. }
  896. FUNCTION_MAY_BE_UNUSED
  897. static struct tm *
  898. localtime_s(const time_t *ptime, struct tm *ptm)
  899. {
  900. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  901. FILETIME ft, lft;
  902. SYSTEMTIME st;
  903. TIME_ZONE_INFORMATION tzinfo;
  904. if (ptm == NULL) {
  905. return NULL;
  906. }
  907. *(int64_t *)&ft = t;
  908. FileTimeToLocalFileTime(&ft, &lft);
  909. FileTimeToSystemTime(&lft, &st);
  910. ptm->tm_year = st.wYear - 1900;
  911. ptm->tm_mon = st.wMonth - 1;
  912. ptm->tm_wday = st.wDayOfWeek;
  913. ptm->tm_mday = st.wDay;
  914. ptm->tm_hour = st.wHour;
  915. ptm->tm_min = st.wMinute;
  916. ptm->tm_sec = st.wSecond;
  917. ptm->tm_yday = 0; /* hope nobody uses this */
  918. ptm->tm_isdst =
  919. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  920. return ptm;
  921. }
  922. FUNCTION_MAY_BE_UNUSED
  923. static struct tm *
  924. gmtime_s(const time_t *ptime, struct tm *ptm)
  925. {
  926. /* FIXME(lsm): fix this. */
  927. return localtime_s(ptime, ptm);
  928. }
  929. static ptrdiff_t mg_atomic_inc(volatile ptrdiff_t *addr);
  930. static struct tm tm_array[MAX_WORKER_THREADS]; /* Must be 2^n */
  931. static volatile ptrdiff_t tm_index = 0;
  932. FUNCTION_MAY_BE_UNUSED
  933. static struct tm *
  934. localtime(const time_t *ptime)
  935. {
  936. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  937. return localtime_s(ptime, tm_array + i);
  938. }
  939. FUNCTION_MAY_BE_UNUSED
  940. static struct tm *
  941. gmtime(const time_t *ptime)
  942. {
  943. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  944. return gmtime_s(ptime, tm_array + i);
  945. }
  946. FUNCTION_MAY_BE_UNUSED
  947. static size_t
  948. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  949. {
  950. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  951. * for WinCE"); */
  952. return 0;
  953. }
  954. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  955. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  956. #define remove(f) mg_remove(NULL, f)
  957. FUNCTION_MAY_BE_UNUSED
  958. static int
  959. rename(const char *a, const char *b)
  960. {
  961. wchar_t wa[W_PATH_MAX];
  962. wchar_t wb[W_PATH_MAX];
  963. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  964. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  965. return MoveFileW(wa, wb) ? 0 : -1;
  966. }
  967. struct stat {
  968. int64_t st_size;
  969. time_t st_mtime;
  970. };
  971. FUNCTION_MAY_BE_UNUSED
  972. static int
  973. stat(const char *name, struct stat *st)
  974. {
  975. wchar_t wbuf[W_PATH_MAX];
  976. WIN32_FILE_ATTRIBUTE_DATA attr;
  977. time_t creation_time, write_time;
  978. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  979. memset(&attr, 0, sizeof(attr));
  980. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  981. st->st_size =
  982. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  983. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  984. attr.ftLastWriteTime.dwHighDateTime);
  985. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  986. attr.ftCreationTime.dwHighDateTime);
  987. if (creation_time > write_time) {
  988. st->st_mtime = creation_time;
  989. } else {
  990. st->st_mtime = write_time;
  991. }
  992. return 0;
  993. }
  994. #define access(x, a) 1 /* not required anyway */
  995. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  996. /* Values from errno.h in Windows SDK (Visual Studio). */
  997. #define EEXIST 17
  998. #define EACCES 13
  999. #define ENOENT 2
  1000. #if defined(GCC_DIAGNOSTIC)
  1001. /* Enable unused function warning again */
  1002. #pragma GCC diagnostic pop
  1003. #endif
  1004. #endif /* defined(_WIN32_WCE) */
  1005. #if defined(GCC_DIAGNOSTIC)
  1006. /* Show no warning in case system functions are not used. */
  1007. #pragma GCC diagnostic push
  1008. #pragma GCC diagnostic ignored "-Wunused-function"
  1009. #endif /* defined(GCC_DIAGNOSTIC) */
  1010. #if defined(__clang__)
  1011. /* Show no warning in case system functions are not used. */
  1012. #pragma clang diagnostic push
  1013. #pragma clang diagnostic ignored "-Wunused-function"
  1014. #endif
  1015. static pthread_mutex_t global_lock_mutex;
  1016. FUNCTION_MAY_BE_UNUSED
  1017. static void
  1018. mg_global_lock(void)
  1019. {
  1020. (void)pthread_mutex_lock(&global_lock_mutex);
  1021. }
  1022. FUNCTION_MAY_BE_UNUSED
  1023. static void
  1024. mg_global_unlock(void)
  1025. {
  1026. (void)pthread_mutex_unlock(&global_lock_mutex);
  1027. }
  1028. #if defined(_WIN64)
  1029. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  1030. #elif defined(_WIN32)
  1031. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  1032. #endif
  1033. /* Atomic functions working on ptrdiff_t ("signed size_t").
  1034. * Operations: Increment, Decrement, Add, Maximum.
  1035. * Up to size_t, they do not an atomic "load" operation.
  1036. */
  1037. FUNCTION_MAY_BE_UNUSED
  1038. static ptrdiff_t
  1039. mg_atomic_inc(volatile ptrdiff_t *addr)
  1040. {
  1041. ptrdiff_t ret;
  1042. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1043. ret = InterlockedIncrement64(addr);
  1044. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1045. ret = InterlockedIncrement(addr);
  1046. #elif defined(__GNUC__) \
  1047. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1048. && !defined(NO_ATOMICS)
  1049. ret = __sync_add_and_fetch(addr, 1);
  1050. #else
  1051. mg_global_lock();
  1052. ret = (++(*addr));
  1053. mg_global_unlock();
  1054. #endif
  1055. return ret;
  1056. }
  1057. FUNCTION_MAY_BE_UNUSED
  1058. static ptrdiff_t
  1059. mg_atomic_dec(volatile ptrdiff_t *addr)
  1060. {
  1061. ptrdiff_t ret;
  1062. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1063. ret = InterlockedDecrement64(addr);
  1064. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1065. ret = InterlockedDecrement(addr);
  1066. #elif defined(__GNUC__) \
  1067. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1068. && !defined(NO_ATOMICS)
  1069. ret = __sync_sub_and_fetch(addr, 1);
  1070. #else
  1071. mg_global_lock();
  1072. ret = (--(*addr));
  1073. mg_global_unlock();
  1074. #endif
  1075. return ret;
  1076. }
  1077. #if defined(USE_SERVER_STATS)
  1078. static ptrdiff_t
  1079. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1080. {
  1081. ptrdiff_t ret;
  1082. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1083. ret = InterlockedAdd64(addr, value);
  1084. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1085. ret = InterlockedExchangeAdd(addr, value) + value;
  1086. #elif defined(__GNUC__) \
  1087. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1088. && !defined(NO_ATOMICS)
  1089. ret = __sync_add_and_fetch(addr, value);
  1090. #else
  1091. mg_global_lock();
  1092. *addr += value;
  1093. ret = (*addr);
  1094. mg_global_unlock();
  1095. #endif
  1096. return ret;
  1097. }
  1098. FUNCTION_MAY_BE_UNUSED
  1099. static int
  1100. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1101. ptrdiff_t oldval,
  1102. ptrdiff_t newval)
  1103. {
  1104. ptrdiff_t ret;
  1105. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1106. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1107. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1108. ret = InterlockedCompareExchange(addr, newval, oldval);
  1109. #elif defined(__GNUC__) \
  1110. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1111. && !defined(NO_ATOMICS)
  1112. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1113. #else
  1114. mg_global_lock();
  1115. ret = *addr;
  1116. if ((ret != newval) && (ret == oldval)) {
  1117. *addr = newval;
  1118. }
  1119. mg_global_unlock();
  1120. #endif
  1121. return ret;
  1122. }
  1123. static void
  1124. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1125. {
  1126. register ptrdiff_t tmp = *addr;
  1127. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1128. while (tmp < value) {
  1129. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1130. }
  1131. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1132. while (tmp < value) {
  1133. tmp = InterlockedCompareExchange(addr, value, tmp);
  1134. }
  1135. #elif defined(__GNUC__) \
  1136. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1137. && !defined(NO_ATOMICS)
  1138. while (tmp < value) {
  1139. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1140. }
  1141. #else
  1142. mg_global_lock();
  1143. if (*addr < value) {
  1144. *addr = value;
  1145. }
  1146. mg_global_unlock();
  1147. #endif
  1148. }
  1149. static int64_t
  1150. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1151. {
  1152. int64_t ret;
  1153. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1154. ret = InterlockedAdd64(addr, value);
  1155. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1156. ret = InterlockedExchangeAdd64(addr, value) + value;
  1157. #elif defined(__GNUC__) \
  1158. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1159. && !defined(NO_ATOMICS)
  1160. ret = __sync_add_and_fetch(addr, value);
  1161. #else
  1162. mg_global_lock();
  1163. *addr += value;
  1164. ret = (*addr);
  1165. mg_global_unlock();
  1166. #endif
  1167. return ret;
  1168. }
  1169. #endif
  1170. #if defined(GCC_DIAGNOSTIC)
  1171. /* Show no warning in case system functions are not used. */
  1172. #pragma GCC diagnostic pop
  1173. #endif /* defined(GCC_DIAGNOSTIC) */
  1174. #if defined(__clang__)
  1175. /* Show no warning in case system functions are not used. */
  1176. #pragma clang diagnostic pop
  1177. #endif
  1178. #if defined(USE_SERVER_STATS)
  1179. struct mg_memory_stat {
  1180. volatile ptrdiff_t totalMemUsed;
  1181. volatile ptrdiff_t maxMemUsed;
  1182. volatile ptrdiff_t blockCount;
  1183. };
  1184. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1185. static void *
  1186. mg_malloc_ex(size_t size,
  1187. struct mg_context *ctx,
  1188. const char *file,
  1189. unsigned line)
  1190. {
  1191. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1192. void *memory = 0;
  1193. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1194. #if defined(MEMORY_DEBUGGING)
  1195. char mallocStr[256];
  1196. #else
  1197. (void)file;
  1198. (void)line;
  1199. #endif
  1200. if (data) {
  1201. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1202. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1203. mg_atomic_inc(&mstat->blockCount);
  1204. ((uintptr_t *)data)[0] = size;
  1205. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1206. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1207. }
  1208. #if defined(MEMORY_DEBUGGING)
  1209. sprintf(mallocStr,
  1210. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1211. memory,
  1212. (unsigned long)size,
  1213. (unsigned long)mstat->totalMemUsed,
  1214. (unsigned long)mstat->blockCount,
  1215. file,
  1216. line);
  1217. DEBUG_TRACE("%s", mallocStr);
  1218. #endif
  1219. return memory;
  1220. }
  1221. static void *
  1222. mg_calloc_ex(size_t count,
  1223. size_t size,
  1224. struct mg_context *ctx,
  1225. const char *file,
  1226. unsigned line)
  1227. {
  1228. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1229. if (data) {
  1230. memset(data, 0, size * count);
  1231. }
  1232. return data;
  1233. }
  1234. static void
  1235. mg_free_ex(void *memory, const char *file, unsigned line)
  1236. {
  1237. #if defined(MEMORY_DEBUGGING)
  1238. char mallocStr[256];
  1239. #else
  1240. (void)file;
  1241. (void)line;
  1242. #endif
  1243. if (memory) {
  1244. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1245. uintptr_t size = ((uintptr_t *)data)[0];
  1246. struct mg_memory_stat *mstat =
  1247. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1248. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1249. mg_atomic_dec(&mstat->blockCount);
  1250. #if defined(MEMORY_DEBUGGING)
  1251. sprintf(mallocStr,
  1252. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1253. memory,
  1254. (unsigned long)size,
  1255. (unsigned long)mstat->totalMemUsed,
  1256. (unsigned long)mstat->blockCount,
  1257. file,
  1258. line);
  1259. DEBUG_TRACE("%s", mallocStr);
  1260. #endif
  1261. free(data);
  1262. }
  1263. }
  1264. static void *
  1265. mg_realloc_ex(void *memory,
  1266. size_t newsize,
  1267. struct mg_context *ctx,
  1268. const char *file,
  1269. unsigned line)
  1270. {
  1271. void *data;
  1272. void *_realloc;
  1273. uintptr_t oldsize;
  1274. #if defined(MEMORY_DEBUGGING)
  1275. char mallocStr[256];
  1276. #else
  1277. (void)file;
  1278. (void)line;
  1279. #endif
  1280. if (newsize) {
  1281. if (memory) {
  1282. /* Reallocate existing block */
  1283. struct mg_memory_stat *mstat;
  1284. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1285. oldsize = ((uintptr_t *)data)[0];
  1286. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1287. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1288. if (_realloc) {
  1289. data = _realloc;
  1290. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1291. #if defined(MEMORY_DEBUGGING)
  1292. sprintf(mallocStr,
  1293. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1294. memory,
  1295. (unsigned long)oldsize,
  1296. (unsigned long)mstat->totalMemUsed,
  1297. (unsigned long)mstat->blockCount,
  1298. file,
  1299. line);
  1300. DEBUG_TRACE("%s", mallocStr);
  1301. #endif
  1302. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1303. #if defined(MEMORY_DEBUGGING)
  1304. sprintf(mallocStr,
  1305. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1306. memory,
  1307. (unsigned long)newsize,
  1308. (unsigned long)mstat->totalMemUsed,
  1309. (unsigned long)mstat->blockCount,
  1310. file,
  1311. line);
  1312. DEBUG_TRACE("%s", mallocStr);
  1313. #endif
  1314. *(uintptr_t *)data = newsize;
  1315. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1316. } else {
  1317. #if defined(MEMORY_DEBUGGING)
  1318. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1319. #endif
  1320. return _realloc;
  1321. }
  1322. } else {
  1323. /* Allocate new block */
  1324. data = mg_malloc_ex(newsize, ctx, file, line);
  1325. }
  1326. } else {
  1327. /* Free existing block */
  1328. data = 0;
  1329. mg_free_ex(memory, file, line);
  1330. }
  1331. return data;
  1332. }
  1333. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1334. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1335. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1336. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1337. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1338. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1339. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1340. #else /* USE_SERVER_STATS */
  1341. static __inline void *
  1342. mg_malloc(size_t a)
  1343. {
  1344. return malloc(a);
  1345. }
  1346. static __inline void *
  1347. mg_calloc(size_t a, size_t b)
  1348. {
  1349. return calloc(a, b);
  1350. }
  1351. static __inline void *
  1352. mg_realloc(void *a, size_t b)
  1353. {
  1354. return realloc(a, b);
  1355. }
  1356. static __inline void
  1357. mg_free(void *a)
  1358. {
  1359. free(a);
  1360. }
  1361. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1362. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1363. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1364. #define mg_free_ctx(a, c) mg_free(a)
  1365. #endif /* USE_SERVER_STATS */
  1366. static void mg_vsnprintf(const struct mg_connection *conn,
  1367. int *truncated,
  1368. char *buf,
  1369. size_t buflen,
  1370. const char *fmt,
  1371. va_list ap);
  1372. static void mg_snprintf(const struct mg_connection *conn,
  1373. int *truncated,
  1374. char *buf,
  1375. size_t buflen,
  1376. PRINTF_FORMAT_STRING(const char *fmt),
  1377. ...) PRINTF_ARGS(5, 6);
  1378. /* This following lines are just meant as a reminder to use the mg-functions
  1379. * for memory management */
  1380. #if defined(malloc)
  1381. #undef malloc
  1382. #endif
  1383. #if defined(calloc)
  1384. #undef calloc
  1385. #endif
  1386. #if defined(realloc)
  1387. #undef realloc
  1388. #endif
  1389. #if defined(free)
  1390. #undef free
  1391. #endif
  1392. #if defined(snprintf)
  1393. #undef snprintf
  1394. #endif
  1395. #if defined(vsnprintf)
  1396. #undef vsnprintf
  1397. #endif
  1398. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1399. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1400. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1401. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1402. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1403. #if defined(_WIN32)
  1404. /* vsnprintf must not be used in any system,
  1405. * but this define only works well for Windows. */
  1406. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1407. #endif
  1408. /* mg_init_library counter */
  1409. static int mg_init_library_called = 0;
  1410. #if !defined(NO_SSL)
  1411. static int mg_ssl_initialized = 0;
  1412. /* TODO: Selection of SSL library and version */
  1413. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1)
  1414. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1415. #endif
  1416. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1417. #error "Multiple OPENSSL_API versions defined"
  1418. #endif
  1419. #endif /* NO_SSL */
  1420. static pthread_key_t sTlsKey; /* Thread local storage index */
  1421. static volatile ptrdiff_t thread_idx_max = 0;
  1422. #if defined(MG_LEGACY_INTERFACE)
  1423. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1424. #endif
  1425. struct mg_workerTLS {
  1426. int is_master;
  1427. unsigned long thread_idx;
  1428. void *user_ptr;
  1429. #if defined(_WIN32)
  1430. HANDLE pthread_cond_helper_mutex;
  1431. struct mg_workerTLS *next_waiting_thread;
  1432. #endif
  1433. const char *alpn_proto;
  1434. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1435. char txtbuf[4];
  1436. #endif
  1437. };
  1438. #if defined(GCC_DIAGNOSTIC)
  1439. /* Show no warning in case system functions are not used. */
  1440. #pragma GCC diagnostic push
  1441. #pragma GCC diagnostic ignored "-Wunused-function"
  1442. #endif /* defined(GCC_DIAGNOSTIC) */
  1443. #if defined(__clang__)
  1444. /* Show no warning in case system functions are not used. */
  1445. #pragma clang diagnostic push
  1446. #pragma clang diagnostic ignored "-Wunused-function"
  1447. #endif
  1448. /* Get a unique thread ID as unsigned long, independent from the data type
  1449. * of thread IDs defined by the operating system API.
  1450. * If two calls to mg_current_thread_id return the same value, they calls
  1451. * are done from the same thread. If they return different values, they are
  1452. * done from different threads. (Provided this function is used in the same
  1453. * process context and threads are not repeatedly created and deleted, but
  1454. * CivetWeb does not do that).
  1455. * This function must match the signature required for SSL id callbacks:
  1456. * CRYPTO_set_id_callback
  1457. */
  1458. FUNCTION_MAY_BE_UNUSED
  1459. static unsigned long
  1460. mg_current_thread_id(void)
  1461. {
  1462. #if defined(_WIN32)
  1463. return GetCurrentThreadId();
  1464. #else
  1465. #if defined(__clang__)
  1466. #pragma clang diagnostic push
  1467. #pragma clang diagnostic ignored "-Wunreachable-code"
  1468. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1469. * or not, so one of the two conditions will be unreachable by construction.
  1470. * Unfortunately the C standard does not define a way to check this at
  1471. * compile time, since the #if preprocessor conditions can not use the sizeof
  1472. * operator as an argument. */
  1473. #endif
  1474. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1475. /* This is the problematic case for CRYPTO_set_id_callback:
  1476. * The OS pthread_t can not be cast to unsigned long. */
  1477. struct mg_workerTLS *tls =
  1478. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1479. if (tls == NULL) {
  1480. /* SSL called from an unknown thread: Create some thread index.
  1481. */
  1482. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1483. tls->is_master = -2; /* -2 means "3rd party thread" */
  1484. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1485. pthread_setspecific(sTlsKey, tls);
  1486. }
  1487. return tls->thread_idx;
  1488. } else {
  1489. /* pthread_t may be any data type, so a simple cast to unsigned long
  1490. * can rise a warning/error, depending on the platform.
  1491. * Here memcpy is used as an anything-to-anything cast. */
  1492. unsigned long ret = 0;
  1493. pthread_t t = pthread_self();
  1494. memcpy(&ret, &t, sizeof(pthread_t));
  1495. return ret;
  1496. }
  1497. #if defined(__clang__)
  1498. #pragma clang diagnostic pop
  1499. #endif
  1500. #endif
  1501. }
  1502. FUNCTION_MAY_BE_UNUSED
  1503. static uint64_t
  1504. mg_get_current_time_ns(void)
  1505. {
  1506. struct timespec tsnow;
  1507. clock_gettime(CLOCK_REALTIME, &tsnow);
  1508. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1509. }
  1510. #if defined(GCC_DIAGNOSTIC)
  1511. /* Show no warning in case system functions are not used. */
  1512. #pragma GCC diagnostic pop
  1513. #endif /* defined(GCC_DIAGNOSTIC) */
  1514. #if defined(__clang__)
  1515. /* Show no warning in case system functions are not used. */
  1516. #pragma clang diagnostic pop
  1517. #endif
  1518. #if defined(NEED_DEBUG_TRACE_FUNC)
  1519. static void
  1520. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1521. {
  1522. va_list args;
  1523. struct timespec tsnow;
  1524. /* Get some operating system independent thread id */
  1525. unsigned long thread_id = mg_current_thread_id();
  1526. clock_gettime(CLOCK_REALTIME, &tsnow);
  1527. flockfile(DEBUG_TRACE_STREAM);
  1528. fprintf(DEBUG_TRACE_STREAM,
  1529. "*** %lu.%09lu %lu %s:%u: ",
  1530. (unsigned long)tsnow.tv_sec,
  1531. (unsigned long)tsnow.tv_nsec,
  1532. thread_id,
  1533. func,
  1534. line);
  1535. va_start(args, fmt);
  1536. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1537. va_end(args);
  1538. putc('\n', DEBUG_TRACE_STREAM);
  1539. fflush(DEBUG_TRACE_STREAM);
  1540. funlockfile(DEBUG_TRACE_STREAM);
  1541. }
  1542. #endif /* NEED_DEBUG_TRACE_FUNC */
  1543. #define MD5_STATIC static
  1544. #include "md5.inl"
  1545. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1546. #if defined(NO_SOCKLEN_T)
  1547. typedef int socklen_t;
  1548. #endif /* NO_SOCKLEN_T */
  1549. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1550. #if !defined(MSG_NOSIGNAL)
  1551. #define MSG_NOSIGNAL (0)
  1552. #endif
  1553. #if defined(NO_SSL)
  1554. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1555. typedef struct SSL_CTX SSL_CTX;
  1556. #else
  1557. #if defined(NO_SSL_DL)
  1558. #include <openssl/bn.h>
  1559. #include <openssl/conf.h>
  1560. #include <openssl/crypto.h>
  1561. #include <openssl/dh.h>
  1562. #include <openssl/engine.h>
  1563. #include <openssl/err.h>
  1564. #include <openssl/opensslv.h>
  1565. #include <openssl/pem.h>
  1566. #include <openssl/ssl.h>
  1567. #include <openssl/tls1.h>
  1568. #include <openssl/x509.h>
  1569. #if defined(WOLFSSL_VERSION)
  1570. /* Additional defines for WolfSSL, see
  1571. * https://github.com/civetweb/civetweb/issues/583 */
  1572. #include "wolfssl_extras.inl"
  1573. #endif
  1574. #if defined(OPENSSL_IS_BORINGSSL)
  1575. /* From boringssl/src/include/openssl/mem.h:
  1576. *
  1577. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1578. * However, that was written in a time before Valgrind and ASAN. Since we now
  1579. * have those tools, the OpenSSL allocation functions are simply macros around
  1580. * the standard memory functions.
  1581. *
  1582. * #define OPENSSL_free free */
  1583. #define free free
  1584. // disable for boringssl
  1585. #define CONF_modules_unload(a) ((void)0)
  1586. #define ENGINE_cleanup() ((void)0)
  1587. #endif
  1588. /* If OpenSSL headers are included, automatically select the API version */
  1589. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1590. #if !defined(OPENSSL_API_1_1)
  1591. #define OPENSSL_API_1_1
  1592. #endif
  1593. #define OPENSSL_REMOVE_THREAD_STATE()
  1594. #else
  1595. #if !defined(OPENSSL_API_1_0)
  1596. #define OPENSSL_API_1_0
  1597. #endif
  1598. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1599. #endif
  1600. #else
  1601. /* SSL loaded dynamically from DLL.
  1602. * I put the prototypes here to be independent from OpenSSL source
  1603. * installation. */
  1604. typedef struct ssl_st SSL;
  1605. typedef struct ssl_method_st SSL_METHOD;
  1606. typedef struct ssl_ctx_st SSL_CTX;
  1607. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1608. typedef struct x509_name X509_NAME;
  1609. typedef struct asn1_integer ASN1_INTEGER;
  1610. typedef struct bignum BIGNUM;
  1611. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1612. typedef struct evp_md EVP_MD;
  1613. typedef struct x509 X509;
  1614. #define SSL_CTRL_OPTIONS (32)
  1615. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1616. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1617. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1618. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1619. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1620. #define SSL_VERIFY_NONE (0)
  1621. #define SSL_VERIFY_PEER (1)
  1622. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1623. #define SSL_VERIFY_CLIENT_ONCE (4)
  1624. #define SSL_OP_ALL (0x80000BFFul)
  1625. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1626. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1627. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1628. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1629. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1630. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1631. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1632. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1633. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1634. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1635. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1636. #define SSL_CB_HANDSHAKE_START (0x10)
  1637. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1638. #define SSL_ERROR_NONE (0)
  1639. #define SSL_ERROR_SSL (1)
  1640. #define SSL_ERROR_WANT_READ (2)
  1641. #define SSL_ERROR_WANT_WRITE (3)
  1642. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1643. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1644. #define SSL_ERROR_ZERO_RETURN (6)
  1645. #define SSL_ERROR_WANT_CONNECT (7)
  1646. #define SSL_ERROR_WANT_ACCEPT (8)
  1647. #define TLSEXT_TYPE_server_name (0)
  1648. #define TLSEXT_NAMETYPE_host_name (0)
  1649. #define SSL_TLSEXT_ERR_OK (0)
  1650. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1651. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1652. #define SSL_TLSEXT_ERR_NOACK (3)
  1653. #define SSL_SESS_CACHE_BOTH (3)
  1654. enum ssl_func_category {
  1655. TLS_Mandatory, /* required for HTTPS */
  1656. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1657. TLS_END_OF_LIST
  1658. };
  1659. /* Check if all TLS functions/features are available */
  1660. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1661. struct ssl_func {
  1662. const char *name; /* SSL function name */
  1663. enum ssl_func_category required; /* Mandatory or optional */
  1664. void (*ptr)(void); /* Function pointer */
  1665. };
  1666. #if defined(OPENSSL_API_1_1)
  1667. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1668. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1669. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1670. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1671. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1672. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1673. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1674. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1675. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1676. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1677. #define OPENSSL_init_ssl \
  1678. (*(int (*)(uint64_t opts, \
  1679. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1680. .ptr)
  1681. #define SSL_CTX_use_PrivateKey_file \
  1682. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1683. #define SSL_CTX_use_certificate_file \
  1684. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1685. #define SSL_CTX_set_default_passwd_cb \
  1686. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1687. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1688. #define SSL_CTX_use_certificate_chain_file \
  1689. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1690. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1691. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1692. #define SSL_CTX_set_verify \
  1693. (*(void (*)(SSL_CTX *, \
  1694. int, \
  1695. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1696. .ptr)
  1697. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1698. #define SSL_CTX_load_verify_locations \
  1699. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1700. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1701. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1702. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1703. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1704. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1705. #define SSL_CIPHER_get_name \
  1706. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1707. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1708. #define SSL_CTX_set_session_id_context \
  1709. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1710. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1711. #define SSL_CTX_set_cipher_list \
  1712. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1713. #define SSL_CTX_set_options \
  1714. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1715. #define SSL_CTX_set_info_callback \
  1716. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1717. ssl_sw[32] \
  1718. .ptr)
  1719. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1720. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1721. #define SSL_CTX_callback_ctrl \
  1722. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1723. #define SSL_get_servername \
  1724. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1725. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1726. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1727. #define SSL_CTX_set_alpn_protos \
  1728. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1729. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1730. const unsigned char **out,
  1731. unsigned char *outlen,
  1732. const unsigned char *in,
  1733. unsigned int inlen,
  1734. void *arg);
  1735. #define SSL_CTX_set_alpn_select_cb \
  1736. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1737. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1738. const unsigned char **out,
  1739. unsigned int *outlen,
  1740. void *arg);
  1741. #define SSL_CTX_set_next_protos_advertised_cb \
  1742. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1743. .ptr)
  1744. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1745. #define SSL_CTX_clear_options(ctx, op) \
  1746. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1747. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1748. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1749. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1750. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1751. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1752. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1753. SSL_CTX_callback_ctrl(ctx, \
  1754. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1755. (void (*)(void))cb)
  1756. #define SSL_set_tlsext_host_name(ctx, arg) \
  1757. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1758. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1759. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1760. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1761. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1762. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1763. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1764. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1765. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1766. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1767. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1768. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1769. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1770. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1771. #define X509_NAME_oneline \
  1772. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1773. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1774. #define EVP_get_digestbyname \
  1775. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1776. #define EVP_Digest \
  1777. (*(int (*)( \
  1778. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1779. crypto_sw[9] \
  1780. .ptr)
  1781. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1782. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1783. #define ASN1_INTEGER_to_BN \
  1784. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1785. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1786. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1787. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1788. #define OPENSSL_free(a) CRYPTO_free(a)
  1789. #define OPENSSL_REMOVE_THREAD_STATE()
  1790. /* init_ssl_ctx() function updates this array.
  1791. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1792. * of respective functions. The macros above (like SSL_connect()) are really
  1793. * just calling these functions indirectly via the pointer. */
  1794. static struct ssl_func ssl_sw[] = {
  1795. {"SSL_free", TLS_Mandatory, NULL},
  1796. {"SSL_accept", TLS_Mandatory, NULL},
  1797. {"SSL_connect", TLS_Mandatory, NULL},
  1798. {"SSL_read", TLS_Mandatory, NULL},
  1799. {"SSL_write", TLS_Mandatory, NULL},
  1800. {"SSL_get_error", TLS_Mandatory, NULL},
  1801. {"SSL_set_fd", TLS_Mandatory, NULL},
  1802. {"SSL_new", TLS_Mandatory, NULL},
  1803. {"SSL_CTX_new", TLS_Mandatory, NULL},
  1804. {"TLS_server_method", TLS_Mandatory, NULL},
  1805. {"OPENSSL_init_ssl", TLS_Mandatory, NULL},
  1806. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  1807. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  1808. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  1809. {"SSL_CTX_free", TLS_Mandatory, NULL},
  1810. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  1811. {"TLS_client_method", TLS_Mandatory, NULL},
  1812. {"SSL_pending", TLS_Mandatory, NULL},
  1813. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  1814. {"SSL_shutdown", TLS_Mandatory, NULL},
  1815. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  1816. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  1817. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  1818. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  1819. {"SSL_get_version", TLS_Mandatory, NULL},
  1820. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  1821. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  1822. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  1823. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  1824. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  1825. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  1826. {"SSL_CTX_set_options", TLS_Mandatory, NULL},
  1827. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  1828. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  1829. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  1830. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  1831. {"SSL_get_servername", TLS_Mandatory, NULL},
  1832. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  1833. {"SSL_ctrl", TLS_Mandatory, NULL},
  1834. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  1835. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  1836. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  1837. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  1838. {NULL, TLS_END_OF_LIST, NULL}};
  1839. /* Similar array as ssl_sw. These functions could be located in different
  1840. * lib. */
  1841. static struct ssl_func crypto_sw[] = {
  1842. {"ERR_get_error", TLS_Mandatory, NULL},
  1843. {"ERR_error_string", TLS_Mandatory, NULL},
  1844. {"CONF_modules_unload", TLS_Mandatory, NULL},
  1845. {"X509_free", TLS_Mandatory, NULL},
  1846. {"X509_get_subject_name", TLS_Mandatory, NULL},
  1847. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  1848. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  1849. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  1850. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  1851. {"EVP_Digest", TLS_Mandatory, NULL},
  1852. {"i2d_X509", TLS_Mandatory, NULL},
  1853. {"BN_bn2hex", TLS_Mandatory, NULL},
  1854. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  1855. {"BN_free", TLS_Mandatory, NULL},
  1856. {"CRYPTO_free", TLS_Mandatory, NULL},
  1857. {"ERR_clear_error", TLS_Mandatory, NULL},
  1858. {NULL, TLS_END_OF_LIST, NULL}};
  1859. #else
  1860. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1861. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1862. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1863. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1864. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1865. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1866. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1867. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1868. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1869. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1870. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1871. #define SSL_CTX_use_PrivateKey_file \
  1872. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1873. #define SSL_CTX_use_certificate_file \
  1874. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1875. #define SSL_CTX_set_default_passwd_cb \
  1876. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1877. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1878. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1879. #define SSL_CTX_use_certificate_chain_file \
  1880. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1881. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1882. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1883. #define SSL_CTX_set_verify \
  1884. (*(void (*)(SSL_CTX *, \
  1885. int, \
  1886. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1887. .ptr)
  1888. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1889. #define SSL_CTX_load_verify_locations \
  1890. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1891. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1892. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1893. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1894. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1895. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1896. #define SSL_CIPHER_get_name \
  1897. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1898. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1899. #define SSL_CTX_set_session_id_context \
  1900. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1901. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1902. #define SSL_CTX_set_cipher_list \
  1903. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1904. #define SSL_CTX_set_info_callback \
  1905. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1906. .ptr)
  1907. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1908. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1909. #define SSL_CTX_callback_ctrl \
  1910. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1911. #define SSL_get_servername \
  1912. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1913. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1914. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1915. #define SSL_CTX_set_alpn_protos \
  1916. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1917. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1918. const unsigned char **out,
  1919. unsigned char *outlen,
  1920. const unsigned char *in,
  1921. unsigned int inlen,
  1922. void *arg);
  1923. #define SSL_CTX_set_alpn_select_cb \
  1924. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1925. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1926. const unsigned char **out,
  1927. unsigned int *outlen,
  1928. void *arg);
  1929. #define SSL_CTX_set_next_protos_advertised_cb \
  1930. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1931. .ptr)
  1932. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1933. #define SSL_CTX_set_options(ctx, op) \
  1934. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1935. #define SSL_CTX_clear_options(ctx, op) \
  1936. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1937. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1938. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1939. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1940. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1941. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1942. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1943. SSL_CTX_callback_ctrl(ctx, \
  1944. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1945. (void (*)(void))cb)
  1946. #define SSL_set_tlsext_host_name(ctx, arg) \
  1947. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1948. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1949. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1950. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1951. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1952. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1953. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1954. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1955. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1956. #define CRYPTO_set_locking_callback \
  1957. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1958. #define CRYPTO_set_id_callback \
  1959. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1960. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1961. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1962. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1963. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1964. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1965. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1966. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1967. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1968. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1969. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1970. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1971. #define X509_NAME_oneline \
  1972. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1973. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1974. #define i2c_ASN1_INTEGER \
  1975. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1976. #define EVP_get_digestbyname \
  1977. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1978. #define EVP_Digest \
  1979. (*(int (*)( \
  1980. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1981. crypto_sw[18] \
  1982. .ptr)
  1983. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1984. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1985. #define ASN1_INTEGER_to_BN \
  1986. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1987. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1988. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1989. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1990. #define OPENSSL_free(a) CRYPTO_free(a)
  1991. /* use here ERR_remove_state,
  1992. * while on some platforms function is not included into library due to
  1993. * deprication */
  1994. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1995. /* init_ssl_ctx() function updates this array.
  1996. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1997. * of respective functions. The macros above (like SSL_connect()) are really
  1998. * just calling these functions indirectly via the pointer. */
  1999. static struct ssl_func ssl_sw[] = {
  2000. {"SSL_free", TLS_Mandatory, NULL},
  2001. {"SSL_accept", TLS_Mandatory, NULL},
  2002. {"SSL_connect", TLS_Mandatory, NULL},
  2003. {"SSL_read", TLS_Mandatory, NULL},
  2004. {"SSL_write", TLS_Mandatory, NULL},
  2005. {"SSL_get_error", TLS_Mandatory, NULL},
  2006. {"SSL_set_fd", TLS_Mandatory, NULL},
  2007. {"SSL_new", TLS_Mandatory, NULL},
  2008. {"SSL_CTX_new", TLS_Mandatory, NULL},
  2009. {"SSLv23_server_method", TLS_Mandatory, NULL},
  2010. {"SSL_library_init", TLS_Mandatory, NULL},
  2011. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  2012. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  2013. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  2014. {"SSL_CTX_free", TLS_Mandatory, NULL},
  2015. {"SSL_load_error_strings", TLS_Mandatory, NULL},
  2016. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  2017. {"SSLv23_client_method", TLS_Mandatory, NULL},
  2018. {"SSL_pending", TLS_Mandatory, NULL},
  2019. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  2020. {"SSL_shutdown", TLS_Mandatory, NULL},
  2021. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  2022. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  2023. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  2024. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  2025. {"SSL_get_version", TLS_Mandatory, NULL},
  2026. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  2027. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  2028. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  2029. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  2030. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  2031. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  2032. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  2033. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  2034. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  2035. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  2036. {"SSL_get_servername", TLS_Mandatory, NULL},
  2037. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  2038. {"SSL_ctrl", TLS_Mandatory, NULL},
  2039. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  2040. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  2041. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  2042. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  2043. {NULL, TLS_END_OF_LIST, NULL}};
  2044. /* Similar array as ssl_sw. These functions could be located in different
  2045. * lib. */
  2046. static struct ssl_func crypto_sw[] = {
  2047. {"CRYPTO_num_locks", TLS_Mandatory, NULL},
  2048. {"CRYPTO_set_locking_callback", TLS_Mandatory, NULL},
  2049. {"CRYPTO_set_id_callback", TLS_Mandatory, NULL},
  2050. {"ERR_get_error", TLS_Mandatory, NULL},
  2051. {"ERR_error_string", TLS_Mandatory, NULL},
  2052. {"ERR_remove_state", TLS_Mandatory, NULL},
  2053. {"ERR_free_strings", TLS_Mandatory, NULL},
  2054. {"ENGINE_cleanup", TLS_Mandatory, NULL},
  2055. {"CONF_modules_unload", TLS_Mandatory, NULL},
  2056. {"CRYPTO_cleanup_all_ex_data", TLS_Mandatory, NULL},
  2057. {"EVP_cleanup", TLS_Mandatory, NULL},
  2058. {"X509_free", TLS_Mandatory, NULL},
  2059. {"X509_get_subject_name", TLS_Mandatory, NULL},
  2060. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  2061. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  2062. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  2063. {"i2c_ASN1_INTEGER", TLS_Mandatory, NULL},
  2064. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  2065. {"EVP_Digest", TLS_Mandatory, NULL},
  2066. {"i2d_X509", TLS_Mandatory, NULL},
  2067. {"BN_bn2hex", TLS_Mandatory, NULL},
  2068. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  2069. {"BN_free", TLS_Mandatory, NULL},
  2070. {"CRYPTO_free", TLS_Mandatory, NULL},
  2071. {"ERR_clear_error", TLS_Mandatory, NULL},
  2072. {NULL, TLS_END_OF_LIST, NULL}};
  2073. #endif /* OPENSSL_API_1_1 */
  2074. #endif /* NO_SSL_DL */
  2075. #endif /* NO_SSL */
  2076. #if !defined(NO_CACHING)
  2077. static const char month_names[][4] = {"Jan",
  2078. "Feb",
  2079. "Mar",
  2080. "Apr",
  2081. "May",
  2082. "Jun",
  2083. "Jul",
  2084. "Aug",
  2085. "Sep",
  2086. "Oct",
  2087. "Nov",
  2088. "Dec"};
  2089. #endif /* !NO_CACHING */
  2090. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2091. * the union u. */
  2092. union usa {
  2093. struct sockaddr sa;
  2094. struct sockaddr_in sin;
  2095. #if defined(USE_IPV6)
  2096. struct sockaddr_in6 sin6;
  2097. #endif
  2098. };
  2099. #if defined(USE_IPV6)
  2100. #define USA_IN_PORT_UNSAFE(s) \
  2101. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  2102. #else
  2103. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  2104. #endif
  2105. /* Describes a string (chunk of memory). */
  2106. struct vec {
  2107. const char *ptr;
  2108. size_t len;
  2109. };
  2110. struct mg_file_stat {
  2111. /* File properties filled by mg_stat: */
  2112. uint64_t size;
  2113. time_t last_modified;
  2114. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2115. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2116. * case we need a "Content-Eencoding: gzip" header */
  2117. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2118. };
  2119. struct mg_file_access {
  2120. /* File properties filled by mg_fopen: */
  2121. FILE *fp;
  2122. };
  2123. struct mg_file {
  2124. struct mg_file_stat stat;
  2125. struct mg_file_access access;
  2126. };
  2127. #define STRUCT_FILE_INITIALIZER \
  2128. { \
  2129. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2130. { \
  2131. (FILE *)NULL \
  2132. } \
  2133. }
  2134. /* Describes listening socket, or socket which was accept()-ed by the master
  2135. * thread and queued for future handling by the worker thread. */
  2136. struct socket {
  2137. SOCKET sock; /* Listening socket */
  2138. union usa lsa; /* Local socket address */
  2139. union usa rsa; /* Remote socket address */
  2140. unsigned char is_ssl; /* Is port SSL-ed */
  2141. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2142. * port */
  2143. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2144. };
  2145. /* Enum const for all options must be in sync with
  2146. * static struct mg_option config_options[]
  2147. * This is tested in the unit test (test/private.c)
  2148. * "Private Config Options"
  2149. */
  2150. enum {
  2151. /* Once for each server */
  2152. LISTENING_PORTS,
  2153. NUM_THREADS,
  2154. RUN_AS_USER,
  2155. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2156. * socket option typedef TCP_NODELAY. */
  2157. MAX_REQUEST_SIZE,
  2158. LINGER_TIMEOUT,
  2159. CONNECTION_QUEUE_SIZE,
  2160. LISTEN_BACKLOG_SIZE,
  2161. #if defined(__linux__)
  2162. ALLOW_SENDFILE_CALL,
  2163. #endif
  2164. #if defined(_WIN32)
  2165. CASE_SENSITIVE_FILES,
  2166. #endif
  2167. THROTTLE,
  2168. ACCESS_LOG_FILE,
  2169. ERROR_LOG_FILE,
  2170. ENABLE_KEEP_ALIVE,
  2171. REQUEST_TIMEOUT,
  2172. KEEP_ALIVE_TIMEOUT,
  2173. #if defined(USE_WEBSOCKET)
  2174. WEBSOCKET_TIMEOUT,
  2175. ENABLE_WEBSOCKET_PING_PONG,
  2176. #endif
  2177. DECODE_URL,
  2178. #if defined(USE_LUA)
  2179. LUA_BACKGROUND_SCRIPT,
  2180. LUA_BACKGROUND_SCRIPT_PARAMS,
  2181. #endif
  2182. #if defined(USE_HTTP2)
  2183. ENABLE_HTTP2,
  2184. #endif
  2185. /* Once for each domain */
  2186. DOCUMENT_ROOT,
  2187. CGI_EXTENSIONS,
  2188. CGI2_EXTENSIONS,
  2189. CGI_ENVIRONMENT,
  2190. CGI2_ENVIRONMENT,
  2191. CGI_INTERPRETER,
  2192. CGI2_INTERPRETER,
  2193. CGI_INTERPRETER_ARGS,
  2194. CGI2_INTERPRETER_ARGS,
  2195. #if defined(USE_TIMERS)
  2196. CGI_TIMEOUT,
  2197. CGI2_TIMEOUT,
  2198. #endif
  2199. PUT_DELETE_PASSWORDS_FILE,
  2200. PROTECT_URI,
  2201. AUTHENTICATION_DOMAIN,
  2202. ENABLE_AUTH_DOMAIN_CHECK,
  2203. SSI_EXTENSIONS,
  2204. ENABLE_DIRECTORY_LISTING,
  2205. GLOBAL_PASSWORDS_FILE,
  2206. INDEX_FILES,
  2207. ACCESS_CONTROL_LIST,
  2208. EXTRA_MIME_TYPES,
  2209. SSL_CERTIFICATE,
  2210. SSL_CERTIFICATE_CHAIN,
  2211. URL_REWRITE_PATTERN,
  2212. HIDE_FILES,
  2213. SSL_DO_VERIFY_PEER,
  2214. SSL_CACHE_TIMEOUT,
  2215. SSL_CA_PATH,
  2216. SSL_CA_FILE,
  2217. SSL_VERIFY_DEPTH,
  2218. SSL_DEFAULT_VERIFY_PATHS,
  2219. SSL_CIPHER_LIST,
  2220. SSL_PROTOCOL_VERSION,
  2221. SSL_SHORT_TRUST,
  2222. #if defined(USE_LUA)
  2223. LUA_PRELOAD_FILE,
  2224. LUA_SCRIPT_EXTENSIONS,
  2225. LUA_SERVER_PAGE_EXTENSIONS,
  2226. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2227. LUA_DEBUG_PARAMS,
  2228. #endif
  2229. #endif
  2230. #if defined(USE_DUKTAPE)
  2231. DUKTAPE_SCRIPT_EXTENSIONS,
  2232. #endif
  2233. #if defined(USE_WEBSOCKET)
  2234. WEBSOCKET_ROOT,
  2235. #endif
  2236. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2237. LUA_WEBSOCKET_EXTENSIONS,
  2238. #endif
  2239. ACCESS_CONTROL_ALLOW_ORIGIN,
  2240. ACCESS_CONTROL_ALLOW_METHODS,
  2241. ACCESS_CONTROL_ALLOW_HEADERS,
  2242. ERROR_PAGES,
  2243. #if !defined(NO_CACHING)
  2244. STATIC_FILE_MAX_AGE,
  2245. STATIC_FILE_CACHE_CONTROL,
  2246. #endif
  2247. #if !defined(NO_SSL)
  2248. STRICT_HTTPS_MAX_AGE,
  2249. #endif
  2250. ADDITIONAL_HEADER,
  2251. ALLOW_INDEX_SCRIPT_SUB_RES,
  2252. #if defined(DAEMONIZE)
  2253. ENABLE_DAEMONIZE,
  2254. #endif
  2255. NUM_OPTIONS
  2256. };
  2257. /* Config option name, config types, default value.
  2258. * Must be in the same order as the enum const above.
  2259. */
  2260. static const struct mg_option config_options[] = {
  2261. /* Once for each server */
  2262. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2263. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2264. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2265. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2266. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2267. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2268. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2269. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2270. #if defined(__linux__)
  2271. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2272. #endif
  2273. #if defined(_WIN32)
  2274. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2275. #endif
  2276. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2277. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2278. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2279. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2280. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2281. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2282. #if defined(USE_WEBSOCKET)
  2283. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2284. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2285. #endif
  2286. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2287. #if defined(USE_LUA)
  2288. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2289. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2290. #endif
  2291. #if defined(USE_HTTP2)
  2292. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2293. #endif
  2294. /* Once for each domain */
  2295. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2296. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2297. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2298. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2299. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2300. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2301. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2302. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2303. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2304. #if defined(USE_TIMERS)
  2305. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2306. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2307. #endif
  2308. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2309. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2310. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2311. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2312. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2313. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2314. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2315. {"index_files",
  2316. MG_CONFIG_TYPE_STRING_LIST,
  2317. #if defined(USE_LUA)
  2318. "index.xhtml,index.html,index.htm,"
  2319. "index.lp,index.lsp,index.lua,index.cgi,"
  2320. "index.shtml,index.php"},
  2321. #else
  2322. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2323. #endif
  2324. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2325. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2326. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2327. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2328. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2329. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2330. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2331. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  2332. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2333. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2334. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2335. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2336. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2337. #if defined(USE_HTTP2)
  2338. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  2339. * as a minimum in 2020 */
  2340. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  2341. #else
  2342. /* Keep the default (compatibility) */
  2343. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2344. #endif /* defined(USE_HTTP2) */
  2345. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2346. #if defined(USE_LUA)
  2347. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2348. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2349. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2350. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2351. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2352. #endif
  2353. #endif
  2354. #if defined(USE_DUKTAPE)
  2355. /* The support for duktape is still in alpha version state.
  2356. * The name of this config option might change. */
  2357. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2358. #endif
  2359. #if defined(USE_WEBSOCKET)
  2360. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2361. #endif
  2362. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2363. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2364. #endif
  2365. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2366. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2367. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2368. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2369. #if !defined(NO_CACHING)
  2370. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2371. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2372. #endif
  2373. #if !defined(NO_SSL)
  2374. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2375. #endif
  2376. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2377. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2378. #if defined(DAEMONIZE)
  2379. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2380. #endif
  2381. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2382. /* Check if the config_options and the corresponding enum have compatible
  2383. * sizes. */
  2384. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2385. == (NUM_OPTIONS + 1),
  2386. "config_options and enum not sync");
  2387. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2388. struct mg_handler_info {
  2389. /* Name/Pattern of the URI. */
  2390. char *uri;
  2391. size_t uri_len;
  2392. /* handler type */
  2393. int handler_type;
  2394. /* Handler for http/https or authorization requests. */
  2395. mg_request_handler handler;
  2396. unsigned int refcount;
  2397. int removing;
  2398. /* Handler for ws/wss (websocket) requests. */
  2399. mg_websocket_connect_handler connect_handler;
  2400. mg_websocket_ready_handler ready_handler;
  2401. mg_websocket_data_handler data_handler;
  2402. mg_websocket_close_handler close_handler;
  2403. /* accepted subprotocols for ws/wss requests. */
  2404. struct mg_websocket_subprotocols *subprotocols;
  2405. /* Handler for authorization requests */
  2406. mg_authorization_handler auth_handler;
  2407. /* User supplied argument for the handler function. */
  2408. void *cbdata;
  2409. /* next handler in a linked list */
  2410. struct mg_handler_info *next;
  2411. };
  2412. enum {
  2413. CONTEXT_INVALID,
  2414. CONTEXT_SERVER,
  2415. CONTEXT_HTTP_CLIENT,
  2416. CONTEXT_WS_CLIENT
  2417. };
  2418. struct mg_domain_context {
  2419. SSL_CTX *ssl_ctx; /* SSL context */
  2420. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2421. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2422. int64_t ssl_cert_last_mtime;
  2423. /* Server nonce */
  2424. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2425. unsigned long nonce_count; /* Used nonces, used for authentication */
  2426. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2427. /* linked list of shared lua websockets */
  2428. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2429. #endif
  2430. /* Linked list of domains */
  2431. struct mg_domain_context *next;
  2432. };
  2433. /* Stop flag can be "volatile" or require a lock.
  2434. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  2435. * states a read operation for int is always atomic. */
  2436. #ifdef STOP_FLAG_NEEDS_LOCK
  2437. typedef ptrdiff_t volatile stop_flag_t;
  2438. static int
  2439. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2440. {
  2441. stop_flag_t sf = mg_atomic_add(f, 0);
  2442. return (sf == 0);
  2443. }
  2444. static int
  2445. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2446. {
  2447. stop_flag_t sf = mg_atomic_add(f, 0);
  2448. return (sf == 2);
  2449. }
  2450. static void
  2451. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2452. {
  2453. stop_flag_t sf;
  2454. do {
  2455. sf = mg_atomic_compare_and_swap(f, *f, v);
  2456. } while (sf != v);
  2457. }
  2458. #else /* STOP_FLAG_NEEDS_LOCK */
  2459. typedef int volatile stop_flag_t;
  2460. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2461. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2462. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2463. #endif /* STOP_FLAG_NEEDS_LOCK */
  2464. struct mg_context {
  2465. /* Part 1 - Physical context:
  2466. * This holds threads, ports, timeouts, ...
  2467. * set for the entire server, independent from the
  2468. * addressed hostname.
  2469. */
  2470. /* Connection related */
  2471. int context_type; /* See CONTEXT_* above */
  2472. struct socket *listening_sockets;
  2473. struct mg_pollfd *listening_socket_fds;
  2474. unsigned int num_listening_sockets;
  2475. struct mg_connection *worker_connections; /* The connection struct, pre-
  2476. * allocated for each worker */
  2477. #if defined(USE_SERVER_STATS)
  2478. volatile ptrdiff_t active_connections;
  2479. volatile ptrdiff_t max_active_connections;
  2480. volatile ptrdiff_t total_connections;
  2481. volatile ptrdiff_t total_requests;
  2482. volatile int64_t total_data_read;
  2483. volatile int64_t total_data_written;
  2484. #endif
  2485. /* Thread related */
  2486. stop_flag_t stop_flag; /* Should we stop event loop */
  2487. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2488. pthread_t masterthreadid; /* The master thread ID */
  2489. unsigned int
  2490. cfg_worker_threads; /* The number of configured worker threads. */
  2491. pthread_t *worker_threadids; /* The worker thread IDs */
  2492. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2493. /* Connection to thread dispatching */
  2494. #if defined(ALTERNATIVE_QUEUE)
  2495. struct socket *client_socks;
  2496. void **client_wait_events;
  2497. #else
  2498. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2499. worker thread */
  2500. volatile int sq_head; /* Head of the socket queue */
  2501. volatile int sq_tail; /* Tail of the socket queue */
  2502. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2503. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2504. volatile int sq_blocked; /* Status information: sq is full */
  2505. int sq_size; /* No of elements in socket queue */
  2506. #if defined(USE_SERVER_STATS)
  2507. int sq_max_fill;
  2508. #endif /* USE_SERVER_STATS */
  2509. #endif /* ALTERNATIVE_QUEUE */
  2510. /* Memory related */
  2511. unsigned int max_request_size; /* The max request size */
  2512. #if defined(USE_SERVER_STATS)
  2513. struct mg_memory_stat ctx_memory;
  2514. #endif
  2515. /* Operating system related */
  2516. char *systemName; /* What operating system is running */
  2517. time_t start_time; /* Server start time, used for authentication
  2518. * and for diagnstics. */
  2519. #if defined(USE_TIMERS)
  2520. struct ttimers *timers;
  2521. #endif
  2522. /* Lua specific: Background operations and shared websockets */
  2523. #if defined(USE_LUA)
  2524. void *lua_background_state;
  2525. #endif
  2526. /* Server nonce */
  2527. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2528. * ssl_cert_last_mtime, nonce_count, and
  2529. * next (linked list) */
  2530. /* Server callbacks */
  2531. struct mg_callbacks callbacks; /* User-defined callback function */
  2532. void *user_data; /* User-defined data */
  2533. /* Part 2 - Logical domain:
  2534. * This holds hostname, TLS certificate, document root, ...
  2535. * set for a domain hosted at the server.
  2536. * There may be multiple domains hosted at one physical server.
  2537. * The default domain "dd" is the first element of a list of
  2538. * domains.
  2539. */
  2540. struct mg_domain_context dd; /* default domain */
  2541. };
  2542. #if defined(USE_SERVER_STATS)
  2543. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2544. static struct mg_memory_stat *
  2545. get_memory_stat(struct mg_context *ctx)
  2546. {
  2547. if (ctx) {
  2548. return &(ctx->ctx_memory);
  2549. }
  2550. return &mg_common_memory;
  2551. }
  2552. #endif
  2553. enum {
  2554. CONNECTION_TYPE_INVALID = 0,
  2555. CONNECTION_TYPE_REQUEST = 1,
  2556. CONNECTION_TYPE_RESPONSE = 2
  2557. };
  2558. enum {
  2559. PROTOCOL_TYPE_HTTP1 = 0,
  2560. PROTOCOL_TYPE_WEBSOCKET = 1,
  2561. PROTOCOL_TYPE_HTTP2 = 2
  2562. };
  2563. #if defined(USE_HTTP2)
  2564. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2565. #define HTTP2_DYN_TABLE_SIZE (256)
  2566. #endif
  2567. struct mg_http2_connection {
  2568. uint32_t stream_id;
  2569. uint32_t dyn_table_size;
  2570. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2571. };
  2572. #endif
  2573. struct mg_connection {
  2574. int connection_type; /* see CONNECTION_TYPE_* above */
  2575. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2576. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2577. fully sent */
  2578. #ifdef USE_HTTP2
  2579. struct mg_http2_connection http2;
  2580. #endif
  2581. struct mg_request_info request_info;
  2582. struct mg_response_info response_info;
  2583. struct mg_context *phys_ctx;
  2584. struct mg_domain_context *dom_ctx;
  2585. #if defined(USE_SERVER_STATS)
  2586. int conn_state; /* 0 = undef, numerical value may change in different
  2587. * versions. For the current definition, see
  2588. * mg_get_connection_info_impl */
  2589. #endif
  2590. SSL *ssl; /* SSL descriptor */
  2591. struct socket client; /* Connected client */
  2592. time_t conn_birth_time; /* Time (wall clock) when connection was
  2593. * established */
  2594. #if defined(USE_SERVER_STATS)
  2595. time_t conn_close_time; /* Time (wall clock) when connection was
  2596. * closed (or 0 if still open) */
  2597. #endif
  2598. struct timespec req_time; /* Time (since system start) when the request
  2599. * was received */
  2600. int64_t num_bytes_sent; /* Total bytes sent to client */
  2601. int64_t content_len; /* How many bytes of content can be read
  2602. * !is_chunked: Content-Length header value
  2603. * or -1 (until connection closed,
  2604. * not allowed for a request)
  2605. * is_chunked: >= 0, appended gradually
  2606. */
  2607. int64_t consumed_content; /* How many bytes of content have been read */
  2608. int is_chunked; /* Transfer-Encoding is chunked:
  2609. * 0 = not chunked,
  2610. * 1 = chunked, not yet, or some data read,
  2611. * 2 = chunked, has error,
  2612. * 3 = chunked, all data read except trailer,
  2613. * 4 = chunked, all data read
  2614. */
  2615. char *buf; /* Buffer for received data */
  2616. char *path_info; /* PATH_INFO part of the URL */
  2617. int must_close; /* 1 if connection must be closed */
  2618. int accept_gzip; /* 1 if gzip encoding is accepted */
  2619. int in_error_handler; /* 1 if in handler for user defined error
  2620. * pages */
  2621. #if defined(USE_WEBSOCKET)
  2622. int in_websocket_handling; /* 1 if in read_websocket */
  2623. #endif
  2624. int handled_requests; /* Number of requests handled by this connection
  2625. */
  2626. int buf_size; /* Buffer size */
  2627. int request_len; /* Size of the request + headers in a buffer */
  2628. int data_len; /* Total size of data in a buffer */
  2629. int status_code; /* HTTP reply status code, e.g. 200 */
  2630. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2631. * throttle */
  2632. time_t last_throttle_time; /* Last time throttled data was sent */
  2633. int last_throttle_bytes; /* Bytes sent this second */
  2634. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2635. * atomic transmissions for websockets */
  2636. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2637. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2638. #endif
  2639. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2640. * for quick access */
  2641. };
  2642. /* Directory entry */
  2643. struct de {
  2644. struct mg_connection *conn;
  2645. char *file_name;
  2646. struct mg_file_stat file;
  2647. };
  2648. #define mg_cry_internal(conn, fmt, ...) \
  2649. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2650. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2651. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2652. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2653. struct mg_context *ctx,
  2654. const char *func,
  2655. unsigned line,
  2656. const char *fmt,
  2657. ...) PRINTF_ARGS(5, 6);
  2658. #if !defined(NO_THREAD_NAME)
  2659. #if defined(_WIN32) && defined(_MSC_VER)
  2660. /* Set the thread name for debugging purposes in Visual Studio
  2661. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2662. */
  2663. #pragma pack(push, 8)
  2664. typedef struct tagTHREADNAME_INFO {
  2665. DWORD dwType; /* Must be 0x1000. */
  2666. LPCSTR szName; /* Pointer to name (in user addr space). */
  2667. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2668. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2669. } THREADNAME_INFO;
  2670. #pragma pack(pop)
  2671. #elif defined(__linux__)
  2672. #include <sys/prctl.h>
  2673. #include <sys/sendfile.h>
  2674. #if defined(ALTERNATIVE_QUEUE)
  2675. #include <sys/eventfd.h>
  2676. #endif /* ALTERNATIVE_QUEUE */
  2677. #if defined(ALTERNATIVE_QUEUE)
  2678. static void *
  2679. event_create(void)
  2680. {
  2681. int evhdl = eventfd(0, EFD_CLOEXEC);
  2682. int *ret;
  2683. if (evhdl == -1) {
  2684. /* Linux uses -1 on error, Windows NULL. */
  2685. /* However, Linux does not return 0 on success either. */
  2686. return 0;
  2687. }
  2688. ret = (int *)mg_malloc(sizeof(int));
  2689. if (ret) {
  2690. *ret = evhdl;
  2691. } else {
  2692. (void)close(evhdl);
  2693. }
  2694. return (void *)ret;
  2695. }
  2696. static int
  2697. event_wait(void *eventhdl)
  2698. {
  2699. uint64_t u;
  2700. int evhdl, s;
  2701. if (!eventhdl) {
  2702. /* error */
  2703. return 0;
  2704. }
  2705. evhdl = *(int *)eventhdl;
  2706. s = (int)read(evhdl, &u, sizeof(u));
  2707. if (s != sizeof(u)) {
  2708. /* error */
  2709. return 0;
  2710. }
  2711. (void)u; /* the value is not required */
  2712. return 1;
  2713. }
  2714. static int
  2715. event_signal(void *eventhdl)
  2716. {
  2717. uint64_t u = 1;
  2718. int evhdl, s;
  2719. if (!eventhdl) {
  2720. /* error */
  2721. return 0;
  2722. }
  2723. evhdl = *(int *)eventhdl;
  2724. s = (int)write(evhdl, &u, sizeof(u));
  2725. if (s != sizeof(u)) {
  2726. /* error */
  2727. return 0;
  2728. }
  2729. return 1;
  2730. }
  2731. static void
  2732. event_destroy(void *eventhdl)
  2733. {
  2734. int evhdl;
  2735. if (!eventhdl) {
  2736. /* error */
  2737. return;
  2738. }
  2739. evhdl = *(int *)eventhdl;
  2740. close(evhdl);
  2741. mg_free(eventhdl);
  2742. }
  2743. #endif
  2744. #endif
  2745. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2746. struct posix_event {
  2747. pthread_mutex_t mutex;
  2748. pthread_cond_t cond;
  2749. int signaled;
  2750. };
  2751. static void *
  2752. event_create(void)
  2753. {
  2754. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2755. if (ret == 0) {
  2756. /* out of memory */
  2757. return 0;
  2758. }
  2759. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2760. /* pthread mutex not available */
  2761. mg_free(ret);
  2762. return 0;
  2763. }
  2764. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2765. /* pthread cond not available */
  2766. pthread_mutex_destroy(&(ret->mutex));
  2767. mg_free(ret);
  2768. return 0;
  2769. }
  2770. ret->signaled = 0;
  2771. return (void *)ret;
  2772. }
  2773. static int
  2774. event_wait(void *eventhdl)
  2775. {
  2776. struct posix_event *ev = (struct posix_event *)eventhdl;
  2777. pthread_mutex_lock(&(ev->mutex));
  2778. while (!ev->signaled) {
  2779. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2780. }
  2781. ev->signaled = 0;
  2782. pthread_mutex_unlock(&(ev->mutex));
  2783. return 1;
  2784. }
  2785. static int
  2786. event_signal(void *eventhdl)
  2787. {
  2788. struct posix_event *ev = (struct posix_event *)eventhdl;
  2789. pthread_mutex_lock(&(ev->mutex));
  2790. pthread_cond_signal(&(ev->cond));
  2791. ev->signaled = 1;
  2792. pthread_mutex_unlock(&(ev->mutex));
  2793. return 1;
  2794. }
  2795. static void
  2796. event_destroy(void *eventhdl)
  2797. {
  2798. struct posix_event *ev = (struct posix_event *)eventhdl;
  2799. pthread_cond_destroy(&(ev->cond));
  2800. pthread_mutex_destroy(&(ev->mutex));
  2801. mg_free(ev);
  2802. }
  2803. #endif
  2804. static void
  2805. mg_set_thread_name(const char *name)
  2806. {
  2807. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2808. mg_snprintf(
  2809. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2810. #if defined(_WIN32)
  2811. #if defined(_MSC_VER)
  2812. /* Windows and Visual Studio Compiler */
  2813. __try {
  2814. THREADNAME_INFO info;
  2815. info.dwType = 0x1000;
  2816. info.szName = threadName;
  2817. info.dwThreadID = ~0U;
  2818. info.dwFlags = 0;
  2819. RaiseException(0x406D1388,
  2820. 0,
  2821. sizeof(info) / sizeof(ULONG_PTR),
  2822. (ULONG_PTR *)&info);
  2823. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2824. }
  2825. #elif defined(__MINGW32__)
  2826. /* No option known to set thread name for MinGW known */
  2827. #endif
  2828. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2829. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2830. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2831. #if defined(__MACH__)
  2832. /* OS X only current thread name can be changed */
  2833. (void)pthread_setname_np(threadName);
  2834. #else
  2835. (void)pthread_setname_np(pthread_self(), threadName);
  2836. #endif
  2837. #elif defined(__linux__)
  2838. /* On Linux we can use the prctl function.
  2839. * When building for Linux Standard Base (LSB) use
  2840. * NO_THREAD_NAME. However, thread names are a big
  2841. * help for debugging, so the stadard is to set them.
  2842. */
  2843. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2844. #endif
  2845. }
  2846. #else /* !defined(NO_THREAD_NAME) */
  2847. void
  2848. mg_set_thread_name(const char *threadName)
  2849. {
  2850. }
  2851. #endif
  2852. const struct mg_option *
  2853. mg_get_valid_options(void)
  2854. {
  2855. return config_options;
  2856. }
  2857. /* Do not open file (unused) */
  2858. #define MG_FOPEN_MODE_NONE (0)
  2859. /* Open file for read only access */
  2860. #define MG_FOPEN_MODE_READ (1)
  2861. /* Open file for writing, create and overwrite */
  2862. #define MG_FOPEN_MODE_WRITE (2)
  2863. /* Open file for writing, create and append */
  2864. #define MG_FOPEN_MODE_APPEND (4)
  2865. static int
  2866. is_file_opened(const struct mg_file_access *fileacc)
  2867. {
  2868. if (!fileacc) {
  2869. return 0;
  2870. }
  2871. return (fileacc->fp != NULL);
  2872. }
  2873. #if !defined(NO_FILESYSTEMS)
  2874. static int mg_stat(const struct mg_connection *conn,
  2875. const char *path,
  2876. struct mg_file_stat *filep);
  2877. /* Reject files with special characters */
  2878. static int
  2879. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2880. {
  2881. const uint8_t *c = (const uint8_t *)path;
  2882. (void)conn; /* not used */
  2883. if ((c == NULL) || (c[0] == 0)) {
  2884. /* Null pointer or empty path --> suspicious */
  2885. return 1;
  2886. }
  2887. while (*c) {
  2888. if (*c <= 32) {
  2889. /* Control character or space */
  2890. return 0;
  2891. }
  2892. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2893. /* stdin/stdout redirection character */
  2894. return 0;
  2895. }
  2896. #if defined(_WIN32)
  2897. if (*c == '\\') {
  2898. /* Windows backslash */
  2899. return 0;
  2900. }
  2901. #else
  2902. if (*c == '&') {
  2903. /* Linux ampersand */
  2904. return 0;
  2905. }
  2906. #endif
  2907. c++;
  2908. }
  2909. /* Nothing suspicious found */
  2910. return 0;
  2911. }
  2912. /* mg_fopen will open a file either in memory or on the disk.
  2913. * The input parameter path is a string in UTF-8 encoding.
  2914. * The input parameter mode is MG_FOPEN_MODE_*
  2915. * On success, fp will be set in the output struct mg_file.
  2916. * All status members will also be set.
  2917. * The function returns 1 on success, 0 on error. */
  2918. static int
  2919. mg_fopen(const struct mg_connection *conn,
  2920. const char *path,
  2921. int mode,
  2922. struct mg_file *filep)
  2923. {
  2924. int found;
  2925. if (!filep) {
  2926. return 0;
  2927. }
  2928. filep->access.fp = NULL;
  2929. if (mg_path_suspicious(conn, path)) {
  2930. return 0;
  2931. }
  2932. /* filep is initialized in mg_stat: all fields with memset to,
  2933. * some fields like size and modification date with values */
  2934. found = mg_stat(conn, path, &(filep->stat));
  2935. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2936. /* file does not exist and will not be created */
  2937. return 0;
  2938. }
  2939. #if defined(_WIN32)
  2940. {
  2941. wchar_t wbuf[W_PATH_MAX];
  2942. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2943. switch (mode) {
  2944. case MG_FOPEN_MODE_READ:
  2945. filep->access.fp = _wfopen(wbuf, L"rb");
  2946. break;
  2947. case MG_FOPEN_MODE_WRITE:
  2948. filep->access.fp = _wfopen(wbuf, L"wb");
  2949. break;
  2950. case MG_FOPEN_MODE_APPEND:
  2951. filep->access.fp = _wfopen(wbuf, L"ab");
  2952. break;
  2953. }
  2954. }
  2955. #else
  2956. /* Linux et al already use unicode. No need to convert. */
  2957. switch (mode) {
  2958. case MG_FOPEN_MODE_READ:
  2959. filep->access.fp = fopen(path, "r");
  2960. break;
  2961. case MG_FOPEN_MODE_WRITE:
  2962. filep->access.fp = fopen(path, "w");
  2963. break;
  2964. case MG_FOPEN_MODE_APPEND:
  2965. filep->access.fp = fopen(path, "a");
  2966. break;
  2967. }
  2968. #endif
  2969. if (!found) {
  2970. /* File did not exist before fopen was called.
  2971. * Maybe it has been created now. Get stat info
  2972. * like creation time now. */
  2973. found = mg_stat(conn, path, &(filep->stat));
  2974. (void)found;
  2975. }
  2976. /* return OK if file is opened */
  2977. return (filep->access.fp != NULL);
  2978. }
  2979. /* return 0 on success, just like fclose */
  2980. static int
  2981. mg_fclose(struct mg_file_access *fileacc)
  2982. {
  2983. int ret = -1;
  2984. if (fileacc != NULL) {
  2985. if (fileacc->fp != NULL) {
  2986. ret = fclose(fileacc->fp);
  2987. }
  2988. /* reset all members of fileacc */
  2989. memset(fileacc, 0, sizeof(*fileacc));
  2990. }
  2991. return ret;
  2992. }
  2993. #endif /* NO_FILESYSTEMS */
  2994. static void
  2995. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2996. {
  2997. for (; *src != '\0' && n > 1; n--) {
  2998. *dst++ = *src++;
  2999. }
  3000. *dst = '\0';
  3001. }
  3002. static int
  3003. lowercase(const char *s)
  3004. {
  3005. return tolower((unsigned char)*s);
  3006. }
  3007. int
  3008. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  3009. {
  3010. int diff = 0;
  3011. if (len > 0) {
  3012. do {
  3013. diff = lowercase(s1++) - lowercase(s2++);
  3014. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  3015. }
  3016. return diff;
  3017. }
  3018. int
  3019. mg_strcasecmp(const char *s1, const char *s2)
  3020. {
  3021. int diff;
  3022. do {
  3023. diff = lowercase(s1++) - lowercase(s2++);
  3024. } while (diff == 0 && s1[-1] != '\0');
  3025. return diff;
  3026. }
  3027. static char *
  3028. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3029. {
  3030. char *p;
  3031. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3032. * defined */
  3033. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3034. mg_strlcpy(p, ptr, len + 1);
  3035. }
  3036. return p;
  3037. }
  3038. static char *
  3039. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3040. {
  3041. return mg_strndup_ctx(str, strlen(str), ctx);
  3042. }
  3043. static char *
  3044. mg_strdup(const char *str)
  3045. {
  3046. return mg_strndup_ctx(str, strlen(str), NULL);
  3047. }
  3048. static const char *
  3049. mg_strcasestr(const char *big_str, const char *small_str)
  3050. {
  3051. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3052. if (big_len >= small_len) {
  3053. for (i = 0; i <= (big_len - small_len); i++) {
  3054. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3055. return big_str + i;
  3056. }
  3057. }
  3058. }
  3059. return NULL;
  3060. }
  3061. /* Return null terminated string of given maximum length.
  3062. * Report errors if length is exceeded. */
  3063. static void
  3064. mg_vsnprintf(const struct mg_connection *conn,
  3065. int *truncated,
  3066. char *buf,
  3067. size_t buflen,
  3068. const char *fmt,
  3069. va_list ap)
  3070. {
  3071. int n, ok;
  3072. if (buflen == 0) {
  3073. if (truncated) {
  3074. *truncated = 1;
  3075. }
  3076. return;
  3077. }
  3078. #if defined(__clang__)
  3079. #pragma clang diagnostic push
  3080. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3081. /* Using fmt as a non-literal is intended here, since it is mostly called
  3082. * indirectly by mg_snprintf */
  3083. #endif
  3084. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3085. ok = (n >= 0) && ((size_t)n < buflen);
  3086. #if defined(__clang__)
  3087. #pragma clang diagnostic pop
  3088. #endif
  3089. if (ok) {
  3090. if (truncated) {
  3091. *truncated = 0;
  3092. }
  3093. } else {
  3094. if (truncated) {
  3095. *truncated = 1;
  3096. }
  3097. mg_cry_internal(conn,
  3098. "truncating vsnprintf buffer: [%.*s]",
  3099. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3100. buf);
  3101. n = (int)buflen - 1;
  3102. }
  3103. buf[n] = '\0';
  3104. }
  3105. static void
  3106. mg_snprintf(const struct mg_connection *conn,
  3107. int *truncated,
  3108. char *buf,
  3109. size_t buflen,
  3110. const char *fmt,
  3111. ...)
  3112. {
  3113. va_list ap;
  3114. va_start(ap, fmt);
  3115. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3116. va_end(ap);
  3117. }
  3118. static int
  3119. get_option_index(const char *name)
  3120. {
  3121. int i;
  3122. for (i = 0; config_options[i].name != NULL; i++) {
  3123. if (strcmp(config_options[i].name, name) == 0) {
  3124. return i;
  3125. }
  3126. }
  3127. return -1;
  3128. }
  3129. const char *
  3130. mg_get_option(const struct mg_context *ctx, const char *name)
  3131. {
  3132. int i;
  3133. if ((i = get_option_index(name)) == -1) {
  3134. return NULL;
  3135. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3136. return "";
  3137. } else {
  3138. return ctx->dd.config[i];
  3139. }
  3140. }
  3141. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3142. struct mg_context *
  3143. mg_get_context(const struct mg_connection *conn)
  3144. {
  3145. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3146. }
  3147. void *
  3148. mg_get_user_data(const struct mg_context *ctx)
  3149. {
  3150. return (ctx == NULL) ? NULL : ctx->user_data;
  3151. }
  3152. void *
  3153. mg_get_user_context_data(const struct mg_connection *conn)
  3154. {
  3155. return mg_get_user_data(mg_get_context(conn));
  3156. }
  3157. void *
  3158. mg_get_thread_pointer(const struct mg_connection *conn)
  3159. {
  3160. /* both methods should return the same pointer */
  3161. if (conn) {
  3162. /* quick access, in case conn is known */
  3163. return conn->tls_user_ptr;
  3164. } else {
  3165. /* otherwise get pointer from thread local storage (TLS) */
  3166. struct mg_workerTLS *tls =
  3167. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3168. return tls->user_ptr;
  3169. }
  3170. }
  3171. void
  3172. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3173. {
  3174. if (conn != NULL) {
  3175. conn->request_info.conn_data = data;
  3176. }
  3177. }
  3178. void *
  3179. mg_get_user_connection_data(const struct mg_connection *conn)
  3180. {
  3181. if (conn != NULL) {
  3182. return conn->request_info.conn_data;
  3183. }
  3184. return NULL;
  3185. }
  3186. #if defined(MG_LEGACY_INTERFACE)
  3187. /* Deprecated: Use mg_get_server_ports instead. */
  3188. size_t
  3189. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3190. {
  3191. size_t i;
  3192. if (!ctx) {
  3193. return 0;
  3194. }
  3195. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3196. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3197. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3198. }
  3199. return i;
  3200. }
  3201. #endif
  3202. int
  3203. mg_get_server_ports(const struct mg_context *ctx,
  3204. int size,
  3205. struct mg_server_port *ports)
  3206. {
  3207. int i, cnt = 0;
  3208. if (size <= 0) {
  3209. return -1;
  3210. }
  3211. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3212. if (!ctx) {
  3213. return -1;
  3214. }
  3215. if (!ctx->listening_sockets) {
  3216. return -1;
  3217. }
  3218. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3219. ports[cnt].port =
  3220. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3221. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3222. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3223. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3224. /* IPv4 */
  3225. ports[cnt].protocol = 1;
  3226. cnt++;
  3227. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3228. /* IPv6 */
  3229. ports[cnt].protocol = 3;
  3230. cnt++;
  3231. }
  3232. }
  3233. return cnt;
  3234. }
  3235. static void
  3236. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3237. {
  3238. buf[0] = '\0';
  3239. if (!usa) {
  3240. return;
  3241. }
  3242. if (usa->sa.sa_family == AF_INET) {
  3243. getnameinfo(&usa->sa,
  3244. sizeof(usa->sin),
  3245. buf,
  3246. (unsigned)len,
  3247. NULL,
  3248. 0,
  3249. NI_NUMERICHOST);
  3250. }
  3251. #if defined(USE_IPV6)
  3252. else if (usa->sa.sa_family == AF_INET6) {
  3253. getnameinfo(&usa->sa,
  3254. sizeof(usa->sin6),
  3255. buf,
  3256. (unsigned)len,
  3257. NULL,
  3258. 0,
  3259. NI_NUMERICHOST);
  3260. }
  3261. #endif
  3262. }
  3263. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3264. * included in all responses other than 100, 101, 5xx. */
  3265. static void
  3266. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3267. {
  3268. #if !defined(REENTRANT_TIME)
  3269. struct tm *tm;
  3270. tm = ((t != NULL) ? gmtime(t) : NULL);
  3271. if (tm != NULL) {
  3272. #else
  3273. struct tm _tm;
  3274. struct tm *tm = &_tm;
  3275. if (t != NULL) {
  3276. gmtime_r(t, tm);
  3277. #endif
  3278. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3279. } else {
  3280. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3281. buf[buf_len - 1] = '\0';
  3282. }
  3283. }
  3284. /* difftime for struct timespec. Return value is in seconds. */
  3285. static double
  3286. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3287. {
  3288. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3289. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3290. }
  3291. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3292. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3293. const char *func,
  3294. unsigned line,
  3295. const char *fmt,
  3296. va_list ap);
  3297. #include "external_mg_cry_internal_impl.inl"
  3298. #elif !defined(NO_FILESYSTEMS)
  3299. /* Print error message to the opened error log stream. */
  3300. static void
  3301. mg_cry_internal_impl(const struct mg_connection *conn,
  3302. const char *func,
  3303. unsigned line,
  3304. const char *fmt,
  3305. va_list ap)
  3306. {
  3307. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3308. struct mg_file fi;
  3309. time_t timestamp;
  3310. /* Unused, in the RELEASE build */
  3311. (void)func;
  3312. (void)line;
  3313. #if defined(GCC_DIAGNOSTIC)
  3314. #pragma GCC diagnostic push
  3315. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3316. #endif
  3317. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3318. #if defined(GCC_DIAGNOSTIC)
  3319. #pragma GCC diagnostic pop
  3320. #endif
  3321. buf[sizeof(buf) - 1] = 0;
  3322. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3323. if (!conn) {
  3324. puts(buf);
  3325. return;
  3326. }
  3327. /* Do not lock when getting the callback value, here and below.
  3328. * I suppose this is fine, since function cannot disappear in the
  3329. * same way string option can. */
  3330. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3331. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3332. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3333. if (mg_fopen(conn,
  3334. conn->dom_ctx->config[ERROR_LOG_FILE],
  3335. MG_FOPEN_MODE_APPEND,
  3336. &fi)
  3337. == 0) {
  3338. fi.access.fp = NULL;
  3339. }
  3340. } else {
  3341. fi.access.fp = NULL;
  3342. }
  3343. if (fi.access.fp != NULL) {
  3344. flockfile(fi.access.fp);
  3345. timestamp = time(NULL);
  3346. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3347. fprintf(fi.access.fp,
  3348. "[%010lu] [error] [client %s] ",
  3349. (unsigned long)timestamp,
  3350. src_addr);
  3351. if (conn->request_info.request_method != NULL) {
  3352. fprintf(fi.access.fp,
  3353. "%s %s: ",
  3354. conn->request_info.request_method,
  3355. conn->request_info.request_uri
  3356. ? conn->request_info.request_uri
  3357. : "");
  3358. }
  3359. fprintf(fi.access.fp, "%s", buf);
  3360. fputc('\n', fi.access.fp);
  3361. fflush(fi.access.fp);
  3362. funlockfile(fi.access.fp);
  3363. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3364. * mg_cry here anyway ;-) */
  3365. }
  3366. }
  3367. }
  3368. #else
  3369. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3370. #endif /* Externally provided function */
  3371. /* Construct fake connection structure. Used for logging, if connection
  3372. * is not applicable at the moment of logging. */
  3373. static struct mg_connection *
  3374. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3375. {
  3376. static const struct mg_connection conn_zero = {0};
  3377. *fc = conn_zero;
  3378. fc->phys_ctx = ctx;
  3379. fc->dom_ctx = &(ctx->dd);
  3380. return fc;
  3381. }
  3382. static void
  3383. mg_cry_internal_wrap(const struct mg_connection *conn,
  3384. struct mg_context *ctx,
  3385. const char *func,
  3386. unsigned line,
  3387. const char *fmt,
  3388. ...)
  3389. {
  3390. va_list ap;
  3391. va_start(ap, fmt);
  3392. if (!conn && ctx) {
  3393. struct mg_connection fc;
  3394. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3395. } else {
  3396. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3397. }
  3398. va_end(ap);
  3399. }
  3400. void
  3401. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3402. {
  3403. va_list ap;
  3404. va_start(ap, fmt);
  3405. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3406. va_end(ap);
  3407. }
  3408. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3409. const char *
  3410. mg_version(void)
  3411. {
  3412. return CIVETWEB_VERSION;
  3413. }
  3414. const struct mg_request_info *
  3415. mg_get_request_info(const struct mg_connection *conn)
  3416. {
  3417. if (!conn) {
  3418. return NULL;
  3419. }
  3420. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3421. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3422. char txt[16];
  3423. struct mg_workerTLS *tls =
  3424. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3425. sprintf(txt, "%03i", conn->response_info.status_code);
  3426. if (strlen(txt) == 3) {
  3427. memcpy(tls->txtbuf, txt, 4);
  3428. } else {
  3429. strcpy(tls->txtbuf, "ERR");
  3430. }
  3431. ((struct mg_connection *)conn)->request_info.local_uri =
  3432. ((struct mg_connection *)conn)->request_info.request_uri =
  3433. tls->txtbuf; /* use thread safe buffer */
  3434. ((struct mg_connection *)conn)->request_info.num_headers =
  3435. conn->response_info.num_headers;
  3436. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3437. conn->response_info.http_headers,
  3438. sizeof(conn->response_info.http_headers));
  3439. } else
  3440. #endif
  3441. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3442. return NULL;
  3443. }
  3444. return &conn->request_info;
  3445. }
  3446. const struct mg_response_info *
  3447. mg_get_response_info(const struct mg_connection *conn)
  3448. {
  3449. if (!conn) {
  3450. return NULL;
  3451. }
  3452. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3453. return NULL;
  3454. }
  3455. return &conn->response_info;
  3456. }
  3457. static const char *
  3458. get_proto_name(const struct mg_connection *conn)
  3459. {
  3460. #if defined(__clang__)
  3461. #pragma clang diagnostic push
  3462. #pragma clang diagnostic ignored "-Wunreachable-code"
  3463. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3464. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3465. * unreachable, but splitting into four different #ifdef clauses here is more
  3466. * complicated.
  3467. */
  3468. #endif
  3469. const struct mg_request_info *ri = &conn->request_info;
  3470. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3471. ? (ri->is_ssl ? "wss" : "ws")
  3472. : (ri->is_ssl ? "https" : "http"));
  3473. return proto;
  3474. #if defined(__clang__)
  3475. #pragma clang diagnostic pop
  3476. #endif
  3477. }
  3478. static int
  3479. mg_construct_local_link(const struct mg_connection *conn,
  3480. char *buf,
  3481. size_t buflen,
  3482. const char *define_proto,
  3483. int define_port,
  3484. const char *define_uri)
  3485. {
  3486. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3487. return -1;
  3488. } else {
  3489. int truncated = 0;
  3490. const struct mg_request_info *ri = &conn->request_info;
  3491. const char *proto =
  3492. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3493. const char *uri =
  3494. (define_uri != NULL)
  3495. ? define_uri
  3496. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3497. int port = (define_port > 0)
  3498. ? define_port
  3499. : htons(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  3500. int default_port = 80;
  3501. if (uri == NULL) {
  3502. return -1;
  3503. }
  3504. if (define_proto) {
  3505. /* If we got a protocol name, use the default port accordingly. */
  3506. if ((0 == strcmp(define_proto, "https"))
  3507. || (0 == strcmp(define_proto, "wss"))) {
  3508. default_port = 443;
  3509. }
  3510. } else if (ri->is_ssl) {
  3511. /* If we did not get a protocol name, use TLS as default if it is
  3512. * already used. */
  3513. default_port = 443;
  3514. }
  3515. {
  3516. #if defined(USE_IPV6)
  3517. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3518. #endif
  3519. int auth_domain_check_enabled =
  3520. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3521. && (!mg_strcasecmp(
  3522. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3523. const char *server_domain =
  3524. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3525. char portstr[16];
  3526. char server_ip[48];
  3527. if (port != default_port) {
  3528. sprintf(portstr, ":%u", (unsigned)port);
  3529. } else {
  3530. portstr[0] = 0;
  3531. }
  3532. if (!auth_domain_check_enabled || !server_domain) {
  3533. sockaddr_to_string(server_ip,
  3534. sizeof(server_ip),
  3535. &conn->client.lsa);
  3536. server_domain = server_ip;
  3537. }
  3538. mg_snprintf(conn,
  3539. &truncated,
  3540. buf,
  3541. buflen,
  3542. #if defined(USE_IPV6)
  3543. "%s://%s%s%s%s%s",
  3544. proto,
  3545. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3546. server_domain,
  3547. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3548. #else
  3549. "%s://%s%s%s",
  3550. proto,
  3551. server_domain,
  3552. #endif
  3553. portstr,
  3554. ri->local_uri);
  3555. if (truncated) {
  3556. return -1;
  3557. }
  3558. return 0;
  3559. }
  3560. }
  3561. }
  3562. int
  3563. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3564. {
  3565. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3566. }
  3567. /* Skip the characters until one of the delimiters characters found.
  3568. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3569. * Advance pointer to buffer to the next word. Return found 0-terminated
  3570. * word.
  3571. * Delimiters can be quoted with quotechar. */
  3572. static char *
  3573. skip_quoted(char **buf,
  3574. const char *delimiters,
  3575. const char *whitespace,
  3576. char quotechar)
  3577. {
  3578. char *p, *begin_word, *end_word, *end_whitespace;
  3579. begin_word = *buf;
  3580. end_word = begin_word + strcspn(begin_word, delimiters);
  3581. /* Check for quotechar */
  3582. if (end_word > begin_word) {
  3583. p = end_word - 1;
  3584. while (*p == quotechar) {
  3585. /* While the delimiter is quoted, look for the next delimiter.
  3586. */
  3587. /* This happens, e.g., in calls from parse_auth_header,
  3588. * if the user name contains a " character. */
  3589. /* If there is anything beyond end_word, copy it. */
  3590. if (*end_word != '\0') {
  3591. size_t end_off = strcspn(end_word + 1, delimiters);
  3592. memmove(p, end_word, end_off + 1);
  3593. p += end_off; /* p must correspond to end_word - 1 */
  3594. end_word += end_off + 1;
  3595. } else {
  3596. *p = '\0';
  3597. break;
  3598. }
  3599. }
  3600. for (p++; p < end_word; p++) {
  3601. *p = '\0';
  3602. }
  3603. }
  3604. if (*end_word == '\0') {
  3605. *buf = end_word;
  3606. } else {
  3607. #if defined(GCC_DIAGNOSTIC)
  3608. /* Disable spurious conversion warning for GCC */
  3609. #pragma GCC diagnostic push
  3610. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3611. #endif /* defined(GCC_DIAGNOSTIC) */
  3612. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3613. #if defined(GCC_DIAGNOSTIC)
  3614. #pragma GCC diagnostic pop
  3615. #endif /* defined(GCC_DIAGNOSTIC) */
  3616. for (p = end_word; p < end_whitespace; p++) {
  3617. *p = '\0';
  3618. }
  3619. *buf = end_whitespace;
  3620. }
  3621. return begin_word;
  3622. }
  3623. /* Return HTTP header value, or NULL if not found. */
  3624. static const char *
  3625. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3626. {
  3627. int i;
  3628. for (i = 0; i < num_hdr; i++) {
  3629. if (!mg_strcasecmp(name, hdr[i].name)) {
  3630. return hdr[i].value;
  3631. }
  3632. }
  3633. return NULL;
  3634. }
  3635. #if defined(USE_WEBSOCKET)
  3636. /* Retrieve requested HTTP header multiple values, and return the number of
  3637. * found occurrences */
  3638. static int
  3639. get_req_headers(const struct mg_request_info *ri,
  3640. const char *name,
  3641. const char **output,
  3642. int output_max_size)
  3643. {
  3644. int i;
  3645. int cnt = 0;
  3646. if (ri) {
  3647. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3648. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3649. output[cnt++] = ri->http_headers[i].value;
  3650. }
  3651. }
  3652. }
  3653. return cnt;
  3654. }
  3655. #endif
  3656. const char *
  3657. mg_get_header(const struct mg_connection *conn, const char *name)
  3658. {
  3659. if (!conn) {
  3660. return NULL;
  3661. }
  3662. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3663. return get_header(conn->request_info.http_headers,
  3664. conn->request_info.num_headers,
  3665. name);
  3666. }
  3667. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3668. return get_header(conn->response_info.http_headers,
  3669. conn->response_info.num_headers,
  3670. name);
  3671. }
  3672. return NULL;
  3673. }
  3674. static const char *
  3675. get_http_version(const struct mg_connection *conn)
  3676. {
  3677. if (!conn) {
  3678. return NULL;
  3679. }
  3680. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3681. return conn->request_info.http_version;
  3682. }
  3683. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3684. return conn->response_info.http_version;
  3685. }
  3686. return NULL;
  3687. }
  3688. /* A helper function for traversing a comma separated list of values.
  3689. * It returns a list pointer shifted to the next value, or NULL if the end
  3690. * of the list found.
  3691. * Value is stored in val vector. If value has form "x=y", then eq_val
  3692. * vector is initialized to point to the "y" part, and val vector length
  3693. * is adjusted to point only to "x". */
  3694. static const char *
  3695. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3696. {
  3697. int end;
  3698. reparse:
  3699. if (val == NULL || list == NULL || *list == '\0') {
  3700. /* End of the list */
  3701. return NULL;
  3702. }
  3703. /* Skip over leading LWS */
  3704. while (*list == ' ' || *list == '\t')
  3705. list++;
  3706. val->ptr = list;
  3707. if ((list = strchr(val->ptr, ',')) != NULL) {
  3708. /* Comma found. Store length and shift the list ptr */
  3709. val->len = ((size_t)(list - val->ptr));
  3710. list++;
  3711. } else {
  3712. /* This value is the last one */
  3713. list = val->ptr + strlen(val->ptr);
  3714. val->len = ((size_t)(list - val->ptr));
  3715. }
  3716. /* Adjust length for trailing LWS */
  3717. end = (int)val->len - 1;
  3718. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3719. end--;
  3720. val->len = (size_t)(end) + (size_t)(1);
  3721. if (val->len == 0) {
  3722. /* Ignore any empty entries. */
  3723. goto reparse;
  3724. }
  3725. if (eq_val != NULL) {
  3726. /* Value has form "x=y", adjust pointers and lengths
  3727. * so that val points to "x", and eq_val points to "y". */
  3728. eq_val->len = 0;
  3729. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3730. if (eq_val->ptr != NULL) {
  3731. eq_val->ptr++; /* Skip over '=' character */
  3732. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3733. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3734. }
  3735. }
  3736. return list;
  3737. }
  3738. /* A helper function for checking if a comma separated list of values
  3739. * contains
  3740. * the given option (case insensitvely).
  3741. * 'header' can be NULL, in which case false is returned. */
  3742. static int
  3743. header_has_option(const char *header, const char *option)
  3744. {
  3745. struct vec opt_vec;
  3746. struct vec eq_vec;
  3747. DEBUG_ASSERT(option != NULL);
  3748. DEBUG_ASSERT(option[0] != '\0');
  3749. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3750. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3751. return 1;
  3752. }
  3753. return 0;
  3754. }
  3755. /* Perform case-insensitive match of string against pattern */
  3756. static ptrdiff_t
  3757. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3758. {
  3759. const char *or_str;
  3760. ptrdiff_t i, j, len, res;
  3761. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3762. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3763. return (res > 0) ? res
  3764. : match_prefix(or_str + 1,
  3765. (size_t)((pattern + pattern_len)
  3766. - (or_str + 1)),
  3767. str);
  3768. }
  3769. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3770. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3771. continue;
  3772. } else if (pattern[i] == '$') {
  3773. return (str[j] == '\0') ? j : -1;
  3774. } else if (pattern[i] == '*') {
  3775. i++;
  3776. if (pattern[i] == '*') {
  3777. i++;
  3778. len = (ptrdiff_t)strlen(str + j);
  3779. } else {
  3780. len = (ptrdiff_t)strcspn(str + j, "/");
  3781. }
  3782. if (i == (ptrdiff_t)pattern_len) {
  3783. return j + len;
  3784. }
  3785. do {
  3786. res = match_prefix(pattern + i,
  3787. (pattern_len - (size_t)i),
  3788. str + j + len);
  3789. } while (res == -1 && len-- > 0);
  3790. return (res == -1) ? -1 : j + res + len;
  3791. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3792. return -1;
  3793. }
  3794. }
  3795. return (ptrdiff_t)j;
  3796. }
  3797. static ptrdiff_t
  3798. match_prefix_strlen(const char *pattern, const char *str)
  3799. {
  3800. if (pattern == NULL) {
  3801. return -1;
  3802. }
  3803. return match_prefix(pattern, strlen(pattern), str);
  3804. }
  3805. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3806. * This function must tolerate situations when connection info is not
  3807. * set up, for example if request parsing failed. */
  3808. static int
  3809. should_keep_alive(const struct mg_connection *conn)
  3810. {
  3811. const char *http_version;
  3812. const char *header;
  3813. /* First satisfy needs of the server */
  3814. if ((conn == NULL) || conn->must_close) {
  3815. /* Close, if civetweb framework needs to close */
  3816. return 0;
  3817. }
  3818. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3819. /* Close, if keep alive is not enabled */
  3820. return 0;
  3821. }
  3822. /* Check explicit wish of the client */
  3823. header = mg_get_header(conn, "Connection");
  3824. if (header) {
  3825. /* If there is a connection header from the client, obey */
  3826. if (header_has_option(header, "keep-alive")) {
  3827. return 1;
  3828. }
  3829. return 0;
  3830. }
  3831. /* Use default of the standard */
  3832. http_version = get_http_version(conn);
  3833. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3834. /* HTTP 1.1 default is keep alive */
  3835. return 1;
  3836. }
  3837. /* HTTP 1.0 (and earlier) default is to close the connection */
  3838. return 0;
  3839. }
  3840. static int
  3841. should_decode_url(const struct mg_connection *conn)
  3842. {
  3843. if (!conn || !conn->dom_ctx) {
  3844. return 0;
  3845. }
  3846. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3847. }
  3848. static const char *
  3849. suggest_connection_header(const struct mg_connection *conn)
  3850. {
  3851. return should_keep_alive(conn) ? "keep-alive" : "close";
  3852. }
  3853. #include "response.inl"
  3854. static void
  3855. send_no_cache_header(struct mg_connection *conn)
  3856. {
  3857. /* Send all current and obsolete cache opt-out directives. */
  3858. mg_response_add_header(conn,
  3859. "Cache-Control",
  3860. "no-cache, no-store, "
  3861. "must-revalidate, private, max-age=0",
  3862. -1);
  3863. mg_response_add_header(conn, "Expires", "0", -1);
  3864. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3865. /* Obsolete, but still send it for HTTP/1.0 */
  3866. mg_response_add_header(conn, "Pragma", "no-cache", -1);
  3867. }
  3868. }
  3869. static void
  3870. send_static_cache_header(struct mg_connection *conn)
  3871. {
  3872. #if !defined(NO_CACHING)
  3873. int max_age;
  3874. char val[64];
  3875. const char *cache_control =
  3876. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3877. /* If there is a full cache-control option configured,0 use it */
  3878. if (cache_control != NULL) {
  3879. mg_response_add_header(conn, "Cache-Control", cache_control, -1);
  3880. return;
  3881. }
  3882. /* Read the server config to check how long a file may be cached.
  3883. * The configuration is in seconds. */
  3884. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3885. if (max_age <= 0) {
  3886. /* 0 means "do not cache". All values <0 are reserved
  3887. * and may be used differently in the future. */
  3888. /* If a file should not be cached, do not only send
  3889. * max-age=0, but also pragmas and Expires headers. */
  3890. send_no_cache_header(conn);
  3891. return;
  3892. }
  3893. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3894. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3895. /* See also https://www.mnot.net/cache_docs/ */
  3896. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3897. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3898. * leap
  3899. * year to 31622400 seconds. For the moment, we just send whatever has
  3900. * been configured, still the behavior for >1 year should be considered
  3901. * as undefined. */
  3902. mg_snprintf(
  3903. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3904. mg_response_add_header(conn, "Cache-Control", val, -1);
  3905. #else /* NO_CACHING */
  3906. send_no_cache_header(conn);
  3907. #endif /* !NO_CACHING */
  3908. }
  3909. static void
  3910. send_additional_header(struct mg_connection *conn)
  3911. {
  3912. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3913. #if !defined(NO_SSL)
  3914. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3915. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3916. if (max_age >= 0) {
  3917. char val[64];
  3918. mg_snprintf(conn,
  3919. NULL,
  3920. val,
  3921. sizeof(val),
  3922. "max-age=%lu",
  3923. (unsigned long)max_age);
  3924. mg_response_add_header(conn, "Strict-Transport-Security", val, -1);
  3925. }
  3926. }
  3927. #endif
  3928. if (header && header[0]) {
  3929. mg_response_add_headerlines(conn, header);
  3930. }
  3931. }
  3932. #if !defined(NO_FILESYSTEMS)
  3933. static void handle_file_based_request(struct mg_connection *conn,
  3934. const char *path,
  3935. struct mg_file *filep);
  3936. #endif /* NO_FILESYSTEMS */
  3937. const char *
  3938. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3939. {
  3940. /* See IANA HTTP status code assignment:
  3941. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3942. */
  3943. switch (response_code) {
  3944. /* RFC2616 Section 10.1 - Informational 1xx */
  3945. case 100:
  3946. return "Continue"; /* RFC2616 Section 10.1.1 */
  3947. case 101:
  3948. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3949. case 102:
  3950. return "Processing"; /* RFC2518 Section 10.1 */
  3951. /* RFC2616 Section 10.2 - Successful 2xx */
  3952. case 200:
  3953. return "OK"; /* RFC2616 Section 10.2.1 */
  3954. case 201:
  3955. return "Created"; /* RFC2616 Section 10.2.2 */
  3956. case 202:
  3957. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3958. case 203:
  3959. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3960. case 204:
  3961. return "No Content"; /* RFC2616 Section 10.2.5 */
  3962. case 205:
  3963. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3964. case 206:
  3965. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3966. case 207:
  3967. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3968. */
  3969. case 208:
  3970. return "Already Reported"; /* RFC5842 Section 7.1 */
  3971. case 226:
  3972. return "IM used"; /* RFC3229 Section 10.4.1 */
  3973. /* RFC2616 Section 10.3 - Redirection 3xx */
  3974. case 300:
  3975. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3976. case 301:
  3977. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3978. case 302:
  3979. return "Found"; /* RFC2616 Section 10.3.3 */
  3980. case 303:
  3981. return "See Other"; /* RFC2616 Section 10.3.4 */
  3982. case 304:
  3983. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3984. case 305:
  3985. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3986. case 307:
  3987. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3988. case 308:
  3989. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3990. /* RFC2616 Section 10.4 - Client Error 4xx */
  3991. case 400:
  3992. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3993. case 401:
  3994. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3995. case 402:
  3996. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3997. case 403:
  3998. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3999. case 404:
  4000. return "Not Found"; /* RFC2616 Section 10.4.5 */
  4001. case 405:
  4002. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  4003. case 406:
  4004. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  4005. case 407:
  4006. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  4007. case 408:
  4008. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  4009. case 409:
  4010. return "Conflict"; /* RFC2616 Section 10.4.10 */
  4011. case 410:
  4012. return "Gone"; /* RFC2616 Section 10.4.11 */
  4013. case 411:
  4014. return "Length Required"; /* RFC2616 Section 10.4.12 */
  4015. case 412:
  4016. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  4017. case 413:
  4018. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  4019. case 414:
  4020. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  4021. case 415:
  4022. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  4023. case 416:
  4024. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  4025. */
  4026. case 417:
  4027. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  4028. case 421:
  4029. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  4030. case 422:
  4031. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  4032. * Section 11.2 */
  4033. case 423:
  4034. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  4035. case 424:
  4036. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  4037. * Section 11.4 */
  4038. case 426:
  4039. return "Upgrade Required"; /* RFC 2817 Section 4 */
  4040. case 428:
  4041. return "Precondition Required"; /* RFC 6585, Section 3 */
  4042. case 429:
  4043. return "Too Many Requests"; /* RFC 6585, Section 4 */
  4044. case 431:
  4045. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  4046. case 451:
  4047. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  4048. * Section 3 */
  4049. /* RFC2616 Section 10.5 - Server Error 5xx */
  4050. case 500:
  4051. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  4052. case 501:
  4053. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  4054. case 502:
  4055. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4056. case 503:
  4057. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4058. case 504:
  4059. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4060. case 505:
  4061. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4062. case 506:
  4063. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4064. case 507:
  4065. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4066. * Section 11.5 */
  4067. case 508:
  4068. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4069. case 510:
  4070. return "Not Extended"; /* RFC 2774, Section 7 */
  4071. case 511:
  4072. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4073. /* Other status codes, not shown in the IANA HTTP status code
  4074. * assignment.
  4075. * E.g., "de facto" standards due to common use, ... */
  4076. case 418:
  4077. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4078. case 419:
  4079. return "Authentication Timeout"; /* common use */
  4080. case 420:
  4081. return "Enhance Your Calm"; /* common use */
  4082. case 440:
  4083. return "Login Timeout"; /* common use */
  4084. case 509:
  4085. return "Bandwidth Limit Exceeded"; /* common use */
  4086. default:
  4087. /* This error code is unknown. This should not happen. */
  4088. if (conn) {
  4089. mg_cry_internal(conn,
  4090. "Unknown HTTP response code: %u",
  4091. response_code);
  4092. }
  4093. /* Return at least a category according to RFC 2616 Section 10. */
  4094. if (response_code >= 100 && response_code < 200) {
  4095. /* Unknown informational status code */
  4096. return "Information";
  4097. }
  4098. if (response_code >= 200 && response_code < 300) {
  4099. /* Unknown success code */
  4100. return "Success";
  4101. }
  4102. if (response_code >= 300 && response_code < 400) {
  4103. /* Unknown redirection code */
  4104. return "Redirection";
  4105. }
  4106. if (response_code >= 400 && response_code < 500) {
  4107. /* Unknown request error code */
  4108. return "Client Error";
  4109. }
  4110. if (response_code >= 500 && response_code < 600) {
  4111. /* Unknown server error code */
  4112. return "Server Error";
  4113. }
  4114. /* Response code not even within reasonable range */
  4115. return "";
  4116. }
  4117. }
  4118. static int
  4119. mg_send_http_error_impl(struct mg_connection *conn,
  4120. int status,
  4121. const char *fmt,
  4122. va_list args)
  4123. {
  4124. char errmsg_buf[MG_BUF_LEN];
  4125. va_list ap;
  4126. int has_body;
  4127. #if !defined(NO_FILESYSTEMS)
  4128. char path_buf[PATH_MAX];
  4129. int len, i, page_handler_found, scope, truncated;
  4130. const char *error_handler = NULL;
  4131. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4132. const char *error_page_file_ext, *tstr;
  4133. #endif /* NO_FILESYSTEMS */
  4134. int handled_by_callback = 0;
  4135. if ((conn == NULL) || (fmt == NULL)) {
  4136. return -2;
  4137. }
  4138. /* Set status (for log) */
  4139. conn->status_code = status;
  4140. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4141. has_body = ((status > 199) && (status != 204) && (status != 304));
  4142. /* Prepare message in buf, if required */
  4143. if (has_body
  4144. || (!conn->in_error_handler
  4145. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4146. /* Store error message in errmsg_buf */
  4147. va_copy(ap, args);
  4148. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4149. va_end(ap);
  4150. /* In a debug build, print all html errors */
  4151. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4152. }
  4153. /* If there is a http_error callback, call it.
  4154. * But don't do it recursively, if callback calls mg_send_http_error again.
  4155. */
  4156. if (!conn->in_error_handler
  4157. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4158. /* Mark in_error_handler to avoid recursion and call user callback. */
  4159. conn->in_error_handler = 1;
  4160. handled_by_callback =
  4161. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4162. == 0);
  4163. conn->in_error_handler = 0;
  4164. }
  4165. if (!handled_by_callback) {
  4166. /* Check for recursion */
  4167. if (conn->in_error_handler) {
  4168. DEBUG_TRACE(
  4169. "Recursion when handling error %u - fall back to default",
  4170. status);
  4171. #if !defined(NO_FILESYSTEMS)
  4172. } else {
  4173. /* Send user defined error pages, if defined */
  4174. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4175. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4176. page_handler_found = 0;
  4177. if (error_handler != NULL) {
  4178. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4179. switch (scope) {
  4180. case 1: /* Handler for specific error, e.g. 404 error */
  4181. mg_snprintf(conn,
  4182. &truncated,
  4183. path_buf,
  4184. sizeof(path_buf) - 32,
  4185. "%serror%03u.",
  4186. error_handler,
  4187. status);
  4188. break;
  4189. case 2: /* Handler for error group, e.g., 5xx error
  4190. * handler
  4191. * for all server errors (500-599) */
  4192. mg_snprintf(conn,
  4193. &truncated,
  4194. path_buf,
  4195. sizeof(path_buf) - 32,
  4196. "%serror%01uxx.",
  4197. error_handler,
  4198. status / 100);
  4199. break;
  4200. default: /* Handler for all errors */
  4201. mg_snprintf(conn,
  4202. &truncated,
  4203. path_buf,
  4204. sizeof(path_buf) - 32,
  4205. "%serror.",
  4206. error_handler);
  4207. break;
  4208. }
  4209. /* String truncation in buf may only occur if
  4210. * error_handler is too long. This string is
  4211. * from the config, not from a client. */
  4212. (void)truncated;
  4213. /* The following code is redundant, but it should avoid
  4214. * false positives in static source code analyzers and
  4215. * vulnerability scanners.
  4216. */
  4217. path_buf[sizeof(path_buf) - 32] = 0;
  4218. len = (int)strlen(path_buf);
  4219. if (len > (int)sizeof(path_buf) - 32) {
  4220. len = (int)sizeof(path_buf) - 32;
  4221. }
  4222. /* Start with the file extenstion from the configuration. */
  4223. tstr = strchr(error_page_file_ext, '.');
  4224. while (tstr) {
  4225. for (i = 1;
  4226. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4227. i++) {
  4228. /* buffer overrun is not possible here, since
  4229. * (i < 32) && (len < sizeof(path_buf) - 32)
  4230. * ==> (i + len) < sizeof(path_buf) */
  4231. path_buf[len + i - 1] = tstr[i];
  4232. }
  4233. /* buffer overrun is not possible here, since
  4234. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4235. * ==> (i + len) <= sizeof(path_buf) */
  4236. path_buf[len + i - 1] = 0;
  4237. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4238. DEBUG_TRACE("Check error page %s - found",
  4239. path_buf);
  4240. page_handler_found = 1;
  4241. break;
  4242. }
  4243. DEBUG_TRACE("Check error page %s - not found",
  4244. path_buf);
  4245. /* Continue with the next file extenstion from the
  4246. * configuration (if there is a next one). */
  4247. tstr = strchr(tstr + i, '.');
  4248. }
  4249. }
  4250. }
  4251. if (page_handler_found) {
  4252. conn->in_error_handler = 1;
  4253. handle_file_based_request(conn, path_buf, &error_page_file);
  4254. conn->in_error_handler = 0;
  4255. return 0;
  4256. }
  4257. #endif /* NO_FILESYSTEMS */
  4258. }
  4259. /* No custom error page. Send default error page. */
  4260. conn->must_close = 1;
  4261. mg_response_start(conn, status);
  4262. send_no_cache_header(conn);
  4263. send_additional_header(conn);
  4264. if (has_body) {
  4265. mg_response_add_header(conn,
  4266. "Content-Type",
  4267. "text/plain; charset=utf-8",
  4268. -1);
  4269. }
  4270. mg_response_send_headers(conn);
  4271. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4272. if (has_body) {
  4273. /* For other errors, send a generic error message. */
  4274. const char *status_text = mg_get_response_code_text(conn, status);
  4275. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4276. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4277. } else {
  4278. /* No body allowed. Close the connection. */
  4279. DEBUG_TRACE("Error %i", status);
  4280. }
  4281. }
  4282. return 0;
  4283. }
  4284. int
  4285. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4286. {
  4287. va_list ap;
  4288. int ret;
  4289. va_start(ap, fmt);
  4290. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4291. va_end(ap);
  4292. return ret;
  4293. }
  4294. int
  4295. mg_send_http_ok(struct mg_connection *conn,
  4296. const char *mime_type,
  4297. long long content_length)
  4298. {
  4299. if ((mime_type == NULL) || (*mime_type == 0)) {
  4300. /* No content type defined: default to text/html */
  4301. mime_type = "text/html";
  4302. }
  4303. mg_response_start(conn, 200);
  4304. send_no_cache_header(conn);
  4305. send_additional_header(conn);
  4306. mg_response_add_header(conn, "Content-Type", mime_type, -1);
  4307. if (content_length < 0) {
  4308. /* Size not known. Use chunked encoding (HTTP/1.x) */
  4309. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  4310. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  4311. mg_response_add_header(conn, "Transfer-Encoding", "chunked", -1);
  4312. }
  4313. } else {
  4314. char len[32];
  4315. int trunc = 0;
  4316. mg_snprintf(conn,
  4317. &trunc,
  4318. len,
  4319. sizeof(len),
  4320. "%" UINT64_FMT,
  4321. (uint64_t)content_length);
  4322. if (!trunc) {
  4323. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  4324. * !trunc is always true */
  4325. mg_response_add_header(conn, "Content-Length", len, -1);
  4326. }
  4327. }
  4328. mg_response_send_headers(conn);
  4329. return 0;
  4330. }
  4331. int
  4332. mg_send_http_redirect(struct mg_connection *conn,
  4333. const char *target_url,
  4334. int redirect_code)
  4335. {
  4336. /* Send a 30x redirect response.
  4337. *
  4338. * Redirect types (status codes):
  4339. *
  4340. * Status | Perm/Temp | Method | Version
  4341. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4342. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4343. * 303 | temporary | always use GET | HTTP/1.1
  4344. * 307 | temporary | always keep method | HTTP/1.1
  4345. * 308 | permanent | always keep method | HTTP/1.1
  4346. */
  4347. const char *redirect_text;
  4348. int ret;
  4349. size_t content_len = 0;
  4350. #if defined(MG_SEND_REDIRECT_BODY)
  4351. char reply[MG_BUF_LEN];
  4352. #endif
  4353. /* In case redirect_code=0, use 307. */
  4354. if (redirect_code == 0) {
  4355. redirect_code = 307;
  4356. }
  4357. /* In case redirect_code is none of the above, return error. */
  4358. if ((redirect_code != 301) && (redirect_code != 302)
  4359. && (redirect_code != 303) && (redirect_code != 307)
  4360. && (redirect_code != 308)) {
  4361. /* Parameter error */
  4362. return -2;
  4363. }
  4364. /* Get proper text for response code */
  4365. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4366. /* If target_url is not defined, redirect to "/". */
  4367. if ((target_url == NULL) || (*target_url == 0)) {
  4368. target_url = "/";
  4369. }
  4370. #if defined(MG_SEND_REDIRECT_BODY)
  4371. /* TODO: condition name? */
  4372. /* Prepare a response body with a hyperlink.
  4373. *
  4374. * According to RFC2616 (and RFC1945 before):
  4375. * Unless the request method was HEAD, the entity of the
  4376. * response SHOULD contain a short hypertext note with a hyperlink to
  4377. * the new URI(s).
  4378. *
  4379. * However, this response body is not useful in M2M communication.
  4380. * Probably the original reason in the RFC was, clients not supporting
  4381. * a 30x HTTP redirect could still show the HTML page and let the user
  4382. * press the link. Since current browsers support 30x HTTP, the additional
  4383. * HTML body does not seem to make sense anymore.
  4384. *
  4385. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4386. * but it only notes:
  4387. * The server's response payload usually contains a short
  4388. * hypertext note with a hyperlink to the new URI(s).
  4389. *
  4390. * Deactivated by default. If you need the 30x body, set the define.
  4391. */
  4392. mg_snprintf(
  4393. conn,
  4394. NULL /* ignore truncation */,
  4395. reply,
  4396. sizeof(reply),
  4397. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4398. redirect_text,
  4399. target_url,
  4400. target_url);
  4401. content_len = strlen(reply);
  4402. #endif
  4403. /* Do not send any additional header. For all other options,
  4404. * including caching, there are suitable defaults. */
  4405. ret = mg_printf(conn,
  4406. "HTTP/1.1 %i %s\r\n"
  4407. "Location: %s\r\n"
  4408. "Content-Length: %u\r\n"
  4409. "Connection: %s\r\n\r\n",
  4410. redirect_code,
  4411. redirect_text,
  4412. target_url,
  4413. (unsigned int)content_len,
  4414. suggest_connection_header(conn));
  4415. #if defined(MG_SEND_REDIRECT_BODY)
  4416. /* Send response body */
  4417. if (ret > 0) {
  4418. /* ... unless it is a HEAD request */
  4419. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4420. ret = mg_write(conn, reply, content_len);
  4421. }
  4422. }
  4423. #endif
  4424. return (ret > 0) ? ret : -1;
  4425. }
  4426. #if defined(_WIN32)
  4427. /* Create substitutes for POSIX functions in Win32. */
  4428. #if defined(GCC_DIAGNOSTIC)
  4429. /* Show no warning in case system functions are not used. */
  4430. #pragma GCC diagnostic push
  4431. #pragma GCC diagnostic ignored "-Wunused-function"
  4432. #endif
  4433. static int
  4434. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4435. {
  4436. (void)unused;
  4437. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4438. InitializeCriticalSection(&mutex->sec);
  4439. return 0;
  4440. }
  4441. static int
  4442. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4443. {
  4444. DeleteCriticalSection(&mutex->sec);
  4445. return 0;
  4446. }
  4447. static int
  4448. pthread_mutex_lock(pthread_mutex_t *mutex)
  4449. {
  4450. EnterCriticalSection(&mutex->sec);
  4451. return 0;
  4452. }
  4453. static int
  4454. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4455. {
  4456. LeaveCriticalSection(&mutex->sec);
  4457. return 0;
  4458. }
  4459. FUNCTION_MAY_BE_UNUSED
  4460. static int
  4461. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4462. {
  4463. (void)unused;
  4464. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4465. cv->waiting_thread = NULL;
  4466. return 0;
  4467. }
  4468. FUNCTION_MAY_BE_UNUSED
  4469. static int
  4470. pthread_cond_timedwait(pthread_cond_t *cv,
  4471. pthread_mutex_t *mutex,
  4472. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4473. {
  4474. struct mg_workerTLS **ptls,
  4475. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4476. int ok;
  4477. int64_t nsnow, nswaitabs, nswaitrel;
  4478. DWORD mswaitrel;
  4479. pthread_mutex_lock(&cv->threadIdSec);
  4480. /* Add this thread to cv's waiting list */
  4481. ptls = &cv->waiting_thread;
  4482. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4483. ;
  4484. tls->next_waiting_thread = NULL;
  4485. *ptls = tls;
  4486. pthread_mutex_unlock(&cv->threadIdSec);
  4487. if (abstime) {
  4488. nsnow = mg_get_current_time_ns();
  4489. nswaitabs =
  4490. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4491. nswaitrel = nswaitabs - nsnow;
  4492. if (nswaitrel < 0) {
  4493. nswaitrel = 0;
  4494. }
  4495. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4496. } else {
  4497. mswaitrel = (DWORD)INFINITE;
  4498. }
  4499. pthread_mutex_unlock(mutex);
  4500. ok = (WAIT_OBJECT_0
  4501. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4502. if (!ok) {
  4503. ok = 1;
  4504. pthread_mutex_lock(&cv->threadIdSec);
  4505. ptls = &cv->waiting_thread;
  4506. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4507. if (*ptls == tls) {
  4508. *ptls = tls->next_waiting_thread;
  4509. ok = 0;
  4510. break;
  4511. }
  4512. }
  4513. pthread_mutex_unlock(&cv->threadIdSec);
  4514. if (ok) {
  4515. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4516. (DWORD)INFINITE);
  4517. }
  4518. }
  4519. /* This thread has been removed from cv's waiting list */
  4520. pthread_mutex_lock(mutex);
  4521. return ok ? 0 : -1;
  4522. }
  4523. FUNCTION_MAY_BE_UNUSED
  4524. static int
  4525. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4526. {
  4527. return pthread_cond_timedwait(cv, mutex, NULL);
  4528. }
  4529. FUNCTION_MAY_BE_UNUSED
  4530. static int
  4531. pthread_cond_signal(pthread_cond_t *cv)
  4532. {
  4533. HANDLE wkup = NULL;
  4534. BOOL ok = FALSE;
  4535. pthread_mutex_lock(&cv->threadIdSec);
  4536. if (cv->waiting_thread) {
  4537. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4538. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4539. ok = SetEvent(wkup);
  4540. DEBUG_ASSERT(ok);
  4541. }
  4542. pthread_mutex_unlock(&cv->threadIdSec);
  4543. return ok ? 0 : 1;
  4544. }
  4545. FUNCTION_MAY_BE_UNUSED
  4546. static int
  4547. pthread_cond_broadcast(pthread_cond_t *cv)
  4548. {
  4549. pthread_mutex_lock(&cv->threadIdSec);
  4550. while (cv->waiting_thread) {
  4551. pthread_cond_signal(cv);
  4552. }
  4553. pthread_mutex_unlock(&cv->threadIdSec);
  4554. return 0;
  4555. }
  4556. FUNCTION_MAY_BE_UNUSED
  4557. static int
  4558. pthread_cond_destroy(pthread_cond_t *cv)
  4559. {
  4560. pthread_mutex_lock(&cv->threadIdSec);
  4561. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4562. pthread_mutex_unlock(&cv->threadIdSec);
  4563. pthread_mutex_destroy(&cv->threadIdSec);
  4564. return 0;
  4565. }
  4566. #if defined(ALTERNATIVE_QUEUE)
  4567. FUNCTION_MAY_BE_UNUSED
  4568. static void *
  4569. event_create(void)
  4570. {
  4571. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4572. }
  4573. FUNCTION_MAY_BE_UNUSED
  4574. static int
  4575. event_wait(void *eventhdl)
  4576. {
  4577. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4578. return (res == WAIT_OBJECT_0);
  4579. }
  4580. FUNCTION_MAY_BE_UNUSED
  4581. static int
  4582. event_signal(void *eventhdl)
  4583. {
  4584. return (int)SetEvent((HANDLE)eventhdl);
  4585. }
  4586. FUNCTION_MAY_BE_UNUSED
  4587. static void
  4588. event_destroy(void *eventhdl)
  4589. {
  4590. CloseHandle((HANDLE)eventhdl);
  4591. }
  4592. #endif
  4593. #if defined(GCC_DIAGNOSTIC)
  4594. /* Enable unused function warning again */
  4595. #pragma GCC diagnostic pop
  4596. #endif
  4597. /* For Windows, change all slashes to backslashes in path names. */
  4598. static void
  4599. change_slashes_to_backslashes(char *path)
  4600. {
  4601. int i;
  4602. for (i = 0; path[i] != '\0'; i++) {
  4603. if (path[i] == '/') {
  4604. path[i] = '\\';
  4605. }
  4606. /* remove double backslash (check i > 0 to preserve UNC paths,
  4607. * like \\server\file.txt) */
  4608. if ((i > 0) && (path[i] == '\\')) {
  4609. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4610. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4611. }
  4612. }
  4613. }
  4614. }
  4615. static int
  4616. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4617. {
  4618. int diff;
  4619. do {
  4620. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4621. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4622. s1++;
  4623. s2++;
  4624. } while ((diff == 0) && (s1[-1] != L'\0'));
  4625. return diff;
  4626. }
  4627. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4628. * wbuf and wbuf_len is a target buffer and its length. */
  4629. static void
  4630. path_to_unicode(const struct mg_connection *conn,
  4631. const char *path,
  4632. wchar_t *wbuf,
  4633. size_t wbuf_len)
  4634. {
  4635. char buf[PATH_MAX], buf2[PATH_MAX];
  4636. wchar_t wbuf2[W_PATH_MAX + 1];
  4637. DWORD long_len, err;
  4638. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4639. mg_strlcpy(buf, path, sizeof(buf));
  4640. change_slashes_to_backslashes(buf);
  4641. /* Convert to Unicode and back. If doubly-converted string does not
  4642. * match the original, something is fishy, reject. */
  4643. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4644. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4645. WideCharToMultiByte(
  4646. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4647. if (strcmp(buf, buf2) != 0) {
  4648. wbuf[0] = L'\0';
  4649. }
  4650. /* Windows file systems are not case sensitive, but you can still use
  4651. * uppercase and lowercase letters (on all modern file systems).
  4652. * The server can check if the URI uses the same upper/lowercase
  4653. * letters an the file system, effectively making Windows servers
  4654. * case sensitive (like Linux servers are). It is still not possible
  4655. * to use two files with the same name in different cases on Windows
  4656. * (like /a and /A) - this would be possible in Linux.
  4657. * As a default, Windows is not case sensitive, but the case sensitive
  4658. * file name check can be activated by an additional configuration. */
  4659. if (conn) {
  4660. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4661. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4662. "yes")) {
  4663. /* Use case sensitive compare function */
  4664. fcompare = wcscmp;
  4665. }
  4666. }
  4667. (void)conn; /* conn is currently unused */
  4668. #if !defined(_WIN32_WCE)
  4669. /* Only accept a full file path, not a Windows short (8.3) path. */
  4670. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4671. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4672. if (long_len == 0) {
  4673. err = GetLastError();
  4674. if (err == ERROR_FILE_NOT_FOUND) {
  4675. /* File does not exist. This is not always a problem here. */
  4676. return;
  4677. }
  4678. }
  4679. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4680. /* Short name is used. */
  4681. wbuf[0] = L'\0';
  4682. }
  4683. #else
  4684. (void)long_len;
  4685. (void)wbuf2;
  4686. (void)err;
  4687. if (strchr(path, '~')) {
  4688. wbuf[0] = L'\0';
  4689. }
  4690. #endif
  4691. }
  4692. #if !defined(NO_FILESYSTEMS)
  4693. /* Get file information, return 1 if file exists, 0 if not */
  4694. static int
  4695. mg_stat(const struct mg_connection *conn,
  4696. const char *path,
  4697. struct mg_file_stat *filep)
  4698. {
  4699. wchar_t wbuf[W_PATH_MAX];
  4700. WIN32_FILE_ATTRIBUTE_DATA info;
  4701. time_t creation_time;
  4702. size_t len;
  4703. if (!filep) {
  4704. return 0;
  4705. }
  4706. memset(filep, 0, sizeof(*filep));
  4707. if (mg_path_suspicious(conn, path)) {
  4708. return 0;
  4709. }
  4710. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4711. /* Windows happily opens files with some garbage at the end of file name.
  4712. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4713. * "a.cgi", despite one would expect an error back. */
  4714. len = strlen(path);
  4715. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4716. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4717. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4718. filep->last_modified =
  4719. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4720. info.ftLastWriteTime.dwHighDateTime);
  4721. /* On Windows, the file creation time can be higher than the
  4722. * modification time, e.g. when a file is copied.
  4723. * Since the Last-Modified timestamp is used for caching
  4724. * it should be based on the most recent timestamp. */
  4725. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4726. info.ftCreationTime.dwHighDateTime);
  4727. if (creation_time > filep->last_modified) {
  4728. filep->last_modified = creation_time;
  4729. }
  4730. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4731. return 1;
  4732. }
  4733. return 0;
  4734. }
  4735. #endif
  4736. static int
  4737. mg_remove(const struct mg_connection *conn, const char *path)
  4738. {
  4739. wchar_t wbuf[W_PATH_MAX];
  4740. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4741. return DeleteFileW(wbuf) ? 0 : -1;
  4742. }
  4743. static int
  4744. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4745. {
  4746. wchar_t wbuf[W_PATH_MAX];
  4747. (void)mode;
  4748. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4749. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4750. }
  4751. /* Create substitutes for POSIX functions in Win32. */
  4752. #if defined(GCC_DIAGNOSTIC)
  4753. /* Show no warning in case system functions are not used. */
  4754. #pragma GCC diagnostic push
  4755. #pragma GCC diagnostic ignored "-Wunused-function"
  4756. #endif
  4757. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4758. FUNCTION_MAY_BE_UNUSED
  4759. static DIR *
  4760. mg_opendir(const struct mg_connection *conn, const char *name)
  4761. {
  4762. DIR *dir = NULL;
  4763. wchar_t wpath[W_PATH_MAX];
  4764. DWORD attrs;
  4765. if (name == NULL) {
  4766. SetLastError(ERROR_BAD_ARGUMENTS);
  4767. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4768. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4769. } else {
  4770. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4771. attrs = GetFileAttributesW(wpath);
  4772. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4773. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4774. (void)wcscat(wpath, L"\\*");
  4775. dir->handle = FindFirstFileW(wpath, &dir->info);
  4776. dir->result.d_name[0] = '\0';
  4777. } else {
  4778. mg_free(dir);
  4779. dir = NULL;
  4780. }
  4781. }
  4782. return dir;
  4783. }
  4784. FUNCTION_MAY_BE_UNUSED
  4785. static int
  4786. mg_closedir(DIR *dir)
  4787. {
  4788. int result = 0;
  4789. if (dir != NULL) {
  4790. if (dir->handle != INVALID_HANDLE_VALUE)
  4791. result = FindClose(dir->handle) ? 0 : -1;
  4792. mg_free(dir);
  4793. } else {
  4794. result = -1;
  4795. SetLastError(ERROR_BAD_ARGUMENTS);
  4796. }
  4797. return result;
  4798. }
  4799. FUNCTION_MAY_BE_UNUSED
  4800. static struct dirent *
  4801. mg_readdir(DIR *dir)
  4802. {
  4803. struct dirent *result = 0;
  4804. if (dir) {
  4805. if (dir->handle != INVALID_HANDLE_VALUE) {
  4806. result = &dir->result;
  4807. (void)WideCharToMultiByte(CP_UTF8,
  4808. 0,
  4809. dir->info.cFileName,
  4810. -1,
  4811. result->d_name,
  4812. sizeof(result->d_name),
  4813. NULL,
  4814. NULL);
  4815. if (!FindNextFileW(dir->handle, &dir->info)) {
  4816. (void)FindClose(dir->handle);
  4817. dir->handle = INVALID_HANDLE_VALUE;
  4818. }
  4819. } else {
  4820. SetLastError(ERROR_FILE_NOT_FOUND);
  4821. }
  4822. } else {
  4823. SetLastError(ERROR_BAD_ARGUMENTS);
  4824. }
  4825. return result;
  4826. }
  4827. #if !defined(HAVE_POLL)
  4828. #undef POLLIN
  4829. #undef POLLPRI
  4830. #undef POLLOUT
  4831. #define POLLIN (1) /* Data ready - read will not block. */
  4832. #define POLLPRI (2) /* Priority data ready. */
  4833. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4834. FUNCTION_MAY_BE_UNUSED
  4835. static int
  4836. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4837. {
  4838. struct timeval tv;
  4839. fd_set rset;
  4840. fd_set wset;
  4841. unsigned int i;
  4842. int result;
  4843. SOCKET maxfd = 0;
  4844. memset(&tv, 0, sizeof(tv));
  4845. tv.tv_sec = milliseconds / 1000;
  4846. tv.tv_usec = (milliseconds % 1000) * 1000;
  4847. FD_ZERO(&rset);
  4848. FD_ZERO(&wset);
  4849. for (i = 0; i < n; i++) {
  4850. if (pfd[i].events & POLLIN) {
  4851. FD_SET(pfd[i].fd, &rset);
  4852. }
  4853. if (pfd[i].events & POLLOUT) {
  4854. FD_SET(pfd[i].fd, &wset);
  4855. }
  4856. pfd[i].revents = 0;
  4857. if (pfd[i].fd > maxfd) {
  4858. maxfd = pfd[i].fd;
  4859. }
  4860. }
  4861. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4862. for (i = 0; i < n; i++) {
  4863. if (FD_ISSET(pfd[i].fd, &rset)) {
  4864. pfd[i].revents |= POLLIN;
  4865. }
  4866. if (FD_ISSET(pfd[i].fd, &wset)) {
  4867. pfd[i].revents |= POLLOUT;
  4868. }
  4869. }
  4870. }
  4871. /* We should subtract the time used in select from remaining
  4872. * "milliseconds", in particular if called from mg_poll with a
  4873. * timeout quantum.
  4874. * Unfortunately, the remaining time is not stored in "tv" in all
  4875. * implementations, so the result in "tv" must be considered undefined.
  4876. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4877. return result;
  4878. }
  4879. #endif /* HAVE_POLL */
  4880. #if defined(GCC_DIAGNOSTIC)
  4881. /* Enable unused function warning again */
  4882. #pragma GCC diagnostic pop
  4883. #endif
  4884. static void
  4885. set_close_on_exec(SOCKET sock,
  4886. const struct mg_connection *conn /* may be null */,
  4887. struct mg_context *ctx /* may be null */)
  4888. {
  4889. (void)conn; /* Unused. */
  4890. (void)ctx;
  4891. #if defined(_WIN32_WCE)
  4892. (void)sock;
  4893. #else
  4894. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4895. #endif
  4896. }
  4897. int
  4898. mg_start_thread(mg_thread_func_t f, void *p)
  4899. {
  4900. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4901. /* Compile-time option to control stack size, e.g.
  4902. * -DUSE_STACK_SIZE=16384
  4903. */
  4904. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4905. == ((uintptr_t)(-1L)))
  4906. ? -1
  4907. : 0);
  4908. #else
  4909. return (
  4910. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4911. ? -1
  4912. : 0);
  4913. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4914. }
  4915. /* Start a thread storing the thread context. */
  4916. static int
  4917. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4918. void *p,
  4919. pthread_t *threadidptr)
  4920. {
  4921. uintptr_t uip;
  4922. HANDLE threadhandle;
  4923. int result = -1;
  4924. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4925. threadhandle = (HANDLE)uip;
  4926. if ((uip != 0) && (threadidptr != NULL)) {
  4927. *threadidptr = threadhandle;
  4928. result = 0;
  4929. }
  4930. return result;
  4931. }
  4932. /* Wait for a thread to finish. */
  4933. static int
  4934. mg_join_thread(pthread_t threadid)
  4935. {
  4936. int result;
  4937. DWORD dwevent;
  4938. result = -1;
  4939. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4940. if (dwevent == WAIT_FAILED) {
  4941. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4942. } else {
  4943. if (dwevent == WAIT_OBJECT_0) {
  4944. CloseHandle(threadid);
  4945. result = 0;
  4946. }
  4947. }
  4948. return result;
  4949. }
  4950. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4951. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4952. /* Create substitutes for POSIX functions in Win32. */
  4953. #if defined(GCC_DIAGNOSTIC)
  4954. /* Show no warning in case system functions are not used. */
  4955. #pragma GCC diagnostic push
  4956. #pragma GCC diagnostic ignored "-Wunused-function"
  4957. #endif
  4958. FUNCTION_MAY_BE_UNUSED
  4959. static HANDLE
  4960. dlopen(const char *dll_name, int flags)
  4961. {
  4962. wchar_t wbuf[W_PATH_MAX];
  4963. (void)flags;
  4964. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4965. return LoadLibraryW(wbuf);
  4966. }
  4967. FUNCTION_MAY_BE_UNUSED
  4968. static int
  4969. dlclose(void *handle)
  4970. {
  4971. int result;
  4972. if (FreeLibrary((HMODULE)handle) != 0) {
  4973. result = 0;
  4974. } else {
  4975. result = -1;
  4976. }
  4977. return result;
  4978. }
  4979. #if defined(GCC_DIAGNOSTIC)
  4980. /* Enable unused function warning again */
  4981. #pragma GCC diagnostic pop
  4982. #endif
  4983. #endif
  4984. #if !defined(NO_CGI)
  4985. #define SIGKILL (0)
  4986. static int
  4987. kill(pid_t pid, int sig_num)
  4988. {
  4989. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4990. (void)CloseHandle((HANDLE)pid);
  4991. return 0;
  4992. }
  4993. #if !defined(WNOHANG)
  4994. #define WNOHANG (1)
  4995. #endif
  4996. static pid_t
  4997. waitpid(pid_t pid, int *status, int flags)
  4998. {
  4999. DWORD timeout = INFINITE;
  5000. DWORD waitres;
  5001. (void)status; /* Currently not used by any client here */
  5002. if ((flags | WNOHANG) == WNOHANG) {
  5003. timeout = 0;
  5004. }
  5005. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  5006. if (waitres == WAIT_OBJECT_0) {
  5007. return pid;
  5008. }
  5009. if (waitres == WAIT_TIMEOUT) {
  5010. return 0;
  5011. }
  5012. return (pid_t)-1;
  5013. }
  5014. static void
  5015. trim_trailing_whitespaces(char *s)
  5016. {
  5017. char *e = s + strlen(s);
  5018. while ((e > s) && isspace((unsigned char)e[-1])) {
  5019. *(--e) = '\0';
  5020. }
  5021. }
  5022. static pid_t
  5023. spawn_process(struct mg_connection *conn,
  5024. const char *prog,
  5025. char *envblk,
  5026. char *envp[],
  5027. int fdin[2],
  5028. int fdout[2],
  5029. int fderr[2],
  5030. const char *dir)
  5031. {
  5032. HANDLE me;
  5033. char *interp;
  5034. char *interp_arg = 0;
  5035. char full_dir[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX];
  5036. int truncated;
  5037. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5038. STARTUPINFOA si;
  5039. PROCESS_INFORMATION pi = {0};
  5040. (void)envp;
  5041. memset(&si, 0, sizeof(si));
  5042. si.cb = sizeof(si);
  5043. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5044. si.wShowWindow = SW_HIDE;
  5045. me = GetCurrentProcess();
  5046. DuplicateHandle(me,
  5047. (HANDLE)_get_osfhandle(fdin[0]),
  5048. me,
  5049. &si.hStdInput,
  5050. 0,
  5051. TRUE,
  5052. DUPLICATE_SAME_ACCESS);
  5053. DuplicateHandle(me,
  5054. (HANDLE)_get_osfhandle(fdout[1]),
  5055. me,
  5056. &si.hStdOutput,
  5057. 0,
  5058. TRUE,
  5059. DUPLICATE_SAME_ACCESS);
  5060. DuplicateHandle(me,
  5061. (HANDLE)_get_osfhandle(fderr[1]),
  5062. me,
  5063. &si.hStdError,
  5064. 0,
  5065. TRUE,
  5066. DUPLICATE_SAME_ACCESS);
  5067. /* Mark handles that should not be inherited. See
  5068. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5069. */
  5070. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5071. HANDLE_FLAG_INHERIT,
  5072. 0);
  5073. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5074. HANDLE_FLAG_INHERIT,
  5075. 0);
  5076. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5077. HANDLE_FLAG_INHERIT,
  5078. 0);
  5079. /* First check, if there is a CGI interpreter configured for all CGI
  5080. * scripts. */
  5081. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5082. if (interp != NULL) {
  5083. /* If there is a configured interpreter, check for additional arguments
  5084. */
  5085. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5086. } else {
  5087. /* Otherwise, the interpreter must be stated in the first line of the
  5088. * CGI script file, after a #! (shebang) mark. */
  5089. buf[0] = buf[1] = '\0';
  5090. /* Get the full script path */
  5091. mg_snprintf(
  5092. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5093. if (truncated) {
  5094. pi.hProcess = (pid_t)-1;
  5095. goto spawn_cleanup;
  5096. }
  5097. /* Open the script file, to read the first line */
  5098. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5099. /* Read the first line of the script into the buffer */
  5100. mg_fgets(buf, sizeof(buf), &file);
  5101. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5102. buf[sizeof(buf) - 1] = '\0';
  5103. }
  5104. if ((buf[0] == '#') && (buf[1] == '!')) {
  5105. trim_trailing_whitespaces(buf + 2);
  5106. } else {
  5107. buf[2] = '\0';
  5108. }
  5109. interp = buf + 2;
  5110. }
  5111. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5112. if (interp[0] != '\0') {
  5113. /* This is an interpreted script file. We must call the interpreter. */
  5114. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5115. mg_snprintf(conn,
  5116. &truncated,
  5117. cmdline,
  5118. sizeof(cmdline),
  5119. "\"%s\" %s \"%s\\%s\"",
  5120. interp,
  5121. interp_arg,
  5122. full_dir,
  5123. prog);
  5124. } else {
  5125. mg_snprintf(conn,
  5126. &truncated,
  5127. cmdline,
  5128. sizeof(cmdline),
  5129. "\"%s\" \"%s\\%s\"",
  5130. interp,
  5131. full_dir,
  5132. prog);
  5133. }
  5134. } else {
  5135. /* This is (probably) a compiled program. We call it directly. */
  5136. mg_snprintf(conn,
  5137. &truncated,
  5138. cmdline,
  5139. sizeof(cmdline),
  5140. "\"%s\\%s\"",
  5141. full_dir,
  5142. prog);
  5143. }
  5144. if (truncated) {
  5145. pi.hProcess = (pid_t)-1;
  5146. goto spawn_cleanup;
  5147. }
  5148. DEBUG_TRACE("Running [%s]", cmdline);
  5149. if (CreateProcessA(NULL,
  5150. cmdline,
  5151. NULL,
  5152. NULL,
  5153. TRUE,
  5154. CREATE_NEW_PROCESS_GROUP,
  5155. envblk,
  5156. NULL,
  5157. &si,
  5158. &pi)
  5159. == 0) {
  5160. mg_cry_internal(
  5161. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5162. pi.hProcess = (pid_t)-1;
  5163. /* goto spawn_cleanup; */
  5164. }
  5165. spawn_cleanup:
  5166. (void)CloseHandle(si.hStdOutput);
  5167. (void)CloseHandle(si.hStdError);
  5168. (void)CloseHandle(si.hStdInput);
  5169. if (pi.hThread != NULL) {
  5170. (void)CloseHandle(pi.hThread);
  5171. }
  5172. return (pid_t)pi.hProcess;
  5173. }
  5174. #endif /* !NO_CGI */
  5175. static int
  5176. set_blocking_mode(SOCKET sock)
  5177. {
  5178. unsigned long non_blocking = 0;
  5179. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5180. }
  5181. static int
  5182. set_non_blocking_mode(SOCKET sock)
  5183. {
  5184. unsigned long non_blocking = 1;
  5185. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5186. }
  5187. #else
  5188. #if !defined(NO_FILESYSTEMS)
  5189. static int
  5190. mg_stat(const struct mg_connection *conn,
  5191. const char *path,
  5192. struct mg_file_stat *filep)
  5193. {
  5194. struct stat st;
  5195. if (!filep) {
  5196. return 0;
  5197. }
  5198. memset(filep, 0, sizeof(*filep));
  5199. if (mg_path_suspicious(conn, path)) {
  5200. return 0;
  5201. }
  5202. if (0 == stat(path, &st)) {
  5203. filep->size = (uint64_t)(st.st_size);
  5204. filep->last_modified = st.st_mtime;
  5205. filep->is_directory = S_ISDIR(st.st_mode);
  5206. return 1;
  5207. }
  5208. return 0;
  5209. }
  5210. #endif /* NO_FILESYSTEMS */
  5211. static void
  5212. set_close_on_exec(int fd,
  5213. const struct mg_connection *conn /* may be null */,
  5214. struct mg_context *ctx /* may be null */)
  5215. {
  5216. #if defined(__ZEPHYR__)
  5217. (void)fd;
  5218. (void)conn;
  5219. (void)ctx;
  5220. #else
  5221. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5222. if (conn || ctx) {
  5223. struct mg_connection fc;
  5224. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5225. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5226. __func__,
  5227. strerror(ERRNO));
  5228. }
  5229. }
  5230. #endif
  5231. }
  5232. int
  5233. mg_start_thread(mg_thread_func_t func, void *param)
  5234. {
  5235. pthread_t thread_id;
  5236. pthread_attr_t attr;
  5237. int result;
  5238. (void)pthread_attr_init(&attr);
  5239. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5240. #if defined(__ZEPHYR__)
  5241. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5242. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5243. /* Compile-time option to control stack size,
  5244. * e.g. -DUSE_STACK_SIZE=16384 */
  5245. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5246. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5247. result = pthread_create(&thread_id, &attr, func, param);
  5248. pthread_attr_destroy(&attr);
  5249. return result;
  5250. }
  5251. /* Start a thread storing the thread context. */
  5252. static int
  5253. mg_start_thread_with_id(mg_thread_func_t func,
  5254. void *param,
  5255. pthread_t *threadidptr)
  5256. {
  5257. pthread_t thread_id;
  5258. pthread_attr_t attr;
  5259. int result;
  5260. (void)pthread_attr_init(&attr);
  5261. #if defined(__ZEPHYR__)
  5262. pthread_attr_setstack(&attr,
  5263. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5264. ZEPHYR_STACK_SIZE);
  5265. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5266. /* Compile-time option to control stack size,
  5267. * e.g. -DUSE_STACK_SIZE=16384 */
  5268. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5269. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5270. result = pthread_create(&thread_id, &attr, func, param);
  5271. pthread_attr_destroy(&attr);
  5272. if ((result == 0) && (threadidptr != NULL)) {
  5273. *threadidptr = thread_id;
  5274. }
  5275. return result;
  5276. }
  5277. /* Wait for a thread to finish. */
  5278. static int
  5279. mg_join_thread(pthread_t threadid)
  5280. {
  5281. int result;
  5282. result = pthread_join(threadid, NULL);
  5283. return result;
  5284. }
  5285. #if !defined(NO_CGI)
  5286. static pid_t
  5287. spawn_process(struct mg_connection *conn,
  5288. const char *prog,
  5289. char *envblk,
  5290. char *envp[],
  5291. int fdin[2],
  5292. int fdout[2],
  5293. int fderr[2],
  5294. const char *dir)
  5295. {
  5296. pid_t pid;
  5297. const char *interp;
  5298. (void)envblk;
  5299. if ((pid = fork()) == -1) {
  5300. /* Parent */
  5301. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5302. } else if (pid != 0) {
  5303. /* Make sure children close parent-side descriptors.
  5304. * The caller will close the child-side immediately. */
  5305. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5306. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5307. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5308. } else {
  5309. /* Child */
  5310. if (chdir(dir) != 0) {
  5311. mg_cry_internal(
  5312. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5313. } else if (dup2(fdin[0], 0) == -1) {
  5314. mg_cry_internal(conn,
  5315. "%s: dup2(%d, 0): %s",
  5316. __func__,
  5317. fdin[0],
  5318. strerror(ERRNO));
  5319. } else if (dup2(fdout[1], 1) == -1) {
  5320. mg_cry_internal(conn,
  5321. "%s: dup2(%d, 1): %s",
  5322. __func__,
  5323. fdout[1],
  5324. strerror(ERRNO));
  5325. } else if (dup2(fderr[1], 2) == -1) {
  5326. mg_cry_internal(conn,
  5327. "%s: dup2(%d, 2): %s",
  5328. __func__,
  5329. fderr[1],
  5330. strerror(ERRNO));
  5331. } else {
  5332. struct sigaction sa;
  5333. /* Keep stderr and stdout in two different pipes.
  5334. * Stdout will be sent back to the client,
  5335. * stderr should go into a server error log. */
  5336. (void)close(fdin[0]);
  5337. (void)close(fdout[1]);
  5338. (void)close(fderr[1]);
  5339. /* Close write end fdin and read end fdout and fderr */
  5340. (void)close(fdin[1]);
  5341. (void)close(fdout[0]);
  5342. (void)close(fderr[0]);
  5343. /* After exec, all signal handlers are restored to their default
  5344. * values, with one exception of SIGCHLD. According to
  5345. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5346. * will leave unchanged after exec if it was set to be ignored.
  5347. * Restore it to default action. */
  5348. memset(&sa, 0, sizeof(sa));
  5349. sa.sa_handler = SIG_DFL;
  5350. sigaction(SIGCHLD, &sa, NULL);
  5351. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5352. if (interp == NULL) {
  5353. /* no interpreter configured, call the programm directly */
  5354. (void)execle(prog, prog, NULL, envp);
  5355. mg_cry_internal(conn,
  5356. "%s: execle(%s): %s",
  5357. __func__,
  5358. prog,
  5359. strerror(ERRNO));
  5360. } else {
  5361. /* call the configured interpreter */
  5362. const char *interp_args =
  5363. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5364. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5365. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5366. } else {
  5367. (void)execle(interp, interp, prog, NULL, envp);
  5368. }
  5369. mg_cry_internal(conn,
  5370. "%s: execle(%s %s): %s",
  5371. __func__,
  5372. interp,
  5373. prog,
  5374. strerror(ERRNO));
  5375. }
  5376. }
  5377. exit(EXIT_FAILURE);
  5378. }
  5379. return pid;
  5380. }
  5381. #endif /* !NO_CGI */
  5382. static int
  5383. set_non_blocking_mode(SOCKET sock)
  5384. {
  5385. int flags = fcntl(sock, F_GETFL, 0);
  5386. if (flags < 0) {
  5387. return -1;
  5388. }
  5389. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5390. return -1;
  5391. }
  5392. return 0;
  5393. }
  5394. static int
  5395. set_blocking_mode(SOCKET sock)
  5396. {
  5397. int flags = fcntl(sock, F_GETFL, 0);
  5398. if (flags < 0) {
  5399. return -1;
  5400. }
  5401. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5402. return -1;
  5403. }
  5404. return 0;
  5405. }
  5406. #endif /* _WIN32 / else */
  5407. /* End of initial operating system specific define block. */
  5408. /* Get a random number (independent of C rand function) */
  5409. static uint64_t
  5410. get_random(void)
  5411. {
  5412. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5413. static uint64_t lcg = 0; /* Linear congruential generator */
  5414. uint64_t now = mg_get_current_time_ns();
  5415. if (lfsr == 0) {
  5416. /* lfsr will be only 0 if has not been initialized,
  5417. * so this code is called only once. */
  5418. lfsr = mg_get_current_time_ns();
  5419. lcg = mg_get_current_time_ns();
  5420. } else {
  5421. /* Get the next step of both random number generators. */
  5422. lfsr = (lfsr >> 1)
  5423. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5424. << 63);
  5425. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5426. }
  5427. /* Combining two pseudo-random number generators and a high resolution
  5428. * part
  5429. * of the current server time will make it hard (impossible?) to guess
  5430. * the
  5431. * next number. */
  5432. return (lfsr ^ lcg ^ now);
  5433. }
  5434. static int
  5435. mg_poll(struct mg_pollfd *pfd,
  5436. unsigned int n,
  5437. int milliseconds,
  5438. stop_flag_t *stop_flag)
  5439. {
  5440. /* Call poll, but only for a maximum time of a few seconds.
  5441. * This will allow to stop the server after some seconds, instead
  5442. * of having to wait for a long socket timeout. */
  5443. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5444. do {
  5445. int result;
  5446. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5447. /* Shut down signal */
  5448. return -2;
  5449. }
  5450. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5451. ms_now = milliseconds;
  5452. }
  5453. result = poll(pfd, n, ms_now);
  5454. if (result != 0) {
  5455. /* Poll returned either success (1) or error (-1).
  5456. * Forward both to the caller. */
  5457. return result;
  5458. }
  5459. /* Poll returned timeout (0). */
  5460. if (milliseconds > 0) {
  5461. milliseconds -= ms_now;
  5462. }
  5463. } while (milliseconds > 0);
  5464. /* timeout: return 0 */
  5465. return 0;
  5466. }
  5467. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5468. * descriptor.
  5469. * Return value:
  5470. * >=0 .. number of bytes successfully written
  5471. * -1 .. timeout
  5472. * -2 .. error
  5473. */
  5474. static int
  5475. push_inner(struct mg_context *ctx,
  5476. FILE *fp,
  5477. SOCKET sock,
  5478. SSL *ssl,
  5479. const char *buf,
  5480. int len,
  5481. double timeout)
  5482. {
  5483. uint64_t start = 0, now = 0, timeout_ns = 0;
  5484. int n, err;
  5485. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5486. #if defined(_WIN32)
  5487. typedef int len_t;
  5488. #else
  5489. typedef size_t len_t;
  5490. #endif
  5491. if (timeout > 0) {
  5492. now = mg_get_current_time_ns();
  5493. start = now;
  5494. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5495. }
  5496. if (ctx == NULL) {
  5497. return -2;
  5498. }
  5499. #if defined(NO_SSL)
  5500. if (ssl) {
  5501. return -2;
  5502. }
  5503. #endif
  5504. /* Try to read until it succeeds, fails, times out, or the server
  5505. * shuts down. */
  5506. for (;;) {
  5507. #if !defined(NO_SSL)
  5508. if (ssl != NULL) {
  5509. ERR_clear_error();
  5510. n = SSL_write(ssl, buf, len);
  5511. if (n <= 0) {
  5512. err = SSL_get_error(ssl, n);
  5513. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5514. err = ERRNO;
  5515. } else if ((err == SSL_ERROR_WANT_READ)
  5516. || (err == SSL_ERROR_WANT_WRITE)) {
  5517. n = 0;
  5518. } else {
  5519. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5520. ERR_clear_error();
  5521. return -2;
  5522. }
  5523. ERR_clear_error();
  5524. } else {
  5525. err = 0;
  5526. }
  5527. } else
  5528. #endif
  5529. if (fp != NULL) {
  5530. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5531. if (ferror(fp)) {
  5532. n = -1;
  5533. err = ERRNO;
  5534. } else {
  5535. err = 0;
  5536. }
  5537. } else {
  5538. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5539. err = (n < 0) ? ERRNO : 0;
  5540. #if defined(_WIN32)
  5541. if (err == WSAEWOULDBLOCK) {
  5542. err = 0;
  5543. n = 0;
  5544. }
  5545. #else
  5546. if (ERROR_TRY_AGAIN(err)) {
  5547. err = 0;
  5548. n = 0;
  5549. }
  5550. #endif
  5551. if (n < 0) {
  5552. /* shutdown of the socket at client side */
  5553. return -2;
  5554. }
  5555. }
  5556. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5557. return -2;
  5558. }
  5559. if ((n > 0) || ((n == 0) && (len == 0))) {
  5560. /* some data has been read, or no data was requested */
  5561. return n;
  5562. }
  5563. if (n < 0) {
  5564. /* socket error - check errno */
  5565. DEBUG_TRACE("send() failed, error %d", err);
  5566. /* TODO (mid): error handling depending on the error code.
  5567. * These codes are different between Windows and Linux.
  5568. * Currently there is no problem with failing send calls,
  5569. * if there is a reproducible situation, it should be
  5570. * investigated in detail.
  5571. */
  5572. return -2;
  5573. }
  5574. /* Only in case n=0 (timeout), repeat calling the write function */
  5575. /* If send failed, wait before retry */
  5576. if (fp != NULL) {
  5577. /* For files, just wait a fixed time.
  5578. * Maybe it helps, maybe not. */
  5579. mg_sleep(5);
  5580. } else {
  5581. /* For sockets, wait for the socket using poll */
  5582. struct mg_pollfd pfd[1];
  5583. int pollres;
  5584. pfd[0].fd = sock;
  5585. pfd[0].events = POLLOUT;
  5586. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5587. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5588. return -2;
  5589. }
  5590. if (pollres > 0) {
  5591. continue;
  5592. }
  5593. }
  5594. if (timeout > 0) {
  5595. now = mg_get_current_time_ns();
  5596. if ((now - start) > timeout_ns) {
  5597. /* Timeout */
  5598. break;
  5599. }
  5600. }
  5601. }
  5602. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5603. used */
  5604. return -1;
  5605. }
  5606. static int
  5607. push_all(struct mg_context *ctx,
  5608. FILE *fp,
  5609. SOCKET sock,
  5610. SSL *ssl,
  5611. const char *buf,
  5612. int len)
  5613. {
  5614. double timeout = -1.0;
  5615. int n, nwritten = 0;
  5616. if (ctx == NULL) {
  5617. return -1;
  5618. }
  5619. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5620. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5621. }
  5622. if (timeout <= 0.0) {
  5623. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5624. }
  5625. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5626. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5627. if (n < 0) {
  5628. if (nwritten == 0) {
  5629. nwritten = -1; /* Propagate the error */
  5630. }
  5631. break;
  5632. } else if (n == 0) {
  5633. break; /* No more data to write */
  5634. } else {
  5635. nwritten += n;
  5636. len -= n;
  5637. }
  5638. }
  5639. return nwritten;
  5640. }
  5641. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5642. * Return value:
  5643. * >=0 .. number of bytes successfully read
  5644. * -1 .. timeout
  5645. * -2 .. error
  5646. */
  5647. static int
  5648. pull_inner(FILE *fp,
  5649. struct mg_connection *conn,
  5650. char *buf,
  5651. int len,
  5652. double timeout)
  5653. {
  5654. int nread, err = 0;
  5655. #if defined(_WIN32)
  5656. typedef int len_t;
  5657. #else
  5658. typedef size_t len_t;
  5659. #endif
  5660. /* We need an additional wait loop around this, because in some cases
  5661. * with TLSwe may get data from the socket but not from SSL_read.
  5662. * In this case we need to repeat at least once.
  5663. */
  5664. if (fp != NULL) {
  5665. #if !defined(_WIN32_WCE)
  5666. /* Use read() instead of fread(), because if we're reading from the
  5667. * CGI pipe, fread() may block until IO buffer is filled up. We
  5668. * cannot afford to block and must pass all read bytes immediately
  5669. * to the client. */
  5670. nread = (int)read(fileno(fp), buf, (size_t)len);
  5671. #else
  5672. /* WinCE does not support CGI pipes */
  5673. nread = (int)fread(buf, 1, (size_t)len, fp);
  5674. #endif
  5675. err = (nread < 0) ? ERRNO : 0;
  5676. if ((nread == 0) && (len > 0)) {
  5677. /* Should get data, but got EOL */
  5678. return -2;
  5679. }
  5680. #if !defined(NO_SSL)
  5681. } else if (conn->ssl != NULL) {
  5682. int ssl_pending;
  5683. struct mg_pollfd pfd[1];
  5684. int pollres;
  5685. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5686. /* We already know there is no more data buffered in conn->buf
  5687. * but there is more available in the SSL layer. So don't poll
  5688. * conn->client.sock yet. */
  5689. if (ssl_pending > len) {
  5690. ssl_pending = len;
  5691. }
  5692. pollres = 1;
  5693. } else {
  5694. pfd[0].fd = conn->client.sock;
  5695. pfd[0].events = POLLIN;
  5696. pollres = mg_poll(pfd,
  5697. 1,
  5698. (int)(timeout * 1000.0),
  5699. &(conn->phys_ctx->stop_flag));
  5700. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5701. return -2;
  5702. }
  5703. }
  5704. if (pollres > 0) {
  5705. ERR_clear_error();
  5706. nread =
  5707. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5708. if (nread <= 0) {
  5709. err = SSL_get_error(conn->ssl, nread);
  5710. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5711. err = ERRNO;
  5712. } else if ((err == SSL_ERROR_WANT_READ)
  5713. || (err == SSL_ERROR_WANT_WRITE)) {
  5714. nread = 0;
  5715. } else {
  5716. /* All errors should return -2 */
  5717. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5718. ERR_clear_error();
  5719. return -2;
  5720. }
  5721. ERR_clear_error();
  5722. } else {
  5723. err = 0;
  5724. }
  5725. } else if (pollres < 0) {
  5726. /* Error */
  5727. return -2;
  5728. } else {
  5729. /* pollres = 0 means timeout */
  5730. nread = 0;
  5731. }
  5732. #endif
  5733. } else {
  5734. struct mg_pollfd pfd[1];
  5735. int pollres;
  5736. pfd[0].fd = conn->client.sock;
  5737. pfd[0].events = POLLIN;
  5738. pollres = mg_poll(pfd,
  5739. 1,
  5740. (int)(timeout * 1000.0),
  5741. &(conn->phys_ctx->stop_flag));
  5742. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5743. return -2;
  5744. }
  5745. if (pollres > 0) {
  5746. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5747. err = (nread < 0) ? ERRNO : 0;
  5748. if (nread <= 0) {
  5749. /* shutdown of the socket at client side */
  5750. return -2;
  5751. }
  5752. } else if (pollres < 0) {
  5753. /* error callint poll */
  5754. return -2;
  5755. } else {
  5756. /* pollres = 0 means timeout */
  5757. nread = 0;
  5758. }
  5759. }
  5760. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5761. return -2;
  5762. }
  5763. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5764. /* some data has been read, or no data was requested */
  5765. return nread;
  5766. }
  5767. if (nread < 0) {
  5768. /* socket error - check errno */
  5769. #if defined(_WIN32)
  5770. if (err == WSAEWOULDBLOCK) {
  5771. /* TODO (low): check if this is still required */
  5772. /* standard case if called from close_socket_gracefully */
  5773. return -2;
  5774. } else if (err == WSAETIMEDOUT) {
  5775. /* TODO (low): check if this is still required */
  5776. /* timeout is handled by the while loop */
  5777. return 0;
  5778. } else if (err == WSAECONNABORTED) {
  5779. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5780. return -2;
  5781. } else {
  5782. DEBUG_TRACE("recv() failed, error %d", err);
  5783. return -2;
  5784. }
  5785. #else
  5786. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5787. * if the timeout is reached and if the socket was set to non-
  5788. * blocking in close_socket_gracefully, so we can not distinguish
  5789. * here. We have to wait for the timeout in both cases for now.
  5790. */
  5791. if (ERROR_TRY_AGAIN(err)) {
  5792. /* TODO (low): check if this is still required */
  5793. /* EAGAIN/EWOULDBLOCK:
  5794. * standard case if called from close_socket_gracefully
  5795. * => should return -1 */
  5796. /* or timeout occurred
  5797. * => the code must stay in the while loop */
  5798. /* EINTR can be generated on a socket with a timeout set even
  5799. * when SA_RESTART is effective for all relevant signals
  5800. * (see signal(7)).
  5801. * => stay in the while loop */
  5802. } else {
  5803. DEBUG_TRACE("recv() failed, error %d", err);
  5804. return -2;
  5805. }
  5806. #endif
  5807. }
  5808. /* Timeout occurred, but no data available. */
  5809. return -1;
  5810. }
  5811. static int
  5812. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5813. {
  5814. int n, nread = 0;
  5815. double timeout = -1.0;
  5816. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5817. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5818. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5819. }
  5820. if (timeout <= 0.0) {
  5821. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5822. }
  5823. start_time = mg_get_current_time_ns();
  5824. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5825. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5826. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5827. if (n == -2) {
  5828. if (nread == 0) {
  5829. nread = -1; /* Propagate the error */
  5830. }
  5831. break;
  5832. } else if (n == -1) {
  5833. /* timeout */
  5834. if (timeout >= 0.0) {
  5835. now = mg_get_current_time_ns();
  5836. if ((now - start_time) <= timeout_ns) {
  5837. continue;
  5838. }
  5839. }
  5840. break;
  5841. } else if (n == 0) {
  5842. break; /* No more data to read */
  5843. } else {
  5844. nread += n;
  5845. len -= n;
  5846. }
  5847. }
  5848. return nread;
  5849. }
  5850. static void
  5851. discard_unread_request_data(struct mg_connection *conn)
  5852. {
  5853. char buf[MG_BUF_LEN];
  5854. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5855. ;
  5856. }
  5857. static int
  5858. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5859. {
  5860. int64_t content_len, n, buffered_len, nread;
  5861. int64_t len64 =
  5862. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5863. * int, we may not read more
  5864. * bytes */
  5865. const char *body;
  5866. if (conn == NULL) {
  5867. return 0;
  5868. }
  5869. /* If Content-Length is not set for a response with body data,
  5870. * we do not know in advance how much data should be read. */
  5871. content_len = conn->content_len;
  5872. if (content_len < 0) {
  5873. /* The body data is completed when the connection is closed. */
  5874. content_len = INT64_MAX;
  5875. }
  5876. nread = 0;
  5877. if (conn->consumed_content < content_len) {
  5878. /* Adjust number of bytes to read. */
  5879. int64_t left_to_read = content_len - conn->consumed_content;
  5880. if (left_to_read < len64) {
  5881. /* Do not read more than the total content length of the
  5882. * request.
  5883. */
  5884. len64 = left_to_read;
  5885. }
  5886. /* Return buffered data */
  5887. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5888. - conn->consumed_content;
  5889. if (buffered_len > 0) {
  5890. if (len64 < buffered_len) {
  5891. buffered_len = len64;
  5892. }
  5893. body = conn->buf + conn->request_len + conn->consumed_content;
  5894. memcpy(buf, body, (size_t)buffered_len);
  5895. len64 -= buffered_len;
  5896. conn->consumed_content += buffered_len;
  5897. nread += buffered_len;
  5898. buf = (char *)buf + buffered_len;
  5899. }
  5900. /* We have returned all buffered data. Read new data from the remote
  5901. * socket.
  5902. */
  5903. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5904. conn->consumed_content += n;
  5905. nread += n;
  5906. } else {
  5907. nread = ((nread > 0) ? nread : n);
  5908. }
  5909. }
  5910. return (int)nread;
  5911. }
  5912. /* Forward declarations */
  5913. static void handle_request(struct mg_connection *);
  5914. #ifdef USE_HTTP2
  5915. #if defined(NO_SSL)
  5916. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5917. #endif
  5918. #define USE_ALPN
  5919. #include "mod_http2.inl"
  5920. /* Not supported with HTTP/2 */
  5921. #define HTTP1_only \
  5922. { \
  5923. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5924. http2_must_use_http1(conn); \
  5925. return; \
  5926. } \
  5927. }
  5928. #else
  5929. #define HTTP1_only
  5930. #endif
  5931. int
  5932. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5933. {
  5934. if (len > INT_MAX) {
  5935. len = INT_MAX;
  5936. }
  5937. if (conn == NULL) {
  5938. return 0;
  5939. }
  5940. if (conn->is_chunked) {
  5941. size_t all_read = 0;
  5942. while (len > 0) {
  5943. if (conn->is_chunked >= 3) {
  5944. /* No more data left to read */
  5945. return 0;
  5946. }
  5947. if (conn->is_chunked != 1) {
  5948. /* Has error */
  5949. return -1;
  5950. }
  5951. if (conn->consumed_content != conn->content_len) {
  5952. /* copy from the current chunk */
  5953. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5954. if (read_ret < 1) {
  5955. /* read error */
  5956. conn->is_chunked = 2;
  5957. return -1;
  5958. }
  5959. all_read += (size_t)read_ret;
  5960. len -= (size_t)read_ret;
  5961. if (conn->consumed_content == conn->content_len) {
  5962. /* Add data bytes in the current chunk have been read,
  5963. * so we are expecting \r\n now. */
  5964. char x[2];
  5965. conn->content_len += 2;
  5966. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5967. || (x[1] != '\n')) {
  5968. /* Protocol violation */
  5969. conn->is_chunked = 2;
  5970. return -1;
  5971. }
  5972. }
  5973. } else {
  5974. /* fetch a new chunk */
  5975. size_t i;
  5976. char lenbuf[64];
  5977. char *end = NULL;
  5978. unsigned long chunkSize = 0;
  5979. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5980. conn->content_len++;
  5981. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5982. lenbuf[i] = 0;
  5983. }
  5984. if ((i > 0) && (lenbuf[i] == '\r')
  5985. && (lenbuf[i - 1] != '\r')) {
  5986. continue;
  5987. }
  5988. if ((i > 1) && (lenbuf[i] == '\n')
  5989. && (lenbuf[i - 1] == '\r')) {
  5990. lenbuf[i + 1] = 0;
  5991. chunkSize = strtoul(lenbuf, &end, 16);
  5992. if (chunkSize == 0) {
  5993. /* regular end of content */
  5994. conn->is_chunked = 3;
  5995. }
  5996. break;
  5997. }
  5998. if (!isxdigit((unsigned char)lenbuf[i])) {
  5999. /* illegal character for chunk length */
  6000. conn->is_chunked = 2;
  6001. return -1;
  6002. }
  6003. }
  6004. if ((end == NULL) || (*end != '\r')) {
  6005. /* chunksize not set correctly */
  6006. conn->is_chunked = 2;
  6007. return -1;
  6008. }
  6009. if (chunkSize == 0) {
  6010. /* try discarding trailer for keep-alive */
  6011. conn->content_len += 2;
  6012. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  6013. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  6014. conn->is_chunked = 4;
  6015. }
  6016. break;
  6017. }
  6018. /* append a new chunk */
  6019. conn->content_len += (int64_t)chunkSize;
  6020. }
  6021. }
  6022. return (int)all_read;
  6023. }
  6024. return mg_read_inner(conn, buf, len);
  6025. }
  6026. int
  6027. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  6028. {
  6029. time_t now;
  6030. int n, total, allowed;
  6031. if (conn == NULL) {
  6032. return 0;
  6033. }
  6034. if (len > INT_MAX) {
  6035. return -1;
  6036. }
  6037. /* Mark connection as "data sent" */
  6038. conn->request_state = 10;
  6039. #ifdef USE_HTTP2
  6040. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  6041. http2_data_frame_head(conn, len, 0);
  6042. }
  6043. #endif
  6044. if (conn->throttle > 0) {
  6045. if ((now = time(NULL)) != conn->last_throttle_time) {
  6046. conn->last_throttle_time = now;
  6047. conn->last_throttle_bytes = 0;
  6048. }
  6049. allowed = conn->throttle - conn->last_throttle_bytes;
  6050. if (allowed > (int)len) {
  6051. allowed = (int)len;
  6052. }
  6053. total = push_all(conn->phys_ctx,
  6054. NULL,
  6055. conn->client.sock,
  6056. conn->ssl,
  6057. (const char *)buf,
  6058. allowed);
  6059. if (total == allowed) {
  6060. buf = (const char *)buf + total;
  6061. conn->last_throttle_bytes += total;
  6062. while ((total < (int)len)
  6063. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6064. allowed = (conn->throttle > ((int)len - total))
  6065. ? (int)len - total
  6066. : conn->throttle;
  6067. n = push_all(conn->phys_ctx,
  6068. NULL,
  6069. conn->client.sock,
  6070. conn->ssl,
  6071. (const char *)buf,
  6072. allowed);
  6073. if (n != allowed) {
  6074. break;
  6075. }
  6076. sleep(1);
  6077. conn->last_throttle_bytes = allowed;
  6078. conn->last_throttle_time = time(NULL);
  6079. buf = (const char *)buf + n;
  6080. total += n;
  6081. }
  6082. }
  6083. } else {
  6084. total = push_all(conn->phys_ctx,
  6085. NULL,
  6086. conn->client.sock,
  6087. conn->ssl,
  6088. (const char *)buf,
  6089. (int)len);
  6090. }
  6091. if (total > 0) {
  6092. conn->num_bytes_sent += total;
  6093. }
  6094. return total;
  6095. }
  6096. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6097. int
  6098. mg_send_chunk(struct mg_connection *conn,
  6099. const char *chunk,
  6100. unsigned int chunk_len)
  6101. {
  6102. char lenbuf[16];
  6103. size_t lenbuf_len;
  6104. int ret;
  6105. int t;
  6106. /* First store the length information in a text buffer. */
  6107. sprintf(lenbuf, "%x\r\n", chunk_len);
  6108. lenbuf_len = strlen(lenbuf);
  6109. /* Then send length information, chunk and terminating \r\n. */
  6110. ret = mg_write(conn, lenbuf, lenbuf_len);
  6111. if (ret != (int)lenbuf_len) {
  6112. return -1;
  6113. }
  6114. t = ret;
  6115. ret = mg_write(conn, chunk, chunk_len);
  6116. if (ret != (int)chunk_len) {
  6117. return -1;
  6118. }
  6119. t += ret;
  6120. ret = mg_write(conn, "\r\n", 2);
  6121. if (ret != 2) {
  6122. return -1;
  6123. }
  6124. t += ret;
  6125. return t;
  6126. }
  6127. #if defined(GCC_DIAGNOSTIC)
  6128. /* This block forwards format strings to printf implementations,
  6129. * so we need to disable the format-nonliteral warning. */
  6130. #pragma GCC diagnostic push
  6131. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6132. #endif
  6133. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6134. static int
  6135. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6136. {
  6137. va_list ap_copy;
  6138. size_t size = MG_BUF_LEN / 4;
  6139. int len = -1;
  6140. *buf = NULL;
  6141. while (len < 0) {
  6142. if (*buf) {
  6143. mg_free(*buf);
  6144. }
  6145. size *= 4;
  6146. *buf = (char *)mg_malloc(size);
  6147. if (!*buf) {
  6148. break;
  6149. }
  6150. va_copy(ap_copy, ap);
  6151. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6152. va_end(ap_copy);
  6153. (*buf)[size - 1] = 0;
  6154. }
  6155. return len;
  6156. }
  6157. /* Print message to buffer. If buffer is large enough to hold the message,
  6158. * return buffer. If buffer is to small, allocate large enough buffer on
  6159. * heap,
  6160. * and return allocated buffer. */
  6161. static int
  6162. alloc_vprintf(char **out_buf,
  6163. char *prealloc_buf,
  6164. size_t prealloc_size,
  6165. const char *fmt,
  6166. va_list ap)
  6167. {
  6168. va_list ap_copy;
  6169. int len;
  6170. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6171. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6172. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6173. * Therefore, we make two passes: on first pass, get required message
  6174. * length.
  6175. * On second pass, actually print the message. */
  6176. va_copy(ap_copy, ap);
  6177. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6178. va_end(ap_copy);
  6179. if (len < 0) {
  6180. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6181. * Switch to alternative code path that uses incremental
  6182. * allocations.
  6183. */
  6184. va_copy(ap_copy, ap);
  6185. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6186. va_end(ap_copy);
  6187. } else if ((size_t)(len) >= prealloc_size) {
  6188. /* The pre-allocated buffer not large enough. */
  6189. /* Allocate a new buffer. */
  6190. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6191. if (!*out_buf) {
  6192. /* Allocation failed. Return -1 as "out of memory" error. */
  6193. return -1;
  6194. }
  6195. /* Buffer allocation successful. Store the string there. */
  6196. va_copy(ap_copy, ap);
  6197. IGNORE_UNUSED_RESULT(
  6198. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6199. va_end(ap_copy);
  6200. } else {
  6201. /* The pre-allocated buffer is large enough.
  6202. * Use it to store the string and return the address. */
  6203. va_copy(ap_copy, ap);
  6204. IGNORE_UNUSED_RESULT(
  6205. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6206. va_end(ap_copy);
  6207. *out_buf = prealloc_buf;
  6208. }
  6209. return len;
  6210. }
  6211. #if defined(GCC_DIAGNOSTIC)
  6212. /* Enable format-nonliteral warning again. */
  6213. #pragma GCC diagnostic pop
  6214. #endif
  6215. static int
  6216. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6217. {
  6218. char mem[MG_BUF_LEN];
  6219. char *buf = NULL;
  6220. int len;
  6221. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6222. len = mg_write(conn, buf, (size_t)len);
  6223. }
  6224. if (buf != mem) {
  6225. mg_free(buf);
  6226. }
  6227. return len;
  6228. }
  6229. int
  6230. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6231. {
  6232. va_list ap;
  6233. int result;
  6234. va_start(ap, fmt);
  6235. result = mg_vprintf(conn, fmt, ap);
  6236. va_end(ap);
  6237. return result;
  6238. }
  6239. int
  6240. mg_url_decode(const char *src,
  6241. int src_len,
  6242. char *dst,
  6243. int dst_len,
  6244. int is_form_url_encoded)
  6245. {
  6246. int i, j, a, b;
  6247. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6248. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6249. if ((i < src_len - 2) && (src[i] == '%')
  6250. && isxdigit((unsigned char)src[i + 1])
  6251. && isxdigit((unsigned char)src[i + 2])) {
  6252. a = tolower((unsigned char)src[i + 1]);
  6253. b = tolower((unsigned char)src[i + 2]);
  6254. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6255. i += 2;
  6256. } else if (is_form_url_encoded && (src[i] == '+')) {
  6257. dst[j] = ' ';
  6258. } else {
  6259. dst[j] = src[i];
  6260. }
  6261. }
  6262. dst[j] = '\0'; /* Null-terminate the destination */
  6263. return (i >= src_len) ? j : -1;
  6264. }
  6265. /* form url decoding of an entire string */
  6266. static void
  6267. url_decode_in_place(char *buf)
  6268. {
  6269. int len = (int)strlen(buf);
  6270. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6271. }
  6272. int
  6273. mg_get_var(const char *data,
  6274. size_t data_len,
  6275. const char *name,
  6276. char *dst,
  6277. size_t dst_len)
  6278. {
  6279. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6280. }
  6281. int
  6282. mg_get_var2(const char *data,
  6283. size_t data_len,
  6284. const char *name,
  6285. char *dst,
  6286. size_t dst_len,
  6287. size_t occurrence)
  6288. {
  6289. const char *p, *e, *s;
  6290. size_t name_len;
  6291. int len;
  6292. if ((dst == NULL) || (dst_len == 0)) {
  6293. len = -2;
  6294. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6295. len = -1;
  6296. dst[0] = '\0';
  6297. } else {
  6298. name_len = strlen(name);
  6299. e = data + data_len;
  6300. len = -1;
  6301. dst[0] = '\0';
  6302. /* data is "var1=val1&var2=val2...". Find variable first */
  6303. for (p = data; p + name_len < e; p++) {
  6304. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6305. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6306. /* Point p to variable value */
  6307. p += name_len + 1;
  6308. /* Point s to the end of the value */
  6309. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6310. if (s == NULL) {
  6311. s = e;
  6312. }
  6313. DEBUG_ASSERT(s >= p);
  6314. if (s < p) {
  6315. return -3;
  6316. }
  6317. /* Decode variable into destination buffer */
  6318. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6319. /* Redirect error code from -1 to -2 (destination buffer too
  6320. * small). */
  6321. if (len == -1) {
  6322. len = -2;
  6323. }
  6324. break;
  6325. }
  6326. }
  6327. }
  6328. return len;
  6329. }
  6330. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6331. int
  6332. mg_split_form_urlencoded(char *data,
  6333. struct mg_header *form_fields,
  6334. unsigned num_form_fields)
  6335. {
  6336. char *b;
  6337. int i;
  6338. int num = 0;
  6339. if (data == NULL) {
  6340. /* parameter error */
  6341. return -1;
  6342. }
  6343. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6344. /* determine the number of expected fields */
  6345. if (data[0] == 0) {
  6346. return 0;
  6347. }
  6348. /* count number of & to return the number of key-value-pairs */
  6349. num = 1;
  6350. while (*data) {
  6351. if (*data == '&') {
  6352. num++;
  6353. }
  6354. data++;
  6355. }
  6356. return num;
  6357. }
  6358. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6359. /* parameter error */
  6360. return -1;
  6361. }
  6362. for (i = 0; i < (int)num_form_fields; i++) {
  6363. /* extract key-value pairs from input data */
  6364. while ((*data == ' ') || (*data == '\t')) {
  6365. /* skip initial spaces */
  6366. data++;
  6367. }
  6368. if (*data == 0) {
  6369. /* end of string reached */
  6370. break;
  6371. }
  6372. form_fields[num].name = data;
  6373. /* find & or = */
  6374. b = data;
  6375. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6376. b++;
  6377. }
  6378. if (*b == 0) {
  6379. /* last key without value */
  6380. form_fields[num].value = NULL;
  6381. } else if (*b == '&') {
  6382. /* mid key without value */
  6383. form_fields[num].value = NULL;
  6384. } else {
  6385. /* terminate string */
  6386. *b = 0;
  6387. /* value starts after '=' */
  6388. data = b + 1;
  6389. form_fields[num].value = data;
  6390. }
  6391. /* new field is stored */
  6392. num++;
  6393. /* find a next key */
  6394. b = strchr(data, '&');
  6395. if (b == 0) {
  6396. /* no more data */
  6397. break;
  6398. } else {
  6399. /* terminate value of last field at '&' */
  6400. *b = 0;
  6401. /* next key-value-pairs starts after '&' */
  6402. data = b + 1;
  6403. }
  6404. }
  6405. /* Decode all values */
  6406. for (i = 0; i < num; i++) {
  6407. if (form_fields[i].name) {
  6408. url_decode_in_place((char *)form_fields[i].name);
  6409. }
  6410. if (form_fields[i].value) {
  6411. url_decode_in_place((char *)form_fields[i].value);
  6412. }
  6413. }
  6414. /* return number of fields found */
  6415. return num;
  6416. }
  6417. /* HCP24: some changes to compare hole var_name */
  6418. int
  6419. mg_get_cookie(const char *cookie_header,
  6420. const char *var_name,
  6421. char *dst,
  6422. size_t dst_size)
  6423. {
  6424. const char *s, *p, *end;
  6425. int name_len, len = -1;
  6426. if ((dst == NULL) || (dst_size == 0)) {
  6427. return -2;
  6428. }
  6429. dst[0] = '\0';
  6430. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6431. return -1;
  6432. }
  6433. name_len = (int)strlen(var_name);
  6434. end = s + strlen(s);
  6435. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6436. if (s[name_len] == '=') {
  6437. /* HCP24: now check is it a substring or a full cookie name */
  6438. if ((s == cookie_header) || (s[-1] == ' ')) {
  6439. s += name_len + 1;
  6440. if ((p = strchr(s, ' ')) == NULL) {
  6441. p = end;
  6442. }
  6443. if (p[-1] == ';') {
  6444. p--;
  6445. }
  6446. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6447. s++;
  6448. p--;
  6449. }
  6450. if ((size_t)(p - s) < dst_size) {
  6451. len = (int)(p - s);
  6452. mg_strlcpy(dst, s, (size_t)len + 1);
  6453. } else {
  6454. len = -3;
  6455. }
  6456. break;
  6457. }
  6458. }
  6459. }
  6460. return len;
  6461. }
  6462. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6463. static void
  6464. base64_encode(const unsigned char *src, int src_len, char *dst)
  6465. {
  6466. static const char *b64 =
  6467. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6468. int i, j, a, b, c;
  6469. for (i = j = 0; i < src_len; i += 3) {
  6470. a = src[i];
  6471. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6472. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6473. dst[j++] = b64[a >> 2];
  6474. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6475. if (i + 1 < src_len) {
  6476. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6477. }
  6478. if (i + 2 < src_len) {
  6479. dst[j++] = b64[c & 63];
  6480. }
  6481. }
  6482. while (j % 4 != 0) {
  6483. dst[j++] = '=';
  6484. }
  6485. dst[j++] = '\0';
  6486. }
  6487. #endif
  6488. #if defined(USE_LUA)
  6489. static unsigned char
  6490. b64reverse(char letter)
  6491. {
  6492. if ((letter >= 'A') && (letter <= 'Z')) {
  6493. return letter - 'A';
  6494. }
  6495. if ((letter >= 'a') && (letter <= 'z')) {
  6496. return letter - 'a' + 26;
  6497. }
  6498. if ((letter >= '0') && (letter <= '9')) {
  6499. return letter - '0' + 52;
  6500. }
  6501. if (letter == '+') {
  6502. return 62;
  6503. }
  6504. if (letter == '/') {
  6505. return 63;
  6506. }
  6507. if (letter == '=') {
  6508. return 255; /* normal end */
  6509. }
  6510. return 254; /* error */
  6511. }
  6512. static int
  6513. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6514. {
  6515. int i;
  6516. unsigned char a, b, c, d;
  6517. *dst_len = 0;
  6518. for (i = 0; i < src_len; i += 4) {
  6519. a = b64reverse(src[i]);
  6520. if (a >= 254) {
  6521. return i;
  6522. }
  6523. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6524. if (b >= 254) {
  6525. return i + 1;
  6526. }
  6527. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6528. if (c == 254) {
  6529. return i + 2;
  6530. }
  6531. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6532. if (d == 254) {
  6533. return i + 3;
  6534. }
  6535. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6536. if (c != 255) {
  6537. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6538. if (d != 255) {
  6539. dst[(*dst_len)++] = (c << 6) + d;
  6540. }
  6541. }
  6542. }
  6543. return -1;
  6544. }
  6545. #endif
  6546. static int
  6547. is_put_or_delete_method(const struct mg_connection *conn)
  6548. {
  6549. if (conn) {
  6550. const char *s = conn->request_info.request_method;
  6551. return (s != NULL)
  6552. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6553. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6554. }
  6555. return 0;
  6556. }
  6557. #if !defined(NO_FILES)
  6558. static int
  6559. extention_matches_script(
  6560. struct mg_connection *conn, /* in: request (must be valid) */
  6561. const char *filename /* in: filename (must be valid) */
  6562. )
  6563. {
  6564. #if !defined(NO_CGI)
  6565. if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], filename)
  6566. > 0) {
  6567. return 1;
  6568. }
  6569. if (match_prefix_strlen(conn->dom_ctx->config[CGI2_EXTENSIONS], filename)
  6570. > 0) {
  6571. return 1;
  6572. }
  6573. #endif
  6574. #if defined(USE_LUA)
  6575. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6576. filename)
  6577. > 0) {
  6578. return 1;
  6579. }
  6580. #endif
  6581. #if defined(USE_DUKTAPE)
  6582. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6583. filename)
  6584. > 0) {
  6585. return 1;
  6586. }
  6587. #endif
  6588. /* filename and conn could be unused, if all preocessor conditions
  6589. * are false (no script language supported). */
  6590. (void)filename;
  6591. (void)conn;
  6592. return 0;
  6593. }
  6594. /* For given directory path, substitute it to valid index file.
  6595. * Return 1 if index file has been found, 0 if not found.
  6596. * If the file is found, it's stats is returned in stp. */
  6597. static int
  6598. substitute_index_file(struct mg_connection *conn,
  6599. char *path,
  6600. size_t path_len,
  6601. struct mg_file_stat *filestat)
  6602. {
  6603. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6604. struct vec filename_vec;
  6605. size_t n = strlen(path);
  6606. int found = 0;
  6607. /* The 'path' given to us points to the directory. Remove all trailing
  6608. * directory separator characters from the end of the path, and
  6609. * then append single directory separator character. */
  6610. while ((n > 0) && (path[n - 1] == '/')) {
  6611. n--;
  6612. }
  6613. path[n] = '/';
  6614. /* Traverse index files list. For each entry, append it to the given
  6615. * path and see if the file exists. If it exists, break the loop */
  6616. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6617. /* Ignore too long entries that may overflow path buffer */
  6618. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6619. continue;
  6620. }
  6621. /* Prepare full path to the index file */
  6622. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6623. /* Does it exist? */
  6624. if (mg_stat(conn, path, filestat)) {
  6625. /* Yes it does, break the loop */
  6626. found = 1;
  6627. break;
  6628. }
  6629. }
  6630. /* If no index file exists, restore directory path */
  6631. if (!found) {
  6632. path[n] = '\0';
  6633. }
  6634. return found;
  6635. }
  6636. #endif
  6637. static void
  6638. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6639. char *filename, /* out: filename */
  6640. size_t filename_buf_len, /* in: size of filename buffer */
  6641. struct mg_file_stat *filestat, /* out: file status structure */
  6642. int *is_found, /* out: file found (directly) */
  6643. int *is_script_resource, /* out: handled by a script? */
  6644. int *is_websocket_request, /* out: websocket connetion? */
  6645. int *is_put_or_delete_request /* out: put/delete a file? */
  6646. )
  6647. {
  6648. char const *accept_encoding;
  6649. #if !defined(NO_FILES)
  6650. const char *uri = conn->request_info.local_uri;
  6651. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6652. const char *rewrite;
  6653. struct vec a, b;
  6654. ptrdiff_t match_len;
  6655. char gz_path[PATH_MAX];
  6656. int truncated;
  6657. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6658. char *tmp_str;
  6659. size_t tmp_str_len, sep_pos;
  6660. int allow_substitute_script_subresources;
  6661. #endif
  6662. #else
  6663. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6664. #endif
  6665. /* Step 1: Set all initially unknown outputs to zero */
  6666. memset(filestat, 0, sizeof(*filestat));
  6667. *filename = 0;
  6668. *is_found = 0;
  6669. *is_script_resource = 0;
  6670. /* Step 2: Check if the request attempts to modify the file system */
  6671. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6672. /* Step 3: Check if it is a websocket request, and modify the document
  6673. * root if required */
  6674. #if defined(USE_WEBSOCKET)
  6675. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6676. #if !defined(NO_FILES)
  6677. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6678. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6679. }
  6680. #endif /* !NO_FILES */
  6681. #else /* USE_WEBSOCKET */
  6682. *is_websocket_request = 0;
  6683. #endif /* USE_WEBSOCKET */
  6684. /* Step 4: Check if gzip encoded response is allowed */
  6685. conn->accept_gzip = 0;
  6686. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6687. if (strstr(accept_encoding, "gzip") != NULL) {
  6688. conn->accept_gzip = 1;
  6689. }
  6690. }
  6691. #if !defined(NO_FILES)
  6692. /* Step 5: If there is no root directory, don't look for files. */
  6693. /* Note that root == NULL is a regular use case here. This occurs,
  6694. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6695. * config is not required. */
  6696. if (root == NULL) {
  6697. /* all file related outputs have already been set to 0, just return
  6698. */
  6699. return;
  6700. }
  6701. /* Step 6: Determine the local file path from the root path and the
  6702. * request uri. */
  6703. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6704. * part of the path one byte on the right. */
  6705. truncated = 0;
  6706. mg_snprintf(
  6707. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6708. if (truncated) {
  6709. goto interpret_cleanup;
  6710. }
  6711. /* Step 7: URI rewriting */
  6712. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6713. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6714. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6715. mg_snprintf(conn,
  6716. &truncated,
  6717. filename,
  6718. filename_buf_len - 1,
  6719. "%.*s%s",
  6720. (int)b.len,
  6721. b.ptr,
  6722. uri + match_len);
  6723. break;
  6724. }
  6725. }
  6726. if (truncated) {
  6727. goto interpret_cleanup;
  6728. }
  6729. /* Step 8: Check if the file exists at the server */
  6730. /* Local file path and name, corresponding to requested URI
  6731. * is now stored in "filename" variable. */
  6732. if (mg_stat(conn, filename, filestat)) {
  6733. int uri_len = (int)strlen(uri);
  6734. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6735. /* 8.1: File exists. */
  6736. *is_found = 1;
  6737. /* 8.2: Check if it is a script type. */
  6738. if (extention_matches_script(conn, filename)) {
  6739. /* The request addresses a CGI resource, Lua script or
  6740. * server-side javascript.
  6741. * The URI corresponds to the script itself (like
  6742. * /path/script.cgi), and there is no additional resource
  6743. * path (like /path/script.cgi/something).
  6744. * Requests that modify (replace or delete) a resource, like
  6745. * PUT and DELETE requests, should replace/delete the script
  6746. * file.
  6747. * Requests that read or write from/to a resource, like GET and
  6748. * POST requests, should call the script and return the
  6749. * generated response. */
  6750. *is_script_resource = (!*is_put_or_delete_request);
  6751. }
  6752. /* 8.3: If the request target is a directory, there could be
  6753. * a substitute file (index.html, index.cgi, ...). */
  6754. if (filestat->is_directory && is_uri_end_slash) {
  6755. /* Use a local copy here, since substitute_index_file will
  6756. * change the content of the file status */
  6757. struct mg_file_stat tmp_filestat;
  6758. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6759. if (substitute_index_file(
  6760. conn, filename, filename_buf_len, &tmp_filestat)) {
  6761. /* Substitute file found. Copy stat to the output, then
  6762. * check if the file is a script file */
  6763. *filestat = tmp_filestat;
  6764. if (extention_matches_script(conn, filename)) {
  6765. /* Substitute file is a script file */
  6766. *is_script_resource = 1;
  6767. } else {
  6768. /* Substitute file is a regular file */
  6769. *is_script_resource = 0;
  6770. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6771. }
  6772. }
  6773. /* If there is no substitute file, the server could return
  6774. * a directory listing in a later step */
  6775. }
  6776. return;
  6777. }
  6778. /* Step 9: Check for zipped files: */
  6779. /* If we can't find the actual file, look for the file
  6780. * with the same name but a .gz extension. If we find it,
  6781. * use that and set the gzipped flag in the file struct
  6782. * to indicate that the response need to have the content-
  6783. * encoding: gzip header.
  6784. * We can only do this if the browser declares support. */
  6785. if (conn->accept_gzip) {
  6786. mg_snprintf(
  6787. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6788. if (truncated) {
  6789. goto interpret_cleanup;
  6790. }
  6791. if (mg_stat(conn, gz_path, filestat)) {
  6792. if (filestat) {
  6793. filestat->is_gzipped = 1;
  6794. *is_found = 1;
  6795. }
  6796. /* Currently gz files can not be scripts. */
  6797. return;
  6798. }
  6799. }
  6800. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6801. /* Step 10: Script resources may handle sub-resources */
  6802. /* Support PATH_INFO for CGI scripts. */
  6803. tmp_str_len = strlen(filename);
  6804. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6805. if (!tmp_str) {
  6806. /* Out of memory */
  6807. goto interpret_cleanup;
  6808. }
  6809. memcpy(tmp_str, filename, tmp_str_len + 1);
  6810. /* Check config, if index scripts may have sub-resources */
  6811. allow_substitute_script_subresources =
  6812. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6813. "yes");
  6814. sep_pos = tmp_str_len;
  6815. while (sep_pos > 0) {
  6816. sep_pos--;
  6817. if (tmp_str[sep_pos] == '/') {
  6818. int is_script = 0, does_exist = 0;
  6819. tmp_str[sep_pos] = 0;
  6820. if (tmp_str[0]) {
  6821. is_script = extention_matches_script(conn, tmp_str);
  6822. does_exist = mg_stat(conn, tmp_str, filestat);
  6823. }
  6824. if (does_exist && is_script) {
  6825. filename[sep_pos] = 0;
  6826. memmove(filename + sep_pos + 2,
  6827. filename + sep_pos + 1,
  6828. strlen(filename + sep_pos + 1) + 1);
  6829. conn->path_info = filename + sep_pos + 1;
  6830. filename[sep_pos + 1] = '/';
  6831. *is_script_resource = 1;
  6832. *is_found = 1;
  6833. break;
  6834. }
  6835. if (allow_substitute_script_subresources) {
  6836. if (substitute_index_file(
  6837. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6838. /* some intermediate directory has an index file */
  6839. if (extention_matches_script(conn, tmp_str)) {
  6840. size_t script_name_len = strlen(tmp_str);
  6841. /* subres_name read before this memory locatio will be
  6842. overwritten */
  6843. char *subres_name = filename + sep_pos;
  6844. size_t subres_name_len = strlen(subres_name);
  6845. DEBUG_TRACE("Substitute script %s serving path %s",
  6846. tmp_str,
  6847. filename);
  6848. /* this index file is a script */
  6849. if ((script_name_len + subres_name_len + 2)
  6850. >= filename_buf_len) {
  6851. mg_free(tmp_str);
  6852. goto interpret_cleanup;
  6853. }
  6854. conn->path_info =
  6855. filename + script_name_len + 1; /* new target */
  6856. memmove(conn->path_info, subres_name, subres_name_len);
  6857. conn->path_info[subres_name_len] = 0;
  6858. memcpy(filename, tmp_str, script_name_len + 1);
  6859. *is_script_resource = 1;
  6860. *is_found = 1;
  6861. break;
  6862. } else {
  6863. DEBUG_TRACE("Substitute file %s serving path %s",
  6864. tmp_str,
  6865. filename);
  6866. /* non-script files will not have sub-resources */
  6867. filename[sep_pos] = 0;
  6868. conn->path_info = 0;
  6869. *is_script_resource = 0;
  6870. *is_found = 0;
  6871. break;
  6872. }
  6873. }
  6874. }
  6875. tmp_str[sep_pos] = '/';
  6876. }
  6877. }
  6878. mg_free(tmp_str);
  6879. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6880. #endif /* !defined(NO_FILES) */
  6881. return;
  6882. #if !defined(NO_FILES)
  6883. /* Reset all outputs */
  6884. interpret_cleanup:
  6885. memset(filestat, 0, sizeof(*filestat));
  6886. *filename = 0;
  6887. *is_found = 0;
  6888. *is_script_resource = 0;
  6889. *is_websocket_request = 0;
  6890. *is_put_or_delete_request = 0;
  6891. #endif /* !defined(NO_FILES) */
  6892. }
  6893. /* Check whether full request is buffered. Return:
  6894. * -1 if request or response is malformed
  6895. * 0 if request or response is not yet fully buffered
  6896. * >0 actual request length, including last \r\n\r\n */
  6897. static int
  6898. get_http_header_len(const char *buf, int buflen)
  6899. {
  6900. int i;
  6901. for (i = 0; i < buflen; i++) {
  6902. /* Do an unsigned comparison in some conditions below */
  6903. const unsigned char c = (unsigned char)buf[i];
  6904. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6905. && !isprint(c)) {
  6906. /* abort scan as soon as one malformed character is found */
  6907. return -1;
  6908. }
  6909. if (i < buflen - 1) {
  6910. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6911. /* Two newline, no carriage return - not standard compliant,
  6912. * but it should be accepted */
  6913. return i + 2;
  6914. }
  6915. }
  6916. if (i < buflen - 3) {
  6917. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6918. && (buf[i + 3] == '\n')) {
  6919. /* Two \r\n - standard compliant */
  6920. return i + 4;
  6921. }
  6922. }
  6923. }
  6924. return 0;
  6925. }
  6926. #if !defined(NO_CACHING)
  6927. /* Convert month to the month number. Return -1 on error, or month number */
  6928. static int
  6929. get_month_index(const char *s)
  6930. {
  6931. size_t i;
  6932. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6933. if (!strcmp(s, month_names[i])) {
  6934. return (int)i;
  6935. }
  6936. }
  6937. return -1;
  6938. }
  6939. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6940. static time_t
  6941. parse_date_string(const char *datetime)
  6942. {
  6943. char month_str[32] = {0};
  6944. int second, minute, hour, day, month, year;
  6945. time_t result = (time_t)0;
  6946. struct tm tm;
  6947. if ((sscanf(datetime,
  6948. "%d/%3s/%d %d:%d:%d",
  6949. &day,
  6950. month_str,
  6951. &year,
  6952. &hour,
  6953. &minute,
  6954. &second)
  6955. == 6)
  6956. || (sscanf(datetime,
  6957. "%d %3s %d %d:%d:%d",
  6958. &day,
  6959. month_str,
  6960. &year,
  6961. &hour,
  6962. &minute,
  6963. &second)
  6964. == 6)
  6965. || (sscanf(datetime,
  6966. "%*3s, %d %3s %d %d:%d:%d",
  6967. &day,
  6968. month_str,
  6969. &year,
  6970. &hour,
  6971. &minute,
  6972. &second)
  6973. == 6)
  6974. || (sscanf(datetime,
  6975. "%d-%3s-%d %d:%d:%d",
  6976. &day,
  6977. month_str,
  6978. &year,
  6979. &hour,
  6980. &minute,
  6981. &second)
  6982. == 6)) {
  6983. month = get_month_index(month_str);
  6984. if ((month >= 0) && (year >= 1970)) {
  6985. memset(&tm, 0, sizeof(tm));
  6986. tm.tm_year = year - 1900;
  6987. tm.tm_mon = month;
  6988. tm.tm_mday = day;
  6989. tm.tm_hour = hour;
  6990. tm.tm_min = minute;
  6991. tm.tm_sec = second;
  6992. result = timegm(&tm);
  6993. }
  6994. }
  6995. return result;
  6996. }
  6997. #endif /* !NO_CACHING */
  6998. /* Pre-process URIs according to RFC + protect against directory disclosure
  6999. * attacks by removing '..', excessive '/' and '\' characters */
  7000. static void
  7001. remove_dot_segments(char *inout)
  7002. {
  7003. /* Windows backend protection
  7004. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7005. * in URI by slash */
  7006. char *out_end = inout;
  7007. char *in = inout;
  7008. if (!in) {
  7009. /* Param error. */
  7010. return;
  7011. }
  7012. while (*in) {
  7013. if (*in == '\\') {
  7014. *in = '/';
  7015. }
  7016. in++;
  7017. }
  7018. /* Algorithm "remove_dot_segments" from
  7019. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7020. /* Step 1:
  7021. * The input buffer is initialized.
  7022. * The output buffer is initialized to the empty string.
  7023. */
  7024. in = inout;
  7025. /* Step 2:
  7026. * While the input buffer is not empty, loop as follows:
  7027. */
  7028. /* Less than out_end of the inout buffer is used as output, so keep
  7029. * condition: out_end <= in */
  7030. while (*in) {
  7031. /* Step 2a:
  7032. * If the input buffer begins with a prefix of "../" or "./",
  7033. * then remove that prefix from the input buffer;
  7034. */
  7035. if (!strncmp(in, "../", 3)) {
  7036. in += 3;
  7037. } else if (!strncmp(in, "./", 2)) {
  7038. in += 2;
  7039. }
  7040. /* otherwise */
  7041. /* Step 2b:
  7042. * if the input buffer begins with a prefix of "/./" or "/.",
  7043. * where "." is a complete path segment, then replace that
  7044. * prefix with "/" in the input buffer;
  7045. */
  7046. else if (!strncmp(in, "/./", 3)) {
  7047. in += 2;
  7048. } else if (!strcmp(in, "/.")) {
  7049. in[1] = 0;
  7050. }
  7051. /* otherwise */
  7052. /* Step 2c:
  7053. * if the input buffer begins with a prefix of "/../" or "/..",
  7054. * where ".." is a complete path segment, then replace that
  7055. * prefix with "/" in the input buffer and remove the last
  7056. * segment and its preceding "/" (if any) from the output
  7057. * buffer;
  7058. */
  7059. else if (!strncmp(in, "/../", 4)) {
  7060. in += 3;
  7061. if (inout != out_end) {
  7062. /* remove last segment */
  7063. do {
  7064. out_end--;
  7065. } while ((inout != out_end) && (*out_end != '/'));
  7066. }
  7067. } else if (!strcmp(in, "/..")) {
  7068. in[1] = 0;
  7069. if (inout != out_end) {
  7070. /* remove last segment */
  7071. do {
  7072. out_end--;
  7073. } while ((inout != out_end) && (*out_end != '/'));
  7074. }
  7075. }
  7076. /* otherwise */
  7077. /* Step 2d:
  7078. * if the input buffer consists only of "." or "..", then remove
  7079. * that from the input buffer;
  7080. */
  7081. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7082. *in = 0;
  7083. }
  7084. /* otherwise */
  7085. /* Step 2e:
  7086. * move the first path segment in the input buffer to the end of
  7087. * the output buffer, including the initial "/" character (if
  7088. * any) and any subsequent characters up to, but not including,
  7089. * the next "/" character or the end of the input buffer.
  7090. */
  7091. else {
  7092. do {
  7093. *out_end = *in;
  7094. out_end++;
  7095. in++;
  7096. } while ((*in != 0) && (*in != '/'));
  7097. }
  7098. }
  7099. /* Step 3:
  7100. * Finally, the output buffer is returned as the result of
  7101. * remove_dot_segments.
  7102. */
  7103. /* Terminate output */
  7104. *out_end = 0;
  7105. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7106. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7107. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7108. * or "//" anymore.
  7109. */
  7110. out_end = in = inout;
  7111. while (*in) {
  7112. if (*in == '.') {
  7113. /* remove . at the end or preceding of / */
  7114. char *in_ahead = in;
  7115. do {
  7116. in_ahead++;
  7117. } while (*in_ahead == '.');
  7118. if (*in_ahead == '/') {
  7119. in = in_ahead;
  7120. if ((out_end != inout) && (out_end[-1] == '/')) {
  7121. /* remove generated // */
  7122. out_end--;
  7123. }
  7124. } else if (*in_ahead == 0) {
  7125. in = in_ahead;
  7126. } else {
  7127. do {
  7128. *out_end++ = '.';
  7129. in++;
  7130. } while (in != in_ahead);
  7131. }
  7132. } else if (*in == '/') {
  7133. /* replace // by / */
  7134. *out_end++ = '/';
  7135. do {
  7136. in++;
  7137. } while (*in == '/');
  7138. } else {
  7139. *out_end++ = *in;
  7140. in++;
  7141. }
  7142. }
  7143. *out_end = 0;
  7144. }
  7145. static const struct {
  7146. const char *extension;
  7147. size_t ext_len;
  7148. const char *mime_type;
  7149. } builtin_mime_types[] = {
  7150. /* IANA registered MIME types
  7151. * (http://www.iana.org/assignments/media-types)
  7152. * application types */
  7153. {".doc", 4, "application/msword"},
  7154. {".eps", 4, "application/postscript"},
  7155. {".exe", 4, "application/octet-stream"},
  7156. {".js", 3, "application/javascript"},
  7157. {".json", 5, "application/json"},
  7158. {".pdf", 4, "application/pdf"},
  7159. {".ps", 3, "application/postscript"},
  7160. {".rtf", 4, "application/rtf"},
  7161. {".xhtml", 6, "application/xhtml+xml"},
  7162. {".xsl", 4, "application/xml"},
  7163. {".xslt", 5, "application/xml"},
  7164. /* fonts */
  7165. {".ttf", 4, "application/font-sfnt"},
  7166. {".cff", 4, "application/font-sfnt"},
  7167. {".otf", 4, "application/font-sfnt"},
  7168. {".aat", 4, "application/font-sfnt"},
  7169. {".sil", 4, "application/font-sfnt"},
  7170. {".pfr", 4, "application/font-tdpfr"},
  7171. {".woff", 5, "application/font-woff"},
  7172. /* audio */
  7173. {".mp3", 4, "audio/mpeg"},
  7174. {".oga", 4, "audio/ogg"},
  7175. {".ogg", 4, "audio/ogg"},
  7176. /* image */
  7177. {".gif", 4, "image/gif"},
  7178. {".ief", 4, "image/ief"},
  7179. {".jpeg", 5, "image/jpeg"},
  7180. {".jpg", 4, "image/jpeg"},
  7181. {".jpm", 4, "image/jpm"},
  7182. {".jpx", 4, "image/jpx"},
  7183. {".png", 4, "image/png"},
  7184. {".svg", 4, "image/svg+xml"},
  7185. {".tif", 4, "image/tiff"},
  7186. {".tiff", 5, "image/tiff"},
  7187. /* model */
  7188. {".wrl", 4, "model/vrml"},
  7189. /* text */
  7190. {".css", 4, "text/css"},
  7191. {".csv", 4, "text/csv"},
  7192. {".htm", 4, "text/html"},
  7193. {".html", 5, "text/html"},
  7194. {".sgm", 4, "text/sgml"},
  7195. {".shtm", 5, "text/html"},
  7196. {".shtml", 6, "text/html"},
  7197. {".txt", 4, "text/plain"},
  7198. {".xml", 4, "text/xml"},
  7199. /* video */
  7200. {".mov", 4, "video/quicktime"},
  7201. {".mp4", 4, "video/mp4"},
  7202. {".mpeg", 5, "video/mpeg"},
  7203. {".mpg", 4, "video/mpeg"},
  7204. {".ogv", 4, "video/ogg"},
  7205. {".qt", 3, "video/quicktime"},
  7206. /* not registered types
  7207. * (http://reference.sitepoint.com/html/mime-types-full,
  7208. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7209. {".arj", 4, "application/x-arj-compressed"},
  7210. {".gz", 3, "application/x-gunzip"},
  7211. {".rar", 4, "application/x-arj-compressed"},
  7212. {".swf", 4, "application/x-shockwave-flash"},
  7213. {".tar", 4, "application/x-tar"},
  7214. {".tgz", 4, "application/x-tar-gz"},
  7215. {".torrent", 8, "application/x-bittorrent"},
  7216. {".ppt", 4, "application/x-mspowerpoint"},
  7217. {".xls", 4, "application/x-msexcel"},
  7218. {".zip", 4, "application/x-zip-compressed"},
  7219. {".aac",
  7220. 4,
  7221. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7222. {".aif", 4, "audio/x-aif"},
  7223. {".m3u", 4, "audio/x-mpegurl"},
  7224. {".mid", 4, "audio/x-midi"},
  7225. {".ra", 3, "audio/x-pn-realaudio"},
  7226. {".ram", 4, "audio/x-pn-realaudio"},
  7227. {".wav", 4, "audio/x-wav"},
  7228. {".bmp", 4, "image/bmp"},
  7229. {".ico", 4, "image/x-icon"},
  7230. {".pct", 4, "image/x-pct"},
  7231. {".pict", 5, "image/pict"},
  7232. {".rgb", 4, "image/x-rgb"},
  7233. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7234. {".asf", 4, "video/x-ms-asf"},
  7235. {".avi", 4, "video/x-msvideo"},
  7236. {".m4v", 4, "video/x-m4v"},
  7237. {NULL, 0, NULL}};
  7238. const char *
  7239. mg_get_builtin_mime_type(const char *path)
  7240. {
  7241. const char *ext;
  7242. size_t i, path_len;
  7243. path_len = strlen(path);
  7244. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7245. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7246. if ((path_len > builtin_mime_types[i].ext_len)
  7247. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7248. return builtin_mime_types[i].mime_type;
  7249. }
  7250. }
  7251. return "text/plain";
  7252. }
  7253. /* Look at the "path" extension and figure what mime type it has.
  7254. * Store mime type in the vector. */
  7255. static void
  7256. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7257. {
  7258. struct vec ext_vec, mime_vec;
  7259. const char *list, *ext;
  7260. size_t path_len;
  7261. path_len = strlen(path);
  7262. if ((conn == NULL) || (vec == NULL)) {
  7263. if (vec != NULL) {
  7264. memset(vec, '\0', sizeof(struct vec));
  7265. }
  7266. return;
  7267. }
  7268. /* Scan user-defined mime types first, in case user wants to
  7269. * override default mime types. */
  7270. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7271. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7272. /* ext now points to the path suffix */
  7273. ext = path + path_len - ext_vec.len;
  7274. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7275. *vec = mime_vec;
  7276. return;
  7277. }
  7278. }
  7279. vec->ptr = mg_get_builtin_mime_type(path);
  7280. vec->len = strlen(vec->ptr);
  7281. }
  7282. /* Stringify binary data. Output buffer must be twice as big as input,
  7283. * because each byte takes 2 bytes in string representation */
  7284. static void
  7285. bin2str(char *to, const unsigned char *p, size_t len)
  7286. {
  7287. static const char *hex = "0123456789abcdef";
  7288. for (; len--; p++) {
  7289. *to++ = hex[p[0] >> 4];
  7290. *to++ = hex[p[0] & 0x0f];
  7291. }
  7292. *to = '\0';
  7293. }
  7294. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7295. */
  7296. char *
  7297. mg_md5(char buf[33], ...)
  7298. {
  7299. md5_byte_t hash[16];
  7300. const char *p;
  7301. va_list ap;
  7302. md5_state_t ctx;
  7303. md5_init(&ctx);
  7304. va_start(ap, buf);
  7305. while ((p = va_arg(ap, const char *)) != NULL) {
  7306. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7307. }
  7308. va_end(ap);
  7309. md5_finish(&ctx, hash);
  7310. bin2str(buf, hash, sizeof(hash));
  7311. return buf;
  7312. }
  7313. /* Check the user's password, return 1 if OK */
  7314. static int
  7315. check_password(const char *method,
  7316. const char *ha1,
  7317. const char *uri,
  7318. const char *nonce,
  7319. const char *nc,
  7320. const char *cnonce,
  7321. const char *qop,
  7322. const char *response)
  7323. {
  7324. char ha2[32 + 1], expected_response[32 + 1];
  7325. /* Some of the parameters may be NULL */
  7326. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7327. || (qop == NULL) || (response == NULL)) {
  7328. return 0;
  7329. }
  7330. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7331. if (strlen(response) != 32) {
  7332. return 0;
  7333. }
  7334. mg_md5(ha2, method, ":", uri, NULL);
  7335. mg_md5(expected_response,
  7336. ha1,
  7337. ":",
  7338. nonce,
  7339. ":",
  7340. nc,
  7341. ":",
  7342. cnonce,
  7343. ":",
  7344. qop,
  7345. ":",
  7346. ha2,
  7347. NULL);
  7348. return mg_strcasecmp(response, expected_response) == 0;
  7349. }
  7350. #if !defined(NO_FILESYSTEMS)
  7351. /* Use the global passwords file, if specified by auth_gpass option,
  7352. * or search for .htpasswd in the requested directory. */
  7353. static void
  7354. open_auth_file(struct mg_connection *conn,
  7355. const char *path,
  7356. struct mg_file *filep)
  7357. {
  7358. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7359. char name[PATH_MAX];
  7360. const char *p, *e,
  7361. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7362. int truncated;
  7363. if (gpass != NULL) {
  7364. /* Use global passwords file */
  7365. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7366. #if defined(DEBUG)
  7367. /* Use mg_cry_internal here, since gpass has been
  7368. * configured. */
  7369. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7370. #endif
  7371. }
  7372. /* Important: using local struct mg_file to test path for
  7373. * is_directory flag. If filep is used, mg_stat() makes it
  7374. * appear as if auth file was opened.
  7375. * TODO(mid): Check if this is still required after rewriting
  7376. * mg_stat */
  7377. } else if (mg_stat(conn, path, &filep->stat)
  7378. && filep->stat.is_directory) {
  7379. mg_snprintf(conn,
  7380. &truncated,
  7381. name,
  7382. sizeof(name),
  7383. "%s/%s",
  7384. path,
  7385. PASSWORDS_FILE_NAME);
  7386. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7387. #if defined(DEBUG)
  7388. /* Don't use mg_cry_internal here, but only a trace, since
  7389. * this is a typical case. It will occur for every directory
  7390. * without a password file. */
  7391. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7392. #endif
  7393. }
  7394. } else {
  7395. /* Try to find .htpasswd in requested directory. */
  7396. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7397. if (e[0] == '/') {
  7398. break;
  7399. }
  7400. }
  7401. mg_snprintf(conn,
  7402. &truncated,
  7403. name,
  7404. sizeof(name),
  7405. "%.*s/%s",
  7406. (int)(e - p),
  7407. p,
  7408. PASSWORDS_FILE_NAME);
  7409. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7410. #if defined(DEBUG)
  7411. /* Don't use mg_cry_internal here, but only a trace, since
  7412. * this is a typical case. It will occur for every directory
  7413. * without a password file. */
  7414. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7415. #endif
  7416. }
  7417. }
  7418. }
  7419. }
  7420. #endif /* NO_FILESYSTEMS */
  7421. /* Parsed Authorization header */
  7422. struct ah {
  7423. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7424. };
  7425. /* Return 1 on success. Always initializes the ah structure. */
  7426. static int
  7427. parse_auth_header(struct mg_connection *conn,
  7428. char *buf,
  7429. size_t buf_size,
  7430. struct ah *ah)
  7431. {
  7432. char *name, *value, *s;
  7433. const char *auth_header;
  7434. uint64_t nonce;
  7435. if (!ah || !conn) {
  7436. return 0;
  7437. }
  7438. (void)memset(ah, 0, sizeof(*ah));
  7439. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7440. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7441. return 0;
  7442. }
  7443. /* Make modifiable copy of the auth header */
  7444. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7445. s = buf;
  7446. /* Parse authorization header */
  7447. for (;;) {
  7448. /* Gobble initial spaces */
  7449. while (isspace((unsigned char)*s)) {
  7450. s++;
  7451. }
  7452. name = skip_quoted(&s, "=", " ", 0);
  7453. /* Value is either quote-delimited, or ends at first comma or space.
  7454. */
  7455. if (s[0] == '\"') {
  7456. s++;
  7457. value = skip_quoted(&s, "\"", " ", '\\');
  7458. if (s[0] == ',') {
  7459. s++;
  7460. }
  7461. } else {
  7462. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7463. * uses spaces */
  7464. }
  7465. if (*name == '\0') {
  7466. break;
  7467. }
  7468. if (!strcmp(name, "username")) {
  7469. ah->user = value;
  7470. } else if (!strcmp(name, "cnonce")) {
  7471. ah->cnonce = value;
  7472. } else if (!strcmp(name, "response")) {
  7473. ah->response = value;
  7474. } else if (!strcmp(name, "uri")) {
  7475. ah->uri = value;
  7476. } else if (!strcmp(name, "qop")) {
  7477. ah->qop = value;
  7478. } else if (!strcmp(name, "nc")) {
  7479. ah->nc = value;
  7480. } else if (!strcmp(name, "nonce")) {
  7481. ah->nonce = value;
  7482. }
  7483. }
  7484. #if !defined(NO_NONCE_CHECK)
  7485. /* Read the nonce from the response. */
  7486. if (ah->nonce == NULL) {
  7487. return 0;
  7488. }
  7489. s = NULL;
  7490. nonce = strtoull(ah->nonce, &s, 10);
  7491. if ((s == NULL) || (*s != 0)) {
  7492. return 0;
  7493. }
  7494. /* Convert the nonce from the client to a number. */
  7495. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7496. /* The converted number corresponds to the time the nounce has been
  7497. * created. This should not be earlier than the server start. */
  7498. /* Server side nonce check is valuable in all situations but one:
  7499. * if the server restarts frequently, but the client should not see
  7500. * that, so the server should accept nonces from previous starts. */
  7501. /* However, the reasonable default is to not accept a nonce from a
  7502. * previous start, so if anyone changed the access rights between
  7503. * two restarts, a new login is required. */
  7504. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7505. /* nonce is from a previous start of the server and no longer valid
  7506. * (replay attack?) */
  7507. return 0;
  7508. }
  7509. /* Check if the nonce is too high, so it has not (yet) been used by the
  7510. * server. */
  7511. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7512. + conn->dom_ctx->nonce_count)) {
  7513. return 0;
  7514. }
  7515. #else
  7516. (void)nonce;
  7517. #endif
  7518. /* CGI needs it as REMOTE_USER */
  7519. if (ah->user != NULL) {
  7520. conn->request_info.remote_user =
  7521. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7522. } else {
  7523. return 0;
  7524. }
  7525. return 1;
  7526. }
  7527. static const char *
  7528. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7529. {
  7530. if (!filep) {
  7531. return NULL;
  7532. }
  7533. if (filep->access.fp != NULL) {
  7534. return fgets(buf, (int)size, filep->access.fp);
  7535. } else {
  7536. return NULL;
  7537. }
  7538. }
  7539. /* Define the initial recursion depth for procesesing htpasswd files that
  7540. * include other htpasswd
  7541. * (or even the same) files. It is not difficult to provide a file or files
  7542. * s.t. they force civetweb
  7543. * to infinitely recurse and then crash.
  7544. */
  7545. #define INITIAL_DEPTH 9
  7546. #if INITIAL_DEPTH <= 0
  7547. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7548. #endif
  7549. #if !defined(NO_FILESYSTEMS)
  7550. struct read_auth_file_struct {
  7551. struct mg_connection *conn;
  7552. struct ah ah;
  7553. const char *domain;
  7554. char buf[256 + 256 + 40];
  7555. const char *f_user;
  7556. const char *f_domain;
  7557. const char *f_ha1;
  7558. };
  7559. static int
  7560. read_auth_file(struct mg_file *filep,
  7561. struct read_auth_file_struct *workdata,
  7562. int depth)
  7563. {
  7564. int is_authorized = 0;
  7565. struct mg_file fp;
  7566. size_t l;
  7567. if (!filep || !workdata || (0 == depth)) {
  7568. return 0;
  7569. }
  7570. /* Loop over passwords file */
  7571. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7572. l = strlen(workdata->buf);
  7573. while (l > 0) {
  7574. if (isspace((unsigned char)workdata->buf[l - 1])
  7575. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7576. l--;
  7577. workdata->buf[l] = 0;
  7578. } else
  7579. break;
  7580. }
  7581. if (l < 1) {
  7582. continue;
  7583. }
  7584. workdata->f_user = workdata->buf;
  7585. if (workdata->f_user[0] == ':') {
  7586. /* user names may not contain a ':' and may not be empty,
  7587. * so lines starting with ':' may be used for a special purpose
  7588. */
  7589. if (workdata->f_user[1] == '#') {
  7590. /* :# is a comment */
  7591. continue;
  7592. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7593. if (mg_fopen(workdata->conn,
  7594. workdata->f_user + 9,
  7595. MG_FOPEN_MODE_READ,
  7596. &fp)) {
  7597. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7598. (void)mg_fclose(
  7599. &fp.access); /* ignore error on read only file */
  7600. /* No need to continue processing files once we have a
  7601. * match, since nothing will reset it back
  7602. * to 0.
  7603. */
  7604. if (is_authorized) {
  7605. return is_authorized;
  7606. }
  7607. } else {
  7608. mg_cry_internal(workdata->conn,
  7609. "%s: cannot open authorization file: %s",
  7610. __func__,
  7611. workdata->buf);
  7612. }
  7613. continue;
  7614. }
  7615. /* everything is invalid for the moment (might change in the
  7616. * future) */
  7617. mg_cry_internal(workdata->conn,
  7618. "%s: syntax error in authorization file: %s",
  7619. __func__,
  7620. workdata->buf);
  7621. continue;
  7622. }
  7623. workdata->f_domain = strchr(workdata->f_user, ':');
  7624. if (workdata->f_domain == NULL) {
  7625. mg_cry_internal(workdata->conn,
  7626. "%s: syntax error in authorization file: %s",
  7627. __func__,
  7628. workdata->buf);
  7629. continue;
  7630. }
  7631. *(char *)(workdata->f_domain) = 0;
  7632. (workdata->f_domain)++;
  7633. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7634. if (workdata->f_ha1 == NULL) {
  7635. mg_cry_internal(workdata->conn,
  7636. "%s: syntax error in authorization file: %s",
  7637. __func__,
  7638. workdata->buf);
  7639. continue;
  7640. }
  7641. *(char *)(workdata->f_ha1) = 0;
  7642. (workdata->f_ha1)++;
  7643. if (!strcmp(workdata->ah.user, workdata->f_user)
  7644. && !strcmp(workdata->domain, workdata->f_domain)) {
  7645. return check_password(workdata->conn->request_info.request_method,
  7646. workdata->f_ha1,
  7647. workdata->ah.uri,
  7648. workdata->ah.nonce,
  7649. workdata->ah.nc,
  7650. workdata->ah.cnonce,
  7651. workdata->ah.qop,
  7652. workdata->ah.response);
  7653. }
  7654. }
  7655. return is_authorized;
  7656. }
  7657. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7658. static int
  7659. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7660. {
  7661. struct read_auth_file_struct workdata;
  7662. char buf[MG_BUF_LEN];
  7663. if (!conn || !conn->dom_ctx) {
  7664. return 0;
  7665. }
  7666. memset(&workdata, 0, sizeof(workdata));
  7667. workdata.conn = conn;
  7668. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7669. return 0;
  7670. }
  7671. if (realm) {
  7672. workdata.domain = realm;
  7673. } else {
  7674. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7675. }
  7676. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7677. }
  7678. /* Public function to check http digest authentication header */
  7679. int
  7680. mg_check_digest_access_authentication(struct mg_connection *conn,
  7681. const char *realm,
  7682. const char *filename)
  7683. {
  7684. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7685. int auth;
  7686. if (!conn || !filename) {
  7687. return -1;
  7688. }
  7689. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7690. return -2;
  7691. }
  7692. auth = authorize(conn, &file, realm);
  7693. mg_fclose(&file.access);
  7694. return auth;
  7695. }
  7696. #endif /* NO_FILESYSTEMS */
  7697. /* Return 1 if request is authorised, 0 otherwise. */
  7698. static int
  7699. check_authorization(struct mg_connection *conn, const char *path)
  7700. {
  7701. #if !defined(NO_FILESYSTEMS)
  7702. char fname[PATH_MAX];
  7703. struct vec uri_vec, filename_vec;
  7704. const char *list;
  7705. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7706. int authorized = 1, truncated;
  7707. if (!conn || !conn->dom_ctx) {
  7708. return 0;
  7709. }
  7710. list = conn->dom_ctx->config[PROTECT_URI];
  7711. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7712. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7713. mg_snprintf(conn,
  7714. &truncated,
  7715. fname,
  7716. sizeof(fname),
  7717. "%.*s",
  7718. (int)filename_vec.len,
  7719. filename_vec.ptr);
  7720. if (truncated
  7721. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7722. mg_cry_internal(conn,
  7723. "%s: cannot open %s: %s",
  7724. __func__,
  7725. fname,
  7726. strerror(errno));
  7727. }
  7728. break;
  7729. }
  7730. }
  7731. if (!is_file_opened(&file.access)) {
  7732. open_auth_file(conn, path, &file);
  7733. }
  7734. if (is_file_opened(&file.access)) {
  7735. authorized = authorize(conn, &file, NULL);
  7736. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7737. }
  7738. return authorized;
  7739. #else
  7740. (void)conn;
  7741. (void)path;
  7742. return 1;
  7743. #endif /* NO_FILESYSTEMS */
  7744. }
  7745. /* Internal function. Assumes conn is valid */
  7746. static void
  7747. send_authorization_request(struct mg_connection *conn, const char *realm)
  7748. {
  7749. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7750. int trunc = 0;
  7751. char buf[128];
  7752. if (!realm) {
  7753. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7754. }
  7755. mg_lock_context(conn->phys_ctx);
  7756. nonce += conn->dom_ctx->nonce_count;
  7757. ++conn->dom_ctx->nonce_count;
  7758. mg_unlock_context(conn->phys_ctx);
  7759. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7760. conn->must_close = 1;
  7761. /* Create 401 response */
  7762. mg_response_start(conn, 401);
  7763. send_no_cache_header(conn);
  7764. send_additional_header(conn);
  7765. mg_response_add_header(conn, "Content-Length", "0", -1);
  7766. /* Content for "WWW-Authenticate" header */
  7767. mg_snprintf(conn,
  7768. &trunc,
  7769. buf,
  7770. sizeof(buf),
  7771. "Digest qop=\"auth\", realm=\"%s\", "
  7772. "nonce=\"%" UINT64_FMT "\"",
  7773. realm,
  7774. nonce);
  7775. if (!trunc) {
  7776. /* !trunc should always be true */
  7777. mg_response_add_header(conn, "WWW-Authenticate", buf, -1);
  7778. }
  7779. /* Send all headers */
  7780. mg_response_send_headers(conn);
  7781. }
  7782. /* Interface function. Parameters are provided by the user, so do
  7783. * at least some basic checks.
  7784. */
  7785. int
  7786. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7787. const char *realm)
  7788. {
  7789. if (conn && conn->dom_ctx) {
  7790. send_authorization_request(conn, realm);
  7791. return 0;
  7792. }
  7793. return -1;
  7794. }
  7795. #if !defined(NO_FILES)
  7796. static int
  7797. is_authorized_for_put(struct mg_connection *conn)
  7798. {
  7799. if (conn) {
  7800. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7801. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7802. int ret = 0;
  7803. if (passfile != NULL
  7804. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7805. ret = authorize(conn, &file, NULL);
  7806. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7807. }
  7808. return ret;
  7809. }
  7810. return 0;
  7811. }
  7812. #endif
  7813. int
  7814. mg_modify_passwords_file(const char *fname,
  7815. const char *domain,
  7816. const char *user,
  7817. const char *pass)
  7818. {
  7819. int found, i;
  7820. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7821. FILE *fp, *fp2;
  7822. found = 0;
  7823. fp = fp2 = NULL;
  7824. /* Regard empty password as no password - remove user record. */
  7825. if ((pass != NULL) && (pass[0] == '\0')) {
  7826. pass = NULL;
  7827. }
  7828. /* Other arguments must not be empty */
  7829. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7830. return 0;
  7831. }
  7832. /* Using the given file format, user name and domain must not contain
  7833. * ':'
  7834. */
  7835. if (strchr(user, ':') != NULL) {
  7836. return 0;
  7837. }
  7838. if (strchr(domain, ':') != NULL) {
  7839. return 0;
  7840. }
  7841. /* Do not allow control characters like newline in user name and domain.
  7842. * Do not allow excessively long names either. */
  7843. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7844. if (iscntrl((unsigned char)user[i])) {
  7845. return 0;
  7846. }
  7847. }
  7848. if (user[i]) {
  7849. return 0;
  7850. }
  7851. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7852. if (iscntrl((unsigned char)domain[i])) {
  7853. return 0;
  7854. }
  7855. }
  7856. if (domain[i]) {
  7857. return 0;
  7858. }
  7859. /* The maximum length of the path to the password file is limited */
  7860. if ((strlen(fname) + 4) >= PATH_MAX) {
  7861. return 0;
  7862. }
  7863. /* Create a temporary file name. Length has been checked before. */
  7864. strcpy(tmp, fname);
  7865. strcat(tmp, ".tmp");
  7866. /* Create the file if does not exist */
  7867. /* Use of fopen here is OK, since fname is only ASCII */
  7868. if ((fp = fopen(fname, "a+")) != NULL) {
  7869. (void)fclose(fp);
  7870. }
  7871. /* Open the given file and temporary file */
  7872. if ((fp = fopen(fname, "r")) == NULL) {
  7873. return 0;
  7874. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7875. fclose(fp);
  7876. return 0;
  7877. }
  7878. /* Copy the stuff to temporary file */
  7879. while (fgets(line, sizeof(line), fp) != NULL) {
  7880. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7881. continue;
  7882. }
  7883. u[255] = 0;
  7884. d[255] = 0;
  7885. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7886. found++;
  7887. if (pass != NULL) {
  7888. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7889. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7890. }
  7891. } else {
  7892. fprintf(fp2, "%s", line);
  7893. }
  7894. }
  7895. /* If new user, just add it */
  7896. if (!found && (pass != NULL)) {
  7897. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7898. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7899. }
  7900. /* Close files */
  7901. fclose(fp);
  7902. fclose(fp2);
  7903. /* Put the temp file in place of real file */
  7904. IGNORE_UNUSED_RESULT(remove(fname));
  7905. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7906. return 1;
  7907. }
  7908. static int
  7909. is_valid_port(unsigned long port)
  7910. {
  7911. return (port <= 0xffff);
  7912. }
  7913. static int
  7914. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7915. {
  7916. struct addrinfo hints, *res, *ressave;
  7917. int func_ret = 0;
  7918. int gai_ret;
  7919. memset(&hints, 0, sizeof(struct addrinfo));
  7920. hints.ai_family = af;
  7921. if (!resolve_src) {
  7922. hints.ai_flags = AI_NUMERICHOST;
  7923. }
  7924. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7925. if (gai_ret != 0) {
  7926. /* gai_strerror could be used to convert gai_ret to a string */
  7927. /* POSIX return values: see
  7928. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7929. */
  7930. /* Windows return values: see
  7931. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7932. */
  7933. return 0;
  7934. }
  7935. ressave = res;
  7936. while (res) {
  7937. if ((dstlen >= (size_t)res->ai_addrlen)
  7938. && (res->ai_addr->sa_family == af)) {
  7939. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7940. func_ret = 1;
  7941. }
  7942. res = res->ai_next;
  7943. }
  7944. freeaddrinfo(ressave);
  7945. return func_ret;
  7946. }
  7947. static int
  7948. connect_socket(struct mg_context *ctx /* may be NULL */,
  7949. const char *host,
  7950. int port,
  7951. int use_ssl,
  7952. char *ebuf,
  7953. size_t ebuf_len,
  7954. SOCKET *sock /* output: socket, must not be NULL */,
  7955. union usa *sa /* output: socket address, must not be NULL */
  7956. )
  7957. {
  7958. int ip_ver = 0;
  7959. int conn_ret = -1;
  7960. int sockerr = 0;
  7961. *sock = INVALID_SOCKET;
  7962. memset(sa, 0, sizeof(*sa));
  7963. if (ebuf_len > 0) {
  7964. *ebuf = 0;
  7965. }
  7966. if (host == NULL) {
  7967. mg_snprintf(NULL,
  7968. NULL, /* No truncation check for ebuf */
  7969. ebuf,
  7970. ebuf_len,
  7971. "%s",
  7972. "NULL host");
  7973. return 0;
  7974. }
  7975. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7976. mg_snprintf(NULL,
  7977. NULL, /* No truncation check for ebuf */
  7978. ebuf,
  7979. ebuf_len,
  7980. "%s",
  7981. "invalid port");
  7982. return 0;
  7983. }
  7984. #if !defined(NO_SSL)
  7985. #if !defined(NO_SSL_DL)
  7986. #if defined(OPENSSL_API_1_1)
  7987. if (use_ssl && (TLS_client_method == NULL)) {
  7988. mg_snprintf(NULL,
  7989. NULL, /* No truncation check for ebuf */
  7990. ebuf,
  7991. ebuf_len,
  7992. "%s",
  7993. "SSL is not initialized");
  7994. return 0;
  7995. }
  7996. #else
  7997. if (use_ssl && (SSLv23_client_method == NULL)) {
  7998. mg_snprintf(NULL,
  7999. NULL, /* No truncation check for ebuf */
  8000. ebuf,
  8001. ebuf_len,
  8002. "%s",
  8003. "SSL is not initialized");
  8004. return 0;
  8005. }
  8006. #endif /* OPENSSL_API_1_1 */
  8007. #else
  8008. (void)use_ssl;
  8009. #endif /* NO_SSL_DL */
  8010. #else
  8011. (void)use_ssl;
  8012. #endif /* !defined(NO_SSL) */
  8013. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8014. sa->sin.sin_port = htons((uint16_t)port);
  8015. ip_ver = 4;
  8016. #if defined(USE_IPV6)
  8017. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8018. sa->sin6.sin6_port = htons((uint16_t)port);
  8019. ip_ver = 6;
  8020. } else if (host[0] == '[') {
  8021. /* While getaddrinfo on Windows will work with [::1],
  8022. * getaddrinfo on Linux only works with ::1 (without []). */
  8023. size_t l = strlen(host + 1);
  8024. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8025. if (h) {
  8026. h[l - 1] = 0;
  8027. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8028. sa->sin6.sin6_port = htons((uint16_t)port);
  8029. ip_ver = 6;
  8030. }
  8031. mg_free(h);
  8032. }
  8033. #endif
  8034. }
  8035. if (ip_ver == 0) {
  8036. mg_snprintf(NULL,
  8037. NULL, /* No truncation check for ebuf */
  8038. ebuf,
  8039. ebuf_len,
  8040. "%s",
  8041. "host not found");
  8042. return 0;
  8043. }
  8044. if (ip_ver == 4) {
  8045. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8046. }
  8047. #if defined(USE_IPV6)
  8048. else if (ip_ver == 6) {
  8049. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8050. }
  8051. #endif
  8052. if (*sock == INVALID_SOCKET) {
  8053. mg_snprintf(NULL,
  8054. NULL, /* No truncation check for ebuf */
  8055. ebuf,
  8056. ebuf_len,
  8057. "socket(): %s",
  8058. strerror(ERRNO));
  8059. return 0;
  8060. }
  8061. if (0 != set_non_blocking_mode(*sock)) {
  8062. mg_snprintf(NULL,
  8063. NULL, /* No truncation check for ebuf */
  8064. ebuf,
  8065. ebuf_len,
  8066. "Cannot set socket to non-blocking: %s",
  8067. strerror(ERRNO));
  8068. closesocket(*sock);
  8069. *sock = INVALID_SOCKET;
  8070. return 0;
  8071. }
  8072. set_close_on_exec(*sock, NULL, ctx);
  8073. if (ip_ver == 4) {
  8074. /* connected with IPv4 */
  8075. conn_ret = connect(*sock,
  8076. (struct sockaddr *)((void *)&sa->sin),
  8077. sizeof(sa->sin));
  8078. }
  8079. #if defined(USE_IPV6)
  8080. else if (ip_ver == 6) {
  8081. /* connected with IPv6 */
  8082. conn_ret = connect(*sock,
  8083. (struct sockaddr *)((void *)&sa->sin6),
  8084. sizeof(sa->sin6));
  8085. }
  8086. #endif
  8087. if (conn_ret != 0) {
  8088. sockerr = ERRNO;
  8089. }
  8090. #if defined(_WIN32)
  8091. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8092. #else
  8093. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8094. #endif
  8095. /* Data for getsockopt */
  8096. void *psockerr = &sockerr;
  8097. int ret;
  8098. #if defined(_WIN32)
  8099. int len = (int)sizeof(sockerr);
  8100. #else
  8101. socklen_t len = (socklen_t)sizeof(sockerr);
  8102. #endif
  8103. /* Data for poll */
  8104. struct mg_pollfd pfd[1];
  8105. int pollres;
  8106. int ms_wait = 10000; /* 10 second timeout */
  8107. stop_flag_t nonstop;
  8108. STOP_FLAG_ASSIGN(&nonstop, 0);
  8109. /* For a non-blocking socket, the connect sequence is:
  8110. * 1) call connect (will not block)
  8111. * 2) wait until the socket is ready for writing (select or poll)
  8112. * 3) check connection state with getsockopt
  8113. */
  8114. pfd[0].fd = *sock;
  8115. pfd[0].events = POLLOUT;
  8116. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8117. if (pollres != 1) {
  8118. /* Not connected */
  8119. mg_snprintf(NULL,
  8120. NULL, /* No truncation check for ebuf */
  8121. ebuf,
  8122. ebuf_len,
  8123. "connect(%s:%d): timeout",
  8124. host,
  8125. port);
  8126. closesocket(*sock);
  8127. *sock = INVALID_SOCKET;
  8128. return 0;
  8129. }
  8130. #if defined(_WIN32)
  8131. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8132. #else
  8133. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8134. #endif
  8135. if ((ret == 0) && (sockerr == 0)) {
  8136. conn_ret = 0;
  8137. }
  8138. }
  8139. if (conn_ret != 0) {
  8140. /* Not connected */
  8141. mg_snprintf(NULL,
  8142. NULL, /* No truncation check for ebuf */
  8143. ebuf,
  8144. ebuf_len,
  8145. "connect(%s:%d): error %s",
  8146. host,
  8147. port,
  8148. strerror(sockerr));
  8149. closesocket(*sock);
  8150. *sock = INVALID_SOCKET;
  8151. return 0;
  8152. }
  8153. return 1;
  8154. }
  8155. int
  8156. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8157. {
  8158. static const char *dont_escape = "._-$,;~()";
  8159. static const char *hex = "0123456789abcdef";
  8160. char *pos = dst;
  8161. const char *end = dst + dst_len - 1;
  8162. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8163. if (isalnum((unsigned char)*src)
  8164. || (strchr(dont_escape, *src) != NULL)) {
  8165. *pos = *src;
  8166. } else if (pos + 2 < end) {
  8167. pos[0] = '%';
  8168. pos[1] = hex[(unsigned char)*src >> 4];
  8169. pos[2] = hex[(unsigned char)*src & 0xf];
  8170. pos += 2;
  8171. } else {
  8172. break;
  8173. }
  8174. }
  8175. *pos = '\0';
  8176. return (*src == '\0') ? (int)(pos - dst) : -1;
  8177. }
  8178. /* Return 0 on success, non-zero if an error occurs. */
  8179. static int
  8180. print_dir_entry(struct de *de)
  8181. {
  8182. size_t namesize, escsize, i;
  8183. char *href, *esc, *p;
  8184. char size[64], mod[64];
  8185. #if defined(REENTRANT_TIME)
  8186. struct tm _tm;
  8187. struct tm *tm = &_tm;
  8188. #else
  8189. struct tm *tm;
  8190. #endif
  8191. /* Estimate worst case size for encoding and escaping */
  8192. namesize = strlen(de->file_name) + 1;
  8193. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8194. href = (char *)mg_malloc(namesize * 3 + escsize);
  8195. if (href == NULL) {
  8196. return -1;
  8197. }
  8198. mg_url_encode(de->file_name, href, namesize * 3);
  8199. esc = NULL;
  8200. if (escsize > 0) {
  8201. /* HTML escaping needed */
  8202. esc = href + namesize * 3;
  8203. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8204. mg_strlcpy(p, de->file_name + i, 2);
  8205. if (*p == '&') {
  8206. strcpy(p, "&amp;");
  8207. } else if (*p == '<') {
  8208. strcpy(p, "&lt;");
  8209. } else if (*p == '>') {
  8210. strcpy(p, "&gt;");
  8211. }
  8212. }
  8213. }
  8214. if (de->file.is_directory) {
  8215. mg_snprintf(de->conn,
  8216. NULL, /* Buffer is big enough */
  8217. size,
  8218. sizeof(size),
  8219. "%s",
  8220. "[DIRECTORY]");
  8221. } else {
  8222. /* We use (signed) cast below because MSVC 6 compiler cannot
  8223. * convert unsigned __int64 to double. Sigh. */
  8224. if (de->file.size < 1024) {
  8225. mg_snprintf(de->conn,
  8226. NULL, /* Buffer is big enough */
  8227. size,
  8228. sizeof(size),
  8229. "%d",
  8230. (int)de->file.size);
  8231. } else if (de->file.size < 0x100000) {
  8232. mg_snprintf(de->conn,
  8233. NULL, /* Buffer is big enough */
  8234. size,
  8235. sizeof(size),
  8236. "%.1fk",
  8237. (double)de->file.size / 1024.0);
  8238. } else if (de->file.size < 0x40000000) {
  8239. mg_snprintf(de->conn,
  8240. NULL, /* Buffer is big enough */
  8241. size,
  8242. sizeof(size),
  8243. "%.1fM",
  8244. (double)de->file.size / 1048576);
  8245. } else {
  8246. mg_snprintf(de->conn,
  8247. NULL, /* Buffer is big enough */
  8248. size,
  8249. sizeof(size),
  8250. "%.1fG",
  8251. (double)de->file.size / 1073741824);
  8252. }
  8253. }
  8254. /* Note: mg_snprintf will not cause a buffer overflow above.
  8255. * So, string truncation checks are not required here. */
  8256. #if defined(REENTRANT_TIME)
  8257. localtime_r(&de->file.last_modified, tm);
  8258. #else
  8259. tm = localtime(&de->file.last_modified);
  8260. #endif
  8261. if (tm != NULL) {
  8262. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8263. } else {
  8264. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8265. mod[sizeof(mod) - 1] = '\0';
  8266. }
  8267. mg_printf(de->conn,
  8268. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8269. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8270. href,
  8271. de->file.is_directory ? "/" : "",
  8272. esc ? esc : de->file_name,
  8273. de->file.is_directory ? "/" : "",
  8274. mod,
  8275. size);
  8276. mg_free(href);
  8277. return 0;
  8278. }
  8279. /* This function is called from send_directory() and used for
  8280. * sorting directory entries by size, or name, or modification time.
  8281. * On windows, __cdecl specification is needed in case if project is built
  8282. * with __stdcall convention. qsort always requires __cdels callback. */
  8283. static int WINCDECL
  8284. compare_dir_entries(const void *p1, const void *p2)
  8285. {
  8286. if (p1 && p2) {
  8287. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8288. const char *query_string = a->conn->request_info.query_string;
  8289. int cmp_result = 0;
  8290. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8291. query_string = "n";
  8292. }
  8293. if (a->file.is_directory && !b->file.is_directory) {
  8294. return -1; /* Always put directories on top */
  8295. } else if (!a->file.is_directory && b->file.is_directory) {
  8296. return 1; /* Always put directories on top */
  8297. } else if (*query_string == 'n') {
  8298. cmp_result = strcmp(a->file_name, b->file_name);
  8299. } else if (*query_string == 's') {
  8300. cmp_result = (a->file.size == b->file.size)
  8301. ? 0
  8302. : ((a->file.size > b->file.size) ? 1 : -1);
  8303. } else if (*query_string == 'd') {
  8304. cmp_result =
  8305. (a->file.last_modified == b->file.last_modified)
  8306. ? 0
  8307. : ((a->file.last_modified > b->file.last_modified) ? 1
  8308. : -1);
  8309. }
  8310. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8311. }
  8312. return 0;
  8313. }
  8314. static int
  8315. must_hide_file(struct mg_connection *conn, const char *path)
  8316. {
  8317. if (conn && conn->dom_ctx) {
  8318. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8319. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8320. return (match_prefix_strlen(pw_pattern, path) > 0)
  8321. || (match_prefix_strlen(pattern, path) > 0);
  8322. }
  8323. return 0;
  8324. }
  8325. #if !defined(NO_FILESYSTEMS)
  8326. static int
  8327. scan_directory(struct mg_connection *conn,
  8328. const char *dir,
  8329. void *data,
  8330. int (*cb)(struct de *, void *))
  8331. {
  8332. char path[PATH_MAX];
  8333. struct dirent *dp;
  8334. DIR *dirp;
  8335. struct de de;
  8336. int truncated;
  8337. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8338. return 0;
  8339. } else {
  8340. de.conn = conn;
  8341. while ((dp = mg_readdir(dirp)) != NULL) {
  8342. /* Do not show current dir and hidden files */
  8343. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8344. || must_hide_file(conn, dp->d_name)) {
  8345. continue;
  8346. }
  8347. mg_snprintf(
  8348. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8349. /* If we don't memset stat structure to zero, mtime will have
  8350. * garbage and strftime() will segfault later on in
  8351. * print_dir_entry(). memset is required only if mg_stat()
  8352. * fails. For more details, see
  8353. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8354. memset(&de.file, 0, sizeof(de.file));
  8355. if (truncated) {
  8356. /* If the path is not complete, skip processing. */
  8357. continue;
  8358. }
  8359. if (!mg_stat(conn, path, &de.file)) {
  8360. mg_cry_internal(conn,
  8361. "%s: mg_stat(%s) failed: %s",
  8362. __func__,
  8363. path,
  8364. strerror(ERRNO));
  8365. }
  8366. de.file_name = dp->d_name;
  8367. if (cb(&de, data)) {
  8368. /* stopped */
  8369. break;
  8370. }
  8371. }
  8372. (void)mg_closedir(dirp);
  8373. }
  8374. return 1;
  8375. }
  8376. #endif /* NO_FILESYSTEMS */
  8377. #if !defined(NO_FILES)
  8378. static int
  8379. remove_directory(struct mg_connection *conn, const char *dir)
  8380. {
  8381. char path[PATH_MAX];
  8382. struct dirent *dp;
  8383. DIR *dirp;
  8384. struct de de;
  8385. int truncated;
  8386. int ok = 1;
  8387. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8388. return 0;
  8389. } else {
  8390. de.conn = conn;
  8391. while ((dp = mg_readdir(dirp)) != NULL) {
  8392. /* Do not show current dir (but show hidden files as they will
  8393. * also be removed) */
  8394. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8395. continue;
  8396. }
  8397. mg_snprintf(
  8398. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8399. /* If we don't memset stat structure to zero, mtime will have
  8400. * garbage and strftime() will segfault later on in
  8401. * print_dir_entry(). memset is required only if mg_stat()
  8402. * fails. For more details, see
  8403. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8404. memset(&de.file, 0, sizeof(de.file));
  8405. if (truncated) {
  8406. /* Do not delete anything shorter */
  8407. ok = 0;
  8408. continue;
  8409. }
  8410. if (!mg_stat(conn, path, &de.file)) {
  8411. mg_cry_internal(conn,
  8412. "%s: mg_stat(%s) failed: %s",
  8413. __func__,
  8414. path,
  8415. strerror(ERRNO));
  8416. ok = 0;
  8417. }
  8418. if (de.file.is_directory) {
  8419. if (remove_directory(conn, path) == 0) {
  8420. ok = 0;
  8421. }
  8422. } else {
  8423. /* This will fail file is the file is in memory */
  8424. if (mg_remove(conn, path) == 0) {
  8425. ok = 0;
  8426. }
  8427. }
  8428. }
  8429. (void)mg_closedir(dirp);
  8430. IGNORE_UNUSED_RESULT(rmdir(dir));
  8431. }
  8432. return ok;
  8433. }
  8434. #endif
  8435. struct dir_scan_data {
  8436. struct de *entries;
  8437. size_t num_entries;
  8438. size_t arr_size;
  8439. };
  8440. #if !defined(NO_FILESYSTEMS)
  8441. static int
  8442. dir_scan_callback(struct de *de, void *data)
  8443. {
  8444. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8445. struct de *entries = dsd->entries;
  8446. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8447. entries =
  8448. (struct de *)mg_realloc(entries,
  8449. dsd->arr_size * 2 * sizeof(entries[0]));
  8450. if (entries == NULL) {
  8451. /* stop scan */
  8452. return 1;
  8453. }
  8454. dsd->entries = entries;
  8455. dsd->arr_size *= 2;
  8456. }
  8457. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8458. if (entries[dsd->num_entries].file_name == NULL) {
  8459. /* stop scan */
  8460. return 1;
  8461. }
  8462. entries[dsd->num_entries].file = de->file;
  8463. entries[dsd->num_entries].conn = de->conn;
  8464. dsd->num_entries++;
  8465. return 0;
  8466. }
  8467. static void
  8468. handle_directory_request(struct mg_connection *conn, const char *dir)
  8469. {
  8470. size_t i;
  8471. int sort_direction;
  8472. struct dir_scan_data data = {NULL, 0, 128};
  8473. char date[64], *esc, *p;
  8474. const char *title;
  8475. time_t curtime = time(NULL);
  8476. if (!conn) {
  8477. return;
  8478. }
  8479. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8480. mg_send_http_error(conn,
  8481. 500,
  8482. "Error: Cannot open directory\nopendir(%s): %s",
  8483. dir,
  8484. strerror(ERRNO));
  8485. return;
  8486. }
  8487. gmt_time_string(date, sizeof(date), &curtime);
  8488. esc = NULL;
  8489. title = conn->request_info.local_uri;
  8490. if (title[strcspn(title, "&<>")]) {
  8491. /* HTML escaping needed */
  8492. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8493. if (esc) {
  8494. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8495. mg_strlcpy(p, title + i, 2);
  8496. if (*p == '&') {
  8497. strcpy(p, "&amp;");
  8498. } else if (*p == '<') {
  8499. strcpy(p, "&lt;");
  8500. } else if (*p == '>') {
  8501. strcpy(p, "&gt;");
  8502. }
  8503. }
  8504. } else {
  8505. title = "";
  8506. }
  8507. }
  8508. sort_direction = ((conn->request_info.query_string != NULL)
  8509. && (conn->request_info.query_string[0] != '\0')
  8510. && (conn->request_info.query_string[1] == 'd'))
  8511. ? 'a'
  8512. : 'd';
  8513. conn->must_close = 1;
  8514. /* Create 200 OK response */
  8515. mg_response_start(conn, 200);
  8516. send_static_cache_header(conn);
  8517. send_additional_header(conn);
  8518. mg_response_add_header(conn,
  8519. "Content-Type",
  8520. "text/html; charset=utf-8",
  8521. -1);
  8522. /* Send all headers */
  8523. mg_response_send_headers(conn);
  8524. /* Body */
  8525. mg_printf(conn,
  8526. "<html><head><title>Index of %s</title>"
  8527. "<style>th {text-align: left;}</style></head>"
  8528. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8529. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8530. "<th><a href=\"?d%c\">Modified</a></th>"
  8531. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8532. "<tr><td colspan=\"3\"><hr></td></tr>",
  8533. esc ? esc : title,
  8534. esc ? esc : title,
  8535. sort_direction,
  8536. sort_direction,
  8537. sort_direction);
  8538. mg_free(esc);
  8539. /* Print first entry - link to a parent directory */
  8540. mg_printf(conn,
  8541. "<tr><td><a href=\"%s\">%s</a></td>"
  8542. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8543. "..",
  8544. "Parent directory",
  8545. "-",
  8546. "-");
  8547. /* Sort and print directory entries */
  8548. if (data.entries != NULL) {
  8549. qsort(data.entries,
  8550. data.num_entries,
  8551. sizeof(data.entries[0]),
  8552. compare_dir_entries);
  8553. for (i = 0; i < data.num_entries; i++) {
  8554. print_dir_entry(&data.entries[i]);
  8555. mg_free(data.entries[i].file_name);
  8556. }
  8557. mg_free(data.entries);
  8558. }
  8559. mg_printf(conn, "%s", "</table></pre></body></html>");
  8560. conn->status_code = 200;
  8561. }
  8562. #endif /* NO_FILESYSTEMS */
  8563. /* Send len bytes from the opened file to the client. */
  8564. static void
  8565. send_file_data(struct mg_connection *conn,
  8566. struct mg_file *filep,
  8567. int64_t offset,
  8568. int64_t len)
  8569. {
  8570. char buf[MG_BUF_LEN];
  8571. int to_read, num_read, num_written;
  8572. int64_t size;
  8573. if (!filep || !conn) {
  8574. return;
  8575. }
  8576. /* Sanity check the offset */
  8577. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8578. : (int64_t)(filep->stat.size);
  8579. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8580. if (len > 0 && filep->access.fp != NULL) {
  8581. /* file stored on disk */
  8582. #if defined(__linux__)
  8583. /* sendfile is only available for Linux */
  8584. if ((conn->ssl == 0) && (conn->throttle == 0)
  8585. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8586. "yes"))) {
  8587. off_t sf_offs = (off_t)offset;
  8588. ssize_t sf_sent;
  8589. int sf_file = fileno(filep->access.fp);
  8590. int loop_cnt = 0;
  8591. do {
  8592. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8593. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8594. size_t sf_tosend =
  8595. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8596. sf_sent =
  8597. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8598. if (sf_sent > 0) {
  8599. len -= sf_sent;
  8600. offset += sf_sent;
  8601. } else if (loop_cnt == 0) {
  8602. /* This file can not be sent using sendfile.
  8603. * This might be the case for pseudo-files in the
  8604. * /sys/ and /proc/ file system.
  8605. * Use the regular user mode copy code instead. */
  8606. break;
  8607. } else if (sf_sent == 0) {
  8608. /* No error, but 0 bytes sent. May be EOF? */
  8609. return;
  8610. }
  8611. loop_cnt++;
  8612. } while ((len > 0) && (sf_sent >= 0));
  8613. if (sf_sent > 0) {
  8614. return; /* OK */
  8615. }
  8616. /* sf_sent<0 means error, thus fall back to the classic way */
  8617. /* This is always the case, if sf_file is not a "normal" file,
  8618. * e.g., for sending data from the output of a CGI process. */
  8619. offset = (int64_t)sf_offs;
  8620. }
  8621. #endif
  8622. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8623. mg_cry_internal(conn,
  8624. "%s: fseeko() failed: %s",
  8625. __func__,
  8626. strerror(ERRNO));
  8627. mg_send_http_error(
  8628. conn,
  8629. 500,
  8630. "%s",
  8631. "Error: Unable to access file at requested position.");
  8632. } else {
  8633. while (len > 0) {
  8634. /* Calculate how much to read from the file in the buffer */
  8635. to_read = sizeof(buf);
  8636. if ((int64_t)to_read > len) {
  8637. to_read = (int)len;
  8638. }
  8639. /* Read from file, exit the loop on error */
  8640. if ((num_read =
  8641. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8642. <= 0) {
  8643. break;
  8644. }
  8645. /* Send read bytes to the client, exit the loop on error */
  8646. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8647. != num_read) {
  8648. break;
  8649. }
  8650. /* Both read and were successful, adjust counters */
  8651. len -= num_written;
  8652. }
  8653. }
  8654. }
  8655. }
  8656. static int
  8657. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8658. {
  8659. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8660. }
  8661. static void
  8662. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8663. {
  8664. if ((filestat != NULL) && (buf != NULL)) {
  8665. mg_snprintf(NULL,
  8666. NULL, /* All calls to construct_etag use 64 byte buffer */
  8667. buf,
  8668. buf_len,
  8669. "\"%lx.%" INT64_FMT "\"",
  8670. (unsigned long)filestat->last_modified,
  8671. filestat->size);
  8672. }
  8673. }
  8674. static void
  8675. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8676. {
  8677. if (filep != NULL && filep->fp != NULL) {
  8678. #if defined(_WIN32)
  8679. (void)conn; /* Unused. */
  8680. #else
  8681. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8682. mg_cry_internal(conn,
  8683. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8684. __func__,
  8685. strerror(ERRNO));
  8686. }
  8687. #endif
  8688. }
  8689. }
  8690. #if defined(USE_ZLIB)
  8691. #include "mod_zlib.inl"
  8692. #endif
  8693. #if !defined(NO_FILESYSTEMS)
  8694. static void
  8695. handle_static_file_request(struct mg_connection *conn,
  8696. const char *path,
  8697. struct mg_file *filep,
  8698. const char *mime_type,
  8699. const char *additional_headers)
  8700. {
  8701. char lm[64], etag[64];
  8702. char range[128]; /* large enough, so there will be no overflow */
  8703. const char *range_hdr;
  8704. int64_t cl, r1, r2;
  8705. struct vec mime_vec;
  8706. int n, truncated;
  8707. char gz_path[PATH_MAX];
  8708. const char *encoding = 0;
  8709. const char *origin_hdr;
  8710. const char *cors_orig_cfg;
  8711. const char *cors1, *cors2;
  8712. int is_head_request;
  8713. #if defined(USE_ZLIB)
  8714. /* Compression is allowed, unless there is a reason not to use
  8715. * compression. If the file is already compressed, too small or a
  8716. * "range" request was made, on the fly compression is not possible. */
  8717. int allow_on_the_fly_compression = 1;
  8718. #endif
  8719. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8720. return;
  8721. }
  8722. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8723. if (mime_type == NULL) {
  8724. get_mime_type(conn, path, &mime_vec);
  8725. } else {
  8726. mime_vec.ptr = mime_type;
  8727. mime_vec.len = strlen(mime_type);
  8728. }
  8729. if (filep->stat.size > INT64_MAX) {
  8730. mg_send_http_error(conn,
  8731. 500,
  8732. "Error: File size is too large to send\n%" INT64_FMT,
  8733. filep->stat.size);
  8734. return;
  8735. }
  8736. cl = (int64_t)filep->stat.size;
  8737. conn->status_code = 200;
  8738. range[0] = '\0';
  8739. #if defined(USE_ZLIB)
  8740. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8741. * it's important to rewrite the filename after resolving
  8742. * the mime type from it, to preserve the actual file's type */
  8743. if (!conn->accept_gzip) {
  8744. allow_on_the_fly_compression = 0;
  8745. }
  8746. #endif
  8747. /* Check if there is a range header */
  8748. range_hdr = mg_get_header(conn, "Range");
  8749. /* For gzipped files, add *.gz */
  8750. if (filep->stat.is_gzipped) {
  8751. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8752. if (truncated) {
  8753. mg_send_http_error(conn,
  8754. 500,
  8755. "Error: Path of zipped file too long (%s)",
  8756. path);
  8757. return;
  8758. }
  8759. path = gz_path;
  8760. encoding = "gzip";
  8761. #if defined(USE_ZLIB)
  8762. /* File is already compressed. No "on the fly" compression. */
  8763. allow_on_the_fly_compression = 0;
  8764. #endif
  8765. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8766. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8767. struct mg_file_stat file_stat;
  8768. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8769. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8770. && !file_stat.is_directory) {
  8771. file_stat.is_gzipped = 1;
  8772. filep->stat = file_stat;
  8773. cl = (int64_t)filep->stat.size;
  8774. path = gz_path;
  8775. encoding = "gzip";
  8776. #if defined(USE_ZLIB)
  8777. /* File is already compressed. No "on the fly" compression. */
  8778. allow_on_the_fly_compression = 0;
  8779. #endif
  8780. }
  8781. }
  8782. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8783. mg_send_http_error(conn,
  8784. 500,
  8785. "Error: Cannot open file\nfopen(%s): %s",
  8786. path,
  8787. strerror(ERRNO));
  8788. return;
  8789. }
  8790. fclose_on_exec(&filep->access, conn);
  8791. /* If "Range" request was made: parse header, send only selected part
  8792. * of the file. */
  8793. r1 = r2 = 0;
  8794. if ((range_hdr != NULL)
  8795. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8796. && (r2 >= 0)) {
  8797. /* actually, range requests don't play well with a pre-gzipped
  8798. * file (since the range is specified in the uncompressed space) */
  8799. if (filep->stat.is_gzipped) {
  8800. mg_send_http_error(
  8801. conn,
  8802. 416, /* 416 = Range Not Satisfiable */
  8803. "%s",
  8804. "Error: Range requests in gzipped files are not supported");
  8805. (void)mg_fclose(
  8806. &filep->access); /* ignore error on read only file */
  8807. return;
  8808. }
  8809. conn->status_code = 206;
  8810. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8811. mg_snprintf(conn,
  8812. NULL, /* range buffer is big enough */
  8813. range,
  8814. sizeof(range),
  8815. "bytes "
  8816. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8817. r1,
  8818. r1 + cl - 1,
  8819. filep->stat.size);
  8820. #if defined(USE_ZLIB)
  8821. /* Do not compress ranges. */
  8822. allow_on_the_fly_compression = 0;
  8823. #endif
  8824. }
  8825. /* Do not compress small files. Small files do not benefit from file
  8826. * compression, but there is still some overhead. */
  8827. #if defined(USE_ZLIB)
  8828. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8829. /* File is below the size limit. */
  8830. allow_on_the_fly_compression = 0;
  8831. }
  8832. #endif
  8833. /* Standard CORS header */
  8834. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8835. origin_hdr = mg_get_header(conn, "Origin");
  8836. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8837. /* Cross-origin resource sharing (CORS), see
  8838. * http://www.html5rocks.com/en/tutorials/cors/,
  8839. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8840. * -
  8841. * preflight is not supported for files. */
  8842. cors1 = "Access-Control-Allow-Origin";
  8843. cors2 = cors_orig_cfg;
  8844. } else {
  8845. cors1 = cors2 = "";
  8846. }
  8847. /* Prepare Etag, and Last-Modified headers. */
  8848. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8849. construct_etag(etag, sizeof(etag), &filep->stat);
  8850. /* Create 2xx (200, 206) response */
  8851. mg_response_start(conn, conn->status_code);
  8852. send_static_cache_header(conn);
  8853. send_additional_header(conn);
  8854. mg_response_add_header(conn,
  8855. "Content-Type",
  8856. mime_vec.ptr,
  8857. (int)mime_vec.len);
  8858. if (cors1[0] != 0) {
  8859. mg_response_add_header(conn, cors1, cors2, -1);
  8860. }
  8861. mg_response_add_header(conn, "Last-Modified", lm, -1);
  8862. mg_response_add_header(conn, "Etag", etag, -1);
  8863. #if defined(USE_ZLIB)
  8864. /* On the fly compression allowed */
  8865. if (allow_on_the_fly_compression) {
  8866. /* For on the fly compression, we don't know the content size in
  8867. * advance, so we have to use chunked encoding */
  8868. encoding = "gzip";
  8869. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8870. /* HTTP/2 is always using "chunks" (frames) */
  8871. mg_response_add_header(conn, "Transfer-Encoding", "chunked", -1);
  8872. }
  8873. } else
  8874. #endif
  8875. {
  8876. /* Without on-the-fly compression, we know the content-length
  8877. * and we can use ranges (with on-the-fly compression we cannot).
  8878. * So we send these response headers only in this case. */
  8879. char len[32];
  8880. int trunc = 0;
  8881. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8882. if (!trunc) {
  8883. mg_response_add_header(conn, "Content-Length", len, -1);
  8884. }
  8885. mg_response_add_header(conn, "Accept-Ranges", "bytes", -1);
  8886. }
  8887. if (encoding) {
  8888. mg_response_add_header(conn, "Content-Encoding", encoding, -1);
  8889. }
  8890. if (range[0] != 0) {
  8891. mg_response_add_header(conn, "Content-Range", range, -1);
  8892. }
  8893. /* The code above does not add any header starting with X- to make
  8894. * sure no one of the additional_headers is included twice */
  8895. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8896. mg_response_add_headerlines(conn, additional_headers);
  8897. }
  8898. /* Send all headers */
  8899. mg_response_send_headers(conn);
  8900. if (!is_head_request) {
  8901. #if defined(USE_ZLIB)
  8902. if (allow_on_the_fly_compression) {
  8903. /* Compress and send */
  8904. send_compressed_data(conn, filep);
  8905. } else
  8906. #endif
  8907. {
  8908. /* Send file directly */
  8909. send_file_data(conn, filep, r1, cl);
  8910. }
  8911. }
  8912. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8913. }
  8914. int
  8915. mg_send_file_body(struct mg_connection *conn, const char *path)
  8916. {
  8917. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8918. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8919. return -1;
  8920. }
  8921. fclose_on_exec(&file.access, conn);
  8922. send_file_data(conn, &file, 0, INT64_MAX);
  8923. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8924. return 0; /* >= 0 for OK */
  8925. }
  8926. #endif /* NO_FILESYSTEMS */
  8927. #if !defined(NO_CACHING)
  8928. /* Return True if we should reply 304 Not Modified. */
  8929. static int
  8930. is_not_modified(const struct mg_connection *conn,
  8931. const struct mg_file_stat *filestat)
  8932. {
  8933. char etag[64];
  8934. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8935. const char *inm = mg_get_header(conn, "If-None-Match");
  8936. construct_etag(etag, sizeof(etag), filestat);
  8937. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8938. || ((ims != NULL)
  8939. && (filestat->last_modified <= parse_date_string(ims)));
  8940. }
  8941. static void
  8942. handle_not_modified_static_file_request(struct mg_connection *conn,
  8943. struct mg_file *filep)
  8944. {
  8945. char lm[64], etag[64];
  8946. if ((conn == NULL) || (filep == NULL)) {
  8947. return;
  8948. }
  8949. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8950. construct_etag(etag, sizeof(etag), &filep->stat);
  8951. /* Create 304 "not modified" response */
  8952. mg_response_start(conn, 304);
  8953. send_static_cache_header(conn);
  8954. send_additional_header(conn);
  8955. mg_response_add_header(conn, "Last-Modified", lm, -1);
  8956. mg_response_add_header(conn, "Etag", etag, -1);
  8957. /* Send all headers */
  8958. mg_response_send_headers(conn);
  8959. }
  8960. #endif
  8961. #if !defined(NO_FILESYSTEMS)
  8962. void
  8963. mg_send_file(struct mg_connection *conn, const char *path)
  8964. {
  8965. mg_send_mime_file2(conn, path, NULL, NULL);
  8966. }
  8967. void
  8968. mg_send_mime_file(struct mg_connection *conn,
  8969. const char *path,
  8970. const char *mime_type)
  8971. {
  8972. mg_send_mime_file2(conn, path, mime_type, NULL);
  8973. }
  8974. void
  8975. mg_send_mime_file2(struct mg_connection *conn,
  8976. const char *path,
  8977. const char *mime_type,
  8978. const char *additional_headers)
  8979. {
  8980. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8981. if (!conn) {
  8982. /* No conn */
  8983. return;
  8984. }
  8985. if (mg_stat(conn, path, &file.stat)) {
  8986. #if !defined(NO_CACHING)
  8987. if (is_not_modified(conn, &file.stat)) {
  8988. /* Send 304 "Not Modified" - this must not send any body data */
  8989. handle_not_modified_static_file_request(conn, &file);
  8990. } else
  8991. #endif /* NO_CACHING */
  8992. if (file.stat.is_directory) {
  8993. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8994. "yes")) {
  8995. handle_directory_request(conn, path);
  8996. } else {
  8997. mg_send_http_error(conn,
  8998. 403,
  8999. "%s",
  9000. "Error: Directory listing denied");
  9001. }
  9002. } else {
  9003. handle_static_file_request(
  9004. conn, path, &file, mime_type, additional_headers);
  9005. }
  9006. } else {
  9007. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9008. }
  9009. }
  9010. /* For a given PUT path, create all intermediate subdirectories.
  9011. * Return 0 if the path itself is a directory.
  9012. * Return 1 if the path leads to a file.
  9013. * Return -1 for if the path is too long.
  9014. * Return -2 if path can not be created.
  9015. */
  9016. static int
  9017. put_dir(struct mg_connection *conn, const char *path)
  9018. {
  9019. char buf[PATH_MAX];
  9020. const char *s, *p;
  9021. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9022. size_t len;
  9023. int res = 1;
  9024. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9025. len = (size_t)(p - path);
  9026. if (len >= sizeof(buf)) {
  9027. /* path too long */
  9028. res = -1;
  9029. break;
  9030. }
  9031. memcpy(buf, path, len);
  9032. buf[len] = '\0';
  9033. /* Try to create intermediate directory */
  9034. DEBUG_TRACE("mkdir(%s)", buf);
  9035. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9036. /* path does not exixt and can not be created */
  9037. res = -2;
  9038. break;
  9039. }
  9040. /* Is path itself a directory? */
  9041. if (p[1] == '\0') {
  9042. res = 0;
  9043. }
  9044. }
  9045. return res;
  9046. }
  9047. static void
  9048. remove_bad_file(const struct mg_connection *conn, const char *path)
  9049. {
  9050. int r = mg_remove(conn, path);
  9051. if (r != 0) {
  9052. mg_cry_internal(conn,
  9053. "%s: Cannot remove invalid file %s",
  9054. __func__,
  9055. path);
  9056. }
  9057. }
  9058. long long
  9059. mg_store_body(struct mg_connection *conn, const char *path)
  9060. {
  9061. char buf[MG_BUF_LEN];
  9062. long long len = 0;
  9063. int ret, n;
  9064. struct mg_file fi;
  9065. if (conn->consumed_content != 0) {
  9066. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9067. return -11;
  9068. }
  9069. ret = put_dir(conn, path);
  9070. if (ret < 0) {
  9071. /* -1 for path too long,
  9072. * -2 for path can not be created. */
  9073. return ret;
  9074. }
  9075. if (ret != 1) {
  9076. /* Return 0 means, path itself is a directory. */
  9077. return 0;
  9078. }
  9079. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9080. return -12;
  9081. }
  9082. ret = mg_read(conn, buf, sizeof(buf));
  9083. while (ret > 0) {
  9084. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9085. if (n != ret) {
  9086. (void)mg_fclose(
  9087. &fi.access); /* File is bad and will be removed anyway. */
  9088. remove_bad_file(conn, path);
  9089. return -13;
  9090. }
  9091. len += ret;
  9092. ret = mg_read(conn, buf, sizeof(buf));
  9093. }
  9094. /* File is open for writing. If fclose fails, there was probably an
  9095. * error flushing the buffer to disk, so the file on disk might be
  9096. * broken. Delete it and return an error to the caller. */
  9097. if (mg_fclose(&fi.access) != 0) {
  9098. remove_bad_file(conn, path);
  9099. return -14;
  9100. }
  9101. return len;
  9102. }
  9103. #endif /* NO_FILESYSTEMS */
  9104. /* Parse a buffer:
  9105. * Forward the string pointer till the end of a word, then
  9106. * terminate it and forward till the begin of the next word.
  9107. */
  9108. static int
  9109. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9110. {
  9111. /* Forward until a space is found - use isgraph here */
  9112. /* See http://www.cplusplus.com/reference/cctype/ */
  9113. while (isgraph((unsigned char)**ppw)) {
  9114. (*ppw)++;
  9115. }
  9116. /* Check end of word */
  9117. if (eol) {
  9118. /* must be a end of line */
  9119. if ((**ppw != '\r') && (**ppw != '\n')) {
  9120. return -1;
  9121. }
  9122. } else {
  9123. /* must be a end of a word, but not a line */
  9124. if (**ppw != ' ') {
  9125. return -1;
  9126. }
  9127. }
  9128. /* Terminate and forward to the next word */
  9129. do {
  9130. **ppw = 0;
  9131. (*ppw)++;
  9132. } while (isspace((unsigned char)**ppw));
  9133. /* Check after term */
  9134. if (!eol) {
  9135. /* if it's not the end of line, there must be a next word */
  9136. if (!isgraph((unsigned char)**ppw)) {
  9137. return -1;
  9138. }
  9139. }
  9140. /* ok */
  9141. return 1;
  9142. }
  9143. /* Parse HTTP headers from the given buffer, advance buf pointer
  9144. * to the point where parsing stopped.
  9145. * All parameters must be valid pointers (not NULL).
  9146. * Return <0 on error. */
  9147. static int
  9148. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9149. {
  9150. int i;
  9151. int num_headers = 0;
  9152. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9153. char *dp = *buf;
  9154. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9155. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9156. dp++;
  9157. }
  9158. if (dp == *buf) {
  9159. /* End of headers reached. */
  9160. break;
  9161. }
  9162. if (*dp != ':') {
  9163. /* This is not a valid field. */
  9164. return -1;
  9165. }
  9166. /* End of header key (*dp == ':') */
  9167. /* Truncate here and set the key name */
  9168. *dp = 0;
  9169. hdr[i].name = *buf;
  9170. /* Skip all spaces */
  9171. do {
  9172. dp++;
  9173. } while ((*dp == ' ') || (*dp == '\t'));
  9174. /* The rest of the line is the value */
  9175. hdr[i].value = dp;
  9176. /* Find end of line */
  9177. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9178. dp++;
  9179. };
  9180. /* eliminate \r */
  9181. if (*dp == '\r') {
  9182. *dp = 0;
  9183. dp++;
  9184. if (*dp != '\n') {
  9185. /* This is not a valid line. */
  9186. return -1;
  9187. }
  9188. }
  9189. /* here *dp is either 0 or '\n' */
  9190. /* in any case, we have a new header */
  9191. num_headers = i + 1;
  9192. if (*dp) {
  9193. *dp = 0;
  9194. dp++;
  9195. *buf = dp;
  9196. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9197. /* This is the end of the header */
  9198. break;
  9199. }
  9200. } else {
  9201. *buf = dp;
  9202. break;
  9203. }
  9204. }
  9205. return num_headers;
  9206. }
  9207. struct mg_http_method_info {
  9208. const char *name;
  9209. int request_has_body;
  9210. int response_has_body;
  9211. int is_safe;
  9212. int is_idempotent;
  9213. int is_cacheable;
  9214. };
  9215. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9216. static const struct mg_http_method_info http_methods[] = {
  9217. /* HTTP (RFC 2616) */
  9218. {"GET", 0, 1, 1, 1, 1},
  9219. {"POST", 1, 1, 0, 0, 0},
  9220. {"PUT", 1, 0, 0, 1, 0},
  9221. {"DELETE", 0, 0, 0, 1, 0},
  9222. {"HEAD", 0, 0, 1, 1, 1},
  9223. {"OPTIONS", 0, 0, 1, 1, 0},
  9224. {"CONNECT", 1, 1, 0, 0, 0},
  9225. /* TRACE method (RFC 2616) is not supported for security reasons */
  9226. /* PATCH method (RFC 5789) */
  9227. {"PATCH", 1, 0, 0, 0, 0},
  9228. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9229. /* WEBDAV (RFC 2518) */
  9230. {"PROPFIND", 0, 1, 1, 1, 0},
  9231. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9232. * Some PROPFIND results MAY be cached, with care,
  9233. * as there is no cache validation mechanism for
  9234. * most properties. This method is both safe and
  9235. * idempotent (see Section 9.1 of [RFC2616]). */
  9236. {"MKCOL", 0, 0, 0, 1, 0},
  9237. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9238. * When MKCOL is invoked without a request body,
  9239. * the newly created collection SHOULD have no
  9240. * members. A MKCOL request message may contain
  9241. * a message body. The precise behavior of a MKCOL
  9242. * request when the body is present is undefined,
  9243. * ... ==> We do not support MKCOL with body data.
  9244. * This method is idempotent, but not safe (see
  9245. * Section 9.1 of [RFC2616]). Responses to this
  9246. * method MUST NOT be cached. */
  9247. /* Unsupported WEBDAV Methods: */
  9248. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9249. /* + 11 methods from RFC 3253 */
  9250. /* ORDERPATCH (RFC 3648) */
  9251. /* ACL (RFC 3744) */
  9252. /* SEARCH (RFC 5323) */
  9253. /* + MicroSoft extensions
  9254. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9255. /* REPORT method (RFC 3253) */
  9256. {"REPORT", 1, 1, 1, 1, 1},
  9257. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9258. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9259. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9260. * to be useful for REST in case a "GET request with body" is
  9261. * required. */
  9262. {NULL, 0, 0, 0, 0, 0}
  9263. /* end of list */
  9264. };
  9265. static const struct mg_http_method_info *
  9266. get_http_method_info(const char *method)
  9267. {
  9268. /* Check if the method is known to the server. The list of all known
  9269. * HTTP methods can be found here at
  9270. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9271. */
  9272. const struct mg_http_method_info *m = http_methods;
  9273. while (m->name) {
  9274. if (!strcmp(m->name, method)) {
  9275. return m;
  9276. }
  9277. m++;
  9278. }
  9279. return NULL;
  9280. }
  9281. static int
  9282. is_valid_http_method(const char *method)
  9283. {
  9284. return (get_http_method_info(method) != NULL);
  9285. }
  9286. /* Parse HTTP request, fill in mg_request_info structure.
  9287. * This function modifies the buffer by NUL-terminating
  9288. * HTTP request components, header names and header values.
  9289. * Parameters:
  9290. * buf (in/out): pointer to the HTTP header to parse and split
  9291. * len (in): length of HTTP header buffer
  9292. * re (out): parsed header as mg_request_info
  9293. * buf and ri must be valid pointers (not NULL), len>0.
  9294. * Returns <0 on error. */
  9295. static int
  9296. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9297. {
  9298. int request_length;
  9299. int init_skip = 0;
  9300. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9301. * remote_port */
  9302. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9303. NULL;
  9304. ri->num_headers = 0;
  9305. /* RFC says that all initial whitespaces should be ingored */
  9306. /* This included all leading \r and \n (isspace) */
  9307. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9308. while ((len > 0) && isspace((unsigned char)*buf)) {
  9309. buf++;
  9310. len--;
  9311. init_skip++;
  9312. }
  9313. if (len == 0) {
  9314. /* Incomplete request */
  9315. return 0;
  9316. }
  9317. /* Control characters are not allowed, including zero */
  9318. if (iscntrl((unsigned char)*buf)) {
  9319. return -1;
  9320. }
  9321. /* Find end of HTTP header */
  9322. request_length = get_http_header_len(buf, len);
  9323. if (request_length <= 0) {
  9324. return request_length;
  9325. }
  9326. buf[request_length - 1] = '\0';
  9327. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9328. return -1;
  9329. }
  9330. /* The first word has to be the HTTP method */
  9331. ri->request_method = buf;
  9332. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9333. return -1;
  9334. }
  9335. /* Check for a valid http method */
  9336. if (!is_valid_http_method(ri->request_method)) {
  9337. return -1;
  9338. }
  9339. /* The second word is the URI */
  9340. ri->request_uri = buf;
  9341. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9342. return -1;
  9343. }
  9344. /* Next would be the HTTP version */
  9345. ri->http_version = buf;
  9346. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9347. return -1;
  9348. }
  9349. /* Check for a valid HTTP version key */
  9350. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9351. /* Invalid request */
  9352. return -1;
  9353. }
  9354. ri->http_version += 5;
  9355. /* Parse all HTTP headers */
  9356. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9357. if (ri->num_headers < 0) {
  9358. /* Error while parsing headers */
  9359. return -1;
  9360. }
  9361. return request_length + init_skip;
  9362. }
  9363. static int
  9364. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9365. {
  9366. int response_length;
  9367. int init_skip = 0;
  9368. char *tmp, *tmp2;
  9369. long l;
  9370. /* Initialize elements. */
  9371. ri->http_version = ri->status_text = NULL;
  9372. ri->num_headers = ri->status_code = 0;
  9373. /* RFC says that all initial whitespaces should be ingored */
  9374. /* This included all leading \r and \n (isspace) */
  9375. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9376. while ((len > 0) && isspace((unsigned char)*buf)) {
  9377. buf++;
  9378. len--;
  9379. init_skip++;
  9380. }
  9381. if (len == 0) {
  9382. /* Incomplete request */
  9383. return 0;
  9384. }
  9385. /* Control characters are not allowed, including zero */
  9386. if (iscntrl((unsigned char)*buf)) {
  9387. return -1;
  9388. }
  9389. /* Find end of HTTP header */
  9390. response_length = get_http_header_len(buf, len);
  9391. if (response_length <= 0) {
  9392. return response_length;
  9393. }
  9394. buf[response_length - 1] = '\0';
  9395. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9396. return -1;
  9397. }
  9398. /* The first word is the HTTP version */
  9399. /* Check for a valid HTTP version key */
  9400. if (strncmp(buf, "HTTP/", 5) != 0) {
  9401. /* Invalid request */
  9402. return -1;
  9403. }
  9404. buf += 5;
  9405. if (!isgraph((unsigned char)buf[0])) {
  9406. /* Invalid request */
  9407. return -1;
  9408. }
  9409. ri->http_version = buf;
  9410. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9411. return -1;
  9412. }
  9413. /* The second word is the status as a number */
  9414. tmp = buf;
  9415. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9416. return -1;
  9417. }
  9418. l = strtol(tmp, &tmp2, 10);
  9419. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9420. /* Everything else but a 3 digit code is invalid */
  9421. return -1;
  9422. }
  9423. ri->status_code = (int)l;
  9424. /* The rest of the line is the status text */
  9425. ri->status_text = buf;
  9426. /* Find end of status text */
  9427. /* isgraph or isspace = isprint */
  9428. while (isprint((unsigned char)*buf)) {
  9429. buf++;
  9430. }
  9431. if ((*buf != '\r') && (*buf != '\n')) {
  9432. return -1;
  9433. }
  9434. /* Terminate string and forward buf to next line */
  9435. do {
  9436. *buf = 0;
  9437. buf++;
  9438. } while (isspace((unsigned char)*buf));
  9439. /* Parse all HTTP headers */
  9440. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9441. if (ri->num_headers < 0) {
  9442. /* Error while parsing headers */
  9443. return -1;
  9444. }
  9445. return response_length + init_skip;
  9446. }
  9447. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9448. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9449. * buffer (which marks the end of HTTP request). Buffer buf may already
  9450. * have some data. The length of the data is stored in nread.
  9451. * Upon every read operation, increase nread by the number of bytes read. */
  9452. static int
  9453. read_message(FILE *fp,
  9454. struct mg_connection *conn,
  9455. char *buf,
  9456. int bufsiz,
  9457. int *nread)
  9458. {
  9459. int request_len, n = 0;
  9460. struct timespec last_action_time;
  9461. double request_timeout;
  9462. if (!conn) {
  9463. return 0;
  9464. }
  9465. memset(&last_action_time, 0, sizeof(last_action_time));
  9466. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9467. /* value of request_timeout is in seconds, config in milliseconds */
  9468. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9469. } else {
  9470. request_timeout =
  9471. atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  9472. }
  9473. if (conn->handled_requests > 0) {
  9474. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9475. request_timeout =
  9476. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9477. }
  9478. }
  9479. request_len = get_http_header_len(buf, *nread);
  9480. while (request_len == 0) {
  9481. /* Full request not yet received */
  9482. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9483. /* Server is to be stopped. */
  9484. return -1;
  9485. }
  9486. if (*nread >= bufsiz) {
  9487. /* Request too long */
  9488. return -2;
  9489. }
  9490. n = pull_inner(
  9491. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9492. if (n == -2) {
  9493. /* Receive error */
  9494. return -1;
  9495. }
  9496. /* update clock after every read request */
  9497. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9498. if (n > 0) {
  9499. *nread += n;
  9500. request_len = get_http_header_len(buf, *nread);
  9501. }
  9502. if ((request_len == 0) && (request_timeout >= 0)) {
  9503. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9504. > request_timeout) {
  9505. /* Timeout */
  9506. return -1;
  9507. }
  9508. }
  9509. }
  9510. return request_len;
  9511. }
  9512. #if !defined(NO_CGI) || !defined(NO_FILES)
  9513. static int
  9514. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9515. {
  9516. const char *expect;
  9517. char buf[MG_BUF_LEN];
  9518. int success = 0;
  9519. if (!conn) {
  9520. return 0;
  9521. }
  9522. expect = mg_get_header(conn, "Expect");
  9523. DEBUG_ASSERT(fp != NULL);
  9524. if (!fp) {
  9525. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9526. return 0;
  9527. }
  9528. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9529. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9530. */
  9531. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9532. } else {
  9533. if (expect != NULL) {
  9534. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9535. conn->status_code = 100;
  9536. } else {
  9537. conn->status_code = 200;
  9538. }
  9539. DEBUG_ASSERT(conn->consumed_content == 0);
  9540. if (conn->consumed_content != 0) {
  9541. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9542. return 0;
  9543. }
  9544. for (;;) {
  9545. int nread = mg_read(conn, buf, sizeof(buf));
  9546. if (nread <= 0) {
  9547. success = (nread == 0);
  9548. break;
  9549. }
  9550. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9551. break;
  9552. }
  9553. }
  9554. /* Each error code path in this function must send an error */
  9555. if (!success) {
  9556. /* NOTE: Maybe some data has already been sent. */
  9557. /* TODO (low): If some data has been sent, a correct error
  9558. * reply can no longer be sent, so just close the connection */
  9559. mg_send_http_error(conn, 500, "%s", "");
  9560. }
  9561. }
  9562. return success;
  9563. }
  9564. #endif
  9565. #if defined(USE_TIMERS)
  9566. #define TIMER_API static
  9567. #include "timer.inl"
  9568. #endif /* USE_TIMERS */
  9569. #if !defined(NO_CGI)
  9570. /* This structure helps to create an environment for the spawned CGI
  9571. * program.
  9572. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9573. * last element must be NULL.
  9574. * However, on Windows there is a requirement that all these
  9575. * VARIABLE=VALUE\0
  9576. * strings must reside in a contiguous buffer. The end of the buffer is
  9577. * marked by two '\0' characters.
  9578. * We satisfy both worlds: we create an envp array (which is vars), all
  9579. * entries are actually pointers inside buf. */
  9580. struct cgi_environment {
  9581. struct mg_connection *conn;
  9582. /* Data block */
  9583. char *buf; /* Environment buffer */
  9584. size_t buflen; /* Space available in buf */
  9585. size_t bufused; /* Space taken in buf */
  9586. /* Index block */
  9587. char **var; /* char **envp */
  9588. size_t varlen; /* Number of variables available in var */
  9589. size_t varused; /* Number of variables stored in var */
  9590. };
  9591. static void addenv(struct cgi_environment *env,
  9592. PRINTF_FORMAT_STRING(const char *fmt),
  9593. ...) PRINTF_ARGS(2, 3);
  9594. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9595. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9596. static void
  9597. addenv(struct cgi_environment *env, const char *fmt, ...)
  9598. {
  9599. size_t i, n, space;
  9600. int truncated = 0;
  9601. char *added;
  9602. va_list ap;
  9603. if ((env->varlen - env->varused) < 2) {
  9604. mg_cry_internal(env->conn,
  9605. "%s: Cannot register CGI variable [%s]",
  9606. __func__,
  9607. fmt);
  9608. return;
  9609. }
  9610. /* Calculate how much space is left in the buffer */
  9611. space = (env->buflen - env->bufused);
  9612. do {
  9613. /* Space for "\0\0" is always needed. */
  9614. if (space <= 2) {
  9615. /* Allocate new buffer */
  9616. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9617. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9618. if (!added) {
  9619. /* Out of memory */
  9620. mg_cry_internal(
  9621. env->conn,
  9622. "%s: Cannot allocate memory for CGI variable [%s]",
  9623. __func__,
  9624. fmt);
  9625. return;
  9626. }
  9627. /* Retarget pointers */
  9628. env->buf = added;
  9629. env->buflen = n;
  9630. for (i = 0, n = 0; i < env->varused; i++) {
  9631. env->var[i] = added + n;
  9632. n += strlen(added + n) + 1;
  9633. }
  9634. space = (env->buflen - env->bufused);
  9635. }
  9636. /* Make a pointer to the free space int the buffer */
  9637. added = env->buf + env->bufused;
  9638. /* Copy VARIABLE=VALUE\0 string into the free space */
  9639. va_start(ap, fmt);
  9640. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9641. va_end(ap);
  9642. /* Do not add truncated strings to the environment */
  9643. if (truncated) {
  9644. /* Reallocate the buffer */
  9645. space = 0;
  9646. }
  9647. } while (truncated);
  9648. /* Calculate number of bytes added to the environment */
  9649. n = strlen(added) + 1;
  9650. env->bufused += n;
  9651. /* Append a pointer to the added string into the envp array */
  9652. env->var[env->varused] = added;
  9653. env->varused++;
  9654. }
  9655. /* Return 0 on success, non-zero if an error occurs. */
  9656. static int
  9657. prepare_cgi_environment(struct mg_connection *conn,
  9658. const char *prog,
  9659. struct cgi_environment *env)
  9660. {
  9661. const char *s;
  9662. struct vec var_vec;
  9663. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9664. int i, truncated, uri_len;
  9665. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9666. return -1;
  9667. }
  9668. env->conn = conn;
  9669. env->buflen = CGI_ENVIRONMENT_SIZE;
  9670. env->bufused = 0;
  9671. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9672. if (env->buf == NULL) {
  9673. mg_cry_internal(conn,
  9674. "%s: Not enough memory for environmental buffer",
  9675. __func__);
  9676. return -1;
  9677. }
  9678. env->varlen = MAX_CGI_ENVIR_VARS;
  9679. env->varused = 0;
  9680. env->var =
  9681. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9682. if (env->var == NULL) {
  9683. mg_cry_internal(conn,
  9684. "%s: Not enough memory for environmental variables",
  9685. __func__);
  9686. mg_free(env->buf);
  9687. return -1;
  9688. }
  9689. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9690. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9691. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9692. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9693. /* Prepare the environment block */
  9694. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9695. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9696. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9697. addenv(env, "SERVER_PORT=%d", ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)));
  9698. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9699. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9700. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9701. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9702. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9703. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9704. /* SCRIPT_NAME */
  9705. uri_len = (int)strlen(conn->request_info.local_uri);
  9706. if (conn->path_info == NULL) {
  9707. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9708. /* URI: /path_to_script/script.cgi */
  9709. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9710. } else {
  9711. /* URI: /path_to_script/ ... using index.cgi */
  9712. const char *index_file = strrchr(prog, '/');
  9713. if (index_file) {
  9714. addenv(env,
  9715. "SCRIPT_NAME=%s%s",
  9716. conn->request_info.local_uri,
  9717. index_file + 1);
  9718. }
  9719. }
  9720. } else {
  9721. /* URI: /path_to_script/script.cgi/path_info */
  9722. addenv(env,
  9723. "SCRIPT_NAME=%.*s",
  9724. uri_len - (int)strlen(conn->path_info),
  9725. conn->request_info.local_uri);
  9726. }
  9727. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9728. if (conn->path_info == NULL) {
  9729. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9730. } else {
  9731. addenv(env,
  9732. "PATH_TRANSLATED=%s%s",
  9733. conn->dom_ctx->config[DOCUMENT_ROOT],
  9734. conn->path_info);
  9735. }
  9736. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9737. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9738. addenv(env, "CONTENT_TYPE=%s", s);
  9739. }
  9740. if (conn->request_info.query_string != NULL) {
  9741. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9742. }
  9743. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9744. addenv(env, "CONTENT_LENGTH=%s", s);
  9745. }
  9746. if ((s = getenv("PATH")) != NULL) {
  9747. addenv(env, "PATH=%s", s);
  9748. }
  9749. if (conn->path_info != NULL) {
  9750. addenv(env, "PATH_INFO=%s", conn->path_info);
  9751. }
  9752. if (conn->status_code > 0) {
  9753. /* CGI error handler should show the status code */
  9754. addenv(env, "STATUS=%d", conn->status_code);
  9755. }
  9756. #if defined(_WIN32)
  9757. if ((s = getenv("COMSPEC")) != NULL) {
  9758. addenv(env, "COMSPEC=%s", s);
  9759. }
  9760. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9761. addenv(env, "SYSTEMROOT=%s", s);
  9762. }
  9763. if ((s = getenv("SystemDrive")) != NULL) {
  9764. addenv(env, "SystemDrive=%s", s);
  9765. }
  9766. if ((s = getenv("ProgramFiles")) != NULL) {
  9767. addenv(env, "ProgramFiles=%s", s);
  9768. }
  9769. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9770. addenv(env, "ProgramFiles(x86)=%s", s);
  9771. }
  9772. #else
  9773. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9774. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9775. }
  9776. #endif /* _WIN32 */
  9777. if ((s = getenv("PERLLIB")) != NULL) {
  9778. addenv(env, "PERLLIB=%s", s);
  9779. }
  9780. if (conn->request_info.remote_user != NULL) {
  9781. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9782. addenv(env, "%s", "AUTH_TYPE=Digest");
  9783. }
  9784. /* Add all headers as HTTP_* variables */
  9785. for (i = 0; i < conn->request_info.num_headers; i++) {
  9786. (void)mg_snprintf(conn,
  9787. &truncated,
  9788. http_var_name,
  9789. sizeof(http_var_name),
  9790. "HTTP_%s",
  9791. conn->request_info.http_headers[i].name);
  9792. if (truncated) {
  9793. mg_cry_internal(conn,
  9794. "%s: HTTP header variable too long [%s]",
  9795. __func__,
  9796. conn->request_info.http_headers[i].name);
  9797. continue;
  9798. }
  9799. /* Convert variable name into uppercase, and change - to _ */
  9800. for (p = http_var_name; *p != '\0'; p++) {
  9801. if (*p == '-') {
  9802. *p = '_';
  9803. }
  9804. *p = (char)toupper((unsigned char)*p);
  9805. }
  9806. addenv(env,
  9807. "%s=%s",
  9808. http_var_name,
  9809. conn->request_info.http_headers[i].value);
  9810. }
  9811. /* Add user-specified variables */
  9812. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9813. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9814. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9815. }
  9816. env->var[env->varused] = NULL;
  9817. env->buf[env->bufused] = '\0';
  9818. return 0;
  9819. }
  9820. /* Data for CGI process control: PID and number of references */
  9821. struct process_control_data {
  9822. pid_t pid;
  9823. ptrdiff_t references;
  9824. };
  9825. static int
  9826. abort_cgi_process(void *data)
  9827. {
  9828. /* Waitpid checks for child status and won't work for a pid that does
  9829. * not identify a child of the current process. Thus, if the pid is
  9830. * reused, we will not affect a different process. */
  9831. struct process_control_data *proc = (struct process_control_data *)data;
  9832. int status = 0;
  9833. ptrdiff_t refs;
  9834. pid_t ret_pid;
  9835. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9836. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9837. /* Stop child process */
  9838. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9839. kill(proc->pid, SIGABRT);
  9840. /* Wait until process is terminated (don't leave zombies) */
  9841. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9842. ;
  9843. } else {
  9844. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9845. }
  9846. /* Dec reference counter */
  9847. refs = mg_atomic_dec(&proc->references);
  9848. if (refs == 0) {
  9849. /* no more references - free data */
  9850. mg_free(data);
  9851. }
  9852. return 0;
  9853. }
  9854. /* Local (static) function assumes all arguments are valid. */
  9855. static void
  9856. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9857. {
  9858. char *buf;
  9859. size_t buflen;
  9860. int headers_len, data_len, i, truncated;
  9861. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9862. const char *status, *status_text, *connection_state;
  9863. char *pbuf, dir[PATH_MAX], *p;
  9864. struct mg_request_info ri;
  9865. struct cgi_environment blk;
  9866. FILE *in = NULL, *out = NULL, *err = NULL;
  9867. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9868. pid_t pid = (pid_t)-1;
  9869. struct process_control_data *proc = NULL;
  9870. #if defined(USE_TIMERS)
  9871. double cgi_timeout;
  9872. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9873. /* Get timeout in seconds */
  9874. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9875. } else {
  9876. cgi_timeout =
  9877. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9878. }
  9879. #endif
  9880. buf = NULL;
  9881. buflen = conn->phys_ctx->max_request_size;
  9882. i = prepare_cgi_environment(conn, prog, &blk);
  9883. if (i != 0) {
  9884. blk.buf = NULL;
  9885. blk.var = NULL;
  9886. goto done;
  9887. }
  9888. /* CGI must be executed in its own directory. 'dir' must point to the
  9889. * directory containing executable program, 'p' must point to the
  9890. * executable program name relative to 'dir'. */
  9891. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9892. if (truncated) {
  9893. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9894. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9895. goto done;
  9896. }
  9897. if ((p = strrchr(dir, '/')) != NULL) {
  9898. *p++ = '\0';
  9899. } else {
  9900. dir[0] = '.';
  9901. dir[1] = '\0';
  9902. p = (char *)prog;
  9903. }
  9904. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9905. status = strerror(ERRNO);
  9906. mg_cry_internal(
  9907. conn,
  9908. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9909. prog,
  9910. status);
  9911. mg_send_http_error(conn,
  9912. 500,
  9913. "Error: Cannot create CGI pipe: %s",
  9914. status);
  9915. goto done;
  9916. }
  9917. proc = (struct process_control_data *)
  9918. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9919. if (proc == NULL) {
  9920. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9921. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9922. goto done;
  9923. }
  9924. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9925. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9926. if (pid == (pid_t)-1) {
  9927. status = strerror(ERRNO);
  9928. mg_cry_internal(
  9929. conn,
  9930. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9931. prog,
  9932. status);
  9933. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9934. mg_free(proc);
  9935. proc = NULL;
  9936. goto done;
  9937. }
  9938. /* Store data in shared process_control_data */
  9939. proc->pid = pid;
  9940. proc->references = 1;
  9941. #if defined(USE_TIMERS)
  9942. if (cgi_timeout > 0.0) {
  9943. proc->references = 2;
  9944. // Start a timer for CGI
  9945. timer_add(conn->phys_ctx,
  9946. cgi_timeout /* in seconds */,
  9947. 0.0,
  9948. 1,
  9949. abort_cgi_process,
  9950. (void *)proc,
  9951. NULL);
  9952. }
  9953. #endif
  9954. /* Parent closes only one side of the pipes.
  9955. * If we don't mark them as closed, close() attempt before
  9956. * return from this function throws an exception on Windows.
  9957. * Windows does not like when closed descriptor is closed again. */
  9958. (void)close(fdin[0]);
  9959. (void)close(fdout[1]);
  9960. (void)close(fderr[1]);
  9961. fdin[0] = fdout[1] = fderr[1] = -1;
  9962. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9963. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9964. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9965. status = strerror(ERRNO);
  9966. mg_cry_internal(conn,
  9967. "Error: CGI program \"%s\": Can not open fd: %s",
  9968. prog,
  9969. status);
  9970. mg_send_http_error(conn,
  9971. 500,
  9972. "Error: CGI can not open fd\nfdopen: %s",
  9973. status);
  9974. goto done;
  9975. }
  9976. setbuf(in, NULL);
  9977. setbuf(out, NULL);
  9978. setbuf(err, NULL);
  9979. fout.access.fp = out;
  9980. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9981. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9982. conn->content_len);
  9983. /* This is a POST/PUT request, or another request with body data. */
  9984. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9985. /* Error sending the body data */
  9986. mg_cry_internal(
  9987. conn,
  9988. "Error: CGI program \"%s\": Forward body data failed",
  9989. prog);
  9990. goto done;
  9991. }
  9992. }
  9993. /* Close so child gets an EOF. */
  9994. fclose(in);
  9995. in = NULL;
  9996. fdin[1] = -1;
  9997. /* Now read CGI reply into a buffer. We need to set correct
  9998. * status code, thus we need to see all HTTP headers first.
  9999. * Do not send anything back to client, until we buffer in all
  10000. * HTTP headers. */
  10001. data_len = 0;
  10002. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10003. if (buf == NULL) {
  10004. mg_send_http_error(conn,
  10005. 500,
  10006. "Error: Not enough memory for CGI buffer (%u bytes)",
  10007. (unsigned int)buflen);
  10008. mg_cry_internal(
  10009. conn,
  10010. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10011. "bytes)",
  10012. prog,
  10013. (unsigned int)buflen);
  10014. goto done;
  10015. }
  10016. DEBUG_TRACE("CGI: %s", "wait for response");
  10017. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10018. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10019. if (headers_len <= 0) {
  10020. /* Could not parse the CGI response. Check if some error message on
  10021. * stderr. */
  10022. i = pull_all(err, conn, buf, (int)buflen);
  10023. if (i > 0) {
  10024. /* CGI program explicitly sent an error */
  10025. /* Write the error message to the internal log */
  10026. mg_cry_internal(conn,
  10027. "Error: CGI program \"%s\" sent error "
  10028. "message: [%.*s]",
  10029. prog,
  10030. i,
  10031. buf);
  10032. /* Don't send the error message back to the client */
  10033. mg_send_http_error(conn,
  10034. 500,
  10035. "Error: CGI program \"%s\" failed.",
  10036. prog);
  10037. } else {
  10038. /* CGI program did not explicitly send an error, but a broken
  10039. * respon header */
  10040. mg_cry_internal(conn,
  10041. "Error: CGI program sent malformed or too big "
  10042. "(>%u bytes) HTTP headers: [%.*s]",
  10043. (unsigned)buflen,
  10044. data_len,
  10045. buf);
  10046. mg_send_http_error(conn,
  10047. 500,
  10048. "Error: CGI program sent malformed or too big "
  10049. "(>%u bytes) HTTP headers: [%.*s]",
  10050. (unsigned)buflen,
  10051. data_len,
  10052. buf);
  10053. }
  10054. /* in both cases, abort processing CGI */
  10055. goto done;
  10056. }
  10057. pbuf = buf;
  10058. buf[headers_len - 1] = '\0';
  10059. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10060. /* Make up and send the status line */
  10061. status_text = "OK";
  10062. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10063. != NULL) {
  10064. conn->status_code = atoi(status);
  10065. status_text = status;
  10066. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10067. status_text++;
  10068. }
  10069. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10070. != NULL) {
  10071. conn->status_code = 307;
  10072. } else {
  10073. conn->status_code = 200;
  10074. }
  10075. connection_state =
  10076. get_header(ri.http_headers, ri.num_headers, "Connection");
  10077. if (!header_has_option(connection_state, "keep-alive")) {
  10078. conn->must_close = 1;
  10079. }
  10080. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10081. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10082. /* Send headers */
  10083. for (i = 0; i < ri.num_headers; i++) {
  10084. DEBUG_TRACE("CGI header: %s: %s",
  10085. ri.http_headers[i].name,
  10086. ri.http_headers[i].value);
  10087. mg_printf(conn,
  10088. "%s: %s\r\n",
  10089. ri.http_headers[i].name,
  10090. ri.http_headers[i].value);
  10091. }
  10092. mg_write(conn, "\r\n", 2);
  10093. /* Send chunk of data that may have been read after the headers */
  10094. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10095. /* Read the rest of CGI output and send to the client */
  10096. DEBUG_TRACE("CGI: %s", "forward all data");
  10097. send_file_data(conn, &fout, 0, INT64_MAX);
  10098. DEBUG_TRACE("CGI: %s", "all data sent");
  10099. done:
  10100. mg_free(blk.var);
  10101. mg_free(blk.buf);
  10102. if (pid != (pid_t)-1) {
  10103. abort_cgi_process((void *)proc);
  10104. }
  10105. if (fdin[0] != -1) {
  10106. close(fdin[0]);
  10107. }
  10108. if (fdout[1] != -1) {
  10109. close(fdout[1]);
  10110. }
  10111. if (fderr[1] != -1) {
  10112. close(fderr[1]);
  10113. }
  10114. if (in != NULL) {
  10115. fclose(in);
  10116. } else if (fdin[1] != -1) {
  10117. close(fdin[1]);
  10118. }
  10119. if (out != NULL) {
  10120. fclose(out);
  10121. } else if (fdout[0] != -1) {
  10122. close(fdout[0]);
  10123. }
  10124. if (err != NULL) {
  10125. fclose(err);
  10126. } else if (fderr[0] != -1) {
  10127. close(fderr[0]);
  10128. }
  10129. mg_free(buf);
  10130. }
  10131. #endif /* !NO_CGI */
  10132. #if !defined(NO_FILES)
  10133. static void
  10134. mkcol(struct mg_connection *conn, const char *path)
  10135. {
  10136. int rc, body_len;
  10137. struct de de;
  10138. if (conn == NULL) {
  10139. return;
  10140. }
  10141. /* TODO (mid): Check the mg_send_http_error situations in this function
  10142. */
  10143. memset(&de.file, 0, sizeof(de.file));
  10144. if (!mg_stat(conn, path, &de.file)) {
  10145. mg_cry_internal(conn,
  10146. "%s: mg_stat(%s) failed: %s",
  10147. __func__,
  10148. path,
  10149. strerror(ERRNO));
  10150. }
  10151. if (de.file.last_modified) {
  10152. /* TODO (mid): This check does not seem to make any sense ! */
  10153. /* TODO (mid): Add a webdav unit test first, before changing
  10154. * anything here. */
  10155. mg_send_http_error(
  10156. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10157. return;
  10158. }
  10159. body_len = conn->data_len - conn->request_len;
  10160. if (body_len > 0) {
  10161. mg_send_http_error(
  10162. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10163. return;
  10164. }
  10165. rc = mg_mkdir(conn, path, 0755);
  10166. if (rc == 0) {
  10167. /* Create 201 "Created" response */
  10168. mg_response_start(conn, 201);
  10169. send_static_cache_header(conn);
  10170. send_additional_header(conn);
  10171. mg_response_add_header(conn, "Content-Length", "0", -1);
  10172. /* Send all headers - there is no body */
  10173. mg_response_send_headers(conn);
  10174. } else {
  10175. if (errno == EEXIST) {
  10176. mg_send_http_error(
  10177. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10178. } else if (errno == EACCES) {
  10179. mg_send_http_error(
  10180. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10181. } else if (errno == ENOENT) {
  10182. mg_send_http_error(
  10183. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10184. } else {
  10185. mg_send_http_error(
  10186. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10187. }
  10188. }
  10189. }
  10190. static void
  10191. put_file(struct mg_connection *conn, const char *path)
  10192. {
  10193. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10194. const char *range;
  10195. int64_t r1, r2;
  10196. int rc;
  10197. if (conn == NULL) {
  10198. return;
  10199. }
  10200. if (mg_stat(conn, path, &file.stat)) {
  10201. /* File already exists */
  10202. conn->status_code = 200;
  10203. if (file.stat.is_directory) {
  10204. /* This is an already existing directory,
  10205. * so there is nothing to do for the server. */
  10206. rc = 0;
  10207. } else {
  10208. /* File exists and is not a directory. */
  10209. /* Can it be replaced? */
  10210. /* Check if the server may write this file */
  10211. if (access(path, W_OK) == 0) {
  10212. /* Access granted */
  10213. rc = 1;
  10214. } else {
  10215. mg_send_http_error(
  10216. conn,
  10217. 403,
  10218. "Error: Put not possible\nReplacing %s is not allowed",
  10219. path);
  10220. return;
  10221. }
  10222. }
  10223. } else {
  10224. /* File should be created */
  10225. conn->status_code = 201;
  10226. rc = put_dir(conn, path);
  10227. }
  10228. if (rc == 0) {
  10229. /* put_dir returns 0 if path is a directory */
  10230. /* Create response */
  10231. mg_response_start(conn, conn->status_code);
  10232. send_no_cache_header(conn);
  10233. send_additional_header(conn);
  10234. mg_response_add_header(conn, "Content-Length", "0", -1);
  10235. /* Send all headers - there is no body */
  10236. mg_response_send_headers(conn);
  10237. /* Request to create a directory has been fulfilled successfully.
  10238. * No need to put a file. */
  10239. return;
  10240. }
  10241. if (rc == -1) {
  10242. /* put_dir returns -1 if the path is too long */
  10243. mg_send_http_error(conn,
  10244. 414,
  10245. "Error: Path too long\nput_dir(%s): %s",
  10246. path,
  10247. strerror(ERRNO));
  10248. return;
  10249. }
  10250. if (rc == -2) {
  10251. /* put_dir returns -2 if the directory can not be created */
  10252. mg_send_http_error(conn,
  10253. 500,
  10254. "Error: Can not create directory\nput_dir(%s): %s",
  10255. path,
  10256. strerror(ERRNO));
  10257. return;
  10258. }
  10259. /* A file should be created or overwritten. */
  10260. /* Currently CivetWeb does not nead read+write access. */
  10261. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10262. || file.access.fp == NULL) {
  10263. (void)mg_fclose(&file.access);
  10264. mg_send_http_error(conn,
  10265. 500,
  10266. "Error: Can not create file\nfopen(%s): %s",
  10267. path,
  10268. strerror(ERRNO));
  10269. return;
  10270. }
  10271. fclose_on_exec(&file.access, conn);
  10272. range = mg_get_header(conn, "Content-Range");
  10273. r1 = r2 = 0;
  10274. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10275. conn->status_code = 206; /* Partial content */
  10276. fseeko(file.access.fp, r1, SEEK_SET);
  10277. }
  10278. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10279. /* forward_body_data failed.
  10280. * The error code has already been sent to the client,
  10281. * and conn->status_code is already set. */
  10282. (void)mg_fclose(&file.access);
  10283. return;
  10284. }
  10285. if (mg_fclose(&file.access) != 0) {
  10286. /* fclose failed. This might have different reasons, but a likely
  10287. * one is "no space on disk", http 507. */
  10288. conn->status_code = 507;
  10289. }
  10290. /* Create response (status_code has been set before) */
  10291. mg_response_start(conn, conn->status_code);
  10292. send_no_cache_header(conn);
  10293. send_additional_header(conn);
  10294. mg_response_add_header(conn, "Content-Length", "0", -1);
  10295. /* Send all headers - there is no body */
  10296. mg_response_send_headers(conn);
  10297. }
  10298. static void
  10299. delete_file(struct mg_connection *conn, const char *path)
  10300. {
  10301. struct de de;
  10302. memset(&de.file, 0, sizeof(de.file));
  10303. if (!mg_stat(conn, path, &de.file)) {
  10304. /* mg_stat returns 0 if the file does not exist */
  10305. mg_send_http_error(conn,
  10306. 404,
  10307. "Error: Cannot delete file\nFile %s not found",
  10308. path);
  10309. return;
  10310. }
  10311. if (de.file.is_directory) {
  10312. if (remove_directory(conn, path)) {
  10313. /* Delete is successful: Return 204 without content. */
  10314. mg_send_http_error(conn, 204, "%s", "");
  10315. } else {
  10316. /* Delete is not successful: Return 500 (Server error). */
  10317. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10318. }
  10319. return;
  10320. }
  10321. /* This is an existing file (not a directory).
  10322. * Check if write permission is granted. */
  10323. if (access(path, W_OK) != 0) {
  10324. /* File is read only */
  10325. mg_send_http_error(
  10326. conn,
  10327. 403,
  10328. "Error: Delete not possible\nDeleting %s is not allowed",
  10329. path);
  10330. return;
  10331. }
  10332. /* Try to delete it. */
  10333. if (mg_remove(conn, path) == 0) {
  10334. /* Delete was successful: Return 204 without content. */
  10335. mg_response_start(conn, 204);
  10336. send_no_cache_header(conn);
  10337. send_additional_header(conn);
  10338. mg_response_add_header(conn, "Content-Length", "0", -1);
  10339. mg_response_send_headers(conn);
  10340. } else {
  10341. /* Delete not successful (file locked). */
  10342. mg_send_http_error(conn,
  10343. 423,
  10344. "Error: Cannot delete file\nremove(%s): %s",
  10345. path,
  10346. strerror(ERRNO));
  10347. }
  10348. }
  10349. #endif /* !NO_FILES */
  10350. #if !defined(NO_FILESYSTEMS)
  10351. static void
  10352. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10353. static void
  10354. do_ssi_include(struct mg_connection *conn,
  10355. const char *ssi,
  10356. char *tag,
  10357. int include_level)
  10358. {
  10359. char file_name[MG_BUF_LEN], path[512], *p;
  10360. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10361. size_t len;
  10362. int truncated = 0;
  10363. if (conn == NULL) {
  10364. return;
  10365. }
  10366. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10367. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10368. * always < MG_BUF_LEN. */
  10369. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10370. /* File name is relative to the webserver root */
  10371. file_name[511] = 0;
  10372. (void)mg_snprintf(conn,
  10373. &truncated,
  10374. path,
  10375. sizeof(path),
  10376. "%s/%s",
  10377. conn->dom_ctx->config[DOCUMENT_ROOT],
  10378. file_name);
  10379. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10380. /* File name is relative to the webserver working directory
  10381. * or it is absolute system path */
  10382. file_name[511] = 0;
  10383. (void)
  10384. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10385. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10386. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10387. /* File name is relative to the currect document */
  10388. file_name[511] = 0;
  10389. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10390. if (!truncated) {
  10391. if ((p = strrchr(path, '/')) != NULL) {
  10392. p[1] = '\0';
  10393. }
  10394. len = strlen(path);
  10395. (void)mg_snprintf(conn,
  10396. &truncated,
  10397. path + len,
  10398. sizeof(path) - len,
  10399. "%s",
  10400. file_name);
  10401. }
  10402. } else {
  10403. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10404. return;
  10405. }
  10406. if (truncated) {
  10407. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10408. return;
  10409. }
  10410. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10411. mg_cry_internal(conn,
  10412. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10413. tag,
  10414. path,
  10415. strerror(ERRNO));
  10416. } else {
  10417. fclose_on_exec(&file.access, conn);
  10418. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10419. > 0) {
  10420. send_ssi_file(conn, path, &file, include_level + 1);
  10421. } else {
  10422. send_file_data(conn, &file, 0, INT64_MAX);
  10423. }
  10424. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10425. }
  10426. }
  10427. #if !defined(NO_POPEN)
  10428. static void
  10429. do_ssi_exec(struct mg_connection *conn, char *tag)
  10430. {
  10431. char cmd[1024] = "";
  10432. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10433. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10434. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10435. } else {
  10436. cmd[1023] = 0;
  10437. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10438. mg_cry_internal(conn,
  10439. "Cannot SSI #exec: [%s]: %s",
  10440. cmd,
  10441. strerror(ERRNO));
  10442. } else {
  10443. send_file_data(conn, &file, 0, INT64_MAX);
  10444. pclose(file.access.fp);
  10445. }
  10446. }
  10447. }
  10448. #endif /* !NO_POPEN */
  10449. static int
  10450. mg_fgetc(struct mg_file *filep)
  10451. {
  10452. if (filep == NULL) {
  10453. return EOF;
  10454. }
  10455. if (filep->access.fp != NULL) {
  10456. return fgetc(filep->access.fp);
  10457. } else {
  10458. return EOF;
  10459. }
  10460. }
  10461. static void
  10462. send_ssi_file(struct mg_connection *conn,
  10463. const char *path,
  10464. struct mg_file *filep,
  10465. int include_level)
  10466. {
  10467. char buf[MG_BUF_LEN];
  10468. int ch, len, in_tag, in_ssi_tag;
  10469. if (include_level > 10) {
  10470. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10471. return;
  10472. }
  10473. in_tag = in_ssi_tag = len = 0;
  10474. /* Read file, byte by byte, and look for SSI include tags */
  10475. while ((ch = mg_fgetc(filep)) != EOF) {
  10476. if (in_tag) {
  10477. /* We are in a tag, either SSI tag or html tag */
  10478. if (ch == '>') {
  10479. /* Tag is closing */
  10480. buf[len++] = '>';
  10481. if (in_ssi_tag) {
  10482. /* Handle SSI tag */
  10483. buf[len] = 0;
  10484. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10485. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10486. #if !defined(NO_POPEN)
  10487. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10488. do_ssi_exec(conn, buf + 9);
  10489. #endif /* !NO_POPEN */
  10490. } else {
  10491. mg_cry_internal(conn,
  10492. "%s: unknown SSI "
  10493. "command: \"%s\"",
  10494. path,
  10495. buf);
  10496. }
  10497. len = 0;
  10498. in_ssi_tag = in_tag = 0;
  10499. } else {
  10500. /* Not an SSI tag */
  10501. /* Flush buffer */
  10502. (void)mg_write(conn, buf, (size_t)len);
  10503. len = 0;
  10504. in_tag = 0;
  10505. }
  10506. } else {
  10507. /* Tag is still open */
  10508. buf[len++] = (char)(ch & 0xff);
  10509. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10510. /* All SSI tags start with <!--# */
  10511. in_ssi_tag = 1;
  10512. }
  10513. if ((len + 2) > (int)sizeof(buf)) {
  10514. /* Tag to long for buffer */
  10515. mg_cry_internal(conn, "%s: tag is too large", path);
  10516. return;
  10517. }
  10518. }
  10519. } else {
  10520. /* We are not in a tag yet. */
  10521. if (ch == '<') {
  10522. /* Tag is opening */
  10523. in_tag = 1;
  10524. if (len > 0) {
  10525. /* Flush current buffer.
  10526. * Buffer is filled with "len" bytes. */
  10527. (void)mg_write(conn, buf, (size_t)len);
  10528. }
  10529. /* Store the < */
  10530. len = 1;
  10531. buf[0] = '<';
  10532. } else {
  10533. /* No Tag */
  10534. /* Add data to buffer */
  10535. buf[len++] = (char)(ch & 0xff);
  10536. /* Flush if buffer is full */
  10537. if (len == (int)sizeof(buf)) {
  10538. mg_write(conn, buf, (size_t)len);
  10539. len = 0;
  10540. }
  10541. }
  10542. }
  10543. }
  10544. /* Send the rest of buffered data */
  10545. if (len > 0) {
  10546. mg_write(conn, buf, (size_t)len);
  10547. }
  10548. }
  10549. static void
  10550. handle_ssi_file_request(struct mg_connection *conn,
  10551. const char *path,
  10552. struct mg_file *filep)
  10553. {
  10554. char date[64];
  10555. time_t curtime = time(NULL);
  10556. const char *cors_orig_cfg;
  10557. const char *cors1, *cors2;
  10558. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10559. return;
  10560. }
  10561. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10562. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10563. /* Cross-origin resource sharing (CORS). */
  10564. cors1 = "Access-Control-Allow-Origin";
  10565. cors2 = cors_orig_cfg;
  10566. } else {
  10567. cors1 = cors2 = "";
  10568. }
  10569. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10570. /* File exists (precondition for calling this function),
  10571. * but can not be opened by the server. */
  10572. mg_send_http_error(conn,
  10573. 500,
  10574. "Error: Cannot read file\nfopen(%s): %s",
  10575. path,
  10576. strerror(ERRNO));
  10577. } else {
  10578. /* Set "must_close" for HTTP/1.x, since we do not know the
  10579. * content length */
  10580. conn->must_close = 1;
  10581. gmt_time_string(date, sizeof(date), &curtime);
  10582. fclose_on_exec(&filep->access, conn);
  10583. /* 200 OK response */
  10584. mg_response_start(conn, 200);
  10585. send_no_cache_header(conn);
  10586. send_additional_header(conn);
  10587. mg_response_add_header(conn, "Content-Type", "text/html", -1);
  10588. if (cors1[0]) {
  10589. mg_response_add_header(conn, cors1, cors2, -1);
  10590. }
  10591. mg_response_send_headers(conn);
  10592. /* Header sent, now send body */
  10593. send_ssi_file(conn, path, filep, 0);
  10594. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10595. }
  10596. }
  10597. #endif /* NO_FILESYSTEMS */
  10598. #if !defined(NO_FILES)
  10599. static void
  10600. send_options(struct mg_connection *conn)
  10601. {
  10602. if (!conn) {
  10603. return;
  10604. }
  10605. /* We do not set a "Cache-Control" header here, but leave the default.
  10606. * Since browsers do not send an OPTIONS request, we can not test the
  10607. * effect anyway. */
  10608. mg_response_start(conn, 200);
  10609. mg_response_add_header(conn, "Content-Type", "text/html", -1);
  10610. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10611. /* Use the same as before */
  10612. mg_response_add_header(
  10613. conn,
  10614. "Allow",
  10615. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10616. -1);
  10617. mg_response_add_header(conn, "DAV", "1", -1);
  10618. } else {
  10619. /* TODO: Check this later for HTTP/2 */
  10620. mg_response_add_header(conn, "Allow", "GET, POST", -1);
  10621. }
  10622. send_additional_header(conn);
  10623. mg_response_send_headers(conn);
  10624. }
  10625. /* Writes PROPFIND properties for a collection element */
  10626. static int
  10627. print_props(struct mg_connection *conn,
  10628. const char *uri,
  10629. const char *name,
  10630. struct mg_file_stat *filep)
  10631. {
  10632. size_t href_size, i, j;
  10633. int len;
  10634. char *href, mtime[64];
  10635. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10636. return 0;
  10637. }
  10638. /* Estimate worst case size for encoding */
  10639. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10640. href = (char *)mg_malloc(href_size);
  10641. if (href == NULL) {
  10642. return 0;
  10643. }
  10644. len = mg_url_encode(uri, href, href_size);
  10645. if (len >= 0) {
  10646. /* Append an extra string */
  10647. mg_url_encode(name, href + len, href_size - (size_t)len);
  10648. }
  10649. /* Directory separator should be preserved. */
  10650. for (i = j = 0; href[i]; j++) {
  10651. if (!strncmp(href + i, "%2f", 3)) {
  10652. href[j] = '/';
  10653. i += 3;
  10654. } else {
  10655. href[j] = href[i++];
  10656. }
  10657. }
  10658. href[j] = '\0';
  10659. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10660. mg_printf(conn,
  10661. "<d:response>"
  10662. "<d:href>%s</d:href>"
  10663. "<d:propstat>"
  10664. "<d:prop>"
  10665. "<d:resourcetype>%s</d:resourcetype>"
  10666. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10667. "<d:getlastmodified>%s</d:getlastmodified>"
  10668. "</d:prop>"
  10669. "<d:status>HTTP/1.1 200 OK</d:status>"
  10670. "</d:propstat>"
  10671. "</d:response>\n",
  10672. href,
  10673. filep->is_directory ? "<d:collection/>" : "",
  10674. filep->size,
  10675. mtime);
  10676. mg_free(href);
  10677. return 1;
  10678. }
  10679. static int
  10680. print_dav_dir_entry(struct de *de, void *data)
  10681. {
  10682. struct mg_connection *conn = (struct mg_connection *)data;
  10683. if (!de || !conn
  10684. || !print_props(
  10685. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10686. /* stop scan */
  10687. return 1;
  10688. }
  10689. return 0;
  10690. }
  10691. static void
  10692. handle_propfind(struct mg_connection *conn,
  10693. const char *path,
  10694. struct mg_file_stat *filep)
  10695. {
  10696. const char *depth = mg_get_header(conn, "Depth");
  10697. char date[64];
  10698. time_t curtime = time(NULL);
  10699. gmt_time_string(date, sizeof(date), &curtime);
  10700. if (!conn || !path || !filep || !conn->dom_ctx) {
  10701. return;
  10702. }
  10703. conn->must_close = 1;
  10704. /* return 207 "Multi-Status" */
  10705. mg_response_start(conn, 207);
  10706. send_static_cache_header(conn);
  10707. send_additional_header(conn);
  10708. mg_response_add_header(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10709. mg_response_send_headers(conn);
  10710. /* Content */
  10711. mg_printf(conn,
  10712. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10713. "<d:multistatus xmlns:d='DAV:'>\n");
  10714. /* Print properties for the requested resource itself */
  10715. print_props(conn, conn->request_info.local_uri, "", filep);
  10716. /* If it is a directory, print directory entries too if Depth is not 0
  10717. */
  10718. if (filep->is_directory
  10719. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10720. "yes")
  10721. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10722. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10723. }
  10724. mg_printf(conn, "%s\n", "</d:multistatus>");
  10725. }
  10726. #endif
  10727. void
  10728. mg_lock_connection(struct mg_connection *conn)
  10729. {
  10730. if (conn) {
  10731. (void)pthread_mutex_lock(&conn->mutex);
  10732. }
  10733. }
  10734. void
  10735. mg_unlock_connection(struct mg_connection *conn)
  10736. {
  10737. if (conn) {
  10738. (void)pthread_mutex_unlock(&conn->mutex);
  10739. }
  10740. }
  10741. void
  10742. mg_lock_context(struct mg_context *ctx)
  10743. {
  10744. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10745. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10746. }
  10747. }
  10748. void
  10749. mg_unlock_context(struct mg_context *ctx)
  10750. {
  10751. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10752. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10753. }
  10754. }
  10755. #if defined(USE_LUA)
  10756. #include "mod_lua.inl"
  10757. #endif /* USE_LUA */
  10758. #if defined(USE_DUKTAPE)
  10759. #include "mod_duktape.inl"
  10760. #endif /* USE_DUKTAPE */
  10761. #if defined(USE_WEBSOCKET)
  10762. #if !defined(NO_SSL_DL)
  10763. #define SHA_API static
  10764. #include "sha1.inl"
  10765. #endif
  10766. static int
  10767. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10768. {
  10769. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10770. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10771. SHA_CTX sha_ctx;
  10772. int truncated;
  10773. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10774. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10775. if (truncated) {
  10776. conn->must_close = 1;
  10777. return 0;
  10778. }
  10779. DEBUG_TRACE("%s", "Send websocket handshake");
  10780. SHA1_Init(&sha_ctx);
  10781. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10782. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10783. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10784. mg_printf(conn,
  10785. "HTTP/1.1 101 Switching Protocols\r\n"
  10786. "Upgrade: websocket\r\n"
  10787. "Connection: Upgrade\r\n"
  10788. "Sec-WebSocket-Accept: %s\r\n",
  10789. b64_sha);
  10790. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10791. mg_printf(conn,
  10792. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10793. conn->request_info.acceptedWebSocketSubprotocol);
  10794. } else {
  10795. mg_printf(conn, "%s", "\r\n");
  10796. }
  10797. return 1;
  10798. }
  10799. #if !defined(MG_MAX_UNANSWERED_PING)
  10800. /* Configuration of the maximum number of websocket PINGs that might
  10801. * stay unanswered before the connection is considered broken.
  10802. * Note: The name of this define may still change (until it is
  10803. * defined as a compile parameter in a documentation).
  10804. */
  10805. #define MG_MAX_UNANSWERED_PING (5)
  10806. #endif
  10807. static void
  10808. read_websocket(struct mg_connection *conn,
  10809. mg_websocket_data_handler ws_data_handler,
  10810. void *callback_data)
  10811. {
  10812. /* Pointer to the beginning of the portion of the incoming websocket
  10813. * message queue.
  10814. * The original websocket upgrade request is never removed, so the queue
  10815. * begins after it. */
  10816. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10817. int n, error, exit_by_callback;
  10818. int ret;
  10819. /* body_len is the length of the entire queue in bytes
  10820. * len is the length of the current message
  10821. * data_len is the length of the current message's data payload
  10822. * header_len is the length of the current message's header */
  10823. size_t i, len, mask_len = 0, header_len, body_len;
  10824. uint64_t data_len = 0;
  10825. /* "The masking key is a 32-bit value chosen at random by the client."
  10826. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10827. */
  10828. unsigned char mask[4];
  10829. /* data points to the place where the message is stored when passed to
  10830. * the websocket_data callback. This is either mem on the stack, or a
  10831. * dynamically allocated buffer if it is too large. */
  10832. unsigned char mem[4096];
  10833. unsigned char mop; /* mask flag and opcode */
  10834. /* Variables used for connection monitoring */
  10835. double timeout = -1.0;
  10836. int enable_ping_pong = 0;
  10837. int ping_count = 0;
  10838. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10839. enable_ping_pong =
  10840. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10841. "yes");
  10842. }
  10843. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10844. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10845. }
  10846. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10847. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10848. }
  10849. if (timeout <= 0.0) {
  10850. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  10851. }
  10852. /* Enter data processing loop */
  10853. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10854. conn->request_info.remote_addr,
  10855. conn->request_info.remote_port);
  10856. conn->in_websocket_handling = 1;
  10857. mg_set_thread_name("wsock");
  10858. /* Loop continuously, reading messages from the socket, invoking the
  10859. * callback, and waiting repeatedly until an error occurs. */
  10860. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10861. && (!conn->must_close)) {
  10862. header_len = 0;
  10863. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10864. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10865. len = buf[1] & 127;
  10866. mask_len = (buf[1] & 128) ? 4 : 0;
  10867. if ((len < 126) && (body_len >= mask_len)) {
  10868. /* inline 7-bit length field */
  10869. data_len = len;
  10870. header_len = 2 + mask_len;
  10871. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10872. /* 16-bit length field */
  10873. header_len = 4 + mask_len;
  10874. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10875. } else if (body_len >= (10 + mask_len)) {
  10876. /* 64-bit length field */
  10877. uint32_t l1, l2;
  10878. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10879. memcpy(&l2, &buf[6], 4);
  10880. header_len = 10 + mask_len;
  10881. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10882. if (data_len > (uint64_t)0x7FFF0000ul) {
  10883. /* no can do */
  10884. mg_cry_internal(
  10885. conn,
  10886. "%s",
  10887. "websocket out of memory; closing connection");
  10888. break;
  10889. }
  10890. }
  10891. }
  10892. if ((header_len > 0) && (body_len >= header_len)) {
  10893. /* Allocate space to hold websocket payload */
  10894. unsigned char *data = mem;
  10895. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10896. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10897. conn->phys_ctx);
  10898. if (data == NULL) {
  10899. /* Allocation failed, exit the loop and then close the
  10900. * connection */
  10901. mg_cry_internal(
  10902. conn,
  10903. "%s",
  10904. "websocket out of memory; closing connection");
  10905. break;
  10906. }
  10907. }
  10908. /* Copy the mask before we shift the queue and destroy it */
  10909. if (mask_len > 0) {
  10910. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10911. } else {
  10912. memset(mask, 0, sizeof(mask));
  10913. }
  10914. /* Read frame payload from the first message in the queue into
  10915. * data and advance the queue by moving the memory in place. */
  10916. DEBUG_ASSERT(body_len >= header_len);
  10917. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10918. mop = buf[0]; /* current mask and opcode */
  10919. /* Overflow case */
  10920. len = body_len - header_len;
  10921. memcpy(data, buf + header_len, len);
  10922. error = 0;
  10923. while ((uint64_t)len < data_len) {
  10924. n = pull_inner(NULL,
  10925. conn,
  10926. (char *)(data + len),
  10927. (int)(data_len - len),
  10928. timeout);
  10929. if (n <= -2) {
  10930. error = 1;
  10931. break;
  10932. } else if (n > 0) {
  10933. len += (size_t)n;
  10934. } else {
  10935. /* Timeout: should retry */
  10936. /* TODO: retry condition */
  10937. }
  10938. }
  10939. if (error) {
  10940. mg_cry_internal(
  10941. conn,
  10942. "%s",
  10943. "Websocket pull failed; closing connection");
  10944. if (data != mem) {
  10945. mg_free(data);
  10946. }
  10947. break;
  10948. }
  10949. conn->data_len = conn->request_len;
  10950. } else {
  10951. mop = buf[0]; /* current mask and opcode, overwritten by
  10952. * memmove() */
  10953. /* Length of the message being read at the front of the
  10954. * queue. Cast to 31 bit is OK, since we limited
  10955. * data_len before. */
  10956. len = (size_t)data_len + header_len;
  10957. /* Copy the data payload into the data pointer for the
  10958. * callback. Cast to 31 bit is OK, since we
  10959. * limited data_len */
  10960. memcpy(data, buf + header_len, (size_t)data_len);
  10961. /* Move the queue forward len bytes */
  10962. memmove(buf, buf + len, body_len - len);
  10963. /* Mark the queue as advanced */
  10964. conn->data_len -= (int)len;
  10965. }
  10966. /* Apply mask if necessary */
  10967. if (mask_len > 0) {
  10968. for (i = 0; i < (size_t)data_len; i++) {
  10969. data[i] ^= mask[i & 3];
  10970. }
  10971. }
  10972. exit_by_callback = 0;
  10973. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10974. /* filter PONG messages */
  10975. DEBUG_TRACE("PONG from %s:%u",
  10976. conn->request_info.remote_addr,
  10977. conn->request_info.remote_port);
  10978. /* No unanwered PINGs left */
  10979. ping_count = 0;
  10980. } else if (enable_ping_pong
  10981. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10982. /* reply PING messages */
  10983. DEBUG_TRACE("Reply PING from %s:%u",
  10984. conn->request_info.remote_addr,
  10985. conn->request_info.remote_port);
  10986. ret = mg_websocket_write(conn,
  10987. MG_WEBSOCKET_OPCODE_PONG,
  10988. (char *)data,
  10989. (size_t)data_len);
  10990. if (ret <= 0) {
  10991. /* Error: send failed */
  10992. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10993. break;
  10994. }
  10995. } else {
  10996. /* Exit the loop if callback signals to exit (server side),
  10997. * or "connection close" opcode received (client side). */
  10998. if ((ws_data_handler != NULL)
  10999. && !ws_data_handler(conn,
  11000. mop,
  11001. (char *)data,
  11002. (size_t)data_len,
  11003. callback_data)) {
  11004. exit_by_callback = 1;
  11005. }
  11006. }
  11007. /* It a buffer has been allocated, free it again */
  11008. if (data != mem) {
  11009. mg_free(data);
  11010. }
  11011. if (exit_by_callback) {
  11012. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11013. conn->request_info.remote_addr,
  11014. conn->request_info.remote_port);
  11015. break;
  11016. }
  11017. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11018. /* Opcode == 8, connection close */
  11019. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11020. conn->request_info.remote_addr,
  11021. conn->request_info.remote_port);
  11022. break;
  11023. }
  11024. /* Not breaking the loop, process next websocket frame. */
  11025. } else {
  11026. /* Read from the socket into the next available location in the
  11027. * message queue. */
  11028. n = pull_inner(NULL,
  11029. conn,
  11030. conn->buf + conn->data_len,
  11031. conn->buf_size - conn->data_len,
  11032. timeout);
  11033. if (n <= -2) {
  11034. /* Error, no bytes read */
  11035. DEBUG_TRACE("PULL from %s:%u failed",
  11036. conn->request_info.remote_addr,
  11037. conn->request_info.remote_port);
  11038. break;
  11039. }
  11040. if (n > 0) {
  11041. conn->data_len += n;
  11042. /* Reset open PING count */
  11043. ping_count = 0;
  11044. } else {
  11045. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11046. && (!conn->must_close)) {
  11047. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11048. /* Stop sending PING */
  11049. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11050. "- closing connection",
  11051. ping_count,
  11052. conn->request_info.remote_addr,
  11053. conn->request_info.remote_port);
  11054. break;
  11055. }
  11056. if (enable_ping_pong) {
  11057. /* Send Websocket PING message */
  11058. DEBUG_TRACE("PING to %s:%u",
  11059. conn->request_info.remote_addr,
  11060. conn->request_info.remote_port);
  11061. ret = mg_websocket_write(conn,
  11062. MG_WEBSOCKET_OPCODE_PING,
  11063. NULL,
  11064. 0);
  11065. if (ret <= 0) {
  11066. /* Error: send failed */
  11067. DEBUG_TRACE("Send PING failed (%i)", ret);
  11068. break;
  11069. }
  11070. ping_count++;
  11071. }
  11072. }
  11073. /* Timeout: should retry */
  11074. /* TODO: get timeout def */
  11075. }
  11076. }
  11077. }
  11078. /* Leave data processing loop */
  11079. mg_set_thread_name("worker");
  11080. conn->in_websocket_handling = 0;
  11081. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11082. conn->request_info.remote_addr,
  11083. conn->request_info.remote_port);
  11084. }
  11085. static int
  11086. mg_websocket_write_exec(struct mg_connection *conn,
  11087. int opcode,
  11088. const char *data,
  11089. size_t dataLen,
  11090. uint32_t masking_key)
  11091. {
  11092. unsigned char header[14];
  11093. size_t headerLen;
  11094. int retval;
  11095. #if defined(GCC_DIAGNOSTIC)
  11096. /* Disable spurious conversion warning for GCC */
  11097. #pragma GCC diagnostic push
  11098. #pragma GCC diagnostic ignored "-Wconversion"
  11099. #endif
  11100. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11101. #if defined(GCC_DIAGNOSTIC)
  11102. #pragma GCC diagnostic pop
  11103. #endif
  11104. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11105. if (dataLen < 126) {
  11106. /* inline 7-bit length field */
  11107. header[1] = (unsigned char)dataLen;
  11108. headerLen = 2;
  11109. } else if (dataLen <= 0xFFFF) {
  11110. /* 16-bit length field */
  11111. uint16_t len = htons((uint16_t)dataLen);
  11112. header[1] = 126;
  11113. memcpy(header + 2, &len, 2);
  11114. headerLen = 4;
  11115. } else {
  11116. /* 64-bit length field */
  11117. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11118. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11119. header[1] = 127;
  11120. memcpy(header + 2, &len1, 4);
  11121. memcpy(header + 6, &len2, 4);
  11122. headerLen = 10;
  11123. }
  11124. if (masking_key) {
  11125. /* add mask */
  11126. header[1] |= 0x80;
  11127. memcpy(header + headerLen, &masking_key, 4);
  11128. headerLen += 4;
  11129. }
  11130. /* Note that POSIX/Winsock's send() is threadsafe
  11131. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11132. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11133. * push(), although that is only a problem if the packet is large or
  11134. * outgoing buffer is full). */
  11135. /* TODO: Check if this lock should be moved to user land.
  11136. * Currently the server sets this lock for websockets, but
  11137. * not for any other connection. It must be set for every
  11138. * conn read/written by more than one thread, no matter if
  11139. * it is a websocket or regular connection. */
  11140. (void)mg_lock_connection(conn);
  11141. retval = mg_write(conn, header, headerLen);
  11142. if (retval != (int)headerLen) {
  11143. /* Did not send complete header */
  11144. retval = -1;
  11145. } else {
  11146. if (dataLen > 0) {
  11147. retval = mg_write(conn, data, dataLen);
  11148. }
  11149. /* if dataLen == 0, the header length (2) is returned */
  11150. }
  11151. /* TODO: Remove this unlock as well, when lock is removed. */
  11152. mg_unlock_connection(conn);
  11153. return retval;
  11154. }
  11155. int
  11156. mg_websocket_write(struct mg_connection *conn,
  11157. int opcode,
  11158. const char *data,
  11159. size_t dataLen)
  11160. {
  11161. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11162. }
  11163. static void
  11164. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11165. {
  11166. size_t i = 0;
  11167. i = 0;
  11168. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11169. /* Convert in 32 bit words, if data is 4 byte aligned */
  11170. while (i < (in_len - 3)) {
  11171. *(uint32_t *)(void *)(out + i) =
  11172. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11173. i += 4;
  11174. }
  11175. }
  11176. if (i != in_len) {
  11177. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11178. while (i < in_len) {
  11179. *(uint8_t *)(void *)(out + i) =
  11180. *(uint8_t *)(void *)(in + i)
  11181. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11182. i++;
  11183. }
  11184. }
  11185. }
  11186. int
  11187. mg_websocket_client_write(struct mg_connection *conn,
  11188. int opcode,
  11189. const char *data,
  11190. size_t dataLen)
  11191. {
  11192. int retval = -1;
  11193. char *masked_data =
  11194. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11195. uint32_t masking_key = 0;
  11196. if (masked_data == NULL) {
  11197. /* Return -1 in an error case */
  11198. mg_cry_internal(conn,
  11199. "%s",
  11200. "Cannot allocate buffer for masked websocket response: "
  11201. "Out of memory");
  11202. return -1;
  11203. }
  11204. do {
  11205. /* Get a masking key - but not 0 */
  11206. masking_key = (uint32_t)get_random();
  11207. } while (masking_key == 0);
  11208. mask_data(data, dataLen, masking_key, masked_data);
  11209. retval = mg_websocket_write_exec(
  11210. conn, opcode, masked_data, dataLen, masking_key);
  11211. mg_free(masked_data);
  11212. return retval;
  11213. }
  11214. static void
  11215. handle_websocket_request(struct mg_connection *conn,
  11216. const char *path,
  11217. int is_callback_resource,
  11218. struct mg_websocket_subprotocols *subprotocols,
  11219. mg_websocket_connect_handler ws_connect_handler,
  11220. mg_websocket_ready_handler ws_ready_handler,
  11221. mg_websocket_data_handler ws_data_handler,
  11222. mg_websocket_close_handler ws_close_handler,
  11223. void *cbData)
  11224. {
  11225. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11226. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11227. ptrdiff_t lua_websock = 0;
  11228. #if !defined(USE_LUA)
  11229. (void)path;
  11230. #endif
  11231. /* Step 1: Check websocket protocol version. */
  11232. /* Step 1.1: Check Sec-WebSocket-Key. */
  11233. if (!websock_key) {
  11234. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11235. * requires a Sec-WebSocket-Key header.
  11236. */
  11237. /* It could be the hixie draft version
  11238. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11239. */
  11240. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11241. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11242. char key3[8];
  11243. if ((key1 != NULL) && (key2 != NULL)) {
  11244. /* This version uses 8 byte body data in a GET request */
  11245. conn->content_len = 8;
  11246. if (8 == mg_read(conn, key3, 8)) {
  11247. /* This is the hixie version */
  11248. mg_send_http_error(conn,
  11249. 426,
  11250. "%s",
  11251. "Protocol upgrade to RFC 6455 required");
  11252. return;
  11253. }
  11254. }
  11255. /* This is an unknown version */
  11256. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11257. return;
  11258. }
  11259. /* Step 1.2: Check websocket protocol version. */
  11260. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11261. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11262. /* Reject wrong versions */
  11263. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11264. return;
  11265. }
  11266. /* Step 1.3: Could check for "Host", but we do not really nead this
  11267. * value for anything, so just ignore it. */
  11268. /* Step 2: If a callback is responsible, call it. */
  11269. if (is_callback_resource) {
  11270. /* Step 2.1 check and select subprotocol */
  11271. const char *protocols[64]; // max 64 headers
  11272. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11273. "Sec-WebSocket-Protocol",
  11274. protocols,
  11275. 64);
  11276. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11277. int cnt = 0;
  11278. int idx;
  11279. unsigned long len;
  11280. const char *sep, *curSubProtocol,
  11281. *acceptedWebSocketSubprotocol = NULL;
  11282. /* look for matching subprotocol */
  11283. do {
  11284. const char *protocol = protocols[cnt];
  11285. do {
  11286. sep = strchr(protocol, ',');
  11287. curSubProtocol = protocol;
  11288. len = sep ? (unsigned long)(sep - protocol)
  11289. : (unsigned long)strlen(protocol);
  11290. while (sep && isspace((unsigned char)*++sep))
  11291. ; // ignore leading whitespaces
  11292. protocol = sep;
  11293. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11294. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11295. && (strncmp(curSubProtocol,
  11296. subprotocols->subprotocols[idx],
  11297. len)
  11298. == 0)) {
  11299. acceptedWebSocketSubprotocol =
  11300. subprotocols->subprotocols[idx];
  11301. break;
  11302. }
  11303. }
  11304. } while (sep && !acceptedWebSocketSubprotocol);
  11305. } while (++cnt < nbSubprotocolHeader
  11306. && !acceptedWebSocketSubprotocol);
  11307. conn->request_info.acceptedWebSocketSubprotocol =
  11308. acceptedWebSocketSubprotocol;
  11309. } else if (nbSubprotocolHeader > 0) {
  11310. /* keep legacy behavior */
  11311. const char *protocol = protocols[0];
  11312. /* The protocol is a comma separated list of names. */
  11313. /* The server must only return one value from this list. */
  11314. /* First check if it is a list or just a single value. */
  11315. const char *sep = strrchr(protocol, ',');
  11316. if (sep == NULL) {
  11317. /* Just a single protocol -> accept it. */
  11318. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11319. } else {
  11320. /* Multiple protocols -> accept the last one. */
  11321. /* This is just a quick fix if the client offers multiple
  11322. * protocols. The handler should have a list of accepted
  11323. * protocols on his own
  11324. * and use it to select one protocol among those the client
  11325. * has
  11326. * offered.
  11327. */
  11328. while (isspace((unsigned char)*++sep)) {
  11329. ; /* ignore leading whitespaces */
  11330. }
  11331. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11332. }
  11333. }
  11334. if ((ws_connect_handler != NULL)
  11335. && (ws_connect_handler(conn, cbData) != 0)) {
  11336. /* C callback has returned non-zero, do not proceed with
  11337. * handshake.
  11338. */
  11339. /* Note that C callbacks are no longer called when Lua is
  11340. * responsible, so C can no longer filter callbacks for Lua. */
  11341. return;
  11342. }
  11343. }
  11344. #if defined(USE_LUA)
  11345. /* Step 3: No callback. Check if Lua is responsible. */
  11346. else {
  11347. /* Step 3.1: Check if Lua is responsible. */
  11348. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11349. lua_websock = match_prefix_strlen(
  11350. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11351. }
  11352. if (lua_websock) {
  11353. /* Step 3.2: Lua is responsible: call it. */
  11354. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11355. if (!conn->lua_websocket_state) {
  11356. /* Lua rejected the new client */
  11357. return;
  11358. }
  11359. }
  11360. }
  11361. #endif
  11362. /* Step 4: Check if there is a responsible websocket handler. */
  11363. if (!is_callback_resource && !lua_websock) {
  11364. /* There is no callback, and Lua is not responsible either. */
  11365. /* Reply with a 404 Not Found. We are still at a standard
  11366. * HTTP request here, before the websocket handshake, so
  11367. * we can still send standard HTTP error replies. */
  11368. mg_send_http_error(conn, 404, "%s", "Not found");
  11369. return;
  11370. }
  11371. /* Step 5: The websocket connection has been accepted */
  11372. if (!send_websocket_handshake(conn, websock_key)) {
  11373. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11374. return;
  11375. }
  11376. /* Step 6: Call the ready handler */
  11377. if (is_callback_resource) {
  11378. if (ws_ready_handler != NULL) {
  11379. ws_ready_handler(conn, cbData);
  11380. }
  11381. #if defined(USE_LUA)
  11382. } else if (lua_websock) {
  11383. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11384. /* the ready handler returned false */
  11385. return;
  11386. }
  11387. #endif
  11388. }
  11389. /* Step 7: Enter the read loop */
  11390. if (is_callback_resource) {
  11391. read_websocket(conn, ws_data_handler, cbData);
  11392. #if defined(USE_LUA)
  11393. } else if (lua_websock) {
  11394. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11395. #endif
  11396. }
  11397. /* Step 8: Call the close handler */
  11398. if (ws_close_handler) {
  11399. ws_close_handler(conn, cbData);
  11400. }
  11401. }
  11402. #endif /* !USE_WEBSOCKET */
  11403. /* Is upgrade request:
  11404. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11405. * 1 = upgrade to websocket
  11406. * 2 = upgrade to HTTP/2
  11407. * -1 = upgrade to unknown protocol
  11408. */
  11409. static int
  11410. should_switch_to_protocol(const struct mg_connection *conn)
  11411. {
  11412. const char *upgrade, *connection;
  11413. /* A websocket protocoll has the following HTTP headers:
  11414. *
  11415. * Connection: Upgrade
  11416. * Upgrade: Websocket
  11417. */
  11418. connection = mg_get_header(conn, "Connection");
  11419. if (connection == NULL) {
  11420. return PROTOCOL_TYPE_HTTP1;
  11421. }
  11422. if (!mg_strcasestr(connection, "upgrade")) {
  11423. return PROTOCOL_TYPE_HTTP1;
  11424. }
  11425. upgrade = mg_get_header(conn, "Upgrade");
  11426. if (upgrade == NULL) {
  11427. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11428. return -1;
  11429. }
  11430. /* Upgrade to ... */
  11431. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11432. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11433. * "Sec-WebSocket-Version" are also required.
  11434. * Don't check them here, since even an unsupported websocket protocol
  11435. * request still IS a websocket request (in contrast to a standard HTTP
  11436. * request). It will fail later in handle_websocket_request.
  11437. */
  11438. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11439. }
  11440. if (0 != mg_strcasestr(upgrade, "h2")) {
  11441. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11442. }
  11443. /* Upgrade to another protocol */
  11444. return -1;
  11445. }
  11446. static int
  11447. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11448. {
  11449. int n;
  11450. unsigned int a, b, c, d, slash;
  11451. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11452. slash = 32;
  11453. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11454. n = 0;
  11455. }
  11456. }
  11457. if ((n > 0) && ((size_t)n == vec->len)) {
  11458. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11459. /* IPv4 format */
  11460. if (sa->sa.sa_family == AF_INET) {
  11461. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11462. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11463. | ((uint32_t)c << 8) | (uint32_t)d;
  11464. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11465. return (ip & mask) == net;
  11466. }
  11467. return 0;
  11468. }
  11469. }
  11470. #if defined(USE_IPV6)
  11471. else {
  11472. char ad[50];
  11473. const char *p;
  11474. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11475. slash = 128;
  11476. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11477. n = 0;
  11478. }
  11479. }
  11480. if ((n <= 0) && no_strict) {
  11481. /* no square brackets? */
  11482. p = strchr(vec->ptr, '/');
  11483. if (p && (p < (vec->ptr + vec->len))) {
  11484. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11485. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11486. n += (int)(p - vec->ptr);
  11487. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11488. } else {
  11489. n = 0;
  11490. }
  11491. } else if (vec->len < sizeof(ad)) {
  11492. n = (int)vec->len;
  11493. slash = 128;
  11494. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11495. }
  11496. }
  11497. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11498. p = ad;
  11499. c = 0;
  11500. /* zone indexes are unsupported, at least two colons are needed */
  11501. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11502. if (*(p++) == ':') {
  11503. c++;
  11504. }
  11505. }
  11506. if ((*p == '\0') && (c >= 2)) {
  11507. struct sockaddr_in6 sin6;
  11508. unsigned int i;
  11509. /* for strict validation, an actual IPv6 argument is needed */
  11510. if (sa->sa.sa_family != AF_INET6) {
  11511. return 0;
  11512. }
  11513. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11514. /* IPv6 format */
  11515. for (i = 0; i < 16; i++) {
  11516. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11517. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11518. uint8_t mask = 0;
  11519. if (8 * i + 8 < slash) {
  11520. mask = 0xFFu;
  11521. } else if (8 * i < slash) {
  11522. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11523. }
  11524. if ((ip & mask) != net) {
  11525. return 0;
  11526. }
  11527. }
  11528. return 1;
  11529. }
  11530. }
  11531. }
  11532. }
  11533. #else
  11534. (void)no_strict;
  11535. #endif
  11536. /* malformed */
  11537. return -1;
  11538. }
  11539. static int
  11540. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11541. {
  11542. int throttle = 0;
  11543. struct vec vec, val;
  11544. char mult;
  11545. double v;
  11546. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11547. mult = ',';
  11548. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11549. || (v < 0)
  11550. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11551. && (mult != ','))) {
  11552. continue;
  11553. }
  11554. v *= (lowercase(&mult) == 'k')
  11555. ? 1024
  11556. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11557. if (vec.len == 1 && vec.ptr[0] == '*') {
  11558. throttle = (int)v;
  11559. } else {
  11560. int matched = parse_match_net(&vec, rsa, 0);
  11561. if (matched >= 0) {
  11562. /* a valid IP subnet */
  11563. if (matched) {
  11564. throttle = (int)v;
  11565. }
  11566. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11567. throttle = (int)v;
  11568. }
  11569. }
  11570. }
  11571. return throttle;
  11572. }
  11573. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11574. #include "handle_form.inl"
  11575. static int
  11576. get_first_ssl_listener_index(const struct mg_context *ctx)
  11577. {
  11578. unsigned int i;
  11579. int idx = -1;
  11580. if (ctx) {
  11581. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11582. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11583. }
  11584. }
  11585. return idx;
  11586. }
  11587. /* Return host (without port) */
  11588. static void
  11589. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11590. {
  11591. const char *host_header =
  11592. get_header(ri->http_headers, ri->num_headers, "Host");
  11593. host->ptr = NULL;
  11594. host->len = 0;
  11595. if (host_header != NULL) {
  11596. char *pos;
  11597. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11598. * is found. */
  11599. if (*host_header == '[') {
  11600. pos = strchr(host_header, ']');
  11601. if (!pos) {
  11602. /* Malformed hostname starts with '[', but no ']' found */
  11603. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11604. return;
  11605. }
  11606. /* terminate after ']' */
  11607. host->ptr = host_header;
  11608. host->len = (size_t)(pos + 1 - host_header);
  11609. } else {
  11610. /* Otherwise, a ':' separates hostname and port number */
  11611. pos = strchr(host_header, ':');
  11612. if (pos != NULL) {
  11613. host->len = (size_t)(pos - host_header);
  11614. } else {
  11615. host->len = strlen(host_header);
  11616. }
  11617. host->ptr = host_header;
  11618. }
  11619. }
  11620. }
  11621. static int
  11622. switch_domain_context(struct mg_connection *conn)
  11623. {
  11624. struct vec host;
  11625. get_host_from_request_info(&host, &conn->request_info);
  11626. if (host.ptr) {
  11627. if (conn->ssl) {
  11628. /* This is a HTTPS connection, maybe we have a hostname
  11629. * from SNI (set in ssl_servername_callback). */
  11630. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11631. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11632. /* We are not using the default domain */
  11633. if ((strlen(sslhost) != host.len)
  11634. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11635. /* Mismatch between SNI domain and HTTP domain */
  11636. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11637. sslhost,
  11638. (int)host.len,
  11639. host.ptr);
  11640. return 0;
  11641. }
  11642. }
  11643. } else {
  11644. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11645. while (dom) {
  11646. if ((strlen(dom->config[AUTHENTICATION_DOMAIN]) == host.len)
  11647. && !mg_strncasecmp(host.ptr,
  11648. dom->config[AUTHENTICATION_DOMAIN],
  11649. host.len)) {
  11650. /* Found matching domain */
  11651. DEBUG_TRACE("HTTP domain %s found",
  11652. dom->config[AUTHENTICATION_DOMAIN]);
  11653. /* TODO: Check if this is a HTTP or HTTPS domain */
  11654. conn->dom_ctx = dom;
  11655. break;
  11656. }
  11657. mg_lock_context(conn->phys_ctx);
  11658. dom = dom->next;
  11659. mg_unlock_context(conn->phys_ctx);
  11660. }
  11661. }
  11662. } else {
  11663. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11664. return 1;
  11665. }
  11666. DEBUG_TRACE("HTTP%s Host: %.*s",
  11667. conn->ssl ? "S" : "",
  11668. (int)host.len,
  11669. host.ptr);
  11670. return 1;
  11671. }
  11672. static int mg_construct_local_link(const struct mg_connection *conn,
  11673. char *buf,
  11674. size_t buflen,
  11675. const char *define_proto,
  11676. int define_port,
  11677. const char *define_uri);
  11678. static void
  11679. redirect_to_https_port(struct mg_connection *conn, int port)
  11680. {
  11681. char target_url[MG_BUF_LEN];
  11682. int truncated = 0;
  11683. const char *expect_proto =
  11684. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11685. /* Use "308 Permanent Redirect" */
  11686. int redirect_code = 308;
  11687. /* In any case, close the current connection */
  11688. conn->must_close = 1;
  11689. /* Send host, port, uri and (if it exists) ?query_string */
  11690. if (mg_construct_local_link(
  11691. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11692. < 0) {
  11693. truncated = 1;
  11694. } else if (conn->request_info.query_string != NULL) {
  11695. size_t slen1 = strlen(target_url);
  11696. size_t slen2 = strlen(conn->request_info.query_string);
  11697. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11698. target_url[slen1] = '?';
  11699. memcpy(target_url + slen1 + 1,
  11700. conn->request_info.query_string,
  11701. slen2);
  11702. target_url[slen1 + slen2 + 1] = 0;
  11703. } else {
  11704. truncated = 1;
  11705. }
  11706. }
  11707. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11708. * is used as buffer size) */
  11709. if (truncated) {
  11710. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11711. return;
  11712. }
  11713. /* Use redirect helper function */
  11714. mg_send_http_redirect(conn, target_url, redirect_code);
  11715. }
  11716. static void
  11717. mg_set_handler_type(struct mg_context *phys_ctx,
  11718. struct mg_domain_context *dom_ctx,
  11719. const char *uri,
  11720. int handler_type,
  11721. int is_delete_request,
  11722. mg_request_handler handler,
  11723. struct mg_websocket_subprotocols *subprotocols,
  11724. mg_websocket_connect_handler connect_handler,
  11725. mg_websocket_ready_handler ready_handler,
  11726. mg_websocket_data_handler data_handler,
  11727. mg_websocket_close_handler close_handler,
  11728. mg_authorization_handler auth_handler,
  11729. void *cbdata)
  11730. {
  11731. struct mg_handler_info *tmp_rh, **lastref;
  11732. size_t urilen = strlen(uri);
  11733. if (handler_type == WEBSOCKET_HANDLER) {
  11734. DEBUG_ASSERT(handler == NULL);
  11735. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11736. || ready_handler != NULL || data_handler != NULL
  11737. || close_handler != NULL);
  11738. DEBUG_ASSERT(auth_handler == NULL);
  11739. if (handler != NULL) {
  11740. return;
  11741. }
  11742. if (!is_delete_request && (connect_handler == NULL)
  11743. && (ready_handler == NULL) && (data_handler == NULL)
  11744. && (close_handler == NULL)) {
  11745. return;
  11746. }
  11747. if (auth_handler != NULL) {
  11748. return;
  11749. }
  11750. } else if (handler_type == REQUEST_HANDLER) {
  11751. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11752. && data_handler == NULL && close_handler == NULL);
  11753. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11754. DEBUG_ASSERT(auth_handler == NULL);
  11755. if ((connect_handler != NULL) || (ready_handler != NULL)
  11756. || (data_handler != NULL) || (close_handler != NULL)) {
  11757. return;
  11758. }
  11759. if (!is_delete_request && (handler == NULL)) {
  11760. return;
  11761. }
  11762. if (auth_handler != NULL) {
  11763. return;
  11764. }
  11765. } else { /* AUTH_HANDLER */
  11766. DEBUG_ASSERT(handler == NULL);
  11767. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11768. && data_handler == NULL && close_handler == NULL);
  11769. DEBUG_ASSERT(auth_handler != NULL);
  11770. if (handler != NULL) {
  11771. return;
  11772. }
  11773. if ((connect_handler != NULL) || (ready_handler != NULL)
  11774. || (data_handler != NULL) || (close_handler != NULL)) {
  11775. return;
  11776. }
  11777. if (!is_delete_request && (auth_handler == NULL)) {
  11778. return;
  11779. }
  11780. }
  11781. if (!phys_ctx || !dom_ctx) {
  11782. return;
  11783. }
  11784. mg_lock_context(phys_ctx);
  11785. /* first try to find an existing handler */
  11786. do {
  11787. lastref = &(dom_ctx->handlers);
  11788. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11789. tmp_rh = tmp_rh->next) {
  11790. if (tmp_rh->handler_type == handler_type
  11791. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11792. if (!is_delete_request) {
  11793. /* update existing handler */
  11794. if (handler_type == REQUEST_HANDLER) {
  11795. /* Wait for end of use before updating */
  11796. if (tmp_rh->refcount) {
  11797. mg_unlock_context(phys_ctx);
  11798. mg_sleep(1);
  11799. mg_lock_context(phys_ctx);
  11800. /* tmp_rh might have been freed, search again. */
  11801. break;
  11802. }
  11803. /* Ok, the handler is no more use -> Update it */
  11804. tmp_rh->handler = handler;
  11805. } else if (handler_type == WEBSOCKET_HANDLER) {
  11806. tmp_rh->subprotocols = subprotocols;
  11807. tmp_rh->connect_handler = connect_handler;
  11808. tmp_rh->ready_handler = ready_handler;
  11809. tmp_rh->data_handler = data_handler;
  11810. tmp_rh->close_handler = close_handler;
  11811. } else { /* AUTH_HANDLER */
  11812. tmp_rh->auth_handler = auth_handler;
  11813. }
  11814. tmp_rh->cbdata = cbdata;
  11815. } else {
  11816. /* remove existing handler */
  11817. if (handler_type == REQUEST_HANDLER) {
  11818. /* Wait for end of use before removing */
  11819. if (tmp_rh->refcount) {
  11820. tmp_rh->removing = 1;
  11821. mg_unlock_context(phys_ctx);
  11822. mg_sleep(1);
  11823. mg_lock_context(phys_ctx);
  11824. /* tmp_rh might have been freed, search again. */
  11825. break;
  11826. }
  11827. /* Ok, the handler is no more used */
  11828. }
  11829. *lastref = tmp_rh->next;
  11830. mg_free(tmp_rh->uri);
  11831. mg_free(tmp_rh);
  11832. }
  11833. mg_unlock_context(phys_ctx);
  11834. return;
  11835. }
  11836. lastref = &(tmp_rh->next);
  11837. }
  11838. } while (tmp_rh != NULL);
  11839. if (is_delete_request) {
  11840. /* no handler to set, this was a remove request to a non-existing
  11841. * handler */
  11842. mg_unlock_context(phys_ctx);
  11843. return;
  11844. }
  11845. tmp_rh =
  11846. (struct mg_handler_info *)mg_calloc_ctx(1,
  11847. sizeof(struct mg_handler_info),
  11848. phys_ctx);
  11849. if (tmp_rh == NULL) {
  11850. mg_unlock_context(phys_ctx);
  11851. mg_cry_ctx_internal(phys_ctx,
  11852. "%s",
  11853. "Cannot create new request handler struct, OOM");
  11854. return;
  11855. }
  11856. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11857. if (!tmp_rh->uri) {
  11858. mg_unlock_context(phys_ctx);
  11859. mg_free(tmp_rh);
  11860. mg_cry_ctx_internal(phys_ctx,
  11861. "%s",
  11862. "Cannot create new request handler struct, OOM");
  11863. return;
  11864. }
  11865. tmp_rh->uri_len = urilen;
  11866. if (handler_type == REQUEST_HANDLER) {
  11867. tmp_rh->refcount = 0;
  11868. tmp_rh->removing = 0;
  11869. tmp_rh->handler = handler;
  11870. } else if (handler_type == WEBSOCKET_HANDLER) {
  11871. tmp_rh->subprotocols = subprotocols;
  11872. tmp_rh->connect_handler = connect_handler;
  11873. tmp_rh->ready_handler = ready_handler;
  11874. tmp_rh->data_handler = data_handler;
  11875. tmp_rh->close_handler = close_handler;
  11876. } else { /* AUTH_HANDLER */
  11877. tmp_rh->auth_handler = auth_handler;
  11878. }
  11879. tmp_rh->cbdata = cbdata;
  11880. tmp_rh->handler_type = handler_type;
  11881. tmp_rh->next = NULL;
  11882. *lastref = tmp_rh;
  11883. mg_unlock_context(phys_ctx);
  11884. }
  11885. void
  11886. mg_set_request_handler(struct mg_context *ctx,
  11887. const char *uri,
  11888. mg_request_handler handler,
  11889. void *cbdata)
  11890. {
  11891. mg_set_handler_type(ctx,
  11892. &(ctx->dd),
  11893. uri,
  11894. REQUEST_HANDLER,
  11895. handler == NULL,
  11896. handler,
  11897. NULL,
  11898. NULL,
  11899. NULL,
  11900. NULL,
  11901. NULL,
  11902. NULL,
  11903. cbdata);
  11904. }
  11905. void
  11906. mg_set_websocket_handler(struct mg_context *ctx,
  11907. const char *uri,
  11908. mg_websocket_connect_handler connect_handler,
  11909. mg_websocket_ready_handler ready_handler,
  11910. mg_websocket_data_handler data_handler,
  11911. mg_websocket_close_handler close_handler,
  11912. void *cbdata)
  11913. {
  11914. mg_set_websocket_handler_with_subprotocols(ctx,
  11915. uri,
  11916. NULL,
  11917. connect_handler,
  11918. ready_handler,
  11919. data_handler,
  11920. close_handler,
  11921. cbdata);
  11922. }
  11923. void
  11924. mg_set_websocket_handler_with_subprotocols(
  11925. struct mg_context *ctx,
  11926. const char *uri,
  11927. struct mg_websocket_subprotocols *subprotocols,
  11928. mg_websocket_connect_handler connect_handler,
  11929. mg_websocket_ready_handler ready_handler,
  11930. mg_websocket_data_handler data_handler,
  11931. mg_websocket_close_handler close_handler,
  11932. void *cbdata)
  11933. {
  11934. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11935. && (data_handler == NULL)
  11936. && (close_handler == NULL);
  11937. mg_set_handler_type(ctx,
  11938. &(ctx->dd),
  11939. uri,
  11940. WEBSOCKET_HANDLER,
  11941. is_delete_request,
  11942. NULL,
  11943. subprotocols,
  11944. connect_handler,
  11945. ready_handler,
  11946. data_handler,
  11947. close_handler,
  11948. NULL,
  11949. cbdata);
  11950. }
  11951. void
  11952. mg_set_auth_handler(struct mg_context *ctx,
  11953. const char *uri,
  11954. mg_authorization_handler handler,
  11955. void *cbdata)
  11956. {
  11957. mg_set_handler_type(ctx,
  11958. &(ctx->dd),
  11959. uri,
  11960. AUTH_HANDLER,
  11961. handler == NULL,
  11962. NULL,
  11963. NULL,
  11964. NULL,
  11965. NULL,
  11966. NULL,
  11967. NULL,
  11968. handler,
  11969. cbdata);
  11970. }
  11971. static int
  11972. get_request_handler(struct mg_connection *conn,
  11973. int handler_type,
  11974. mg_request_handler *handler,
  11975. struct mg_websocket_subprotocols **subprotocols,
  11976. mg_websocket_connect_handler *connect_handler,
  11977. mg_websocket_ready_handler *ready_handler,
  11978. mg_websocket_data_handler *data_handler,
  11979. mg_websocket_close_handler *close_handler,
  11980. mg_authorization_handler *auth_handler,
  11981. void **cbdata,
  11982. struct mg_handler_info **handler_info)
  11983. {
  11984. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11985. if (request_info) {
  11986. const char *uri = request_info->local_uri;
  11987. size_t urilen = strlen(uri);
  11988. struct mg_handler_info *tmp_rh;
  11989. int step, matched;
  11990. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11991. return 0;
  11992. }
  11993. mg_lock_context(conn->phys_ctx);
  11994. for (step = 0; step < 3; step++) {
  11995. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11996. tmp_rh = tmp_rh->next) {
  11997. if (tmp_rh->handler_type != handler_type) {
  11998. continue;
  11999. }
  12000. if (step == 0) {
  12001. /* first try for an exact match */
  12002. matched = (tmp_rh->uri_len == urilen)
  12003. && (strcmp(tmp_rh->uri, uri) == 0);
  12004. } else if (step == 1) {
  12005. /* next try for a partial match, we will accept
  12006. uri/something */
  12007. matched =
  12008. (tmp_rh->uri_len < urilen)
  12009. && (uri[tmp_rh->uri_len] == '/')
  12010. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12011. } else {
  12012. /* finally try for pattern match */
  12013. matched =
  12014. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12015. }
  12016. if (matched) {
  12017. if (handler_type == WEBSOCKET_HANDLER) {
  12018. *subprotocols = tmp_rh->subprotocols;
  12019. *connect_handler = tmp_rh->connect_handler;
  12020. *ready_handler = tmp_rh->ready_handler;
  12021. *data_handler = tmp_rh->data_handler;
  12022. *close_handler = tmp_rh->close_handler;
  12023. } else if (handler_type == REQUEST_HANDLER) {
  12024. if (tmp_rh->removing) {
  12025. /* Treat as none found */
  12026. step = 2;
  12027. break;
  12028. }
  12029. *handler = tmp_rh->handler;
  12030. /* Acquire handler and give it back */
  12031. tmp_rh->refcount++;
  12032. *handler_info = tmp_rh;
  12033. } else { /* AUTH_HANDLER */
  12034. *auth_handler = tmp_rh->auth_handler;
  12035. }
  12036. *cbdata = tmp_rh->cbdata;
  12037. mg_unlock_context(conn->phys_ctx);
  12038. return 1;
  12039. }
  12040. }
  12041. }
  12042. mg_unlock_context(conn->phys_ctx);
  12043. }
  12044. return 0; /* none found */
  12045. }
  12046. /* Check if the script file is in a path, allowed for script files.
  12047. * This can be used if uploading files is possible not only for the server
  12048. * admin, and the upload mechanism does not check the file extension.
  12049. */
  12050. static int
  12051. is_in_script_path(const struct mg_connection *conn, const char *path)
  12052. {
  12053. /* TODO (Feature): Add config value for allowed script path.
  12054. * Default: All allowed. */
  12055. (void)conn;
  12056. (void)path;
  12057. return 1;
  12058. }
  12059. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12060. static int
  12061. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12062. int bits,
  12063. char *data,
  12064. size_t len,
  12065. void *cbdata)
  12066. {
  12067. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12068. if (pcallbacks->websocket_data) {
  12069. return pcallbacks->websocket_data(conn, bits, data, len);
  12070. }
  12071. /* No handler set - assume "OK" */
  12072. return 1;
  12073. }
  12074. static void
  12075. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12076. void *cbdata)
  12077. {
  12078. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12079. if (pcallbacks->connection_close) {
  12080. pcallbacks->connection_close(conn);
  12081. }
  12082. }
  12083. #endif
  12084. /* This is the heart of the Civetweb's logic.
  12085. * This function is called when the request is read, parsed and validated,
  12086. * and Civetweb must decide what action to take: serve a file, or
  12087. * a directory, or call embedded function, etcetera. */
  12088. static void
  12089. handle_request(struct mg_connection *conn)
  12090. {
  12091. struct mg_request_info *ri = &conn->request_info;
  12092. char path[PATH_MAX];
  12093. int uri_len, ssl_index;
  12094. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12095. is_put_or_delete_request = 0, is_callback_resource = 0;
  12096. int i;
  12097. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12098. mg_request_handler callback_handler = NULL;
  12099. struct mg_handler_info *handler_info = NULL;
  12100. struct mg_websocket_subprotocols *subprotocols;
  12101. mg_websocket_connect_handler ws_connect_handler = NULL;
  12102. mg_websocket_ready_handler ws_ready_handler = NULL;
  12103. mg_websocket_data_handler ws_data_handler = NULL;
  12104. mg_websocket_close_handler ws_close_handler = NULL;
  12105. void *callback_data = NULL;
  12106. mg_authorization_handler auth_handler = NULL;
  12107. void *auth_callback_data = NULL;
  12108. int handler_type;
  12109. time_t curtime = time(NULL);
  12110. char date[64];
  12111. path[0] = 0;
  12112. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12113. conn->request_state = 0;
  12114. /* 1. get the request url */
  12115. /* 1.1. split into url and query string */
  12116. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12117. != NULL) {
  12118. *((char *)conn->request_info.query_string++) = '\0';
  12119. }
  12120. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12121. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12122. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12123. if (ssl_index >= 0) {
  12124. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12125. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12126. redirect_to_https_port(conn, port);
  12127. } else {
  12128. /* A http to https forward port has been specified,
  12129. * but no https port to forward to. */
  12130. mg_send_http_error(conn,
  12131. 503,
  12132. "%s",
  12133. "Error: SSL forward not configured properly");
  12134. mg_cry_internal(conn,
  12135. "%s",
  12136. "Can not redirect to SSL, no SSL port available");
  12137. }
  12138. return;
  12139. }
  12140. uri_len = (int)strlen(ri->local_uri);
  12141. /* 1.3. decode url (if config says so) */
  12142. if (should_decode_url(conn)) {
  12143. mg_url_decode(
  12144. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12145. if (conn->request_info.query_string) {
  12146. url_decode_in_place((char *)conn->request_info.query_string);
  12147. }
  12148. }
  12149. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12150. * not possible */
  12151. remove_dot_segments((char *)ri->local_uri);
  12152. /* step 1. completed, the url is known now */
  12153. uri_len = (int)strlen(ri->local_uri);
  12154. DEBUG_TRACE("URL: %s", ri->local_uri);
  12155. /* 2. if this ip has limited speed, set it for this connection */
  12156. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12157. &conn->client.rsa,
  12158. ri->local_uri);
  12159. /* 3. call a "handle everything" callback, if registered */
  12160. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12161. /* Note that since V1.7 the "begin_request" function is called
  12162. * before an authorization check. If an authorization check is
  12163. * required, use a request_handler instead. */
  12164. i = conn->phys_ctx->callbacks.begin_request(conn);
  12165. if (i > 0) {
  12166. /* callback already processed the request. Store the
  12167. return value as a status code for the access log. */
  12168. conn->status_code = i;
  12169. if (!conn->must_close) {
  12170. discard_unread_request_data(conn);
  12171. }
  12172. return;
  12173. } else if (i == 0) {
  12174. /* civetweb should process the request */
  12175. } else {
  12176. /* unspecified - may change with the next version */
  12177. return;
  12178. }
  12179. }
  12180. /* request not yet handled by a handler or redirect, so the request
  12181. * is processed here */
  12182. /* 4. Check for CORS preflight requests and handle them (if configured).
  12183. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12184. */
  12185. if (!strcmp(ri->request_method, "OPTIONS")) {
  12186. /* Send a response to CORS preflights only if
  12187. * access_control_allow_methods is not NULL and not an empty string.
  12188. * In this case, scripts can still handle CORS. */
  12189. const char *cors_meth_cfg =
  12190. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12191. const char *cors_orig_cfg =
  12192. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12193. const char *cors_origin =
  12194. get_header(ri->http_headers, ri->num_headers, "Origin");
  12195. const char *cors_acrm = get_header(ri->http_headers,
  12196. ri->num_headers,
  12197. "Access-Control-Request-Method");
  12198. /* Todo: check if cors_origin is in cors_orig_cfg.
  12199. * Or, let the client check this. */
  12200. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12201. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12202. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12203. /* This is a valid CORS preflight, and the server is configured
  12204. * to handle it automatically. */
  12205. const char *cors_acrh =
  12206. get_header(ri->http_headers,
  12207. ri->num_headers,
  12208. "Access-Control-Request-Headers");
  12209. gmt_time_string(date, sizeof(date), &curtime);
  12210. mg_printf(conn,
  12211. "HTTP/1.1 200 OK\r\n"
  12212. "Date: %s\r\n"
  12213. "Access-Control-Allow-Origin: %s\r\n"
  12214. "Access-Control-Allow-Methods: %s\r\n"
  12215. "Content-Length: 0\r\n"
  12216. "Connection: %s\r\n",
  12217. date,
  12218. cors_orig_cfg,
  12219. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12220. suggest_connection_header(conn));
  12221. if (cors_acrh != NULL) {
  12222. /* CORS request is asking for additional headers */
  12223. const char *cors_hdr_cfg =
  12224. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12225. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12226. /* Allow only if access_control_allow_headers is
  12227. * not NULL and not an empty string. If this
  12228. * configuration is set to *, allow everything.
  12229. * Otherwise this configuration must be a list
  12230. * of allowed HTTP header names. */
  12231. mg_printf(conn,
  12232. "Access-Control-Allow-Headers: %s\r\n",
  12233. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12234. : cors_hdr_cfg));
  12235. }
  12236. }
  12237. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12238. mg_printf(conn, "\r\n");
  12239. return;
  12240. }
  12241. }
  12242. /* 5. interpret the url to find out how the request must be handled
  12243. */
  12244. /* 5.1. first test, if the request targets the regular http(s)://
  12245. * protocol namespace or the websocket ws(s):// protocol namespace.
  12246. */
  12247. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12248. #if defined(USE_WEBSOCKET)
  12249. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12250. #else
  12251. handler_type = REQUEST_HANDLER;
  12252. #endif /* defined(USE_WEBSOCKET) */
  12253. if (is_websocket_request) {
  12254. HTTP1_only;
  12255. }
  12256. /* 5.2. check if the request will be handled by a callback */
  12257. if (get_request_handler(conn,
  12258. handler_type,
  12259. &callback_handler,
  12260. &subprotocols,
  12261. &ws_connect_handler,
  12262. &ws_ready_handler,
  12263. &ws_data_handler,
  12264. &ws_close_handler,
  12265. NULL,
  12266. &callback_data,
  12267. &handler_info)) {
  12268. /* 5.2.1. A callback will handle this request. All requests
  12269. * handled by a callback have to be considered as requests
  12270. * to a script resource. */
  12271. is_callback_resource = 1;
  12272. is_script_resource = 1;
  12273. is_put_or_delete_request = is_put_or_delete_method(conn);
  12274. } else {
  12275. no_callback_resource:
  12276. /* 5.2.2. No callback is responsible for this request. The URI
  12277. * addresses a file based resource (static content or Lua/cgi
  12278. * scripts in the file system). */
  12279. is_callback_resource = 0;
  12280. interpret_uri(conn,
  12281. path,
  12282. sizeof(path),
  12283. &file.stat,
  12284. &is_found,
  12285. &is_script_resource,
  12286. &is_websocket_request,
  12287. &is_put_or_delete_request);
  12288. }
  12289. /* 6. authorization check */
  12290. /* 6.1. a custom authorization handler is installed */
  12291. if (get_request_handler(conn,
  12292. AUTH_HANDLER,
  12293. NULL,
  12294. NULL,
  12295. NULL,
  12296. NULL,
  12297. NULL,
  12298. NULL,
  12299. &auth_handler,
  12300. &auth_callback_data,
  12301. NULL)) {
  12302. if (!auth_handler(conn, auth_callback_data)) {
  12303. return;
  12304. }
  12305. } else if (is_put_or_delete_request && !is_script_resource
  12306. && !is_callback_resource) {
  12307. HTTP1_only;
  12308. /* 6.2. this request is a PUT/DELETE to a real file */
  12309. /* 6.2.1. thus, the server must have real files */
  12310. #if defined(NO_FILES)
  12311. if (1) {
  12312. #else
  12313. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12314. #endif
  12315. /* This server does not have any real files, thus the
  12316. * PUT/DELETE methods are not valid. */
  12317. mg_send_http_error(conn,
  12318. 405,
  12319. "%s method not allowed",
  12320. conn->request_info.request_method);
  12321. return;
  12322. }
  12323. #if !defined(NO_FILES)
  12324. /* 6.2.2. Check if put authorization for static files is
  12325. * available.
  12326. */
  12327. if (!is_authorized_for_put(conn)) {
  12328. send_authorization_request(conn, NULL);
  12329. return;
  12330. }
  12331. #endif
  12332. } else {
  12333. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12334. * or it is a PUT or DELETE request to a resource that does not
  12335. * correspond to a file. Check authorization. */
  12336. if (!check_authorization(conn, path)) {
  12337. send_authorization_request(conn, NULL);
  12338. return;
  12339. }
  12340. }
  12341. /* request is authorized or does not need authorization */
  12342. /* 7. check if there are request handlers for this uri */
  12343. if (is_callback_resource) {
  12344. HTTP1_only;
  12345. if (!is_websocket_request) {
  12346. i = callback_handler(conn, callback_data);
  12347. /* Callback handler will not be used anymore. Release it */
  12348. mg_lock_context(conn->phys_ctx);
  12349. handler_info->refcount--;
  12350. mg_unlock_context(conn->phys_ctx);
  12351. if (i > 0) {
  12352. /* Do nothing, callback has served the request. Store
  12353. * then return value as status code for the log and discard
  12354. * all data from the client not used by the callback. */
  12355. conn->status_code = i;
  12356. if (!conn->must_close) {
  12357. discard_unread_request_data(conn);
  12358. }
  12359. } else {
  12360. /* The handler did NOT handle the request. */
  12361. /* Some proper reactions would be:
  12362. * a) close the connections without sending anything
  12363. * b) send a 404 not found
  12364. * c) try if there is a file matching the URI
  12365. * It would be possible to do a, b or c in the callback
  12366. * implementation, and return 1 - we cannot do anything
  12367. * here, that is not possible in the callback.
  12368. *
  12369. * TODO: What would be the best reaction here?
  12370. * (Note: The reaction may change, if there is a better
  12371. *idea.)
  12372. */
  12373. /* For the moment, use option c: We look for a proper file,
  12374. * but since a file request is not always a script resource,
  12375. * the authorization check might be different. */
  12376. interpret_uri(conn,
  12377. path,
  12378. sizeof(path),
  12379. &file.stat,
  12380. &is_found,
  12381. &is_script_resource,
  12382. &is_websocket_request,
  12383. &is_put_or_delete_request);
  12384. callback_handler = NULL;
  12385. /* Here we are at a dead end:
  12386. * According to URI matching, a callback should be
  12387. * responsible for handling the request,
  12388. * we called it, but the callback declared itself
  12389. * not responsible.
  12390. * We use a goto here, to get out of this dead end,
  12391. * and continue with the default handling.
  12392. * A goto here is simpler and better to understand
  12393. * than some curious loop. */
  12394. goto no_callback_resource;
  12395. }
  12396. } else {
  12397. #if defined(USE_WEBSOCKET)
  12398. handle_websocket_request(conn,
  12399. path,
  12400. is_callback_resource,
  12401. subprotocols,
  12402. ws_connect_handler,
  12403. ws_ready_handler,
  12404. ws_data_handler,
  12405. ws_close_handler,
  12406. callback_data);
  12407. #endif
  12408. }
  12409. return;
  12410. }
  12411. /* 8. handle websocket requests */
  12412. #if defined(USE_WEBSOCKET)
  12413. if (is_websocket_request) {
  12414. HTTP1_only;
  12415. if (is_script_resource) {
  12416. if (is_in_script_path(conn, path)) {
  12417. /* Websocket Lua script */
  12418. handle_websocket_request(conn,
  12419. path,
  12420. 0 /* Lua Script */,
  12421. NULL,
  12422. NULL,
  12423. NULL,
  12424. NULL,
  12425. NULL,
  12426. conn->phys_ctx->user_data);
  12427. } else {
  12428. /* Script was in an illegal path */
  12429. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12430. }
  12431. } else {
  12432. mg_send_http_error(conn, 404, "%s", "Not found");
  12433. }
  12434. return;
  12435. } else
  12436. #endif
  12437. #if defined(NO_FILES)
  12438. /* 9a. In case the server uses only callbacks, this uri is
  12439. * unknown.
  12440. * Then, all request handling ends here. */
  12441. mg_send_http_error(conn, 404, "%s", "Not Found");
  12442. #else
  12443. /* 9b. This request is either for a static file or resource handled
  12444. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12445. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12446. mg_send_http_error(conn, 404, "%s", "Not Found");
  12447. return;
  12448. }
  12449. /* 10. Request is handled by a script */
  12450. if (is_script_resource) {
  12451. HTTP1_only;
  12452. handle_file_based_request(conn, path, &file);
  12453. return;
  12454. }
  12455. /* 11. Handle put/delete/mkcol requests */
  12456. if (is_put_or_delete_request) {
  12457. HTTP1_only;
  12458. /* 11.1. PUT method */
  12459. if (!strcmp(ri->request_method, "PUT")) {
  12460. put_file(conn, path);
  12461. return;
  12462. }
  12463. /* 11.2. DELETE method */
  12464. if (!strcmp(ri->request_method, "DELETE")) {
  12465. delete_file(conn, path);
  12466. return;
  12467. }
  12468. /* 11.3. MKCOL method */
  12469. if (!strcmp(ri->request_method, "MKCOL")) {
  12470. mkcol(conn, path);
  12471. return;
  12472. }
  12473. /* 11.4. PATCH method
  12474. * This method is not supported for static resources,
  12475. * only for scripts (Lua, CGI) and callbacks. */
  12476. mg_send_http_error(conn,
  12477. 405,
  12478. "%s method not allowed",
  12479. conn->request_info.request_method);
  12480. return;
  12481. }
  12482. /* 11. File does not exist, or it was configured that it should be
  12483. * hidden */
  12484. if (!is_found || (must_hide_file(conn, path))) {
  12485. mg_send_http_error(conn, 404, "%s", "Not found");
  12486. return;
  12487. }
  12488. /* 12. Directory uris should end with a slash */
  12489. if (file.stat.is_directory && (uri_len > 0)
  12490. && (ri->local_uri[uri_len - 1] != '/')) {
  12491. size_t len = strlen(ri->request_uri);
  12492. char *new_path = mg_malloc_ctx(len + 2, conn->phys_ctx);
  12493. if (!new_path) {
  12494. mg_send_http_error(conn, 500, "out or memory");
  12495. } else {
  12496. memcpy(new_path, ri->request_uri, len);
  12497. new_path[len] = '/';
  12498. new_path[len + 1] = 0;
  12499. mg_send_http_redirect(conn, new_path, 301);
  12500. }
  12501. return;
  12502. }
  12503. /* 13. Handle other methods than GET/HEAD */
  12504. /* 13.1. Handle PROPFIND */
  12505. if (!strcmp(ri->request_method, "PROPFIND")) {
  12506. handle_propfind(conn, path, &file.stat);
  12507. return;
  12508. }
  12509. /* 13.2. Handle OPTIONS for files */
  12510. if (!strcmp(ri->request_method, "OPTIONS")) {
  12511. /* This standard handler is only used for real files.
  12512. * Scripts should support the OPTIONS method themselves, to allow a
  12513. * maximum flexibility.
  12514. * Lua and CGI scripts may fully support CORS this way (including
  12515. * preflights). */
  12516. send_options(conn);
  12517. return;
  12518. }
  12519. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12520. if ((0 != strcmp(ri->request_method, "GET"))
  12521. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12522. mg_send_http_error(conn,
  12523. 405,
  12524. "%s method not allowed",
  12525. conn->request_info.request_method);
  12526. return;
  12527. }
  12528. /* 14. directories */
  12529. if (file.stat.is_directory) {
  12530. /* Substitute files have already been handled above. */
  12531. /* Here we can either generate and send a directory listing,
  12532. * or send an "access denied" error. */
  12533. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12534. "yes")) {
  12535. handle_directory_request(conn, path);
  12536. } else {
  12537. mg_send_http_error(conn,
  12538. 403,
  12539. "%s",
  12540. "Error: Directory listing denied");
  12541. }
  12542. return;
  12543. }
  12544. /* 15. SSI files */
  12545. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12546. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12547. path)
  12548. > 0) {
  12549. if (is_in_script_path(conn, path)) {
  12550. handle_ssi_file_request(conn, path, &file);
  12551. } else {
  12552. /* Script was in an illegal path */
  12553. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12554. }
  12555. return;
  12556. }
  12557. /* 16. Static file - maybe cached */
  12558. #if !defined(NO_CACHING)
  12559. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12560. /* Send 304 "Not Modified" - this must not send any body data */
  12561. handle_not_modified_static_file_request(conn, &file);
  12562. return;
  12563. }
  12564. #endif /* !NO_CACHING */
  12565. /* 17. Static file - not cached */
  12566. handle_static_file_request(conn, path, &file, NULL, NULL);
  12567. #endif /* !defined(NO_FILES) */
  12568. }
  12569. #if !defined(NO_FILESYSTEMS)
  12570. static void
  12571. handle_file_based_request(struct mg_connection *conn,
  12572. const char *path,
  12573. struct mg_file *file)
  12574. {
  12575. if (!conn || !conn->dom_ctx) {
  12576. return;
  12577. }
  12578. if (0) {
  12579. #if defined(USE_LUA)
  12580. } else if (match_prefix_strlen(
  12581. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS], path)
  12582. > 0) {
  12583. if (is_in_script_path(conn, path)) {
  12584. /* Lua server page: an SSI like page containing mostly plain
  12585. * html code plus some tags with server generated contents. */
  12586. handle_lsp_request(conn, path, file, NULL);
  12587. } else {
  12588. /* Script was in an illegal path */
  12589. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12590. }
  12591. } else if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12592. path)
  12593. > 0) {
  12594. if (is_in_script_path(conn, path)) {
  12595. /* Lua in-server module script: a CGI like script used to
  12596. * generate
  12597. * the
  12598. * entire reply. */
  12599. mg_exec_lua_script(conn, path, NULL);
  12600. } else {
  12601. /* Script was in an illegal path */
  12602. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12603. }
  12604. #endif
  12605. #if defined(USE_DUKTAPE)
  12606. } else if (match_prefix_strlen(
  12607. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS], path)
  12608. > 0) {
  12609. if (is_in_script_path(conn, path)) {
  12610. /* Call duktape to generate the page */
  12611. mg_exec_duktape_script(conn, path);
  12612. } else {
  12613. /* Script was in an illegal path */
  12614. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12615. }
  12616. #endif
  12617. #if !defined(NO_CGI)
  12618. } else if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], path)
  12619. > 0) {
  12620. if (is_in_script_path(conn, path)) {
  12621. /* CGI scripts may support all HTTP methods */
  12622. handle_cgi_request(conn, path);
  12623. } else {
  12624. /* Script was in an illegal path */
  12625. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12626. }
  12627. #endif /* !NO_CGI */
  12628. } else if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  12629. > 0) {
  12630. if (is_in_script_path(conn, path)) {
  12631. handle_ssi_file_request(conn, path, file);
  12632. } else {
  12633. /* Script was in an illegal path */
  12634. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12635. }
  12636. #if !defined(NO_CACHING)
  12637. } else if ((!conn->in_error_handler)
  12638. && is_not_modified(conn, &file->stat)) {
  12639. /* Send 304 "Not Modified" - this must not send any body data */
  12640. handle_not_modified_static_file_request(conn, file);
  12641. #endif /* !NO_CACHING */
  12642. } else {
  12643. handle_static_file_request(conn, path, file, NULL, NULL);
  12644. }
  12645. }
  12646. #endif /* NO_FILESYSTEMS */
  12647. static void
  12648. close_all_listening_sockets(struct mg_context *ctx)
  12649. {
  12650. unsigned int i;
  12651. if (!ctx) {
  12652. return;
  12653. }
  12654. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12655. closesocket(ctx->listening_sockets[i].sock);
  12656. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12657. }
  12658. mg_free(ctx->listening_sockets);
  12659. ctx->listening_sockets = NULL;
  12660. mg_free(ctx->listening_socket_fds);
  12661. ctx->listening_socket_fds = NULL;
  12662. }
  12663. /* Valid listening port specification is: [ip_address:]port[s]
  12664. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12665. * Examples for IPv6: [::]:80, [::1]:80,
  12666. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12667. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12668. * In order to bind to both, IPv4 and IPv6, you can either add
  12669. * both ports using 8080,[::]:8080, or the short form +8080.
  12670. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12671. * one only accepting IPv4 the other only IPv6. +8080 creates
  12672. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12673. * environment, they might work differently, or might not work
  12674. * at all - it must be tested what options work best in the
  12675. * relevant network environment.
  12676. */
  12677. static int
  12678. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12679. {
  12680. unsigned int a, b, c, d;
  12681. unsigned port;
  12682. unsigned long portUL;
  12683. int ch, len;
  12684. const char *cb;
  12685. char *endptr;
  12686. #if defined(USE_IPV6)
  12687. char buf[100] = {0};
  12688. #endif
  12689. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12690. * Also, all-zeroes in the socket address means binding to all addresses
  12691. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12692. memset(so, 0, sizeof(*so));
  12693. so->lsa.sin.sin_family = AF_INET;
  12694. *ip_version = 0;
  12695. /* Initialize len as invalid. */
  12696. port = 0;
  12697. len = 0;
  12698. /* Test for different ways to format this string */
  12699. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12700. == 5) {
  12701. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12702. so->lsa.sin.sin_addr.s_addr =
  12703. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12704. so->lsa.sin.sin_port = htons((uint16_t)port);
  12705. *ip_version = 4;
  12706. #if defined(USE_IPV6)
  12707. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12708. && ((size_t)len <= vec->len)
  12709. && mg_inet_pton(
  12710. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12711. /* IPv6 address, examples: see above */
  12712. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12713. */
  12714. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12715. *ip_version = 6;
  12716. #endif
  12717. } else if ((vec->ptr[0] == '+')
  12718. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12719. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12720. /* Add 1 to len for the + character we skipped before */
  12721. len++;
  12722. #if defined(USE_IPV6)
  12723. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12724. so->lsa.sin6.sin6_family = AF_INET6;
  12725. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12726. *ip_version = 4 + 6;
  12727. #else
  12728. /* Bind to IPv4 only, since IPv6 is not built in. */
  12729. so->lsa.sin.sin_port = htons((uint16_t)port);
  12730. *ip_version = 4;
  12731. #endif
  12732. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12733. && (vec->ptr != endptr)) {
  12734. len = (int)(endptr - vec->ptr);
  12735. port = (uint16_t)portUL;
  12736. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12737. so->lsa.sin.sin_port = htons((uint16_t)port);
  12738. *ip_version = 4;
  12739. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12740. /* String could be a hostname. This check algotithm
  12741. * will only work for RFC 952 compliant hostnames,
  12742. * starting with a letter, containing only letters,
  12743. * digits and hyphen ('-'). Newer specs may allow
  12744. * more, but this is not guaranteed here, since it
  12745. * may interfere with rules for port option lists. */
  12746. /* According to RFC 1035, hostnames are restricted to 255 characters
  12747. * in total (63 between two dots). */
  12748. char hostname[256];
  12749. size_t hostnlen = (size_t)(cb - vec->ptr);
  12750. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12751. /* This would be invalid in any case */
  12752. *ip_version = 0;
  12753. return 0;
  12754. }
  12755. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12756. if (mg_inet_pton(
  12757. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12758. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12759. *ip_version = 4;
  12760. so->lsa.sin.sin_port = htons((uint16_t)port);
  12761. len += (int)(hostnlen + 1);
  12762. } else {
  12763. len = 0;
  12764. }
  12765. #if defined(USE_IPV6)
  12766. } else if (mg_inet_pton(AF_INET6,
  12767. hostname,
  12768. &so->lsa.sin6,
  12769. sizeof(so->lsa.sin6),
  12770. 1)) {
  12771. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12772. *ip_version = 6;
  12773. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12774. len += (int)(hostnlen + 1);
  12775. } else {
  12776. len = 0;
  12777. }
  12778. #endif
  12779. } else {
  12780. len = 0;
  12781. }
  12782. } else {
  12783. /* Parsing failure. */
  12784. len = 0;
  12785. }
  12786. /* sscanf and the option splitting code ensure the following condition
  12787. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12788. if ((len > 0) && is_valid_port(port)
  12789. && (((size_t)len == vec->len) || ((size_t)(len + 1) == vec->len))) {
  12790. /* Next character after the port number */
  12791. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12792. so->is_ssl = (ch == 's');
  12793. so->ssl_redir = (ch == 'r');
  12794. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12795. return 1;
  12796. }
  12797. }
  12798. /* Reset ip_version to 0 if there is an error */
  12799. *ip_version = 0;
  12800. return 0;
  12801. }
  12802. /* Is there any SSL port in use? */
  12803. static int
  12804. is_ssl_port_used(const char *ports)
  12805. {
  12806. if (ports) {
  12807. /* There are several different allowed syntax variants:
  12808. * - "80" for a single port using every network interface
  12809. * - "localhost:80" for a single port using only localhost
  12810. * - "80,localhost:8080" for two ports, one bound to localhost
  12811. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12812. * to IPv4 localhost, one to IPv6 localhost
  12813. * - "+80" use port 80 for IPv4 and IPv6
  12814. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12815. * for both: IPv4 and IPv4
  12816. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12817. * additionally port 8080 bound to localhost connections
  12818. *
  12819. * If we just look for 's' anywhere in the string, "localhost:80"
  12820. * will be detected as SSL (false positive).
  12821. * Looking for 's' after a digit may cause false positives in
  12822. * "my24service:8080".
  12823. * Looking from 's' backward if there are only ':' and numbers
  12824. * before will not work for "24service:8080" (non SSL, port 8080)
  12825. * or "24s" (SSL, port 24).
  12826. *
  12827. * Remark: Initially hostnames were not allowed to start with a
  12828. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12829. * Section 2.1).
  12830. *
  12831. * To get this correct, the entire string must be parsed as a whole,
  12832. * reading it as a list element for element and parsing with an
  12833. * algorithm equivalent to parse_port_string.
  12834. *
  12835. * In fact, we use local interface names here, not arbitrary
  12836. * hostnames, so in most cases the only name will be "localhost".
  12837. *
  12838. * So, for now, we use this simple algorithm, that may still return
  12839. * a false positive in bizarre cases.
  12840. */
  12841. int i;
  12842. int portslen = (int)strlen(ports);
  12843. char prevIsNumber = 0;
  12844. for (i = 0; i < portslen; i++) {
  12845. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12846. return 1;
  12847. }
  12848. if (ports[i] >= '0' && ports[i] <= '9') {
  12849. prevIsNumber = 1;
  12850. } else {
  12851. prevIsNumber = 0;
  12852. }
  12853. }
  12854. }
  12855. return 0;
  12856. }
  12857. static int
  12858. set_ports_option(struct mg_context *phys_ctx)
  12859. {
  12860. const char *list;
  12861. int on = 1;
  12862. #if defined(USE_IPV6)
  12863. int off = 0;
  12864. #endif
  12865. struct vec vec;
  12866. struct socket so, *ptr;
  12867. struct mg_pollfd *pfd;
  12868. union usa usa;
  12869. socklen_t len;
  12870. int ip_version;
  12871. int portsTotal = 0;
  12872. int portsOk = 0;
  12873. const char *opt_txt;
  12874. long opt_listen_backlog;
  12875. if (!phys_ctx) {
  12876. return 0;
  12877. }
  12878. memset(&so, 0, sizeof(so));
  12879. memset(&usa, 0, sizeof(usa));
  12880. len = sizeof(usa);
  12881. list = phys_ctx->dd.config[LISTENING_PORTS];
  12882. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12883. portsTotal++;
  12884. if (!parse_port_string(&vec, &so, &ip_version)) {
  12885. mg_cry_ctx_internal(
  12886. phys_ctx,
  12887. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12888. (int)vec.len,
  12889. vec.ptr,
  12890. portsTotal,
  12891. "[IP_ADDRESS:]PORT[s|r]");
  12892. continue;
  12893. }
  12894. #if !defined(NO_SSL)
  12895. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12896. mg_cry_ctx_internal(phys_ctx,
  12897. "Cannot add SSL socket (entry %i)",
  12898. portsTotal);
  12899. continue;
  12900. }
  12901. #endif
  12902. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12903. == INVALID_SOCKET) {
  12904. mg_cry_ctx_internal(phys_ctx,
  12905. "cannot create socket (entry %i)",
  12906. portsTotal);
  12907. continue;
  12908. }
  12909. #if defined(_WIN32)
  12910. /* Windows SO_REUSEADDR lets many procs binds to a
  12911. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12912. * if someone already has the socket -- DTL */
  12913. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12914. * Windows might need a few seconds before
  12915. * the same port can be used again in the
  12916. * same process, so a short Sleep may be
  12917. * required between mg_stop and mg_start.
  12918. */
  12919. if (setsockopt(so.sock,
  12920. SOL_SOCKET,
  12921. SO_EXCLUSIVEADDRUSE,
  12922. (SOCK_OPT_TYPE)&on,
  12923. sizeof(on))
  12924. != 0) {
  12925. /* Set reuse option, but don't abort on errors. */
  12926. mg_cry_ctx_internal(
  12927. phys_ctx,
  12928. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12929. portsTotal);
  12930. }
  12931. #else
  12932. if (setsockopt(so.sock,
  12933. SOL_SOCKET,
  12934. SO_REUSEADDR,
  12935. (SOCK_OPT_TYPE)&on,
  12936. sizeof(on))
  12937. != 0) {
  12938. /* Set reuse option, but don't abort on errors. */
  12939. mg_cry_ctx_internal(
  12940. phys_ctx,
  12941. "cannot set socket option SO_REUSEADDR (entry %i)",
  12942. portsTotal);
  12943. }
  12944. #endif
  12945. if (ip_version > 4) {
  12946. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12947. #if defined(USE_IPV6)
  12948. if (ip_version > 6) {
  12949. if (so.lsa.sa.sa_family == AF_INET6
  12950. && setsockopt(so.sock,
  12951. IPPROTO_IPV6,
  12952. IPV6_V6ONLY,
  12953. (void *)&off,
  12954. sizeof(off))
  12955. != 0) {
  12956. /* Set IPv6 only option, but don't abort on errors. */
  12957. mg_cry_ctx_internal(phys_ctx,
  12958. "cannot set socket option "
  12959. "IPV6_V6ONLY=off (entry %i)",
  12960. portsTotal);
  12961. }
  12962. } else {
  12963. if (so.lsa.sa.sa_family == AF_INET6
  12964. && setsockopt(so.sock,
  12965. IPPROTO_IPV6,
  12966. IPV6_V6ONLY,
  12967. (void *)&on,
  12968. sizeof(on))
  12969. != 0) {
  12970. /* Set IPv6 only option, but don't abort on errors. */
  12971. mg_cry_ctx_internal(phys_ctx,
  12972. "cannot set socket option "
  12973. "IPV6_V6ONLY=on (entry %i)",
  12974. portsTotal);
  12975. }
  12976. }
  12977. #else
  12978. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12979. closesocket(so.sock);
  12980. so.sock = INVALID_SOCKET;
  12981. continue;
  12982. #endif
  12983. }
  12984. if (so.lsa.sa.sa_family == AF_INET) {
  12985. len = sizeof(so.lsa.sin);
  12986. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12987. mg_cry_ctx_internal(phys_ctx,
  12988. "cannot bind to %.*s: %d (%s)",
  12989. (int)vec.len,
  12990. vec.ptr,
  12991. (int)ERRNO,
  12992. strerror(errno));
  12993. closesocket(so.sock);
  12994. so.sock = INVALID_SOCKET;
  12995. continue;
  12996. }
  12997. }
  12998. #if defined(USE_IPV6)
  12999. else if (so.lsa.sa.sa_family == AF_INET6) {
  13000. len = sizeof(so.lsa.sin6);
  13001. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13002. mg_cry_ctx_internal(phys_ctx,
  13003. "cannot bind to IPv6 %.*s: %d (%s)",
  13004. (int)vec.len,
  13005. vec.ptr,
  13006. (int)ERRNO,
  13007. strerror(errno));
  13008. closesocket(so.sock);
  13009. so.sock = INVALID_SOCKET;
  13010. continue;
  13011. }
  13012. }
  13013. #endif
  13014. else {
  13015. mg_cry_ctx_internal(
  13016. phys_ctx,
  13017. "cannot bind: address family not supported (entry %i)",
  13018. portsTotal);
  13019. closesocket(so.sock);
  13020. so.sock = INVALID_SOCKET;
  13021. continue;
  13022. }
  13023. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13024. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13025. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13026. mg_cry_ctx_internal(phys_ctx,
  13027. "%s value \"%s\" is invalid",
  13028. config_options[LISTEN_BACKLOG_SIZE].name,
  13029. opt_txt);
  13030. closesocket(so.sock);
  13031. so.sock = INVALID_SOCKET;
  13032. continue;
  13033. }
  13034. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13035. mg_cry_ctx_internal(phys_ctx,
  13036. "cannot listen to %.*s: %d (%s)",
  13037. (int)vec.len,
  13038. vec.ptr,
  13039. (int)ERRNO,
  13040. strerror(errno));
  13041. closesocket(so.sock);
  13042. so.sock = INVALID_SOCKET;
  13043. continue;
  13044. }
  13045. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13046. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13047. int err = (int)ERRNO;
  13048. mg_cry_ctx_internal(phys_ctx,
  13049. "call to getsockname failed %.*s: %d (%s)",
  13050. (int)vec.len,
  13051. vec.ptr,
  13052. err,
  13053. strerror(errno));
  13054. closesocket(so.sock);
  13055. so.sock = INVALID_SOCKET;
  13056. continue;
  13057. }
  13058. /* Update lsa port in case of random free ports */
  13059. #if defined(USE_IPV6)
  13060. if (so.lsa.sa.sa_family == AF_INET6) {
  13061. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13062. } else
  13063. #endif
  13064. {
  13065. so.lsa.sin.sin_port = usa.sin.sin_port;
  13066. }
  13067. if ((ptr = (struct socket *)
  13068. mg_realloc_ctx(phys_ctx->listening_sockets,
  13069. (phys_ctx->num_listening_sockets + 1)
  13070. * sizeof(phys_ctx->listening_sockets[0]),
  13071. phys_ctx))
  13072. == NULL) {
  13073. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13074. closesocket(so.sock);
  13075. so.sock = INVALID_SOCKET;
  13076. continue;
  13077. }
  13078. if ((pfd = (struct mg_pollfd *)
  13079. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13080. (phys_ctx->num_listening_sockets + 1)
  13081. * sizeof(phys_ctx->listening_socket_fds[0]),
  13082. phys_ctx))
  13083. == NULL) {
  13084. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13085. closesocket(so.sock);
  13086. so.sock = INVALID_SOCKET;
  13087. mg_free(ptr);
  13088. continue;
  13089. }
  13090. set_close_on_exec(so.sock, NULL, phys_ctx);
  13091. phys_ctx->listening_sockets = ptr;
  13092. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13093. phys_ctx->listening_socket_fds = pfd;
  13094. phys_ctx->num_listening_sockets++;
  13095. portsOk++;
  13096. }
  13097. if (portsOk != portsTotal) {
  13098. close_all_listening_sockets(phys_ctx);
  13099. portsOk = 0;
  13100. }
  13101. return portsOk;
  13102. }
  13103. static const char *
  13104. header_val(const struct mg_connection *conn, const char *header)
  13105. {
  13106. const char *header_value;
  13107. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13108. return "-";
  13109. } else {
  13110. return header_value;
  13111. }
  13112. }
  13113. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13114. static void log_access(const struct mg_connection *conn);
  13115. #include "external_log_access.inl"
  13116. #elif !defined(NO_FILESYSTEMS)
  13117. static void
  13118. log_access(const struct mg_connection *conn)
  13119. {
  13120. const struct mg_request_info *ri;
  13121. struct mg_file fi;
  13122. char date[64], src_addr[IP_ADDR_STR_LEN];
  13123. struct tm *tm;
  13124. const char *referer;
  13125. const char *user_agent;
  13126. char buf[4096];
  13127. if (!conn || !conn->dom_ctx) {
  13128. return;
  13129. }
  13130. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13131. if (mg_fopen(conn,
  13132. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13133. MG_FOPEN_MODE_APPEND,
  13134. &fi)
  13135. == 0) {
  13136. fi.access.fp = NULL;
  13137. }
  13138. } else {
  13139. fi.access.fp = NULL;
  13140. }
  13141. /* Log is written to a file and/or a callback. If both are not set,
  13142. * executing the rest of the function is pointless. */
  13143. if ((fi.access.fp == NULL)
  13144. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13145. return;
  13146. }
  13147. tm = localtime(&conn->conn_birth_time);
  13148. if (tm != NULL) {
  13149. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13150. } else {
  13151. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13152. date[sizeof(date) - 1] = '\0';
  13153. }
  13154. ri = &conn->request_info;
  13155. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13156. referer = header_val(conn, "Referer");
  13157. user_agent = header_val(conn, "User-Agent");
  13158. mg_snprintf(conn,
  13159. NULL, /* Ignore truncation in access log */
  13160. buf,
  13161. sizeof(buf),
  13162. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13163. src_addr,
  13164. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13165. date,
  13166. ri->request_method ? ri->request_method : "-",
  13167. ri->request_uri ? ri->request_uri : "-",
  13168. ri->query_string ? "?" : "",
  13169. ri->query_string ? ri->query_string : "",
  13170. ri->http_version,
  13171. conn->status_code,
  13172. conn->num_bytes_sent,
  13173. referer,
  13174. user_agent);
  13175. if (conn->phys_ctx->callbacks.log_access) {
  13176. conn->phys_ctx->callbacks.log_access(conn, buf);
  13177. }
  13178. if (fi.access.fp) {
  13179. int ok = 1;
  13180. flockfile(fi.access.fp);
  13181. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13182. ok = 0;
  13183. }
  13184. if (fflush(fi.access.fp) != 0) {
  13185. ok = 0;
  13186. }
  13187. funlockfile(fi.access.fp);
  13188. if (mg_fclose(&fi.access) != 0) {
  13189. ok = 0;
  13190. }
  13191. if (!ok) {
  13192. mg_cry_internal(conn,
  13193. "Error writing log file %s",
  13194. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13195. }
  13196. }
  13197. }
  13198. #else
  13199. #error Must either enable filesystems or provide a custom log_access implementation
  13200. #endif /* Externally provided function */
  13201. /* Verify given socket address against the ACL.
  13202. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13203. */
  13204. static int
  13205. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13206. {
  13207. int allowed, flag, matched;
  13208. struct vec vec;
  13209. if (phys_ctx) {
  13210. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13211. /* If any ACL is set, deny by default */
  13212. allowed = (list == NULL) ? '+' : '-';
  13213. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13214. flag = vec.ptr[0];
  13215. matched = -1;
  13216. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13217. vec.ptr++;
  13218. vec.len--;
  13219. matched = parse_match_net(&vec, sa, 1);
  13220. }
  13221. if (matched < 0) {
  13222. mg_cry_ctx_internal(phys_ctx,
  13223. "%s: subnet must be [+|-]IP-addr[/x]",
  13224. __func__);
  13225. return -1;
  13226. }
  13227. if (matched) {
  13228. allowed = flag;
  13229. }
  13230. }
  13231. return allowed == '+';
  13232. }
  13233. return -1;
  13234. }
  13235. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13236. static int
  13237. set_uid_option(struct mg_context *phys_ctx)
  13238. {
  13239. int success = 0;
  13240. if (phys_ctx) {
  13241. /* We are currently running as curr_uid. */
  13242. const uid_t curr_uid = getuid();
  13243. /* If set, we want to run as run_as_user. */
  13244. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13245. const struct passwd *to_pw = NULL;
  13246. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13247. /* run_as_user does not exist on the system. We can't proceed
  13248. * further. */
  13249. mg_cry_ctx_internal(phys_ctx,
  13250. "%s: unknown user [%s]",
  13251. __func__,
  13252. run_as_user);
  13253. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13254. /* There was either no request to change user, or we're already
  13255. * running as run_as_user. Nothing else to do.
  13256. */
  13257. success = 1;
  13258. } else {
  13259. /* Valid change request. */
  13260. if (setgid(to_pw->pw_gid) == -1) {
  13261. mg_cry_ctx_internal(phys_ctx,
  13262. "%s: setgid(%s): %s",
  13263. __func__,
  13264. run_as_user,
  13265. strerror(errno));
  13266. } else if (setgroups(0, NULL) == -1) {
  13267. mg_cry_ctx_internal(phys_ctx,
  13268. "%s: setgroups(): %s",
  13269. __func__,
  13270. strerror(errno));
  13271. } else if (setuid(to_pw->pw_uid) == -1) {
  13272. mg_cry_ctx_internal(phys_ctx,
  13273. "%s: setuid(%s): %s",
  13274. __func__,
  13275. run_as_user,
  13276. strerror(errno));
  13277. } else {
  13278. success = 1;
  13279. }
  13280. }
  13281. }
  13282. return success;
  13283. }
  13284. #endif /* !_WIN32 */
  13285. static void
  13286. tls_dtor(void *key)
  13287. {
  13288. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13289. /* key == pthread_getspecific(sTlsKey); */
  13290. if (tls) {
  13291. if (tls->is_master == 2) {
  13292. tls->is_master = -3; /* Mark memory as dead */
  13293. mg_free(tls);
  13294. }
  13295. }
  13296. pthread_setspecific(sTlsKey, NULL);
  13297. }
  13298. #if !defined(NO_SSL)
  13299. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13300. struct mg_domain_context *dom_ctx,
  13301. const char *pem,
  13302. const char *chain);
  13303. static const char *ssl_error(void);
  13304. static int
  13305. refresh_trust(struct mg_connection *conn)
  13306. {
  13307. struct stat cert_buf;
  13308. int64_t t = 0;
  13309. const char *pem;
  13310. const char *chain;
  13311. int should_verify_peer;
  13312. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13313. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13314. * refresh_trust still can not work. */
  13315. return 0;
  13316. }
  13317. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13318. if (chain == NULL) {
  13319. /* pem is not NULL here */
  13320. chain = pem;
  13321. }
  13322. if (*chain == 0) {
  13323. chain = NULL;
  13324. }
  13325. if (stat(pem, &cert_buf) != -1) {
  13326. t = (int64_t)cert_buf.st_mtime;
  13327. }
  13328. mg_lock_context(conn->phys_ctx);
  13329. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13330. conn->dom_ctx->ssl_cert_last_mtime = t;
  13331. should_verify_peer = 0;
  13332. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13333. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13334. == 0) {
  13335. should_verify_peer = 1;
  13336. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13337. "optional")
  13338. == 0) {
  13339. should_verify_peer = 1;
  13340. }
  13341. }
  13342. if (should_verify_peer) {
  13343. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13344. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13345. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13346. ca_file,
  13347. ca_path)
  13348. != 1) {
  13349. mg_unlock_context(conn->phys_ctx);
  13350. mg_cry_ctx_internal(
  13351. conn->phys_ctx,
  13352. "SSL_CTX_load_verify_locations error: %s "
  13353. "ssl_verify_peer requires setting "
  13354. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13355. "present in "
  13356. "the .conf file?",
  13357. ssl_error());
  13358. return 0;
  13359. }
  13360. }
  13361. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13362. mg_unlock_context(conn->phys_ctx);
  13363. return 0;
  13364. }
  13365. }
  13366. mg_unlock_context(conn->phys_ctx);
  13367. return 1;
  13368. }
  13369. #if defined(OPENSSL_API_1_1)
  13370. #else
  13371. static pthread_mutex_t *ssl_mutexes;
  13372. #endif /* OPENSSL_API_1_1 */
  13373. static int
  13374. sslize(struct mg_connection *conn,
  13375. int (*func)(SSL *),
  13376. const struct mg_client_options *client_options)
  13377. {
  13378. int ret, err;
  13379. int short_trust;
  13380. unsigned timeout = 1024;
  13381. unsigned i;
  13382. if (!conn) {
  13383. return 0;
  13384. }
  13385. short_trust =
  13386. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13387. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13388. if (short_trust) {
  13389. int trust_ret = refresh_trust(conn);
  13390. if (!trust_ret) {
  13391. return trust_ret;
  13392. }
  13393. }
  13394. mg_lock_context(conn->phys_ctx);
  13395. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13396. mg_unlock_context(conn->phys_ctx);
  13397. if (conn->ssl == NULL) {
  13398. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13399. OPENSSL_REMOVE_THREAD_STATE();
  13400. return 0;
  13401. }
  13402. SSL_set_app_data(conn->ssl, (char *)conn);
  13403. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13404. if (ret != 1) {
  13405. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13406. SSL_free(conn->ssl);
  13407. conn->ssl = NULL;
  13408. OPENSSL_REMOVE_THREAD_STATE();
  13409. return 0;
  13410. }
  13411. if (client_options) {
  13412. if (client_options->host_name) {
  13413. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13414. }
  13415. }
  13416. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13417. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13418. /* NOTE: The loop below acts as a back-off, so we can end
  13419. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13420. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13421. if (to >= 0) {
  13422. timeout = (unsigned)to;
  13423. }
  13424. }
  13425. /* SSL functions may fail and require to be called again:
  13426. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13427. * Here "func" could be SSL_connect or SSL_accept. */
  13428. for (i = 0; i <= timeout; i += 50) {
  13429. ERR_clear_error();
  13430. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13431. ret = func(conn->ssl);
  13432. if (ret != 1) {
  13433. err = SSL_get_error(conn->ssl, ret);
  13434. if ((err == SSL_ERROR_WANT_CONNECT)
  13435. || (err == SSL_ERROR_WANT_ACCEPT)
  13436. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13437. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13438. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13439. /* Don't wait if the server is going to be stopped. */
  13440. break;
  13441. }
  13442. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13443. /* Simply retry the function call. */
  13444. mg_sleep(50);
  13445. } else {
  13446. /* Need to retry the function call "later".
  13447. * See https://linux.die.net/man/3/ssl_get_error
  13448. * This is typical for non-blocking sockets. */
  13449. struct mg_pollfd pfd;
  13450. int pollres;
  13451. pfd.fd = conn->client.sock;
  13452. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13453. || (err == SSL_ERROR_WANT_WRITE))
  13454. ? POLLOUT
  13455. : POLLIN;
  13456. pollres =
  13457. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13458. if (pollres < 0) {
  13459. /* Break if error occured (-1)
  13460. * or server shutdown (-2) */
  13461. break;
  13462. }
  13463. }
  13464. } else if (err == SSL_ERROR_SYSCALL) {
  13465. /* This is an IO error. Look at errno. */
  13466. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13467. break;
  13468. } else {
  13469. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13470. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13471. break;
  13472. }
  13473. } else {
  13474. /* success */
  13475. break;
  13476. }
  13477. }
  13478. ERR_clear_error();
  13479. if (ret != 1) {
  13480. SSL_free(conn->ssl);
  13481. conn->ssl = NULL;
  13482. OPENSSL_REMOVE_THREAD_STATE();
  13483. return 0;
  13484. }
  13485. return 1;
  13486. }
  13487. /* Return OpenSSL error message (from CRYPTO lib) */
  13488. static const char *
  13489. ssl_error(void)
  13490. {
  13491. unsigned long err;
  13492. err = ERR_get_error();
  13493. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13494. }
  13495. static int
  13496. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13497. {
  13498. int i;
  13499. const char hexdigit[] = "0123456789abcdef";
  13500. if ((memlen <= 0) || (buflen <= 0)) {
  13501. return 0;
  13502. }
  13503. if (buflen < (3 * memlen)) {
  13504. return 0;
  13505. }
  13506. for (i = 0; i < memlen; i++) {
  13507. if (i > 0) {
  13508. buf[3 * i - 1] = ' ';
  13509. }
  13510. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13511. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13512. }
  13513. buf[3 * memlen - 1] = 0;
  13514. return 1;
  13515. }
  13516. static int
  13517. ssl_get_client_cert_info(const struct mg_connection *conn,
  13518. struct mg_client_cert *client_cert)
  13519. {
  13520. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13521. if (cert) {
  13522. char str_buf[1024];
  13523. unsigned char buf[256];
  13524. char *str_serial = NULL;
  13525. unsigned int ulen;
  13526. int ilen;
  13527. unsigned char *tmp_buf;
  13528. unsigned char *tmp_p;
  13529. /* Handle to algorithm used for fingerprint */
  13530. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13531. /* Get Subject and issuer */
  13532. X509_NAME *subj = X509_get_subject_name(cert);
  13533. X509_NAME *iss = X509_get_issuer_name(cert);
  13534. /* Get serial number */
  13535. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13536. /* Translate serial number to a hex string */
  13537. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13538. if (serial_bn) {
  13539. str_serial = BN_bn2hex(serial_bn);
  13540. BN_free(serial_bn);
  13541. }
  13542. client_cert->serial =
  13543. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13544. /* Translate subject and issuer to a string */
  13545. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13546. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13547. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13548. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13549. /* Calculate SHA1 fingerprint and store as a hex string */
  13550. ulen = 0;
  13551. /* ASN1_digest is deprecated. Do the calculation manually,
  13552. * using EVP_Digest. */
  13553. ilen = i2d_X509(cert, NULL);
  13554. tmp_buf = (ilen > 0)
  13555. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13556. conn->phys_ctx)
  13557. : NULL;
  13558. if (tmp_buf) {
  13559. tmp_p = tmp_buf;
  13560. (void)i2d_X509(cert, &tmp_p);
  13561. if (!EVP_Digest(
  13562. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13563. ulen = 0;
  13564. }
  13565. mg_free(tmp_buf);
  13566. }
  13567. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13568. *str_buf = 0;
  13569. }
  13570. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13571. client_cert->peer_cert = (void *)cert;
  13572. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13573. * see https://linux.die.net/man/3/bn_bn2hex */
  13574. OPENSSL_free(str_serial);
  13575. return 1;
  13576. }
  13577. return 0;
  13578. }
  13579. #if defined(OPENSSL_API_1_1)
  13580. #else
  13581. static void
  13582. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13583. {
  13584. (void)line;
  13585. (void)file;
  13586. if (mode & 1) {
  13587. /* 1 is CRYPTO_LOCK */
  13588. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13589. } else {
  13590. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13591. }
  13592. }
  13593. #endif /* OPENSSL_API_1_1 */
  13594. #if !defined(NO_SSL_DL)
  13595. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13596. static void *
  13597. load_tls_dll(char *ebuf,
  13598. size_t ebuf_len,
  13599. const char *dll_name,
  13600. struct ssl_func *sw,
  13601. int *feature_missing)
  13602. {
  13603. union {
  13604. void *p;
  13605. void (*fp)(void);
  13606. } u;
  13607. void *dll_handle;
  13608. struct ssl_func *fp;
  13609. int ok;
  13610. int truncated = 0;
  13611. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13612. mg_snprintf(NULL,
  13613. NULL, /* No truncation check for ebuf */
  13614. ebuf,
  13615. ebuf_len,
  13616. "%s: cannot load %s",
  13617. __func__,
  13618. dll_name);
  13619. return NULL;
  13620. }
  13621. ok = 1;
  13622. for (fp = sw; fp->name != NULL; fp++) {
  13623. #if defined(_WIN32)
  13624. /* GetProcAddress() returns pointer to function */
  13625. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13626. #else
  13627. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13628. * pointers to function pointers. We need to use a union to make a
  13629. * cast. */
  13630. u.p = dlsym(dll_handle, fp->name);
  13631. #endif /* _WIN32 */
  13632. /* Set pointer (might be NULL) */
  13633. fp->ptr = u.fp;
  13634. if (u.fp == NULL) {
  13635. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13636. if (feature_missing) {
  13637. feature_missing[fp->required]++;
  13638. }
  13639. if (fp->required == TLS_Mandatory) {
  13640. /* Mandatory function is missing */
  13641. if (ok) {
  13642. /* This is the first missing function.
  13643. * Create a new error message. */
  13644. mg_snprintf(NULL,
  13645. &truncated,
  13646. ebuf,
  13647. ebuf_len,
  13648. "%s: %s: cannot find %s",
  13649. __func__,
  13650. dll_name,
  13651. fp->name);
  13652. ok = 0;
  13653. } else {
  13654. /* This is yet anothermissing function.
  13655. * Append existing error message. */
  13656. size_t cur_len = strlen(ebuf);
  13657. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13658. mg_snprintf(NULL,
  13659. &truncated,
  13660. ebuf + cur_len,
  13661. ebuf_len - cur_len - 3,
  13662. ", %s",
  13663. fp->name);
  13664. if (truncated) {
  13665. /* If truncated, add "..." */
  13666. strcat(ebuf, "...");
  13667. }
  13668. }
  13669. }
  13670. }
  13671. }
  13672. }
  13673. if (!ok) {
  13674. (void)dlclose(dll_handle);
  13675. return NULL;
  13676. }
  13677. return dll_handle;
  13678. }
  13679. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13680. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13681. #endif /* NO_SSL_DL */
  13682. #if defined(SSL_ALREADY_INITIALIZED)
  13683. static volatile ptrdiff_t cryptolib_users =
  13684. 1; /* Reference counter for crypto library. */
  13685. #else
  13686. static volatile ptrdiff_t cryptolib_users =
  13687. 0; /* Reference counter for crypto library. */
  13688. #endif
  13689. static int
  13690. initialize_ssl(char *ebuf, size_t ebuf_len)
  13691. {
  13692. #if !defined(OPENSSL_API_1_1)
  13693. int i, num_locks;
  13694. size_t size;
  13695. #endif
  13696. if (ebuf_len > 0) {
  13697. ebuf[0] = 0;
  13698. }
  13699. #if !defined(NO_SSL_DL)
  13700. if (!cryptolib_dll_handle) {
  13701. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13702. cryptolib_dll_handle = load_tls_dll(
  13703. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13704. if (!cryptolib_dll_handle) {
  13705. mg_snprintf(NULL,
  13706. NULL, /* No truncation check for ebuf */
  13707. ebuf,
  13708. ebuf_len,
  13709. "%s: error loading library %s",
  13710. __func__,
  13711. CRYPTO_LIB);
  13712. DEBUG_TRACE("%s", ebuf);
  13713. return 0;
  13714. }
  13715. }
  13716. #endif /* NO_SSL_DL */
  13717. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13718. return 1;
  13719. }
  13720. #if !defined(OPENSSL_API_1_1)
  13721. /* Initialize locking callbacks, needed for thread safety.
  13722. * http://www.openssl.org/support/faq.html#PROG1
  13723. */
  13724. num_locks = CRYPTO_num_locks();
  13725. if (num_locks < 0) {
  13726. num_locks = 0;
  13727. }
  13728. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13729. /* allocate mutex array, if required */
  13730. if (num_locks == 0) {
  13731. /* No mutex array required */
  13732. ssl_mutexes = NULL;
  13733. } else {
  13734. /* Mutex array required - allocate it */
  13735. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13736. /* Check OOM */
  13737. if (ssl_mutexes == NULL) {
  13738. mg_snprintf(NULL,
  13739. NULL, /* No truncation check for ebuf */
  13740. ebuf,
  13741. ebuf_len,
  13742. "%s: cannot allocate mutexes: %s",
  13743. __func__,
  13744. ssl_error());
  13745. DEBUG_TRACE("%s", ebuf);
  13746. return 0;
  13747. }
  13748. /* initialize mutex array */
  13749. for (i = 0; i < num_locks; i++) {
  13750. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13751. mg_snprintf(NULL,
  13752. NULL, /* No truncation check for ebuf */
  13753. ebuf,
  13754. ebuf_len,
  13755. "%s: error initializing mutex %i of %i",
  13756. __func__,
  13757. i,
  13758. num_locks);
  13759. DEBUG_TRACE("%s", ebuf);
  13760. mg_free(ssl_mutexes);
  13761. return 0;
  13762. }
  13763. }
  13764. }
  13765. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13766. CRYPTO_set_id_callback(&mg_current_thread_id);
  13767. #endif /* OPENSSL_API_1_1 */
  13768. #if !defined(NO_SSL_DL)
  13769. if (!ssllib_dll_handle) {
  13770. ssllib_dll_handle =
  13771. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  13772. if (!ssllib_dll_handle) {
  13773. #if !defined(OPENSSL_API_1_1)
  13774. mg_free(ssl_mutexes);
  13775. #endif
  13776. DEBUG_TRACE("%s", ebuf);
  13777. return 0;
  13778. }
  13779. }
  13780. #endif /* NO_SSL_DL */
  13781. #if defined(OPENSSL_API_1_1)
  13782. /* Initialize SSL library */
  13783. OPENSSL_init_ssl(0, NULL);
  13784. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13785. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13786. NULL);
  13787. #else
  13788. /* Initialize SSL library */
  13789. SSL_library_init();
  13790. SSL_load_error_strings();
  13791. #endif
  13792. return 1;
  13793. }
  13794. static int
  13795. ssl_use_pem_file(struct mg_context *phys_ctx,
  13796. struct mg_domain_context *dom_ctx,
  13797. const char *pem,
  13798. const char *chain)
  13799. {
  13800. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13801. mg_cry_ctx_internal(phys_ctx,
  13802. "%s: cannot open certificate file %s: %s",
  13803. __func__,
  13804. pem,
  13805. ssl_error());
  13806. return 0;
  13807. }
  13808. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13809. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13810. mg_cry_ctx_internal(phys_ctx,
  13811. "%s: cannot open private key file %s: %s",
  13812. __func__,
  13813. pem,
  13814. ssl_error());
  13815. return 0;
  13816. }
  13817. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13818. mg_cry_ctx_internal(phys_ctx,
  13819. "%s: certificate and private key do not match: %s",
  13820. __func__,
  13821. pem);
  13822. return 0;
  13823. }
  13824. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13825. * chain files that contain private keys and certificates in
  13826. * SSL_CTX_use_certificate_chain_file.
  13827. * The CivetWeb-Server used pem-Files that contained both information.
  13828. * In order to make wolfSSL work, it is split in two files.
  13829. * One file that contains key and certificate used by the server and
  13830. * an optional chain file for the ssl stack.
  13831. */
  13832. if (chain) {
  13833. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13834. mg_cry_ctx_internal(phys_ctx,
  13835. "%s: cannot use certificate chain file %s: %s",
  13836. __func__,
  13837. chain,
  13838. ssl_error());
  13839. return 0;
  13840. }
  13841. }
  13842. return 1;
  13843. }
  13844. #if defined(OPENSSL_API_1_1)
  13845. static unsigned long
  13846. ssl_get_protocol(int version_id)
  13847. {
  13848. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13849. if (version_id > 0)
  13850. ret |= SSL_OP_NO_SSLv2;
  13851. if (version_id > 1)
  13852. ret |= SSL_OP_NO_SSLv3;
  13853. if (version_id > 2)
  13854. ret |= SSL_OP_NO_TLSv1;
  13855. if (version_id > 3)
  13856. ret |= SSL_OP_NO_TLSv1_1;
  13857. if (version_id > 4)
  13858. ret |= SSL_OP_NO_TLSv1_2;
  13859. #if defined(SSL_OP_NO_TLSv1_3)
  13860. if (version_id > 5)
  13861. ret |= SSL_OP_NO_TLSv1_3;
  13862. #endif
  13863. return ret;
  13864. }
  13865. #else
  13866. static long
  13867. ssl_get_protocol(int version_id)
  13868. {
  13869. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13870. if (version_id > 0)
  13871. ret |= SSL_OP_NO_SSLv2;
  13872. if (version_id > 1)
  13873. ret |= SSL_OP_NO_SSLv3;
  13874. if (version_id > 2)
  13875. ret |= SSL_OP_NO_TLSv1;
  13876. if (version_id > 3)
  13877. ret |= SSL_OP_NO_TLSv1_1;
  13878. if (version_id > 4)
  13879. ret |= SSL_OP_NO_TLSv1_2;
  13880. #if defined(SSL_OP_NO_TLSv1_3)
  13881. if (version_id > 5)
  13882. ret |= SSL_OP_NO_TLSv1_3;
  13883. #endif
  13884. return (long)ret;
  13885. }
  13886. #endif /* OPENSSL_API_1_1 */
  13887. /* SSL callback documentation:
  13888. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13889. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13890. * https://linux.die.net/man/3/ssl_set_info_callback */
  13891. /* Note: There is no "const" for the first argument in the documentation
  13892. * examples, however some (maybe most, but not all) headers of OpenSSL
  13893. * versions / OpenSSL compatibility layers have it. Having a different
  13894. * definition will cause a warning in C and an error in C++. Use "const SSL
  13895. * *", while automatical conversion from "SSL *" works for all compilers,
  13896. * but not other way around */
  13897. static void
  13898. ssl_info_callback(const SSL *ssl, int what, int ret)
  13899. {
  13900. (void)ret;
  13901. if (what & SSL_CB_HANDSHAKE_START) {
  13902. SSL_get_app_data(ssl);
  13903. }
  13904. if (what & SSL_CB_HANDSHAKE_DONE) {
  13905. /* TODO: check for openSSL 1.1 */
  13906. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13907. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13908. }
  13909. }
  13910. static int
  13911. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13912. {
  13913. #if defined(GCC_DIAGNOSTIC)
  13914. #pragma GCC diagnostic push
  13915. #pragma GCC diagnostic ignored "-Wcast-align"
  13916. #endif /* defined(GCC_DIAGNOSTIC) */
  13917. /* We used an aligned pointer in SSL_set_app_data */
  13918. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13919. #if defined(GCC_DIAGNOSTIC)
  13920. #pragma GCC diagnostic pop
  13921. #endif /* defined(GCC_DIAGNOSTIC) */
  13922. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13923. (void)ad;
  13924. (void)arg;
  13925. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13926. DEBUG_ASSERT(0);
  13927. return SSL_TLSEXT_ERR_NOACK;
  13928. }
  13929. conn->dom_ctx = &(conn->phys_ctx->dd);
  13930. /* Old clients (Win XP) will not support SNI. Then, there
  13931. * is no server name available in the request - we can
  13932. * only work with the default certificate.
  13933. * Multiple HTTPS hosts on one IP+port are only possible
  13934. * with a certificate containing all alternative names.
  13935. */
  13936. if ((servername == NULL) || (*servername == 0)) {
  13937. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13938. mg_lock_context(conn->phys_ctx);
  13939. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13940. mg_unlock_context(conn->phys_ctx);
  13941. return SSL_TLSEXT_ERR_NOACK;
  13942. }
  13943. DEBUG_TRACE("TLS connection to host %s", servername);
  13944. while (conn->dom_ctx) {
  13945. if (!mg_strcasecmp(servername,
  13946. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  13947. /* Found matching domain */
  13948. DEBUG_TRACE("TLS domain %s found",
  13949. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  13950. break;
  13951. }
  13952. mg_lock_context(conn->phys_ctx);
  13953. conn->dom_ctx = conn->dom_ctx->next;
  13954. mg_unlock_context(conn->phys_ctx);
  13955. }
  13956. if (conn->dom_ctx == NULL) {
  13957. /* Default domain */
  13958. DEBUG_TRACE("TLS default domain %s used",
  13959. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13960. conn->dom_ctx = &(conn->phys_ctx->dd);
  13961. }
  13962. mg_lock_context(conn->phys_ctx);
  13963. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13964. mg_unlock_context(conn->phys_ctx);
  13965. return SSL_TLSEXT_ERR_OK;
  13966. }
  13967. #ifdef USE_ALPN
  13968. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  13969. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  13970. alpn_proto_list + 3 + 8,
  13971. NULL};
  13972. #if defined(USE_HTTP2)
  13973. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  13974. alpn_proto_list + 3,
  13975. alpn_proto_list + 3 + 8,
  13976. NULL};
  13977. #endif
  13978. static int
  13979. alpn_select_cb(SSL *ssl,
  13980. const unsigned char **out,
  13981. unsigned char *outlen,
  13982. const unsigned char *in,
  13983. unsigned int inlen,
  13984. void *arg)
  13985. {
  13986. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  13987. unsigned int i, j, enable_http2 = 0;
  13988. const char **alpn_proto_order = alpn_proto_order_http1;
  13989. struct mg_workerTLS *tls =
  13990. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  13991. (void)ssl;
  13992. if (tls == NULL) {
  13993. /* Need to store protocol in Thread Local Storage */
  13994. /* If there is no Thread Local Storage, don't use ALPN */
  13995. return SSL_TLSEXT_ERR_NOACK;
  13996. }
  13997. #if defined(USE_HTTP2)
  13998. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  13999. if (enable_http2) {
  14000. alpn_proto_order = alpn_proto_order_http2;
  14001. }
  14002. #endif
  14003. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14004. /* check all accepted protocols in this order */
  14005. const char *alpn_proto = alpn_proto_order[j];
  14006. /* search input for matching protocol */
  14007. for (i = 0; i < inlen; i++) {
  14008. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14009. *out = in + i + 1;
  14010. *outlen = in[i];
  14011. tls->alpn_proto = alpn_proto;
  14012. return SSL_TLSEXT_ERR_OK;
  14013. }
  14014. }
  14015. }
  14016. /* Nothing found */
  14017. return SSL_TLSEXT_ERR_NOACK;
  14018. }
  14019. static int
  14020. next_protos_advertised_cb(SSL *ssl,
  14021. const unsigned char **data,
  14022. unsigned int *len,
  14023. void *arg)
  14024. {
  14025. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14026. *data = (const unsigned char *)alpn_proto_list;
  14027. *len = (unsigned int)strlen((const char *)data);
  14028. (void)ssl;
  14029. (void)dom_ctx;
  14030. return SSL_TLSEXT_ERR_OK;
  14031. }
  14032. static int
  14033. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14034. {
  14035. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14036. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14037. (const unsigned char *)alpn_proto_list,
  14038. alpn_len);
  14039. if (ret != 0) {
  14040. mg_cry_ctx_internal(phys_ctx,
  14041. "SSL_CTX_set_alpn_protos error: %s",
  14042. ssl_error());
  14043. }
  14044. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14045. alpn_select_cb,
  14046. (void *)dom_ctx);
  14047. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14048. next_protos_advertised_cb,
  14049. (void *)dom_ctx);
  14050. return ret;
  14051. }
  14052. #endif
  14053. /* Setup SSL CTX as required by CivetWeb */
  14054. static int
  14055. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14056. struct mg_domain_context *dom_ctx,
  14057. const char *pem,
  14058. const char *chain)
  14059. {
  14060. int callback_ret;
  14061. int should_verify_peer;
  14062. int peer_certificate_optional;
  14063. const char *ca_path;
  14064. const char *ca_file;
  14065. int use_default_verify_paths;
  14066. int verify_depth;
  14067. struct timespec now_mt;
  14068. md5_byte_t ssl_context_id[16];
  14069. md5_state_t md5state;
  14070. int protocol_ver;
  14071. int ssl_cache_timeout;
  14072. #if defined(OPENSSL_API_1_1)
  14073. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14074. mg_cry_ctx_internal(phys_ctx,
  14075. "SSL_CTX_new (server) error: %s",
  14076. ssl_error());
  14077. return 0;
  14078. }
  14079. #else
  14080. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14081. mg_cry_ctx_internal(phys_ctx,
  14082. "SSL_CTX_new (server) error: %s",
  14083. ssl_error());
  14084. return 0;
  14085. }
  14086. #endif /* OPENSSL_API_1_1 */
  14087. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14088. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14089. | SSL_OP_NO_TLSv1_1);
  14090. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14091. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14092. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14093. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14094. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14095. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14096. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14097. #if defined(SSL_OP_NO_RENEGOTIATION)
  14098. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14099. #endif
  14100. #if !defined(NO_SSL_DL)
  14101. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14102. #endif /* NO_SSL_DL */
  14103. /* In SSL documentation examples callback defined without const
  14104. * specifier 'void (*)(SSL *, int, int)' See:
  14105. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14106. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14107. * But in the source code const SSL is used:
  14108. * 'void (*)(const SSL *, int, int)' See:
  14109. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14110. * Problem about wrong documentation described, but not resolved:
  14111. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14112. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14113. * But when compiled with modern C++ compiler, correct const should be
  14114. * provided
  14115. */
  14116. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14117. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14118. ssl_servername_callback);
  14119. /* If a callback has been specified, call it. */
  14120. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14121. ? 0
  14122. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14123. phys_ctx->user_data));
  14124. /* If callback returns 0, civetweb sets up the SSL certificate.
  14125. * If it returns 1, civetweb assumes the calback already did this.
  14126. * If it returns -1, initializing ssl fails. */
  14127. if (callback_ret < 0) {
  14128. mg_cry_ctx_internal(phys_ctx,
  14129. "SSL callback returned error: %i",
  14130. callback_ret);
  14131. return 0;
  14132. }
  14133. if (callback_ret > 0) {
  14134. /* Callback did everything. */
  14135. return 1;
  14136. }
  14137. /* If a domain callback has been specified, call it. */
  14138. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14139. ? 0
  14140. : (phys_ctx->callbacks.init_ssl_domain(
  14141. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14142. dom_ctx->ssl_ctx,
  14143. phys_ctx->user_data));
  14144. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14145. * If it returns 1, civetweb assumes the calback already did this.
  14146. * If it returns -1, initializing ssl fails. */
  14147. if (callback_ret < 0) {
  14148. mg_cry_ctx_internal(phys_ctx,
  14149. "Domain SSL callback returned error: %i",
  14150. callback_ret);
  14151. return 0;
  14152. }
  14153. if (callback_ret > 0) {
  14154. /* Domain callback did everything. */
  14155. return 1;
  14156. }
  14157. /* Use some combination of start time, domain and port as a SSL
  14158. * context ID. This should be unique on the current machine. */
  14159. md5_init(&md5state);
  14160. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14161. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14162. md5_append(&md5state,
  14163. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14164. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14165. md5_append(&md5state,
  14166. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14167. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14168. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14169. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14170. md5_finish(&md5state, ssl_context_id);
  14171. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14172. (unsigned char *)ssl_context_id,
  14173. sizeof(ssl_context_id));
  14174. if (pem != NULL) {
  14175. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14176. return 0;
  14177. }
  14178. }
  14179. /* Should we support client certificates? */
  14180. /* Default is "no". */
  14181. should_verify_peer = 0;
  14182. peer_certificate_optional = 0;
  14183. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14184. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14185. /* Yes, they are mandatory */
  14186. should_verify_peer = 1;
  14187. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14188. "optional")
  14189. == 0) {
  14190. /* Yes, they are optional */
  14191. should_verify_peer = 1;
  14192. peer_certificate_optional = 1;
  14193. }
  14194. }
  14195. use_default_verify_paths =
  14196. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14197. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14198. == 0);
  14199. if (should_verify_peer) {
  14200. ca_path = dom_ctx->config[SSL_CA_PATH];
  14201. ca_file = dom_ctx->config[SSL_CA_FILE];
  14202. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14203. != 1) {
  14204. mg_cry_ctx_internal(phys_ctx,
  14205. "SSL_CTX_load_verify_locations error: %s "
  14206. "ssl_verify_peer requires setting "
  14207. "either ssl_ca_path or ssl_ca_file. "
  14208. "Is any of them present in the "
  14209. ".conf file?",
  14210. ssl_error());
  14211. return 0;
  14212. }
  14213. if (peer_certificate_optional) {
  14214. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14215. } else {
  14216. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14217. SSL_VERIFY_PEER
  14218. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14219. NULL);
  14220. }
  14221. if (use_default_verify_paths
  14222. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14223. mg_cry_ctx_internal(phys_ctx,
  14224. "SSL_CTX_set_default_verify_paths error: %s",
  14225. ssl_error());
  14226. return 0;
  14227. }
  14228. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14229. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14230. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14231. }
  14232. }
  14233. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14234. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14235. dom_ctx->config[SSL_CIPHER_LIST])
  14236. != 1) {
  14237. mg_cry_ctx_internal(phys_ctx,
  14238. "SSL_CTX_set_cipher_list error: %s",
  14239. ssl_error());
  14240. }
  14241. }
  14242. /* SSL session caching */
  14243. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14244. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14245. : 0);
  14246. if (ssl_cache_timeout > 0) {
  14247. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14248. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14249. * default */
  14250. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14251. }
  14252. #ifdef USE_ALPN
  14253. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14254. #if !defined(NO_SSL_DL)
  14255. if (!tls_feature_missing[TLS_ALPN])
  14256. #endif
  14257. {
  14258. init_alpn(phys_ctx, dom_ctx);
  14259. }
  14260. #endif
  14261. return 1;
  14262. }
  14263. /* Check if SSL is required.
  14264. * If so, dynamically load SSL library
  14265. * and set up ctx->ssl_ctx pointer. */
  14266. static int
  14267. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14268. {
  14269. void *ssl_ctx = 0;
  14270. int callback_ret;
  14271. const char *pem;
  14272. const char *chain;
  14273. char ebuf[128];
  14274. if (!phys_ctx) {
  14275. return 0;
  14276. }
  14277. if (!dom_ctx) {
  14278. dom_ctx = &(phys_ctx->dd);
  14279. }
  14280. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14281. /* No SSL port is set. No need to setup SSL. */
  14282. return 1;
  14283. }
  14284. /* Check for external SSL_CTX */
  14285. callback_ret =
  14286. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14287. ? 0
  14288. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14289. phys_ctx->user_data));
  14290. if (callback_ret < 0) {
  14291. /* Callback exists and returns <0: Initializing failed. */
  14292. mg_cry_ctx_internal(phys_ctx,
  14293. "external_ssl_ctx callback returned error: %i",
  14294. callback_ret);
  14295. return 0;
  14296. } else if (callback_ret > 0) {
  14297. /* Callback exists and returns >0: Initializing complete,
  14298. * civetweb should not modify the SSL context. */
  14299. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14300. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14301. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14302. return 0;
  14303. }
  14304. return 1;
  14305. }
  14306. /* If the callback does not exist or return 0, civetweb must initialize
  14307. * the SSL context. Handle "domain" callback next. */
  14308. /* Check for external domain SSL_CTX callback. */
  14309. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14310. ? 0
  14311. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14312. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14313. &ssl_ctx,
  14314. phys_ctx->user_data));
  14315. if (callback_ret < 0) {
  14316. /* Callback < 0: Error. Abort init. */
  14317. mg_cry_ctx_internal(
  14318. phys_ctx,
  14319. "external_ssl_ctx_domain callback returned error: %i",
  14320. callback_ret);
  14321. return 0;
  14322. } else if (callback_ret > 0) {
  14323. /* Callback > 0: Consider init done. */
  14324. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14325. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14326. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14327. return 0;
  14328. }
  14329. return 1;
  14330. }
  14331. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14332. * 0, CivetWeb should continue initializing SSL */
  14333. /* If PEM file is not specified and the init_ssl callbacks
  14334. * are not specified, setup will fail. */
  14335. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14336. && (phys_ctx->callbacks.init_ssl == NULL)
  14337. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14338. /* No certificate and no init_ssl callbacks:
  14339. * Essential data to set up TLS is missing.
  14340. */
  14341. mg_cry_ctx_internal(phys_ctx,
  14342. "Initializing SSL failed: -%s is not set",
  14343. config_options[SSL_CERTIFICATE].name);
  14344. return 0;
  14345. }
  14346. /* If a certificate chain is configured, use it. */
  14347. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14348. if (chain == NULL) {
  14349. /* Default: certificate chain in PEM file */
  14350. chain = pem;
  14351. }
  14352. if ((chain != NULL) && (*chain == 0)) {
  14353. /* If the chain is an empty string, don't use it. */
  14354. chain = NULL;
  14355. }
  14356. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14357. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14358. return 0;
  14359. }
  14360. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14361. }
  14362. static void
  14363. uninitialize_ssl(void)
  14364. {
  14365. #if defined(OPENSSL_API_1_1)
  14366. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14367. /* Shutdown according to
  14368. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14369. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14370. */
  14371. CONF_modules_unload(1);
  14372. #else
  14373. int i;
  14374. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14375. /* Shutdown according to
  14376. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14377. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14378. */
  14379. CRYPTO_set_locking_callback(NULL);
  14380. CRYPTO_set_id_callback(NULL);
  14381. ENGINE_cleanup();
  14382. CONF_modules_unload(1);
  14383. ERR_free_strings();
  14384. EVP_cleanup();
  14385. CRYPTO_cleanup_all_ex_data();
  14386. OPENSSL_REMOVE_THREAD_STATE();
  14387. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14388. pthread_mutex_destroy(&ssl_mutexes[i]);
  14389. }
  14390. mg_free(ssl_mutexes);
  14391. ssl_mutexes = NULL;
  14392. #endif /* OPENSSL_API_1_1 */
  14393. }
  14394. }
  14395. #endif /* !NO_SSL */
  14396. #if !defined(NO_FILESYSTEMS)
  14397. static int
  14398. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14399. {
  14400. if (phys_ctx) {
  14401. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14402. const char *path;
  14403. struct mg_connection fc;
  14404. if (!dom_ctx) {
  14405. dom_ctx = &(phys_ctx->dd);
  14406. }
  14407. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14408. if ((path != NULL)
  14409. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14410. mg_cry_ctx_internal(phys_ctx,
  14411. "Cannot open %s: %s",
  14412. path,
  14413. strerror(ERRNO));
  14414. return 0;
  14415. }
  14416. return 1;
  14417. }
  14418. return 0;
  14419. }
  14420. #endif /* NO_FILESYSTEMS */
  14421. static int
  14422. set_acl_option(struct mg_context *phys_ctx)
  14423. {
  14424. union usa sa;
  14425. memset(&sa, 0, sizeof(sa));
  14426. #if defined(USE_IPV6)
  14427. sa.sin6.sin6_family = AF_INET6;
  14428. #else
  14429. sa.sin.sin_family = AF_INET;
  14430. #endif
  14431. return check_acl(phys_ctx, &sa) != -1;
  14432. }
  14433. static void
  14434. reset_per_request_attributes(struct mg_connection *conn)
  14435. {
  14436. if (!conn) {
  14437. return;
  14438. }
  14439. conn->connection_type =
  14440. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14441. conn->num_bytes_sent = conn->consumed_content = 0;
  14442. conn->path_info = NULL;
  14443. conn->status_code = -1;
  14444. conn->content_len = -1;
  14445. conn->is_chunked = 0;
  14446. conn->must_close = 0;
  14447. conn->request_len = 0;
  14448. conn->throttle = 0;
  14449. conn->accept_gzip = 0;
  14450. conn->response_info.content_length = conn->request_info.content_length = -1;
  14451. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14452. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14453. conn->response_info.status_text = NULL;
  14454. conn->response_info.status_code = 0;
  14455. conn->request_info.remote_user = NULL;
  14456. conn->request_info.request_method = NULL;
  14457. conn->request_info.request_uri = NULL;
  14458. conn->request_info.local_uri = NULL;
  14459. #if defined(MG_LEGACY_INTERFACE)
  14460. /* Legacy before split into local_uri and request_uri */
  14461. conn->request_info.uri = NULL;
  14462. #endif
  14463. }
  14464. static int
  14465. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14466. {
  14467. if (setsockopt(sock,
  14468. IPPROTO_TCP,
  14469. TCP_NODELAY,
  14470. (SOCK_OPT_TYPE)&nodelay_on,
  14471. sizeof(nodelay_on))
  14472. != 0) {
  14473. /* Error */
  14474. return 1;
  14475. }
  14476. /* OK */
  14477. return 0;
  14478. }
  14479. #if !defined(__ZEPHYR__)
  14480. static void
  14481. close_socket_gracefully(struct mg_connection *conn)
  14482. {
  14483. #if defined(_WIN32)
  14484. char buf[MG_BUF_LEN];
  14485. int n;
  14486. #endif
  14487. struct linger linger;
  14488. int error_code = 0;
  14489. int linger_timeout = -2;
  14490. socklen_t opt_len = sizeof(error_code);
  14491. if (!conn) {
  14492. return;
  14493. }
  14494. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14495. * "Note that enabling a nonzero timeout on a nonblocking socket
  14496. * is not recommended.", so set it to blocking now */
  14497. set_blocking_mode(conn->client.sock);
  14498. /* Send FIN to the client */
  14499. shutdown(conn->client.sock, SHUTDOWN_WR);
  14500. #if defined(_WIN32)
  14501. /* Read and discard pending incoming data. If we do not do that and
  14502. * close
  14503. * the socket, the data in the send buffer may be discarded. This
  14504. * behaviour is seen on Windows, when client keeps sending data
  14505. * when server decides to close the connection; then when client
  14506. * does recv() it gets no data back. */
  14507. do {
  14508. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14509. } while (n > 0);
  14510. #endif
  14511. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14512. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14513. }
  14514. /* Set linger option according to configuration */
  14515. if (linger_timeout >= 0) {
  14516. /* Set linger option to avoid socket hanging out after close. This
  14517. * prevent ephemeral port exhaust problem under high QPS. */
  14518. linger.l_onoff = 1;
  14519. #if defined(_MSC_VER)
  14520. #pragma warning(push)
  14521. #pragma warning(disable : 4244)
  14522. #endif
  14523. #if defined(GCC_DIAGNOSTIC)
  14524. #pragma GCC diagnostic push
  14525. #pragma GCC diagnostic ignored "-Wconversion"
  14526. #endif
  14527. /* Data type of linger structure elements may differ,
  14528. * so we don't know what cast we need here.
  14529. * Disable type conversion warnings. */
  14530. linger.l_linger = (linger_timeout + 999) / 1000;
  14531. #if defined(GCC_DIAGNOSTIC)
  14532. #pragma GCC diagnostic pop
  14533. #endif
  14534. #if defined(_MSC_VER)
  14535. #pragma warning(pop)
  14536. #endif
  14537. } else {
  14538. linger.l_onoff = 0;
  14539. linger.l_linger = 0;
  14540. }
  14541. if (linger_timeout < -1) {
  14542. /* Default: don't configure any linger */
  14543. } else if (getsockopt(conn->client.sock,
  14544. SOL_SOCKET,
  14545. SO_ERROR,
  14546. #if defined(_WIN32) /* WinSock uses different data type here */
  14547. (char *)&error_code,
  14548. #else
  14549. &error_code,
  14550. #endif
  14551. &opt_len)
  14552. != 0) {
  14553. /* Cannot determine if socket is already closed. This should
  14554. * not occur and never did in a test. Log an error message
  14555. * and continue. */
  14556. mg_cry_internal(conn,
  14557. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14558. __func__,
  14559. strerror(ERRNO));
  14560. #if defined(_WIN32)
  14561. } else if (error_code == WSAECONNRESET) {
  14562. #else
  14563. } else if (error_code == ECONNRESET) {
  14564. #endif
  14565. /* Socket already closed by client/peer, close socket without linger
  14566. */
  14567. } else {
  14568. /* Set linger timeout */
  14569. if (setsockopt(conn->client.sock,
  14570. SOL_SOCKET,
  14571. SO_LINGER,
  14572. (char *)&linger,
  14573. sizeof(linger))
  14574. != 0) {
  14575. mg_cry_internal(
  14576. conn,
  14577. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14578. __func__,
  14579. linger.l_onoff,
  14580. linger.l_linger,
  14581. strerror(ERRNO));
  14582. }
  14583. }
  14584. /* Now we know that our FIN is ACK-ed, safe to close */
  14585. closesocket(conn->client.sock);
  14586. conn->client.sock = INVALID_SOCKET;
  14587. }
  14588. #endif
  14589. static void
  14590. close_connection(struct mg_connection *conn)
  14591. {
  14592. #if defined(USE_SERVER_STATS)
  14593. conn->conn_state = 6; /* to close */
  14594. #endif
  14595. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14596. if (conn->lua_websocket_state) {
  14597. lua_websocket_close(conn, conn->lua_websocket_state);
  14598. conn->lua_websocket_state = NULL;
  14599. }
  14600. #endif
  14601. mg_lock_connection(conn);
  14602. /* Set close flag, so keep-alive loops will stop */
  14603. conn->must_close = 1;
  14604. /* call the connection_close callback if assigned */
  14605. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14606. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14607. conn->phys_ctx->callbacks.connection_close(conn);
  14608. }
  14609. }
  14610. /* Reset user data, after close callback is called.
  14611. * Do not reuse it. If the user needs a destructor,
  14612. * it must be done in the connection_close callback. */
  14613. mg_set_user_connection_data(conn, NULL);
  14614. #if defined(USE_SERVER_STATS)
  14615. conn->conn_state = 7; /* closing */
  14616. #endif
  14617. #if !defined(NO_SSL)
  14618. if (conn->ssl != NULL) {
  14619. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14620. */
  14621. SSL_shutdown(conn->ssl);
  14622. SSL_free(conn->ssl);
  14623. OPENSSL_REMOVE_THREAD_STATE();
  14624. conn->ssl = NULL;
  14625. }
  14626. #endif
  14627. if (conn->client.sock != INVALID_SOCKET) {
  14628. #if defined(__ZEPHYR__)
  14629. closesocket(conn->client.sock);
  14630. #else
  14631. close_socket_gracefully(conn);
  14632. #endif
  14633. conn->client.sock = INVALID_SOCKET;
  14634. }
  14635. mg_unlock_connection(conn);
  14636. #if defined(USE_SERVER_STATS)
  14637. conn->conn_state = 8; /* closed */
  14638. #endif
  14639. }
  14640. void
  14641. mg_close_connection(struct mg_connection *conn)
  14642. {
  14643. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14644. return;
  14645. }
  14646. #if defined(USE_WEBSOCKET)
  14647. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14648. if (conn->in_websocket_handling) {
  14649. /* Set close flag, so the server thread can exit. */
  14650. conn->must_close = 1;
  14651. return;
  14652. }
  14653. }
  14654. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14655. unsigned int i;
  14656. /* client context: loops must end */
  14657. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14658. conn->must_close = 1;
  14659. /* We need to get the client thread out of the select/recv call
  14660. * here. */
  14661. /* Since we use a sleep quantum of some seconds to check for recv
  14662. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14663. /* join worker thread */
  14664. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14665. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14666. }
  14667. }
  14668. #endif /* defined(USE_WEBSOCKET) */
  14669. close_connection(conn);
  14670. #if !defined(NO_SSL)
  14671. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14672. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14673. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14674. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14675. }
  14676. #endif
  14677. #if defined(USE_WEBSOCKET)
  14678. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14679. mg_free(conn->phys_ctx->worker_threadids);
  14680. (void)pthread_mutex_destroy(&conn->mutex);
  14681. mg_free(conn);
  14682. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14683. (void)pthread_mutex_destroy(&conn->mutex);
  14684. mg_free(conn);
  14685. }
  14686. #else
  14687. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14688. (void)pthread_mutex_destroy(&conn->mutex);
  14689. mg_free(conn);
  14690. }
  14691. #endif /* defined(USE_WEBSOCKET) */
  14692. }
  14693. static struct mg_connection *
  14694. mg_connect_client_impl(const struct mg_client_options *client_options,
  14695. int use_ssl,
  14696. char *ebuf,
  14697. size_t ebuf_len)
  14698. {
  14699. struct mg_connection *conn = NULL;
  14700. SOCKET sock;
  14701. union usa sa;
  14702. struct sockaddr *psa;
  14703. socklen_t len;
  14704. unsigned max_req_size =
  14705. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14706. /* Size of structures, aligned to 8 bytes */
  14707. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14708. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14709. conn =
  14710. (struct mg_connection *)mg_calloc(1,
  14711. conn_size + ctx_size + max_req_size);
  14712. if (conn == NULL) {
  14713. mg_snprintf(NULL,
  14714. NULL, /* No truncation check for ebuf */
  14715. ebuf,
  14716. ebuf_len,
  14717. "calloc(): %s",
  14718. strerror(ERRNO));
  14719. return NULL;
  14720. }
  14721. #if defined(GCC_DIAGNOSTIC)
  14722. #pragma GCC diagnostic push
  14723. #pragma GCC diagnostic ignored "-Wcast-align"
  14724. #endif /* defined(GCC_DIAGNOSTIC) */
  14725. /* conn_size is aligned to 8 bytes */
  14726. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14727. #if defined(GCC_DIAGNOSTIC)
  14728. #pragma GCC diagnostic pop
  14729. #endif /* defined(GCC_DIAGNOSTIC) */
  14730. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14731. conn->buf_size = (int)max_req_size;
  14732. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14733. conn->dom_ctx = &(conn->phys_ctx->dd);
  14734. if (!connect_socket(conn->phys_ctx,
  14735. client_options->host,
  14736. client_options->port,
  14737. use_ssl,
  14738. ebuf,
  14739. ebuf_len,
  14740. &sock,
  14741. &sa)) {
  14742. /* ebuf is set by connect_socket,
  14743. * free all memory and return NULL; */
  14744. mg_free(conn);
  14745. return NULL;
  14746. }
  14747. #if !defined(NO_SSL)
  14748. #if defined(OPENSSL_API_1_1)
  14749. if (use_ssl
  14750. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14751. == NULL) {
  14752. mg_snprintf(NULL,
  14753. NULL, /* No truncation check for ebuf */
  14754. ebuf,
  14755. ebuf_len,
  14756. "SSL_CTX_new error: %s",
  14757. ssl_error());
  14758. closesocket(sock);
  14759. mg_free(conn);
  14760. return NULL;
  14761. }
  14762. #else
  14763. if (use_ssl
  14764. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14765. == NULL) {
  14766. mg_snprintf(NULL,
  14767. NULL, /* No truncation check for ebuf */
  14768. ebuf,
  14769. ebuf_len,
  14770. "SSL_CTX_new error: %s",
  14771. ssl_error());
  14772. closesocket(sock);
  14773. mg_free(conn);
  14774. return NULL;
  14775. }
  14776. #endif /* OPENSSL_API_1_1 */
  14777. #endif /* NO_SSL */
  14778. #if defined(USE_IPV6)
  14779. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14780. : sizeof(conn->client.rsa.sin6);
  14781. psa = (sa.sa.sa_family == AF_INET)
  14782. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14783. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14784. #else
  14785. len = sizeof(conn->client.rsa.sin);
  14786. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14787. #endif
  14788. conn->client.sock = sock;
  14789. conn->client.lsa = sa;
  14790. if (getsockname(sock, psa, &len) != 0) {
  14791. mg_cry_internal(conn,
  14792. "%s: getsockname() failed: %s",
  14793. __func__,
  14794. strerror(ERRNO));
  14795. }
  14796. conn->client.is_ssl = use_ssl ? 1 : 0;
  14797. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14798. mg_snprintf(NULL,
  14799. NULL, /* No truncation check for ebuf */
  14800. ebuf,
  14801. ebuf_len,
  14802. "Can not create mutex");
  14803. #if !defined(NO_SSL)
  14804. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14805. #endif
  14806. closesocket(sock);
  14807. mg_free(conn);
  14808. return NULL;
  14809. }
  14810. #if !defined(NO_SSL)
  14811. if (use_ssl) {
  14812. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14813. * SSL_CTX_set_verify call is needed to switch off server
  14814. * certificate checking, which is off by default in OpenSSL and
  14815. * on in yaSSL. */
  14816. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14817. * SSL_VERIFY_PEER, verify_ssl_server); */
  14818. if (client_options->client_cert) {
  14819. if (!ssl_use_pem_file(conn->phys_ctx,
  14820. conn->dom_ctx,
  14821. client_options->client_cert,
  14822. NULL)) {
  14823. mg_snprintf(NULL,
  14824. NULL, /* No truncation check for ebuf */
  14825. ebuf,
  14826. ebuf_len,
  14827. "Can not use SSL client certificate");
  14828. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14829. closesocket(sock);
  14830. mg_free(conn);
  14831. return NULL;
  14832. }
  14833. }
  14834. if (client_options->server_cert) {
  14835. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14836. client_options->server_cert,
  14837. NULL)
  14838. != 1) {
  14839. mg_cry_internal(conn,
  14840. "SSL_CTX_load_verify_locations error: %s ",
  14841. ssl_error());
  14842. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14843. closesocket(sock);
  14844. mg_free(conn);
  14845. return NULL;
  14846. }
  14847. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14848. } else {
  14849. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14850. }
  14851. if (!sslize(conn, SSL_connect, client_options)) {
  14852. mg_snprintf(NULL,
  14853. NULL, /* No truncation check for ebuf */
  14854. ebuf,
  14855. ebuf_len,
  14856. "SSL connection error");
  14857. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14858. closesocket(sock);
  14859. mg_free(conn);
  14860. return NULL;
  14861. }
  14862. }
  14863. #endif
  14864. return conn;
  14865. }
  14866. CIVETWEB_API struct mg_connection *
  14867. mg_connect_client_secure(const struct mg_client_options *client_options,
  14868. char *error_buffer,
  14869. size_t error_buffer_size)
  14870. {
  14871. return mg_connect_client_impl(client_options,
  14872. 1,
  14873. error_buffer,
  14874. error_buffer_size);
  14875. }
  14876. struct mg_connection *
  14877. mg_connect_client(const char *host,
  14878. int port,
  14879. int use_ssl,
  14880. char *error_buffer,
  14881. size_t error_buffer_size)
  14882. {
  14883. struct mg_client_options opts;
  14884. memset(&opts, 0, sizeof(opts));
  14885. opts.host = host;
  14886. opts.port = port;
  14887. return mg_connect_client_impl(&opts,
  14888. use_ssl,
  14889. error_buffer,
  14890. error_buffer_size);
  14891. }
  14892. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14893. struct mg_connection *
  14894. mg_connect_client2(const char *host,
  14895. const char *protocol,
  14896. int port,
  14897. const char *path,
  14898. struct mg_init_data *init,
  14899. struct mg_error_data *error)
  14900. {
  14901. int is_ssl, is_ws;
  14902. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14903. if (error != NULL) {
  14904. error->code = 0;
  14905. if (error->text_buffer_size > 0) {
  14906. *error->text = 0;
  14907. }
  14908. }
  14909. if ((host == NULL) || (protocol == NULL)) {
  14910. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14911. mg_snprintf(NULL,
  14912. NULL, /* No truncation check for error buffers */
  14913. error->text,
  14914. error->text_buffer_size,
  14915. "%s",
  14916. "Invalid parameters");
  14917. }
  14918. return NULL;
  14919. }
  14920. /* check all known protocolls */
  14921. if (!mg_strcasecmp(protocol, "http")) {
  14922. is_ssl = 0;
  14923. is_ws = 0;
  14924. } else if (!mg_strcasecmp(protocol, "https")) {
  14925. is_ssl = 1;
  14926. is_ws = 0;
  14927. #if defined(USE_WEBSOCKET)
  14928. } else if (!mg_strcasecmp(protocol, "ws")) {
  14929. is_ssl = 0;
  14930. is_ws = 1;
  14931. } else if (!mg_strcasecmp(protocol, "wss")) {
  14932. is_ssl = 1;
  14933. is_ws = 1;
  14934. #endif
  14935. } else {
  14936. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14937. mg_snprintf(NULL,
  14938. NULL, /* No truncation check for error buffers */
  14939. error->text,
  14940. error->text_buffer_size,
  14941. "Protocol %s not supported",
  14942. protocol);
  14943. }
  14944. return NULL;
  14945. }
  14946. /* TODO: The current implementation here just calls the old
  14947. * implementations, without using any new options. This is just a first
  14948. * step to test the new interfaces. */
  14949. #if defined(USE_WEBSOCKET)
  14950. if (is_ws) {
  14951. /* TODO: implement all options */
  14952. return mg_connect_websocket_client(
  14953. host,
  14954. port,
  14955. is_ssl,
  14956. ((error != NULL) ? error->text : NULL),
  14957. ((error != NULL) ? error->text_buffer_size : 0),
  14958. (path ? path : ""),
  14959. NULL /* TODO: origin */,
  14960. experimental_websocket_client_data_wrapper,
  14961. experimental_websocket_client_close_wrapper,
  14962. (void *)init->callbacks);
  14963. }
  14964. #endif
  14965. /* TODO: all additional options */
  14966. struct mg_client_options opts;
  14967. memset(&opts, 0, sizeof(opts));
  14968. opts.host = host;
  14969. opts.port = port;
  14970. return mg_connect_client_impl(&opts,
  14971. is_ssl,
  14972. ((error != NULL) ? error->text : NULL),
  14973. ((error != NULL) ? error->text_buffer_size
  14974. : 0));
  14975. }
  14976. #endif
  14977. static const struct {
  14978. const char *proto;
  14979. size_t proto_len;
  14980. unsigned default_port;
  14981. } abs_uri_protocols[] = {{"http://", 7, 80},
  14982. {"https://", 8, 443},
  14983. {"ws://", 5, 80},
  14984. {"wss://", 6, 443},
  14985. {NULL, 0, 0}};
  14986. /* Check if the uri is valid.
  14987. * return 0 for invalid uri,
  14988. * return 1 for *,
  14989. * return 2 for relative uri,
  14990. * return 3 for absolute uri without port,
  14991. * return 4 for absolute uri with port */
  14992. static int
  14993. get_uri_type(const char *uri)
  14994. {
  14995. int i;
  14996. const char *hostend, *portbegin;
  14997. char *portend;
  14998. unsigned long port;
  14999. /* According to the HTTP standard
  15000. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15001. * URI can be an asterisk (*) or should start with slash (relative uri),
  15002. * or it should start with the protocol (absolute uri). */
  15003. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15004. /* asterisk */
  15005. return 1;
  15006. }
  15007. /* Valid URIs according to RFC 3986
  15008. * (https://www.ietf.org/rfc/rfc3986.txt)
  15009. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15010. * and unreserved characters A-Z a-z 0-9 and -._~
  15011. * and % encoded symbols.
  15012. */
  15013. for (i = 0; uri[i] != 0; i++) {
  15014. if (uri[i] < 33) {
  15015. /* control characters and spaces are invalid */
  15016. return 0;
  15017. }
  15018. /* Allow everything else here (See #894) */
  15019. }
  15020. /* A relative uri starts with a / character */
  15021. if (uri[0] == '/') {
  15022. /* relative uri */
  15023. return 2;
  15024. }
  15025. /* It could be an absolute uri: */
  15026. /* This function only checks if the uri is valid, not if it is
  15027. * addressing the current server. So civetweb can also be used
  15028. * as a proxy server. */
  15029. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15030. if (mg_strncasecmp(uri,
  15031. abs_uri_protocols[i].proto,
  15032. abs_uri_protocols[i].proto_len)
  15033. == 0) {
  15034. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15035. if (!hostend) {
  15036. return 0;
  15037. }
  15038. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15039. if (!portbegin) {
  15040. return 3;
  15041. }
  15042. port = strtoul(portbegin + 1, &portend, 10);
  15043. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15044. return 0;
  15045. }
  15046. return 4;
  15047. }
  15048. }
  15049. return 0;
  15050. }
  15051. /* Return NULL or the relative uri at the current server */
  15052. static const char *
  15053. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15054. {
  15055. const char *server_domain;
  15056. size_t server_domain_len;
  15057. size_t request_domain_len = 0;
  15058. unsigned long port = 0;
  15059. int i, auth_domain_check_enabled;
  15060. const char *hostbegin = NULL;
  15061. const char *hostend = NULL;
  15062. const char *portbegin;
  15063. char *portend;
  15064. auth_domain_check_enabled =
  15065. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15066. /* DNS is case insensitive, so use case insensitive string compare here
  15067. */
  15068. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15069. if (mg_strncasecmp(uri,
  15070. abs_uri_protocols[i].proto,
  15071. abs_uri_protocols[i].proto_len)
  15072. == 0) {
  15073. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15074. hostend = strchr(hostbegin, '/');
  15075. if (!hostend) {
  15076. return 0;
  15077. }
  15078. portbegin = strchr(hostbegin, ':');
  15079. if ((!portbegin) || (portbegin > hostend)) {
  15080. port = abs_uri_protocols[i].default_port;
  15081. request_domain_len = (size_t)(hostend - hostbegin);
  15082. } else {
  15083. port = strtoul(portbegin + 1, &portend, 10);
  15084. if ((portend != hostend) || (port <= 0)
  15085. || !is_valid_port(port)) {
  15086. return 0;
  15087. }
  15088. request_domain_len = (size_t)(portbegin - hostbegin);
  15089. }
  15090. /* protocol found, port set */
  15091. break;
  15092. }
  15093. }
  15094. if (!port) {
  15095. /* port remains 0 if the protocol is not found */
  15096. return 0;
  15097. }
  15098. /* Check if the request is directed to a different server. */
  15099. /* First check if the port is the same. */
  15100. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15101. /* Request is directed to a different port */
  15102. return 0;
  15103. }
  15104. /* Finally check if the server corresponds to the authentication
  15105. * domain of the server (the server domain).
  15106. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15107. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15108. * but do not allow substrings (like
  15109. * http://notmydomain.com/path/file.ext
  15110. * or http://mydomain.com.fake/path/file.ext).
  15111. */
  15112. if (auth_domain_check_enabled) {
  15113. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15114. server_domain_len = strlen(server_domain);
  15115. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15116. return 0;
  15117. }
  15118. if ((request_domain_len == server_domain_len)
  15119. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15120. /* Request is directed to this server - full name match. */
  15121. } else {
  15122. if (request_domain_len < (server_domain_len + 2)) {
  15123. /* Request is directed to another server: The server name
  15124. * is longer than the request name.
  15125. * Drop this case here to avoid overflows in the
  15126. * following checks. */
  15127. return 0;
  15128. }
  15129. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15130. /* Request is directed to another server: It could be a
  15131. * substring
  15132. * like notmyserver.com */
  15133. return 0;
  15134. }
  15135. if (0
  15136. != memcmp(server_domain,
  15137. hostbegin + request_domain_len - server_domain_len,
  15138. server_domain_len)) {
  15139. /* Request is directed to another server:
  15140. * The server name is different. */
  15141. return 0;
  15142. }
  15143. }
  15144. }
  15145. return hostend;
  15146. }
  15147. static int
  15148. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15149. {
  15150. if (ebuf_len > 0) {
  15151. ebuf[0] = '\0';
  15152. }
  15153. *err = 0;
  15154. reset_per_request_attributes(conn);
  15155. if (!conn) {
  15156. mg_snprintf(conn,
  15157. NULL, /* No truncation check for ebuf */
  15158. ebuf,
  15159. ebuf_len,
  15160. "%s",
  15161. "Internal error");
  15162. *err = 500;
  15163. return 0;
  15164. }
  15165. /* Set the time the request was received. This value should be used for
  15166. * timeouts. */
  15167. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15168. conn->request_len =
  15169. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15170. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15171. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15172. mg_snprintf(conn,
  15173. NULL, /* No truncation check for ebuf */
  15174. ebuf,
  15175. ebuf_len,
  15176. "%s",
  15177. "Invalid message size");
  15178. *err = 500;
  15179. return 0;
  15180. }
  15181. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15182. mg_snprintf(conn,
  15183. NULL, /* No truncation check for ebuf */
  15184. ebuf,
  15185. ebuf_len,
  15186. "%s",
  15187. "Message too large");
  15188. *err = 413;
  15189. return 0;
  15190. }
  15191. if (conn->request_len <= 0) {
  15192. if (conn->data_len > 0) {
  15193. mg_snprintf(conn,
  15194. NULL, /* No truncation check for ebuf */
  15195. ebuf,
  15196. ebuf_len,
  15197. "%s",
  15198. "Malformed message");
  15199. *err = 400;
  15200. } else {
  15201. /* Server did not recv anything -> just close the connection */
  15202. conn->must_close = 1;
  15203. mg_snprintf(conn,
  15204. NULL, /* No truncation check for ebuf */
  15205. ebuf,
  15206. ebuf_len,
  15207. "%s",
  15208. "No data received");
  15209. *err = 0;
  15210. }
  15211. return 0;
  15212. }
  15213. return 1;
  15214. }
  15215. static int
  15216. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15217. {
  15218. const char *cl;
  15219. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15220. return 0;
  15221. }
  15222. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15223. <= 0) {
  15224. mg_snprintf(conn,
  15225. NULL, /* No truncation check for ebuf */
  15226. ebuf,
  15227. ebuf_len,
  15228. "%s",
  15229. "Bad request");
  15230. *err = 400;
  15231. return 0;
  15232. }
  15233. /* Message is a valid request */
  15234. if (!switch_domain_context(conn)) {
  15235. mg_snprintf(conn,
  15236. NULL, /* No truncation check for ebuf */
  15237. ebuf,
  15238. ebuf_len,
  15239. "%s",
  15240. "Bad request: Host mismatch");
  15241. *err = 400;
  15242. return 0;
  15243. }
  15244. if (((cl = get_header(conn->request_info.http_headers,
  15245. conn->request_info.num_headers,
  15246. "Transfer-Encoding"))
  15247. != NULL)
  15248. && mg_strcasecmp(cl, "identity")) {
  15249. if (mg_strcasecmp(cl, "chunked")) {
  15250. mg_snprintf(conn,
  15251. NULL, /* No truncation check for ebuf */
  15252. ebuf,
  15253. ebuf_len,
  15254. "%s",
  15255. "Bad request");
  15256. *err = 400;
  15257. return 0;
  15258. }
  15259. conn->is_chunked = 1;
  15260. conn->content_len = 0; /* not yet read */
  15261. } else if ((cl = get_header(conn->request_info.http_headers,
  15262. conn->request_info.num_headers,
  15263. "Content-Length"))
  15264. != NULL) {
  15265. /* Request has content length set */
  15266. char *endptr = NULL;
  15267. conn->content_len = strtoll(cl, &endptr, 10);
  15268. if ((endptr == cl) || (conn->content_len < 0)) {
  15269. mg_snprintf(conn,
  15270. NULL, /* No truncation check for ebuf */
  15271. ebuf,
  15272. ebuf_len,
  15273. "%s",
  15274. "Bad request");
  15275. *err = 411;
  15276. return 0;
  15277. }
  15278. /* Publish the content length back to the request info. */
  15279. conn->request_info.content_length = conn->content_len;
  15280. } else {
  15281. /* There is no exception, see RFC7230. */
  15282. conn->content_len = 0;
  15283. }
  15284. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15285. return 1;
  15286. }
  15287. /* conn is assumed to be valid in this internal function */
  15288. static int
  15289. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15290. {
  15291. const char *cl;
  15292. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15293. return 0;
  15294. }
  15295. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15296. <= 0) {
  15297. mg_snprintf(conn,
  15298. NULL, /* No truncation check for ebuf */
  15299. ebuf,
  15300. ebuf_len,
  15301. "%s",
  15302. "Bad response");
  15303. *err = 400;
  15304. return 0;
  15305. }
  15306. /* Message is a valid response */
  15307. if (((cl = get_header(conn->response_info.http_headers,
  15308. conn->response_info.num_headers,
  15309. "Transfer-Encoding"))
  15310. != NULL)
  15311. && mg_strcasecmp(cl, "identity")) {
  15312. if (mg_strcasecmp(cl, "chunked")) {
  15313. mg_snprintf(conn,
  15314. NULL, /* No truncation check for ebuf */
  15315. ebuf,
  15316. ebuf_len,
  15317. "%s",
  15318. "Bad request");
  15319. *err = 400;
  15320. return 0;
  15321. }
  15322. conn->is_chunked = 1;
  15323. conn->content_len = 0; /* not yet read */
  15324. } else if ((cl = get_header(conn->response_info.http_headers,
  15325. conn->response_info.num_headers,
  15326. "Content-Length"))
  15327. != NULL) {
  15328. char *endptr = NULL;
  15329. conn->content_len = strtoll(cl, &endptr, 10);
  15330. if ((endptr == cl) || (conn->content_len < 0)) {
  15331. mg_snprintf(conn,
  15332. NULL, /* No truncation check for ebuf */
  15333. ebuf,
  15334. ebuf_len,
  15335. "%s",
  15336. "Bad request");
  15337. *err = 411;
  15338. return 0;
  15339. }
  15340. /* Publish the content length back to the response info. */
  15341. conn->response_info.content_length = conn->content_len;
  15342. /* TODO: check if it is still used in response_info */
  15343. conn->request_info.content_length = conn->content_len;
  15344. /* TODO: we should also consider HEAD method */
  15345. if (conn->response_info.status_code == 304) {
  15346. conn->content_len = 0;
  15347. }
  15348. } else {
  15349. /* TODO: we should also consider HEAD method */
  15350. if (((conn->response_info.status_code >= 100)
  15351. && (conn->response_info.status_code <= 199))
  15352. || (conn->response_info.status_code == 204)
  15353. || (conn->response_info.status_code == 304)) {
  15354. conn->content_len = 0;
  15355. } else {
  15356. conn->content_len = -1; /* unknown content length */
  15357. }
  15358. }
  15359. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15360. return 1;
  15361. }
  15362. int
  15363. mg_get_response(struct mg_connection *conn,
  15364. char *ebuf,
  15365. size_t ebuf_len,
  15366. int timeout)
  15367. {
  15368. int err, ret;
  15369. char txt[32]; /* will not overflow */
  15370. char *save_timeout;
  15371. char *new_timeout;
  15372. if (ebuf_len > 0) {
  15373. ebuf[0] = '\0';
  15374. }
  15375. if (!conn) {
  15376. mg_snprintf(conn,
  15377. NULL, /* No truncation check for ebuf */
  15378. ebuf,
  15379. ebuf_len,
  15380. "%s",
  15381. "Parameter error");
  15382. return -1;
  15383. }
  15384. /* Reset the previous responses */
  15385. conn->data_len = 0;
  15386. /* Implementation of API function for HTTP clients */
  15387. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15388. if (timeout >= 0) {
  15389. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15390. new_timeout = txt;
  15391. } else {
  15392. new_timeout = NULL;
  15393. }
  15394. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15395. ret = get_response(conn, ebuf, ebuf_len, &err);
  15396. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15397. #if defined(MG_LEGACY_INTERFACE)
  15398. /* TODO: 1) uri is deprecated;
  15399. * 2) here, ri.uri is the http response code */
  15400. conn->request_info.uri = conn->request_info.request_uri;
  15401. #endif
  15402. conn->request_info.local_uri = conn->request_info.request_uri;
  15403. /* TODO (mid): Define proper return values - maybe return length?
  15404. * For the first test use <0 for error and >0 for OK */
  15405. return (ret == 0) ? -1 : +1;
  15406. }
  15407. struct mg_connection *
  15408. mg_download(const char *host,
  15409. int port,
  15410. int use_ssl,
  15411. char *ebuf,
  15412. size_t ebuf_len,
  15413. const char *fmt,
  15414. ...)
  15415. {
  15416. struct mg_connection *conn;
  15417. va_list ap;
  15418. int i;
  15419. int reqerr;
  15420. if (ebuf_len > 0) {
  15421. ebuf[0] = '\0';
  15422. }
  15423. va_start(ap, fmt);
  15424. /* open a connection */
  15425. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15426. if (conn != NULL) {
  15427. i = mg_vprintf(conn, fmt, ap);
  15428. if (i <= 0) {
  15429. mg_snprintf(conn,
  15430. NULL, /* No truncation check for ebuf */
  15431. ebuf,
  15432. ebuf_len,
  15433. "%s",
  15434. "Error sending request");
  15435. } else {
  15436. /* make sure the buffer is clear */
  15437. conn->data_len = 0;
  15438. get_response(conn, ebuf, ebuf_len, &reqerr);
  15439. #if defined(MG_LEGACY_INTERFACE)
  15440. /* TODO: 1) uri is deprecated;
  15441. * 2) here, ri.uri is the http response code */
  15442. conn->request_info.uri = conn->request_info.request_uri;
  15443. #endif
  15444. conn->request_info.local_uri = conn->request_info.request_uri;
  15445. }
  15446. }
  15447. /* if an error occurred, close the connection */
  15448. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15449. mg_close_connection(conn);
  15450. conn = NULL;
  15451. }
  15452. va_end(ap);
  15453. return conn;
  15454. }
  15455. struct websocket_client_thread_data {
  15456. struct mg_connection *conn;
  15457. mg_websocket_data_handler data_handler;
  15458. mg_websocket_close_handler close_handler;
  15459. void *callback_data;
  15460. };
  15461. #if defined(USE_WEBSOCKET)
  15462. #if defined(_WIN32)
  15463. static unsigned __stdcall websocket_client_thread(void *data)
  15464. #else
  15465. static void *
  15466. websocket_client_thread(void *data)
  15467. #endif
  15468. {
  15469. struct websocket_client_thread_data *cdata =
  15470. (struct websocket_client_thread_data *)data;
  15471. void *user_thread_ptr = NULL;
  15472. #if !defined(_WIN32)
  15473. struct sigaction sa;
  15474. /* Ignore SIGPIPE */
  15475. memset(&sa, 0, sizeof(sa));
  15476. sa.sa_handler = SIG_IGN;
  15477. sigaction(SIGPIPE, &sa, NULL);
  15478. #endif
  15479. mg_set_thread_name("ws-clnt");
  15480. if (cdata->conn->phys_ctx) {
  15481. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15482. /* 3 indicates a websocket client thread */
  15483. /* TODO: check if conn->phys_ctx can be set */
  15484. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15485. cdata->conn->phys_ctx, 3);
  15486. }
  15487. }
  15488. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15489. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15490. if (cdata->close_handler != NULL) {
  15491. cdata->close_handler(cdata->conn, cdata->callback_data);
  15492. }
  15493. /* The websocket_client context has only this thread. If it runs out,
  15494. set the stop_flag to 2 (= "stopped"). */
  15495. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15496. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15497. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15498. 3,
  15499. user_thread_ptr);
  15500. }
  15501. mg_free((void *)cdata);
  15502. #if defined(_WIN32)
  15503. return 0;
  15504. #else
  15505. return NULL;
  15506. #endif
  15507. }
  15508. #endif
  15509. static struct mg_connection *
  15510. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15511. int use_ssl,
  15512. char *error_buffer,
  15513. size_t error_buffer_size,
  15514. const char *path,
  15515. const char *origin,
  15516. mg_websocket_data_handler data_func,
  15517. mg_websocket_close_handler close_func,
  15518. void *user_data)
  15519. {
  15520. struct mg_connection *conn = NULL;
  15521. #if defined(USE_WEBSOCKET)
  15522. struct websocket_client_thread_data *thread_data;
  15523. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15524. const char *handshake_req;
  15525. const char *host = client_options->host;
  15526. int i;
  15527. if (origin != NULL) {
  15528. handshake_req = "GET %s HTTP/1.1\r\n"
  15529. "Host: %s\r\n"
  15530. "Upgrade: websocket\r\n"
  15531. "Connection: Upgrade\r\n"
  15532. "Sec-WebSocket-Key: %s\r\n"
  15533. "Sec-WebSocket-Version: 13\r\n"
  15534. "Origin: %s\r\n"
  15535. "\r\n";
  15536. } else {
  15537. handshake_req = "GET %s HTTP/1.1\r\n"
  15538. "Host: %s\r\n"
  15539. "Upgrade: websocket\r\n"
  15540. "Connection: Upgrade\r\n"
  15541. "Sec-WebSocket-Key: %s\r\n"
  15542. "Sec-WebSocket-Version: 13\r\n"
  15543. "\r\n";
  15544. }
  15545. #if defined(__clang__)
  15546. #pragma clang diagnostic push
  15547. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15548. #endif
  15549. /* Establish the client connection and request upgrade */
  15550. conn = mg_connect_client_impl(client_options,
  15551. use_ssl,
  15552. error_buffer,
  15553. error_buffer_size);
  15554. if (conn == NULL) {
  15555. /* error_buffer already filled */
  15556. return NULL;
  15557. }
  15558. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15559. if (i <= 0) {
  15560. mg_snprintf(conn,
  15561. NULL, /* No truncation check for ebuf */
  15562. error_buffer,
  15563. error_buffer_size,
  15564. "%s",
  15565. "Error sending request");
  15566. mg_close_connection(conn);
  15567. return NULL;
  15568. }
  15569. conn->data_len = 0;
  15570. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15571. mg_close_connection(conn);
  15572. return NULL;
  15573. }
  15574. conn->request_info.local_uri = conn->request_info.request_uri;
  15575. #if defined(__clang__)
  15576. #pragma clang diagnostic pop
  15577. #endif
  15578. /* Connection object will be null if something goes wrong */
  15579. if (conn == NULL) {
  15580. if (!*error_buffer) {
  15581. /* There should be already an error message */
  15582. mg_snprintf(conn,
  15583. NULL, /* No truncation check for ebuf */
  15584. error_buffer,
  15585. error_buffer_size,
  15586. "Unexpected error");
  15587. }
  15588. return NULL;
  15589. }
  15590. if (conn->response_info.status_code != 101) {
  15591. /* We sent an "upgrade" request. For a correct websocket
  15592. * protocol handshake, we expect a "101 Continue" response.
  15593. * Otherwise it is a protocol violation. Maybe the HTTP
  15594. * Server does not know websockets. */
  15595. if (!*error_buffer) {
  15596. /* set an error, if not yet set */
  15597. mg_snprintf(conn,
  15598. NULL, /* No truncation check for ebuf */
  15599. error_buffer,
  15600. error_buffer_size,
  15601. "Unexpected server reply");
  15602. }
  15603. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15604. mg_close_connection(conn);
  15605. return NULL;
  15606. }
  15607. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15608. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15609. if (!thread_data) {
  15610. DEBUG_TRACE("%s\r\n", "Out of memory");
  15611. mg_close_connection(conn);
  15612. return NULL;
  15613. }
  15614. thread_data->conn = conn;
  15615. thread_data->data_handler = data_func;
  15616. thread_data->close_handler = close_func;
  15617. thread_data->callback_data = user_data;
  15618. conn->phys_ctx->worker_threadids =
  15619. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15620. if (!conn->phys_ctx->worker_threadids) {
  15621. DEBUG_TRACE("%s\r\n", "Out of memory");
  15622. mg_free(thread_data);
  15623. mg_close_connection(conn);
  15624. return NULL;
  15625. }
  15626. /* Now upgrade to ws/wss client context */
  15627. conn->phys_ctx->user_data = user_data;
  15628. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15629. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15630. /* Start a thread to read the websocket client connection
  15631. * This thread will automatically stop when mg_disconnect is
  15632. * called on the client connection */
  15633. if (mg_start_thread_with_id(websocket_client_thread,
  15634. thread_data,
  15635. conn->phys_ctx->worker_threadids)
  15636. != 0) {
  15637. conn->phys_ctx->cfg_worker_threads = 0;
  15638. mg_free(thread_data);
  15639. mg_close_connection(conn);
  15640. conn = NULL;
  15641. DEBUG_TRACE("%s",
  15642. "Websocket client connect thread could not be started\r\n");
  15643. }
  15644. #else
  15645. /* Appease "unused parameter" warnings */
  15646. (void)client_options;
  15647. (void)use_ssl;
  15648. (void)error_buffer;
  15649. (void)error_buffer_size;
  15650. (void)path;
  15651. (void)origin;
  15652. (void)user_data;
  15653. (void)data_func;
  15654. (void)close_func;
  15655. #endif
  15656. return conn;
  15657. }
  15658. struct mg_connection *
  15659. mg_connect_websocket_client(const char *host,
  15660. int port,
  15661. int use_ssl,
  15662. char *error_buffer,
  15663. size_t error_buffer_size,
  15664. const char *path,
  15665. const char *origin,
  15666. mg_websocket_data_handler data_func,
  15667. mg_websocket_close_handler close_func,
  15668. void *user_data)
  15669. {
  15670. struct mg_client_options client_options;
  15671. memset(&client_options, 0, sizeof(client_options));
  15672. client_options.host = host;
  15673. client_options.port = port;
  15674. return mg_connect_websocket_client_impl(&client_options,
  15675. use_ssl,
  15676. error_buffer,
  15677. error_buffer_size,
  15678. path,
  15679. origin,
  15680. data_func,
  15681. close_func,
  15682. user_data);
  15683. }
  15684. struct mg_connection *
  15685. mg_connect_websocket_client_secure(
  15686. const struct mg_client_options *client_options,
  15687. char *error_buffer,
  15688. size_t error_buffer_size,
  15689. const char *path,
  15690. const char *origin,
  15691. mg_websocket_data_handler data_func,
  15692. mg_websocket_close_handler close_func,
  15693. void *user_data)
  15694. {
  15695. if (!client_options) {
  15696. return NULL;
  15697. }
  15698. return mg_connect_websocket_client_impl(client_options,
  15699. 1,
  15700. error_buffer,
  15701. error_buffer_size,
  15702. path,
  15703. origin,
  15704. data_func,
  15705. close_func,
  15706. user_data);
  15707. }
  15708. /* Prepare connection data structure */
  15709. static void
  15710. init_connection(struct mg_connection *conn)
  15711. {
  15712. /* Is keep alive allowed by the server */
  15713. int keep_alive_enabled =
  15714. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15715. if (!keep_alive_enabled) {
  15716. conn->must_close = 1;
  15717. }
  15718. /* Important: on new connection, reset the receiving buffer. Credit
  15719. * goes to crule42. */
  15720. conn->data_len = 0;
  15721. conn->handled_requests = 0;
  15722. conn->connection_type = CONNECTION_TYPE_INVALID;
  15723. mg_set_user_connection_data(conn, NULL);
  15724. #if defined(USE_SERVER_STATS)
  15725. conn->conn_state = 2; /* init */
  15726. #endif
  15727. /* call the init_connection callback if assigned */
  15728. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15729. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15730. void *conn_data = NULL;
  15731. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15732. mg_set_user_connection_data(conn, conn_data);
  15733. }
  15734. }
  15735. }
  15736. /* Process a connection - may handle multiple requests
  15737. * using the same connection.
  15738. * Must be called with a valid connection (conn and
  15739. * conn->phys_ctx must be valid).
  15740. */
  15741. static void
  15742. process_new_connection(struct mg_connection *conn)
  15743. {
  15744. struct mg_request_info *ri = &conn->request_info;
  15745. int keep_alive, discard_len;
  15746. char ebuf[100];
  15747. const char *hostend;
  15748. int reqerr, uri_type;
  15749. #if defined(USE_SERVER_STATS)
  15750. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15751. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15752. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  15753. #endif
  15754. DEBUG_TRACE("Start processing connection from %s",
  15755. conn->request_info.remote_addr);
  15756. /* Loop over multiple requests sent using the same connection
  15757. * (while "keep alive"). */
  15758. do {
  15759. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15760. conn->handled_requests + 1);
  15761. #if defined(USE_SERVER_STATS)
  15762. conn->conn_state = 3; /* ready */
  15763. #endif
  15764. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15765. /* The request sent by the client could not be understood by
  15766. * the server, or it was incomplete or a timeout. Send an
  15767. * error message and close the connection. */
  15768. if (reqerr > 0) {
  15769. DEBUG_ASSERT(ebuf[0] != '\0');
  15770. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15771. }
  15772. } else if (strcmp(ri->http_version, "1.0")
  15773. && strcmp(ri->http_version, "1.1")) {
  15774. /* HTTP/2 is not allowed here */
  15775. mg_snprintf(conn,
  15776. NULL, /* No truncation check for ebuf */
  15777. ebuf,
  15778. sizeof(ebuf),
  15779. "Bad HTTP version: [%s]",
  15780. ri->http_version);
  15781. mg_send_http_error(conn, 505, "%s", ebuf);
  15782. }
  15783. if (ebuf[0] == '\0') {
  15784. uri_type = get_uri_type(conn->request_info.request_uri);
  15785. switch (uri_type) {
  15786. case 1:
  15787. /* Asterisk */
  15788. conn->request_info.local_uri = 0;
  15789. /* TODO: Deal with '*'. */
  15790. break;
  15791. case 2:
  15792. /* relative uri */
  15793. conn->request_info.local_uri = conn->request_info.request_uri;
  15794. break;
  15795. case 3:
  15796. case 4:
  15797. /* absolute uri (with/without port) */
  15798. hostend = get_rel_url_at_current_server(
  15799. conn->request_info.request_uri, conn);
  15800. if (hostend) {
  15801. conn->request_info.local_uri = hostend;
  15802. } else {
  15803. conn->request_info.local_uri = NULL;
  15804. }
  15805. break;
  15806. default:
  15807. mg_snprintf(conn,
  15808. NULL, /* No truncation check for ebuf */
  15809. ebuf,
  15810. sizeof(ebuf),
  15811. "Invalid URI");
  15812. mg_send_http_error(conn, 400, "%s", ebuf);
  15813. conn->request_info.local_uri = NULL;
  15814. break;
  15815. }
  15816. #if defined(MG_LEGACY_INTERFACE)
  15817. /* Legacy before split into local_uri and request_uri */
  15818. conn->request_info.uri = conn->request_info.local_uri;
  15819. #endif
  15820. }
  15821. if (ebuf[0] != '\0') {
  15822. conn->protocol_type = -1;
  15823. } else {
  15824. /* HTTP/1 allows protocol upgrade */
  15825. conn->protocol_type = should_switch_to_protocol(conn);
  15826. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15827. /* This will occur, if a HTTP/1.1 request should be upgraded
  15828. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15829. * Since most (all?) major browsers only support HTTP/2 using
  15830. * ALPN, this is hard to test and very low priority.
  15831. * Deactivate it (at least for now).
  15832. */
  15833. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15834. }
  15835. }
  15836. DEBUG_TRACE("http: %s, error: %s",
  15837. (ri->http_version ? ri->http_version : "none"),
  15838. (ebuf[0] ? ebuf : "none"));
  15839. if (ebuf[0] == '\0') {
  15840. if (conn->request_info.local_uri) {
  15841. /* handle request to local server */
  15842. #if defined(USE_SERVER_STATS)
  15843. conn->conn_state = 4; /* processing */
  15844. #endif
  15845. handle_request(conn);
  15846. #if defined(USE_SERVER_STATS)
  15847. conn->conn_state = 5; /* processed */
  15848. mg_atomic_add64(&(conn->phys_ctx->total_data_read),
  15849. conn->consumed_content);
  15850. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  15851. conn->num_bytes_sent);
  15852. #endif
  15853. DEBUG_TRACE("%s", "handle_request done");
  15854. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15855. conn->phys_ctx->callbacks.end_request(conn,
  15856. conn->status_code);
  15857. DEBUG_TRACE("%s", "end_request callback done");
  15858. }
  15859. log_access(conn);
  15860. /* Response complete. Free header buffer */
  15861. free_buffered_response_header_list(conn);
  15862. } else {
  15863. /* TODO: handle non-local request (PROXY) */
  15864. conn->must_close = 1;
  15865. }
  15866. } else {
  15867. conn->must_close = 1;
  15868. }
  15869. if (ri->remote_user != NULL) {
  15870. mg_free((void *)ri->remote_user);
  15871. /* Important! When having connections with and without auth
  15872. * would cause double free and then crash */
  15873. ri->remote_user = NULL;
  15874. }
  15875. /* NOTE(lsm): order is important here. should_keep_alive() call
  15876. * is using parsed request, which will be invalid after
  15877. * memmove's below.
  15878. * Therefore, memorize should_keep_alive() result now for later
  15879. * use in loop exit condition. */
  15880. /* Enable it only if this request is completely discardable. */
  15881. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  15882. && should_keep_alive(conn) && (conn->content_len >= 0)
  15883. && (conn->request_len > 0)
  15884. && ((conn->is_chunked == 4)
  15885. || (!conn->is_chunked
  15886. && ((conn->consumed_content == conn->content_len)
  15887. || ((conn->request_len + conn->content_len)
  15888. <= conn->data_len))))
  15889. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  15890. if (keep_alive) {
  15891. /* Discard all buffered data for this request */
  15892. discard_len =
  15893. ((conn->request_len + conn->content_len) < conn->data_len)
  15894. ? (int)(conn->request_len + conn->content_len)
  15895. : conn->data_len;
  15896. conn->data_len -= discard_len;
  15897. if (conn->data_len > 0) {
  15898. DEBUG_TRACE("discard_len = %d", discard_len);
  15899. memmove(conn->buf,
  15900. conn->buf + discard_len,
  15901. (size_t)conn->data_len);
  15902. }
  15903. }
  15904. DEBUG_ASSERT(conn->data_len >= 0);
  15905. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15906. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15907. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15908. (long int)conn->data_len,
  15909. (long int)conn->buf_size);
  15910. break;
  15911. }
  15912. conn->handled_requests++;
  15913. } while (keep_alive);
  15914. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15915. conn->request_info.remote_addr,
  15916. difftime(time(NULL), conn->conn_birth_time));
  15917. close_connection(conn);
  15918. #if defined(USE_SERVER_STATS)
  15919. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15920. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15921. #endif
  15922. }
  15923. #if defined(ALTERNATIVE_QUEUE)
  15924. static void
  15925. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15926. {
  15927. unsigned int i;
  15928. while (!ctx->stop_flag) {
  15929. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15930. /* find a free worker slot and signal it */
  15931. if (ctx->client_socks[i].in_use == 2) {
  15932. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15933. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15934. ctx->client_socks[i] = *sp;
  15935. ctx->client_socks[i].in_use = 1;
  15936. /* socket has been moved to the consumer */
  15937. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15938. (void)event_signal(ctx->client_wait_events[i]);
  15939. return;
  15940. }
  15941. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15942. }
  15943. }
  15944. /* queue is full */
  15945. mg_sleep(1);
  15946. }
  15947. /* must consume */
  15948. set_blocking_mode(sp->sock);
  15949. closesocket(sp->sock);
  15950. }
  15951. static int
  15952. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15953. {
  15954. DEBUG_TRACE("%s", "going idle");
  15955. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15956. ctx->client_socks[thread_index].in_use = 2;
  15957. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15958. event_wait(ctx->client_wait_events[thread_index]);
  15959. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15960. *sp = ctx->client_socks[thread_index];
  15961. if (ctx->stop_flag) {
  15962. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15963. if (sp->in_use == 1) {
  15964. /* must consume */
  15965. set_blocking_mode(sp->sock);
  15966. closesocket(sp->sock);
  15967. }
  15968. return 0;
  15969. }
  15970. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15971. if (sp->in_use == 1) {
  15972. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15973. return 1;
  15974. }
  15975. /* must not reach here */
  15976. DEBUG_ASSERT(0);
  15977. return 0;
  15978. }
  15979. #else /* ALTERNATIVE_QUEUE */
  15980. /* Worker threads take accepted socket from the queue */
  15981. static int
  15982. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15983. {
  15984. (void)thread_index;
  15985. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15986. DEBUG_TRACE("%s", "going idle");
  15987. /* If the queue is empty, wait. We're idle at this point. */
  15988. while ((ctx->sq_head == ctx->sq_tail)
  15989. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  15990. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15991. }
  15992. /* If we're stopping, sq_head may be equal to sq_tail. */
  15993. if (ctx->sq_head > ctx->sq_tail) {
  15994. /* Copy socket from the queue and increment tail */
  15995. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  15996. ctx->sq_tail++;
  15997. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15998. /* Wrap pointers if needed */
  15999. while (ctx->sq_tail > ctx->sq_size) {
  16000. ctx->sq_tail -= ctx->sq_size;
  16001. ctx->sq_head -= ctx->sq_size;
  16002. }
  16003. }
  16004. (void)pthread_cond_signal(&ctx->sq_empty);
  16005. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16006. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16007. }
  16008. /* Master thread adds accepted socket to a queue */
  16009. static void
  16010. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16011. {
  16012. int queue_filled;
  16013. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16014. queue_filled = ctx->sq_head - ctx->sq_tail;
  16015. /* If the queue is full, wait */
  16016. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16017. && (queue_filled >= ctx->sq_size)) {
  16018. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16019. #if defined(USE_SERVER_STATS)
  16020. if (queue_filled > ctx->sq_max_fill) {
  16021. ctx->sq_max_fill = queue_filled;
  16022. }
  16023. #endif
  16024. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16025. ctx->sq_blocked = 0; /* Not blocked now */
  16026. queue_filled = ctx->sq_head - ctx->sq_tail;
  16027. }
  16028. if (queue_filled < ctx->sq_size) {
  16029. /* Copy socket to the queue and increment head */
  16030. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16031. ctx->sq_head++;
  16032. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16033. }
  16034. queue_filled = ctx->sq_head - ctx->sq_tail;
  16035. #if defined(USE_SERVER_STATS)
  16036. if (queue_filled > ctx->sq_max_fill) {
  16037. ctx->sq_max_fill = queue_filled;
  16038. }
  16039. #endif
  16040. (void)pthread_cond_signal(&ctx->sq_full);
  16041. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16042. }
  16043. #endif /* ALTERNATIVE_QUEUE */
  16044. static void
  16045. worker_thread_run(struct mg_connection *conn)
  16046. {
  16047. struct mg_context *ctx = conn->phys_ctx;
  16048. int thread_index;
  16049. struct mg_workerTLS tls;
  16050. mg_set_thread_name("worker");
  16051. tls.is_master = 0;
  16052. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16053. #if defined(_WIN32)
  16054. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16055. #endif
  16056. /* Initialize thread local storage before calling any callback */
  16057. pthread_setspecific(sTlsKey, &tls);
  16058. /* Check if there is a user callback */
  16059. if (ctx->callbacks.init_thread) {
  16060. /* call init_thread for a worker thread (type 1), and store the
  16061. * return value */
  16062. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16063. } else {
  16064. /* No callback: set user pointer to NULL */
  16065. tls.user_ptr = NULL;
  16066. }
  16067. /* Connection structure has been pre-allocated */
  16068. thread_index = (int)(conn - ctx->worker_connections);
  16069. if ((thread_index < 0)
  16070. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16071. mg_cry_ctx_internal(ctx,
  16072. "Internal error: Invalid worker index %i",
  16073. thread_index);
  16074. return;
  16075. }
  16076. /* Request buffers are not pre-allocated. They are private to the
  16077. * request and do not contain any state information that might be
  16078. * of interest to anyone observing a server status. */
  16079. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16080. if (conn->buf == NULL) {
  16081. mg_cry_ctx_internal(
  16082. ctx,
  16083. "Out of memory: Cannot allocate buffer for worker %i",
  16084. thread_index);
  16085. return;
  16086. }
  16087. conn->buf_size = (int)ctx->max_request_size;
  16088. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16089. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16090. conn->request_info.user_data = ctx->user_data;
  16091. /* Allocate a mutex for this connection to allow communication both
  16092. * within the request handler and from elsewhere in the application
  16093. */
  16094. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16095. mg_free(conn->buf);
  16096. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16097. return;
  16098. }
  16099. #if defined(USE_SERVER_STATS)
  16100. conn->conn_state = 1; /* not consumed */
  16101. #endif
  16102. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16103. * signal sq_empty condvar to wake up the master waiting in
  16104. * produce_socket() */
  16105. while (consume_socket(ctx, &conn->client, thread_index)) {
  16106. /* New connections must start with new protocol negotiation */
  16107. tls.alpn_proto = NULL;
  16108. #if defined(USE_SERVER_STATS)
  16109. conn->conn_close_time = 0;
  16110. #endif
  16111. conn->conn_birth_time = time(NULL);
  16112. /* Fill in IP, port info early so even if SSL setup below fails,
  16113. * error handler would have the corresponding info.
  16114. * Thanks to Johannes Winkelmann for the patch.
  16115. */
  16116. conn->request_info.remote_port =
  16117. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16118. sockaddr_to_string(conn->request_info.remote_addr,
  16119. sizeof(conn->request_info.remote_addr),
  16120. &conn->client.rsa);
  16121. DEBUG_TRACE("Start processing connection from %s",
  16122. conn->request_info.remote_addr);
  16123. conn->request_info.is_ssl = conn->client.is_ssl;
  16124. if (conn->client.is_ssl) {
  16125. #if !defined(NO_SSL)
  16126. /* HTTPS connection */
  16127. if (sslize(conn, SSL_accept, NULL)) {
  16128. /* conn->dom_ctx is set in get_request */
  16129. /* Get SSL client certificate information (if set) */
  16130. struct mg_client_cert client_cert;
  16131. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16132. conn->request_info.client_cert = &client_cert;
  16133. }
  16134. /* process HTTPS connection */
  16135. #if defined(USE_HTTP2)
  16136. if ((tls.alpn_proto != NULL)
  16137. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16138. /* process HTTPS/2 connection */
  16139. init_connection(conn);
  16140. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16141. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16142. conn->content_len =
  16143. -1; /* content length is not predefined */
  16144. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16145. process_new_http2_connection(conn);
  16146. } else
  16147. #endif
  16148. {
  16149. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16150. init_connection(conn);
  16151. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16152. /* Start with HTTP, WS will be an "upgrade" request later */
  16153. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16154. process_new_connection(conn);
  16155. }
  16156. /* Free client certificate info */
  16157. if (conn->request_info.client_cert) {
  16158. mg_free((void *)(conn->request_info.client_cert->subject));
  16159. mg_free((void *)(conn->request_info.client_cert->issuer));
  16160. mg_free((void *)(conn->request_info.client_cert->serial));
  16161. mg_free((void *)(conn->request_info.client_cert->finger));
  16162. /* Free certificate memory */
  16163. X509_free(
  16164. (X509 *)conn->request_info.client_cert->peer_cert);
  16165. conn->request_info.client_cert->peer_cert = 0;
  16166. conn->request_info.client_cert->subject = 0;
  16167. conn->request_info.client_cert->issuer = 0;
  16168. conn->request_info.client_cert->serial = 0;
  16169. conn->request_info.client_cert->finger = 0;
  16170. conn->request_info.client_cert = 0;
  16171. }
  16172. } else {
  16173. /* make sure the connection is cleaned up on SSL failure */
  16174. close_connection(conn);
  16175. }
  16176. #endif
  16177. } else {
  16178. /* process HTTP connection */
  16179. init_connection(conn);
  16180. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16181. /* Start with HTTP, WS will be an "upgrade" request later */
  16182. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16183. process_new_connection(conn);
  16184. }
  16185. DEBUG_TRACE("%s", "Connection closed");
  16186. #if defined(USE_SERVER_STATS)
  16187. conn->conn_close_time = time(NULL);
  16188. #endif
  16189. }
  16190. /* Call exit thread user callback */
  16191. if (ctx->callbacks.exit_thread) {
  16192. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16193. }
  16194. /* delete thread local storage objects */
  16195. pthread_setspecific(sTlsKey, NULL);
  16196. #if defined(_WIN32)
  16197. CloseHandle(tls.pthread_cond_helper_mutex);
  16198. #endif
  16199. pthread_mutex_destroy(&conn->mutex);
  16200. /* Free the request buffer. */
  16201. conn->buf_size = 0;
  16202. mg_free(conn->buf);
  16203. conn->buf = NULL;
  16204. #if defined(USE_SERVER_STATS)
  16205. conn->conn_state = 9; /* done */
  16206. #endif
  16207. DEBUG_TRACE("%s", "exiting");
  16208. }
  16209. /* Threads have different return types on Windows and Unix. */
  16210. #if defined(_WIN32)
  16211. static unsigned __stdcall worker_thread(void *thread_func_param)
  16212. {
  16213. worker_thread_run((struct mg_connection *)thread_func_param);
  16214. return 0;
  16215. }
  16216. #else
  16217. static void *
  16218. worker_thread(void *thread_func_param)
  16219. {
  16220. #if !defined(__ZEPHYR__)
  16221. struct sigaction sa;
  16222. /* Ignore SIGPIPE */
  16223. memset(&sa, 0, sizeof(sa));
  16224. sa.sa_handler = SIG_IGN;
  16225. sigaction(SIGPIPE, &sa, NULL);
  16226. #endif
  16227. worker_thread_run((struct mg_connection *)thread_func_param);
  16228. return NULL;
  16229. }
  16230. #endif /* _WIN32 */
  16231. /* This is an internal function, thus all arguments are expected to be
  16232. * valid - a NULL check is not required. */
  16233. static void
  16234. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16235. {
  16236. struct socket so;
  16237. char src_addr[IP_ADDR_STR_LEN];
  16238. socklen_t len = sizeof(so.rsa);
  16239. #if !defined(__ZEPHYR__)
  16240. int on = 1;
  16241. #endif
  16242. memset(&so, 0, sizeof(so));
  16243. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16244. == INVALID_SOCKET) {
  16245. } else if (check_acl(ctx, &so.rsa) != 1) {
  16246. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16247. mg_cry_ctx_internal(ctx,
  16248. "%s: %s is not allowed to connect",
  16249. __func__,
  16250. src_addr);
  16251. closesocket(so.sock);
  16252. } else {
  16253. /* Put so socket structure into the queue */
  16254. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16255. set_close_on_exec(so.sock, NULL, ctx);
  16256. so.is_ssl = listener->is_ssl;
  16257. so.ssl_redir = listener->ssl_redir;
  16258. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16259. mg_cry_ctx_internal(ctx,
  16260. "%s: getsockname() failed: %s",
  16261. __func__,
  16262. strerror(ERRNO));
  16263. }
  16264. #if !defined(__ZEPHYR__)
  16265. /* Set TCP keep-alive. This is needed because if HTTP-level
  16266. * keep-alive
  16267. * is enabled, and client resets the connection, server won't get
  16268. * TCP FIN or RST and will keep the connection open forever. With
  16269. * TCP keep-alive, next keep-alive handshake will figure out that
  16270. * the client is down and will close the server end.
  16271. * Thanks to Igor Klopov who suggested the patch. */
  16272. if (setsockopt(so.sock,
  16273. SOL_SOCKET,
  16274. SO_KEEPALIVE,
  16275. (SOCK_OPT_TYPE)&on,
  16276. sizeof(on))
  16277. != 0) {
  16278. mg_cry_ctx_internal(
  16279. ctx,
  16280. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16281. __func__,
  16282. strerror(ERRNO));
  16283. }
  16284. #endif
  16285. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16286. * to effectively fill up the underlying IP packet payload and
  16287. * reduce the overhead of sending lots of small buffers. However
  16288. * this hurts the server's throughput (ie. operations per second)
  16289. * when HTTP 1.1 persistent connections are used and the responses
  16290. * are relatively small (eg. less than 1400 bytes).
  16291. */
  16292. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16293. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16294. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16295. mg_cry_ctx_internal(
  16296. ctx,
  16297. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16298. __func__,
  16299. strerror(ERRNO));
  16300. }
  16301. }
  16302. /* The "non blocking" property should already be
  16303. * inherited from the parent socket. Set it for
  16304. * non-compliant socket implementations. */
  16305. set_non_blocking_mode(so.sock);
  16306. so.in_use = 0;
  16307. produce_socket(ctx, &so);
  16308. }
  16309. }
  16310. static void
  16311. master_thread_run(struct mg_context *ctx)
  16312. {
  16313. struct mg_workerTLS tls;
  16314. struct mg_pollfd *pfd;
  16315. unsigned int i;
  16316. unsigned int workerthreadcount;
  16317. if (!ctx) {
  16318. return;
  16319. }
  16320. mg_set_thread_name("master");
  16321. /* Increase priority of the master thread */
  16322. #if defined(_WIN32)
  16323. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16324. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16325. int min_prio = sched_get_priority_min(SCHED_RR);
  16326. int max_prio = sched_get_priority_max(SCHED_RR);
  16327. if ((min_prio >= 0) && (max_prio >= 0)
  16328. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16329. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16330. struct sched_param sched_param = {0};
  16331. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16332. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16333. }
  16334. #endif
  16335. /* Initialize thread local storage */
  16336. #if defined(_WIN32)
  16337. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16338. #endif
  16339. tls.is_master = 1;
  16340. pthread_setspecific(sTlsKey, &tls);
  16341. if (ctx->callbacks.init_thread) {
  16342. /* Callback for the master thread (type 0) */
  16343. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16344. } else {
  16345. tls.user_ptr = NULL;
  16346. }
  16347. /* Server starts *now* */
  16348. ctx->start_time = time(NULL);
  16349. /* Start the server */
  16350. pfd = ctx->listening_socket_fds;
  16351. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16352. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16353. pfd[i].fd = ctx->listening_sockets[i].sock;
  16354. pfd[i].events = POLLIN;
  16355. }
  16356. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16357. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16358. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16359. * successful poll, and POLLIN is defined as
  16360. * (POLLRDNORM | POLLRDBAND)
  16361. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16362. * pfd[i].revents == POLLIN. */
  16363. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16364. && (pfd[i].revents & POLLIN)) {
  16365. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16366. }
  16367. }
  16368. }
  16369. }
  16370. /* Here stop_flag is 1 - Initiate shutdown. */
  16371. DEBUG_TRACE("%s", "stopping workers");
  16372. /* Stop signal received: somebody called mg_stop. Quit. */
  16373. close_all_listening_sockets(ctx);
  16374. /* Wakeup workers that are waiting for connections to handle. */
  16375. #if defined(ALTERNATIVE_QUEUE)
  16376. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16377. event_signal(ctx->client_wait_events[i]);
  16378. }
  16379. #else
  16380. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16381. pthread_cond_broadcast(&ctx->sq_full);
  16382. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16383. #endif
  16384. /* Join all worker threads to avoid leaking threads. */
  16385. workerthreadcount = ctx->cfg_worker_threads;
  16386. for (i = 0; i < workerthreadcount; i++) {
  16387. if (ctx->worker_threadids[i] != 0) {
  16388. mg_join_thread(ctx->worker_threadids[i]);
  16389. }
  16390. }
  16391. #if defined(USE_LUA)
  16392. /* Free Lua state of lua background task */
  16393. if (ctx->lua_background_state) {
  16394. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16395. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16396. if (lua_istable(lstate, -1)) {
  16397. reg_boolean(lstate, "shutdown", 1);
  16398. lua_pop(lstate, 1);
  16399. mg_sleep(2);
  16400. }
  16401. lua_close(lstate);
  16402. ctx->lua_background_state = 0;
  16403. }
  16404. #endif
  16405. DEBUG_TRACE("%s", "exiting");
  16406. /* call exit thread callback */
  16407. if (ctx->callbacks.exit_thread) {
  16408. /* Callback for the master thread (type 0) */
  16409. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16410. }
  16411. #if defined(_WIN32)
  16412. CloseHandle(tls.pthread_cond_helper_mutex);
  16413. #endif
  16414. pthread_setspecific(sTlsKey, NULL);
  16415. /* Signal mg_stop() that we're done.
  16416. * WARNING: This must be the very last thing this
  16417. * thread does, as ctx becomes invalid after this line. */
  16418. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16419. }
  16420. /* Threads have different return types on Windows and Unix. */
  16421. #if defined(_WIN32)
  16422. static unsigned __stdcall master_thread(void *thread_func_param)
  16423. {
  16424. master_thread_run((struct mg_context *)thread_func_param);
  16425. return 0;
  16426. }
  16427. #else
  16428. static void *
  16429. master_thread(void *thread_func_param)
  16430. {
  16431. #if !defined(__ZEPHYR__)
  16432. struct sigaction sa;
  16433. /* Ignore SIGPIPE */
  16434. memset(&sa, 0, sizeof(sa));
  16435. sa.sa_handler = SIG_IGN;
  16436. sigaction(SIGPIPE, &sa, NULL);
  16437. #endif
  16438. master_thread_run((struct mg_context *)thread_func_param);
  16439. return NULL;
  16440. }
  16441. #endif /* _WIN32 */
  16442. static void
  16443. free_context(struct mg_context *ctx)
  16444. {
  16445. int i;
  16446. struct mg_handler_info *tmp_rh;
  16447. if (ctx == NULL) {
  16448. return;
  16449. }
  16450. /* Call user callback */
  16451. if (ctx->callbacks.exit_context) {
  16452. ctx->callbacks.exit_context(ctx);
  16453. }
  16454. /* All threads exited, no sync is needed. Destroy thread mutex and
  16455. * condvars
  16456. */
  16457. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16458. #if defined(ALTERNATIVE_QUEUE)
  16459. mg_free(ctx->client_socks);
  16460. if (ctx->client_wait_events != NULL) {
  16461. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16462. event_destroy(ctx->client_wait_events[i]);
  16463. }
  16464. mg_free(ctx->client_wait_events);
  16465. }
  16466. #else
  16467. (void)pthread_cond_destroy(&ctx->sq_empty);
  16468. (void)pthread_cond_destroy(&ctx->sq_full);
  16469. mg_free(ctx->squeue);
  16470. #endif
  16471. /* Destroy other context global data structures mutex */
  16472. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16473. /* Deallocate config parameters */
  16474. for (i = 0; i < NUM_OPTIONS; i++) {
  16475. if (ctx->dd.config[i] != NULL) {
  16476. #if defined(_MSC_VER)
  16477. #pragma warning(suppress : 6001)
  16478. #endif
  16479. mg_free(ctx->dd.config[i]);
  16480. }
  16481. }
  16482. /* Deallocate request handlers */
  16483. while (ctx->dd.handlers) {
  16484. tmp_rh = ctx->dd.handlers;
  16485. ctx->dd.handlers = tmp_rh->next;
  16486. mg_free(tmp_rh->uri);
  16487. mg_free(tmp_rh);
  16488. }
  16489. #if !defined(NO_SSL)
  16490. /* Deallocate SSL context */
  16491. if (ctx->dd.ssl_ctx != NULL) {
  16492. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16493. int callback_ret =
  16494. (ctx->callbacks.external_ssl_ctx == NULL)
  16495. ? 0
  16496. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16497. if (callback_ret == 0) {
  16498. SSL_CTX_free(ctx->dd.ssl_ctx);
  16499. }
  16500. /* else: ignore error and ommit SSL_CTX_free in case
  16501. * callback_ret is 1 */
  16502. }
  16503. #endif /* !NO_SSL */
  16504. /* Deallocate worker thread ID array */
  16505. mg_free(ctx->worker_threadids);
  16506. /* Deallocate worker thread ID array */
  16507. mg_free(ctx->worker_connections);
  16508. /* deallocate system name string */
  16509. mg_free(ctx->systemName);
  16510. /* Deallocate context itself */
  16511. mg_free(ctx);
  16512. }
  16513. void
  16514. mg_stop(struct mg_context *ctx)
  16515. {
  16516. pthread_t mt;
  16517. if (!ctx) {
  16518. return;
  16519. }
  16520. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16521. * two threads is not allowed. */
  16522. mt = ctx->masterthreadid;
  16523. if (mt == 0) {
  16524. return;
  16525. }
  16526. ctx->masterthreadid = 0;
  16527. /* Set stop flag, so all threads know they have to exit. */
  16528. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16529. /* Join timer thread */
  16530. #if defined(USE_TIMERS)
  16531. timers_exit(ctx);
  16532. #endif
  16533. /* Wait until everything has stopped. */
  16534. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16535. (void)mg_sleep(10);
  16536. }
  16537. /* Wait to stop master thread */
  16538. mg_join_thread(mt);
  16539. /* Close remaining Lua states */
  16540. #if defined(USE_LUA)
  16541. lua_ctx_exit(ctx);
  16542. #endif
  16543. /* Free memory */
  16544. free_context(ctx);
  16545. }
  16546. static void
  16547. get_system_name(char **sysName)
  16548. {
  16549. #if defined(_WIN32)
  16550. #if defined(_WIN32_WCE)
  16551. *sysName = mg_strdup("WinCE");
  16552. #else
  16553. char name[128];
  16554. DWORD dwVersion = 0;
  16555. DWORD dwMajorVersion = 0;
  16556. DWORD dwMinorVersion = 0;
  16557. DWORD dwBuild = 0;
  16558. BOOL wowRet, isWoW = FALSE;
  16559. #if defined(_MSC_VER)
  16560. #pragma warning(push)
  16561. /* GetVersion was declared deprecated */
  16562. #pragma warning(disable : 4996)
  16563. #endif
  16564. dwVersion = GetVersion();
  16565. #if defined(_MSC_VER)
  16566. #pragma warning(pop)
  16567. #endif
  16568. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16569. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16570. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16571. (void)dwBuild;
  16572. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16573. sprintf(name,
  16574. "Windows %u.%u%s",
  16575. (unsigned)dwMajorVersion,
  16576. (unsigned)dwMinorVersion,
  16577. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16578. *sysName = mg_strdup(name);
  16579. #endif
  16580. #elif defined(__ZEPHYR__)
  16581. *sysName = mg_strdup("Zephyr OS");
  16582. #else
  16583. struct utsname name;
  16584. memset(&name, 0, sizeof(name));
  16585. uname(&name);
  16586. *sysName = mg_strdup(name.sysname);
  16587. #endif
  16588. }
  16589. static void
  16590. legacy_init(const char **options)
  16591. {
  16592. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16593. if (options) {
  16594. const char **run_options = options;
  16595. const char *optname = config_options[LISTENING_PORTS].name;
  16596. /* Try to find the "listening_ports" option */
  16597. while (*run_options) {
  16598. if (!strcmp(*run_options, optname)) {
  16599. ports_option = run_options[1];
  16600. }
  16601. run_options += 2;
  16602. }
  16603. }
  16604. if (is_ssl_port_used(ports_option)) {
  16605. /* Initialize with SSL support */
  16606. mg_init_library(MG_FEATURES_TLS);
  16607. } else {
  16608. /* Initialize without SSL support */
  16609. mg_init_library(MG_FEATURES_DEFAULT);
  16610. }
  16611. }
  16612. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16613. static
  16614. #endif
  16615. struct mg_context *
  16616. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16617. {
  16618. struct mg_context *ctx;
  16619. const char *name, *value, *default_value;
  16620. int idx, ok, workerthreadcount;
  16621. unsigned int i;
  16622. int itmp;
  16623. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16624. const char **options =
  16625. ((init != NULL) ? (init->configuration_options) : (NULL));
  16626. struct mg_workerTLS tls;
  16627. if (error != NULL) {
  16628. error->code = 0;
  16629. if (error->text_buffer_size > 0) {
  16630. *error->text = 0;
  16631. }
  16632. }
  16633. if (mg_init_library_called == 0) {
  16634. /* Legacy INIT, if mg_start is called without mg_init_library.
  16635. * Note: This will cause a memory leak when unloading the library.
  16636. */
  16637. legacy_init(options);
  16638. }
  16639. if (mg_init_library_called == 0) {
  16640. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16641. mg_snprintf(NULL,
  16642. NULL, /* No truncation check for error buffers */
  16643. error->text,
  16644. error->text_buffer_size,
  16645. "%s",
  16646. "Library uninitialized");
  16647. }
  16648. return NULL;
  16649. }
  16650. /* Allocate context and initialize reasonable general case defaults. */
  16651. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16652. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16653. mg_snprintf(NULL,
  16654. NULL, /* No truncation check for error buffers */
  16655. error->text,
  16656. error->text_buffer_size,
  16657. "%s",
  16658. "Out of memory");
  16659. }
  16660. return NULL;
  16661. }
  16662. /* Random number generator will initialize at the first call */
  16663. ctx->dd.auth_nonce_mask =
  16664. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16665. /* Save started thread index to reuse in other external API calls
  16666. * For the sake of thread synchronization all non-civetweb threads
  16667. * can be considered as single external thread */
  16668. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16669. tls.is_master = -1; /* Thread calling mg_start */
  16670. tls.thread_idx = ctx->starter_thread_idx;
  16671. #if defined(_WIN32)
  16672. tls.pthread_cond_helper_mutex = NULL;
  16673. #endif
  16674. pthread_setspecific(sTlsKey, &tls);
  16675. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16676. #if !defined(ALTERNATIVE_QUEUE)
  16677. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16678. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16679. ctx->sq_blocked = 0;
  16680. #endif
  16681. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16682. if (!ok) {
  16683. const char *err_msg =
  16684. "Cannot initialize thread synchronization objects";
  16685. /* Fatal error - abort start. However, this situation should never
  16686. * occur in practice. */
  16687. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16688. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16689. mg_snprintf(NULL,
  16690. NULL, /* No truncation check for error buffers */
  16691. error->text,
  16692. error->text_buffer_size,
  16693. "%s",
  16694. err_msg);
  16695. }
  16696. mg_free(ctx);
  16697. pthread_setspecific(sTlsKey, NULL);
  16698. return NULL;
  16699. }
  16700. if ((init != NULL) && (init->callbacks != NULL)) {
  16701. /* Set all callbacks except exit_context. */
  16702. ctx->callbacks = *init->callbacks;
  16703. exit_callback = init->callbacks->exit_context;
  16704. /* The exit callback is activated once the context is successfully
  16705. * created. It should not be called, if an incomplete context object
  16706. * is deleted during a failed initialization. */
  16707. ctx->callbacks.exit_context = 0;
  16708. }
  16709. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16710. ctx->dd.handlers = NULL;
  16711. ctx->dd.next = NULL;
  16712. #if defined(USE_LUA)
  16713. lua_ctx_init(ctx);
  16714. #endif
  16715. /* Store options */
  16716. while (options && (name = *options++) != NULL) {
  16717. if ((idx = get_option_index(name)) == -1) {
  16718. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16719. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16720. mg_snprintf(NULL,
  16721. NULL, /* No truncation check for error buffers */
  16722. error->text,
  16723. error->text_buffer_size,
  16724. "Invalid configuration option: %s",
  16725. name);
  16726. }
  16727. free_context(ctx);
  16728. pthread_setspecific(sTlsKey, NULL);
  16729. return NULL;
  16730. } else if ((value = *options++) == NULL) {
  16731. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16732. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16733. mg_snprintf(NULL,
  16734. NULL, /* No truncation check for error buffers */
  16735. error->text,
  16736. error->text_buffer_size,
  16737. "Invalid configuration option value: %s",
  16738. name);
  16739. }
  16740. free_context(ctx);
  16741. pthread_setspecific(sTlsKey, NULL);
  16742. return NULL;
  16743. }
  16744. if (ctx->dd.config[idx] != NULL) {
  16745. /* A duplicate configuration option is not an error - the last
  16746. * option value will be used. */
  16747. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16748. mg_free(ctx->dd.config[idx]);
  16749. }
  16750. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16751. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16752. }
  16753. /* Set default value if needed */
  16754. for (i = 0; config_options[i].name != NULL; i++) {
  16755. default_value = config_options[i].default_value;
  16756. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16757. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16758. }
  16759. }
  16760. /* Request size option */
  16761. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16762. if (itmp < 1024) {
  16763. mg_cry_ctx_internal(ctx,
  16764. "%s too small",
  16765. config_options[MAX_REQUEST_SIZE].name);
  16766. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16767. mg_snprintf(NULL,
  16768. NULL, /* No truncation check for error buffers */
  16769. error->text,
  16770. error->text_buffer_size,
  16771. "Invalid configuration option value: %s",
  16772. config_options[MAX_REQUEST_SIZE].name);
  16773. }
  16774. free_context(ctx);
  16775. pthread_setspecific(sTlsKey, NULL);
  16776. return NULL;
  16777. }
  16778. ctx->max_request_size = (unsigned)itmp;
  16779. /* Queue length */
  16780. #if !defined(ALTERNATIVE_QUEUE)
  16781. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16782. if (itmp < 1) {
  16783. mg_cry_ctx_internal(ctx,
  16784. "%s too small",
  16785. config_options[CONNECTION_QUEUE_SIZE].name);
  16786. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16787. mg_snprintf(NULL,
  16788. NULL, /* No truncation check for error buffers */
  16789. error->text,
  16790. error->text_buffer_size,
  16791. "Invalid configuration option value: %s",
  16792. config_options[CONNECTION_QUEUE_SIZE].name);
  16793. }
  16794. free_context(ctx);
  16795. pthread_setspecific(sTlsKey, NULL);
  16796. return NULL;
  16797. }
  16798. ctx->squeue =
  16799. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16800. if (ctx->squeue == NULL) {
  16801. mg_cry_ctx_internal(ctx,
  16802. "Out of memory: Cannot allocate %s",
  16803. config_options[CONNECTION_QUEUE_SIZE].name);
  16804. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16805. mg_snprintf(NULL,
  16806. NULL, /* No truncation check for error buffers */
  16807. error->text,
  16808. error->text_buffer_size,
  16809. "Out of memory: Cannot allocate %s",
  16810. config_options[CONNECTION_QUEUE_SIZE].name);
  16811. }
  16812. free_context(ctx);
  16813. pthread_setspecific(sTlsKey, NULL);
  16814. return NULL;
  16815. }
  16816. ctx->sq_size = itmp;
  16817. #endif
  16818. /* Worker thread count option */
  16819. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16820. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16821. if (workerthreadcount <= 0) {
  16822. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16823. } else {
  16824. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16825. }
  16826. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16827. mg_snprintf(NULL,
  16828. NULL, /* No truncation check for error buffers */
  16829. error->text,
  16830. error->text_buffer_size,
  16831. "Invalid configuration option value: %s",
  16832. config_options[NUM_THREADS].name);
  16833. }
  16834. free_context(ctx);
  16835. pthread_setspecific(sTlsKey, NULL);
  16836. return NULL;
  16837. }
  16838. /* Document root */
  16839. #if defined(NO_FILES)
  16840. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16841. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16842. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16843. mg_snprintf(NULL,
  16844. NULL, /* No truncation check for error buffers */
  16845. error->text,
  16846. error->text_buffer_size,
  16847. "Invalid configuration option value: %s",
  16848. config_options[DOCUMENT_ROOT].name);
  16849. }
  16850. free_context(ctx);
  16851. pthread_setspecific(sTlsKey, NULL);
  16852. return NULL;
  16853. }
  16854. #endif
  16855. get_system_name(&ctx->systemName);
  16856. #if defined(USE_LUA)
  16857. /* If a Lua background script has been configured, start it. */
  16858. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16859. char ebuf[256];
  16860. struct vec opt_vec;
  16861. struct vec eq_vec;
  16862. const char *sparams;
  16863. lua_State *state = mg_prepare_lua_context_script(
  16864. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16865. if (!state) {
  16866. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16867. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16868. mg_snprintf(NULL,
  16869. NULL, /* No truncation check for error buffers */
  16870. error->text,
  16871. error->text_buffer_size,
  16872. "Error in script %s: %s",
  16873. config_options[DOCUMENT_ROOT].name,
  16874. ebuf);
  16875. }
  16876. free_context(ctx);
  16877. pthread_setspecific(sTlsKey, NULL);
  16878. return NULL;
  16879. }
  16880. ctx->lua_background_state = (void *)state;
  16881. lua_newtable(state);
  16882. reg_boolean(state, "shutdown", 0);
  16883. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16884. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16885. reg_llstring(
  16886. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16887. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16888. break;
  16889. }
  16890. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16891. } else {
  16892. ctx->lua_background_state = 0;
  16893. }
  16894. #endif
  16895. /* Step by step initialization of ctx - depending on build options */
  16896. #if !defined(NO_FILESYSTEMS)
  16897. if (!set_gpass_option(ctx, NULL)) {
  16898. const char *err_msg = "Invalid global password file";
  16899. /* Fatal error - abort start. */
  16900. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16901. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16902. mg_snprintf(NULL,
  16903. NULL, /* No truncation check for error buffers */
  16904. error->text,
  16905. error->text_buffer_size,
  16906. "%s",
  16907. err_msg);
  16908. }
  16909. free_context(ctx);
  16910. pthread_setspecific(sTlsKey, NULL);
  16911. return NULL;
  16912. }
  16913. #endif
  16914. #if !defined(NO_SSL)
  16915. if (!init_ssl_ctx(ctx, NULL)) {
  16916. const char *err_msg = "Error initializing SSL context";
  16917. /* Fatal error - abort start. */
  16918. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16919. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16920. mg_snprintf(NULL,
  16921. NULL, /* No truncation check for error buffers */
  16922. error->text,
  16923. error->text_buffer_size,
  16924. "%s",
  16925. err_msg);
  16926. }
  16927. free_context(ctx);
  16928. pthread_setspecific(sTlsKey, NULL);
  16929. return NULL;
  16930. }
  16931. #endif
  16932. if (!set_ports_option(ctx)) {
  16933. const char *err_msg = "Failed to setup server ports";
  16934. /* Fatal error - abort start. */
  16935. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16936. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16937. mg_snprintf(NULL,
  16938. NULL, /* No truncation check for error buffers */
  16939. error->text,
  16940. error->text_buffer_size,
  16941. "%s",
  16942. err_msg);
  16943. }
  16944. free_context(ctx);
  16945. pthread_setspecific(sTlsKey, NULL);
  16946. return NULL;
  16947. }
  16948. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16949. if (!set_uid_option(ctx)) {
  16950. const char *err_msg = "Failed to run as configured user";
  16951. /* Fatal error - abort start. */
  16952. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16953. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16954. mg_snprintf(NULL,
  16955. NULL, /* No truncation check for error buffers */
  16956. error->text,
  16957. error->text_buffer_size,
  16958. "%s",
  16959. err_msg);
  16960. }
  16961. free_context(ctx);
  16962. pthread_setspecific(sTlsKey, NULL);
  16963. return NULL;
  16964. }
  16965. #endif
  16966. if (!set_acl_option(ctx)) {
  16967. const char *err_msg = "Failed to setup access control list";
  16968. /* Fatal error - abort start. */
  16969. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16970. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16971. mg_snprintf(NULL,
  16972. NULL, /* No truncation check for error buffers */
  16973. error->text,
  16974. error->text_buffer_size,
  16975. "%s",
  16976. err_msg);
  16977. }
  16978. free_context(ctx);
  16979. pthread_setspecific(sTlsKey, NULL);
  16980. return NULL;
  16981. }
  16982. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16983. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16984. sizeof(pthread_t),
  16985. ctx);
  16986. if (ctx->worker_threadids == NULL) {
  16987. const char *err_msg = "Not enough memory for worker thread ID array";
  16988. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16989. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16990. mg_snprintf(NULL,
  16991. NULL, /* No truncation check for error buffers */
  16992. error->text,
  16993. error->text_buffer_size,
  16994. "%s",
  16995. err_msg);
  16996. }
  16997. free_context(ctx);
  16998. pthread_setspecific(sTlsKey, NULL);
  16999. return NULL;
  17000. }
  17001. ctx->worker_connections =
  17002. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17003. sizeof(struct mg_connection),
  17004. ctx);
  17005. if (ctx->worker_connections == NULL) {
  17006. const char *err_msg =
  17007. "Not enough memory for worker thread connection array";
  17008. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17009. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17010. mg_snprintf(NULL,
  17011. NULL, /* No truncation check for error buffers */
  17012. error->text,
  17013. error->text_buffer_size,
  17014. "%s",
  17015. err_msg);
  17016. }
  17017. free_context(ctx);
  17018. pthread_setspecific(sTlsKey, NULL);
  17019. return NULL;
  17020. }
  17021. #if defined(ALTERNATIVE_QUEUE)
  17022. ctx->client_wait_events =
  17023. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17024. sizeof(ctx->client_wait_events[0]),
  17025. ctx);
  17026. if (ctx->client_wait_events == NULL) {
  17027. const char *err_msg = "Not enough memory for worker event array";
  17028. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17029. mg_free(ctx->worker_threadids);
  17030. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17031. mg_snprintf(NULL,
  17032. NULL, /* No truncation check for error buffers */
  17033. error->text,
  17034. error->text_buffer_size,
  17035. "%s",
  17036. err_msg);
  17037. }
  17038. free_context(ctx);
  17039. pthread_setspecific(sTlsKey, NULL);
  17040. return NULL;
  17041. }
  17042. ctx->client_socks =
  17043. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17044. sizeof(ctx->client_socks[0]),
  17045. ctx);
  17046. if (ctx->client_socks == NULL) {
  17047. const char *err_msg = "Not enough memory for worker socket array";
  17048. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17049. mg_free(ctx->client_wait_events);
  17050. mg_free(ctx->worker_threadids);
  17051. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17052. mg_snprintf(NULL,
  17053. NULL, /* No truncation check for error buffers */
  17054. error->text,
  17055. error->text_buffer_size,
  17056. "%s",
  17057. err_msg);
  17058. }
  17059. free_context(ctx);
  17060. pthread_setspecific(sTlsKey, NULL);
  17061. return NULL;
  17062. }
  17063. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17064. ctx->client_wait_events[i] = event_create();
  17065. if (ctx->client_wait_events[i] == 0) {
  17066. const char *err_msg = "Error creating worker event %i";
  17067. mg_cry_ctx_internal(ctx, err_msg, i);
  17068. while (i > 0) {
  17069. i--;
  17070. event_destroy(ctx->client_wait_events[i]);
  17071. }
  17072. mg_free(ctx->client_socks);
  17073. mg_free(ctx->client_wait_events);
  17074. mg_free(ctx->worker_threadids);
  17075. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17076. mg_snprintf(NULL,
  17077. NULL, /* No truncation check for error buffers */
  17078. error->text,
  17079. error->text_buffer_size,
  17080. err_msg,
  17081. i);
  17082. }
  17083. free_context(ctx);
  17084. pthread_setspecific(sTlsKey, NULL);
  17085. return NULL;
  17086. }
  17087. }
  17088. #endif
  17089. #if defined(USE_TIMERS)
  17090. if (timers_init(ctx) != 0) {
  17091. const char *err_msg = "Error creating timers";
  17092. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17093. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17094. mg_snprintf(NULL,
  17095. NULL, /* No truncation check for error buffers */
  17096. error->text,
  17097. error->text_buffer_size,
  17098. "%s",
  17099. err_msg);
  17100. }
  17101. free_context(ctx);
  17102. pthread_setspecific(sTlsKey, NULL);
  17103. return NULL;
  17104. }
  17105. #endif
  17106. /* Context has been created - init user libraries */
  17107. if (ctx->callbacks.init_context) {
  17108. ctx->callbacks.init_context(ctx);
  17109. }
  17110. /* From now, the context is successfully created.
  17111. * When it is destroyed, the exit callback should be called. */
  17112. ctx->callbacks.exit_context = exit_callback;
  17113. ctx->context_type = CONTEXT_SERVER; /* server context */
  17114. /* Start worker threads */
  17115. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17116. /* worker_thread sets up the other fields */
  17117. ctx->worker_connections[i].phys_ctx = ctx;
  17118. if (mg_start_thread_with_id(worker_thread,
  17119. &ctx->worker_connections[i],
  17120. &ctx->worker_threadids[i])
  17121. != 0) {
  17122. long error_no = (long)ERRNO;
  17123. /* thread was not created */
  17124. if (i > 0) {
  17125. /* If the second, third, ... thread cannot be created, set a
  17126. * warning, but keep running. */
  17127. mg_cry_ctx_internal(ctx,
  17128. "Cannot start worker thread %i: error %ld",
  17129. i + 1,
  17130. error_no);
  17131. /* If the server initialization should stop here, all
  17132. * threads that have already been created must be stopped
  17133. * first, before any free_context(ctx) call.
  17134. */
  17135. } else {
  17136. /* If the first worker thread cannot be created, stop
  17137. * initialization and free the entire server context. */
  17138. mg_cry_ctx_internal(ctx,
  17139. "Cannot create threads: error %ld",
  17140. error_no);
  17141. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17142. mg_snprintf(
  17143. NULL,
  17144. NULL, /* No truncation check for error buffers */
  17145. error->text,
  17146. error->text_buffer_size,
  17147. "Cannot create first worker thread: error %ld",
  17148. error_no);
  17149. }
  17150. free_context(ctx);
  17151. pthread_setspecific(sTlsKey, NULL);
  17152. return NULL;
  17153. }
  17154. break;
  17155. }
  17156. }
  17157. /* Start master (listening) thread */
  17158. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17159. pthread_setspecific(sTlsKey, NULL);
  17160. return ctx;
  17161. }
  17162. struct mg_context *
  17163. mg_start(const struct mg_callbacks *callbacks,
  17164. void *user_data,
  17165. const char **options)
  17166. {
  17167. struct mg_init_data init = {0};
  17168. init.callbacks = callbacks;
  17169. init.user_data = user_data;
  17170. init.configuration_options = options;
  17171. return mg_start2(&init, NULL);
  17172. }
  17173. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17174. /* Add an additional domain to an already running web server. */
  17175. int
  17176. mg_start_domain2(struct mg_context *ctx,
  17177. const char **options,
  17178. struct mg_error_data *error)
  17179. {
  17180. const char *name;
  17181. const char *value;
  17182. const char *default_value;
  17183. struct mg_domain_context *new_dom;
  17184. struct mg_domain_context *dom;
  17185. int idx, i;
  17186. if (error != NULL) {
  17187. error->code = 0;
  17188. if (error->text_buffer_size > 0) {
  17189. *error->text = 0;
  17190. }
  17191. }
  17192. if ((ctx == NULL) || (options == NULL)) {
  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. "Invalid parameters");
  17200. }
  17201. return -1;
  17202. }
  17203. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17204. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17205. mg_snprintf(NULL,
  17206. NULL, /* No truncation check for error buffers */
  17207. error->text,
  17208. error->text_buffer_size,
  17209. "%s",
  17210. "Server already stopped");
  17211. }
  17212. return -1;
  17213. }
  17214. new_dom = (struct mg_domain_context *)
  17215. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17216. if (!new_dom) {
  17217. /* Out of memory */
  17218. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17219. mg_snprintf(NULL,
  17220. NULL, /* No truncation check for error buffers */
  17221. error->text,
  17222. error->text_buffer_size,
  17223. "%s",
  17224. "Out or memory");
  17225. }
  17226. return -6;
  17227. }
  17228. /* Store options - TODO: unite duplicate code */
  17229. while (options && (name = *options++) != NULL) {
  17230. if ((idx = get_option_index(name)) == -1) {
  17231. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17232. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17233. mg_snprintf(NULL,
  17234. NULL, /* No truncation check for error buffers */
  17235. error->text,
  17236. error->text_buffer_size,
  17237. "Invalid option: %s",
  17238. name);
  17239. }
  17240. mg_free(new_dom);
  17241. return -2;
  17242. } else if ((value = *options++) == NULL) {
  17243. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17244. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17245. mg_snprintf(NULL,
  17246. NULL, /* No truncation check for error buffers */
  17247. error->text,
  17248. error->text_buffer_size,
  17249. "Invalid option value: %s",
  17250. name);
  17251. }
  17252. mg_free(new_dom);
  17253. return -2;
  17254. }
  17255. if (new_dom->config[idx] != NULL) {
  17256. /* Duplicate option: Later values overwrite earlier ones. */
  17257. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17258. mg_free(new_dom->config[idx]);
  17259. }
  17260. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17261. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17262. }
  17263. /* Authentication domain is mandatory */
  17264. /* TODO: Maybe use a new option hostname? */
  17265. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17266. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17267. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17268. mg_snprintf(NULL,
  17269. NULL, /* No truncation check for error buffers */
  17270. error->text,
  17271. error->text_buffer_size,
  17272. "Mandatory option %s missing",
  17273. config_options[AUTHENTICATION_DOMAIN].name);
  17274. }
  17275. mg_free(new_dom);
  17276. return -4;
  17277. }
  17278. /* Set default value if needed. Take the config value from
  17279. * ctx as a default value. */
  17280. for (i = 0; config_options[i].name != NULL; i++) {
  17281. default_value = ctx->dd.config[i];
  17282. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17283. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17284. }
  17285. }
  17286. new_dom->handlers = NULL;
  17287. new_dom->next = NULL;
  17288. new_dom->nonce_count = 0;
  17289. new_dom->auth_nonce_mask =
  17290. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17291. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17292. new_dom->shared_lua_websockets = NULL;
  17293. #endif
  17294. #if !defined(NO_SSL)
  17295. if (!init_ssl_ctx(ctx, new_dom)) {
  17296. /* Init SSL failed */
  17297. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17298. mg_snprintf(NULL,
  17299. NULL, /* No truncation check for error buffers */
  17300. error->text,
  17301. error->text_buffer_size,
  17302. "%s",
  17303. "Initializing SSL context failed");
  17304. }
  17305. mg_free(new_dom);
  17306. return -3;
  17307. }
  17308. #endif
  17309. /* Add element to linked list. */
  17310. mg_lock_context(ctx);
  17311. idx = 0;
  17312. dom = &(ctx->dd);
  17313. for (;;) {
  17314. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17315. dom->config[AUTHENTICATION_DOMAIN])) {
  17316. /* Domain collision */
  17317. mg_cry_ctx_internal(ctx,
  17318. "domain %s already in use",
  17319. new_dom->config[AUTHENTICATION_DOMAIN]);
  17320. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17321. mg_snprintf(NULL,
  17322. NULL, /* No truncation check for error buffers */
  17323. error->text,
  17324. error->text_buffer_size,
  17325. "Domain %s specified by %s is already in use",
  17326. new_dom->config[AUTHENTICATION_DOMAIN],
  17327. config_options[AUTHENTICATION_DOMAIN].name);
  17328. }
  17329. mg_free(new_dom);
  17330. mg_unlock_context(ctx);
  17331. return -5;
  17332. }
  17333. /* Count number of domains */
  17334. idx++;
  17335. if (dom->next == NULL) {
  17336. dom->next = new_dom;
  17337. break;
  17338. }
  17339. dom = dom->next;
  17340. }
  17341. mg_unlock_context(ctx);
  17342. /* Return domain number */
  17343. return idx;
  17344. }
  17345. int
  17346. mg_start_domain(struct mg_context *ctx, const char **options)
  17347. {
  17348. return mg_start_domain2(ctx, options, NULL);
  17349. }
  17350. #endif
  17351. /* Feature check API function */
  17352. unsigned
  17353. mg_check_feature(unsigned feature)
  17354. {
  17355. static const unsigned feature_set = 0
  17356. /* Set bits for available features according to API documentation.
  17357. * This bit mask is created at compile time, according to the active
  17358. * preprocessor defines. It is a single const value at runtime. */
  17359. #if !defined(NO_FILES)
  17360. | MG_FEATURES_FILES
  17361. #endif
  17362. #if !defined(NO_SSL)
  17363. | MG_FEATURES_SSL
  17364. #endif
  17365. #if !defined(NO_CGI)
  17366. | MG_FEATURES_CGI
  17367. #endif
  17368. #if defined(USE_IPV6)
  17369. | MG_FEATURES_IPV6
  17370. #endif
  17371. #if defined(USE_WEBSOCKET)
  17372. | MG_FEATURES_WEBSOCKET
  17373. #endif
  17374. #if defined(USE_LUA)
  17375. | MG_FEATURES_LUA
  17376. #endif
  17377. #if defined(USE_DUKTAPE)
  17378. | MG_FEATURES_SSJS
  17379. #endif
  17380. #if !defined(NO_CACHING)
  17381. | MG_FEATURES_CACHE
  17382. #endif
  17383. #if defined(USE_SERVER_STATS)
  17384. | MG_FEATURES_STATS
  17385. #endif
  17386. #if defined(USE_ZLIB)
  17387. | MG_FEATURES_COMPRESSION
  17388. #endif
  17389. /* Set some extra bits not defined in the API documentation.
  17390. * These bits may change without further notice. */
  17391. #if defined(MG_LEGACY_INTERFACE)
  17392. | 0x00008000u
  17393. #endif
  17394. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17395. | 0x00004000u
  17396. #endif
  17397. #if defined(MEMORY_DEBUGGING)
  17398. | 0x00001000u
  17399. #endif
  17400. #if defined(USE_TIMERS)
  17401. | 0x00020000u
  17402. #endif
  17403. #if !defined(NO_NONCE_CHECK)
  17404. | 0x00040000u
  17405. #endif
  17406. #if !defined(NO_POPEN)
  17407. | 0x00080000u
  17408. #endif
  17409. ;
  17410. return (feature & feature_set);
  17411. }
  17412. static size_t
  17413. mg_str_append(char **dst, char *end, const char *src)
  17414. {
  17415. size_t len = strlen(src);
  17416. if (*dst != end) {
  17417. /* Append src if enough space, or close dst. */
  17418. if ((size_t)(end - *dst) > len) {
  17419. strcpy(*dst, src);
  17420. *dst += len;
  17421. } else {
  17422. *dst = end;
  17423. }
  17424. }
  17425. return len;
  17426. }
  17427. /* Get system information. It can be printed or stored by the caller.
  17428. * Return the size of available information. */
  17429. int
  17430. mg_get_system_info(char *buffer, int buflen)
  17431. {
  17432. char *end, *append_eoobj = NULL, block[256];
  17433. size_t system_info_length = 0;
  17434. #if defined(_WIN32)
  17435. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17436. #else
  17437. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17438. #endif
  17439. if ((buffer == NULL) || (buflen < 1)) {
  17440. buflen = 0;
  17441. end = buffer;
  17442. } else {
  17443. *buffer = 0;
  17444. end = buffer + buflen;
  17445. }
  17446. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17447. /* has enough space to append eoobj */
  17448. append_eoobj = buffer;
  17449. if (end) {
  17450. end -= sizeof(eoobj) - 1;
  17451. }
  17452. }
  17453. system_info_length += mg_str_append(&buffer, end, "{");
  17454. /* Server version */
  17455. {
  17456. const char *version = mg_version();
  17457. mg_snprintf(NULL,
  17458. NULL,
  17459. block,
  17460. sizeof(block),
  17461. "%s\"version\" : \"%s\"",
  17462. eol,
  17463. version);
  17464. system_info_length += mg_str_append(&buffer, end, block);
  17465. }
  17466. /* System info */
  17467. {
  17468. #if defined(_WIN32)
  17469. DWORD dwVersion = 0;
  17470. DWORD dwMajorVersion = 0;
  17471. DWORD dwMinorVersion = 0;
  17472. SYSTEM_INFO si;
  17473. GetSystemInfo(&si);
  17474. #if defined(_MSC_VER)
  17475. #pragma warning(push)
  17476. /* GetVersion was declared deprecated */
  17477. #pragma warning(disable : 4996)
  17478. #endif
  17479. dwVersion = GetVersion();
  17480. #if defined(_MSC_VER)
  17481. #pragma warning(pop)
  17482. #endif
  17483. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17484. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17485. mg_snprintf(NULL,
  17486. NULL,
  17487. block,
  17488. sizeof(block),
  17489. ",%s\"os\" : \"Windows %u.%u\"",
  17490. eol,
  17491. (unsigned)dwMajorVersion,
  17492. (unsigned)dwMinorVersion);
  17493. system_info_length += mg_str_append(&buffer, end, block);
  17494. mg_snprintf(NULL,
  17495. NULL,
  17496. block,
  17497. sizeof(block),
  17498. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17499. eol,
  17500. (unsigned)si.wProcessorArchitecture,
  17501. (unsigned)si.dwNumberOfProcessors,
  17502. (unsigned)si.dwActiveProcessorMask);
  17503. system_info_length += mg_str_append(&buffer, end, block);
  17504. #elif defined(__ZEPHYR__)
  17505. mg_snprintf(NULL,
  17506. NULL,
  17507. block,
  17508. sizeof(block),
  17509. ",%s\"os\" : \"%s %s\"",
  17510. eol,
  17511. "Zephyr OS",
  17512. ZEPHYR_VERSION);
  17513. system_info_length += mg_str_append(&buffer, end, block);
  17514. #else
  17515. struct utsname name;
  17516. memset(&name, 0, sizeof(name));
  17517. uname(&name);
  17518. mg_snprintf(NULL,
  17519. NULL,
  17520. block,
  17521. sizeof(block),
  17522. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17523. eol,
  17524. name.sysname,
  17525. name.version,
  17526. name.release,
  17527. name.machine);
  17528. system_info_length += mg_str_append(&buffer, end, block);
  17529. #endif
  17530. }
  17531. /* Features */
  17532. {
  17533. mg_snprintf(NULL,
  17534. NULL,
  17535. block,
  17536. sizeof(block),
  17537. ",%s\"features\" : %lu"
  17538. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17539. eol,
  17540. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17541. eol,
  17542. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17543. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17544. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17545. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17546. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17547. : "",
  17548. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17549. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17550. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17551. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17552. system_info_length += mg_str_append(&buffer, end, block);
  17553. #if defined(USE_LUA)
  17554. mg_snprintf(NULL,
  17555. NULL,
  17556. block,
  17557. sizeof(block),
  17558. ",%s\"lua_version\" : \"%u (%s)\"",
  17559. eol,
  17560. (unsigned)LUA_VERSION_NUM,
  17561. LUA_RELEASE);
  17562. system_info_length += mg_str_append(&buffer, end, block);
  17563. #endif
  17564. #if defined(USE_DUKTAPE)
  17565. mg_snprintf(NULL,
  17566. NULL,
  17567. block,
  17568. sizeof(block),
  17569. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17570. eol,
  17571. (unsigned)DUK_VERSION / 10000,
  17572. ((unsigned)DUK_VERSION / 100) % 100,
  17573. (unsigned)DUK_VERSION % 100);
  17574. system_info_length += mg_str_append(&buffer, end, block);
  17575. #endif
  17576. }
  17577. /* Build date */
  17578. {
  17579. #if defined(GCC_DIAGNOSTIC)
  17580. #if GCC_VERSION >= 40900
  17581. #pragma GCC diagnostic push
  17582. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17583. #pragma GCC diagnostic ignored "-Wdate-time"
  17584. #endif
  17585. #endif
  17586. mg_snprintf(NULL,
  17587. NULL,
  17588. block,
  17589. sizeof(block),
  17590. ",%s\"build\" : \"%s\"",
  17591. eol,
  17592. __DATE__);
  17593. #if defined(GCC_DIAGNOSTIC)
  17594. #if GCC_VERSION >= 40900
  17595. #pragma GCC diagnostic pop
  17596. #endif
  17597. #endif
  17598. system_info_length += mg_str_append(&buffer, end, block);
  17599. }
  17600. /* Compiler information */
  17601. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17602. {
  17603. #if defined(_MSC_VER)
  17604. mg_snprintf(NULL,
  17605. NULL,
  17606. block,
  17607. sizeof(block),
  17608. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17609. eol,
  17610. (unsigned)_MSC_VER,
  17611. (unsigned)_MSC_FULL_VER);
  17612. system_info_length += mg_str_append(&buffer, end, block);
  17613. #elif defined(__MINGW64__)
  17614. mg_snprintf(NULL,
  17615. NULL,
  17616. block,
  17617. sizeof(block),
  17618. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17619. eol,
  17620. (unsigned)__MINGW64_VERSION_MAJOR,
  17621. (unsigned)__MINGW64_VERSION_MINOR);
  17622. system_info_length += mg_str_append(&buffer, end, block);
  17623. mg_snprintf(NULL,
  17624. NULL,
  17625. block,
  17626. sizeof(block),
  17627. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17628. eol,
  17629. (unsigned)__MINGW32_MAJOR_VERSION,
  17630. (unsigned)__MINGW32_MINOR_VERSION);
  17631. system_info_length += mg_str_append(&buffer, end, block);
  17632. #elif defined(__MINGW32__)
  17633. mg_snprintf(NULL,
  17634. NULL,
  17635. block,
  17636. sizeof(block),
  17637. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17638. eol,
  17639. (unsigned)__MINGW32_MAJOR_VERSION,
  17640. (unsigned)__MINGW32_MINOR_VERSION);
  17641. system_info_length += mg_str_append(&buffer, end, block);
  17642. #elif defined(__clang__)
  17643. mg_snprintf(NULL,
  17644. NULL,
  17645. block,
  17646. sizeof(block),
  17647. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17648. eol,
  17649. __clang_major__,
  17650. __clang_minor__,
  17651. __clang_patchlevel__,
  17652. __clang_version__);
  17653. system_info_length += mg_str_append(&buffer, end, block);
  17654. #elif defined(__GNUC__)
  17655. mg_snprintf(NULL,
  17656. NULL,
  17657. block,
  17658. sizeof(block),
  17659. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17660. eol,
  17661. (unsigned)__GNUC__,
  17662. (unsigned)__GNUC_MINOR__,
  17663. (unsigned)__GNUC_PATCHLEVEL__);
  17664. system_info_length += mg_str_append(&buffer, end, block);
  17665. #elif defined(__INTEL_COMPILER)
  17666. mg_snprintf(NULL,
  17667. NULL,
  17668. block,
  17669. sizeof(block),
  17670. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17671. eol,
  17672. (unsigned)__INTEL_COMPILER);
  17673. system_info_length += mg_str_append(&buffer, end, block);
  17674. #elif defined(__BORLANDC__)
  17675. mg_snprintf(NULL,
  17676. NULL,
  17677. block,
  17678. sizeof(block),
  17679. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17680. eol,
  17681. (unsigned)__BORLANDC__);
  17682. system_info_length += mg_str_append(&buffer, end, block);
  17683. #elif defined(__SUNPRO_C)
  17684. mg_snprintf(NULL,
  17685. NULL,
  17686. block,
  17687. sizeof(block),
  17688. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17689. eol,
  17690. (unsigned)__SUNPRO_C);
  17691. system_info_length += mg_str_append(&buffer, end, block);
  17692. #else
  17693. mg_snprintf(NULL,
  17694. NULL,
  17695. block,
  17696. sizeof(block),
  17697. ",%s\"compiler\" : \"other\"",
  17698. eol);
  17699. system_info_length += mg_str_append(&buffer, end, block);
  17700. #endif
  17701. }
  17702. /* Determine 32/64 bit data mode.
  17703. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17704. {
  17705. mg_snprintf(NULL,
  17706. NULL,
  17707. block,
  17708. sizeof(block),
  17709. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17710. "char:%u/%u, "
  17711. "ptr:%u, size:%u, time:%u\"",
  17712. eol,
  17713. (unsigned)sizeof(short),
  17714. (unsigned)sizeof(int),
  17715. (unsigned)sizeof(long),
  17716. (unsigned)sizeof(long long),
  17717. (unsigned)sizeof(float),
  17718. (unsigned)sizeof(double),
  17719. (unsigned)sizeof(long double),
  17720. (unsigned)sizeof(char),
  17721. (unsigned)sizeof(wchar_t),
  17722. (unsigned)sizeof(void *),
  17723. (unsigned)sizeof(size_t),
  17724. (unsigned)sizeof(time_t));
  17725. system_info_length += mg_str_append(&buffer, end, block);
  17726. }
  17727. /* Terminate string */
  17728. if (append_eoobj) {
  17729. strcat(append_eoobj, eoobj);
  17730. }
  17731. system_info_length += sizeof(eoobj) - 1;
  17732. return (int)system_info_length;
  17733. }
  17734. /* Get context information. It can be printed or stored by the caller.
  17735. * Return the size of available information. */
  17736. int
  17737. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17738. {
  17739. #if defined(USE_SERVER_STATS)
  17740. char *end, *append_eoobj = NULL, block[256];
  17741. size_t context_info_length = 0;
  17742. #if defined(_WIN32)
  17743. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17744. #else
  17745. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17746. #endif
  17747. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17748. if ((buffer == NULL) || (buflen < 1)) {
  17749. buflen = 0;
  17750. end = buffer;
  17751. } else {
  17752. *buffer = 0;
  17753. end = buffer + buflen;
  17754. }
  17755. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17756. /* has enough space to append eoobj */
  17757. append_eoobj = buffer;
  17758. end -= sizeof(eoobj) - 1;
  17759. }
  17760. context_info_length += mg_str_append(&buffer, end, "{");
  17761. if (ms) { /* <-- should be always true */
  17762. /* Memory information */
  17763. int blockCount = (int)ms->blockCount;
  17764. int64_t totalMemUsed = ms->totalMemUsed;
  17765. int64_t maxMemUsed = ms->maxMemUsed;
  17766. if (totalMemUsed > maxMemUsed) {
  17767. maxMemUsed = totalMemUsed;
  17768. }
  17769. mg_snprintf(NULL,
  17770. NULL,
  17771. block,
  17772. sizeof(block),
  17773. "%s\"memory\" : {%s"
  17774. "\"blocks\" : %i,%s"
  17775. "\"used\" : %" INT64_FMT ",%s"
  17776. "\"maxUsed\" : %" INT64_FMT "%s"
  17777. "}",
  17778. eol,
  17779. eol,
  17780. blockCount,
  17781. eol,
  17782. totalMemUsed,
  17783. eol,
  17784. maxMemUsed,
  17785. eol);
  17786. context_info_length += mg_str_append(&buffer, end, block);
  17787. }
  17788. if (ctx) {
  17789. /* Declare all variables at begin of the block, to comply
  17790. * with old C standards. */
  17791. char start_time_str[64] = {0};
  17792. char now_str[64] = {0};
  17793. time_t start_time = ctx->start_time;
  17794. time_t now = time(NULL);
  17795. int64_t total_data_read, total_data_written;
  17796. int active_connections = (int)ctx->active_connections;
  17797. int max_active_connections = (int)ctx->max_active_connections;
  17798. int total_connections = (int)ctx->total_connections;
  17799. if (active_connections > max_active_connections) {
  17800. max_active_connections = active_connections;
  17801. }
  17802. if (active_connections > total_connections) {
  17803. total_connections = active_connections;
  17804. }
  17805. /* Connections information */
  17806. mg_snprintf(NULL,
  17807. NULL,
  17808. block,
  17809. sizeof(block),
  17810. ",%s\"connections\" : {%s"
  17811. "\"active\" : %i,%s"
  17812. "\"maxActive\" : %i,%s"
  17813. "\"total\" : %i%s"
  17814. "}",
  17815. eol,
  17816. eol,
  17817. active_connections,
  17818. eol,
  17819. max_active_connections,
  17820. eol,
  17821. total_connections,
  17822. eol);
  17823. context_info_length += mg_str_append(&buffer, end, block);
  17824. /* Queue information */
  17825. #if !defined(ALTERNATIVE_QUEUE)
  17826. mg_snprintf(NULL,
  17827. NULL,
  17828. block,
  17829. sizeof(block),
  17830. ",%s\"queue\" : {%s"
  17831. "\"length\" : %i,%s"
  17832. "\"filled\" : %i,%s"
  17833. "\"maxFilled\" : %i,%s"
  17834. "\"full\" : %s%s"
  17835. "}",
  17836. eol,
  17837. eol,
  17838. ctx->sq_size,
  17839. eol,
  17840. ctx->sq_head - ctx->sq_tail,
  17841. eol,
  17842. ctx->sq_max_fill,
  17843. eol,
  17844. (ctx->sq_blocked ? "true" : "false"),
  17845. eol);
  17846. context_info_length += mg_str_append(&buffer, end, block);
  17847. #endif
  17848. /* Requests information */
  17849. mg_snprintf(NULL,
  17850. NULL,
  17851. block,
  17852. sizeof(block),
  17853. ",%s\"requests\" : {%s"
  17854. "\"total\" : %lu%s"
  17855. "}",
  17856. eol,
  17857. eol,
  17858. (unsigned long)ctx->total_requests,
  17859. eol);
  17860. context_info_length += mg_str_append(&buffer, end, block);
  17861. /* Data information */
  17862. total_data_read =
  17863. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  17864. total_data_written =
  17865. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  17866. mg_snprintf(NULL,
  17867. NULL,
  17868. block,
  17869. sizeof(block),
  17870. ",%s\"data\" : {%s"
  17871. "\"read\" : %" INT64_FMT ",%s"
  17872. "\"written\" : %" INT64_FMT "%s"
  17873. "}",
  17874. eol,
  17875. eol,
  17876. total_data_read,
  17877. eol,
  17878. total_data_written,
  17879. eol);
  17880. context_info_length += mg_str_append(&buffer, end, block);
  17881. /* Execution time information */
  17882. gmt_time_string(start_time_str,
  17883. sizeof(start_time_str) - 1,
  17884. &start_time);
  17885. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17886. mg_snprintf(NULL,
  17887. NULL,
  17888. block,
  17889. sizeof(block),
  17890. ",%s\"time\" : {%s"
  17891. "\"uptime\" : %.0f,%s"
  17892. "\"start\" : \"%s\",%s"
  17893. "\"now\" : \"%s\"%s"
  17894. "}",
  17895. eol,
  17896. eol,
  17897. difftime(now, start_time),
  17898. eol,
  17899. start_time_str,
  17900. eol,
  17901. now_str,
  17902. eol);
  17903. context_info_length += mg_str_append(&buffer, end, block);
  17904. }
  17905. /* Terminate string */
  17906. if (append_eoobj) {
  17907. strcat(append_eoobj, eoobj);
  17908. }
  17909. context_info_length += sizeof(eoobj) - 1;
  17910. return (int)context_info_length;
  17911. #else
  17912. (void)ctx;
  17913. if ((buffer != NULL) && (buflen > 0)) {
  17914. *buffer = 0;
  17915. }
  17916. return 0;
  17917. #endif
  17918. }
  17919. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17920. /* Get connection information. It can be printed or stored by the caller.
  17921. * Return the size of available information. */
  17922. int
  17923. mg_get_connection_info(const struct mg_context *ctx,
  17924. int idx,
  17925. char *buffer,
  17926. int buflen)
  17927. {
  17928. const struct mg_connection *conn;
  17929. const struct mg_request_info *ri;
  17930. char *end, *append_eoobj = NULL, block[256];
  17931. size_t connection_info_length = 0;
  17932. int state = 0;
  17933. const char *state_str = "unknown";
  17934. #if defined(_WIN32)
  17935. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17936. #else
  17937. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17938. #endif
  17939. if ((buffer == NULL) || (buflen < 1)) {
  17940. buflen = 0;
  17941. end = buffer;
  17942. } else {
  17943. *buffer = 0;
  17944. end = buffer + buflen;
  17945. }
  17946. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17947. /* has enough space to append eoobj */
  17948. append_eoobj = buffer;
  17949. end -= sizeof(eoobj) - 1;
  17950. }
  17951. if ((ctx == NULL) || (idx < 0)) {
  17952. /* Parameter error */
  17953. return 0;
  17954. }
  17955. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  17956. /* Out of range */
  17957. return 0;
  17958. }
  17959. /* Take connection [idx]. This connection is not locked in
  17960. * any way, so some other thread might use it. */
  17961. conn = (ctx->worker_connections) + idx;
  17962. /* Initialize output string */
  17963. connection_info_length += mg_str_append(&buffer, end, "{");
  17964. /* Init variables */
  17965. ri = &(conn->request_info);
  17966. #if defined(USE_SERVER_STATS)
  17967. state = conn->conn_state;
  17968. /* State as string */
  17969. switch (state) {
  17970. case 0:
  17971. state_str = "undefined";
  17972. break;
  17973. case 1:
  17974. state_str = "not used";
  17975. break;
  17976. case 2:
  17977. state_str = "init";
  17978. break;
  17979. case 3:
  17980. state_str = "ready";
  17981. break;
  17982. case 4:
  17983. state_str = "processing";
  17984. break;
  17985. case 5:
  17986. state_str = "processed";
  17987. break;
  17988. case 6:
  17989. state_str = "to close";
  17990. break;
  17991. case 7:
  17992. state_str = "closing";
  17993. break;
  17994. case 8:
  17995. state_str = "closed";
  17996. break;
  17997. case 9:
  17998. state_str = "done";
  17999. break;
  18000. }
  18001. #endif
  18002. /* Connection info */
  18003. if ((state >= 3) && (state < 9)) {
  18004. mg_snprintf(NULL,
  18005. NULL,
  18006. block,
  18007. sizeof(block),
  18008. "%s\"connection\" : {%s"
  18009. "\"remote\" : {%s"
  18010. "\"protocol\" : \"%s\",%s"
  18011. "\"addr\" : \"%s\",%s"
  18012. "\"port\" : %u%s"
  18013. "},%s"
  18014. "\"handled_requests\" : %u%s"
  18015. "}",
  18016. eol,
  18017. eol,
  18018. eol,
  18019. get_proto_name(conn),
  18020. eol,
  18021. ri->remote_addr,
  18022. eol,
  18023. ri->remote_port,
  18024. eol,
  18025. eol,
  18026. conn->handled_requests,
  18027. eol);
  18028. connection_info_length += mg_str_append(&buffer, end, block);
  18029. }
  18030. /* Request info */
  18031. if ((state >= 4) && (state < 6)) {
  18032. mg_snprintf(NULL,
  18033. NULL,
  18034. block,
  18035. sizeof(block),
  18036. "%s%s\"request_info\" : {%s"
  18037. "\"method\" : \"%s\",%s"
  18038. "\"uri\" : \"%s\",%s"
  18039. "\"query\" : %s%s%s%s"
  18040. "}",
  18041. (connection_info_length > 1 ? "," : ""),
  18042. eol,
  18043. eol,
  18044. ri->request_method,
  18045. eol,
  18046. ri->request_uri,
  18047. eol,
  18048. ri->query_string ? "\"" : "",
  18049. ri->query_string ? ri->query_string : "null",
  18050. ri->query_string ? "\"" : "",
  18051. eol);
  18052. connection_info_length += mg_str_append(&buffer, end, block);
  18053. }
  18054. /* Execution time information */
  18055. if ((state >= 2) && (state < 9)) {
  18056. char start_time_str[64] = {0};
  18057. char close_time_str[64] = {0};
  18058. time_t start_time = conn->conn_birth_time;
  18059. time_t close_time = 0;
  18060. double time_diff;
  18061. gmt_time_string(start_time_str,
  18062. sizeof(start_time_str) - 1,
  18063. &start_time);
  18064. #if defined(USE_SERVER_STATS)
  18065. close_time = conn->conn_close_time;
  18066. #endif
  18067. if (close_time != 0) {
  18068. time_diff = difftime(close_time, start_time);
  18069. gmt_time_string(close_time_str,
  18070. sizeof(close_time_str) - 1,
  18071. &close_time);
  18072. } else {
  18073. time_t now = time(NULL);
  18074. time_diff = difftime(now, start_time);
  18075. close_time_str[0] = 0; /* or use "now" ? */
  18076. }
  18077. mg_snprintf(NULL,
  18078. NULL,
  18079. block,
  18080. sizeof(block),
  18081. "%s%s\"time\" : {%s"
  18082. "\"uptime\" : %.0f,%s"
  18083. "\"start\" : \"%s\",%s"
  18084. "\"closed\" : \"%s\"%s"
  18085. "}",
  18086. (connection_info_length > 1 ? "," : ""),
  18087. eol,
  18088. eol,
  18089. time_diff,
  18090. eol,
  18091. start_time_str,
  18092. eol,
  18093. close_time_str,
  18094. eol);
  18095. connection_info_length += mg_str_append(&buffer, end, block);
  18096. }
  18097. /* Remote user name */
  18098. if ((ri->remote_user) && (state < 9)) {
  18099. mg_snprintf(NULL,
  18100. NULL,
  18101. block,
  18102. sizeof(block),
  18103. "%s%s\"user\" : {%s"
  18104. "\"name\" : \"%s\",%s"
  18105. "}",
  18106. (connection_info_length > 1 ? "," : ""),
  18107. eol,
  18108. eol,
  18109. ri->remote_user,
  18110. eol);
  18111. connection_info_length += mg_str_append(&buffer, end, block);
  18112. }
  18113. /* Data block */
  18114. if (state >= 3) {
  18115. mg_snprintf(NULL,
  18116. NULL,
  18117. block,
  18118. sizeof(block),
  18119. "%s%s\"data\" : {%s"
  18120. "\"read\" : %" INT64_FMT ",%s"
  18121. "\"written\" : %" INT64_FMT "%s"
  18122. "}",
  18123. (connection_info_length > 1 ? "," : ""),
  18124. eol,
  18125. eol,
  18126. conn->consumed_content,
  18127. eol,
  18128. conn->num_bytes_sent,
  18129. eol);
  18130. connection_info_length += mg_str_append(&buffer, end, block);
  18131. }
  18132. /* State */
  18133. mg_snprintf(NULL,
  18134. NULL,
  18135. block,
  18136. sizeof(block),
  18137. "%s%s\"state\" : \"%s\"",
  18138. (connection_info_length > 1 ? "," : ""),
  18139. eol,
  18140. state_str);
  18141. connection_info_length += mg_str_append(&buffer, end, block);
  18142. /* Terminate string */
  18143. if (append_eoobj) {
  18144. strcat(append_eoobj, eoobj);
  18145. }
  18146. connection_info_length += sizeof(eoobj) - 1;
  18147. return (int)connection_info_length;
  18148. }
  18149. #endif
  18150. /* Initialize this library. This function does not need to be thread safe.
  18151. */
  18152. unsigned
  18153. mg_init_library(unsigned features)
  18154. {
  18155. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18156. unsigned features_inited = features_to_init;
  18157. if (mg_init_library_called <= 0) {
  18158. /* Not initialized yet */
  18159. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18160. return 0;
  18161. }
  18162. }
  18163. mg_global_lock();
  18164. if (mg_init_library_called <= 0) {
  18165. #if defined(_WIN32)
  18166. int file_mutex_init = 1;
  18167. int wsa = 1;
  18168. #else
  18169. int mutexattr_init = 1;
  18170. #endif
  18171. int failed = 1;
  18172. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18173. if (key_create == 0) {
  18174. #if defined(_WIN32)
  18175. file_mutex_init =
  18176. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18177. if (file_mutex_init == 0) {
  18178. /* Start WinSock */
  18179. WSADATA data;
  18180. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18181. }
  18182. #else
  18183. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18184. if (mutexattr_init == 0) {
  18185. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18186. PTHREAD_MUTEX_RECURSIVE);
  18187. }
  18188. #endif
  18189. }
  18190. if (failed) {
  18191. #if defined(_WIN32)
  18192. if (wsa == 0) {
  18193. (void)WSACleanup();
  18194. }
  18195. if (file_mutex_init == 0) {
  18196. (void)pthread_mutex_destroy(&global_log_file_lock);
  18197. }
  18198. #else
  18199. if (mutexattr_init == 0) {
  18200. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18201. }
  18202. #endif
  18203. if (key_create == 0) {
  18204. (void)pthread_key_delete(sTlsKey);
  18205. }
  18206. mg_global_unlock();
  18207. (void)pthread_mutex_destroy(&global_lock_mutex);
  18208. return 0;
  18209. }
  18210. #if defined(USE_LUA)
  18211. lua_init_optional_libraries();
  18212. #endif
  18213. }
  18214. mg_global_unlock();
  18215. #if !defined(NO_SSL)
  18216. if (features_to_init & MG_FEATURES_SSL) {
  18217. if (!mg_ssl_initialized) {
  18218. char ebuf[128];
  18219. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18220. mg_ssl_initialized = 1;
  18221. } else {
  18222. (void)ebuf;
  18223. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18224. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18225. }
  18226. } else {
  18227. /* ssl already initialized */
  18228. }
  18229. }
  18230. #endif
  18231. mg_global_lock();
  18232. if (mg_init_library_called <= 0) {
  18233. mg_init_library_called = 1;
  18234. } else {
  18235. mg_init_library_called++;
  18236. }
  18237. mg_global_unlock();
  18238. return features_inited;
  18239. }
  18240. /* Un-initialize this library. */
  18241. unsigned
  18242. mg_exit_library(void)
  18243. {
  18244. if (mg_init_library_called <= 0) {
  18245. return 0;
  18246. }
  18247. mg_global_lock();
  18248. mg_init_library_called--;
  18249. if (mg_init_library_called == 0) {
  18250. #if !defined(NO_SSL)
  18251. if (mg_ssl_initialized) {
  18252. uninitialize_ssl();
  18253. mg_ssl_initialized = 0;
  18254. }
  18255. #endif
  18256. #if defined(_WIN32)
  18257. (void)WSACleanup();
  18258. (void)pthread_mutex_destroy(&global_log_file_lock);
  18259. #else
  18260. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18261. #endif
  18262. (void)pthread_key_delete(sTlsKey);
  18263. #if defined(USE_LUA)
  18264. lua_exit_optional_libraries();
  18265. #endif
  18266. mg_global_unlock();
  18267. (void)pthread_mutex_destroy(&global_lock_mutex);
  18268. return 1;
  18269. }
  18270. mg_global_unlock();
  18271. return 1;
  18272. }
  18273. /* End of civetweb.c */