civetweb.c 576 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432
  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 (1024 * 16)
  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. #if !defined(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. #if defined(USE_ZLIB)
  376. #include "zconf.h"
  377. #include "zlib.h"
  378. #endif
  379. #if defined(USE_MBEDTLS)
  380. #include "mod_mbedtls.inl"
  381. #endif
  382. /********************************************************************/
  383. /* CivetWeb configuration defines */
  384. /********************************************************************/
  385. /* Maximum number of threads that can be configured.
  386. * The number of threads actually created depends on the "num_threads"
  387. * configuration parameter, but this is the upper limit. */
  388. #if !defined(MAX_WORKER_THREADS)
  389. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  390. #endif
  391. /* Timeout interval for select/poll calls.
  392. * The timeouts depend on "*_timeout_ms" configuration values, but long
  393. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  394. * This reduces the time required to stop the server. */
  395. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  396. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  397. #endif
  398. /* Do not try to compress files smaller than this limit. */
  399. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  400. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  401. #endif
  402. #if !defined(PASSWORDS_FILE_NAME)
  403. #define PASSWORDS_FILE_NAME ".htpasswd"
  404. #endif
  405. /* Initial buffer size for all CGI environment variables. In case there is
  406. * not enough space, another block is allocated. */
  407. #if !defined(CGI_ENVIRONMENT_SIZE)
  408. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  409. #endif
  410. /* Maximum number of environment variables. */
  411. #if !defined(MAX_CGI_ENVIR_VARS)
  412. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  413. #endif
  414. /* General purpose buffer size. */
  415. #if !defined(MG_BUF_LEN) /* in bytes */
  416. #define MG_BUF_LEN (1024 * 8)
  417. #endif
  418. /********************************************************************/
  419. /* Helper makros */
  420. #if !defined(ARRAY_SIZE)
  421. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  422. #endif
  423. #include <stdint.h>
  424. /* Standard defines */
  425. #if !defined(INT64_MAX)
  426. #define INT64_MAX (9223372036854775807)
  427. #endif
  428. #define SHUTDOWN_RD (0)
  429. #define SHUTDOWN_WR (1)
  430. #define SHUTDOWN_BOTH (2)
  431. mg_static_assert(MAX_WORKER_THREADS >= 1,
  432. "worker threads must be a positive number");
  433. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  434. "size_t data type size check");
  435. #if defined(_WIN32) /* WINDOWS include block */
  436. #include <malloc.h> /* *alloc( */
  437. #include <stdlib.h> /* *alloc( */
  438. #include <time.h> /* struct timespec */
  439. #include <windows.h>
  440. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  441. #include <ws2tcpip.h>
  442. typedef const char *SOCK_OPT_TYPE;
  443. #if !defined(PATH_MAX)
  444. #define W_PATH_MAX (MAX_PATH)
  445. /* at most three UTF-8 chars per wchar_t */
  446. #define PATH_MAX (W_PATH_MAX * 3)
  447. #else
  448. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  449. #endif
  450. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  451. #if !defined(_IN_PORT_T)
  452. #if !defined(in_port_t)
  453. #define in_port_t u_short
  454. #endif
  455. #endif
  456. #if !defined(_WIN32_WCE)
  457. #include <direct.h>
  458. #include <io.h>
  459. #include <process.h>
  460. #else /* _WIN32_WCE */
  461. #define NO_CGI /* WinCE has no pipes */
  462. #define NO_POPEN /* WinCE has no popen */
  463. typedef long off_t;
  464. #define errno ((int)(GetLastError()))
  465. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  466. #endif /* _WIN32_WCE */
  467. #define MAKEUQUAD(lo, hi) \
  468. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  469. #define RATE_DIFF (10000000) /* 100 nsecs */
  470. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  471. #define SYS2UNIX_TIME(lo, hi) \
  472. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  473. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  474. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  475. * Also use _strtoui64 on modern M$ compilers */
  476. #if defined(_MSC_VER)
  477. #if (_MSC_VER < 1300)
  478. #define STRX(x) #x
  479. #define STR(x) STRX(x)
  480. #define __func__ __FILE__ ":" STR(__LINE__)
  481. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  482. #define strtoll(x, y, z) (_atoi64(x))
  483. #else
  484. #define __func__ __FUNCTION__
  485. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  486. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  487. #endif
  488. #endif /* _MSC_VER */
  489. #define ERRNO ((int)(GetLastError()))
  490. #define NO_SOCKLEN_T
  491. #if defined(_WIN64) || defined(__MINGW64__)
  492. #if !defined(SSL_LIB)
  493. #if defined(OPENSSL_API_1_1)
  494. #define SSL_LIB "libssl-1_1-x64.dll"
  495. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  496. #endif /* OPENSSL_API_1_1 */
  497. #if defined(OPENSSL_API_1_0)
  498. #define SSL_LIB "ssleay64.dll"
  499. #define CRYPTO_LIB "libeay64.dll"
  500. #endif /* OPENSSL_API_1_0 */
  501. #endif
  502. #else /* defined(_WIN64) || defined(__MINGW64__) */
  503. #if !defined(SSL_LIB)
  504. #if defined(OPENSSL_API_1_1)
  505. #define SSL_LIB "libssl-1_1.dll"
  506. #define CRYPTO_LIB "libcrypto-1_1.dll"
  507. #endif /* OPENSSL_API_1_1 */
  508. #if defined(OPENSSL_API_1_0)
  509. #define SSL_LIB "ssleay32.dll"
  510. #define CRYPTO_LIB "libeay32.dll"
  511. #endif /* OPENSSL_API_1_0 */
  512. #endif /* SSL_LIB */
  513. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  514. #define O_NONBLOCK (0)
  515. #if !defined(W_OK)
  516. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  517. #endif
  518. #define _POSIX_
  519. #define INT64_FMT "I64d"
  520. #define UINT64_FMT "I64u"
  521. #define WINCDECL __cdecl
  522. #define vsnprintf_impl _vsnprintf
  523. #define access _access
  524. #define mg_sleep(x) (Sleep(x))
  525. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  526. #if !defined(popen)
  527. #define popen(x, y) (_popen(x, y))
  528. #endif
  529. #if !defined(pclose)
  530. #define pclose(x) (_pclose(x))
  531. #endif
  532. #define close(x) (_close(x))
  533. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  534. #define RTLD_LAZY (0)
  535. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  536. #define fdopen(x, y) (_fdopen((x), (y)))
  537. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  538. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  539. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  540. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  541. #define sleep(x) (Sleep((x)*1000))
  542. #define rmdir(x) (_rmdir(x))
  543. #if defined(_WIN64) || !defined(__MINGW32__)
  544. /* Only MinGW 32 bit is missing this function */
  545. #define timegm(x) (_mkgmtime(x))
  546. #else
  547. time_t timegm(struct tm *tm);
  548. #define NEED_TIMEGM
  549. #endif
  550. #if !defined(fileno)
  551. #define fileno(x) (_fileno(x))
  552. #endif /* !fileno MINGW #defines fileno */
  553. typedef struct {
  554. CRITICAL_SECTION sec; /* Immovable */
  555. } pthread_mutex_t;
  556. typedef DWORD pthread_key_t;
  557. typedef HANDLE pthread_t;
  558. typedef struct {
  559. pthread_mutex_t threadIdSec;
  560. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  561. } pthread_cond_t;
  562. #if !defined(__clockid_t_defined)
  563. typedef DWORD clockid_t;
  564. #endif
  565. #if !defined(CLOCK_MONOTONIC)
  566. #define CLOCK_MONOTONIC (1)
  567. #endif
  568. #if !defined(CLOCK_REALTIME)
  569. #define CLOCK_REALTIME (2)
  570. #endif
  571. #if !defined(CLOCK_THREAD)
  572. #define CLOCK_THREAD (3)
  573. #endif
  574. #if !defined(CLOCK_PROCESS)
  575. #define CLOCK_PROCESS (4)
  576. #endif
  577. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  578. #define _TIMESPEC_DEFINED
  579. #endif
  580. #if !defined(_TIMESPEC_DEFINED)
  581. struct timespec {
  582. time_t tv_sec; /* seconds */
  583. long tv_nsec; /* nanoseconds */
  584. };
  585. #endif
  586. #if !defined(WIN_PTHREADS_TIME_H)
  587. #define MUST_IMPLEMENT_CLOCK_GETTIME
  588. #endif
  589. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  590. #define clock_gettime mg_clock_gettime
  591. static int
  592. clock_gettime(clockid_t clk_id, struct timespec *tp)
  593. {
  594. FILETIME ft;
  595. ULARGE_INTEGER li, li2;
  596. BOOL ok = FALSE;
  597. double d;
  598. static double perfcnt_per_sec = 0.0;
  599. static BOOL initialized = FALSE;
  600. if (!initialized) {
  601. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  602. perfcnt_per_sec = 1.0 / li.QuadPart;
  603. initialized = TRUE;
  604. }
  605. if (tp) {
  606. memset(tp, 0, sizeof(*tp));
  607. if (clk_id == CLOCK_REALTIME) {
  608. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  609. GetSystemTimeAsFileTime(&ft);
  610. li.LowPart = ft.dwLowDateTime;
  611. li.HighPart = ft.dwHighDateTime;
  612. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  613. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  614. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  615. ok = TRUE;
  616. /* END: CLOCK_REALTIME */
  617. } else if (clk_id == CLOCK_MONOTONIC) {
  618. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  619. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  620. d = li.QuadPart * perfcnt_per_sec;
  621. tp->tv_sec = (time_t)d;
  622. d -= (double)tp->tv_sec;
  623. tp->tv_nsec = (long)(d * 1.0E9);
  624. ok = TRUE;
  625. /* END: CLOCK_MONOTONIC */
  626. } else if (clk_id == CLOCK_THREAD) {
  627. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  628. FILETIME t_create, t_exit, t_kernel, t_user;
  629. if (GetThreadTimes(GetCurrentThread(),
  630. &t_create,
  631. &t_exit,
  632. &t_kernel,
  633. &t_user)) {
  634. li.LowPart = t_user.dwLowDateTime;
  635. li.HighPart = t_user.dwHighDateTime;
  636. li2.LowPart = t_kernel.dwLowDateTime;
  637. li2.HighPart = t_kernel.dwHighDateTime;
  638. li.QuadPart += li2.QuadPart;
  639. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  640. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  641. ok = TRUE;
  642. }
  643. /* END: CLOCK_THREAD */
  644. } else if (clk_id == CLOCK_PROCESS) {
  645. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  646. FILETIME t_create, t_exit, t_kernel, t_user;
  647. if (GetProcessTimes(GetCurrentProcess(),
  648. &t_create,
  649. &t_exit,
  650. &t_kernel,
  651. &t_user)) {
  652. li.LowPart = t_user.dwLowDateTime;
  653. li.HighPart = t_user.dwHighDateTime;
  654. li2.LowPart = t_kernel.dwLowDateTime;
  655. li2.HighPart = t_kernel.dwHighDateTime;
  656. li.QuadPart += li2.QuadPart;
  657. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  658. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  659. ok = TRUE;
  660. }
  661. /* END: CLOCK_PROCESS */
  662. } else {
  663. /* BEGIN: unknown clock */
  664. /* ok = FALSE; already set by init */
  665. /* END: unknown clock */
  666. }
  667. }
  668. return ok ? 0 : -1;
  669. }
  670. #endif
  671. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  672. static int pthread_mutex_lock(pthread_mutex_t *);
  673. static int pthread_mutex_unlock(pthread_mutex_t *);
  674. static void path_to_unicode(const struct mg_connection *conn,
  675. const char *path,
  676. wchar_t *wbuf,
  677. size_t wbuf_len);
  678. /* All file operations need to be rewritten to solve #246. */
  679. struct mg_file;
  680. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  681. /* POSIX dirent interface */
  682. struct dirent {
  683. char d_name[PATH_MAX];
  684. };
  685. typedef struct DIR {
  686. HANDLE handle;
  687. WIN32_FIND_DATAW info;
  688. struct dirent result;
  689. } DIR;
  690. #if defined(HAVE_POLL)
  691. #define mg_pollfd pollfd
  692. #else
  693. struct mg_pollfd {
  694. SOCKET fd;
  695. short events;
  696. short revents;
  697. };
  698. #endif
  699. /* Mark required libraries */
  700. #if defined(_MSC_VER)
  701. #pragma comment(lib, "Ws2_32.lib")
  702. #endif
  703. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  704. #include <inttypes.h>
  705. typedef const void *SOCK_OPT_TYPE;
  706. #if defined(ANDROID)
  707. typedef unsigned short int in_port_t;
  708. #endif
  709. #if !defined(__ZEPHYR__)
  710. #include <arpa/inet.h>
  711. #include <ctype.h>
  712. #include <dirent.h>
  713. #include <grp.h>
  714. #include <limits.h>
  715. #include <netdb.h>
  716. #include <netinet/in.h>
  717. #include <netinet/tcp.h>
  718. #include <pthread.h>
  719. #include <pwd.h>
  720. #include <stdarg.h>
  721. #include <stddef.h>
  722. #include <stdio.h>
  723. #include <stdlib.h>
  724. #include <string.h>
  725. #include <sys/poll.h>
  726. #include <sys/socket.h>
  727. #include <sys/time.h>
  728. #include <sys/utsname.h>
  729. #include <sys/wait.h>
  730. #include <time.h>
  731. #include <unistd.h>
  732. #endif
  733. #define vsnprintf_impl vsnprintf
  734. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  735. #include <dlfcn.h>
  736. #endif
  737. #if defined(__MACH__)
  738. #define SSL_LIB "libssl.dylib"
  739. #define CRYPTO_LIB "libcrypto.dylib"
  740. #else
  741. #if !defined(SSL_LIB)
  742. #define SSL_LIB "libssl.so"
  743. #endif
  744. #if !defined(CRYPTO_LIB)
  745. #define CRYPTO_LIB "libcrypto.so"
  746. #endif
  747. #endif
  748. #if !defined(O_BINARY)
  749. #define O_BINARY (0)
  750. #endif /* O_BINARY */
  751. #define closesocket(a) (close(a))
  752. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  753. #define mg_remove(conn, x) (remove(x))
  754. #define mg_sleep(x) (usleep((x)*1000))
  755. #define mg_opendir(conn, x) (opendir(x))
  756. #define mg_closedir(x) (closedir(x))
  757. #define mg_readdir(x) (readdir(x))
  758. #define ERRNO (errno)
  759. #define INVALID_SOCKET (-1)
  760. #define INT64_FMT PRId64
  761. #define UINT64_FMT PRIu64
  762. typedef int SOCKET;
  763. #define WINCDECL
  764. #if defined(__hpux)
  765. /* HPUX 11 does not have monotonic, fall back to realtime */
  766. #if !defined(CLOCK_MONOTONIC)
  767. #define CLOCK_MONOTONIC CLOCK_REALTIME
  768. #endif
  769. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  770. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  771. * the prototypes use int* rather than socklen_t* which matches the
  772. * actual library expectation. When called with the wrong size arg
  773. * accept() returns a zero client inet addr and check_acl() always
  774. * fails. Since socklen_t is widely used below, just force replace
  775. * their typedef with int. - DTL
  776. */
  777. #define socklen_t int
  778. #endif /* hpux */
  779. #define mg_pollfd pollfd
  780. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  781. /* In case our C library is missing "timegm", provide an implementation */
  782. #if defined(NEED_TIMEGM)
  783. static inline int
  784. is_leap(int y)
  785. {
  786. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  787. }
  788. static inline int
  789. count_leap(int y)
  790. {
  791. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  792. }
  793. time_t
  794. timegm(struct tm *tm)
  795. {
  796. static const unsigned short ydays[] = {
  797. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  798. int year = tm->tm_year + 1900;
  799. int mon = tm->tm_mon;
  800. int mday = tm->tm_mday - 1;
  801. int hour = tm->tm_hour;
  802. int min = tm->tm_min;
  803. int sec = tm->tm_sec;
  804. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  805. || (mday >= ydays[mon + 1] - ydays[mon]
  806. + (mon == 1 && is_leap(year) ? 1 : 0))
  807. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  808. return -1;
  809. time_t res = year - 1970;
  810. res *= 365;
  811. res += mday;
  812. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  813. res += count_leap(year);
  814. res *= 24;
  815. res += hour;
  816. res *= 60;
  817. res += min;
  818. res *= 60;
  819. res += sec;
  820. return res;
  821. }
  822. #endif /* NEED_TIMEGM */
  823. /* va_copy should always be a macro, C99 and C++11 - DTL */
  824. #if !defined(va_copy)
  825. #define va_copy(x, y) ((x) = (y))
  826. #endif
  827. #if defined(_WIN32)
  828. /* Create substitutes for POSIX functions in Win32. */
  829. #if defined(GCC_DIAGNOSTIC)
  830. /* Show no warning in case system functions are not used. */
  831. #pragma GCC diagnostic push
  832. #pragma GCC diagnostic ignored "-Wunused-function"
  833. #endif
  834. static pthread_mutex_t global_log_file_lock;
  835. FUNCTION_MAY_BE_UNUSED
  836. static DWORD
  837. pthread_self(void)
  838. {
  839. return GetCurrentThreadId();
  840. }
  841. FUNCTION_MAY_BE_UNUSED
  842. static int
  843. pthread_key_create(
  844. pthread_key_t *key,
  845. void (*_ignored)(void *) /* destructor not supported for Windows */
  846. )
  847. {
  848. (void)_ignored;
  849. if ((key != 0)) {
  850. *key = TlsAlloc();
  851. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  852. }
  853. return -2;
  854. }
  855. FUNCTION_MAY_BE_UNUSED
  856. static int
  857. pthread_key_delete(pthread_key_t key)
  858. {
  859. return TlsFree(key) ? 0 : 1;
  860. }
  861. FUNCTION_MAY_BE_UNUSED
  862. static int
  863. pthread_setspecific(pthread_key_t key, void *value)
  864. {
  865. return TlsSetValue(key, value) ? 0 : 1;
  866. }
  867. FUNCTION_MAY_BE_UNUSED
  868. static void *
  869. pthread_getspecific(pthread_key_t key)
  870. {
  871. return TlsGetValue(key);
  872. }
  873. #if defined(GCC_DIAGNOSTIC)
  874. /* Enable unused function warning again */
  875. #pragma GCC diagnostic pop
  876. #endif
  877. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  878. #else
  879. static pthread_mutexattr_t pthread_mutex_attr;
  880. #endif /* _WIN32 */
  881. #if defined(_WIN32_WCE)
  882. /* Create substitutes for POSIX functions in Win32. */
  883. #if defined(GCC_DIAGNOSTIC)
  884. /* Show no warning in case system functions are not used. */
  885. #pragma GCC diagnostic push
  886. #pragma GCC diagnostic ignored "-Wunused-function"
  887. #endif
  888. FUNCTION_MAY_BE_UNUSED
  889. static time_t
  890. time(time_t *ptime)
  891. {
  892. time_t t;
  893. SYSTEMTIME st;
  894. FILETIME ft;
  895. GetSystemTime(&st);
  896. SystemTimeToFileTime(&st, &ft);
  897. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  898. if (ptime != NULL) {
  899. *ptime = t;
  900. }
  901. return t;
  902. }
  903. FUNCTION_MAY_BE_UNUSED
  904. static struct tm *
  905. localtime_s(const time_t *ptime, struct tm *ptm)
  906. {
  907. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  908. FILETIME ft, lft;
  909. SYSTEMTIME st;
  910. TIME_ZONE_INFORMATION tzinfo;
  911. if (ptm == NULL) {
  912. return NULL;
  913. }
  914. *(int64_t *)&ft = t;
  915. FileTimeToLocalFileTime(&ft, &lft);
  916. FileTimeToSystemTime(&lft, &st);
  917. ptm->tm_year = st.wYear - 1900;
  918. ptm->tm_mon = st.wMonth - 1;
  919. ptm->tm_wday = st.wDayOfWeek;
  920. ptm->tm_mday = st.wDay;
  921. ptm->tm_hour = st.wHour;
  922. ptm->tm_min = st.wMinute;
  923. ptm->tm_sec = st.wSecond;
  924. ptm->tm_yday = 0; /* hope nobody uses this */
  925. ptm->tm_isdst =
  926. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  927. return ptm;
  928. }
  929. FUNCTION_MAY_BE_UNUSED
  930. static struct tm *
  931. gmtime_s(const time_t *ptime, struct tm *ptm)
  932. {
  933. /* FIXME(lsm): fix this. */
  934. return localtime_s(ptime, ptm);
  935. }
  936. static ptrdiff_t mg_atomic_inc(volatile ptrdiff_t *addr);
  937. static struct tm tm_array[MAX_WORKER_THREADS]; /* Must be 2^n */
  938. static volatile ptrdiff_t tm_index = 0;
  939. FUNCTION_MAY_BE_UNUSED
  940. static struct tm *
  941. localtime(const time_t *ptime)
  942. {
  943. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  944. return localtime_s(ptime, tm_array + i);
  945. }
  946. FUNCTION_MAY_BE_UNUSED
  947. static struct tm *
  948. gmtime(const time_t *ptime)
  949. {
  950. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  951. return gmtime_s(ptime, tm_array + i);
  952. }
  953. FUNCTION_MAY_BE_UNUSED
  954. static size_t
  955. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  956. {
  957. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  958. * for WinCE"); */
  959. return 0;
  960. }
  961. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  962. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  963. #define remove(f) mg_remove(NULL, f)
  964. FUNCTION_MAY_BE_UNUSED
  965. static int
  966. rename(const char *a, const char *b)
  967. {
  968. wchar_t wa[W_PATH_MAX];
  969. wchar_t wb[W_PATH_MAX];
  970. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  971. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  972. return MoveFileW(wa, wb) ? 0 : -1;
  973. }
  974. struct stat {
  975. int64_t st_size;
  976. time_t st_mtime;
  977. };
  978. FUNCTION_MAY_BE_UNUSED
  979. static int
  980. stat(const char *name, struct stat *st)
  981. {
  982. wchar_t wbuf[W_PATH_MAX];
  983. WIN32_FILE_ATTRIBUTE_DATA attr;
  984. time_t creation_time, write_time;
  985. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  986. memset(&attr, 0, sizeof(attr));
  987. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  988. st->st_size =
  989. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  990. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  991. attr.ftLastWriteTime.dwHighDateTime);
  992. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  993. attr.ftCreationTime.dwHighDateTime);
  994. if (creation_time > write_time) {
  995. st->st_mtime = creation_time;
  996. } else {
  997. st->st_mtime = write_time;
  998. }
  999. return 0;
  1000. }
  1001. #define access(x, a) 1 /* not required anyway */
  1002. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  1003. /* Values from errno.h in Windows SDK (Visual Studio). */
  1004. #define EEXIST 17
  1005. #define EACCES 13
  1006. #define ENOENT 2
  1007. #if defined(GCC_DIAGNOSTIC)
  1008. /* Enable unused function warning again */
  1009. #pragma GCC diagnostic pop
  1010. #endif
  1011. #endif /* defined(_WIN32_WCE) */
  1012. #if defined(GCC_DIAGNOSTIC)
  1013. /* Show no warning in case system functions are not used. */
  1014. #pragma GCC diagnostic push
  1015. #pragma GCC diagnostic ignored "-Wunused-function"
  1016. #endif /* defined(GCC_DIAGNOSTIC) */
  1017. #if defined(__clang__)
  1018. /* Show no warning in case system functions are not used. */
  1019. #pragma clang diagnostic push
  1020. #pragma clang diagnostic ignored "-Wunused-function"
  1021. #endif
  1022. static pthread_mutex_t global_lock_mutex;
  1023. FUNCTION_MAY_BE_UNUSED
  1024. static void
  1025. mg_global_lock(void)
  1026. {
  1027. (void)pthread_mutex_lock(&global_lock_mutex);
  1028. }
  1029. FUNCTION_MAY_BE_UNUSED
  1030. static void
  1031. mg_global_unlock(void)
  1032. {
  1033. (void)pthread_mutex_unlock(&global_lock_mutex);
  1034. }
  1035. #if defined(_WIN64)
  1036. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  1037. #elif defined(_WIN32)
  1038. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  1039. #endif
  1040. /* Atomic functions working on ptrdiff_t ("signed size_t").
  1041. * Operations: Increment, Decrement, Add, Maximum.
  1042. * Up to size_t, they do not an atomic "load" operation.
  1043. */
  1044. FUNCTION_MAY_BE_UNUSED
  1045. static ptrdiff_t
  1046. mg_atomic_inc(volatile ptrdiff_t *addr)
  1047. {
  1048. ptrdiff_t ret;
  1049. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1050. ret = InterlockedIncrement64(addr);
  1051. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1052. ret = InterlockedIncrement(addr);
  1053. #elif defined(__GNUC__) \
  1054. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1055. && !defined(NO_ATOMICS)
  1056. ret = __sync_add_and_fetch(addr, 1);
  1057. #else
  1058. mg_global_lock();
  1059. ret = (++(*addr));
  1060. mg_global_unlock();
  1061. #endif
  1062. return ret;
  1063. }
  1064. FUNCTION_MAY_BE_UNUSED
  1065. static ptrdiff_t
  1066. mg_atomic_dec(volatile ptrdiff_t *addr)
  1067. {
  1068. ptrdiff_t ret;
  1069. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1070. ret = InterlockedDecrement64(addr);
  1071. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1072. ret = InterlockedDecrement(addr);
  1073. #elif defined(__GNUC__) \
  1074. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1075. && !defined(NO_ATOMICS)
  1076. ret = __sync_sub_and_fetch(addr, 1);
  1077. #else
  1078. mg_global_lock();
  1079. ret = (--(*addr));
  1080. mg_global_unlock();
  1081. #endif
  1082. return ret;
  1083. }
  1084. #if defined(USE_SERVER_STATS)
  1085. static ptrdiff_t
  1086. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1087. {
  1088. ptrdiff_t ret;
  1089. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1090. ret = InterlockedAdd64(addr, value);
  1091. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1092. ret = InterlockedExchangeAdd(addr, value) + value;
  1093. #elif defined(__GNUC__) \
  1094. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1095. && !defined(NO_ATOMICS)
  1096. ret = __sync_add_and_fetch(addr, value);
  1097. #else
  1098. mg_global_lock();
  1099. *addr += value;
  1100. ret = (*addr);
  1101. mg_global_unlock();
  1102. #endif
  1103. return ret;
  1104. }
  1105. FUNCTION_MAY_BE_UNUSED
  1106. static ptrdiff_t
  1107. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1108. ptrdiff_t oldval,
  1109. ptrdiff_t newval)
  1110. {
  1111. ptrdiff_t ret;
  1112. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1113. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1114. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1115. ret = InterlockedCompareExchange(addr, newval, oldval);
  1116. #elif defined(__GNUC__) \
  1117. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1118. && !defined(NO_ATOMICS)
  1119. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1120. #else
  1121. mg_global_lock();
  1122. ret = *addr;
  1123. if ((ret != newval) && (ret == oldval)) {
  1124. *addr = newval;
  1125. }
  1126. mg_global_unlock();
  1127. #endif
  1128. return ret;
  1129. }
  1130. static void
  1131. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1132. {
  1133. register ptrdiff_t tmp = *addr;
  1134. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1135. while (tmp < value) {
  1136. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1137. }
  1138. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1139. while (tmp < value) {
  1140. tmp = InterlockedCompareExchange(addr, value, tmp);
  1141. }
  1142. #elif defined(__GNUC__) \
  1143. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1144. && !defined(NO_ATOMICS)
  1145. while (tmp < value) {
  1146. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1147. }
  1148. #else
  1149. mg_global_lock();
  1150. if (*addr < value) {
  1151. *addr = value;
  1152. }
  1153. mg_global_unlock();
  1154. #endif
  1155. }
  1156. static int64_t
  1157. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1158. {
  1159. int64_t ret;
  1160. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1161. ret = InterlockedAdd64(addr, value);
  1162. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1163. ret = InterlockedExchangeAdd64(addr, value) + value;
  1164. #elif defined(__GNUC__) \
  1165. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1166. && !defined(NO_ATOMICS)
  1167. ret = __sync_add_and_fetch(addr, value);
  1168. #else
  1169. mg_global_lock();
  1170. *addr += value;
  1171. ret = (*addr);
  1172. mg_global_unlock();
  1173. #endif
  1174. return ret;
  1175. }
  1176. #endif
  1177. #if defined(GCC_DIAGNOSTIC)
  1178. /* Show no warning in case system functions are not used. */
  1179. #pragma GCC diagnostic pop
  1180. #endif /* defined(GCC_DIAGNOSTIC) */
  1181. #if defined(__clang__)
  1182. /* Show no warning in case system functions are not used. */
  1183. #pragma clang diagnostic pop
  1184. #endif
  1185. #if defined(USE_SERVER_STATS)
  1186. struct mg_memory_stat {
  1187. volatile ptrdiff_t totalMemUsed;
  1188. volatile ptrdiff_t maxMemUsed;
  1189. volatile ptrdiff_t blockCount;
  1190. };
  1191. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1192. static void *
  1193. mg_malloc_ex(size_t size,
  1194. struct mg_context *ctx,
  1195. const char *file,
  1196. unsigned line)
  1197. {
  1198. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1199. void *memory = 0;
  1200. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1201. #if defined(MEMORY_DEBUGGING)
  1202. char mallocStr[256];
  1203. #else
  1204. (void)file;
  1205. (void)line;
  1206. #endif
  1207. if (data) {
  1208. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1209. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1210. mg_atomic_inc(&mstat->blockCount);
  1211. ((uintptr_t *)data)[0] = size;
  1212. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1213. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1214. }
  1215. #if defined(MEMORY_DEBUGGING)
  1216. sprintf(mallocStr,
  1217. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1218. memory,
  1219. (unsigned long)size,
  1220. (unsigned long)mstat->totalMemUsed,
  1221. (unsigned long)mstat->blockCount,
  1222. file,
  1223. line);
  1224. DEBUG_TRACE("%s", mallocStr);
  1225. #endif
  1226. return memory;
  1227. }
  1228. static void *
  1229. mg_calloc_ex(size_t count,
  1230. size_t size,
  1231. struct mg_context *ctx,
  1232. const char *file,
  1233. unsigned line)
  1234. {
  1235. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1236. if (data) {
  1237. memset(data, 0, size * count);
  1238. }
  1239. return data;
  1240. }
  1241. static void
  1242. mg_free_ex(void *memory, const char *file, unsigned line)
  1243. {
  1244. #if defined(MEMORY_DEBUGGING)
  1245. char mallocStr[256];
  1246. #else
  1247. (void)file;
  1248. (void)line;
  1249. #endif
  1250. if (memory) {
  1251. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1252. uintptr_t size = ((uintptr_t *)data)[0];
  1253. struct mg_memory_stat *mstat =
  1254. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1255. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1256. mg_atomic_dec(&mstat->blockCount);
  1257. #if defined(MEMORY_DEBUGGING)
  1258. sprintf(mallocStr,
  1259. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1260. memory,
  1261. (unsigned long)size,
  1262. (unsigned long)mstat->totalMemUsed,
  1263. (unsigned long)mstat->blockCount,
  1264. file,
  1265. line);
  1266. DEBUG_TRACE("%s", mallocStr);
  1267. #endif
  1268. free(data);
  1269. }
  1270. }
  1271. static void *
  1272. mg_realloc_ex(void *memory,
  1273. size_t newsize,
  1274. struct mg_context *ctx,
  1275. const char *file,
  1276. unsigned line)
  1277. {
  1278. void *data;
  1279. void *_realloc;
  1280. uintptr_t oldsize;
  1281. #if defined(MEMORY_DEBUGGING)
  1282. char mallocStr[256];
  1283. #else
  1284. (void)file;
  1285. (void)line;
  1286. #endif
  1287. if (newsize) {
  1288. if (memory) {
  1289. /* Reallocate existing block */
  1290. struct mg_memory_stat *mstat;
  1291. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1292. oldsize = ((uintptr_t *)data)[0];
  1293. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1294. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1295. if (_realloc) {
  1296. data = _realloc;
  1297. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1298. #if defined(MEMORY_DEBUGGING)
  1299. sprintf(mallocStr,
  1300. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1301. memory,
  1302. (unsigned long)oldsize,
  1303. (unsigned long)mstat->totalMemUsed,
  1304. (unsigned long)mstat->blockCount,
  1305. file,
  1306. line);
  1307. DEBUG_TRACE("%s", mallocStr);
  1308. #endif
  1309. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1310. #if defined(MEMORY_DEBUGGING)
  1311. sprintf(mallocStr,
  1312. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1313. memory,
  1314. (unsigned long)newsize,
  1315. (unsigned long)mstat->totalMemUsed,
  1316. (unsigned long)mstat->blockCount,
  1317. file,
  1318. line);
  1319. DEBUG_TRACE("%s", mallocStr);
  1320. #endif
  1321. *(uintptr_t *)data = newsize;
  1322. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1323. } else {
  1324. #if defined(MEMORY_DEBUGGING)
  1325. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1326. #endif
  1327. return _realloc;
  1328. }
  1329. } else {
  1330. /* Allocate new block */
  1331. data = mg_malloc_ex(newsize, ctx, file, line);
  1332. }
  1333. } else {
  1334. /* Free existing block */
  1335. data = 0;
  1336. mg_free_ex(memory, file, line);
  1337. }
  1338. return data;
  1339. }
  1340. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1341. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1342. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1343. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1344. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1345. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1346. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1347. #else /* USE_SERVER_STATS */
  1348. static __inline void *
  1349. mg_malloc(size_t a)
  1350. {
  1351. return malloc(a);
  1352. }
  1353. static __inline void *
  1354. mg_calloc(size_t a, size_t b)
  1355. {
  1356. return calloc(a, b);
  1357. }
  1358. static __inline void *
  1359. mg_realloc(void *a, size_t b)
  1360. {
  1361. return realloc(a, b);
  1362. }
  1363. static __inline void
  1364. mg_free(void *a)
  1365. {
  1366. free(a);
  1367. }
  1368. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1369. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1370. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1371. #define mg_free_ctx(a, c) mg_free(a)
  1372. #endif /* USE_SERVER_STATS */
  1373. static void mg_vsnprintf(const struct mg_connection *conn,
  1374. int *truncated,
  1375. char *buf,
  1376. size_t buflen,
  1377. const char *fmt,
  1378. va_list ap);
  1379. static void mg_snprintf(const struct mg_connection *conn,
  1380. int *truncated,
  1381. char *buf,
  1382. size_t buflen,
  1383. PRINTF_FORMAT_STRING(const char *fmt),
  1384. ...) PRINTF_ARGS(5, 6);
  1385. /* This following lines are just meant as a reminder to use the mg-functions
  1386. * for memory management */
  1387. #if defined(malloc)
  1388. #undef malloc
  1389. #endif
  1390. #if defined(calloc)
  1391. #undef calloc
  1392. #endif
  1393. #if defined(realloc)
  1394. #undef realloc
  1395. #endif
  1396. #if defined(free)
  1397. #undef free
  1398. #endif
  1399. #if defined(snprintf)
  1400. #undef snprintf
  1401. #endif
  1402. #if defined(vsnprintf)
  1403. #undef vsnprintf
  1404. #endif
  1405. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1406. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1407. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1408. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1409. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1410. #if defined(_WIN32)
  1411. /* vsnprintf must not be used in any system,
  1412. * but this define only works well for Windows. */
  1413. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1414. #endif
  1415. /* mg_init_library counter */
  1416. static int mg_init_library_called = 0;
  1417. #if !defined(NO_SSL)
  1418. static int mg_ssl_initialized = 0;
  1419. /* TODO: Selection of SSL library and version */
  1420. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1)
  1421. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1422. #endif
  1423. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1424. #error "Multiple OPENSSL_API versions defined"
  1425. #endif
  1426. #endif /* NO_SSL */
  1427. static pthread_key_t sTlsKey; /* Thread local storage index */
  1428. static volatile ptrdiff_t thread_idx_max = 0;
  1429. #if defined(MG_LEGACY_INTERFACE)
  1430. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1431. #endif
  1432. struct mg_workerTLS {
  1433. int is_master;
  1434. unsigned long thread_idx;
  1435. void *user_ptr;
  1436. #if defined(_WIN32)
  1437. HANDLE pthread_cond_helper_mutex;
  1438. struct mg_workerTLS *next_waiting_thread;
  1439. #endif
  1440. const char *alpn_proto;
  1441. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1442. char txtbuf[4];
  1443. #endif
  1444. };
  1445. #if defined(GCC_DIAGNOSTIC)
  1446. /* Show no warning in case system functions are not used. */
  1447. #pragma GCC diagnostic push
  1448. #pragma GCC diagnostic ignored "-Wunused-function"
  1449. #endif /* defined(GCC_DIAGNOSTIC) */
  1450. #if defined(__clang__)
  1451. /* Show no warning in case system functions are not used. */
  1452. #pragma clang diagnostic push
  1453. #pragma clang diagnostic ignored "-Wunused-function"
  1454. #endif
  1455. /* Get a unique thread ID as unsigned long, independent from the data type
  1456. * of thread IDs defined by the operating system API.
  1457. * If two calls to mg_current_thread_id return the same value, they calls
  1458. * are done from the same thread. If they return different values, they are
  1459. * done from different threads. (Provided this function is used in the same
  1460. * process context and threads are not repeatedly created and deleted, but
  1461. * CivetWeb does not do that).
  1462. * This function must match the signature required for SSL id callbacks:
  1463. * CRYPTO_set_id_callback
  1464. */
  1465. FUNCTION_MAY_BE_UNUSED
  1466. static unsigned long
  1467. mg_current_thread_id(void)
  1468. {
  1469. #if defined(_WIN32)
  1470. return GetCurrentThreadId();
  1471. #else
  1472. #if defined(__clang__)
  1473. #pragma clang diagnostic push
  1474. #pragma clang diagnostic ignored "-Wunreachable-code"
  1475. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1476. * or not, so one of the two conditions will be unreachable by construction.
  1477. * Unfortunately the C standard does not define a way to check this at
  1478. * compile time, since the #if preprocessor conditions can not use the sizeof
  1479. * operator as an argument. */
  1480. #endif
  1481. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1482. /* This is the problematic case for CRYPTO_set_id_callback:
  1483. * The OS pthread_t can not be cast to unsigned long. */
  1484. struct mg_workerTLS *tls =
  1485. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1486. if (tls == NULL) {
  1487. /* SSL called from an unknown thread: Create some thread index.
  1488. */
  1489. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1490. tls->is_master = -2; /* -2 means "3rd party thread" */
  1491. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1492. pthread_setspecific(sTlsKey, tls);
  1493. }
  1494. return tls->thread_idx;
  1495. } else {
  1496. /* pthread_t may be any data type, so a simple cast to unsigned long
  1497. * can rise a warning/error, depending on the platform.
  1498. * Here memcpy is used as an anything-to-anything cast. */
  1499. unsigned long ret = 0;
  1500. pthread_t t = pthread_self();
  1501. memcpy(&ret, &t, sizeof(pthread_t));
  1502. return ret;
  1503. }
  1504. #if defined(__clang__)
  1505. #pragma clang diagnostic pop
  1506. #endif
  1507. #endif
  1508. }
  1509. FUNCTION_MAY_BE_UNUSED
  1510. static uint64_t
  1511. mg_get_current_time_ns(void)
  1512. {
  1513. struct timespec tsnow;
  1514. clock_gettime(CLOCK_REALTIME, &tsnow);
  1515. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1516. }
  1517. #if defined(GCC_DIAGNOSTIC)
  1518. /* Show no warning in case system functions are not used. */
  1519. #pragma GCC diagnostic pop
  1520. #endif /* defined(GCC_DIAGNOSTIC) */
  1521. #if defined(__clang__)
  1522. /* Show no warning in case system functions are not used. */
  1523. #pragma clang diagnostic pop
  1524. #endif
  1525. #if defined(NEED_DEBUG_TRACE_FUNC)
  1526. static void
  1527. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1528. {
  1529. va_list args;
  1530. struct timespec tsnow;
  1531. /* Get some operating system independent thread id */
  1532. unsigned long thread_id = mg_current_thread_id();
  1533. clock_gettime(CLOCK_REALTIME, &tsnow);
  1534. flockfile(DEBUG_TRACE_STREAM);
  1535. fprintf(DEBUG_TRACE_STREAM,
  1536. "*** %lu.%09lu %lu %s:%u: ",
  1537. (unsigned long)tsnow.tv_sec,
  1538. (unsigned long)tsnow.tv_nsec,
  1539. thread_id,
  1540. func,
  1541. line);
  1542. va_start(args, fmt);
  1543. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1544. va_end(args);
  1545. putc('\n', DEBUG_TRACE_STREAM);
  1546. fflush(DEBUG_TRACE_STREAM);
  1547. funlockfile(DEBUG_TRACE_STREAM);
  1548. }
  1549. #endif /* NEED_DEBUG_TRACE_FUNC */
  1550. #define MD5_STATIC static
  1551. #include "md5.inl"
  1552. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1553. #if defined(NO_SOCKLEN_T)
  1554. typedef int socklen_t;
  1555. #endif /* NO_SOCKLEN_T */
  1556. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1557. #if !defined(MSG_NOSIGNAL)
  1558. #define MSG_NOSIGNAL (0)
  1559. #endif
  1560. #if defined(NO_SSL)
  1561. #if !defined(USE_MBEDTLS)
  1562. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1563. typedef struct SSL_CTX SSL_CTX;
  1564. #endif
  1565. #else
  1566. #if defined(NO_SSL_DL)
  1567. #include <openssl/bn.h>
  1568. #include <openssl/conf.h>
  1569. #include <openssl/crypto.h>
  1570. #include <openssl/dh.h>
  1571. #include <openssl/engine.h>
  1572. #include <openssl/err.h>
  1573. #include <openssl/opensslv.h>
  1574. #include <openssl/pem.h>
  1575. #include <openssl/ssl.h>
  1576. #include <openssl/tls1.h>
  1577. #include <openssl/x509.h>
  1578. #if defined(WOLFSSL_VERSION)
  1579. /* Additional defines for WolfSSL, see
  1580. * https://github.com/civetweb/civetweb/issues/583 */
  1581. #include "wolfssl_extras.inl"
  1582. #endif
  1583. #if defined(OPENSSL_IS_BORINGSSL)
  1584. /* From boringssl/src/include/openssl/mem.h:
  1585. *
  1586. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1587. * However, that was written in a time before Valgrind and ASAN. Since we now
  1588. * have those tools, the OpenSSL allocation functions are simply macros around
  1589. * the standard memory functions.
  1590. *
  1591. * #define OPENSSL_free free */
  1592. #define free free
  1593. // disable for boringssl
  1594. #define CONF_modules_unload(a) ((void)0)
  1595. #define ENGINE_cleanup() ((void)0)
  1596. #endif
  1597. /* If OpenSSL headers are included, automatically select the API version */
  1598. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1599. #if !defined(OPENSSL_API_1_1)
  1600. #define OPENSSL_API_1_1
  1601. #endif
  1602. #define OPENSSL_REMOVE_THREAD_STATE()
  1603. #else
  1604. #if !defined(OPENSSL_API_1_0)
  1605. #define OPENSSL_API_1_0
  1606. #endif
  1607. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1608. #endif
  1609. #else
  1610. /* SSL loaded dynamically from DLL.
  1611. * I put the prototypes here to be independent from OpenSSL source
  1612. * installation. */
  1613. typedef struct ssl_st SSL;
  1614. typedef struct ssl_method_st SSL_METHOD;
  1615. typedef struct ssl_ctx_st SSL_CTX;
  1616. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1617. typedef struct x509_name X509_NAME;
  1618. typedef struct asn1_integer ASN1_INTEGER;
  1619. typedef struct bignum BIGNUM;
  1620. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1621. typedef struct evp_md EVP_MD;
  1622. typedef struct x509 X509;
  1623. #define SSL_CTRL_OPTIONS (32)
  1624. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1625. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1626. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1627. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1628. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1629. #define SSL_VERIFY_NONE (0)
  1630. #define SSL_VERIFY_PEER (1)
  1631. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1632. #define SSL_VERIFY_CLIENT_ONCE (4)
  1633. #define SSL_OP_ALL (0x80000BFFul)
  1634. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1635. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1636. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1637. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1638. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1639. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1640. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1641. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1642. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1643. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1644. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1645. #define SSL_CB_HANDSHAKE_START (0x10)
  1646. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1647. #define SSL_ERROR_NONE (0)
  1648. #define SSL_ERROR_SSL (1)
  1649. #define SSL_ERROR_WANT_READ (2)
  1650. #define SSL_ERROR_WANT_WRITE (3)
  1651. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1652. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1653. #define SSL_ERROR_ZERO_RETURN (6)
  1654. #define SSL_ERROR_WANT_CONNECT (7)
  1655. #define SSL_ERROR_WANT_ACCEPT (8)
  1656. #define TLSEXT_TYPE_server_name (0)
  1657. #define TLSEXT_NAMETYPE_host_name (0)
  1658. #define SSL_TLSEXT_ERR_OK (0)
  1659. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1660. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1661. #define SSL_TLSEXT_ERR_NOACK (3)
  1662. #define SSL_SESS_CACHE_BOTH (3)
  1663. enum ssl_func_category {
  1664. TLS_Mandatory, /* required for HTTPS */
  1665. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1666. TLS_END_OF_LIST
  1667. };
  1668. /* Check if all TLS functions/features are available */
  1669. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1670. struct ssl_func {
  1671. const char *name; /* SSL function name */
  1672. enum ssl_func_category required; /* Mandatory or optional */
  1673. void (*ptr)(void); /* Function pointer */
  1674. };
  1675. #if defined(OPENSSL_API_1_1)
  1676. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1677. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1678. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1679. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1680. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1681. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1682. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1683. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1684. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1685. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1686. #define OPENSSL_init_ssl \
  1687. (*(int (*)(uint64_t opts, \
  1688. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1689. .ptr)
  1690. #define SSL_CTX_use_PrivateKey_file \
  1691. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1692. #define SSL_CTX_use_certificate_file \
  1693. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1694. #define SSL_CTX_set_default_passwd_cb \
  1695. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1696. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1697. #define SSL_CTX_use_certificate_chain_file \
  1698. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1699. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1700. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1701. #define SSL_CTX_set_verify \
  1702. (*(void (*)(SSL_CTX *, \
  1703. int, \
  1704. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1705. .ptr)
  1706. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1707. #define SSL_CTX_load_verify_locations \
  1708. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1709. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1710. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1711. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1712. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1713. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1714. #define SSL_CIPHER_get_name \
  1715. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1716. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1717. #define SSL_CTX_set_session_id_context \
  1718. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1719. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1720. #define SSL_CTX_set_cipher_list \
  1721. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1722. #define SSL_CTX_set_options \
  1723. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1724. #define SSL_CTX_set_info_callback \
  1725. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1726. ssl_sw[32] \
  1727. .ptr)
  1728. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1729. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1730. #define SSL_CTX_callback_ctrl \
  1731. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1732. #define SSL_get_servername \
  1733. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1734. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1735. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1736. #define SSL_CTX_set_alpn_protos \
  1737. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1738. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1739. const unsigned char **out,
  1740. unsigned char *outlen,
  1741. const unsigned char *in,
  1742. unsigned int inlen,
  1743. void *arg);
  1744. #define SSL_CTX_set_alpn_select_cb \
  1745. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1746. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1747. const unsigned char **out,
  1748. unsigned int *outlen,
  1749. void *arg);
  1750. #define SSL_CTX_set_next_protos_advertised_cb \
  1751. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1752. .ptr)
  1753. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1754. #define SSL_CTX_clear_options(ctx, op) \
  1755. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1756. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1757. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1758. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1759. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1760. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1761. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1762. SSL_CTX_callback_ctrl(ctx, \
  1763. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1764. (void (*)(void))cb)
  1765. #define SSL_set_tlsext_host_name(ctx, arg) \
  1766. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1767. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1768. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1769. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1770. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1771. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1772. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1773. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1774. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1775. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1776. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1777. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1778. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1779. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1780. #define X509_NAME_oneline \
  1781. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1782. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1783. #define EVP_get_digestbyname \
  1784. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1785. #define EVP_Digest \
  1786. (*(int (*)( \
  1787. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1788. crypto_sw[9] \
  1789. .ptr)
  1790. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1791. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1792. #define ASN1_INTEGER_to_BN \
  1793. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1794. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1795. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1796. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1797. #define OPENSSL_free(a) CRYPTO_free(a)
  1798. #define OPENSSL_REMOVE_THREAD_STATE()
  1799. /* init_ssl_ctx() function updates this array.
  1800. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1801. * of respective functions. The macros above (like SSL_connect()) are really
  1802. * just calling these functions indirectly via the pointer. */
  1803. static struct ssl_func ssl_sw[] = {
  1804. {"SSL_free", TLS_Mandatory, NULL},
  1805. {"SSL_accept", TLS_Mandatory, NULL},
  1806. {"SSL_connect", TLS_Mandatory, NULL},
  1807. {"SSL_read", TLS_Mandatory, NULL},
  1808. {"SSL_write", TLS_Mandatory, NULL},
  1809. {"SSL_get_error", TLS_Mandatory, NULL},
  1810. {"SSL_set_fd", TLS_Mandatory, NULL},
  1811. {"SSL_new", TLS_Mandatory, NULL},
  1812. {"SSL_CTX_new", TLS_Mandatory, NULL},
  1813. {"TLS_server_method", TLS_Mandatory, NULL},
  1814. {"OPENSSL_init_ssl", TLS_Mandatory, NULL},
  1815. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  1816. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  1817. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  1818. {"SSL_CTX_free", TLS_Mandatory, NULL},
  1819. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  1820. {"TLS_client_method", TLS_Mandatory, NULL},
  1821. {"SSL_pending", TLS_Mandatory, NULL},
  1822. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  1823. {"SSL_shutdown", TLS_Mandatory, NULL},
  1824. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  1825. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  1826. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  1827. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  1828. {"SSL_get_version", TLS_Mandatory, NULL},
  1829. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  1830. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  1831. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  1832. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  1833. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  1834. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  1835. {"SSL_CTX_set_options", TLS_Mandatory, NULL},
  1836. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  1837. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  1838. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  1839. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  1840. {"SSL_get_servername", TLS_Mandatory, NULL},
  1841. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  1842. {"SSL_ctrl", TLS_Mandatory, NULL},
  1843. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  1844. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  1845. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  1846. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  1847. {NULL, TLS_END_OF_LIST, NULL}};
  1848. /* Similar array as ssl_sw. These functions could be located in different
  1849. * lib. */
  1850. static struct ssl_func crypto_sw[] = {
  1851. {"ERR_get_error", TLS_Mandatory, NULL},
  1852. {"ERR_error_string", TLS_Mandatory, NULL},
  1853. {"CONF_modules_unload", TLS_Mandatory, NULL},
  1854. {"X509_free", TLS_Mandatory, NULL},
  1855. {"X509_get_subject_name", TLS_Mandatory, NULL},
  1856. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  1857. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  1858. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  1859. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  1860. {"EVP_Digest", TLS_Mandatory, NULL},
  1861. {"i2d_X509", TLS_Mandatory, NULL},
  1862. {"BN_bn2hex", TLS_Mandatory, NULL},
  1863. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  1864. {"BN_free", TLS_Mandatory, NULL},
  1865. {"CRYPTO_free", TLS_Mandatory, NULL},
  1866. {"ERR_clear_error", TLS_Mandatory, NULL},
  1867. {NULL, TLS_END_OF_LIST, NULL}};
  1868. #else
  1869. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1870. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1871. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1872. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1873. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1874. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1875. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1876. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1877. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1878. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1879. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1880. #define SSL_CTX_use_PrivateKey_file \
  1881. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1882. #define SSL_CTX_use_certificate_file \
  1883. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1884. #define SSL_CTX_set_default_passwd_cb \
  1885. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1886. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1887. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1888. #define SSL_CTX_use_certificate_chain_file \
  1889. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1890. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1891. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1892. #define SSL_CTX_set_verify \
  1893. (*(void (*)(SSL_CTX *, \
  1894. int, \
  1895. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1896. .ptr)
  1897. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1898. #define SSL_CTX_load_verify_locations \
  1899. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1900. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1901. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1902. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1903. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1904. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1905. #define SSL_CIPHER_get_name \
  1906. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1907. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1908. #define SSL_CTX_set_session_id_context \
  1909. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1910. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1911. #define SSL_CTX_set_cipher_list \
  1912. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1913. #define SSL_CTX_set_info_callback \
  1914. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1915. .ptr)
  1916. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1917. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1918. #define SSL_CTX_callback_ctrl \
  1919. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1920. #define SSL_get_servername \
  1921. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1922. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1923. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1924. #define SSL_CTX_set_alpn_protos \
  1925. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1926. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1927. const unsigned char **out,
  1928. unsigned char *outlen,
  1929. const unsigned char *in,
  1930. unsigned int inlen,
  1931. void *arg);
  1932. #define SSL_CTX_set_alpn_select_cb \
  1933. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1934. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1935. const unsigned char **out,
  1936. unsigned int *outlen,
  1937. void *arg);
  1938. #define SSL_CTX_set_next_protos_advertised_cb \
  1939. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1940. .ptr)
  1941. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1942. #define SSL_CTX_set_options(ctx, op) \
  1943. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1944. #define SSL_CTX_clear_options(ctx, op) \
  1945. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1946. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1947. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1948. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1949. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1950. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1951. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1952. SSL_CTX_callback_ctrl(ctx, \
  1953. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1954. (void (*)(void))cb)
  1955. #define SSL_set_tlsext_host_name(ctx, arg) \
  1956. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1957. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1958. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1959. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1960. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1961. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1962. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1963. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1964. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1965. #define CRYPTO_set_locking_callback \
  1966. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1967. #define CRYPTO_set_id_callback \
  1968. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1969. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1970. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1971. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1972. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1973. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1974. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1975. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1976. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1977. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1978. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1979. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1980. #define X509_NAME_oneline \
  1981. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1982. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1983. #define i2c_ASN1_INTEGER \
  1984. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1985. #define EVP_get_digestbyname \
  1986. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1987. #define EVP_Digest \
  1988. (*(int (*)( \
  1989. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1990. crypto_sw[18] \
  1991. .ptr)
  1992. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1993. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1994. #define ASN1_INTEGER_to_BN \
  1995. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1996. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1997. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1998. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1999. #define OPENSSL_free(a) CRYPTO_free(a)
  2000. /* use here ERR_remove_state,
  2001. * while on some platforms function is not included into library due to
  2002. * deprication */
  2003. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  2004. /* init_ssl_ctx() function updates this array.
  2005. * It loads SSL library dynamically and changes NULLs to the actual addresses
  2006. * of respective functions. The macros above (like SSL_connect()) are really
  2007. * just calling these functions indirectly via the pointer. */
  2008. static struct ssl_func ssl_sw[] = {
  2009. {"SSL_free", TLS_Mandatory, NULL},
  2010. {"SSL_accept", TLS_Mandatory, NULL},
  2011. {"SSL_connect", TLS_Mandatory, NULL},
  2012. {"SSL_read", TLS_Mandatory, NULL},
  2013. {"SSL_write", TLS_Mandatory, NULL},
  2014. {"SSL_get_error", TLS_Mandatory, NULL},
  2015. {"SSL_set_fd", TLS_Mandatory, NULL},
  2016. {"SSL_new", TLS_Mandatory, NULL},
  2017. {"SSL_CTX_new", TLS_Mandatory, NULL},
  2018. {"SSLv23_server_method", TLS_Mandatory, NULL},
  2019. {"SSL_library_init", TLS_Mandatory, NULL},
  2020. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  2021. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  2022. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  2023. {"SSL_CTX_free", TLS_Mandatory, NULL},
  2024. {"SSL_load_error_strings", TLS_Mandatory, NULL},
  2025. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  2026. {"SSLv23_client_method", TLS_Mandatory, NULL},
  2027. {"SSL_pending", TLS_Mandatory, NULL},
  2028. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  2029. {"SSL_shutdown", TLS_Mandatory, NULL},
  2030. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  2031. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  2032. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  2033. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  2034. {"SSL_get_version", TLS_Mandatory, NULL},
  2035. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  2036. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  2037. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  2038. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  2039. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  2040. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  2041. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  2042. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  2043. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  2044. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  2045. {"SSL_get_servername", TLS_Mandatory, NULL},
  2046. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  2047. {"SSL_ctrl", TLS_Mandatory, NULL},
  2048. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  2049. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  2050. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  2051. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  2052. {NULL, TLS_END_OF_LIST, NULL}};
  2053. /* Similar array as ssl_sw. These functions could be located in different
  2054. * lib. */
  2055. static struct ssl_func crypto_sw[] = {
  2056. {"CRYPTO_num_locks", TLS_Mandatory, NULL},
  2057. {"CRYPTO_set_locking_callback", TLS_Mandatory, NULL},
  2058. {"CRYPTO_set_id_callback", TLS_Mandatory, NULL},
  2059. {"ERR_get_error", TLS_Mandatory, NULL},
  2060. {"ERR_error_string", TLS_Mandatory, NULL},
  2061. {"ERR_remove_state", TLS_Mandatory, NULL},
  2062. {"ERR_free_strings", TLS_Mandatory, NULL},
  2063. {"ENGINE_cleanup", TLS_Mandatory, NULL},
  2064. {"CONF_modules_unload", TLS_Mandatory, NULL},
  2065. {"CRYPTO_cleanup_all_ex_data", TLS_Mandatory, NULL},
  2066. {"EVP_cleanup", TLS_Mandatory, NULL},
  2067. {"X509_free", TLS_Mandatory, NULL},
  2068. {"X509_get_subject_name", TLS_Mandatory, NULL},
  2069. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  2070. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  2071. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  2072. {"i2c_ASN1_INTEGER", TLS_Mandatory, NULL},
  2073. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  2074. {"EVP_Digest", TLS_Mandatory, NULL},
  2075. {"i2d_X509", TLS_Mandatory, NULL},
  2076. {"BN_bn2hex", TLS_Mandatory, NULL},
  2077. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  2078. {"BN_free", TLS_Mandatory, NULL},
  2079. {"CRYPTO_free", TLS_Mandatory, NULL},
  2080. {"ERR_clear_error", TLS_Mandatory, NULL},
  2081. {NULL, TLS_END_OF_LIST, NULL}};
  2082. #endif /* OPENSSL_API_1_1 */
  2083. #endif /* NO_SSL_DL */
  2084. #endif /* NO_SSL */
  2085. #if !defined(NO_CACHING)
  2086. static const char month_names[][4] = {"Jan",
  2087. "Feb",
  2088. "Mar",
  2089. "Apr",
  2090. "May",
  2091. "Jun",
  2092. "Jul",
  2093. "Aug",
  2094. "Sep",
  2095. "Oct",
  2096. "Nov",
  2097. "Dec"};
  2098. #endif /* !NO_CACHING */
  2099. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2100. * the union u. */
  2101. union usa {
  2102. struct sockaddr sa;
  2103. struct sockaddr_in sin;
  2104. #if defined(USE_IPV6)
  2105. struct sockaddr_in6 sin6;
  2106. #endif
  2107. };
  2108. #if defined(USE_IPV6)
  2109. #define USA_IN_PORT_UNSAFE(s) \
  2110. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  2111. #else
  2112. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  2113. #endif
  2114. /* Describes a string (chunk of memory). */
  2115. struct vec {
  2116. const char *ptr;
  2117. size_t len;
  2118. };
  2119. struct mg_file_stat {
  2120. /* File properties filled by mg_stat: */
  2121. uint64_t size;
  2122. time_t last_modified;
  2123. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2124. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2125. * case we need a "Content-Eencoding: gzip" header */
  2126. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2127. };
  2128. struct mg_file_access {
  2129. /* File properties filled by mg_fopen: */
  2130. FILE *fp;
  2131. };
  2132. struct mg_file {
  2133. struct mg_file_stat stat;
  2134. struct mg_file_access access;
  2135. };
  2136. #define STRUCT_FILE_INITIALIZER \
  2137. { \
  2138. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2139. { \
  2140. (FILE *)NULL \
  2141. } \
  2142. }
  2143. /* Describes listening socket, or socket which was accept()-ed by the master
  2144. * thread and queued for future handling by the worker thread. */
  2145. struct socket {
  2146. SOCKET sock; /* Listening socket */
  2147. union usa lsa; /* Local socket address */
  2148. union usa rsa; /* Remote socket address */
  2149. unsigned char is_ssl; /* Is port SSL-ed */
  2150. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2151. * port */
  2152. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2153. };
  2154. /* Enum const for all options must be in sync with
  2155. * static struct mg_option config_options[]
  2156. * This is tested in the unit test (test/private.c)
  2157. * "Private Config Options"
  2158. */
  2159. enum {
  2160. /* Once for each server */
  2161. LISTENING_PORTS,
  2162. NUM_THREADS,
  2163. RUN_AS_USER,
  2164. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2165. * socket option typedef TCP_NODELAY. */
  2166. MAX_REQUEST_SIZE,
  2167. LINGER_TIMEOUT,
  2168. CONNECTION_QUEUE_SIZE,
  2169. LISTEN_BACKLOG_SIZE,
  2170. #if defined(__linux__)
  2171. ALLOW_SENDFILE_CALL,
  2172. #endif
  2173. #if defined(_WIN32)
  2174. CASE_SENSITIVE_FILES,
  2175. #endif
  2176. THROTTLE,
  2177. ACCESS_LOG_FILE,
  2178. ERROR_LOG_FILE,
  2179. ENABLE_KEEP_ALIVE,
  2180. REQUEST_TIMEOUT,
  2181. KEEP_ALIVE_TIMEOUT,
  2182. #if defined(USE_WEBSOCKET)
  2183. WEBSOCKET_TIMEOUT,
  2184. ENABLE_WEBSOCKET_PING_PONG,
  2185. #endif
  2186. DECODE_URL,
  2187. #if defined(USE_LUA)
  2188. LUA_BACKGROUND_SCRIPT,
  2189. LUA_BACKGROUND_SCRIPT_PARAMS,
  2190. #endif
  2191. #if defined(USE_HTTP2)
  2192. ENABLE_HTTP2,
  2193. #endif
  2194. /* Once for each domain */
  2195. DOCUMENT_ROOT,
  2196. CGI_EXTENSIONS,
  2197. CGI2_EXTENSIONS,
  2198. CGI_ENVIRONMENT,
  2199. CGI2_ENVIRONMENT,
  2200. CGI_INTERPRETER,
  2201. CGI2_INTERPRETER,
  2202. CGI_INTERPRETER_ARGS,
  2203. CGI2_INTERPRETER_ARGS,
  2204. #if defined(USE_TIMERS)
  2205. CGI_TIMEOUT,
  2206. CGI2_TIMEOUT,
  2207. #endif
  2208. PUT_DELETE_PASSWORDS_FILE,
  2209. PROTECT_URI,
  2210. AUTHENTICATION_DOMAIN,
  2211. ENABLE_AUTH_DOMAIN_CHECK,
  2212. SSI_EXTENSIONS,
  2213. ENABLE_DIRECTORY_LISTING,
  2214. GLOBAL_PASSWORDS_FILE,
  2215. INDEX_FILES,
  2216. ACCESS_CONTROL_LIST,
  2217. EXTRA_MIME_TYPES,
  2218. SSL_CERTIFICATE,
  2219. SSL_CERTIFICATE_CHAIN,
  2220. URL_REWRITE_PATTERN,
  2221. HIDE_FILES,
  2222. SSL_DO_VERIFY_PEER,
  2223. SSL_CACHE_TIMEOUT,
  2224. SSL_CA_PATH,
  2225. SSL_CA_FILE,
  2226. SSL_VERIFY_DEPTH,
  2227. SSL_DEFAULT_VERIFY_PATHS,
  2228. SSL_CIPHER_LIST,
  2229. SSL_PROTOCOL_VERSION,
  2230. SSL_SHORT_TRUST,
  2231. #if defined(USE_LUA)
  2232. LUA_PRELOAD_FILE,
  2233. LUA_SCRIPT_EXTENSIONS,
  2234. LUA_SERVER_PAGE_EXTENSIONS,
  2235. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2236. LUA_DEBUG_PARAMS,
  2237. #endif
  2238. #endif
  2239. #if defined(USE_DUKTAPE)
  2240. DUKTAPE_SCRIPT_EXTENSIONS,
  2241. #endif
  2242. #if defined(USE_WEBSOCKET)
  2243. WEBSOCKET_ROOT,
  2244. #endif
  2245. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2246. LUA_WEBSOCKET_EXTENSIONS,
  2247. #endif
  2248. ACCESS_CONTROL_ALLOW_ORIGIN,
  2249. ACCESS_CONTROL_ALLOW_METHODS,
  2250. ACCESS_CONTROL_ALLOW_HEADERS,
  2251. ERROR_PAGES,
  2252. #if !defined(NO_CACHING)
  2253. STATIC_FILE_MAX_AGE,
  2254. STATIC_FILE_CACHE_CONTROL,
  2255. #endif
  2256. #if !defined(NO_SSL)
  2257. STRICT_HTTPS_MAX_AGE,
  2258. #endif
  2259. ADDITIONAL_HEADER,
  2260. ALLOW_INDEX_SCRIPT_SUB_RES,
  2261. #if defined(DAEMONIZE)
  2262. ENABLE_DAEMONIZE,
  2263. #endif
  2264. NUM_OPTIONS
  2265. };
  2266. /* Config option name, config types, default value.
  2267. * Must be in the same order as the enum const above.
  2268. */
  2269. static const struct mg_option config_options[] = {
  2270. /* Once for each server */
  2271. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2272. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2273. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2274. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2275. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2276. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2277. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2278. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2279. #if defined(__linux__)
  2280. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2281. #endif
  2282. #if defined(_WIN32)
  2283. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2284. #endif
  2285. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2286. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2287. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2288. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2289. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2290. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2291. #if defined(USE_WEBSOCKET)
  2292. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2293. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2294. #endif
  2295. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2296. #if defined(USE_LUA)
  2297. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2298. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2299. #endif
  2300. #if defined(USE_HTTP2)
  2301. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2302. #endif
  2303. /* Once for each domain */
  2304. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2305. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2306. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2307. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2308. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2309. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2310. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2311. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2312. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2313. #if defined(USE_TIMERS)
  2314. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2315. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2316. #endif
  2317. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2318. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2319. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2320. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2321. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2322. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2323. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2324. {"index_files",
  2325. MG_CONFIG_TYPE_STRING_LIST,
  2326. #if defined(USE_LUA)
  2327. "index.xhtml,index.html,index.htm,"
  2328. "index.lp,index.lsp,index.lua,index.cgi,"
  2329. "index.shtml,index.php"},
  2330. #else
  2331. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2332. #endif
  2333. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2334. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2335. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2336. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2337. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2338. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2339. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2340. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  2341. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2342. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2343. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2344. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2345. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2346. #if defined(USE_HTTP2)
  2347. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  2348. * as a minimum in 2020 */
  2349. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  2350. #else
  2351. /* Keep the default (compatibility) */
  2352. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2353. #endif /* defined(USE_HTTP2) */
  2354. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2355. #if defined(USE_LUA)
  2356. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2357. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2358. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2359. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2360. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2361. #endif
  2362. #endif
  2363. #if defined(USE_DUKTAPE)
  2364. /* The support for duktape is still in alpha version state.
  2365. * The name of this config option might change. */
  2366. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2367. #endif
  2368. #if defined(USE_WEBSOCKET)
  2369. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2370. #endif
  2371. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2372. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2373. #endif
  2374. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2375. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2376. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2377. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2378. #if !defined(NO_CACHING)
  2379. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2380. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2381. #endif
  2382. #if !defined(NO_SSL)
  2383. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2384. #endif
  2385. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2386. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2387. #if defined(DAEMONIZE)
  2388. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2389. #endif
  2390. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2391. /* Check if the config_options and the corresponding enum have compatible
  2392. * sizes. */
  2393. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2394. == (NUM_OPTIONS + 1),
  2395. "config_options and enum not sync");
  2396. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2397. struct mg_handler_info {
  2398. /* Name/Pattern of the URI. */
  2399. char *uri;
  2400. size_t uri_len;
  2401. /* handler type */
  2402. int handler_type;
  2403. /* Handler for http/https or authorization requests. */
  2404. mg_request_handler handler;
  2405. unsigned int refcount;
  2406. int removing;
  2407. /* Handler for ws/wss (websocket) requests. */
  2408. mg_websocket_connect_handler connect_handler;
  2409. mg_websocket_ready_handler ready_handler;
  2410. mg_websocket_data_handler data_handler;
  2411. mg_websocket_close_handler close_handler;
  2412. /* accepted subprotocols for ws/wss requests. */
  2413. struct mg_websocket_subprotocols *subprotocols;
  2414. /* Handler for authorization requests */
  2415. mg_authorization_handler auth_handler;
  2416. /* User supplied argument for the handler function. */
  2417. void *cbdata;
  2418. /* next handler in a linked list */
  2419. struct mg_handler_info *next;
  2420. };
  2421. enum {
  2422. CONTEXT_INVALID,
  2423. CONTEXT_SERVER,
  2424. CONTEXT_HTTP_CLIENT,
  2425. CONTEXT_WS_CLIENT
  2426. };
  2427. struct mg_domain_context {
  2428. SSL_CTX *ssl_ctx; /* SSL context */
  2429. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2430. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2431. int64_t ssl_cert_last_mtime;
  2432. /* Server nonce */
  2433. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2434. unsigned long nonce_count; /* Used nonces, used for authentication */
  2435. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2436. /* linked list of shared lua websockets */
  2437. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2438. #endif
  2439. /* Linked list of domains */
  2440. struct mg_domain_context *next;
  2441. };
  2442. /* Stop flag can be "volatile" or require a lock.
  2443. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  2444. * states a read operation for int is always atomic. */
  2445. #if defined(STOP_FLAG_NEEDS_LOCK)
  2446. typedef ptrdiff_t volatile stop_flag_t;
  2447. static int
  2448. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2449. {
  2450. stop_flag_t sf = mg_atomic_add(f, 0);
  2451. return (sf == 0);
  2452. }
  2453. static int
  2454. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2455. {
  2456. stop_flag_t sf = mg_atomic_add(f, 0);
  2457. return (sf == 2);
  2458. }
  2459. static void
  2460. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2461. {
  2462. stop_flag_t sf;
  2463. do {
  2464. sf = mg_atomic_compare_and_swap(f, *f, v);
  2465. } while (sf != v);
  2466. }
  2467. #else /* STOP_FLAG_NEEDS_LOCK */
  2468. typedef int volatile stop_flag_t;
  2469. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2470. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2471. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2472. #endif /* STOP_FLAG_NEEDS_LOCK */
  2473. struct mg_context {
  2474. /* Part 1 - Physical context:
  2475. * This holds threads, ports, timeouts, ...
  2476. * set for the entire server, independent from the
  2477. * addressed hostname.
  2478. */
  2479. /* Connection related */
  2480. int context_type; /* See CONTEXT_* above */
  2481. struct socket *listening_sockets;
  2482. struct mg_pollfd *listening_socket_fds;
  2483. unsigned int num_listening_sockets;
  2484. struct mg_connection *worker_connections; /* The connection struct, pre-
  2485. * allocated for each worker */
  2486. #if defined(USE_SERVER_STATS)
  2487. volatile ptrdiff_t active_connections;
  2488. volatile ptrdiff_t max_active_connections;
  2489. volatile ptrdiff_t total_connections;
  2490. volatile ptrdiff_t total_requests;
  2491. volatile int64_t total_data_read;
  2492. volatile int64_t total_data_written;
  2493. #endif
  2494. /* Thread related */
  2495. stop_flag_t stop_flag; /* Should we stop event loop */
  2496. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2497. pthread_t masterthreadid; /* The master thread ID */
  2498. unsigned int
  2499. cfg_worker_threads; /* The number of configured worker threads. */
  2500. pthread_t *worker_threadids; /* The worker thread IDs */
  2501. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2502. /* Connection to thread dispatching */
  2503. #if defined(ALTERNATIVE_QUEUE)
  2504. struct socket *client_socks;
  2505. void **client_wait_events;
  2506. #else
  2507. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2508. worker thread */
  2509. volatile int sq_head; /* Head of the socket queue */
  2510. volatile int sq_tail; /* Tail of the socket queue */
  2511. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2512. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2513. volatile int sq_blocked; /* Status information: sq is full */
  2514. int sq_size; /* No of elements in socket queue */
  2515. #if defined(USE_SERVER_STATS)
  2516. int sq_max_fill;
  2517. #endif /* USE_SERVER_STATS */
  2518. #endif /* ALTERNATIVE_QUEUE */
  2519. /* Memory related */
  2520. unsigned int max_request_size; /* The max request size */
  2521. #if defined(USE_SERVER_STATS)
  2522. struct mg_memory_stat ctx_memory;
  2523. #endif
  2524. /* Operating system related */
  2525. char *systemName; /* What operating system is running */
  2526. time_t start_time; /* Server start time, used for authentication
  2527. * and for diagnstics. */
  2528. #if defined(USE_TIMERS)
  2529. struct ttimers *timers;
  2530. #endif
  2531. /* Lua specific: Background operations and shared websockets */
  2532. #if defined(USE_LUA)
  2533. void *lua_background_state;
  2534. #endif
  2535. /* Server nonce */
  2536. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2537. * ssl_cert_last_mtime, nonce_count, and
  2538. * next (linked list) */
  2539. /* Server callbacks */
  2540. struct mg_callbacks callbacks; /* User-defined callback function */
  2541. void *user_data; /* User-defined data */
  2542. /* Part 2 - Logical domain:
  2543. * This holds hostname, TLS certificate, document root, ...
  2544. * set for a domain hosted at the server.
  2545. * There may be multiple domains hosted at one physical server.
  2546. * The default domain "dd" is the first element of a list of
  2547. * domains.
  2548. */
  2549. struct mg_domain_context dd; /* default domain */
  2550. };
  2551. #if defined(USE_SERVER_STATS)
  2552. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2553. static struct mg_memory_stat *
  2554. get_memory_stat(struct mg_context *ctx)
  2555. {
  2556. if (ctx) {
  2557. return &(ctx->ctx_memory);
  2558. }
  2559. return &mg_common_memory;
  2560. }
  2561. #endif
  2562. enum {
  2563. CONNECTION_TYPE_INVALID = 0,
  2564. CONNECTION_TYPE_REQUEST = 1,
  2565. CONNECTION_TYPE_RESPONSE = 2
  2566. };
  2567. enum {
  2568. PROTOCOL_TYPE_HTTP1 = 0,
  2569. PROTOCOL_TYPE_WEBSOCKET = 1,
  2570. PROTOCOL_TYPE_HTTP2 = 2
  2571. };
  2572. #if defined(USE_HTTP2)
  2573. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2574. #define HTTP2_DYN_TABLE_SIZE (256)
  2575. #endif
  2576. struct mg_http2_connection {
  2577. uint32_t stream_id;
  2578. uint32_t dyn_table_size;
  2579. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2580. };
  2581. #endif
  2582. struct mg_connection {
  2583. int connection_type; /* see CONNECTION_TYPE_* above */
  2584. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2585. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2586. fully sent */
  2587. #if defined(USE_HTTP2)
  2588. struct mg_http2_connection http2;
  2589. #endif
  2590. struct mg_request_info request_info;
  2591. struct mg_response_info response_info;
  2592. struct mg_context *phys_ctx;
  2593. struct mg_domain_context *dom_ctx;
  2594. #if defined(USE_SERVER_STATS)
  2595. int conn_state; /* 0 = undef, numerical value may change in different
  2596. * versions. For the current definition, see
  2597. * mg_get_connection_info_impl */
  2598. #endif
  2599. SSL *ssl; /* SSL descriptor */
  2600. struct socket client; /* Connected client */
  2601. time_t conn_birth_time; /* Time (wall clock) when connection was
  2602. * established */
  2603. #if defined(USE_SERVER_STATS)
  2604. time_t conn_close_time; /* Time (wall clock) when connection was
  2605. * closed (or 0 if still open) */
  2606. #endif
  2607. struct timespec req_time; /* Time (since system start) when the request
  2608. * was received */
  2609. int64_t num_bytes_sent; /* Total bytes sent to client */
  2610. int64_t content_len; /* How many bytes of content can be read
  2611. * !is_chunked: Content-Length header value
  2612. * or -1 (until connection closed,
  2613. * not allowed for a request)
  2614. * is_chunked: >= 0, appended gradually
  2615. */
  2616. int64_t consumed_content; /* How many bytes of content have been read */
  2617. int is_chunked; /* Transfer-Encoding is chunked:
  2618. * 0 = not chunked,
  2619. * 1 = chunked, not yet, or some data read,
  2620. * 2 = chunked, has error,
  2621. * 3 = chunked, all data read except trailer,
  2622. * 4 = chunked, all data read
  2623. */
  2624. char *buf; /* Buffer for received data */
  2625. char *path_info; /* PATH_INFO part of the URL */
  2626. int must_close; /* 1 if connection must be closed */
  2627. int accept_gzip; /* 1 if gzip encoding is accepted */
  2628. int in_error_handler; /* 1 if in handler for user defined error
  2629. * pages */
  2630. #if defined(USE_WEBSOCKET)
  2631. int in_websocket_handling; /* 1 if in read_websocket */
  2632. #endif
  2633. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2634. && defined(MG_EXPERIMENTAL_INTERFACES)
  2635. /* Parameters for websocket data compression according to rfc7692 */
  2636. int websocket_deflate_server_max_windows_bits;
  2637. int websocket_deflate_client_max_windows_bits;
  2638. int websocket_deflate_server_no_context_takeover;
  2639. int websocket_deflate_client_no_context_takeover;
  2640. int websocket_deflate_initialized;
  2641. int websocket_deflate_flush;
  2642. z_stream websocket_deflate_state;
  2643. z_stream websocket_inflate_state;
  2644. #endif
  2645. int handled_requests; /* Number of requests handled by this connection
  2646. */
  2647. int buf_size; /* Buffer size */
  2648. int request_len; /* Size of the request + headers in a buffer */
  2649. int data_len; /* Total size of data in a buffer */
  2650. int status_code; /* HTTP reply status code, e.g. 200 */
  2651. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2652. * throttle */
  2653. time_t last_throttle_time; /* Last time throttled data was sent */
  2654. int last_throttle_bytes; /* Bytes sent this second */
  2655. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2656. * atomic transmissions for websockets */
  2657. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2658. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2659. #endif
  2660. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2661. * for quick access */
  2662. };
  2663. /* Directory entry */
  2664. struct de {
  2665. struct mg_connection *conn;
  2666. char *file_name;
  2667. struct mg_file_stat file;
  2668. };
  2669. #define mg_cry_internal(conn, fmt, ...) \
  2670. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2671. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2672. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2673. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2674. struct mg_context *ctx,
  2675. const char *func,
  2676. unsigned line,
  2677. const char *fmt,
  2678. ...) PRINTF_ARGS(5, 6);
  2679. #if !defined(NO_THREAD_NAME)
  2680. #if defined(_WIN32) && defined(_MSC_VER)
  2681. /* Set the thread name for debugging purposes in Visual Studio
  2682. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2683. */
  2684. #pragma pack(push, 8)
  2685. typedef struct tagTHREADNAME_INFO {
  2686. DWORD dwType; /* Must be 0x1000. */
  2687. LPCSTR szName; /* Pointer to name (in user addr space). */
  2688. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2689. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2690. } THREADNAME_INFO;
  2691. #pragma pack(pop)
  2692. #elif defined(__linux__)
  2693. #include <sys/prctl.h>
  2694. #include <sys/sendfile.h>
  2695. #if defined(ALTERNATIVE_QUEUE)
  2696. #include <sys/eventfd.h>
  2697. #endif /* ALTERNATIVE_QUEUE */
  2698. #if defined(ALTERNATIVE_QUEUE)
  2699. static void *
  2700. event_create(void)
  2701. {
  2702. int evhdl = eventfd(0, EFD_CLOEXEC);
  2703. int *ret;
  2704. if (evhdl == -1) {
  2705. /* Linux uses -1 on error, Windows NULL. */
  2706. /* However, Linux does not return 0 on success either. */
  2707. return 0;
  2708. }
  2709. ret = (int *)mg_malloc(sizeof(int));
  2710. if (ret) {
  2711. *ret = evhdl;
  2712. } else {
  2713. (void)close(evhdl);
  2714. }
  2715. return (void *)ret;
  2716. }
  2717. static int
  2718. event_wait(void *eventhdl)
  2719. {
  2720. uint64_t u;
  2721. int evhdl, s;
  2722. if (!eventhdl) {
  2723. /* error */
  2724. return 0;
  2725. }
  2726. evhdl = *(int *)eventhdl;
  2727. s = (int)read(evhdl, &u, sizeof(u));
  2728. if (s != sizeof(u)) {
  2729. /* error */
  2730. return 0;
  2731. }
  2732. (void)u; /* the value is not required */
  2733. return 1;
  2734. }
  2735. static int
  2736. event_signal(void *eventhdl)
  2737. {
  2738. uint64_t u = 1;
  2739. int evhdl, s;
  2740. if (!eventhdl) {
  2741. /* error */
  2742. return 0;
  2743. }
  2744. evhdl = *(int *)eventhdl;
  2745. s = (int)write(evhdl, &u, sizeof(u));
  2746. if (s != sizeof(u)) {
  2747. /* error */
  2748. return 0;
  2749. }
  2750. return 1;
  2751. }
  2752. static void
  2753. event_destroy(void *eventhdl)
  2754. {
  2755. int evhdl;
  2756. if (!eventhdl) {
  2757. /* error */
  2758. return;
  2759. }
  2760. evhdl = *(int *)eventhdl;
  2761. close(evhdl);
  2762. mg_free(eventhdl);
  2763. }
  2764. #endif
  2765. #endif
  2766. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2767. struct posix_event {
  2768. pthread_mutex_t mutex;
  2769. pthread_cond_t cond;
  2770. int signaled;
  2771. };
  2772. static void *
  2773. event_create(void)
  2774. {
  2775. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2776. if (ret == 0) {
  2777. /* out of memory */
  2778. return 0;
  2779. }
  2780. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2781. /* pthread mutex not available */
  2782. mg_free(ret);
  2783. return 0;
  2784. }
  2785. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2786. /* pthread cond not available */
  2787. pthread_mutex_destroy(&(ret->mutex));
  2788. mg_free(ret);
  2789. return 0;
  2790. }
  2791. ret->signaled = 0;
  2792. return (void *)ret;
  2793. }
  2794. static int
  2795. event_wait(void *eventhdl)
  2796. {
  2797. struct posix_event *ev = (struct posix_event *)eventhdl;
  2798. pthread_mutex_lock(&(ev->mutex));
  2799. while (!ev->signaled) {
  2800. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2801. }
  2802. ev->signaled = 0;
  2803. pthread_mutex_unlock(&(ev->mutex));
  2804. return 1;
  2805. }
  2806. static int
  2807. event_signal(void *eventhdl)
  2808. {
  2809. struct posix_event *ev = (struct posix_event *)eventhdl;
  2810. pthread_mutex_lock(&(ev->mutex));
  2811. pthread_cond_signal(&(ev->cond));
  2812. ev->signaled = 1;
  2813. pthread_mutex_unlock(&(ev->mutex));
  2814. return 1;
  2815. }
  2816. static void
  2817. event_destroy(void *eventhdl)
  2818. {
  2819. struct posix_event *ev = (struct posix_event *)eventhdl;
  2820. pthread_cond_destroy(&(ev->cond));
  2821. pthread_mutex_destroy(&(ev->mutex));
  2822. mg_free(ev);
  2823. }
  2824. #endif
  2825. static void
  2826. mg_set_thread_name(const char *name)
  2827. {
  2828. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2829. mg_snprintf(
  2830. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2831. #if defined(_WIN32)
  2832. #if defined(_MSC_VER)
  2833. /* Windows and Visual Studio Compiler */
  2834. __try {
  2835. THREADNAME_INFO info;
  2836. info.dwType = 0x1000;
  2837. info.szName = threadName;
  2838. info.dwThreadID = ~0U;
  2839. info.dwFlags = 0;
  2840. RaiseException(0x406D1388,
  2841. 0,
  2842. sizeof(info) / sizeof(ULONG_PTR),
  2843. (ULONG_PTR *)&info);
  2844. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2845. }
  2846. #elif defined(__MINGW32__)
  2847. /* No option known to set thread name for MinGW known */
  2848. #endif
  2849. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2850. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2851. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2852. #if defined(__MACH__)
  2853. /* OS X only current thread name can be changed */
  2854. (void)pthread_setname_np(threadName);
  2855. #else
  2856. (void)pthread_setname_np(pthread_self(), threadName);
  2857. #endif
  2858. #elif defined(__linux__)
  2859. /* On Linux we can use the prctl function.
  2860. * When building for Linux Standard Base (LSB) use
  2861. * NO_THREAD_NAME. However, thread names are a big
  2862. * help for debugging, so the stadard is to set them.
  2863. */
  2864. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2865. #endif
  2866. }
  2867. #else /* !defined(NO_THREAD_NAME) */
  2868. void
  2869. mg_set_thread_name(const char *threadName)
  2870. {
  2871. }
  2872. #endif
  2873. const struct mg_option *
  2874. mg_get_valid_options(void)
  2875. {
  2876. return config_options;
  2877. }
  2878. /* Do not open file (unused) */
  2879. #define MG_FOPEN_MODE_NONE (0)
  2880. /* Open file for read only access */
  2881. #define MG_FOPEN_MODE_READ (1)
  2882. /* Open file for writing, create and overwrite */
  2883. #define MG_FOPEN_MODE_WRITE (2)
  2884. /* Open file for writing, create and append */
  2885. #define MG_FOPEN_MODE_APPEND (4)
  2886. static int
  2887. is_file_opened(const struct mg_file_access *fileacc)
  2888. {
  2889. if (!fileacc) {
  2890. return 0;
  2891. }
  2892. return (fileacc->fp != NULL);
  2893. }
  2894. #if !defined(NO_FILESYSTEMS)
  2895. static int mg_stat(const struct mg_connection *conn,
  2896. const char *path,
  2897. struct mg_file_stat *filep);
  2898. /* Reject files with special characters */
  2899. static int
  2900. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2901. {
  2902. const uint8_t *c = (const uint8_t *)path;
  2903. (void)conn; /* not used */
  2904. if ((c == NULL) || (c[0] == 0)) {
  2905. /* Null pointer or empty path --> suspicious */
  2906. return 1;
  2907. }
  2908. while (*c) {
  2909. if (*c <= 32) {
  2910. /* Control character or space */
  2911. return 0;
  2912. }
  2913. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2914. /* stdin/stdout redirection character */
  2915. return 0;
  2916. }
  2917. #if defined(_WIN32)
  2918. if (*c == '\\') {
  2919. /* Windows backslash */
  2920. return 0;
  2921. }
  2922. #else
  2923. if (*c == '&') {
  2924. /* Linux ampersand */
  2925. return 0;
  2926. }
  2927. #endif
  2928. c++;
  2929. }
  2930. /* Nothing suspicious found */
  2931. return 0;
  2932. }
  2933. /* mg_fopen will open a file either in memory or on the disk.
  2934. * The input parameter path is a string in UTF-8 encoding.
  2935. * The input parameter mode is MG_FOPEN_MODE_*
  2936. * On success, fp will be set in the output struct mg_file.
  2937. * All status members will also be set.
  2938. * The function returns 1 on success, 0 on error. */
  2939. static int
  2940. mg_fopen(const struct mg_connection *conn,
  2941. const char *path,
  2942. int mode,
  2943. struct mg_file *filep)
  2944. {
  2945. int found;
  2946. if (!filep) {
  2947. return 0;
  2948. }
  2949. filep->access.fp = NULL;
  2950. if (mg_path_suspicious(conn, path)) {
  2951. return 0;
  2952. }
  2953. /* filep is initialized in mg_stat: all fields with memset to,
  2954. * some fields like size and modification date with values */
  2955. found = mg_stat(conn, path, &(filep->stat));
  2956. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2957. /* file does not exist and will not be created */
  2958. return 0;
  2959. }
  2960. #if defined(_WIN32)
  2961. {
  2962. wchar_t wbuf[W_PATH_MAX];
  2963. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2964. switch (mode) {
  2965. case MG_FOPEN_MODE_READ:
  2966. filep->access.fp = _wfopen(wbuf, L"rb");
  2967. break;
  2968. case MG_FOPEN_MODE_WRITE:
  2969. filep->access.fp = _wfopen(wbuf, L"wb");
  2970. break;
  2971. case MG_FOPEN_MODE_APPEND:
  2972. filep->access.fp = _wfopen(wbuf, L"ab");
  2973. break;
  2974. }
  2975. }
  2976. #else
  2977. /* Linux et al already use unicode. No need to convert. */
  2978. switch (mode) {
  2979. case MG_FOPEN_MODE_READ:
  2980. filep->access.fp = fopen(path, "r");
  2981. break;
  2982. case MG_FOPEN_MODE_WRITE:
  2983. filep->access.fp = fopen(path, "w");
  2984. break;
  2985. case MG_FOPEN_MODE_APPEND:
  2986. filep->access.fp = fopen(path, "a");
  2987. break;
  2988. }
  2989. #endif
  2990. if (!found) {
  2991. /* File did not exist before fopen was called.
  2992. * Maybe it has been created now. Get stat info
  2993. * like creation time now. */
  2994. found = mg_stat(conn, path, &(filep->stat));
  2995. (void)found;
  2996. }
  2997. /* return OK if file is opened */
  2998. return (filep->access.fp != NULL);
  2999. }
  3000. /* return 0 on success, just like fclose */
  3001. static int
  3002. mg_fclose(struct mg_file_access *fileacc)
  3003. {
  3004. int ret = -1;
  3005. if (fileacc != NULL) {
  3006. if (fileacc->fp != NULL) {
  3007. ret = fclose(fileacc->fp);
  3008. }
  3009. /* reset all members of fileacc */
  3010. memset(fileacc, 0, sizeof(*fileacc));
  3011. }
  3012. return ret;
  3013. }
  3014. #endif /* NO_FILESYSTEMS */
  3015. static void
  3016. mg_strlcpy(register char *dst, register const char *src, size_t n)
  3017. {
  3018. for (; *src != '\0' && n > 1; n--) {
  3019. *dst++ = *src++;
  3020. }
  3021. *dst = '\0';
  3022. }
  3023. static int
  3024. lowercase(const char *s)
  3025. {
  3026. return tolower((unsigned char)*s);
  3027. }
  3028. int
  3029. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  3030. {
  3031. int diff = 0;
  3032. if (len > 0) {
  3033. do {
  3034. diff = lowercase(s1++) - lowercase(s2++);
  3035. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  3036. }
  3037. return diff;
  3038. }
  3039. int
  3040. mg_strcasecmp(const char *s1, const char *s2)
  3041. {
  3042. int diff;
  3043. do {
  3044. diff = lowercase(s1++) - lowercase(s2++);
  3045. } while (diff == 0 && s1[-1] != '\0');
  3046. return diff;
  3047. }
  3048. static char *
  3049. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3050. {
  3051. char *p;
  3052. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3053. * defined */
  3054. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3055. mg_strlcpy(p, ptr, len + 1);
  3056. }
  3057. return p;
  3058. }
  3059. static char *
  3060. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3061. {
  3062. return mg_strndup_ctx(str, strlen(str), ctx);
  3063. }
  3064. static char *
  3065. mg_strdup(const char *str)
  3066. {
  3067. return mg_strndup_ctx(str, strlen(str), NULL);
  3068. }
  3069. static const char *
  3070. mg_strcasestr(const char *big_str, const char *small_str)
  3071. {
  3072. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3073. if (big_len >= small_len) {
  3074. for (i = 0; i <= (big_len - small_len); i++) {
  3075. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3076. return big_str + i;
  3077. }
  3078. }
  3079. }
  3080. return NULL;
  3081. }
  3082. /* Return null terminated string of given maximum length.
  3083. * Report errors if length is exceeded. */
  3084. static void
  3085. mg_vsnprintf(const struct mg_connection *conn,
  3086. int *truncated,
  3087. char *buf,
  3088. size_t buflen,
  3089. const char *fmt,
  3090. va_list ap)
  3091. {
  3092. int n, ok;
  3093. if (buflen == 0) {
  3094. if (truncated) {
  3095. *truncated = 1;
  3096. }
  3097. return;
  3098. }
  3099. #if defined(__clang__)
  3100. #pragma clang diagnostic push
  3101. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3102. /* Using fmt as a non-literal is intended here, since it is mostly called
  3103. * indirectly by mg_snprintf */
  3104. #endif
  3105. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3106. ok = (n >= 0) && ((size_t)n < buflen);
  3107. #if defined(__clang__)
  3108. #pragma clang diagnostic pop
  3109. #endif
  3110. if (ok) {
  3111. if (truncated) {
  3112. *truncated = 0;
  3113. }
  3114. } else {
  3115. if (truncated) {
  3116. *truncated = 1;
  3117. }
  3118. mg_cry_internal(conn,
  3119. "truncating vsnprintf buffer: [%.*s]",
  3120. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3121. buf);
  3122. n = (int)buflen - 1;
  3123. }
  3124. buf[n] = '\0';
  3125. }
  3126. static void
  3127. mg_snprintf(const struct mg_connection *conn,
  3128. int *truncated,
  3129. char *buf,
  3130. size_t buflen,
  3131. const char *fmt,
  3132. ...)
  3133. {
  3134. va_list ap;
  3135. va_start(ap, fmt);
  3136. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3137. va_end(ap);
  3138. }
  3139. static int
  3140. get_option_index(const char *name)
  3141. {
  3142. int i;
  3143. for (i = 0; config_options[i].name != NULL; i++) {
  3144. if (strcmp(config_options[i].name, name) == 0) {
  3145. return i;
  3146. }
  3147. }
  3148. return -1;
  3149. }
  3150. const char *
  3151. mg_get_option(const struct mg_context *ctx, const char *name)
  3152. {
  3153. int i;
  3154. if ((i = get_option_index(name)) == -1) {
  3155. return NULL;
  3156. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3157. return "";
  3158. } else {
  3159. return ctx->dd.config[i];
  3160. }
  3161. }
  3162. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3163. struct mg_context *
  3164. mg_get_context(const struct mg_connection *conn)
  3165. {
  3166. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3167. }
  3168. void *
  3169. mg_get_user_data(const struct mg_context *ctx)
  3170. {
  3171. return (ctx == NULL) ? NULL : ctx->user_data;
  3172. }
  3173. void *
  3174. mg_get_user_context_data(const struct mg_connection *conn)
  3175. {
  3176. return mg_get_user_data(mg_get_context(conn));
  3177. }
  3178. void *
  3179. mg_get_thread_pointer(const struct mg_connection *conn)
  3180. {
  3181. /* both methods should return the same pointer */
  3182. if (conn) {
  3183. /* quick access, in case conn is known */
  3184. return conn->tls_user_ptr;
  3185. } else {
  3186. /* otherwise get pointer from thread local storage (TLS) */
  3187. struct mg_workerTLS *tls =
  3188. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3189. return tls->user_ptr;
  3190. }
  3191. }
  3192. void
  3193. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3194. {
  3195. if (conn != NULL) {
  3196. conn->request_info.conn_data = data;
  3197. }
  3198. }
  3199. void *
  3200. mg_get_user_connection_data(const struct mg_connection *conn)
  3201. {
  3202. if (conn != NULL) {
  3203. return conn->request_info.conn_data;
  3204. }
  3205. return NULL;
  3206. }
  3207. #if defined(MG_LEGACY_INTERFACE)
  3208. /* Deprecated: Use mg_get_server_ports instead. */
  3209. size_t
  3210. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3211. {
  3212. size_t i;
  3213. if (!ctx) {
  3214. return 0;
  3215. }
  3216. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3217. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3218. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3219. }
  3220. return i;
  3221. }
  3222. #endif
  3223. int
  3224. mg_get_server_ports(const struct mg_context *ctx,
  3225. int size,
  3226. struct mg_server_port *ports)
  3227. {
  3228. int i, cnt = 0;
  3229. if (size <= 0) {
  3230. return -1;
  3231. }
  3232. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3233. if (!ctx) {
  3234. return -1;
  3235. }
  3236. if (!ctx->listening_sockets) {
  3237. return -1;
  3238. }
  3239. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3240. ports[cnt].port =
  3241. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3242. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3243. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3244. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3245. /* IPv4 */
  3246. ports[cnt].protocol = 1;
  3247. cnt++;
  3248. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3249. /* IPv6 */
  3250. ports[cnt].protocol = 3;
  3251. cnt++;
  3252. }
  3253. }
  3254. return cnt;
  3255. }
  3256. static void
  3257. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3258. {
  3259. buf[0] = '\0';
  3260. if (!usa) {
  3261. return;
  3262. }
  3263. if (usa->sa.sa_family == AF_INET) {
  3264. getnameinfo(&usa->sa,
  3265. sizeof(usa->sin),
  3266. buf,
  3267. (unsigned)len,
  3268. NULL,
  3269. 0,
  3270. NI_NUMERICHOST);
  3271. }
  3272. #if defined(USE_IPV6)
  3273. else if (usa->sa.sa_family == AF_INET6) {
  3274. getnameinfo(&usa->sa,
  3275. sizeof(usa->sin6),
  3276. buf,
  3277. (unsigned)len,
  3278. NULL,
  3279. 0,
  3280. NI_NUMERICHOST);
  3281. }
  3282. #endif
  3283. }
  3284. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3285. * included in all responses other than 100, 101, 5xx. */
  3286. static void
  3287. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3288. {
  3289. #if !defined(REENTRANT_TIME)
  3290. struct tm *tm;
  3291. tm = ((t != NULL) ? gmtime(t) : NULL);
  3292. if (tm != NULL) {
  3293. #else
  3294. struct tm _tm;
  3295. struct tm *tm = &_tm;
  3296. if (t != NULL) {
  3297. gmtime_r(t, tm);
  3298. #endif
  3299. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3300. } else {
  3301. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3302. buf[buf_len - 1] = '\0';
  3303. }
  3304. }
  3305. /* difftime for struct timespec. Return value is in seconds. */
  3306. static double
  3307. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3308. {
  3309. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3310. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3311. }
  3312. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3313. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3314. const char *func,
  3315. unsigned line,
  3316. const char *fmt,
  3317. va_list ap);
  3318. #include "external_mg_cry_internal_impl.inl"
  3319. #elif !defined(NO_FILESYSTEMS)
  3320. /* Print error message to the opened error log stream. */
  3321. static void
  3322. mg_cry_internal_impl(const struct mg_connection *conn,
  3323. const char *func,
  3324. unsigned line,
  3325. const char *fmt,
  3326. va_list ap)
  3327. {
  3328. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3329. struct mg_file fi;
  3330. time_t timestamp;
  3331. /* Unused, in the RELEASE build */
  3332. (void)func;
  3333. (void)line;
  3334. #if defined(GCC_DIAGNOSTIC)
  3335. #pragma GCC diagnostic push
  3336. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3337. #endif
  3338. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3339. #if defined(GCC_DIAGNOSTIC)
  3340. #pragma GCC diagnostic pop
  3341. #endif
  3342. buf[sizeof(buf) - 1] = 0;
  3343. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3344. if (!conn) {
  3345. puts(buf);
  3346. return;
  3347. }
  3348. /* Do not lock when getting the callback value, here and below.
  3349. * I suppose this is fine, since function cannot disappear in the
  3350. * same way string option can. */
  3351. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3352. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3353. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3354. if (mg_fopen(conn,
  3355. conn->dom_ctx->config[ERROR_LOG_FILE],
  3356. MG_FOPEN_MODE_APPEND,
  3357. &fi)
  3358. == 0) {
  3359. fi.access.fp = NULL;
  3360. }
  3361. } else {
  3362. fi.access.fp = NULL;
  3363. }
  3364. if (fi.access.fp != NULL) {
  3365. flockfile(fi.access.fp);
  3366. timestamp = time(NULL);
  3367. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3368. fprintf(fi.access.fp,
  3369. "[%010lu] [error] [client %s] ",
  3370. (unsigned long)timestamp,
  3371. src_addr);
  3372. if (conn->request_info.request_method != NULL) {
  3373. fprintf(fi.access.fp,
  3374. "%s %s: ",
  3375. conn->request_info.request_method,
  3376. conn->request_info.request_uri
  3377. ? conn->request_info.request_uri
  3378. : "");
  3379. }
  3380. fprintf(fi.access.fp, "%s", buf);
  3381. fputc('\n', fi.access.fp);
  3382. fflush(fi.access.fp);
  3383. funlockfile(fi.access.fp);
  3384. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3385. * mg_cry here anyway ;-) */
  3386. }
  3387. }
  3388. }
  3389. #else
  3390. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3391. #endif /* Externally provided function */
  3392. /* Construct fake connection structure. Used for logging, if connection
  3393. * is not applicable at the moment of logging. */
  3394. static struct mg_connection *
  3395. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3396. {
  3397. static const struct mg_connection conn_zero = {0};
  3398. *fc = conn_zero;
  3399. fc->phys_ctx = ctx;
  3400. fc->dom_ctx = &(ctx->dd);
  3401. return fc;
  3402. }
  3403. static void
  3404. mg_cry_internal_wrap(const struct mg_connection *conn,
  3405. struct mg_context *ctx,
  3406. const char *func,
  3407. unsigned line,
  3408. const char *fmt,
  3409. ...)
  3410. {
  3411. va_list ap;
  3412. va_start(ap, fmt);
  3413. if (!conn && ctx) {
  3414. struct mg_connection fc;
  3415. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3416. } else {
  3417. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3418. }
  3419. va_end(ap);
  3420. }
  3421. void
  3422. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3423. {
  3424. va_list ap;
  3425. va_start(ap, fmt);
  3426. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3427. va_end(ap);
  3428. }
  3429. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3430. const char *
  3431. mg_version(void)
  3432. {
  3433. return CIVETWEB_VERSION;
  3434. }
  3435. const struct mg_request_info *
  3436. mg_get_request_info(const struct mg_connection *conn)
  3437. {
  3438. if (!conn) {
  3439. return NULL;
  3440. }
  3441. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3442. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3443. char txt[16];
  3444. struct mg_workerTLS *tls =
  3445. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3446. sprintf(txt, "%03i", conn->response_info.status_code);
  3447. if (strlen(txt) == 3) {
  3448. memcpy(tls->txtbuf, txt, 4);
  3449. } else {
  3450. strcpy(tls->txtbuf, "ERR");
  3451. }
  3452. ((struct mg_connection *)conn)->request_info.local_uri =
  3453. ((struct mg_connection *)conn)->request_info.request_uri =
  3454. tls->txtbuf; /* use thread safe buffer */
  3455. ((struct mg_connection *)conn)->request_info.num_headers =
  3456. conn->response_info.num_headers;
  3457. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3458. conn->response_info.http_headers,
  3459. sizeof(conn->response_info.http_headers));
  3460. } else
  3461. #endif
  3462. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3463. return NULL;
  3464. }
  3465. return &conn->request_info;
  3466. }
  3467. const struct mg_response_info *
  3468. mg_get_response_info(const struct mg_connection *conn)
  3469. {
  3470. if (!conn) {
  3471. return NULL;
  3472. }
  3473. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3474. return NULL;
  3475. }
  3476. return &conn->response_info;
  3477. }
  3478. static const char *
  3479. get_proto_name(const struct mg_connection *conn)
  3480. {
  3481. #if defined(__clang__)
  3482. #pragma clang diagnostic push
  3483. #pragma clang diagnostic ignored "-Wunreachable-code"
  3484. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3485. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3486. * unreachable, but splitting into four different #ifdef clauses here is more
  3487. * complicated.
  3488. */
  3489. #endif
  3490. const struct mg_request_info *ri = &conn->request_info;
  3491. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3492. ? (ri->is_ssl ? "wss" : "ws")
  3493. : (ri->is_ssl ? "https" : "http"));
  3494. return proto;
  3495. #if defined(__clang__)
  3496. #pragma clang diagnostic pop
  3497. #endif
  3498. }
  3499. static int
  3500. mg_construct_local_link(const struct mg_connection *conn,
  3501. char *buf,
  3502. size_t buflen,
  3503. const char *define_proto,
  3504. int define_port,
  3505. const char *define_uri)
  3506. {
  3507. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3508. return -1;
  3509. } else {
  3510. int truncated = 0;
  3511. const struct mg_request_info *ri = &conn->request_info;
  3512. const char *proto =
  3513. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3514. const char *uri =
  3515. (define_uri != NULL)
  3516. ? define_uri
  3517. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3518. int port = (define_port > 0)
  3519. ? define_port
  3520. : htons(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  3521. int default_port = 80;
  3522. if (uri == NULL) {
  3523. return -1;
  3524. }
  3525. if (define_proto) {
  3526. /* If we got a protocol name, use the default port accordingly. */
  3527. if ((0 == strcmp(define_proto, "https"))
  3528. || (0 == strcmp(define_proto, "wss"))) {
  3529. default_port = 443;
  3530. }
  3531. } else if (ri->is_ssl) {
  3532. /* If we did not get a protocol name, use TLS as default if it is
  3533. * already used. */
  3534. default_port = 443;
  3535. }
  3536. {
  3537. #if defined(USE_IPV6)
  3538. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3539. #endif
  3540. int auth_domain_check_enabled =
  3541. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3542. && (!mg_strcasecmp(
  3543. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3544. const char *server_domain =
  3545. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3546. char portstr[16];
  3547. char server_ip[48];
  3548. if (port != default_port) {
  3549. sprintf(portstr, ":%u", (unsigned)port);
  3550. } else {
  3551. portstr[0] = 0;
  3552. }
  3553. if (!auth_domain_check_enabled || !server_domain) {
  3554. sockaddr_to_string(server_ip,
  3555. sizeof(server_ip),
  3556. &conn->client.lsa);
  3557. server_domain = server_ip;
  3558. }
  3559. mg_snprintf(conn,
  3560. &truncated,
  3561. buf,
  3562. buflen,
  3563. #if defined(USE_IPV6)
  3564. "%s://%s%s%s%s%s",
  3565. proto,
  3566. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3567. server_domain,
  3568. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3569. #else
  3570. "%s://%s%s%s",
  3571. proto,
  3572. server_domain,
  3573. #endif
  3574. portstr,
  3575. ri->local_uri);
  3576. if (truncated) {
  3577. return -1;
  3578. }
  3579. return 0;
  3580. }
  3581. }
  3582. }
  3583. int
  3584. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3585. {
  3586. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3587. }
  3588. /* Skip the characters until one of the delimiters characters found.
  3589. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3590. * Advance pointer to buffer to the next word. Return found 0-terminated
  3591. * word.
  3592. * Delimiters can be quoted with quotechar. */
  3593. static char *
  3594. skip_quoted(char **buf,
  3595. const char *delimiters,
  3596. const char *whitespace,
  3597. char quotechar)
  3598. {
  3599. char *p, *begin_word, *end_word, *end_whitespace;
  3600. begin_word = *buf;
  3601. end_word = begin_word + strcspn(begin_word, delimiters);
  3602. /* Check for quotechar */
  3603. if (end_word > begin_word) {
  3604. p = end_word - 1;
  3605. while (*p == quotechar) {
  3606. /* While the delimiter is quoted, look for the next delimiter.
  3607. */
  3608. /* This happens, e.g., in calls from parse_auth_header,
  3609. * if the user name contains a " character. */
  3610. /* If there is anything beyond end_word, copy it. */
  3611. if (*end_word != '\0') {
  3612. size_t end_off = strcspn(end_word + 1, delimiters);
  3613. memmove(p, end_word, end_off + 1);
  3614. p += end_off; /* p must correspond to end_word - 1 */
  3615. end_word += end_off + 1;
  3616. } else {
  3617. *p = '\0';
  3618. break;
  3619. }
  3620. }
  3621. for (p++; p < end_word; p++) {
  3622. *p = '\0';
  3623. }
  3624. }
  3625. if (*end_word == '\0') {
  3626. *buf = end_word;
  3627. } else {
  3628. #if defined(GCC_DIAGNOSTIC)
  3629. /* Disable spurious conversion warning for GCC */
  3630. #pragma GCC diagnostic push
  3631. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3632. #endif /* defined(GCC_DIAGNOSTIC) */
  3633. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3634. #if defined(GCC_DIAGNOSTIC)
  3635. #pragma GCC diagnostic pop
  3636. #endif /* defined(GCC_DIAGNOSTIC) */
  3637. for (p = end_word; p < end_whitespace; p++) {
  3638. *p = '\0';
  3639. }
  3640. *buf = end_whitespace;
  3641. }
  3642. return begin_word;
  3643. }
  3644. /* Return HTTP header value, or NULL if not found. */
  3645. static const char *
  3646. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3647. {
  3648. int i;
  3649. for (i = 0; i < num_hdr; i++) {
  3650. if (!mg_strcasecmp(name, hdr[i].name)) {
  3651. return hdr[i].value;
  3652. }
  3653. }
  3654. return NULL;
  3655. }
  3656. #if defined(USE_WEBSOCKET)
  3657. /* Retrieve requested HTTP header multiple values, and return the number of
  3658. * found occurrences */
  3659. static int
  3660. get_req_headers(const struct mg_request_info *ri,
  3661. const char *name,
  3662. const char **output,
  3663. int output_max_size)
  3664. {
  3665. int i;
  3666. int cnt = 0;
  3667. if (ri) {
  3668. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3669. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3670. output[cnt++] = ri->http_headers[i].value;
  3671. }
  3672. }
  3673. }
  3674. return cnt;
  3675. }
  3676. #endif
  3677. const char *
  3678. mg_get_header(const struct mg_connection *conn, const char *name)
  3679. {
  3680. if (!conn) {
  3681. return NULL;
  3682. }
  3683. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3684. return get_header(conn->request_info.http_headers,
  3685. conn->request_info.num_headers,
  3686. name);
  3687. }
  3688. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3689. return get_header(conn->response_info.http_headers,
  3690. conn->response_info.num_headers,
  3691. name);
  3692. }
  3693. return NULL;
  3694. }
  3695. static const char *
  3696. get_http_version(const struct mg_connection *conn)
  3697. {
  3698. if (!conn) {
  3699. return NULL;
  3700. }
  3701. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3702. return conn->request_info.http_version;
  3703. }
  3704. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3705. return conn->response_info.http_version;
  3706. }
  3707. return NULL;
  3708. }
  3709. /* A helper function for traversing a comma separated list of values.
  3710. * It returns a list pointer shifted to the next value, or NULL if the end
  3711. * of the list found.
  3712. * Value is stored in val vector. If value has form "x=y", then eq_val
  3713. * vector is initialized to point to the "y" part, and val vector length
  3714. * is adjusted to point only to "x". */
  3715. static const char *
  3716. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3717. {
  3718. int end;
  3719. reparse:
  3720. if (val == NULL || list == NULL || *list == '\0') {
  3721. /* End of the list */
  3722. return NULL;
  3723. }
  3724. /* Skip over leading LWS */
  3725. while (*list == ' ' || *list == '\t')
  3726. list++;
  3727. val->ptr = list;
  3728. if ((list = strchr(val->ptr, ',')) != NULL) {
  3729. /* Comma found. Store length and shift the list ptr */
  3730. val->len = ((size_t)(list - val->ptr));
  3731. list++;
  3732. } else {
  3733. /* This value is the last one */
  3734. list = val->ptr + strlen(val->ptr);
  3735. val->len = ((size_t)(list - val->ptr));
  3736. }
  3737. /* Adjust length for trailing LWS */
  3738. end = (int)val->len - 1;
  3739. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3740. end--;
  3741. val->len = (size_t)(end) + (size_t)(1);
  3742. if (val->len == 0) {
  3743. /* Ignore any empty entries. */
  3744. goto reparse;
  3745. }
  3746. if (eq_val != NULL) {
  3747. /* Value has form "x=y", adjust pointers and lengths
  3748. * so that val points to "x", and eq_val points to "y". */
  3749. eq_val->len = 0;
  3750. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3751. if (eq_val->ptr != NULL) {
  3752. eq_val->ptr++; /* Skip over '=' character */
  3753. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3754. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3755. }
  3756. }
  3757. return list;
  3758. }
  3759. /* A helper function for checking if a comma separated list of values
  3760. * contains
  3761. * the given option (case insensitvely).
  3762. * 'header' can be NULL, in which case false is returned. */
  3763. static int
  3764. header_has_option(const char *header, const char *option)
  3765. {
  3766. struct vec opt_vec;
  3767. struct vec eq_vec;
  3768. DEBUG_ASSERT(option != NULL);
  3769. DEBUG_ASSERT(option[0] != '\0');
  3770. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3771. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3772. return 1;
  3773. }
  3774. return 0;
  3775. }
  3776. /* Perform case-insensitive match of string against pattern */
  3777. static ptrdiff_t
  3778. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3779. {
  3780. const char *or_str;
  3781. ptrdiff_t i, j, len, res;
  3782. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3783. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3784. return (res > 0) ? res
  3785. : match_prefix(or_str + 1,
  3786. (size_t)((pattern + pattern_len)
  3787. - (or_str + 1)),
  3788. str);
  3789. }
  3790. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3791. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3792. continue;
  3793. } else if (pattern[i] == '$') {
  3794. return (str[j] == '\0') ? j : -1;
  3795. } else if (pattern[i] == '*') {
  3796. i++;
  3797. if (pattern[i] == '*') {
  3798. i++;
  3799. len = (ptrdiff_t)strlen(str + j);
  3800. } else {
  3801. len = (ptrdiff_t)strcspn(str + j, "/");
  3802. }
  3803. if (i == (ptrdiff_t)pattern_len) {
  3804. return j + len;
  3805. }
  3806. do {
  3807. res = match_prefix(pattern + i,
  3808. (pattern_len - (size_t)i),
  3809. str + j + len);
  3810. } while (res == -1 && len-- > 0);
  3811. return (res == -1) ? -1 : j + res + len;
  3812. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3813. return -1;
  3814. }
  3815. }
  3816. return (ptrdiff_t)j;
  3817. }
  3818. static ptrdiff_t
  3819. match_prefix_strlen(const char *pattern, const char *str)
  3820. {
  3821. if (pattern == NULL) {
  3822. return -1;
  3823. }
  3824. return match_prefix(pattern, strlen(pattern), str);
  3825. }
  3826. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3827. * This function must tolerate situations when connection info is not
  3828. * set up, for example if request parsing failed. */
  3829. static int
  3830. should_keep_alive(const struct mg_connection *conn)
  3831. {
  3832. const char *http_version;
  3833. const char *header;
  3834. /* First satisfy needs of the server */
  3835. if ((conn == NULL) || conn->must_close) {
  3836. /* Close, if civetweb framework needs to close */
  3837. return 0;
  3838. }
  3839. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3840. /* Close, if keep alive is not enabled */
  3841. return 0;
  3842. }
  3843. /* Check explicit wish of the client */
  3844. header = mg_get_header(conn, "Connection");
  3845. if (header) {
  3846. /* If there is a connection header from the client, obey */
  3847. if (header_has_option(header, "keep-alive")) {
  3848. return 1;
  3849. }
  3850. return 0;
  3851. }
  3852. /* Use default of the standard */
  3853. http_version = get_http_version(conn);
  3854. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3855. /* HTTP 1.1 default is keep alive */
  3856. return 1;
  3857. }
  3858. /* HTTP 1.0 (and earlier) default is to close the connection */
  3859. return 0;
  3860. }
  3861. static int
  3862. should_decode_url(const struct mg_connection *conn)
  3863. {
  3864. if (!conn || !conn->dom_ctx) {
  3865. return 0;
  3866. }
  3867. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3868. }
  3869. static const char *
  3870. suggest_connection_header(const struct mg_connection *conn)
  3871. {
  3872. return should_keep_alive(conn) ? "keep-alive" : "close";
  3873. }
  3874. #include "response.inl"
  3875. static void
  3876. send_no_cache_header(struct mg_connection *conn)
  3877. {
  3878. /* Send all current and obsolete cache opt-out directives. */
  3879. mg_response_header_add(conn,
  3880. "Cache-Control",
  3881. "no-cache, no-store, "
  3882. "must-revalidate, private, max-age=0",
  3883. -1);
  3884. mg_response_header_add(conn, "Expires", "0", -1);
  3885. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3886. /* Obsolete, but still send it for HTTP/1.0 */
  3887. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3888. }
  3889. }
  3890. static void
  3891. send_static_cache_header(struct mg_connection *conn)
  3892. {
  3893. #if !defined(NO_CACHING)
  3894. int max_age;
  3895. char val[64];
  3896. const char *cache_control =
  3897. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3898. /* If there is a full cache-control option configured,0 use it */
  3899. if (cache_control != NULL) {
  3900. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3901. return;
  3902. }
  3903. /* Read the server config to check how long a file may be cached.
  3904. * The configuration is in seconds. */
  3905. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3906. if (max_age <= 0) {
  3907. /* 0 means "do not cache". All values <0 are reserved
  3908. * and may be used differently in the future. */
  3909. /* If a file should not be cached, do not only send
  3910. * max-age=0, but also pragmas and Expires headers. */
  3911. send_no_cache_header(conn);
  3912. return;
  3913. }
  3914. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3915. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3916. /* See also https://www.mnot.net/cache_docs/ */
  3917. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3918. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3919. * leap
  3920. * year to 31622400 seconds. For the moment, we just send whatever has
  3921. * been configured, still the behavior for >1 year should be considered
  3922. * as undefined. */
  3923. mg_snprintf(
  3924. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3925. mg_response_header_add(conn, "Cache-Control", val, -1);
  3926. #else /* NO_CACHING */
  3927. send_no_cache_header(conn);
  3928. #endif /* !NO_CACHING */
  3929. }
  3930. static void
  3931. send_additional_header(struct mg_connection *conn)
  3932. {
  3933. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3934. #if !defined(NO_SSL)
  3935. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3936. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3937. if (max_age >= 0) {
  3938. char val[64];
  3939. mg_snprintf(conn,
  3940. NULL,
  3941. val,
  3942. sizeof(val),
  3943. "max-age=%lu",
  3944. (unsigned long)max_age);
  3945. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3946. }
  3947. }
  3948. #endif
  3949. if (header && header[0]) {
  3950. mg_response_header_add_lines(conn, header);
  3951. }
  3952. }
  3953. #if !defined(NO_FILESYSTEMS)
  3954. static void handle_file_based_request(struct mg_connection *conn,
  3955. const char *path,
  3956. struct mg_file *filep);
  3957. #endif /* NO_FILESYSTEMS */
  3958. const char *
  3959. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3960. {
  3961. /* See IANA HTTP status code assignment:
  3962. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3963. */
  3964. switch (response_code) {
  3965. /* RFC2616 Section 10.1 - Informational 1xx */
  3966. case 100:
  3967. return "Continue"; /* RFC2616 Section 10.1.1 */
  3968. case 101:
  3969. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3970. case 102:
  3971. return "Processing"; /* RFC2518 Section 10.1 */
  3972. /* RFC2616 Section 10.2 - Successful 2xx */
  3973. case 200:
  3974. return "OK"; /* RFC2616 Section 10.2.1 */
  3975. case 201:
  3976. return "Created"; /* RFC2616 Section 10.2.2 */
  3977. case 202:
  3978. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3979. case 203:
  3980. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3981. case 204:
  3982. return "No Content"; /* RFC2616 Section 10.2.5 */
  3983. case 205:
  3984. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3985. case 206:
  3986. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3987. case 207:
  3988. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3989. */
  3990. case 208:
  3991. return "Already Reported"; /* RFC5842 Section 7.1 */
  3992. case 226:
  3993. return "IM used"; /* RFC3229 Section 10.4.1 */
  3994. /* RFC2616 Section 10.3 - Redirection 3xx */
  3995. case 300:
  3996. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3997. case 301:
  3998. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3999. case 302:
  4000. return "Found"; /* RFC2616 Section 10.3.3 */
  4001. case 303:
  4002. return "See Other"; /* RFC2616 Section 10.3.4 */
  4003. case 304:
  4004. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  4005. case 305:
  4006. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  4007. case 307:
  4008. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  4009. case 308:
  4010. return "Permanent Redirect"; /* RFC7238 Section 3 */
  4011. /* RFC2616 Section 10.4 - Client Error 4xx */
  4012. case 400:
  4013. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  4014. case 401:
  4015. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  4016. case 402:
  4017. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  4018. case 403:
  4019. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  4020. case 404:
  4021. return "Not Found"; /* RFC2616 Section 10.4.5 */
  4022. case 405:
  4023. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  4024. case 406:
  4025. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  4026. case 407:
  4027. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  4028. case 408:
  4029. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  4030. case 409:
  4031. return "Conflict"; /* RFC2616 Section 10.4.10 */
  4032. case 410:
  4033. return "Gone"; /* RFC2616 Section 10.4.11 */
  4034. case 411:
  4035. return "Length Required"; /* RFC2616 Section 10.4.12 */
  4036. case 412:
  4037. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  4038. case 413:
  4039. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  4040. case 414:
  4041. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  4042. case 415:
  4043. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  4044. case 416:
  4045. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  4046. */
  4047. case 417:
  4048. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  4049. case 421:
  4050. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  4051. case 422:
  4052. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  4053. * Section 11.2 */
  4054. case 423:
  4055. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  4056. case 424:
  4057. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  4058. * Section 11.4 */
  4059. case 426:
  4060. return "Upgrade Required"; /* RFC 2817 Section 4 */
  4061. case 428:
  4062. return "Precondition Required"; /* RFC 6585, Section 3 */
  4063. case 429:
  4064. return "Too Many Requests"; /* RFC 6585, Section 4 */
  4065. case 431:
  4066. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  4067. case 451:
  4068. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  4069. * Section 3 */
  4070. /* RFC2616 Section 10.5 - Server Error 5xx */
  4071. case 500:
  4072. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  4073. case 501:
  4074. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  4075. case 502:
  4076. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4077. case 503:
  4078. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4079. case 504:
  4080. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4081. case 505:
  4082. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4083. case 506:
  4084. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4085. case 507:
  4086. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4087. * Section 11.5 */
  4088. case 508:
  4089. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4090. case 510:
  4091. return "Not Extended"; /* RFC 2774, Section 7 */
  4092. case 511:
  4093. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4094. /* Other status codes, not shown in the IANA HTTP status code
  4095. * assignment.
  4096. * E.g., "de facto" standards due to common use, ... */
  4097. case 418:
  4098. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4099. case 419:
  4100. return "Authentication Timeout"; /* common use */
  4101. case 420:
  4102. return "Enhance Your Calm"; /* common use */
  4103. case 440:
  4104. return "Login Timeout"; /* common use */
  4105. case 509:
  4106. return "Bandwidth Limit Exceeded"; /* common use */
  4107. default:
  4108. /* This error code is unknown. This should not happen. */
  4109. if (conn) {
  4110. mg_cry_internal(conn,
  4111. "Unknown HTTP response code: %u",
  4112. response_code);
  4113. }
  4114. /* Return at least a category according to RFC 2616 Section 10. */
  4115. if (response_code >= 100 && response_code < 200) {
  4116. /* Unknown informational status code */
  4117. return "Information";
  4118. }
  4119. if (response_code >= 200 && response_code < 300) {
  4120. /* Unknown success code */
  4121. return "Success";
  4122. }
  4123. if (response_code >= 300 && response_code < 400) {
  4124. /* Unknown redirection code */
  4125. return "Redirection";
  4126. }
  4127. if (response_code >= 400 && response_code < 500) {
  4128. /* Unknown request error code */
  4129. return "Client Error";
  4130. }
  4131. if (response_code >= 500 && response_code < 600) {
  4132. /* Unknown server error code */
  4133. return "Server Error";
  4134. }
  4135. /* Response code not even within reasonable range */
  4136. return "";
  4137. }
  4138. }
  4139. static int
  4140. mg_send_http_error_impl(struct mg_connection *conn,
  4141. int status,
  4142. const char *fmt,
  4143. va_list args)
  4144. {
  4145. char errmsg_buf[MG_BUF_LEN];
  4146. va_list ap;
  4147. int has_body;
  4148. #if !defined(NO_FILESYSTEMS)
  4149. char path_buf[PATH_MAX];
  4150. int len, i, page_handler_found, scope, truncated;
  4151. const char *error_handler = NULL;
  4152. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4153. const char *error_page_file_ext, *tstr;
  4154. #endif /* NO_FILESYSTEMS */
  4155. int handled_by_callback = 0;
  4156. if ((conn == NULL) || (fmt == NULL)) {
  4157. return -2;
  4158. }
  4159. /* Set status (for log) */
  4160. conn->status_code = status;
  4161. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4162. has_body = ((status > 199) && (status != 204) && (status != 304));
  4163. /* Prepare message in buf, if required */
  4164. if (has_body
  4165. || (!conn->in_error_handler
  4166. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4167. /* Store error message in errmsg_buf */
  4168. va_copy(ap, args);
  4169. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4170. va_end(ap);
  4171. /* In a debug build, print all html errors */
  4172. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4173. }
  4174. /* If there is a http_error callback, call it.
  4175. * But don't do it recursively, if callback calls mg_send_http_error again.
  4176. */
  4177. if (!conn->in_error_handler
  4178. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4179. /* Mark in_error_handler to avoid recursion and call user callback. */
  4180. conn->in_error_handler = 1;
  4181. handled_by_callback =
  4182. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4183. == 0);
  4184. conn->in_error_handler = 0;
  4185. }
  4186. if (!handled_by_callback) {
  4187. /* Check for recursion */
  4188. if (conn->in_error_handler) {
  4189. DEBUG_TRACE(
  4190. "Recursion when handling error %u - fall back to default",
  4191. status);
  4192. #if !defined(NO_FILESYSTEMS)
  4193. } else {
  4194. /* Send user defined error pages, if defined */
  4195. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4196. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4197. page_handler_found = 0;
  4198. if (error_handler != NULL) {
  4199. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4200. switch (scope) {
  4201. case 1: /* Handler for specific error, e.g. 404 error */
  4202. mg_snprintf(conn,
  4203. &truncated,
  4204. path_buf,
  4205. sizeof(path_buf) - 32,
  4206. "%serror%03u.",
  4207. error_handler,
  4208. status);
  4209. break;
  4210. case 2: /* Handler for error group, e.g., 5xx error
  4211. * handler
  4212. * for all server errors (500-599) */
  4213. mg_snprintf(conn,
  4214. &truncated,
  4215. path_buf,
  4216. sizeof(path_buf) - 32,
  4217. "%serror%01uxx.",
  4218. error_handler,
  4219. status / 100);
  4220. break;
  4221. default: /* Handler for all errors */
  4222. mg_snprintf(conn,
  4223. &truncated,
  4224. path_buf,
  4225. sizeof(path_buf) - 32,
  4226. "%serror.",
  4227. error_handler);
  4228. break;
  4229. }
  4230. /* String truncation in buf may only occur if
  4231. * error_handler is too long. This string is
  4232. * from the config, not from a client. */
  4233. (void)truncated;
  4234. /* The following code is redundant, but it should avoid
  4235. * false positives in static source code analyzers and
  4236. * vulnerability scanners.
  4237. */
  4238. path_buf[sizeof(path_buf) - 32] = 0;
  4239. len = (int)strlen(path_buf);
  4240. if (len > (int)sizeof(path_buf) - 32) {
  4241. len = (int)sizeof(path_buf) - 32;
  4242. }
  4243. /* Start with the file extenstion from the configuration. */
  4244. tstr = strchr(error_page_file_ext, '.');
  4245. while (tstr) {
  4246. for (i = 1;
  4247. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4248. i++) {
  4249. /* buffer overrun is not possible here, since
  4250. * (i < 32) && (len < sizeof(path_buf) - 32)
  4251. * ==> (i + len) < sizeof(path_buf) */
  4252. path_buf[len + i - 1] = tstr[i];
  4253. }
  4254. /* buffer overrun is not possible here, since
  4255. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4256. * ==> (i + len) <= sizeof(path_buf) */
  4257. path_buf[len + i - 1] = 0;
  4258. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4259. DEBUG_TRACE("Check error page %s - found",
  4260. path_buf);
  4261. page_handler_found = 1;
  4262. break;
  4263. }
  4264. DEBUG_TRACE("Check error page %s - not found",
  4265. path_buf);
  4266. /* Continue with the next file extenstion from the
  4267. * configuration (if there is a next one). */
  4268. tstr = strchr(tstr + i, '.');
  4269. }
  4270. }
  4271. }
  4272. if (page_handler_found) {
  4273. conn->in_error_handler = 1;
  4274. handle_file_based_request(conn, path_buf, &error_page_file);
  4275. conn->in_error_handler = 0;
  4276. return 0;
  4277. }
  4278. #endif /* NO_FILESYSTEMS */
  4279. }
  4280. /* No custom error page. Send default error page. */
  4281. conn->must_close = 1;
  4282. mg_response_header_start(conn, status);
  4283. send_no_cache_header(conn);
  4284. send_additional_header(conn);
  4285. if (has_body) {
  4286. mg_response_header_add(conn,
  4287. "Content-Type",
  4288. "text/plain; charset=utf-8",
  4289. -1);
  4290. }
  4291. mg_response_header_send(conn);
  4292. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4293. if (has_body) {
  4294. /* For other errors, send a generic error message. */
  4295. const char *status_text = mg_get_response_code_text(conn, status);
  4296. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4297. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4298. } else {
  4299. /* No body allowed. Close the connection. */
  4300. DEBUG_TRACE("Error %i", status);
  4301. }
  4302. }
  4303. return 0;
  4304. }
  4305. int
  4306. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4307. {
  4308. va_list ap;
  4309. int ret;
  4310. va_start(ap, fmt);
  4311. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4312. va_end(ap);
  4313. return ret;
  4314. }
  4315. int
  4316. mg_send_http_ok(struct mg_connection *conn,
  4317. const char *mime_type,
  4318. long long content_length)
  4319. {
  4320. if ((mime_type == NULL) || (*mime_type == 0)) {
  4321. /* No content type defined: default to text/html */
  4322. mime_type = "text/html";
  4323. }
  4324. mg_response_header_start(conn, 200);
  4325. send_no_cache_header(conn);
  4326. send_additional_header(conn);
  4327. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  4328. if (content_length < 0) {
  4329. /* Size not known. Use chunked encoding (HTTP/1.x) */
  4330. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  4331. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  4332. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  4333. }
  4334. } else {
  4335. char len[32];
  4336. int trunc = 0;
  4337. mg_snprintf(conn,
  4338. &trunc,
  4339. len,
  4340. sizeof(len),
  4341. "%" UINT64_FMT,
  4342. (uint64_t)content_length);
  4343. if (!trunc) {
  4344. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  4345. * !trunc is always true */
  4346. mg_response_header_add(conn, "Content-Length", len, -1);
  4347. }
  4348. }
  4349. mg_response_header_send(conn);
  4350. return 0;
  4351. }
  4352. int
  4353. mg_send_http_redirect(struct mg_connection *conn,
  4354. const char *target_url,
  4355. int redirect_code)
  4356. {
  4357. /* Send a 30x redirect response.
  4358. *
  4359. * Redirect types (status codes):
  4360. *
  4361. * Status | Perm/Temp | Method | Version
  4362. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4363. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4364. * 303 | temporary | always use GET | HTTP/1.1
  4365. * 307 | temporary | always keep method | HTTP/1.1
  4366. * 308 | permanent | always keep method | HTTP/1.1
  4367. */
  4368. const char *redirect_text;
  4369. int ret;
  4370. size_t content_len = 0;
  4371. #if defined(MG_SEND_REDIRECT_BODY)
  4372. char reply[MG_BUF_LEN];
  4373. #endif
  4374. /* In case redirect_code=0, use 307. */
  4375. if (redirect_code == 0) {
  4376. redirect_code = 307;
  4377. }
  4378. /* In case redirect_code is none of the above, return error. */
  4379. if ((redirect_code != 301) && (redirect_code != 302)
  4380. && (redirect_code != 303) && (redirect_code != 307)
  4381. && (redirect_code != 308)) {
  4382. /* Parameter error */
  4383. return -2;
  4384. }
  4385. /* Get proper text for response code */
  4386. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4387. /* If target_url is not defined, redirect to "/". */
  4388. if ((target_url == NULL) || (*target_url == 0)) {
  4389. target_url = "/";
  4390. }
  4391. #if defined(MG_SEND_REDIRECT_BODY)
  4392. /* TODO: condition name? */
  4393. /* Prepare a response body with a hyperlink.
  4394. *
  4395. * According to RFC2616 (and RFC1945 before):
  4396. * Unless the request method was HEAD, the entity of the
  4397. * response SHOULD contain a short hypertext note with a hyperlink to
  4398. * the new URI(s).
  4399. *
  4400. * However, this response body is not useful in M2M communication.
  4401. * Probably the original reason in the RFC was, clients not supporting
  4402. * a 30x HTTP redirect could still show the HTML page and let the user
  4403. * press the link. Since current browsers support 30x HTTP, the additional
  4404. * HTML body does not seem to make sense anymore.
  4405. *
  4406. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4407. * but it only notes:
  4408. * The server's response payload usually contains a short
  4409. * hypertext note with a hyperlink to the new URI(s).
  4410. *
  4411. * Deactivated by default. If you need the 30x body, set the define.
  4412. */
  4413. mg_snprintf(
  4414. conn,
  4415. NULL /* ignore truncation */,
  4416. reply,
  4417. sizeof(reply),
  4418. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4419. redirect_text,
  4420. target_url,
  4421. target_url);
  4422. content_len = strlen(reply);
  4423. #endif
  4424. /* Do not send any additional header. For all other options,
  4425. * including caching, there are suitable defaults. */
  4426. ret = mg_printf(conn,
  4427. "HTTP/1.1 %i %s\r\n"
  4428. "Location: %s\r\n"
  4429. "Content-Length: %u\r\n"
  4430. "Connection: %s\r\n\r\n",
  4431. redirect_code,
  4432. redirect_text,
  4433. target_url,
  4434. (unsigned int)content_len,
  4435. suggest_connection_header(conn));
  4436. #if defined(MG_SEND_REDIRECT_BODY)
  4437. /* Send response body */
  4438. if (ret > 0) {
  4439. /* ... unless it is a HEAD request */
  4440. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4441. ret = mg_write(conn, reply, content_len);
  4442. }
  4443. }
  4444. #endif
  4445. return (ret > 0) ? ret : -1;
  4446. }
  4447. #if defined(_WIN32)
  4448. /* Create substitutes for POSIX functions in Win32. */
  4449. #if defined(GCC_DIAGNOSTIC)
  4450. /* Show no warning in case system functions are not used. */
  4451. #pragma GCC diagnostic push
  4452. #pragma GCC diagnostic ignored "-Wunused-function"
  4453. #endif
  4454. static int
  4455. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4456. {
  4457. (void)unused;
  4458. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4459. InitializeCriticalSection(&mutex->sec);
  4460. return 0;
  4461. }
  4462. static int
  4463. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4464. {
  4465. DeleteCriticalSection(&mutex->sec);
  4466. return 0;
  4467. }
  4468. static int
  4469. pthread_mutex_lock(pthread_mutex_t *mutex)
  4470. {
  4471. EnterCriticalSection(&mutex->sec);
  4472. return 0;
  4473. }
  4474. static int
  4475. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4476. {
  4477. LeaveCriticalSection(&mutex->sec);
  4478. return 0;
  4479. }
  4480. FUNCTION_MAY_BE_UNUSED
  4481. static int
  4482. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4483. {
  4484. (void)unused;
  4485. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4486. cv->waiting_thread = NULL;
  4487. return 0;
  4488. }
  4489. FUNCTION_MAY_BE_UNUSED
  4490. static int
  4491. pthread_cond_timedwait(pthread_cond_t *cv,
  4492. pthread_mutex_t *mutex,
  4493. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4494. {
  4495. struct mg_workerTLS **ptls,
  4496. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4497. int ok;
  4498. int64_t nsnow, nswaitabs, nswaitrel;
  4499. DWORD mswaitrel;
  4500. pthread_mutex_lock(&cv->threadIdSec);
  4501. /* Add this thread to cv's waiting list */
  4502. ptls = &cv->waiting_thread;
  4503. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4504. ;
  4505. tls->next_waiting_thread = NULL;
  4506. *ptls = tls;
  4507. pthread_mutex_unlock(&cv->threadIdSec);
  4508. if (abstime) {
  4509. nsnow = mg_get_current_time_ns();
  4510. nswaitabs =
  4511. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4512. nswaitrel = nswaitabs - nsnow;
  4513. if (nswaitrel < 0) {
  4514. nswaitrel = 0;
  4515. }
  4516. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4517. } else {
  4518. mswaitrel = (DWORD)INFINITE;
  4519. }
  4520. pthread_mutex_unlock(mutex);
  4521. ok = (WAIT_OBJECT_0
  4522. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4523. if (!ok) {
  4524. ok = 1;
  4525. pthread_mutex_lock(&cv->threadIdSec);
  4526. ptls = &cv->waiting_thread;
  4527. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4528. if (*ptls == tls) {
  4529. *ptls = tls->next_waiting_thread;
  4530. ok = 0;
  4531. break;
  4532. }
  4533. }
  4534. pthread_mutex_unlock(&cv->threadIdSec);
  4535. if (ok) {
  4536. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4537. (DWORD)INFINITE);
  4538. }
  4539. }
  4540. /* This thread has been removed from cv's waiting list */
  4541. pthread_mutex_lock(mutex);
  4542. return ok ? 0 : -1;
  4543. }
  4544. FUNCTION_MAY_BE_UNUSED
  4545. static int
  4546. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4547. {
  4548. return pthread_cond_timedwait(cv, mutex, NULL);
  4549. }
  4550. FUNCTION_MAY_BE_UNUSED
  4551. static int
  4552. pthread_cond_signal(pthread_cond_t *cv)
  4553. {
  4554. HANDLE wkup = NULL;
  4555. BOOL ok = FALSE;
  4556. pthread_mutex_lock(&cv->threadIdSec);
  4557. if (cv->waiting_thread) {
  4558. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4559. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4560. ok = SetEvent(wkup);
  4561. DEBUG_ASSERT(ok);
  4562. }
  4563. pthread_mutex_unlock(&cv->threadIdSec);
  4564. return ok ? 0 : 1;
  4565. }
  4566. FUNCTION_MAY_BE_UNUSED
  4567. static int
  4568. pthread_cond_broadcast(pthread_cond_t *cv)
  4569. {
  4570. pthread_mutex_lock(&cv->threadIdSec);
  4571. while (cv->waiting_thread) {
  4572. pthread_cond_signal(cv);
  4573. }
  4574. pthread_mutex_unlock(&cv->threadIdSec);
  4575. return 0;
  4576. }
  4577. FUNCTION_MAY_BE_UNUSED
  4578. static int
  4579. pthread_cond_destroy(pthread_cond_t *cv)
  4580. {
  4581. pthread_mutex_lock(&cv->threadIdSec);
  4582. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4583. pthread_mutex_unlock(&cv->threadIdSec);
  4584. pthread_mutex_destroy(&cv->threadIdSec);
  4585. return 0;
  4586. }
  4587. #if defined(ALTERNATIVE_QUEUE)
  4588. FUNCTION_MAY_BE_UNUSED
  4589. static void *
  4590. event_create(void)
  4591. {
  4592. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4593. }
  4594. FUNCTION_MAY_BE_UNUSED
  4595. static int
  4596. event_wait(void *eventhdl)
  4597. {
  4598. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4599. return (res == WAIT_OBJECT_0);
  4600. }
  4601. FUNCTION_MAY_BE_UNUSED
  4602. static int
  4603. event_signal(void *eventhdl)
  4604. {
  4605. return (int)SetEvent((HANDLE)eventhdl);
  4606. }
  4607. FUNCTION_MAY_BE_UNUSED
  4608. static void
  4609. event_destroy(void *eventhdl)
  4610. {
  4611. CloseHandle((HANDLE)eventhdl);
  4612. }
  4613. #endif
  4614. #if defined(GCC_DIAGNOSTIC)
  4615. /* Enable unused function warning again */
  4616. #pragma GCC diagnostic pop
  4617. #endif
  4618. /* For Windows, change all slashes to backslashes in path names. */
  4619. static void
  4620. change_slashes_to_backslashes(char *path)
  4621. {
  4622. int i;
  4623. for (i = 0; path[i] != '\0'; i++) {
  4624. if (path[i] == '/') {
  4625. path[i] = '\\';
  4626. }
  4627. /* remove double backslash (check i > 0 to preserve UNC paths,
  4628. * like \\server\file.txt) */
  4629. if ((i > 0) && (path[i] == '\\')) {
  4630. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4631. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4632. }
  4633. }
  4634. }
  4635. }
  4636. static int
  4637. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4638. {
  4639. int diff;
  4640. do {
  4641. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4642. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4643. s1++;
  4644. s2++;
  4645. } while ((diff == 0) && (s1[-1] != L'\0'));
  4646. return diff;
  4647. }
  4648. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4649. * wbuf and wbuf_len is a target buffer and its length. */
  4650. static void
  4651. path_to_unicode(const struct mg_connection *conn,
  4652. const char *path,
  4653. wchar_t *wbuf,
  4654. size_t wbuf_len)
  4655. {
  4656. char buf[PATH_MAX], buf2[PATH_MAX];
  4657. wchar_t wbuf2[W_PATH_MAX + 1];
  4658. DWORD long_len, err;
  4659. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4660. mg_strlcpy(buf, path, sizeof(buf));
  4661. change_slashes_to_backslashes(buf);
  4662. /* Convert to Unicode and back. If doubly-converted string does not
  4663. * match the original, something is fishy, reject. */
  4664. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4665. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4666. WideCharToMultiByte(
  4667. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4668. if (strcmp(buf, buf2) != 0) {
  4669. wbuf[0] = L'\0';
  4670. }
  4671. /* Windows file systems are not case sensitive, but you can still use
  4672. * uppercase and lowercase letters (on all modern file systems).
  4673. * The server can check if the URI uses the same upper/lowercase
  4674. * letters an the file system, effectively making Windows servers
  4675. * case sensitive (like Linux servers are). It is still not possible
  4676. * to use two files with the same name in different cases on Windows
  4677. * (like /a and /A) - this would be possible in Linux.
  4678. * As a default, Windows is not case sensitive, but the case sensitive
  4679. * file name check can be activated by an additional configuration. */
  4680. if (conn) {
  4681. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4682. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4683. "yes")) {
  4684. /* Use case sensitive compare function */
  4685. fcompare = wcscmp;
  4686. }
  4687. }
  4688. (void)conn; /* conn is currently unused */
  4689. #if !defined(_WIN32_WCE)
  4690. /* Only accept a full file path, not a Windows short (8.3) path. */
  4691. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4692. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4693. if (long_len == 0) {
  4694. err = GetLastError();
  4695. if (err == ERROR_FILE_NOT_FOUND) {
  4696. /* File does not exist. This is not always a problem here. */
  4697. return;
  4698. }
  4699. }
  4700. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4701. /* Short name is used. */
  4702. wbuf[0] = L'\0';
  4703. }
  4704. #else
  4705. (void)long_len;
  4706. (void)wbuf2;
  4707. (void)err;
  4708. if (strchr(path, '~')) {
  4709. wbuf[0] = L'\0';
  4710. }
  4711. #endif
  4712. }
  4713. #if !defined(NO_FILESYSTEMS)
  4714. /* Get file information, return 1 if file exists, 0 if not */
  4715. static int
  4716. mg_stat(const struct mg_connection *conn,
  4717. const char *path,
  4718. struct mg_file_stat *filep)
  4719. {
  4720. wchar_t wbuf[W_PATH_MAX];
  4721. WIN32_FILE_ATTRIBUTE_DATA info;
  4722. time_t creation_time;
  4723. size_t len;
  4724. if (!filep) {
  4725. return 0;
  4726. }
  4727. memset(filep, 0, sizeof(*filep));
  4728. if (mg_path_suspicious(conn, path)) {
  4729. return 0;
  4730. }
  4731. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4732. /* Windows happily opens files with some garbage at the end of file name.
  4733. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4734. * "a.cgi", despite one would expect an error back. */
  4735. len = strlen(path);
  4736. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4737. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4738. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4739. filep->last_modified =
  4740. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4741. info.ftLastWriteTime.dwHighDateTime);
  4742. /* On Windows, the file creation time can be higher than the
  4743. * modification time, e.g. when a file is copied.
  4744. * Since the Last-Modified timestamp is used for caching
  4745. * it should be based on the most recent timestamp. */
  4746. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4747. info.ftCreationTime.dwHighDateTime);
  4748. if (creation_time > filep->last_modified) {
  4749. filep->last_modified = creation_time;
  4750. }
  4751. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4752. return 1;
  4753. }
  4754. return 0;
  4755. }
  4756. #endif
  4757. static int
  4758. mg_remove(const struct mg_connection *conn, const char *path)
  4759. {
  4760. wchar_t wbuf[W_PATH_MAX];
  4761. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4762. return DeleteFileW(wbuf) ? 0 : -1;
  4763. }
  4764. static int
  4765. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4766. {
  4767. wchar_t wbuf[W_PATH_MAX];
  4768. (void)mode;
  4769. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4770. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4771. }
  4772. /* Create substitutes for POSIX functions in Win32. */
  4773. #if defined(GCC_DIAGNOSTIC)
  4774. /* Show no warning in case system functions are not used. */
  4775. #pragma GCC diagnostic push
  4776. #pragma GCC diagnostic ignored "-Wunused-function"
  4777. #endif
  4778. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4779. FUNCTION_MAY_BE_UNUSED
  4780. static DIR *
  4781. mg_opendir(const struct mg_connection *conn, const char *name)
  4782. {
  4783. DIR *dir = NULL;
  4784. wchar_t wpath[W_PATH_MAX];
  4785. DWORD attrs;
  4786. if (name == NULL) {
  4787. SetLastError(ERROR_BAD_ARGUMENTS);
  4788. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4789. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4790. } else {
  4791. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4792. attrs = GetFileAttributesW(wpath);
  4793. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4794. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4795. (void)wcscat(wpath, L"\\*");
  4796. dir->handle = FindFirstFileW(wpath, &dir->info);
  4797. dir->result.d_name[0] = '\0';
  4798. } else {
  4799. mg_free(dir);
  4800. dir = NULL;
  4801. }
  4802. }
  4803. return dir;
  4804. }
  4805. FUNCTION_MAY_BE_UNUSED
  4806. static int
  4807. mg_closedir(DIR *dir)
  4808. {
  4809. int result = 0;
  4810. if (dir != NULL) {
  4811. if (dir->handle != INVALID_HANDLE_VALUE)
  4812. result = FindClose(dir->handle) ? 0 : -1;
  4813. mg_free(dir);
  4814. } else {
  4815. result = -1;
  4816. SetLastError(ERROR_BAD_ARGUMENTS);
  4817. }
  4818. return result;
  4819. }
  4820. FUNCTION_MAY_BE_UNUSED
  4821. static struct dirent *
  4822. mg_readdir(DIR *dir)
  4823. {
  4824. struct dirent *result = 0;
  4825. if (dir) {
  4826. if (dir->handle != INVALID_HANDLE_VALUE) {
  4827. result = &dir->result;
  4828. (void)WideCharToMultiByte(CP_UTF8,
  4829. 0,
  4830. dir->info.cFileName,
  4831. -1,
  4832. result->d_name,
  4833. sizeof(result->d_name),
  4834. NULL,
  4835. NULL);
  4836. if (!FindNextFileW(dir->handle, &dir->info)) {
  4837. (void)FindClose(dir->handle);
  4838. dir->handle = INVALID_HANDLE_VALUE;
  4839. }
  4840. } else {
  4841. SetLastError(ERROR_FILE_NOT_FOUND);
  4842. }
  4843. } else {
  4844. SetLastError(ERROR_BAD_ARGUMENTS);
  4845. }
  4846. return result;
  4847. }
  4848. #if !defined(HAVE_POLL)
  4849. #undef POLLIN
  4850. #undef POLLPRI
  4851. #undef POLLOUT
  4852. #define POLLIN (1) /* Data ready - read will not block. */
  4853. #define POLLPRI (2) /* Priority data ready. */
  4854. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4855. FUNCTION_MAY_BE_UNUSED
  4856. static int
  4857. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4858. {
  4859. struct timeval tv;
  4860. fd_set rset;
  4861. fd_set wset;
  4862. unsigned int i;
  4863. int result;
  4864. SOCKET maxfd = 0;
  4865. memset(&tv, 0, sizeof(tv));
  4866. tv.tv_sec = milliseconds / 1000;
  4867. tv.tv_usec = (milliseconds % 1000) * 1000;
  4868. FD_ZERO(&rset);
  4869. FD_ZERO(&wset);
  4870. for (i = 0; i < n; i++) {
  4871. if (pfd[i].events & POLLIN) {
  4872. FD_SET(pfd[i].fd, &rset);
  4873. }
  4874. if (pfd[i].events & POLLOUT) {
  4875. FD_SET(pfd[i].fd, &wset);
  4876. }
  4877. pfd[i].revents = 0;
  4878. if (pfd[i].fd > maxfd) {
  4879. maxfd = pfd[i].fd;
  4880. }
  4881. }
  4882. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4883. for (i = 0; i < n; i++) {
  4884. if (FD_ISSET(pfd[i].fd, &rset)) {
  4885. pfd[i].revents |= POLLIN;
  4886. }
  4887. if (FD_ISSET(pfd[i].fd, &wset)) {
  4888. pfd[i].revents |= POLLOUT;
  4889. }
  4890. }
  4891. }
  4892. /* We should subtract the time used in select from remaining
  4893. * "milliseconds", in particular if called from mg_poll with a
  4894. * timeout quantum.
  4895. * Unfortunately, the remaining time is not stored in "tv" in all
  4896. * implementations, so the result in "tv" must be considered undefined.
  4897. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4898. return result;
  4899. }
  4900. #endif /* HAVE_POLL */
  4901. #if defined(GCC_DIAGNOSTIC)
  4902. /* Enable unused function warning again */
  4903. #pragma GCC diagnostic pop
  4904. #endif
  4905. static void
  4906. set_close_on_exec(SOCKET sock,
  4907. const struct mg_connection *conn /* may be null */,
  4908. struct mg_context *ctx /* may be null */)
  4909. {
  4910. (void)conn; /* Unused. */
  4911. (void)ctx;
  4912. #if defined(_WIN32_WCE)
  4913. (void)sock;
  4914. #else
  4915. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4916. #endif
  4917. }
  4918. int
  4919. mg_start_thread(mg_thread_func_t f, void *p)
  4920. {
  4921. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4922. /* Compile-time option to control stack size, e.g.
  4923. * -DUSE_STACK_SIZE=16384
  4924. */
  4925. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4926. == ((uintptr_t)(-1L)))
  4927. ? -1
  4928. : 0);
  4929. #else
  4930. return (
  4931. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4932. ? -1
  4933. : 0);
  4934. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4935. }
  4936. /* Start a thread storing the thread context. */
  4937. static int
  4938. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4939. void *p,
  4940. pthread_t *threadidptr)
  4941. {
  4942. uintptr_t uip;
  4943. HANDLE threadhandle;
  4944. int result = -1;
  4945. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4946. threadhandle = (HANDLE)uip;
  4947. if ((uip != 0) && (threadidptr != NULL)) {
  4948. *threadidptr = threadhandle;
  4949. result = 0;
  4950. }
  4951. return result;
  4952. }
  4953. /* Wait for a thread to finish. */
  4954. static int
  4955. mg_join_thread(pthread_t threadid)
  4956. {
  4957. int result;
  4958. DWORD dwevent;
  4959. result = -1;
  4960. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4961. if (dwevent == WAIT_FAILED) {
  4962. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4963. } else {
  4964. if (dwevent == WAIT_OBJECT_0) {
  4965. CloseHandle(threadid);
  4966. result = 0;
  4967. }
  4968. }
  4969. return result;
  4970. }
  4971. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4972. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4973. /* Create substitutes for POSIX functions in Win32. */
  4974. #if defined(GCC_DIAGNOSTIC)
  4975. /* Show no warning in case system functions are not used. */
  4976. #pragma GCC diagnostic push
  4977. #pragma GCC diagnostic ignored "-Wunused-function"
  4978. #endif
  4979. FUNCTION_MAY_BE_UNUSED
  4980. static HANDLE
  4981. dlopen(const char *dll_name, int flags)
  4982. {
  4983. wchar_t wbuf[W_PATH_MAX];
  4984. (void)flags;
  4985. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4986. return LoadLibraryW(wbuf);
  4987. }
  4988. FUNCTION_MAY_BE_UNUSED
  4989. static int
  4990. dlclose(void *handle)
  4991. {
  4992. int result;
  4993. if (FreeLibrary((HMODULE)handle) != 0) {
  4994. result = 0;
  4995. } else {
  4996. result = -1;
  4997. }
  4998. return result;
  4999. }
  5000. #if defined(GCC_DIAGNOSTIC)
  5001. /* Enable unused function warning again */
  5002. #pragma GCC diagnostic pop
  5003. #endif
  5004. #endif
  5005. #if !defined(NO_CGI)
  5006. #define SIGKILL (0)
  5007. static int
  5008. kill(pid_t pid, int sig_num)
  5009. {
  5010. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  5011. (void)CloseHandle((HANDLE)pid);
  5012. return 0;
  5013. }
  5014. #if !defined(WNOHANG)
  5015. #define WNOHANG (1)
  5016. #endif
  5017. static pid_t
  5018. waitpid(pid_t pid, int *status, int flags)
  5019. {
  5020. DWORD timeout = INFINITE;
  5021. DWORD waitres;
  5022. (void)status; /* Currently not used by any client here */
  5023. if ((flags | WNOHANG) == WNOHANG) {
  5024. timeout = 0;
  5025. }
  5026. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  5027. if (waitres == WAIT_OBJECT_0) {
  5028. return pid;
  5029. }
  5030. if (waitres == WAIT_TIMEOUT) {
  5031. return 0;
  5032. }
  5033. return (pid_t)-1;
  5034. }
  5035. static void
  5036. trim_trailing_whitespaces(char *s)
  5037. {
  5038. char *e = s + strlen(s);
  5039. while ((e > s) && isspace((unsigned char)e[-1])) {
  5040. *(--e) = '\0';
  5041. }
  5042. }
  5043. static pid_t
  5044. spawn_process(struct mg_connection *conn,
  5045. const char *prog,
  5046. char *envblk,
  5047. char *envp[],
  5048. int fdin[2],
  5049. int fdout[2],
  5050. int fderr[2],
  5051. const char *dir)
  5052. {
  5053. HANDLE me;
  5054. char *interp;
  5055. char *interp_arg = 0;
  5056. char full_dir[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX];
  5057. int truncated;
  5058. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5059. STARTUPINFOA si;
  5060. PROCESS_INFORMATION pi = {0};
  5061. (void)envp;
  5062. memset(&si, 0, sizeof(si));
  5063. si.cb = sizeof(si);
  5064. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5065. si.wShowWindow = SW_HIDE;
  5066. me = GetCurrentProcess();
  5067. DuplicateHandle(me,
  5068. (HANDLE)_get_osfhandle(fdin[0]),
  5069. me,
  5070. &si.hStdInput,
  5071. 0,
  5072. TRUE,
  5073. DUPLICATE_SAME_ACCESS);
  5074. DuplicateHandle(me,
  5075. (HANDLE)_get_osfhandle(fdout[1]),
  5076. me,
  5077. &si.hStdOutput,
  5078. 0,
  5079. TRUE,
  5080. DUPLICATE_SAME_ACCESS);
  5081. DuplicateHandle(me,
  5082. (HANDLE)_get_osfhandle(fderr[1]),
  5083. me,
  5084. &si.hStdError,
  5085. 0,
  5086. TRUE,
  5087. DUPLICATE_SAME_ACCESS);
  5088. /* Mark handles that should not be inherited. See
  5089. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5090. */
  5091. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5092. HANDLE_FLAG_INHERIT,
  5093. 0);
  5094. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5095. HANDLE_FLAG_INHERIT,
  5096. 0);
  5097. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5098. HANDLE_FLAG_INHERIT,
  5099. 0);
  5100. /* First check, if there is a CGI interpreter configured for all CGI
  5101. * scripts. */
  5102. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5103. if (interp != NULL) {
  5104. /* If there is a configured interpreter, check for additional arguments
  5105. */
  5106. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5107. } else {
  5108. /* Otherwise, the interpreter must be stated in the first line of the
  5109. * CGI script file, after a #! (shebang) mark. */
  5110. buf[0] = buf[1] = '\0';
  5111. /* Get the full script path */
  5112. mg_snprintf(
  5113. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5114. if (truncated) {
  5115. pi.hProcess = (pid_t)-1;
  5116. goto spawn_cleanup;
  5117. }
  5118. /* Open the script file, to read the first line */
  5119. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5120. /* Read the first line of the script into the buffer */
  5121. mg_fgets(buf, sizeof(buf), &file);
  5122. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5123. buf[sizeof(buf) - 1] = '\0';
  5124. }
  5125. if ((buf[0] == '#') && (buf[1] == '!')) {
  5126. trim_trailing_whitespaces(buf + 2);
  5127. } else {
  5128. buf[2] = '\0';
  5129. }
  5130. interp = buf + 2;
  5131. }
  5132. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5133. if (interp[0] != '\0') {
  5134. /* This is an interpreted script file. We must call the interpreter. */
  5135. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5136. mg_snprintf(conn,
  5137. &truncated,
  5138. cmdline,
  5139. sizeof(cmdline),
  5140. "\"%s\" %s \"%s\\%s\"",
  5141. interp,
  5142. interp_arg,
  5143. full_dir,
  5144. prog);
  5145. } else {
  5146. mg_snprintf(conn,
  5147. &truncated,
  5148. cmdline,
  5149. sizeof(cmdline),
  5150. "\"%s\" \"%s\\%s\"",
  5151. interp,
  5152. full_dir,
  5153. prog);
  5154. }
  5155. } else {
  5156. /* This is (probably) a compiled program. We call it directly. */
  5157. mg_snprintf(conn,
  5158. &truncated,
  5159. cmdline,
  5160. sizeof(cmdline),
  5161. "\"%s\\%s\"",
  5162. full_dir,
  5163. prog);
  5164. }
  5165. if (truncated) {
  5166. pi.hProcess = (pid_t)-1;
  5167. goto spawn_cleanup;
  5168. }
  5169. DEBUG_TRACE("Running [%s]", cmdline);
  5170. if (CreateProcessA(NULL,
  5171. cmdline,
  5172. NULL,
  5173. NULL,
  5174. TRUE,
  5175. CREATE_NEW_PROCESS_GROUP,
  5176. envblk,
  5177. NULL,
  5178. &si,
  5179. &pi)
  5180. == 0) {
  5181. mg_cry_internal(
  5182. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5183. pi.hProcess = (pid_t)-1;
  5184. /* goto spawn_cleanup; */
  5185. }
  5186. spawn_cleanup:
  5187. (void)CloseHandle(si.hStdOutput);
  5188. (void)CloseHandle(si.hStdError);
  5189. (void)CloseHandle(si.hStdInput);
  5190. if (pi.hThread != NULL) {
  5191. (void)CloseHandle(pi.hThread);
  5192. }
  5193. return (pid_t)pi.hProcess;
  5194. }
  5195. #endif /* !NO_CGI */
  5196. static int
  5197. set_blocking_mode(SOCKET sock)
  5198. {
  5199. unsigned long non_blocking = 0;
  5200. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5201. }
  5202. static int
  5203. set_non_blocking_mode(SOCKET sock)
  5204. {
  5205. unsigned long non_blocking = 1;
  5206. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5207. }
  5208. #else
  5209. #if !defined(NO_FILESYSTEMS)
  5210. static int
  5211. mg_stat(const struct mg_connection *conn,
  5212. const char *path,
  5213. struct mg_file_stat *filep)
  5214. {
  5215. struct stat st;
  5216. if (!filep) {
  5217. return 0;
  5218. }
  5219. memset(filep, 0, sizeof(*filep));
  5220. if (mg_path_suspicious(conn, path)) {
  5221. return 0;
  5222. }
  5223. if (0 == stat(path, &st)) {
  5224. filep->size = (uint64_t)(st.st_size);
  5225. filep->last_modified = st.st_mtime;
  5226. filep->is_directory = S_ISDIR(st.st_mode);
  5227. return 1;
  5228. }
  5229. return 0;
  5230. }
  5231. #endif /* NO_FILESYSTEMS */
  5232. static void
  5233. set_close_on_exec(int fd,
  5234. const struct mg_connection *conn /* may be null */,
  5235. struct mg_context *ctx /* may be null */)
  5236. {
  5237. #if defined(__ZEPHYR__)
  5238. (void)fd;
  5239. (void)conn;
  5240. (void)ctx;
  5241. #else
  5242. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5243. if (conn || ctx) {
  5244. struct mg_connection fc;
  5245. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5246. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5247. __func__,
  5248. strerror(ERRNO));
  5249. }
  5250. }
  5251. #endif
  5252. }
  5253. int
  5254. mg_start_thread(mg_thread_func_t func, void *param)
  5255. {
  5256. pthread_t thread_id;
  5257. pthread_attr_t attr;
  5258. int result;
  5259. (void)pthread_attr_init(&attr);
  5260. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5261. #if defined(__ZEPHYR__)
  5262. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5263. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5264. /* Compile-time option to control stack size,
  5265. * e.g. -DUSE_STACK_SIZE=16384 */
  5266. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5267. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5268. result = pthread_create(&thread_id, &attr, func, param);
  5269. pthread_attr_destroy(&attr);
  5270. return result;
  5271. }
  5272. /* Start a thread storing the thread context. */
  5273. static int
  5274. mg_start_thread_with_id(mg_thread_func_t func,
  5275. void *param,
  5276. pthread_t *threadidptr)
  5277. {
  5278. pthread_t thread_id;
  5279. pthread_attr_t attr;
  5280. int result;
  5281. (void)pthread_attr_init(&attr);
  5282. #if defined(__ZEPHYR__)
  5283. pthread_attr_setstack(&attr,
  5284. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5285. ZEPHYR_STACK_SIZE);
  5286. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5287. /* Compile-time option to control stack size,
  5288. * e.g. -DUSE_STACK_SIZE=16384 */
  5289. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5290. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5291. result = pthread_create(&thread_id, &attr, func, param);
  5292. pthread_attr_destroy(&attr);
  5293. if ((result == 0) && (threadidptr != NULL)) {
  5294. *threadidptr = thread_id;
  5295. }
  5296. return result;
  5297. }
  5298. /* Wait for a thread to finish. */
  5299. static int
  5300. mg_join_thread(pthread_t threadid)
  5301. {
  5302. int result;
  5303. result = pthread_join(threadid, NULL);
  5304. return result;
  5305. }
  5306. #if !defined(NO_CGI)
  5307. static pid_t
  5308. spawn_process(struct mg_connection *conn,
  5309. const char *prog,
  5310. char *envblk,
  5311. char *envp[],
  5312. int fdin[2],
  5313. int fdout[2],
  5314. int fderr[2],
  5315. const char *dir)
  5316. {
  5317. pid_t pid;
  5318. const char *interp;
  5319. (void)envblk;
  5320. if ((pid = fork()) == -1) {
  5321. /* Parent */
  5322. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5323. } else if (pid != 0) {
  5324. /* Make sure children close parent-side descriptors.
  5325. * The caller will close the child-side immediately. */
  5326. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5327. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5328. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5329. } else {
  5330. /* Child */
  5331. if (chdir(dir) != 0) {
  5332. mg_cry_internal(
  5333. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5334. } else if (dup2(fdin[0], 0) == -1) {
  5335. mg_cry_internal(conn,
  5336. "%s: dup2(%d, 0): %s",
  5337. __func__,
  5338. fdin[0],
  5339. strerror(ERRNO));
  5340. } else if (dup2(fdout[1], 1) == -1) {
  5341. mg_cry_internal(conn,
  5342. "%s: dup2(%d, 1): %s",
  5343. __func__,
  5344. fdout[1],
  5345. strerror(ERRNO));
  5346. } else if (dup2(fderr[1], 2) == -1) {
  5347. mg_cry_internal(conn,
  5348. "%s: dup2(%d, 2): %s",
  5349. __func__,
  5350. fderr[1],
  5351. strerror(ERRNO));
  5352. } else {
  5353. struct sigaction sa;
  5354. /* Keep stderr and stdout in two different pipes.
  5355. * Stdout will be sent back to the client,
  5356. * stderr should go into a server error log. */
  5357. (void)close(fdin[0]);
  5358. (void)close(fdout[1]);
  5359. (void)close(fderr[1]);
  5360. /* Close write end fdin and read end fdout and fderr */
  5361. (void)close(fdin[1]);
  5362. (void)close(fdout[0]);
  5363. (void)close(fderr[0]);
  5364. /* After exec, all signal handlers are restored to their default
  5365. * values, with one exception of SIGCHLD. According to
  5366. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5367. * will leave unchanged after exec if it was set to be ignored.
  5368. * Restore it to default action. */
  5369. memset(&sa, 0, sizeof(sa));
  5370. sa.sa_handler = SIG_DFL;
  5371. sigaction(SIGCHLD, &sa, NULL);
  5372. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5373. if (interp == NULL) {
  5374. /* no interpreter configured, call the programm directly */
  5375. (void)execle(prog, prog, NULL, envp);
  5376. mg_cry_internal(conn,
  5377. "%s: execle(%s): %s",
  5378. __func__,
  5379. prog,
  5380. strerror(ERRNO));
  5381. } else {
  5382. /* call the configured interpreter */
  5383. const char *interp_args =
  5384. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5385. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5386. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5387. } else {
  5388. (void)execle(interp, interp, prog, NULL, envp);
  5389. }
  5390. mg_cry_internal(conn,
  5391. "%s: execle(%s %s): %s",
  5392. __func__,
  5393. interp,
  5394. prog,
  5395. strerror(ERRNO));
  5396. }
  5397. }
  5398. exit(EXIT_FAILURE);
  5399. }
  5400. return pid;
  5401. }
  5402. #endif /* !NO_CGI */
  5403. static int
  5404. set_non_blocking_mode(SOCKET sock)
  5405. {
  5406. int flags = fcntl(sock, F_GETFL, 0);
  5407. if (flags < 0) {
  5408. return -1;
  5409. }
  5410. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5411. return -1;
  5412. }
  5413. return 0;
  5414. }
  5415. static int
  5416. set_blocking_mode(SOCKET sock)
  5417. {
  5418. int flags = fcntl(sock, F_GETFL, 0);
  5419. if (flags < 0) {
  5420. return -1;
  5421. }
  5422. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5423. return -1;
  5424. }
  5425. return 0;
  5426. }
  5427. #endif /* _WIN32 / else */
  5428. /* End of initial operating system specific define block. */
  5429. /* Get a random number (independent of C rand function) */
  5430. static uint64_t
  5431. get_random(void)
  5432. {
  5433. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5434. static uint64_t lcg = 0; /* Linear congruential generator */
  5435. uint64_t now = mg_get_current_time_ns();
  5436. if (lfsr == 0) {
  5437. /* lfsr will be only 0 if has not been initialized,
  5438. * so this code is called only once. */
  5439. lfsr = mg_get_current_time_ns();
  5440. lcg = mg_get_current_time_ns();
  5441. } else {
  5442. /* Get the next step of both random number generators. */
  5443. lfsr = (lfsr >> 1)
  5444. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5445. << 63);
  5446. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5447. }
  5448. /* Combining two pseudo-random number generators and a high resolution
  5449. * part
  5450. * of the current server time will make it hard (impossible?) to guess
  5451. * the
  5452. * next number. */
  5453. return (lfsr ^ lcg ^ now);
  5454. }
  5455. static int
  5456. mg_poll(struct mg_pollfd *pfd,
  5457. unsigned int n,
  5458. int milliseconds,
  5459. stop_flag_t *stop_flag)
  5460. {
  5461. /* Call poll, but only for a maximum time of a few seconds.
  5462. * This will allow to stop the server after some seconds, instead
  5463. * of having to wait for a long socket timeout. */
  5464. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5465. do {
  5466. int result;
  5467. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5468. /* Shut down signal */
  5469. return -2;
  5470. }
  5471. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5472. ms_now = milliseconds;
  5473. }
  5474. result = poll(pfd, n, ms_now);
  5475. if (result != 0) {
  5476. /* Poll returned either success (1) or error (-1).
  5477. * Forward both to the caller. */
  5478. return result;
  5479. }
  5480. /* Poll returned timeout (0). */
  5481. if (milliseconds > 0) {
  5482. milliseconds -= ms_now;
  5483. }
  5484. } while (milliseconds > 0);
  5485. /* timeout: return 0 */
  5486. return 0;
  5487. }
  5488. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5489. * descriptor.
  5490. * Return value:
  5491. * >=0 .. number of bytes successfully written
  5492. * -1 .. timeout
  5493. * -2 .. error
  5494. */
  5495. static int
  5496. push_inner(struct mg_context *ctx,
  5497. FILE *fp,
  5498. SOCKET sock,
  5499. SSL *ssl,
  5500. const char *buf,
  5501. int len,
  5502. double timeout)
  5503. {
  5504. uint64_t start = 0, now = 0, timeout_ns = 0;
  5505. int n, err;
  5506. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5507. #if defined(_WIN32)
  5508. typedef int len_t;
  5509. #else
  5510. typedef size_t len_t;
  5511. #endif
  5512. if (timeout > 0) {
  5513. now = mg_get_current_time_ns();
  5514. start = now;
  5515. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5516. }
  5517. if (ctx == NULL) {
  5518. return -2;
  5519. }
  5520. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5521. if (ssl) {
  5522. return -2;
  5523. }
  5524. #endif
  5525. /* Try to read until it succeeds, fails, times out, or the server
  5526. * shuts down. */
  5527. for (;;) {
  5528. #if !defined(NO_SSL)
  5529. if (ssl != NULL) {
  5530. ERR_clear_error();
  5531. n = SSL_write(ssl, buf, len);
  5532. if (n <= 0) {
  5533. err = SSL_get_error(ssl, n);
  5534. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5535. err = ERRNO;
  5536. } else if ((err == SSL_ERROR_WANT_READ)
  5537. || (err == SSL_ERROR_WANT_WRITE)) {
  5538. n = 0;
  5539. } else {
  5540. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5541. ERR_clear_error();
  5542. return -2;
  5543. }
  5544. ERR_clear_error();
  5545. } else {
  5546. err = 0;
  5547. }
  5548. } else
  5549. #endif
  5550. #if defined(USE_MBEDTLS)
  5551. if (ssl != NULL) {
  5552. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5553. if (n <= 0) {
  5554. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5555. || (n == MBEDTLS_ERR_SSL_WANT_WRITE) || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5556. n = 0;
  5557. } else {
  5558. fprintf(stderr, "SSL write failed, error %d\n", n);
  5559. return -2;
  5560. }
  5561. } else {
  5562. err = 0;
  5563. }
  5564. } else
  5565. #endif
  5566. if (fp != NULL) {
  5567. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5568. if (ferror(fp)) {
  5569. n = -1;
  5570. err = ERRNO;
  5571. } else {
  5572. err = 0;
  5573. }
  5574. } else {
  5575. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5576. err = (n < 0) ? ERRNO : 0;
  5577. #if defined(_WIN32)
  5578. if (err == WSAEWOULDBLOCK) {
  5579. err = 0;
  5580. n = 0;
  5581. }
  5582. #else
  5583. if (ERROR_TRY_AGAIN(err)) {
  5584. err = 0;
  5585. n = 0;
  5586. }
  5587. #endif
  5588. if (n < 0) {
  5589. /* shutdown of the socket at client side */
  5590. return -2;
  5591. }
  5592. }
  5593. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5594. return -2;
  5595. }
  5596. if ((n > 0) || ((n == 0) && (len == 0))) {
  5597. /* some data has been read, or no data was requested */
  5598. return n;
  5599. }
  5600. if (n < 0) {
  5601. /* socket error - check errno */
  5602. DEBUG_TRACE("send() failed, error %d", err);
  5603. /* TODO (mid): error handling depending on the error code.
  5604. * These codes are different between Windows and Linux.
  5605. * Currently there is no problem with failing send calls,
  5606. * if there is a reproducible situation, it should be
  5607. * investigated in detail.
  5608. */
  5609. return -2;
  5610. }
  5611. /* Only in case n=0 (timeout), repeat calling the write function */
  5612. /* If send failed, wait before retry */
  5613. if (fp != NULL) {
  5614. /* For files, just wait a fixed time.
  5615. * Maybe it helps, maybe not. */
  5616. mg_sleep(5);
  5617. } else {
  5618. /* For sockets, wait for the socket using poll */
  5619. struct mg_pollfd pfd[1];
  5620. int pollres;
  5621. pfd[0].fd = sock;
  5622. pfd[0].events = POLLOUT;
  5623. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5624. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5625. return -2;
  5626. }
  5627. if (pollres > 0) {
  5628. continue;
  5629. }
  5630. }
  5631. if (timeout > 0) {
  5632. now = mg_get_current_time_ns();
  5633. if ((now - start) > timeout_ns) {
  5634. /* Timeout */
  5635. break;
  5636. }
  5637. }
  5638. }
  5639. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5640. used */
  5641. return -1;
  5642. }
  5643. static int
  5644. push_all(struct mg_context *ctx,
  5645. FILE *fp,
  5646. SOCKET sock,
  5647. SSL *ssl,
  5648. const char *buf,
  5649. int len)
  5650. {
  5651. double timeout = -1.0;
  5652. int n, nwritten = 0;
  5653. if (ctx == NULL) {
  5654. return -1;
  5655. }
  5656. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5657. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5658. }
  5659. if (timeout <= 0.0) {
  5660. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5661. }
  5662. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5663. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5664. if (n < 0) {
  5665. if (nwritten == 0) {
  5666. nwritten = -1; /* Propagate the error */
  5667. }
  5668. break;
  5669. } else if (n == 0) {
  5670. break; /* No more data to write */
  5671. } else {
  5672. nwritten += n;
  5673. len -= n;
  5674. }
  5675. }
  5676. return nwritten;
  5677. }
  5678. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5679. * Return value:
  5680. * >=0 .. number of bytes successfully read
  5681. * -1 .. timeout
  5682. * -2 .. error
  5683. */
  5684. static int
  5685. pull_inner(FILE *fp,
  5686. struct mg_connection *conn,
  5687. char *buf,
  5688. int len,
  5689. double timeout)
  5690. {
  5691. int nread, err = 0;
  5692. #if defined(_WIN32)
  5693. typedef int len_t;
  5694. #else
  5695. typedef size_t len_t;
  5696. #endif
  5697. /* We need an additional wait loop around this, because in some cases
  5698. * with TLSwe may get data from the socket but not from SSL_read.
  5699. * In this case we need to repeat at least once.
  5700. */
  5701. if (fp != NULL) {
  5702. #if !defined(_WIN32_WCE)
  5703. /* Use read() instead of fread(), because if we're reading from the
  5704. * CGI pipe, fread() may block until IO buffer is filled up. We
  5705. * cannot afford to block and must pass all read bytes immediately
  5706. * to the client. */
  5707. nread = (int)read(fileno(fp), buf, (size_t)len);
  5708. #else
  5709. /* WinCE does not support CGI pipes */
  5710. nread = (int)fread(buf, 1, (size_t)len, fp);
  5711. #endif
  5712. err = (nread < 0) ? ERRNO : 0;
  5713. if ((nread == 0) && (len > 0)) {
  5714. /* Should get data, but got EOL */
  5715. return -2;
  5716. }
  5717. #if !defined(NO_SSL)
  5718. } else if (conn->ssl != NULL) {
  5719. int ssl_pending;
  5720. struct mg_pollfd pfd[1];
  5721. int pollres;
  5722. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5723. /* We already know there is no more data buffered in conn->buf
  5724. * but there is more available in the SSL layer. So don't poll
  5725. * conn->client.sock yet. */
  5726. if (ssl_pending > len) {
  5727. ssl_pending = len;
  5728. }
  5729. pollres = 1;
  5730. } else {
  5731. pfd[0].fd = conn->client.sock;
  5732. pfd[0].events = POLLIN;
  5733. pollres = mg_poll(pfd,
  5734. 1,
  5735. (int)(timeout * 1000.0),
  5736. &(conn->phys_ctx->stop_flag));
  5737. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5738. return -2;
  5739. }
  5740. }
  5741. if (pollres > 0) {
  5742. ERR_clear_error();
  5743. nread =
  5744. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5745. if (nread <= 0) {
  5746. err = SSL_get_error(conn->ssl, nread);
  5747. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5748. err = ERRNO;
  5749. } else if ((err == SSL_ERROR_WANT_READ)
  5750. || (err == SSL_ERROR_WANT_WRITE)) {
  5751. nread = 0;
  5752. } else {
  5753. /* All errors should return -2 */
  5754. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5755. ERR_clear_error();
  5756. return -2;
  5757. }
  5758. ERR_clear_error();
  5759. } else {
  5760. err = 0;
  5761. }
  5762. } else if (pollres < 0) {
  5763. /* Error */
  5764. return -2;
  5765. } else {
  5766. /* pollres = 0 means timeout */
  5767. nread = 0;
  5768. }
  5769. #endif
  5770. #if defined(USE_MBEDTLS)
  5771. } else if (conn->ssl != NULL) {
  5772. /* We already know there is no more data buffered in conn->buf
  5773. * but there is more available in the SSL layer. So don't poll
  5774. * conn->client.sock yet. */
  5775. struct pollfd pfd[1];
  5776. int pollres;
  5777. pfd[0].fd = conn->client.sock;
  5778. pfd[0].events = POLLIN;
  5779. pollres = mg_poll(pfd,
  5780. 1,
  5781. (int)(timeout * 1000.0),
  5782. &(conn->phys_ctx->stop_flag));
  5783. if (conn->phys_ctx->stop_flag) {
  5784. return -2;
  5785. }
  5786. if (pollres > 0) {
  5787. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, len);
  5788. if (nread <= 0) {
  5789. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5790. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)|| nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5791. nread = 0;
  5792. } else {
  5793. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5794. return -2;
  5795. }
  5796. } else {
  5797. err = 0;
  5798. }
  5799. } else if (pollres < 0) {
  5800. /* Error */
  5801. return -2;
  5802. } else {
  5803. /* pollres = 0 means timeout */
  5804. nread = 0;
  5805. }
  5806. #endif
  5807. } else {
  5808. struct mg_pollfd pfd[1];
  5809. int pollres;
  5810. pfd[0].fd = conn->client.sock;
  5811. pfd[0].events = POLLIN;
  5812. pollres = mg_poll(pfd,
  5813. 1,
  5814. (int)(timeout * 1000.0),
  5815. &(conn->phys_ctx->stop_flag));
  5816. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5817. return -2;
  5818. }
  5819. if (pollres > 0) {
  5820. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5821. err = (nread < 0) ? ERRNO : 0;
  5822. if (nread <= 0) {
  5823. /* shutdown of the socket at client side */
  5824. return -2;
  5825. }
  5826. } else if (pollres < 0) {
  5827. /* error callint poll */
  5828. return -2;
  5829. } else {
  5830. /* pollres = 0 means timeout */
  5831. nread = 0;
  5832. }
  5833. }
  5834. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5835. return -2;
  5836. }
  5837. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5838. /* some data has been read, or no data was requested */
  5839. return nread;
  5840. }
  5841. if (nread < 0) {
  5842. /* socket error - check errno */
  5843. #if defined(_WIN32)
  5844. if (err == WSAEWOULDBLOCK) {
  5845. /* TODO (low): check if this is still required */
  5846. /* standard case if called from close_socket_gracefully */
  5847. return -2;
  5848. } else if (err == WSAETIMEDOUT) {
  5849. /* TODO (low): check if this is still required */
  5850. /* timeout is handled by the while loop */
  5851. return 0;
  5852. } else if (err == WSAECONNABORTED) {
  5853. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5854. return -2;
  5855. } else {
  5856. DEBUG_TRACE("recv() failed, error %d", err);
  5857. return -2;
  5858. }
  5859. #else
  5860. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5861. * if the timeout is reached and if the socket was set to non-
  5862. * blocking in close_socket_gracefully, so we can not distinguish
  5863. * here. We have to wait for the timeout in both cases for now.
  5864. */
  5865. if (ERROR_TRY_AGAIN(err)) {
  5866. /* TODO (low): check if this is still required */
  5867. /* EAGAIN/EWOULDBLOCK:
  5868. * standard case if called from close_socket_gracefully
  5869. * => should return -1 */
  5870. /* or timeout occurred
  5871. * => the code must stay in the while loop */
  5872. /* EINTR can be generated on a socket with a timeout set even
  5873. * when SA_RESTART is effective for all relevant signals
  5874. * (see signal(7)).
  5875. * => stay in the while loop */
  5876. } else {
  5877. DEBUG_TRACE("recv() failed, error %d", err);
  5878. return -2;
  5879. }
  5880. #endif
  5881. }
  5882. /* Timeout occurred, but no data available. */
  5883. return -1;
  5884. }
  5885. static int
  5886. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5887. {
  5888. int n, nread = 0;
  5889. double timeout = -1.0;
  5890. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5891. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5892. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5893. }
  5894. if (timeout <= 0.0) {
  5895. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5896. }
  5897. start_time = mg_get_current_time_ns();
  5898. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5899. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5900. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5901. if (n == -2) {
  5902. if (nread == 0) {
  5903. nread = -1; /* Propagate the error */
  5904. }
  5905. break;
  5906. } else if (n == -1) {
  5907. /* timeout */
  5908. if (timeout >= 0.0) {
  5909. now = mg_get_current_time_ns();
  5910. if ((now - start_time) <= timeout_ns) {
  5911. continue;
  5912. }
  5913. }
  5914. break;
  5915. } else if (n == 0) {
  5916. break; /* No more data to read */
  5917. } else {
  5918. nread += n;
  5919. len -= n;
  5920. }
  5921. }
  5922. return nread;
  5923. }
  5924. static void
  5925. discard_unread_request_data(struct mg_connection *conn)
  5926. {
  5927. char buf[MG_BUF_LEN];
  5928. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5929. ;
  5930. }
  5931. static int
  5932. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5933. {
  5934. int64_t content_len, n, buffered_len, nread;
  5935. int64_t len64 =
  5936. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5937. * int, we may not read more
  5938. * bytes */
  5939. const char *body;
  5940. if (conn == NULL) {
  5941. return 0;
  5942. }
  5943. /* If Content-Length is not set for a response with body data,
  5944. * we do not know in advance how much data should be read. */
  5945. content_len = conn->content_len;
  5946. if (content_len < 0) {
  5947. /* The body data is completed when the connection is closed. */
  5948. content_len = INT64_MAX;
  5949. }
  5950. nread = 0;
  5951. if (conn->consumed_content < content_len) {
  5952. /* Adjust number of bytes to read. */
  5953. int64_t left_to_read = content_len - conn->consumed_content;
  5954. if (left_to_read < len64) {
  5955. /* Do not read more than the total content length of the
  5956. * request.
  5957. */
  5958. len64 = left_to_read;
  5959. }
  5960. /* Return buffered data */
  5961. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5962. - conn->consumed_content;
  5963. if (buffered_len > 0) {
  5964. if (len64 < buffered_len) {
  5965. buffered_len = len64;
  5966. }
  5967. body = conn->buf + conn->request_len + conn->consumed_content;
  5968. memcpy(buf, body, (size_t)buffered_len);
  5969. len64 -= buffered_len;
  5970. conn->consumed_content += buffered_len;
  5971. nread += buffered_len;
  5972. buf = (char *)buf + buffered_len;
  5973. }
  5974. /* We have returned all buffered data. Read new data from the remote
  5975. * socket.
  5976. */
  5977. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5978. conn->consumed_content += n;
  5979. nread += n;
  5980. } else {
  5981. nread = ((nread > 0) ? nread : n);
  5982. }
  5983. }
  5984. return (int)nread;
  5985. }
  5986. /* Forward declarations */
  5987. static void handle_request(struct mg_connection *);
  5988. #if defined(USE_HTTP2)
  5989. #if defined(NO_SSL)
  5990. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5991. #endif
  5992. #define USE_ALPN
  5993. #include "mod_http2.inl"
  5994. /* Not supported with HTTP/2 */
  5995. #define HTTP1_only \
  5996. { \
  5997. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5998. http2_must_use_http1(conn); \
  5999. return; \
  6000. } \
  6001. }
  6002. #else
  6003. #define HTTP1_only
  6004. #endif
  6005. int
  6006. mg_read(struct mg_connection *conn, void *buf, size_t len)
  6007. {
  6008. if (len > INT_MAX) {
  6009. len = INT_MAX;
  6010. }
  6011. if (conn == NULL) {
  6012. return 0;
  6013. }
  6014. if (conn->is_chunked) {
  6015. size_t all_read = 0;
  6016. while (len > 0) {
  6017. if (conn->is_chunked >= 3) {
  6018. /* No more data left to read */
  6019. return 0;
  6020. }
  6021. if (conn->is_chunked != 1) {
  6022. /* Has error */
  6023. return -1;
  6024. }
  6025. if (conn->consumed_content != conn->content_len) {
  6026. /* copy from the current chunk */
  6027. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  6028. if (read_ret < 1) {
  6029. /* read error */
  6030. conn->is_chunked = 2;
  6031. return -1;
  6032. }
  6033. all_read += (size_t)read_ret;
  6034. len -= (size_t)read_ret;
  6035. if (conn->consumed_content == conn->content_len) {
  6036. /* Add data bytes in the current chunk have been read,
  6037. * so we are expecting \r\n now. */
  6038. char x[2];
  6039. conn->content_len += 2;
  6040. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  6041. || (x[1] != '\n')) {
  6042. /* Protocol violation */
  6043. conn->is_chunked = 2;
  6044. return -1;
  6045. }
  6046. }
  6047. } else {
  6048. /* fetch a new chunk */
  6049. size_t i;
  6050. char lenbuf[64];
  6051. char *end = NULL;
  6052. unsigned long chunkSize = 0;
  6053. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  6054. conn->content_len++;
  6055. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  6056. lenbuf[i] = 0;
  6057. }
  6058. if ((i > 0) && (lenbuf[i] == '\r')
  6059. && (lenbuf[i - 1] != '\r')) {
  6060. continue;
  6061. }
  6062. if ((i > 1) && (lenbuf[i] == '\n')
  6063. && (lenbuf[i - 1] == '\r')) {
  6064. lenbuf[i + 1] = 0;
  6065. chunkSize = strtoul(lenbuf, &end, 16);
  6066. if (chunkSize == 0) {
  6067. /* regular end of content */
  6068. conn->is_chunked = 3;
  6069. }
  6070. break;
  6071. }
  6072. if (!isxdigit((unsigned char)lenbuf[i])) {
  6073. /* illegal character for chunk length */
  6074. conn->is_chunked = 2;
  6075. return -1;
  6076. }
  6077. }
  6078. if ((end == NULL) || (*end != '\r')) {
  6079. /* chunksize not set correctly */
  6080. conn->is_chunked = 2;
  6081. return -1;
  6082. }
  6083. if (chunkSize == 0) {
  6084. /* try discarding trailer for keep-alive */
  6085. conn->content_len += 2;
  6086. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  6087. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  6088. conn->is_chunked = 4;
  6089. }
  6090. break;
  6091. }
  6092. /* append a new chunk */
  6093. conn->content_len += (int64_t)chunkSize;
  6094. }
  6095. }
  6096. return (int)all_read;
  6097. }
  6098. return mg_read_inner(conn, buf, len);
  6099. }
  6100. int
  6101. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  6102. {
  6103. time_t now;
  6104. int n, total, allowed;
  6105. if (conn == NULL) {
  6106. return 0;
  6107. }
  6108. if (len > INT_MAX) {
  6109. return -1;
  6110. }
  6111. /* Mark connection as "data sent" */
  6112. conn->request_state = 10;
  6113. #if defined(USE_HTTP2)
  6114. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  6115. http2_data_frame_head(conn, len, 0);
  6116. }
  6117. #endif
  6118. if (conn->throttle > 0) {
  6119. if ((now = time(NULL)) != conn->last_throttle_time) {
  6120. conn->last_throttle_time = now;
  6121. conn->last_throttle_bytes = 0;
  6122. }
  6123. allowed = conn->throttle - conn->last_throttle_bytes;
  6124. if (allowed > (int)len) {
  6125. allowed = (int)len;
  6126. }
  6127. total = push_all(conn->phys_ctx,
  6128. NULL,
  6129. conn->client.sock,
  6130. conn->ssl,
  6131. (const char *)buf,
  6132. allowed);
  6133. if (total == allowed) {
  6134. buf = (const char *)buf + total;
  6135. conn->last_throttle_bytes += total;
  6136. while ((total < (int)len)
  6137. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6138. allowed = (conn->throttle > ((int)len - total))
  6139. ? (int)len - total
  6140. : conn->throttle;
  6141. n = push_all(conn->phys_ctx,
  6142. NULL,
  6143. conn->client.sock,
  6144. conn->ssl,
  6145. (const char *)buf,
  6146. allowed);
  6147. if (n != allowed) {
  6148. break;
  6149. }
  6150. sleep(1);
  6151. conn->last_throttle_bytes = allowed;
  6152. conn->last_throttle_time = time(NULL);
  6153. buf = (const char *)buf + n;
  6154. total += n;
  6155. }
  6156. }
  6157. } else {
  6158. total = push_all(conn->phys_ctx,
  6159. NULL,
  6160. conn->client.sock,
  6161. conn->ssl,
  6162. (const char *)buf,
  6163. (int)len);
  6164. }
  6165. if (total > 0) {
  6166. conn->num_bytes_sent += total;
  6167. }
  6168. return total;
  6169. }
  6170. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6171. int
  6172. mg_send_chunk(struct mg_connection *conn,
  6173. const char *chunk,
  6174. unsigned int chunk_len)
  6175. {
  6176. char lenbuf[16];
  6177. size_t lenbuf_len;
  6178. int ret;
  6179. int t;
  6180. /* First store the length information in a text buffer. */
  6181. sprintf(lenbuf, "%x\r\n", chunk_len);
  6182. lenbuf_len = strlen(lenbuf);
  6183. /* Then send length information, chunk and terminating \r\n. */
  6184. ret = mg_write(conn, lenbuf, lenbuf_len);
  6185. if (ret != (int)lenbuf_len) {
  6186. return -1;
  6187. }
  6188. t = ret;
  6189. ret = mg_write(conn, chunk, chunk_len);
  6190. if (ret != (int)chunk_len) {
  6191. return -1;
  6192. }
  6193. t += ret;
  6194. ret = mg_write(conn, "\r\n", 2);
  6195. if (ret != 2) {
  6196. return -1;
  6197. }
  6198. t += ret;
  6199. return t;
  6200. }
  6201. #if defined(GCC_DIAGNOSTIC)
  6202. /* This block forwards format strings to printf implementations,
  6203. * so we need to disable the format-nonliteral warning. */
  6204. #pragma GCC diagnostic push
  6205. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6206. #endif
  6207. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6208. static int
  6209. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6210. {
  6211. va_list ap_copy;
  6212. size_t size = MG_BUF_LEN / 4;
  6213. int len = -1;
  6214. *buf = NULL;
  6215. while (len < 0) {
  6216. if (*buf) {
  6217. mg_free(*buf);
  6218. }
  6219. size *= 4;
  6220. *buf = (char *)mg_malloc(size);
  6221. if (!*buf) {
  6222. break;
  6223. }
  6224. va_copy(ap_copy, ap);
  6225. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6226. va_end(ap_copy);
  6227. (*buf)[size - 1] = 0;
  6228. }
  6229. return len;
  6230. }
  6231. /* Print message to buffer. If buffer is large enough to hold the message,
  6232. * return buffer. If buffer is to small, allocate large enough buffer on
  6233. * heap,
  6234. * and return allocated buffer. */
  6235. static int
  6236. alloc_vprintf(char **out_buf,
  6237. char *prealloc_buf,
  6238. size_t prealloc_size,
  6239. const char *fmt,
  6240. va_list ap)
  6241. {
  6242. va_list ap_copy;
  6243. int len;
  6244. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6245. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6246. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6247. * Therefore, we make two passes: on first pass, get required message
  6248. * length.
  6249. * On second pass, actually print the message. */
  6250. va_copy(ap_copy, ap);
  6251. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6252. va_end(ap_copy);
  6253. if (len < 0) {
  6254. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6255. * Switch to alternative code path that uses incremental
  6256. * allocations.
  6257. */
  6258. va_copy(ap_copy, ap);
  6259. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6260. va_end(ap_copy);
  6261. } else if ((size_t)(len) >= prealloc_size) {
  6262. /* The pre-allocated buffer not large enough. */
  6263. /* Allocate a new buffer. */
  6264. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6265. if (!*out_buf) {
  6266. /* Allocation failed. Return -1 as "out of memory" error. */
  6267. return -1;
  6268. }
  6269. /* Buffer allocation successful. Store the string there. */
  6270. va_copy(ap_copy, ap);
  6271. IGNORE_UNUSED_RESULT(
  6272. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6273. va_end(ap_copy);
  6274. } else {
  6275. /* The pre-allocated buffer is large enough.
  6276. * Use it to store the string and return the address. */
  6277. va_copy(ap_copy, ap);
  6278. IGNORE_UNUSED_RESULT(
  6279. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6280. va_end(ap_copy);
  6281. *out_buf = prealloc_buf;
  6282. }
  6283. return len;
  6284. }
  6285. #if defined(GCC_DIAGNOSTIC)
  6286. /* Enable format-nonliteral warning again. */
  6287. #pragma GCC diagnostic pop
  6288. #endif
  6289. static int
  6290. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6291. {
  6292. char mem[MG_BUF_LEN];
  6293. char *buf = NULL;
  6294. int len;
  6295. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6296. len = mg_write(conn, buf, (size_t)len);
  6297. }
  6298. if (buf != mem) {
  6299. mg_free(buf);
  6300. }
  6301. return len;
  6302. }
  6303. int
  6304. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6305. {
  6306. va_list ap;
  6307. int result;
  6308. va_start(ap, fmt);
  6309. result = mg_vprintf(conn, fmt, ap);
  6310. va_end(ap);
  6311. return result;
  6312. }
  6313. int
  6314. mg_url_decode(const char *src,
  6315. int src_len,
  6316. char *dst,
  6317. int dst_len,
  6318. int is_form_url_encoded)
  6319. {
  6320. int i, j, a, b;
  6321. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6322. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6323. if ((i < src_len - 2) && (src[i] == '%')
  6324. && isxdigit((unsigned char)src[i + 1])
  6325. && isxdigit((unsigned char)src[i + 2])) {
  6326. a = tolower((unsigned char)src[i + 1]);
  6327. b = tolower((unsigned char)src[i + 2]);
  6328. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6329. i += 2;
  6330. } else if (is_form_url_encoded && (src[i] == '+')) {
  6331. dst[j] = ' ';
  6332. } else {
  6333. dst[j] = src[i];
  6334. }
  6335. }
  6336. dst[j] = '\0'; /* Null-terminate the destination */
  6337. return (i >= src_len) ? j : -1;
  6338. }
  6339. /* form url decoding of an entire string */
  6340. static void
  6341. url_decode_in_place(char *buf)
  6342. {
  6343. int len = (int)strlen(buf);
  6344. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6345. }
  6346. int
  6347. mg_get_var(const char *data,
  6348. size_t data_len,
  6349. const char *name,
  6350. char *dst,
  6351. size_t dst_len)
  6352. {
  6353. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6354. }
  6355. int
  6356. mg_get_var2(const char *data,
  6357. size_t data_len,
  6358. const char *name,
  6359. char *dst,
  6360. size_t dst_len,
  6361. size_t occurrence)
  6362. {
  6363. const char *p, *e, *s;
  6364. size_t name_len;
  6365. int len;
  6366. if ((dst == NULL) || (dst_len == 0)) {
  6367. len = -2;
  6368. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6369. len = -1;
  6370. dst[0] = '\0';
  6371. } else {
  6372. name_len = strlen(name);
  6373. e = data + data_len;
  6374. len = -1;
  6375. dst[0] = '\0';
  6376. /* data is "var1=val1&var2=val2...". Find variable first */
  6377. for (p = data; p + name_len < e; p++) {
  6378. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6379. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6380. /* Point p to variable value */
  6381. p += name_len + 1;
  6382. /* Point s to the end of the value */
  6383. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6384. if (s == NULL) {
  6385. s = e;
  6386. }
  6387. DEBUG_ASSERT(s >= p);
  6388. if (s < p) {
  6389. return -3;
  6390. }
  6391. /* Decode variable into destination buffer */
  6392. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6393. /* Redirect error code from -1 to -2 (destination buffer too
  6394. * small). */
  6395. if (len == -1) {
  6396. len = -2;
  6397. }
  6398. break;
  6399. }
  6400. }
  6401. }
  6402. return len;
  6403. }
  6404. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6405. int
  6406. mg_split_form_urlencoded(char *data,
  6407. struct mg_header *form_fields,
  6408. unsigned num_form_fields)
  6409. {
  6410. char *b;
  6411. int i;
  6412. int num = 0;
  6413. if (data == NULL) {
  6414. /* parameter error */
  6415. return -1;
  6416. }
  6417. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6418. /* determine the number of expected fields */
  6419. if (data[0] == 0) {
  6420. return 0;
  6421. }
  6422. /* count number of & to return the number of key-value-pairs */
  6423. num = 1;
  6424. while (*data) {
  6425. if (*data == '&') {
  6426. num++;
  6427. }
  6428. data++;
  6429. }
  6430. return num;
  6431. }
  6432. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6433. /* parameter error */
  6434. return -1;
  6435. }
  6436. for (i = 0; i < (int)num_form_fields; i++) {
  6437. /* extract key-value pairs from input data */
  6438. while ((*data == ' ') || (*data == '\t')) {
  6439. /* skip initial spaces */
  6440. data++;
  6441. }
  6442. if (*data == 0) {
  6443. /* end of string reached */
  6444. break;
  6445. }
  6446. form_fields[num].name = data;
  6447. /* find & or = */
  6448. b = data;
  6449. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6450. b++;
  6451. }
  6452. if (*b == 0) {
  6453. /* last key without value */
  6454. form_fields[num].value = NULL;
  6455. } else if (*b == '&') {
  6456. /* mid key without value */
  6457. form_fields[num].value = NULL;
  6458. } else {
  6459. /* terminate string */
  6460. *b = 0;
  6461. /* value starts after '=' */
  6462. data = b + 1;
  6463. form_fields[num].value = data;
  6464. }
  6465. /* new field is stored */
  6466. num++;
  6467. /* find a next key */
  6468. b = strchr(data, '&');
  6469. if (b == 0) {
  6470. /* no more data */
  6471. break;
  6472. } else {
  6473. /* terminate value of last field at '&' */
  6474. *b = 0;
  6475. /* next key-value-pairs starts after '&' */
  6476. data = b + 1;
  6477. }
  6478. }
  6479. /* Decode all values */
  6480. for (i = 0; i < num; i++) {
  6481. if (form_fields[i].name) {
  6482. url_decode_in_place((char *)form_fields[i].name);
  6483. }
  6484. if (form_fields[i].value) {
  6485. url_decode_in_place((char *)form_fields[i].value);
  6486. }
  6487. }
  6488. /* return number of fields found */
  6489. return num;
  6490. }
  6491. /* HCP24: some changes to compare hole var_name */
  6492. int
  6493. mg_get_cookie(const char *cookie_header,
  6494. const char *var_name,
  6495. char *dst,
  6496. size_t dst_size)
  6497. {
  6498. const char *s, *p, *end;
  6499. int name_len, len = -1;
  6500. if ((dst == NULL) || (dst_size == 0)) {
  6501. return -2;
  6502. }
  6503. dst[0] = '\0';
  6504. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6505. return -1;
  6506. }
  6507. name_len = (int)strlen(var_name);
  6508. end = s + strlen(s);
  6509. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6510. if (s[name_len] == '=') {
  6511. /* HCP24: now check is it a substring or a full cookie name */
  6512. if ((s == cookie_header) || (s[-1] == ' ')) {
  6513. s += name_len + 1;
  6514. if ((p = strchr(s, ' ')) == NULL) {
  6515. p = end;
  6516. }
  6517. if (p[-1] == ';') {
  6518. p--;
  6519. }
  6520. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6521. s++;
  6522. p--;
  6523. }
  6524. if ((size_t)(p - s) < dst_size) {
  6525. len = (int)(p - s);
  6526. mg_strlcpy(dst, s, (size_t)len + 1);
  6527. } else {
  6528. len = -3;
  6529. }
  6530. break;
  6531. }
  6532. }
  6533. }
  6534. return len;
  6535. }
  6536. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6537. static void
  6538. base64_encode(const unsigned char *src, int src_len, char *dst)
  6539. {
  6540. static const char *b64 =
  6541. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6542. int i, j, a, b, c;
  6543. for (i = j = 0; i < src_len; i += 3) {
  6544. a = src[i];
  6545. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6546. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6547. dst[j++] = b64[a >> 2];
  6548. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6549. if (i + 1 < src_len) {
  6550. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6551. }
  6552. if (i + 2 < src_len) {
  6553. dst[j++] = b64[c & 63];
  6554. }
  6555. }
  6556. while (j % 4 != 0) {
  6557. dst[j++] = '=';
  6558. }
  6559. dst[j++] = '\0';
  6560. }
  6561. #endif
  6562. #if defined(USE_LUA)
  6563. static unsigned char
  6564. b64reverse(char letter)
  6565. {
  6566. if ((letter >= 'A') && (letter <= 'Z')) {
  6567. return letter - 'A';
  6568. }
  6569. if ((letter >= 'a') && (letter <= 'z')) {
  6570. return letter - 'a' + 26;
  6571. }
  6572. if ((letter >= '0') && (letter <= '9')) {
  6573. return letter - '0' + 52;
  6574. }
  6575. if (letter == '+') {
  6576. return 62;
  6577. }
  6578. if (letter == '/') {
  6579. return 63;
  6580. }
  6581. if (letter == '=') {
  6582. return 255; /* normal end */
  6583. }
  6584. return 254; /* error */
  6585. }
  6586. static int
  6587. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6588. {
  6589. int i;
  6590. unsigned char a, b, c, d;
  6591. *dst_len = 0;
  6592. for (i = 0; i < src_len; i += 4) {
  6593. a = b64reverse(src[i]);
  6594. if (a >= 254) {
  6595. return i;
  6596. }
  6597. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6598. if (b >= 254) {
  6599. return i + 1;
  6600. }
  6601. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6602. if (c == 254) {
  6603. return i + 2;
  6604. }
  6605. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6606. if (d == 254) {
  6607. return i + 3;
  6608. }
  6609. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6610. if (c != 255) {
  6611. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6612. if (d != 255) {
  6613. dst[(*dst_len)++] = (c << 6) + d;
  6614. }
  6615. }
  6616. }
  6617. return -1;
  6618. }
  6619. #endif
  6620. static int
  6621. is_put_or_delete_method(const struct mg_connection *conn)
  6622. {
  6623. if (conn) {
  6624. const char *s = conn->request_info.request_method;
  6625. return (s != NULL)
  6626. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6627. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6628. }
  6629. return 0;
  6630. }
  6631. #if !defined(NO_FILES)
  6632. static int
  6633. extention_matches_script(
  6634. struct mg_connection *conn, /* in: request (must be valid) */
  6635. const char *filename /* in: filename (must be valid) */
  6636. )
  6637. {
  6638. #if !defined(NO_CGI)
  6639. if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], filename)
  6640. > 0) {
  6641. return 1;
  6642. }
  6643. if (match_prefix_strlen(conn->dom_ctx->config[CGI2_EXTENSIONS], filename)
  6644. > 0) {
  6645. return 1;
  6646. }
  6647. #endif
  6648. #if defined(USE_LUA)
  6649. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6650. filename)
  6651. > 0) {
  6652. return 1;
  6653. }
  6654. #endif
  6655. #if defined(USE_DUKTAPE)
  6656. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6657. filename)
  6658. > 0) {
  6659. return 1;
  6660. }
  6661. #endif
  6662. /* filename and conn could be unused, if all preocessor conditions
  6663. * are false (no script language supported). */
  6664. (void)filename;
  6665. (void)conn;
  6666. return 0;
  6667. }
  6668. static int
  6669. extention_matches_template_text(
  6670. struct mg_connection *conn, /* in: request (must be valid) */
  6671. const char *filename /* in: filename (must be valid) */
  6672. )
  6673. {
  6674. #if defined(USE_LUA)
  6675. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6676. filename)
  6677. > 0) {
  6678. return 1;
  6679. }
  6680. #endif
  6681. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6682. > 0) {
  6683. return 1;
  6684. }
  6685. return 0;
  6686. }
  6687. /* For given directory path, substitute it to valid index file.
  6688. * Return 1 if index file has been found, 0 if not found.
  6689. * If the file is found, it's stats is returned in stp. */
  6690. static int
  6691. substitute_index_file(struct mg_connection *conn,
  6692. char *path,
  6693. size_t path_len,
  6694. struct mg_file_stat *filestat)
  6695. {
  6696. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6697. struct vec filename_vec;
  6698. size_t n = strlen(path);
  6699. int found = 0;
  6700. /* The 'path' given to us points to the directory. Remove all trailing
  6701. * directory separator characters from the end of the path, and
  6702. * then append single directory separator character. */
  6703. while ((n > 0) && (path[n - 1] == '/')) {
  6704. n--;
  6705. }
  6706. path[n] = '/';
  6707. /* Traverse index files list. For each entry, append it to the given
  6708. * path and see if the file exists. If it exists, break the loop */
  6709. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6710. /* Ignore too long entries that may overflow path buffer */
  6711. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6712. continue;
  6713. }
  6714. /* Prepare full path to the index file */
  6715. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6716. /* Does it exist? */
  6717. if (mg_stat(conn, path, filestat)) {
  6718. /* Yes it does, break the loop */
  6719. found = 1;
  6720. break;
  6721. }
  6722. }
  6723. /* If no index file exists, restore directory path */
  6724. if (!found) {
  6725. path[n] = '\0';
  6726. }
  6727. return found;
  6728. }
  6729. #endif
  6730. static void
  6731. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6732. char *filename, /* out: filename */
  6733. size_t filename_buf_len, /* in: size of filename buffer */
  6734. struct mg_file_stat *filestat, /* out: file status structure */
  6735. int *is_found, /* out: file found (directly) */
  6736. int *is_script_resource, /* out: handled by a script? */
  6737. int *is_websocket_request, /* out: websocket connetion? */
  6738. int *is_put_or_delete_request, /* out: put/delete a file? */
  6739. int *is_template_text /* out: SSI file or LSP file? */
  6740. )
  6741. {
  6742. char const *accept_encoding;
  6743. #if !defined(NO_FILES)
  6744. const char *uri = conn->request_info.local_uri;
  6745. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6746. const char *rewrite;
  6747. struct vec a, b;
  6748. ptrdiff_t match_len;
  6749. char gz_path[PATH_MAX];
  6750. int truncated;
  6751. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6752. char *tmp_str;
  6753. size_t tmp_str_len, sep_pos;
  6754. int allow_substitute_script_subresources;
  6755. #endif
  6756. #else
  6757. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6758. #endif
  6759. /* Step 1: Set all initially unknown outputs to zero */
  6760. memset(filestat, 0, sizeof(*filestat));
  6761. *filename = 0;
  6762. *is_found = 0;
  6763. *is_script_resource = 0;
  6764. *is_template_text = 0;
  6765. /* Step 2: Check if the request attempts to modify the file system */
  6766. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6767. /* Step 3: Check if it is a websocket request, and modify the document
  6768. * root if required */
  6769. #if defined(USE_WEBSOCKET)
  6770. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6771. #if !defined(NO_FILES)
  6772. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6773. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6774. }
  6775. #endif /* !NO_FILES */
  6776. #else /* USE_WEBSOCKET */
  6777. *is_websocket_request = 0;
  6778. #endif /* USE_WEBSOCKET */
  6779. /* Step 4: Check if gzip encoded response is allowed */
  6780. conn->accept_gzip = 0;
  6781. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6782. if (strstr(accept_encoding, "gzip") != NULL) {
  6783. conn->accept_gzip = 1;
  6784. }
  6785. }
  6786. #if !defined(NO_FILES)
  6787. /* Step 5: If there is no root directory, don't look for files. */
  6788. /* Note that root == NULL is a regular use case here. This occurs,
  6789. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6790. * config is not required. */
  6791. if (root == NULL) {
  6792. /* all file related outputs have already been set to 0, just return
  6793. */
  6794. return;
  6795. }
  6796. /* Step 6: Determine the local file path from the root path and the
  6797. * request uri. */
  6798. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6799. * part of the path one byte on the right. */
  6800. truncated = 0;
  6801. mg_snprintf(
  6802. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6803. if (truncated) {
  6804. goto interpret_cleanup;
  6805. }
  6806. /* Step 7: URI rewriting */
  6807. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6808. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6809. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6810. mg_snprintf(conn,
  6811. &truncated,
  6812. filename,
  6813. filename_buf_len - 1,
  6814. "%.*s%s",
  6815. (int)b.len,
  6816. b.ptr,
  6817. uri + match_len);
  6818. break;
  6819. }
  6820. }
  6821. if (truncated) {
  6822. goto interpret_cleanup;
  6823. }
  6824. /* Step 8: Check if the file exists at the server */
  6825. /* Local file path and name, corresponding to requested URI
  6826. * is now stored in "filename" variable. */
  6827. if (mg_stat(conn, filename, filestat)) {
  6828. int uri_len = (int)strlen(uri);
  6829. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6830. /* 8.1: File exists. */
  6831. *is_found = 1;
  6832. /* 8.2: Check if it is a script type. */
  6833. if (extention_matches_script(conn, filename)) {
  6834. /* The request addresses a CGI resource, Lua script or
  6835. * server-side javascript.
  6836. * The URI corresponds to the script itself (like
  6837. * /path/script.cgi), and there is no additional resource
  6838. * path (like /path/script.cgi/something).
  6839. * Requests that modify (replace or delete) a resource, like
  6840. * PUT and DELETE requests, should replace/delete the script
  6841. * file.
  6842. * Requests that read or write from/to a resource, like GET and
  6843. * POST requests, should call the script and return the
  6844. * generated response. */
  6845. *is_script_resource = (!*is_put_or_delete_request);
  6846. }
  6847. /* 8.3: Check for SSI and LSP files */
  6848. if (extention_matches_template_text(conn, filename)) {
  6849. /* Same as above, but for *.lsp and *.shtml files. */
  6850. /* A "template text" is a file delivered directly to the client,
  6851. * but with some text tags replaced by dynamic content.
  6852. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6853. * (LP, LSP) file. */
  6854. *is_template_text = (!*is_put_or_delete_request);
  6855. }
  6856. /* 8.4: If the request target is a directory, there could be
  6857. * a substitute file (index.html, index.cgi, ...). */
  6858. if (filestat->is_directory && is_uri_end_slash) {
  6859. /* Use a local copy here, since substitute_index_file will
  6860. * change the content of the file status */
  6861. struct mg_file_stat tmp_filestat;
  6862. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6863. if (substitute_index_file(
  6864. conn, filename, filename_buf_len, &tmp_filestat)) {
  6865. /* Substitute file found. Copy stat to the output, then
  6866. * check if the file is a script file */
  6867. *filestat = tmp_filestat;
  6868. if (extention_matches_script(conn, filename)) {
  6869. /* Substitute file is a script file */
  6870. *is_script_resource = 1;
  6871. } else if (extention_matches_template_text(conn, filename)) {
  6872. /* Substitute file is a LSP or SSI file */
  6873. *is_template_text = 1;
  6874. } else {
  6875. /* Substitute file is a regular file */
  6876. *is_script_resource = 0;
  6877. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6878. }
  6879. }
  6880. /* If there is no substitute file, the server could return
  6881. * a directory listing in a later step */
  6882. }
  6883. return;
  6884. }
  6885. /* Step 9: Check for zipped files: */
  6886. /* If we can't find the actual file, look for the file
  6887. * with the same name but a .gz extension. If we find it,
  6888. * use that and set the gzipped flag in the file struct
  6889. * to indicate that the response need to have the content-
  6890. * encoding: gzip header.
  6891. * We can only do this if the browser declares support. */
  6892. if (conn->accept_gzip) {
  6893. mg_snprintf(
  6894. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6895. if (truncated) {
  6896. goto interpret_cleanup;
  6897. }
  6898. if (mg_stat(conn, gz_path, filestat)) {
  6899. if (filestat) {
  6900. filestat->is_gzipped = 1;
  6901. *is_found = 1;
  6902. }
  6903. /* Currently gz files can not be scripts. */
  6904. return;
  6905. }
  6906. }
  6907. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6908. /* Step 10: Script resources may handle sub-resources */
  6909. /* Support PATH_INFO for CGI scripts. */
  6910. tmp_str_len = strlen(filename);
  6911. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6912. if (!tmp_str) {
  6913. /* Out of memory */
  6914. goto interpret_cleanup;
  6915. }
  6916. memcpy(tmp_str, filename, tmp_str_len + 1);
  6917. /* Check config, if index scripts may have sub-resources */
  6918. allow_substitute_script_subresources =
  6919. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6920. "yes");
  6921. sep_pos = tmp_str_len;
  6922. while (sep_pos > 0) {
  6923. sep_pos--;
  6924. if (tmp_str[sep_pos] == '/') {
  6925. int is_script = 0, does_exist = 0;
  6926. tmp_str[sep_pos] = 0;
  6927. if (tmp_str[0]) {
  6928. is_script = extention_matches_script(conn, tmp_str);
  6929. does_exist = mg_stat(conn, tmp_str, filestat);
  6930. }
  6931. if (does_exist && is_script) {
  6932. filename[sep_pos] = 0;
  6933. memmove(filename + sep_pos + 2,
  6934. filename + sep_pos + 1,
  6935. strlen(filename + sep_pos + 1) + 1);
  6936. conn->path_info = filename + sep_pos + 1;
  6937. filename[sep_pos + 1] = '/';
  6938. *is_script_resource = 1;
  6939. *is_found = 1;
  6940. break;
  6941. }
  6942. if (allow_substitute_script_subresources) {
  6943. if (substitute_index_file(
  6944. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6945. /* some intermediate directory has an index file */
  6946. if (extention_matches_script(conn, tmp_str)) {
  6947. size_t script_name_len = strlen(tmp_str);
  6948. /* subres_name read before this memory locatio will be
  6949. overwritten */
  6950. char *subres_name = filename + sep_pos;
  6951. size_t subres_name_len = strlen(subres_name);
  6952. DEBUG_TRACE("Substitute script %s serving path %s",
  6953. tmp_str,
  6954. filename);
  6955. /* this index file is a script */
  6956. if ((script_name_len + subres_name_len + 2)
  6957. >= filename_buf_len) {
  6958. mg_free(tmp_str);
  6959. goto interpret_cleanup;
  6960. }
  6961. conn->path_info =
  6962. filename + script_name_len + 1; /* new target */
  6963. memmove(conn->path_info, subres_name, subres_name_len);
  6964. conn->path_info[subres_name_len] = 0;
  6965. memcpy(filename, tmp_str, script_name_len + 1);
  6966. *is_script_resource = 1;
  6967. *is_found = 1;
  6968. break;
  6969. } else {
  6970. DEBUG_TRACE("Substitute file %s serving path %s",
  6971. tmp_str,
  6972. filename);
  6973. /* non-script files will not have sub-resources */
  6974. filename[sep_pos] = 0;
  6975. conn->path_info = 0;
  6976. *is_script_resource = 0;
  6977. *is_found = 0;
  6978. break;
  6979. }
  6980. }
  6981. }
  6982. tmp_str[sep_pos] = '/';
  6983. }
  6984. }
  6985. mg_free(tmp_str);
  6986. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6987. #endif /* !defined(NO_FILES) */
  6988. return;
  6989. #if !defined(NO_FILES)
  6990. /* Reset all outputs */
  6991. interpret_cleanup:
  6992. memset(filestat, 0, sizeof(*filestat));
  6993. *filename = 0;
  6994. *is_found = 0;
  6995. *is_script_resource = 0;
  6996. *is_websocket_request = 0;
  6997. *is_put_or_delete_request = 0;
  6998. #endif /* !defined(NO_FILES) */
  6999. }
  7000. /* Check whether full request is buffered. Return:
  7001. * -1 if request or response is malformed
  7002. * 0 if request or response is not yet fully buffered
  7003. * >0 actual request length, including last \r\n\r\n */
  7004. static int
  7005. get_http_header_len(const char *buf, int buflen)
  7006. {
  7007. int i;
  7008. for (i = 0; i < buflen; i++) {
  7009. /* Do an unsigned comparison in some conditions below */
  7010. const unsigned char c = (unsigned char)buf[i];
  7011. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7012. && !isprint(c)) {
  7013. /* abort scan as soon as one malformed character is found */
  7014. return -1;
  7015. }
  7016. if (i < buflen - 1) {
  7017. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7018. /* Two newline, no carriage return - not standard compliant,
  7019. * but it should be accepted */
  7020. return i + 2;
  7021. }
  7022. }
  7023. if (i < buflen - 3) {
  7024. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7025. && (buf[i + 3] == '\n')) {
  7026. /* Two \r\n - standard compliant */
  7027. return i + 4;
  7028. }
  7029. }
  7030. }
  7031. return 0;
  7032. }
  7033. #if !defined(NO_CACHING)
  7034. /* Convert month to the month number. Return -1 on error, or month number */
  7035. static int
  7036. get_month_index(const char *s)
  7037. {
  7038. size_t i;
  7039. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7040. if (!strcmp(s, month_names[i])) {
  7041. return (int)i;
  7042. }
  7043. }
  7044. return -1;
  7045. }
  7046. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7047. static time_t
  7048. parse_date_string(const char *datetime)
  7049. {
  7050. char month_str[32] = {0};
  7051. int second, minute, hour, day, month, year;
  7052. time_t result = (time_t)0;
  7053. struct tm tm;
  7054. if ((sscanf(datetime,
  7055. "%d/%3s/%d %d:%d:%d",
  7056. &day,
  7057. month_str,
  7058. &year,
  7059. &hour,
  7060. &minute,
  7061. &second)
  7062. == 6)
  7063. || (sscanf(datetime,
  7064. "%d %3s %d %d:%d:%d",
  7065. &day,
  7066. month_str,
  7067. &year,
  7068. &hour,
  7069. &minute,
  7070. &second)
  7071. == 6)
  7072. || (sscanf(datetime,
  7073. "%*3s, %d %3s %d %d:%d:%d",
  7074. &day,
  7075. month_str,
  7076. &year,
  7077. &hour,
  7078. &minute,
  7079. &second)
  7080. == 6)
  7081. || (sscanf(datetime,
  7082. "%d-%3s-%d %d:%d:%d",
  7083. &day,
  7084. month_str,
  7085. &year,
  7086. &hour,
  7087. &minute,
  7088. &second)
  7089. == 6)) {
  7090. month = get_month_index(month_str);
  7091. if ((month >= 0) && (year >= 1970)) {
  7092. memset(&tm, 0, sizeof(tm));
  7093. tm.tm_year = year - 1900;
  7094. tm.tm_mon = month;
  7095. tm.tm_mday = day;
  7096. tm.tm_hour = hour;
  7097. tm.tm_min = minute;
  7098. tm.tm_sec = second;
  7099. result = timegm(&tm);
  7100. }
  7101. }
  7102. return result;
  7103. }
  7104. #endif /* !NO_CACHING */
  7105. /* Pre-process URIs according to RFC + protect against directory disclosure
  7106. * attacks by removing '..', excessive '/' and '\' characters */
  7107. static void
  7108. remove_dot_segments(char *inout)
  7109. {
  7110. /* Windows backend protection
  7111. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7112. * in URI by slash */
  7113. char *out_end = inout;
  7114. char *in = inout;
  7115. if (!in) {
  7116. /* Param error. */
  7117. return;
  7118. }
  7119. while (*in) {
  7120. if (*in == '\\') {
  7121. *in = '/';
  7122. }
  7123. in++;
  7124. }
  7125. /* Algorithm "remove_dot_segments" from
  7126. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7127. /* Step 1:
  7128. * The input buffer is initialized.
  7129. * The output buffer is initialized to the empty string.
  7130. */
  7131. in = inout;
  7132. /* Step 2:
  7133. * While the input buffer is not empty, loop as follows:
  7134. */
  7135. /* Less than out_end of the inout buffer is used as output, so keep
  7136. * condition: out_end <= in */
  7137. while (*in) {
  7138. /* Step 2a:
  7139. * If the input buffer begins with a prefix of "../" or "./",
  7140. * then remove that prefix from the input buffer;
  7141. */
  7142. if (!strncmp(in, "../", 3)) {
  7143. in += 3;
  7144. } else if (!strncmp(in, "./", 2)) {
  7145. in += 2;
  7146. }
  7147. /* otherwise */
  7148. /* Step 2b:
  7149. * if the input buffer begins with a prefix of "/./" or "/.",
  7150. * where "." is a complete path segment, then replace that
  7151. * prefix with "/" in the input buffer;
  7152. */
  7153. else if (!strncmp(in, "/./", 3)) {
  7154. in += 2;
  7155. } else if (!strcmp(in, "/.")) {
  7156. in[1] = 0;
  7157. }
  7158. /* otherwise */
  7159. /* Step 2c:
  7160. * if the input buffer begins with a prefix of "/../" or "/..",
  7161. * where ".." is a complete path segment, then replace that
  7162. * prefix with "/" in the input buffer and remove the last
  7163. * segment and its preceding "/" (if any) from the output
  7164. * buffer;
  7165. */
  7166. else if (!strncmp(in, "/../", 4)) {
  7167. in += 3;
  7168. if (inout != out_end) {
  7169. /* remove last segment */
  7170. do {
  7171. out_end--;
  7172. } while ((inout != out_end) && (*out_end != '/'));
  7173. }
  7174. } else if (!strcmp(in, "/..")) {
  7175. in[1] = 0;
  7176. if (inout != out_end) {
  7177. /* remove last segment */
  7178. do {
  7179. out_end--;
  7180. } while ((inout != out_end) && (*out_end != '/'));
  7181. }
  7182. }
  7183. /* otherwise */
  7184. /* Step 2d:
  7185. * if the input buffer consists only of "." or "..", then remove
  7186. * that from the input buffer;
  7187. */
  7188. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7189. *in = 0;
  7190. }
  7191. /* otherwise */
  7192. /* Step 2e:
  7193. * move the first path segment in the input buffer to the end of
  7194. * the output buffer, including the initial "/" character (if
  7195. * any) and any subsequent characters up to, but not including,
  7196. * the next "/" character or the end of the input buffer.
  7197. */
  7198. else {
  7199. do {
  7200. *out_end = *in;
  7201. out_end++;
  7202. in++;
  7203. } while ((*in != 0) && (*in != '/'));
  7204. }
  7205. }
  7206. /* Step 3:
  7207. * Finally, the output buffer is returned as the result of
  7208. * remove_dot_segments.
  7209. */
  7210. /* Terminate output */
  7211. *out_end = 0;
  7212. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7213. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7214. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7215. * or "//" anymore.
  7216. */
  7217. out_end = in = inout;
  7218. while (*in) {
  7219. if (*in == '.') {
  7220. /* remove . at the end or preceding of / */
  7221. char *in_ahead = in;
  7222. do {
  7223. in_ahead++;
  7224. } while (*in_ahead == '.');
  7225. if (*in_ahead == '/') {
  7226. in = in_ahead;
  7227. if ((out_end != inout) && (out_end[-1] == '/')) {
  7228. /* remove generated // */
  7229. out_end--;
  7230. }
  7231. } else if (*in_ahead == 0) {
  7232. in = in_ahead;
  7233. } else {
  7234. do {
  7235. *out_end++ = '.';
  7236. in++;
  7237. } while (in != in_ahead);
  7238. }
  7239. } else if (*in == '/') {
  7240. /* replace // by / */
  7241. *out_end++ = '/';
  7242. do {
  7243. in++;
  7244. } while (*in == '/');
  7245. } else {
  7246. *out_end++ = *in;
  7247. in++;
  7248. }
  7249. }
  7250. *out_end = 0;
  7251. }
  7252. static const struct {
  7253. const char *extension;
  7254. size_t ext_len;
  7255. const char *mime_type;
  7256. } builtin_mime_types[] = {
  7257. /* IANA registered MIME types
  7258. * (http://www.iana.org/assignments/media-types)
  7259. * application types */
  7260. {".doc", 4, "application/msword"},
  7261. {".eps", 4, "application/postscript"},
  7262. {".exe", 4, "application/octet-stream"},
  7263. {".js", 3, "application/javascript"},
  7264. {".json", 5, "application/json"},
  7265. {".pdf", 4, "application/pdf"},
  7266. {".ps", 3, "application/postscript"},
  7267. {".rtf", 4, "application/rtf"},
  7268. {".xhtml", 6, "application/xhtml+xml"},
  7269. {".xsl", 4, "application/xml"},
  7270. {".xslt", 5, "application/xml"},
  7271. /* fonts */
  7272. {".ttf", 4, "application/font-sfnt"},
  7273. {".cff", 4, "application/font-sfnt"},
  7274. {".otf", 4, "application/font-sfnt"},
  7275. {".aat", 4, "application/font-sfnt"},
  7276. {".sil", 4, "application/font-sfnt"},
  7277. {".pfr", 4, "application/font-tdpfr"},
  7278. {".woff", 5, "application/font-woff"},
  7279. /* audio */
  7280. {".mp3", 4, "audio/mpeg"},
  7281. {".oga", 4, "audio/ogg"},
  7282. {".ogg", 4, "audio/ogg"},
  7283. /* image */
  7284. {".gif", 4, "image/gif"},
  7285. {".ief", 4, "image/ief"},
  7286. {".jpeg", 5, "image/jpeg"},
  7287. {".jpg", 4, "image/jpeg"},
  7288. {".jpm", 4, "image/jpm"},
  7289. {".jpx", 4, "image/jpx"},
  7290. {".png", 4, "image/png"},
  7291. {".svg", 4, "image/svg+xml"},
  7292. {".tif", 4, "image/tiff"},
  7293. {".tiff", 5, "image/tiff"},
  7294. /* model */
  7295. {".wrl", 4, "model/vrml"},
  7296. /* text */
  7297. {".css", 4, "text/css"},
  7298. {".csv", 4, "text/csv"},
  7299. {".htm", 4, "text/html"},
  7300. {".html", 5, "text/html"},
  7301. {".sgm", 4, "text/sgml"},
  7302. {".shtm", 5, "text/html"},
  7303. {".shtml", 6, "text/html"},
  7304. {".txt", 4, "text/plain"},
  7305. {".xml", 4, "text/xml"},
  7306. /* video */
  7307. {".mov", 4, "video/quicktime"},
  7308. {".mp4", 4, "video/mp4"},
  7309. {".mpeg", 5, "video/mpeg"},
  7310. {".mpg", 4, "video/mpeg"},
  7311. {".ogv", 4, "video/ogg"},
  7312. {".qt", 3, "video/quicktime"},
  7313. /* not registered types
  7314. * (http://reference.sitepoint.com/html/mime-types-full,
  7315. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7316. {".arj", 4, "application/x-arj-compressed"},
  7317. {".gz", 3, "application/x-gunzip"},
  7318. {".rar", 4, "application/x-arj-compressed"},
  7319. {".swf", 4, "application/x-shockwave-flash"},
  7320. {".tar", 4, "application/x-tar"},
  7321. {".tgz", 4, "application/x-tar-gz"},
  7322. {".torrent", 8, "application/x-bittorrent"},
  7323. {".ppt", 4, "application/x-mspowerpoint"},
  7324. {".xls", 4, "application/x-msexcel"},
  7325. {".zip", 4, "application/x-zip-compressed"},
  7326. {".aac",
  7327. 4,
  7328. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7329. {".aif", 4, "audio/x-aif"},
  7330. {".m3u", 4, "audio/x-mpegurl"},
  7331. {".mid", 4, "audio/x-midi"},
  7332. {".ra", 3, "audio/x-pn-realaudio"},
  7333. {".ram", 4, "audio/x-pn-realaudio"},
  7334. {".wav", 4, "audio/x-wav"},
  7335. {".bmp", 4, "image/bmp"},
  7336. {".ico", 4, "image/x-icon"},
  7337. {".pct", 4, "image/x-pct"},
  7338. {".pict", 5, "image/pict"},
  7339. {".rgb", 4, "image/x-rgb"},
  7340. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7341. {".asf", 4, "video/x-ms-asf"},
  7342. {".avi", 4, "video/x-msvideo"},
  7343. {".m4v", 4, "video/x-m4v"},
  7344. {NULL, 0, NULL}};
  7345. const char *
  7346. mg_get_builtin_mime_type(const char *path)
  7347. {
  7348. const char *ext;
  7349. size_t i, path_len;
  7350. path_len = strlen(path);
  7351. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7352. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7353. if ((path_len > builtin_mime_types[i].ext_len)
  7354. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7355. return builtin_mime_types[i].mime_type;
  7356. }
  7357. }
  7358. return "text/plain";
  7359. }
  7360. /* Look at the "path" extension and figure what mime type it has.
  7361. * Store mime type in the vector. */
  7362. static void
  7363. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7364. {
  7365. struct vec ext_vec, mime_vec;
  7366. const char *list, *ext;
  7367. size_t path_len;
  7368. path_len = strlen(path);
  7369. if ((conn == NULL) || (vec == NULL)) {
  7370. if (vec != NULL) {
  7371. memset(vec, '\0', sizeof(struct vec));
  7372. }
  7373. return;
  7374. }
  7375. /* Scan user-defined mime types first, in case user wants to
  7376. * override default mime types. */
  7377. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7378. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7379. /* ext now points to the path suffix */
  7380. ext = path + path_len - ext_vec.len;
  7381. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7382. *vec = mime_vec;
  7383. return;
  7384. }
  7385. }
  7386. vec->ptr = mg_get_builtin_mime_type(path);
  7387. vec->len = strlen(vec->ptr);
  7388. }
  7389. /* Stringify binary data. Output buffer must be twice as big as input,
  7390. * because each byte takes 2 bytes in string representation */
  7391. static void
  7392. bin2str(char *to, const unsigned char *p, size_t len)
  7393. {
  7394. static const char *hex = "0123456789abcdef";
  7395. for (; len--; p++) {
  7396. *to++ = hex[p[0] >> 4];
  7397. *to++ = hex[p[0] & 0x0f];
  7398. }
  7399. *to = '\0';
  7400. }
  7401. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7402. */
  7403. char *
  7404. mg_md5(char buf[33], ...)
  7405. {
  7406. md5_byte_t hash[16];
  7407. const char *p;
  7408. va_list ap;
  7409. md5_state_t ctx;
  7410. md5_init(&ctx);
  7411. va_start(ap, buf);
  7412. while ((p = va_arg(ap, const char *)) != NULL) {
  7413. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7414. }
  7415. va_end(ap);
  7416. md5_finish(&ctx, hash);
  7417. bin2str(buf, hash, sizeof(hash));
  7418. return buf;
  7419. }
  7420. /* Check the user's password, return 1 if OK */
  7421. static int
  7422. check_password(const char *method,
  7423. const char *ha1,
  7424. const char *uri,
  7425. const char *nonce,
  7426. const char *nc,
  7427. const char *cnonce,
  7428. const char *qop,
  7429. const char *response)
  7430. {
  7431. char ha2[32 + 1], expected_response[32 + 1];
  7432. /* Some of the parameters may be NULL */
  7433. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7434. || (qop == NULL) || (response == NULL)) {
  7435. return 0;
  7436. }
  7437. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7438. if (strlen(response) != 32) {
  7439. return 0;
  7440. }
  7441. mg_md5(ha2, method, ":", uri, NULL);
  7442. mg_md5(expected_response,
  7443. ha1,
  7444. ":",
  7445. nonce,
  7446. ":",
  7447. nc,
  7448. ":",
  7449. cnonce,
  7450. ":",
  7451. qop,
  7452. ":",
  7453. ha2,
  7454. NULL);
  7455. return mg_strcasecmp(response, expected_response) == 0;
  7456. }
  7457. #if !defined(NO_FILESYSTEMS)
  7458. /* Use the global passwords file, if specified by auth_gpass option,
  7459. * or search for .htpasswd in the requested directory. */
  7460. static void
  7461. open_auth_file(struct mg_connection *conn,
  7462. const char *path,
  7463. struct mg_file *filep)
  7464. {
  7465. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7466. char name[PATH_MAX];
  7467. const char *p, *e,
  7468. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7469. int truncated;
  7470. if (gpass != NULL) {
  7471. /* Use global passwords file */
  7472. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7473. #if defined(DEBUG)
  7474. /* Use mg_cry_internal here, since gpass has been
  7475. * configured. */
  7476. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7477. #endif
  7478. }
  7479. /* Important: using local struct mg_file to test path for
  7480. * is_directory flag. If filep is used, mg_stat() makes it
  7481. * appear as if auth file was opened.
  7482. * TODO(mid): Check if this is still required after rewriting
  7483. * mg_stat */
  7484. } else if (mg_stat(conn, path, &filep->stat)
  7485. && filep->stat.is_directory) {
  7486. mg_snprintf(conn,
  7487. &truncated,
  7488. name,
  7489. sizeof(name),
  7490. "%s/%s",
  7491. path,
  7492. PASSWORDS_FILE_NAME);
  7493. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7494. #if defined(DEBUG)
  7495. /* Don't use mg_cry_internal here, but only a trace, since
  7496. * this is a typical case. It will occur for every directory
  7497. * without a password file. */
  7498. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7499. #endif
  7500. }
  7501. } else {
  7502. /* Try to find .htpasswd in requested directory. */
  7503. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7504. if (e[0] == '/') {
  7505. break;
  7506. }
  7507. }
  7508. mg_snprintf(conn,
  7509. &truncated,
  7510. name,
  7511. sizeof(name),
  7512. "%.*s/%s",
  7513. (int)(e - p),
  7514. p,
  7515. PASSWORDS_FILE_NAME);
  7516. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7517. #if defined(DEBUG)
  7518. /* Don't use mg_cry_internal here, but only a trace, since
  7519. * this is a typical case. It will occur for every directory
  7520. * without a password file. */
  7521. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7522. #endif
  7523. }
  7524. }
  7525. }
  7526. }
  7527. #endif /* NO_FILESYSTEMS */
  7528. /* Parsed Authorization header */
  7529. struct ah {
  7530. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7531. };
  7532. /* Return 1 on success. Always initializes the ah structure. */
  7533. static int
  7534. parse_auth_header(struct mg_connection *conn,
  7535. char *buf,
  7536. size_t buf_size,
  7537. struct ah *ah)
  7538. {
  7539. char *name, *value, *s;
  7540. const char *auth_header;
  7541. uint64_t nonce;
  7542. if (!ah || !conn) {
  7543. return 0;
  7544. }
  7545. (void)memset(ah, 0, sizeof(*ah));
  7546. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7547. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7548. return 0;
  7549. }
  7550. /* Make modifiable copy of the auth header */
  7551. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7552. s = buf;
  7553. /* Parse authorization header */
  7554. for (;;) {
  7555. /* Gobble initial spaces */
  7556. while (isspace((unsigned char)*s)) {
  7557. s++;
  7558. }
  7559. name = skip_quoted(&s, "=", " ", 0);
  7560. /* Value is either quote-delimited, or ends at first comma or space.
  7561. */
  7562. if (s[0] == '\"') {
  7563. s++;
  7564. value = skip_quoted(&s, "\"", " ", '\\');
  7565. if (s[0] == ',') {
  7566. s++;
  7567. }
  7568. } else {
  7569. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7570. * uses spaces */
  7571. }
  7572. if (*name == '\0') {
  7573. break;
  7574. }
  7575. if (!strcmp(name, "username")) {
  7576. ah->user = value;
  7577. } else if (!strcmp(name, "cnonce")) {
  7578. ah->cnonce = value;
  7579. } else if (!strcmp(name, "response")) {
  7580. ah->response = value;
  7581. } else if (!strcmp(name, "uri")) {
  7582. ah->uri = value;
  7583. } else if (!strcmp(name, "qop")) {
  7584. ah->qop = value;
  7585. } else if (!strcmp(name, "nc")) {
  7586. ah->nc = value;
  7587. } else if (!strcmp(name, "nonce")) {
  7588. ah->nonce = value;
  7589. }
  7590. }
  7591. #if !defined(NO_NONCE_CHECK)
  7592. /* Read the nonce from the response. */
  7593. if (ah->nonce == NULL) {
  7594. return 0;
  7595. }
  7596. s = NULL;
  7597. nonce = strtoull(ah->nonce, &s, 10);
  7598. if ((s == NULL) || (*s != 0)) {
  7599. return 0;
  7600. }
  7601. /* Convert the nonce from the client to a number. */
  7602. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7603. /* The converted number corresponds to the time the nounce has been
  7604. * created. This should not be earlier than the server start. */
  7605. /* Server side nonce check is valuable in all situations but one:
  7606. * if the server restarts frequently, but the client should not see
  7607. * that, so the server should accept nonces from previous starts. */
  7608. /* However, the reasonable default is to not accept a nonce from a
  7609. * previous start, so if anyone changed the access rights between
  7610. * two restarts, a new login is required. */
  7611. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7612. /* nonce is from a previous start of the server and no longer valid
  7613. * (replay attack?) */
  7614. return 0;
  7615. }
  7616. /* Check if the nonce is too high, so it has not (yet) been used by the
  7617. * server. */
  7618. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7619. + conn->dom_ctx->nonce_count)) {
  7620. return 0;
  7621. }
  7622. #else
  7623. (void)nonce;
  7624. #endif
  7625. /* CGI needs it as REMOTE_USER */
  7626. if (ah->user != NULL) {
  7627. conn->request_info.remote_user =
  7628. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7629. } else {
  7630. return 0;
  7631. }
  7632. return 1;
  7633. }
  7634. static const char *
  7635. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7636. {
  7637. if (!filep) {
  7638. return NULL;
  7639. }
  7640. if (filep->access.fp != NULL) {
  7641. return fgets(buf, (int)size, filep->access.fp);
  7642. } else {
  7643. return NULL;
  7644. }
  7645. }
  7646. /* Define the initial recursion depth for procesesing htpasswd files that
  7647. * include other htpasswd
  7648. * (or even the same) files. It is not difficult to provide a file or files
  7649. * s.t. they force civetweb
  7650. * to infinitely recurse and then crash.
  7651. */
  7652. #define INITIAL_DEPTH 9
  7653. #if INITIAL_DEPTH <= 0
  7654. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7655. #endif
  7656. #if !defined(NO_FILESYSTEMS)
  7657. struct read_auth_file_struct {
  7658. struct mg_connection *conn;
  7659. struct ah ah;
  7660. const char *domain;
  7661. char buf[256 + 256 + 40];
  7662. const char *f_user;
  7663. const char *f_domain;
  7664. const char *f_ha1;
  7665. };
  7666. static int
  7667. read_auth_file(struct mg_file *filep,
  7668. struct read_auth_file_struct *workdata,
  7669. int depth)
  7670. {
  7671. int is_authorized = 0;
  7672. struct mg_file fp;
  7673. size_t l;
  7674. if (!filep || !workdata || (0 == depth)) {
  7675. return 0;
  7676. }
  7677. /* Loop over passwords file */
  7678. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7679. l = strlen(workdata->buf);
  7680. while (l > 0) {
  7681. if (isspace((unsigned char)workdata->buf[l - 1])
  7682. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7683. l--;
  7684. workdata->buf[l] = 0;
  7685. } else
  7686. break;
  7687. }
  7688. if (l < 1) {
  7689. continue;
  7690. }
  7691. workdata->f_user = workdata->buf;
  7692. if (workdata->f_user[0] == ':') {
  7693. /* user names may not contain a ':' and may not be empty,
  7694. * so lines starting with ':' may be used for a special purpose
  7695. */
  7696. if (workdata->f_user[1] == '#') {
  7697. /* :# is a comment */
  7698. continue;
  7699. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7700. if (mg_fopen(workdata->conn,
  7701. workdata->f_user + 9,
  7702. MG_FOPEN_MODE_READ,
  7703. &fp)) {
  7704. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7705. (void)mg_fclose(
  7706. &fp.access); /* ignore error on read only file */
  7707. /* No need to continue processing files once we have a
  7708. * match, since nothing will reset it back
  7709. * to 0.
  7710. */
  7711. if (is_authorized) {
  7712. return is_authorized;
  7713. }
  7714. } else {
  7715. mg_cry_internal(workdata->conn,
  7716. "%s: cannot open authorization file: %s",
  7717. __func__,
  7718. workdata->buf);
  7719. }
  7720. continue;
  7721. }
  7722. /* everything is invalid for the moment (might change in the
  7723. * future) */
  7724. mg_cry_internal(workdata->conn,
  7725. "%s: syntax error in authorization file: %s",
  7726. __func__,
  7727. workdata->buf);
  7728. continue;
  7729. }
  7730. workdata->f_domain = strchr(workdata->f_user, ':');
  7731. if (workdata->f_domain == NULL) {
  7732. mg_cry_internal(workdata->conn,
  7733. "%s: syntax error in authorization file: %s",
  7734. __func__,
  7735. workdata->buf);
  7736. continue;
  7737. }
  7738. *(char *)(workdata->f_domain) = 0;
  7739. (workdata->f_domain)++;
  7740. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7741. if (workdata->f_ha1 == NULL) {
  7742. mg_cry_internal(workdata->conn,
  7743. "%s: syntax error in authorization file: %s",
  7744. __func__,
  7745. workdata->buf);
  7746. continue;
  7747. }
  7748. *(char *)(workdata->f_ha1) = 0;
  7749. (workdata->f_ha1)++;
  7750. if (!strcmp(workdata->ah.user, workdata->f_user)
  7751. && !strcmp(workdata->domain, workdata->f_domain)) {
  7752. return check_password(workdata->conn->request_info.request_method,
  7753. workdata->f_ha1,
  7754. workdata->ah.uri,
  7755. workdata->ah.nonce,
  7756. workdata->ah.nc,
  7757. workdata->ah.cnonce,
  7758. workdata->ah.qop,
  7759. workdata->ah.response);
  7760. }
  7761. }
  7762. return is_authorized;
  7763. }
  7764. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7765. static int
  7766. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7767. {
  7768. struct read_auth_file_struct workdata;
  7769. char buf[MG_BUF_LEN];
  7770. if (!conn || !conn->dom_ctx) {
  7771. return 0;
  7772. }
  7773. memset(&workdata, 0, sizeof(workdata));
  7774. workdata.conn = conn;
  7775. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7776. return 0;
  7777. }
  7778. if (realm) {
  7779. workdata.domain = realm;
  7780. } else {
  7781. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7782. }
  7783. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7784. }
  7785. /* Public function to check http digest authentication header */
  7786. int
  7787. mg_check_digest_access_authentication(struct mg_connection *conn,
  7788. const char *realm,
  7789. const char *filename)
  7790. {
  7791. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7792. int auth;
  7793. if (!conn || !filename) {
  7794. return -1;
  7795. }
  7796. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7797. return -2;
  7798. }
  7799. auth = authorize(conn, &file, realm);
  7800. mg_fclose(&file.access);
  7801. return auth;
  7802. }
  7803. #endif /* NO_FILESYSTEMS */
  7804. /* Return 1 if request is authorised, 0 otherwise. */
  7805. static int
  7806. check_authorization(struct mg_connection *conn, const char *path)
  7807. {
  7808. #if !defined(NO_FILESYSTEMS)
  7809. char fname[PATH_MAX];
  7810. struct vec uri_vec, filename_vec;
  7811. const char *list;
  7812. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7813. int authorized = 1, truncated;
  7814. if (!conn || !conn->dom_ctx) {
  7815. return 0;
  7816. }
  7817. list = conn->dom_ctx->config[PROTECT_URI];
  7818. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7819. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7820. mg_snprintf(conn,
  7821. &truncated,
  7822. fname,
  7823. sizeof(fname),
  7824. "%.*s",
  7825. (int)filename_vec.len,
  7826. filename_vec.ptr);
  7827. if (truncated
  7828. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7829. mg_cry_internal(conn,
  7830. "%s: cannot open %s: %s",
  7831. __func__,
  7832. fname,
  7833. strerror(errno));
  7834. }
  7835. break;
  7836. }
  7837. }
  7838. if (!is_file_opened(&file.access)) {
  7839. open_auth_file(conn, path, &file);
  7840. }
  7841. if (is_file_opened(&file.access)) {
  7842. authorized = authorize(conn, &file, NULL);
  7843. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7844. }
  7845. return authorized;
  7846. #else
  7847. (void)conn;
  7848. (void)path;
  7849. return 1;
  7850. #endif /* NO_FILESYSTEMS */
  7851. }
  7852. /* Internal function. Assumes conn is valid */
  7853. static void
  7854. send_authorization_request(struct mg_connection *conn, const char *realm)
  7855. {
  7856. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7857. int trunc = 0;
  7858. char buf[128];
  7859. if (!realm) {
  7860. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7861. }
  7862. mg_lock_context(conn->phys_ctx);
  7863. nonce += conn->dom_ctx->nonce_count;
  7864. ++conn->dom_ctx->nonce_count;
  7865. mg_unlock_context(conn->phys_ctx);
  7866. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7867. conn->must_close = 1;
  7868. /* Create 401 response */
  7869. mg_response_header_start(conn, 401);
  7870. send_no_cache_header(conn);
  7871. send_additional_header(conn);
  7872. mg_response_header_add(conn, "Content-Length", "0", -1);
  7873. /* Content for "WWW-Authenticate" header */
  7874. mg_snprintf(conn,
  7875. &trunc,
  7876. buf,
  7877. sizeof(buf),
  7878. "Digest qop=\"auth\", realm=\"%s\", "
  7879. "nonce=\"%" UINT64_FMT "\"",
  7880. realm,
  7881. nonce);
  7882. if (!trunc) {
  7883. /* !trunc should always be true */
  7884. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7885. }
  7886. /* Send all headers */
  7887. mg_response_header_send(conn);
  7888. }
  7889. /* Interface function. Parameters are provided by the user, so do
  7890. * at least some basic checks.
  7891. */
  7892. int
  7893. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7894. const char *realm)
  7895. {
  7896. if (conn && conn->dom_ctx) {
  7897. send_authorization_request(conn, realm);
  7898. return 0;
  7899. }
  7900. return -1;
  7901. }
  7902. #if !defined(NO_FILES)
  7903. static int
  7904. is_authorized_for_put(struct mg_connection *conn)
  7905. {
  7906. if (conn) {
  7907. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7908. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7909. int ret = 0;
  7910. if (passfile != NULL
  7911. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7912. ret = authorize(conn, &file, NULL);
  7913. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7914. }
  7915. return ret;
  7916. }
  7917. return 0;
  7918. }
  7919. #endif
  7920. int
  7921. mg_modify_passwords_file(const char *fname,
  7922. const char *domain,
  7923. const char *user,
  7924. const char *pass)
  7925. {
  7926. int found, i;
  7927. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7928. FILE *fp, *fp2;
  7929. found = 0;
  7930. fp = fp2 = NULL;
  7931. /* Regard empty password as no password - remove user record. */
  7932. if ((pass != NULL) && (pass[0] == '\0')) {
  7933. pass = NULL;
  7934. }
  7935. /* Other arguments must not be empty */
  7936. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7937. return 0;
  7938. }
  7939. /* Using the given file format, user name and domain must not contain
  7940. * ':'
  7941. */
  7942. if (strchr(user, ':') != NULL) {
  7943. return 0;
  7944. }
  7945. if (strchr(domain, ':') != NULL) {
  7946. return 0;
  7947. }
  7948. /* Do not allow control characters like newline in user name and domain.
  7949. * Do not allow excessively long names either. */
  7950. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7951. if (iscntrl((unsigned char)user[i])) {
  7952. return 0;
  7953. }
  7954. }
  7955. if (user[i]) {
  7956. return 0;
  7957. }
  7958. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7959. if (iscntrl((unsigned char)domain[i])) {
  7960. return 0;
  7961. }
  7962. }
  7963. if (domain[i]) {
  7964. return 0;
  7965. }
  7966. /* The maximum length of the path to the password file is limited */
  7967. if ((strlen(fname) + 4) >= PATH_MAX) {
  7968. return 0;
  7969. }
  7970. /* Create a temporary file name. Length has been checked before. */
  7971. strcpy(tmp, fname);
  7972. strcat(tmp, ".tmp");
  7973. /* Create the file if does not exist */
  7974. /* Use of fopen here is OK, since fname is only ASCII */
  7975. if ((fp = fopen(fname, "a+")) != NULL) {
  7976. (void)fclose(fp);
  7977. }
  7978. /* Open the given file and temporary file */
  7979. if ((fp = fopen(fname, "r")) == NULL) {
  7980. return 0;
  7981. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7982. fclose(fp);
  7983. return 0;
  7984. }
  7985. /* Copy the stuff to temporary file */
  7986. while (fgets(line, sizeof(line), fp) != NULL) {
  7987. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7988. continue;
  7989. }
  7990. u[255] = 0;
  7991. d[255] = 0;
  7992. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7993. found++;
  7994. if (pass != NULL) {
  7995. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7996. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7997. }
  7998. } else {
  7999. fprintf(fp2, "%s", line);
  8000. }
  8001. }
  8002. /* If new user, just add it */
  8003. if (!found && (pass != NULL)) {
  8004. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  8005. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  8006. }
  8007. /* Close files */
  8008. fclose(fp);
  8009. fclose(fp2);
  8010. /* Put the temp file in place of real file */
  8011. IGNORE_UNUSED_RESULT(remove(fname));
  8012. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  8013. return 1;
  8014. }
  8015. static int
  8016. is_valid_port(unsigned long port)
  8017. {
  8018. return (port <= 0xffff);
  8019. }
  8020. static int
  8021. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8022. {
  8023. struct addrinfo hints, *res, *ressave;
  8024. int func_ret = 0;
  8025. int gai_ret;
  8026. memset(&hints, 0, sizeof(struct addrinfo));
  8027. hints.ai_family = af;
  8028. if (!resolve_src) {
  8029. hints.ai_flags = AI_NUMERICHOST;
  8030. }
  8031. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8032. if (gai_ret != 0) {
  8033. /* gai_strerror could be used to convert gai_ret to a string */
  8034. /* POSIX return values: see
  8035. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8036. */
  8037. /* Windows return values: see
  8038. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8039. */
  8040. return 0;
  8041. }
  8042. ressave = res;
  8043. while (res) {
  8044. if ((dstlen >= (size_t)res->ai_addrlen)
  8045. && (res->ai_addr->sa_family == af)) {
  8046. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8047. func_ret = 1;
  8048. }
  8049. res = res->ai_next;
  8050. }
  8051. freeaddrinfo(ressave);
  8052. return func_ret;
  8053. }
  8054. static int
  8055. connect_socket(struct mg_context *ctx /* may be NULL */,
  8056. const char *host,
  8057. int port,
  8058. int use_ssl,
  8059. char *ebuf,
  8060. size_t ebuf_len,
  8061. SOCKET *sock /* output: socket, must not be NULL */,
  8062. union usa *sa /* output: socket address, must not be NULL */
  8063. )
  8064. {
  8065. int ip_ver = 0;
  8066. int conn_ret = -1;
  8067. int sockerr = 0;
  8068. *sock = INVALID_SOCKET;
  8069. memset(sa, 0, sizeof(*sa));
  8070. if (ebuf_len > 0) {
  8071. *ebuf = 0;
  8072. }
  8073. if (host == NULL) {
  8074. mg_snprintf(NULL,
  8075. NULL, /* No truncation check for ebuf */
  8076. ebuf,
  8077. ebuf_len,
  8078. "%s",
  8079. "NULL host");
  8080. return 0;
  8081. }
  8082. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8083. mg_snprintf(NULL,
  8084. NULL, /* No truncation check for ebuf */
  8085. ebuf,
  8086. ebuf_len,
  8087. "%s",
  8088. "invalid port");
  8089. return 0;
  8090. }
  8091. #if !defined(NO_SSL)
  8092. #if !defined(NO_SSL_DL)
  8093. #if defined(OPENSSL_API_1_1)
  8094. if (use_ssl && (TLS_client_method == NULL)) {
  8095. mg_snprintf(NULL,
  8096. NULL, /* No truncation check for ebuf */
  8097. ebuf,
  8098. ebuf_len,
  8099. "%s",
  8100. "SSL is not initialized");
  8101. return 0;
  8102. }
  8103. #else
  8104. if (use_ssl && (SSLv23_client_method == NULL)) {
  8105. mg_snprintf(NULL,
  8106. NULL, /* No truncation check for ebuf */
  8107. ebuf,
  8108. ebuf_len,
  8109. "%s",
  8110. "SSL is not initialized");
  8111. return 0;
  8112. }
  8113. #endif /* OPENSSL_API_1_1 */
  8114. #else
  8115. (void)use_ssl;
  8116. #endif /* NO_SSL_DL */
  8117. #else
  8118. (void)use_ssl;
  8119. #endif /* !defined(NO_SSL) */
  8120. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8121. sa->sin.sin_port = htons((uint16_t)port);
  8122. ip_ver = 4;
  8123. #if defined(USE_IPV6)
  8124. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8125. sa->sin6.sin6_port = htons((uint16_t)port);
  8126. ip_ver = 6;
  8127. } else if (host[0] == '[') {
  8128. /* While getaddrinfo on Windows will work with [::1],
  8129. * getaddrinfo on Linux only works with ::1 (without []). */
  8130. size_t l = strlen(host + 1);
  8131. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8132. if (h) {
  8133. h[l - 1] = 0;
  8134. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8135. sa->sin6.sin6_port = htons((uint16_t)port);
  8136. ip_ver = 6;
  8137. }
  8138. mg_free(h);
  8139. }
  8140. #endif
  8141. }
  8142. if (ip_ver == 0) {
  8143. mg_snprintf(NULL,
  8144. NULL, /* No truncation check for ebuf */
  8145. ebuf,
  8146. ebuf_len,
  8147. "%s",
  8148. "host not found");
  8149. return 0;
  8150. }
  8151. if (ip_ver == 4) {
  8152. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8153. }
  8154. #if defined(USE_IPV6)
  8155. else if (ip_ver == 6) {
  8156. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8157. }
  8158. #endif
  8159. if (*sock == INVALID_SOCKET) {
  8160. mg_snprintf(NULL,
  8161. NULL, /* No truncation check for ebuf */
  8162. ebuf,
  8163. ebuf_len,
  8164. "socket(): %s",
  8165. strerror(ERRNO));
  8166. return 0;
  8167. }
  8168. if (0 != set_non_blocking_mode(*sock)) {
  8169. mg_snprintf(NULL,
  8170. NULL, /* No truncation check for ebuf */
  8171. ebuf,
  8172. ebuf_len,
  8173. "Cannot set socket to non-blocking: %s",
  8174. strerror(ERRNO));
  8175. closesocket(*sock);
  8176. *sock = INVALID_SOCKET;
  8177. return 0;
  8178. }
  8179. set_close_on_exec(*sock, NULL, ctx);
  8180. if (ip_ver == 4) {
  8181. /* connected with IPv4 */
  8182. conn_ret = connect(*sock,
  8183. (struct sockaddr *)((void *)&sa->sin),
  8184. sizeof(sa->sin));
  8185. }
  8186. #if defined(USE_IPV6)
  8187. else if (ip_ver == 6) {
  8188. /* connected with IPv6 */
  8189. conn_ret = connect(*sock,
  8190. (struct sockaddr *)((void *)&sa->sin6),
  8191. sizeof(sa->sin6));
  8192. }
  8193. #endif
  8194. if (conn_ret != 0) {
  8195. sockerr = ERRNO;
  8196. }
  8197. #if defined(_WIN32)
  8198. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8199. #else
  8200. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8201. #endif
  8202. /* Data for getsockopt */
  8203. void *psockerr = &sockerr;
  8204. int ret;
  8205. #if defined(_WIN32)
  8206. int len = (int)sizeof(sockerr);
  8207. #else
  8208. socklen_t len = (socklen_t)sizeof(sockerr);
  8209. #endif
  8210. /* Data for poll */
  8211. struct mg_pollfd pfd[1];
  8212. int pollres;
  8213. int ms_wait = 10000; /* 10 second timeout */
  8214. stop_flag_t nonstop;
  8215. STOP_FLAG_ASSIGN(&nonstop, 0);
  8216. /* For a non-blocking socket, the connect sequence is:
  8217. * 1) call connect (will not block)
  8218. * 2) wait until the socket is ready for writing (select or poll)
  8219. * 3) check connection state with getsockopt
  8220. */
  8221. pfd[0].fd = *sock;
  8222. pfd[0].events = POLLOUT;
  8223. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8224. if (pollres != 1) {
  8225. /* Not connected */
  8226. mg_snprintf(NULL,
  8227. NULL, /* No truncation check for ebuf */
  8228. ebuf,
  8229. ebuf_len,
  8230. "connect(%s:%d): timeout",
  8231. host,
  8232. port);
  8233. closesocket(*sock);
  8234. *sock = INVALID_SOCKET;
  8235. return 0;
  8236. }
  8237. #if defined(_WIN32)
  8238. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8239. #else
  8240. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8241. #endif
  8242. if ((ret == 0) && (sockerr == 0)) {
  8243. conn_ret = 0;
  8244. }
  8245. }
  8246. if (conn_ret != 0) {
  8247. /* Not connected */
  8248. mg_snprintf(NULL,
  8249. NULL, /* No truncation check for ebuf */
  8250. ebuf,
  8251. ebuf_len,
  8252. "connect(%s:%d): error %s",
  8253. host,
  8254. port,
  8255. strerror(sockerr));
  8256. closesocket(*sock);
  8257. *sock = INVALID_SOCKET;
  8258. return 0;
  8259. }
  8260. return 1;
  8261. }
  8262. int
  8263. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8264. {
  8265. static const char *dont_escape = "._-$,;~()";
  8266. static const char *hex = "0123456789abcdef";
  8267. char *pos = dst;
  8268. const char *end = dst + dst_len - 1;
  8269. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8270. if (isalnum((unsigned char)*src)
  8271. || (strchr(dont_escape, *src) != NULL)) {
  8272. *pos = *src;
  8273. } else if (pos + 2 < end) {
  8274. pos[0] = '%';
  8275. pos[1] = hex[(unsigned char)*src >> 4];
  8276. pos[2] = hex[(unsigned char)*src & 0xf];
  8277. pos += 2;
  8278. } else {
  8279. break;
  8280. }
  8281. }
  8282. *pos = '\0';
  8283. return (*src == '\0') ? (int)(pos - dst) : -1;
  8284. }
  8285. /* Return 0 on success, non-zero if an error occurs. */
  8286. static int
  8287. print_dir_entry(struct de *de)
  8288. {
  8289. size_t namesize, escsize, i;
  8290. char *href, *esc, *p;
  8291. char size[64], mod[64];
  8292. #if defined(REENTRANT_TIME)
  8293. struct tm _tm;
  8294. struct tm *tm = &_tm;
  8295. #else
  8296. struct tm *tm;
  8297. #endif
  8298. /* Estimate worst case size for encoding and escaping */
  8299. namesize = strlen(de->file_name) + 1;
  8300. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8301. href = (char *)mg_malloc(namesize * 3 + escsize);
  8302. if (href == NULL) {
  8303. return -1;
  8304. }
  8305. mg_url_encode(de->file_name, href, namesize * 3);
  8306. esc = NULL;
  8307. if (escsize > 0) {
  8308. /* HTML escaping needed */
  8309. esc = href + namesize * 3;
  8310. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8311. mg_strlcpy(p, de->file_name + i, 2);
  8312. if (*p == '&') {
  8313. strcpy(p, "&amp;");
  8314. } else if (*p == '<') {
  8315. strcpy(p, "&lt;");
  8316. } else if (*p == '>') {
  8317. strcpy(p, "&gt;");
  8318. }
  8319. }
  8320. }
  8321. if (de->file.is_directory) {
  8322. mg_snprintf(de->conn,
  8323. NULL, /* Buffer is big enough */
  8324. size,
  8325. sizeof(size),
  8326. "%s",
  8327. "[DIRECTORY]");
  8328. } else {
  8329. /* We use (signed) cast below because MSVC 6 compiler cannot
  8330. * convert unsigned __int64 to double. Sigh. */
  8331. if (de->file.size < 1024) {
  8332. mg_snprintf(de->conn,
  8333. NULL, /* Buffer is big enough */
  8334. size,
  8335. sizeof(size),
  8336. "%d",
  8337. (int)de->file.size);
  8338. } else if (de->file.size < 0x100000) {
  8339. mg_snprintf(de->conn,
  8340. NULL, /* Buffer is big enough */
  8341. size,
  8342. sizeof(size),
  8343. "%.1fk",
  8344. (double)de->file.size / 1024.0);
  8345. } else if (de->file.size < 0x40000000) {
  8346. mg_snprintf(de->conn,
  8347. NULL, /* Buffer is big enough */
  8348. size,
  8349. sizeof(size),
  8350. "%.1fM",
  8351. (double)de->file.size / 1048576);
  8352. } else {
  8353. mg_snprintf(de->conn,
  8354. NULL, /* Buffer is big enough */
  8355. size,
  8356. sizeof(size),
  8357. "%.1fG",
  8358. (double)de->file.size / 1073741824);
  8359. }
  8360. }
  8361. /* Note: mg_snprintf will not cause a buffer overflow above.
  8362. * So, string truncation checks are not required here. */
  8363. #if defined(REENTRANT_TIME)
  8364. localtime_r(&de->file.last_modified, tm);
  8365. #else
  8366. tm = localtime(&de->file.last_modified);
  8367. #endif
  8368. if (tm != NULL) {
  8369. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8370. } else {
  8371. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8372. mod[sizeof(mod) - 1] = '\0';
  8373. }
  8374. mg_printf(de->conn,
  8375. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8376. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8377. href,
  8378. de->file.is_directory ? "/" : "",
  8379. esc ? esc : de->file_name,
  8380. de->file.is_directory ? "/" : "",
  8381. mod,
  8382. size);
  8383. mg_free(href);
  8384. return 0;
  8385. }
  8386. /* This function is called from send_directory() and used for
  8387. * sorting directory entries by size, or name, or modification time.
  8388. * On windows, __cdecl specification is needed in case if project is built
  8389. * with __stdcall convention. qsort always requires __cdels callback. */
  8390. static int WINCDECL
  8391. compare_dir_entries(const void *p1, const void *p2)
  8392. {
  8393. if (p1 && p2) {
  8394. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8395. const char *query_string = a->conn->request_info.query_string;
  8396. int cmp_result = 0;
  8397. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8398. query_string = "n";
  8399. }
  8400. if (a->file.is_directory && !b->file.is_directory) {
  8401. return -1; /* Always put directories on top */
  8402. } else if (!a->file.is_directory && b->file.is_directory) {
  8403. return 1; /* Always put directories on top */
  8404. } else if (*query_string == 'n') {
  8405. cmp_result = strcmp(a->file_name, b->file_name);
  8406. } else if (*query_string == 's') {
  8407. cmp_result = (a->file.size == b->file.size)
  8408. ? 0
  8409. : ((a->file.size > b->file.size) ? 1 : -1);
  8410. } else if (*query_string == 'd') {
  8411. cmp_result =
  8412. (a->file.last_modified == b->file.last_modified)
  8413. ? 0
  8414. : ((a->file.last_modified > b->file.last_modified) ? 1
  8415. : -1);
  8416. }
  8417. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8418. }
  8419. return 0;
  8420. }
  8421. static int
  8422. must_hide_file(struct mg_connection *conn, const char *path)
  8423. {
  8424. if (conn && conn->dom_ctx) {
  8425. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8426. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8427. return (match_prefix_strlen(pw_pattern, path) > 0)
  8428. || (match_prefix_strlen(pattern, path) > 0);
  8429. }
  8430. return 0;
  8431. }
  8432. #if !defined(NO_FILESYSTEMS)
  8433. static int
  8434. scan_directory(struct mg_connection *conn,
  8435. const char *dir,
  8436. void *data,
  8437. int (*cb)(struct de *, void *))
  8438. {
  8439. char path[PATH_MAX];
  8440. struct dirent *dp;
  8441. DIR *dirp;
  8442. struct de de;
  8443. int truncated;
  8444. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8445. return 0;
  8446. } else {
  8447. de.conn = conn;
  8448. while ((dp = mg_readdir(dirp)) != NULL) {
  8449. /* Do not show current dir and hidden files */
  8450. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8451. || must_hide_file(conn, dp->d_name)) {
  8452. continue;
  8453. }
  8454. mg_snprintf(
  8455. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8456. /* If we don't memset stat structure to zero, mtime will have
  8457. * garbage and strftime() will segfault later on in
  8458. * print_dir_entry(). memset is required only if mg_stat()
  8459. * fails. For more details, see
  8460. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8461. memset(&de.file, 0, sizeof(de.file));
  8462. if (truncated) {
  8463. /* If the path is not complete, skip processing. */
  8464. continue;
  8465. }
  8466. if (!mg_stat(conn, path, &de.file)) {
  8467. mg_cry_internal(conn,
  8468. "%s: mg_stat(%s) failed: %s",
  8469. __func__,
  8470. path,
  8471. strerror(ERRNO));
  8472. }
  8473. de.file_name = dp->d_name;
  8474. if (cb(&de, data)) {
  8475. /* stopped */
  8476. break;
  8477. }
  8478. }
  8479. (void)mg_closedir(dirp);
  8480. }
  8481. return 1;
  8482. }
  8483. #endif /* NO_FILESYSTEMS */
  8484. #if !defined(NO_FILES)
  8485. static int
  8486. remove_directory(struct mg_connection *conn, const char *dir)
  8487. {
  8488. char path[PATH_MAX];
  8489. struct dirent *dp;
  8490. DIR *dirp;
  8491. struct de de;
  8492. int truncated;
  8493. int ok = 1;
  8494. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8495. return 0;
  8496. } else {
  8497. de.conn = conn;
  8498. while ((dp = mg_readdir(dirp)) != NULL) {
  8499. /* Do not show current dir (but show hidden files as they will
  8500. * also be removed) */
  8501. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8502. continue;
  8503. }
  8504. mg_snprintf(
  8505. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8506. /* If we don't memset stat structure to zero, mtime will have
  8507. * garbage and strftime() will segfault later on in
  8508. * print_dir_entry(). memset is required only if mg_stat()
  8509. * fails. For more details, see
  8510. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8511. memset(&de.file, 0, sizeof(de.file));
  8512. if (truncated) {
  8513. /* Do not delete anything shorter */
  8514. ok = 0;
  8515. continue;
  8516. }
  8517. if (!mg_stat(conn, path, &de.file)) {
  8518. mg_cry_internal(conn,
  8519. "%s: mg_stat(%s) failed: %s",
  8520. __func__,
  8521. path,
  8522. strerror(ERRNO));
  8523. ok = 0;
  8524. }
  8525. if (de.file.is_directory) {
  8526. if (remove_directory(conn, path) == 0) {
  8527. ok = 0;
  8528. }
  8529. } else {
  8530. /* This will fail file is the file is in memory */
  8531. if (mg_remove(conn, path) == 0) {
  8532. ok = 0;
  8533. }
  8534. }
  8535. }
  8536. (void)mg_closedir(dirp);
  8537. IGNORE_UNUSED_RESULT(rmdir(dir));
  8538. }
  8539. return ok;
  8540. }
  8541. #endif
  8542. struct dir_scan_data {
  8543. struct de *entries;
  8544. size_t num_entries;
  8545. size_t arr_size;
  8546. };
  8547. #if !defined(NO_FILESYSTEMS)
  8548. static int
  8549. dir_scan_callback(struct de *de, void *data)
  8550. {
  8551. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8552. struct de *entries = dsd->entries;
  8553. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8554. /* Here "entries" is a temporary pointer and can be replaced,
  8555. * "dsd->entries" is the original pointer */
  8556. entries =
  8557. (struct de *)mg_realloc(entries,
  8558. dsd->arr_size * 2 * sizeof(entries[0]));
  8559. if (entries == NULL) {
  8560. /* stop scan */
  8561. return 1;
  8562. }
  8563. dsd->entries = entries;
  8564. dsd->arr_size *= 2;
  8565. }
  8566. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8567. if (entries[dsd->num_entries].file_name == NULL) {
  8568. /* stop scan */
  8569. return 1;
  8570. }
  8571. entries[dsd->num_entries].file = de->file;
  8572. entries[dsd->num_entries].conn = de->conn;
  8573. dsd->num_entries++;
  8574. return 0;
  8575. }
  8576. static void
  8577. handle_directory_request(struct mg_connection *conn, const char *dir)
  8578. {
  8579. size_t i;
  8580. int sort_direction;
  8581. struct dir_scan_data data = {NULL, 0, 128};
  8582. char date[64], *esc, *p;
  8583. const char *title;
  8584. time_t curtime = time(NULL);
  8585. if (!conn) {
  8586. return;
  8587. }
  8588. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8589. mg_send_http_error(conn,
  8590. 500,
  8591. "Error: Cannot open directory\nopendir(%s): %s",
  8592. dir,
  8593. strerror(ERRNO));
  8594. return;
  8595. }
  8596. gmt_time_string(date, sizeof(date), &curtime);
  8597. esc = NULL;
  8598. title = conn->request_info.local_uri;
  8599. if (title[strcspn(title, "&<>")]) {
  8600. /* HTML escaping needed */
  8601. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8602. if (esc) {
  8603. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8604. mg_strlcpy(p, title + i, 2);
  8605. if (*p == '&') {
  8606. strcpy(p, "&amp;");
  8607. } else if (*p == '<') {
  8608. strcpy(p, "&lt;");
  8609. } else if (*p == '>') {
  8610. strcpy(p, "&gt;");
  8611. }
  8612. }
  8613. } else {
  8614. title = "";
  8615. }
  8616. }
  8617. sort_direction = ((conn->request_info.query_string != NULL)
  8618. && (conn->request_info.query_string[0] != '\0')
  8619. && (conn->request_info.query_string[1] == 'd'))
  8620. ? 'a'
  8621. : 'd';
  8622. conn->must_close = 1;
  8623. /* Create 200 OK response */
  8624. mg_response_header_start(conn, 200);
  8625. send_static_cache_header(conn);
  8626. send_additional_header(conn);
  8627. mg_response_header_add(conn,
  8628. "Content-Type",
  8629. "text/html; charset=utf-8",
  8630. -1);
  8631. /* Send all headers */
  8632. mg_response_header_send(conn);
  8633. /* Body */
  8634. mg_printf(conn,
  8635. "<html><head><title>Index of %s</title>"
  8636. "<style>th {text-align: left;}</style></head>"
  8637. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8638. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8639. "<th><a href=\"?d%c\">Modified</a></th>"
  8640. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8641. "<tr><td colspan=\"3\"><hr></td></tr>",
  8642. esc ? esc : title,
  8643. esc ? esc : title,
  8644. sort_direction,
  8645. sort_direction,
  8646. sort_direction);
  8647. mg_free(esc);
  8648. /* Print first entry - link to a parent directory */
  8649. mg_printf(conn,
  8650. "<tr><td><a href=\"%s\">%s</a></td>"
  8651. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8652. "..",
  8653. "Parent directory",
  8654. "-",
  8655. "-");
  8656. /* Sort and print directory entries */
  8657. if (data.entries != NULL) {
  8658. qsort(data.entries,
  8659. data.num_entries,
  8660. sizeof(data.entries[0]),
  8661. compare_dir_entries);
  8662. for (i = 0; i < data.num_entries; i++) {
  8663. print_dir_entry(&data.entries[i]);
  8664. mg_free(data.entries[i].file_name);
  8665. }
  8666. mg_free(data.entries);
  8667. }
  8668. mg_printf(conn, "%s", "</table></pre></body></html>");
  8669. conn->status_code = 200;
  8670. }
  8671. #endif /* NO_FILESYSTEMS */
  8672. /* Send len bytes from the opened file to the client. */
  8673. static void
  8674. send_file_data(struct mg_connection *conn,
  8675. struct mg_file *filep,
  8676. int64_t offset,
  8677. int64_t len)
  8678. {
  8679. char buf[MG_BUF_LEN];
  8680. int to_read, num_read, num_written;
  8681. int64_t size;
  8682. if (!filep || !conn) {
  8683. return;
  8684. }
  8685. /* Sanity check the offset */
  8686. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8687. : (int64_t)(filep->stat.size);
  8688. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8689. if (len > 0 && filep->access.fp != NULL) {
  8690. /* file stored on disk */
  8691. #if defined(__linux__)
  8692. /* sendfile is only available for Linux */
  8693. if ((conn->ssl == 0) && (conn->throttle == 0)
  8694. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8695. "yes"))) {
  8696. off_t sf_offs = (off_t)offset;
  8697. ssize_t sf_sent;
  8698. int sf_file = fileno(filep->access.fp);
  8699. int loop_cnt = 0;
  8700. do {
  8701. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8702. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8703. size_t sf_tosend =
  8704. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8705. sf_sent =
  8706. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8707. if (sf_sent > 0) {
  8708. len -= sf_sent;
  8709. offset += sf_sent;
  8710. } else if (loop_cnt == 0) {
  8711. /* This file can not be sent using sendfile.
  8712. * This might be the case for pseudo-files in the
  8713. * /sys/ and /proc/ file system.
  8714. * Use the regular user mode copy code instead. */
  8715. break;
  8716. } else if (sf_sent == 0) {
  8717. /* No error, but 0 bytes sent. May be EOF? */
  8718. return;
  8719. }
  8720. loop_cnt++;
  8721. } while ((len > 0) && (sf_sent >= 0));
  8722. if (sf_sent > 0) {
  8723. return; /* OK */
  8724. }
  8725. /* sf_sent<0 means error, thus fall back to the classic way */
  8726. /* This is always the case, if sf_file is not a "normal" file,
  8727. * e.g., for sending data from the output of a CGI process. */
  8728. offset = (int64_t)sf_offs;
  8729. }
  8730. #endif
  8731. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8732. mg_cry_internal(conn,
  8733. "%s: fseeko() failed: %s",
  8734. __func__,
  8735. strerror(ERRNO));
  8736. mg_send_http_error(
  8737. conn,
  8738. 500,
  8739. "%s",
  8740. "Error: Unable to access file at requested position.");
  8741. } else {
  8742. while (len > 0) {
  8743. /* Calculate how much to read from the file in the buffer */
  8744. to_read = sizeof(buf);
  8745. if ((int64_t)to_read > len) {
  8746. to_read = (int)len;
  8747. }
  8748. /* Read from file, exit the loop on error */
  8749. if ((num_read =
  8750. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8751. <= 0) {
  8752. break;
  8753. }
  8754. /* Send read bytes to the client, exit the loop on error */
  8755. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8756. != num_read) {
  8757. break;
  8758. }
  8759. /* Both read and were successful, adjust counters */
  8760. len -= num_written;
  8761. }
  8762. }
  8763. }
  8764. }
  8765. static int
  8766. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8767. {
  8768. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8769. }
  8770. static void
  8771. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8772. {
  8773. if ((filestat != NULL) && (buf != NULL)) {
  8774. mg_snprintf(NULL,
  8775. NULL, /* All calls to construct_etag use 64 byte buffer */
  8776. buf,
  8777. buf_len,
  8778. "\"%lx.%" INT64_FMT "\"",
  8779. (unsigned long)filestat->last_modified,
  8780. filestat->size);
  8781. }
  8782. }
  8783. static void
  8784. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8785. {
  8786. if (filep != NULL && filep->fp != NULL) {
  8787. #if defined(_WIN32)
  8788. (void)conn; /* Unused. */
  8789. #else
  8790. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8791. mg_cry_internal(conn,
  8792. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8793. __func__,
  8794. strerror(ERRNO));
  8795. }
  8796. #endif
  8797. }
  8798. }
  8799. #if defined(USE_ZLIB)
  8800. #include "mod_zlib.inl"
  8801. #endif
  8802. #if !defined(NO_FILESYSTEMS)
  8803. static void
  8804. handle_static_file_request(struct mg_connection *conn,
  8805. const char *path,
  8806. struct mg_file *filep,
  8807. const char *mime_type,
  8808. const char *additional_headers)
  8809. {
  8810. char lm[64], etag[64];
  8811. char range[128]; /* large enough, so there will be no overflow */
  8812. const char *range_hdr;
  8813. int64_t cl, r1, r2;
  8814. struct vec mime_vec;
  8815. int n, truncated;
  8816. char gz_path[PATH_MAX];
  8817. const char *encoding = 0;
  8818. const char *origin_hdr;
  8819. const char *cors_orig_cfg;
  8820. const char *cors1, *cors2;
  8821. int is_head_request;
  8822. #if defined(USE_ZLIB)
  8823. /* Compression is allowed, unless there is a reason not to use
  8824. * compression. If the file is already compressed, too small or a
  8825. * "range" request was made, on the fly compression is not possible. */
  8826. int allow_on_the_fly_compression = 1;
  8827. #endif
  8828. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8829. return;
  8830. }
  8831. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8832. if (mime_type == NULL) {
  8833. get_mime_type(conn, path, &mime_vec);
  8834. } else {
  8835. mime_vec.ptr = mime_type;
  8836. mime_vec.len = strlen(mime_type);
  8837. }
  8838. if (filep->stat.size > INT64_MAX) {
  8839. mg_send_http_error(conn,
  8840. 500,
  8841. "Error: File size is too large to send\n%" INT64_FMT,
  8842. filep->stat.size);
  8843. return;
  8844. }
  8845. cl = (int64_t)filep->stat.size;
  8846. conn->status_code = 200;
  8847. range[0] = '\0';
  8848. #if defined(USE_ZLIB)
  8849. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8850. * it's important to rewrite the filename after resolving
  8851. * the mime type from it, to preserve the actual file's type */
  8852. if (!conn->accept_gzip) {
  8853. allow_on_the_fly_compression = 0;
  8854. }
  8855. #endif
  8856. /* Check if there is a range header */
  8857. range_hdr = mg_get_header(conn, "Range");
  8858. /* For gzipped files, add *.gz */
  8859. if (filep->stat.is_gzipped) {
  8860. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8861. if (truncated) {
  8862. mg_send_http_error(conn,
  8863. 500,
  8864. "Error: Path of zipped file too long (%s)",
  8865. path);
  8866. return;
  8867. }
  8868. path = gz_path;
  8869. encoding = "gzip";
  8870. #if defined(USE_ZLIB)
  8871. /* File is already compressed. No "on the fly" compression. */
  8872. allow_on_the_fly_compression = 0;
  8873. #endif
  8874. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8875. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8876. struct mg_file_stat file_stat;
  8877. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8878. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8879. && !file_stat.is_directory) {
  8880. file_stat.is_gzipped = 1;
  8881. filep->stat = file_stat;
  8882. cl = (int64_t)filep->stat.size;
  8883. path = gz_path;
  8884. encoding = "gzip";
  8885. #if defined(USE_ZLIB)
  8886. /* File is already compressed. No "on the fly" compression. */
  8887. allow_on_the_fly_compression = 0;
  8888. #endif
  8889. }
  8890. }
  8891. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8892. mg_send_http_error(conn,
  8893. 500,
  8894. "Error: Cannot open file\nfopen(%s): %s",
  8895. path,
  8896. strerror(ERRNO));
  8897. return;
  8898. }
  8899. fclose_on_exec(&filep->access, conn);
  8900. /* If "Range" request was made: parse header, send only selected part
  8901. * of the file. */
  8902. r1 = r2 = 0;
  8903. if ((range_hdr != NULL)
  8904. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8905. && (r2 >= 0)) {
  8906. /* actually, range requests don't play well with a pre-gzipped
  8907. * file (since the range is specified in the uncompressed space) */
  8908. if (filep->stat.is_gzipped) {
  8909. mg_send_http_error(
  8910. conn,
  8911. 416, /* 416 = Range Not Satisfiable */
  8912. "%s",
  8913. "Error: Range requests in gzipped files are not supported");
  8914. (void)mg_fclose(
  8915. &filep->access); /* ignore error on read only file */
  8916. return;
  8917. }
  8918. conn->status_code = 206;
  8919. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8920. mg_snprintf(conn,
  8921. NULL, /* range buffer is big enough */
  8922. range,
  8923. sizeof(range),
  8924. "bytes "
  8925. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8926. r1,
  8927. r1 + cl - 1,
  8928. filep->stat.size);
  8929. #if defined(USE_ZLIB)
  8930. /* Do not compress ranges. */
  8931. allow_on_the_fly_compression = 0;
  8932. #endif
  8933. }
  8934. /* Do not compress small files. Small files do not benefit from file
  8935. * compression, but there is still some overhead. */
  8936. #if defined(USE_ZLIB)
  8937. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8938. /* File is below the size limit. */
  8939. allow_on_the_fly_compression = 0;
  8940. }
  8941. #endif
  8942. /* Standard CORS header */
  8943. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8944. origin_hdr = mg_get_header(conn, "Origin");
  8945. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8946. /* Cross-origin resource sharing (CORS), see
  8947. * http://www.html5rocks.com/en/tutorials/cors/,
  8948. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8949. * -
  8950. * preflight is not supported for files. */
  8951. cors1 = "Access-Control-Allow-Origin";
  8952. cors2 = cors_orig_cfg;
  8953. } else {
  8954. cors1 = cors2 = "";
  8955. }
  8956. /* Prepare Etag, and Last-Modified headers. */
  8957. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8958. construct_etag(etag, sizeof(etag), &filep->stat);
  8959. /* Create 2xx (200, 206) response */
  8960. mg_response_header_start(conn, conn->status_code);
  8961. send_static_cache_header(conn);
  8962. send_additional_header(conn);
  8963. mg_response_header_add(conn,
  8964. "Content-Type",
  8965. mime_vec.ptr,
  8966. (int)mime_vec.len);
  8967. if (cors1[0] != 0) {
  8968. mg_response_header_add(conn, cors1, cors2, -1);
  8969. }
  8970. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8971. mg_response_header_add(conn, "Etag", etag, -1);
  8972. #if defined(USE_ZLIB)
  8973. /* On the fly compression allowed */
  8974. if (allow_on_the_fly_compression) {
  8975. /* For on the fly compression, we don't know the content size in
  8976. * advance, so we have to use chunked encoding */
  8977. encoding = "gzip";
  8978. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8979. /* HTTP/2 is always using "chunks" (frames) */
  8980. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8981. }
  8982. } else
  8983. #endif
  8984. {
  8985. /* Without on-the-fly compression, we know the content-length
  8986. * and we can use ranges (with on-the-fly compression we cannot).
  8987. * So we send these response headers only in this case. */
  8988. char len[32];
  8989. int trunc = 0;
  8990. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8991. if (!trunc) {
  8992. mg_response_header_add(conn, "Content-Length", len, -1);
  8993. }
  8994. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8995. }
  8996. if (encoding) {
  8997. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8998. }
  8999. if (range[0] != 0) {
  9000. mg_response_header_add(conn, "Content-Range", range, -1);
  9001. }
  9002. /* The code above does not add any header starting with X- to make
  9003. * sure no one of the additional_headers is included twice */
  9004. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9005. mg_response_header_add_lines(conn, additional_headers);
  9006. }
  9007. /* Send all headers */
  9008. mg_response_header_send(conn);
  9009. if (!is_head_request) {
  9010. #if defined(USE_ZLIB)
  9011. if (allow_on_the_fly_compression) {
  9012. /* Compress and send */
  9013. send_compressed_data(conn, filep);
  9014. } else
  9015. #endif
  9016. {
  9017. /* Send file directly */
  9018. send_file_data(conn, filep, r1, cl);
  9019. }
  9020. }
  9021. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9022. }
  9023. int
  9024. mg_send_file_body(struct mg_connection *conn, const char *path)
  9025. {
  9026. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9027. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9028. return -1;
  9029. }
  9030. fclose_on_exec(&file.access, conn);
  9031. send_file_data(conn, &file, 0, INT64_MAX);
  9032. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9033. return 0; /* >= 0 for OK */
  9034. }
  9035. #endif /* NO_FILESYSTEMS */
  9036. #if !defined(NO_CACHING)
  9037. /* Return True if we should reply 304 Not Modified. */
  9038. static int
  9039. is_not_modified(const struct mg_connection *conn,
  9040. const struct mg_file_stat *filestat)
  9041. {
  9042. char etag[64];
  9043. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9044. const char *inm = mg_get_header(conn, "If-None-Match");
  9045. construct_etag(etag, sizeof(etag), filestat);
  9046. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9047. || ((ims != NULL)
  9048. && (filestat->last_modified <= parse_date_string(ims)));
  9049. }
  9050. static void
  9051. handle_not_modified_static_file_request(struct mg_connection *conn,
  9052. struct mg_file *filep)
  9053. {
  9054. char lm[64], etag[64];
  9055. if ((conn == NULL) || (filep == NULL)) {
  9056. return;
  9057. }
  9058. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9059. construct_etag(etag, sizeof(etag), &filep->stat);
  9060. /* Create 304 "not modified" response */
  9061. mg_response_header_start(conn, 304);
  9062. send_static_cache_header(conn);
  9063. send_additional_header(conn);
  9064. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9065. mg_response_header_add(conn, "Etag", etag, -1);
  9066. /* Send all headers */
  9067. mg_response_header_send(conn);
  9068. }
  9069. #endif
  9070. #if !defined(NO_FILESYSTEMS)
  9071. void
  9072. mg_send_file(struct mg_connection *conn, const char *path)
  9073. {
  9074. mg_send_mime_file2(conn, path, NULL, NULL);
  9075. }
  9076. void
  9077. mg_send_mime_file(struct mg_connection *conn,
  9078. const char *path,
  9079. const char *mime_type)
  9080. {
  9081. mg_send_mime_file2(conn, path, mime_type, NULL);
  9082. }
  9083. void
  9084. mg_send_mime_file2(struct mg_connection *conn,
  9085. const char *path,
  9086. const char *mime_type,
  9087. const char *additional_headers)
  9088. {
  9089. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9090. if (!conn) {
  9091. /* No conn */
  9092. return;
  9093. }
  9094. if (mg_stat(conn, path, &file.stat)) {
  9095. #if !defined(NO_CACHING)
  9096. if (is_not_modified(conn, &file.stat)) {
  9097. /* Send 304 "Not Modified" - this must not send any body data */
  9098. handle_not_modified_static_file_request(conn, &file);
  9099. } else
  9100. #endif /* NO_CACHING */
  9101. if (file.stat.is_directory) {
  9102. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9103. "yes")) {
  9104. handle_directory_request(conn, path);
  9105. } else {
  9106. mg_send_http_error(conn,
  9107. 403,
  9108. "%s",
  9109. "Error: Directory listing denied");
  9110. }
  9111. } else {
  9112. handle_static_file_request(
  9113. conn, path, &file, mime_type, additional_headers);
  9114. }
  9115. } else {
  9116. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9117. }
  9118. }
  9119. /* For a given PUT path, create all intermediate subdirectories.
  9120. * Return 0 if the path itself is a directory.
  9121. * Return 1 if the path leads to a file.
  9122. * Return -1 for if the path is too long.
  9123. * Return -2 if path can not be created.
  9124. */
  9125. static int
  9126. put_dir(struct mg_connection *conn, const char *path)
  9127. {
  9128. char buf[PATH_MAX];
  9129. const char *s, *p;
  9130. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9131. size_t len;
  9132. int res = 1;
  9133. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9134. len = (size_t)(p - path);
  9135. if (len >= sizeof(buf)) {
  9136. /* path too long */
  9137. res = -1;
  9138. break;
  9139. }
  9140. memcpy(buf, path, len);
  9141. buf[len] = '\0';
  9142. /* Try to create intermediate directory */
  9143. DEBUG_TRACE("mkdir(%s)", buf);
  9144. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9145. /* path does not exixt and can not be created */
  9146. res = -2;
  9147. break;
  9148. }
  9149. /* Is path itself a directory? */
  9150. if (p[1] == '\0') {
  9151. res = 0;
  9152. }
  9153. }
  9154. return res;
  9155. }
  9156. static void
  9157. remove_bad_file(const struct mg_connection *conn, const char *path)
  9158. {
  9159. int r = mg_remove(conn, path);
  9160. if (r != 0) {
  9161. mg_cry_internal(conn,
  9162. "%s: Cannot remove invalid file %s",
  9163. __func__,
  9164. path);
  9165. }
  9166. }
  9167. long long
  9168. mg_store_body(struct mg_connection *conn, const char *path)
  9169. {
  9170. char buf[MG_BUF_LEN];
  9171. long long len = 0;
  9172. int ret, n;
  9173. struct mg_file fi;
  9174. if (conn->consumed_content != 0) {
  9175. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9176. return -11;
  9177. }
  9178. ret = put_dir(conn, path);
  9179. if (ret < 0) {
  9180. /* -1 for path too long,
  9181. * -2 for path can not be created. */
  9182. return ret;
  9183. }
  9184. if (ret != 1) {
  9185. /* Return 0 means, path itself is a directory. */
  9186. return 0;
  9187. }
  9188. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9189. return -12;
  9190. }
  9191. ret = mg_read(conn, buf, sizeof(buf));
  9192. while (ret > 0) {
  9193. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9194. if (n != ret) {
  9195. (void)mg_fclose(
  9196. &fi.access); /* File is bad and will be removed anyway. */
  9197. remove_bad_file(conn, path);
  9198. return -13;
  9199. }
  9200. len += ret;
  9201. ret = mg_read(conn, buf, sizeof(buf));
  9202. }
  9203. /* File is open for writing. If fclose fails, there was probably an
  9204. * error flushing the buffer to disk, so the file on disk might be
  9205. * broken. Delete it and return an error to the caller. */
  9206. if (mg_fclose(&fi.access) != 0) {
  9207. remove_bad_file(conn, path);
  9208. return -14;
  9209. }
  9210. return len;
  9211. }
  9212. #endif /* NO_FILESYSTEMS */
  9213. /* Parse a buffer:
  9214. * Forward the string pointer till the end of a word, then
  9215. * terminate it and forward till the begin of the next word.
  9216. */
  9217. static int
  9218. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9219. {
  9220. /* Forward until a space is found - use isgraph here */
  9221. /* See http://www.cplusplus.com/reference/cctype/ */
  9222. while (isgraph((unsigned char)**ppw)) {
  9223. (*ppw)++;
  9224. }
  9225. /* Check end of word */
  9226. if (eol) {
  9227. /* must be a end of line */
  9228. if ((**ppw != '\r') && (**ppw != '\n')) {
  9229. return -1;
  9230. }
  9231. } else {
  9232. /* must be a end of a word, but not a line */
  9233. if (**ppw != ' ') {
  9234. return -1;
  9235. }
  9236. }
  9237. /* Terminate and forward to the next word */
  9238. do {
  9239. **ppw = 0;
  9240. (*ppw)++;
  9241. } while (isspace((unsigned char)**ppw));
  9242. /* Check after term */
  9243. if (!eol) {
  9244. /* if it's not the end of line, there must be a next word */
  9245. if (!isgraph((unsigned char)**ppw)) {
  9246. return -1;
  9247. }
  9248. }
  9249. /* ok */
  9250. return 1;
  9251. }
  9252. /* Parse HTTP headers from the given buffer, advance buf pointer
  9253. * to the point where parsing stopped.
  9254. * All parameters must be valid pointers (not NULL).
  9255. * Return <0 on error. */
  9256. static int
  9257. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9258. {
  9259. int i;
  9260. int num_headers = 0;
  9261. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9262. char *dp = *buf;
  9263. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9264. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9265. dp++;
  9266. }
  9267. if (dp == *buf) {
  9268. /* End of headers reached. */
  9269. break;
  9270. }
  9271. if (*dp != ':') {
  9272. /* This is not a valid field. */
  9273. return -1;
  9274. }
  9275. /* End of header key (*dp == ':') */
  9276. /* Truncate here and set the key name */
  9277. *dp = 0;
  9278. hdr[i].name = *buf;
  9279. /* Skip all spaces */
  9280. do {
  9281. dp++;
  9282. } while ((*dp == ' ') || (*dp == '\t'));
  9283. /* The rest of the line is the value */
  9284. hdr[i].value = dp;
  9285. /* Find end of line */
  9286. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9287. dp++;
  9288. };
  9289. /* eliminate \r */
  9290. if (*dp == '\r') {
  9291. *dp = 0;
  9292. dp++;
  9293. if (*dp != '\n') {
  9294. /* This is not a valid line. */
  9295. return -1;
  9296. }
  9297. }
  9298. /* here *dp is either 0 or '\n' */
  9299. /* in any case, we have a new header */
  9300. num_headers = i + 1;
  9301. if (*dp) {
  9302. *dp = 0;
  9303. dp++;
  9304. *buf = dp;
  9305. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9306. /* This is the end of the header */
  9307. break;
  9308. }
  9309. } else {
  9310. *buf = dp;
  9311. break;
  9312. }
  9313. }
  9314. return num_headers;
  9315. }
  9316. struct mg_http_method_info {
  9317. const char *name;
  9318. int request_has_body;
  9319. int response_has_body;
  9320. int is_safe;
  9321. int is_idempotent;
  9322. int is_cacheable;
  9323. };
  9324. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9325. static const struct mg_http_method_info http_methods[] = {
  9326. /* HTTP (RFC 2616) */
  9327. {"GET", 0, 1, 1, 1, 1},
  9328. {"POST", 1, 1, 0, 0, 0},
  9329. {"PUT", 1, 0, 0, 1, 0},
  9330. {"DELETE", 0, 0, 0, 1, 0},
  9331. {"HEAD", 0, 0, 1, 1, 1},
  9332. {"OPTIONS", 0, 0, 1, 1, 0},
  9333. {"CONNECT", 1, 1, 0, 0, 0},
  9334. /* TRACE method (RFC 2616) is not supported for security reasons */
  9335. /* PATCH method (RFC 5789) */
  9336. {"PATCH", 1, 0, 0, 0, 0},
  9337. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9338. /* WEBDAV (RFC 2518) */
  9339. {"PROPFIND", 0, 1, 1, 1, 0},
  9340. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9341. * Some PROPFIND results MAY be cached, with care,
  9342. * as there is no cache validation mechanism for
  9343. * most properties. This method is both safe and
  9344. * idempotent (see Section 9.1 of [RFC2616]). */
  9345. {"MKCOL", 0, 0, 0, 1, 0},
  9346. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9347. * When MKCOL is invoked without a request body,
  9348. * the newly created collection SHOULD have no
  9349. * members. A MKCOL request message may contain
  9350. * a message body. The precise behavior of a MKCOL
  9351. * request when the body is present is undefined,
  9352. * ... ==> We do not support MKCOL with body data.
  9353. * This method is idempotent, but not safe (see
  9354. * Section 9.1 of [RFC2616]). Responses to this
  9355. * method MUST NOT be cached. */
  9356. /* Unsupported WEBDAV Methods: */
  9357. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9358. /* + 11 methods from RFC 3253 */
  9359. /* ORDERPATCH (RFC 3648) */
  9360. /* ACL (RFC 3744) */
  9361. /* SEARCH (RFC 5323) */
  9362. /* + MicroSoft extensions
  9363. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9364. /* REPORT method (RFC 3253) */
  9365. {"REPORT", 1, 1, 1, 1, 1},
  9366. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9367. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9368. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9369. * to be useful for REST in case a "GET request with body" is
  9370. * required. */
  9371. {NULL, 0, 0, 0, 0, 0}
  9372. /* end of list */
  9373. };
  9374. static const struct mg_http_method_info *
  9375. get_http_method_info(const char *method)
  9376. {
  9377. /* Check if the method is known to the server. The list of all known
  9378. * HTTP methods can be found here at
  9379. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9380. */
  9381. const struct mg_http_method_info *m = http_methods;
  9382. while (m->name) {
  9383. if (!strcmp(m->name, method)) {
  9384. return m;
  9385. }
  9386. m++;
  9387. }
  9388. return NULL;
  9389. }
  9390. static int
  9391. is_valid_http_method(const char *method)
  9392. {
  9393. return (get_http_method_info(method) != NULL);
  9394. }
  9395. /* Parse HTTP request, fill in mg_request_info structure.
  9396. * This function modifies the buffer by NUL-terminating
  9397. * HTTP request components, header names and header values.
  9398. * Parameters:
  9399. * buf (in/out): pointer to the HTTP header to parse and split
  9400. * len (in): length of HTTP header buffer
  9401. * re (out): parsed header as mg_request_info
  9402. * buf and ri must be valid pointers (not NULL), len>0.
  9403. * Returns <0 on error. */
  9404. static int
  9405. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9406. {
  9407. int request_length;
  9408. int init_skip = 0;
  9409. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9410. * remote_port */
  9411. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9412. NULL;
  9413. ri->num_headers = 0;
  9414. /* RFC says that all initial whitespaces should be ingored */
  9415. /* This included all leading \r and \n (isspace) */
  9416. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9417. while ((len > 0) && isspace((unsigned char)*buf)) {
  9418. buf++;
  9419. len--;
  9420. init_skip++;
  9421. }
  9422. if (len == 0) {
  9423. /* Incomplete request */
  9424. return 0;
  9425. }
  9426. /* Control characters are not allowed, including zero */
  9427. if (iscntrl((unsigned char)*buf)) {
  9428. return -1;
  9429. }
  9430. /* Find end of HTTP header */
  9431. request_length = get_http_header_len(buf, len);
  9432. if (request_length <= 0) {
  9433. return request_length;
  9434. }
  9435. buf[request_length - 1] = '\0';
  9436. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9437. return -1;
  9438. }
  9439. /* The first word has to be the HTTP method */
  9440. ri->request_method = buf;
  9441. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9442. return -1;
  9443. }
  9444. /* Check for a valid http method */
  9445. if (!is_valid_http_method(ri->request_method)) {
  9446. return -1;
  9447. }
  9448. /* The second word is the URI */
  9449. ri->request_uri = buf;
  9450. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9451. return -1;
  9452. }
  9453. /* Next would be the HTTP version */
  9454. ri->http_version = buf;
  9455. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9456. return -1;
  9457. }
  9458. /* Check for a valid HTTP version key */
  9459. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9460. /* Invalid request */
  9461. return -1;
  9462. }
  9463. ri->http_version += 5;
  9464. /* Parse all HTTP headers */
  9465. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9466. if (ri->num_headers < 0) {
  9467. /* Error while parsing headers */
  9468. return -1;
  9469. }
  9470. return request_length + init_skip;
  9471. }
  9472. static int
  9473. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9474. {
  9475. int response_length;
  9476. int init_skip = 0;
  9477. char *tmp, *tmp2;
  9478. long l;
  9479. /* Initialize elements. */
  9480. ri->http_version = ri->status_text = NULL;
  9481. ri->num_headers = ri->status_code = 0;
  9482. /* RFC says that all initial whitespaces should be ingored */
  9483. /* This included all leading \r and \n (isspace) */
  9484. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9485. while ((len > 0) && isspace((unsigned char)*buf)) {
  9486. buf++;
  9487. len--;
  9488. init_skip++;
  9489. }
  9490. if (len == 0) {
  9491. /* Incomplete request */
  9492. return 0;
  9493. }
  9494. /* Control characters are not allowed, including zero */
  9495. if (iscntrl((unsigned char)*buf)) {
  9496. return -1;
  9497. }
  9498. /* Find end of HTTP header */
  9499. response_length = get_http_header_len(buf, len);
  9500. if (response_length <= 0) {
  9501. return response_length;
  9502. }
  9503. buf[response_length - 1] = '\0';
  9504. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9505. return -1;
  9506. }
  9507. /* The first word is the HTTP version */
  9508. /* Check for a valid HTTP version key */
  9509. if (strncmp(buf, "HTTP/", 5) != 0) {
  9510. /* Invalid request */
  9511. return -1;
  9512. }
  9513. buf += 5;
  9514. if (!isgraph((unsigned char)buf[0])) {
  9515. /* Invalid request */
  9516. return -1;
  9517. }
  9518. ri->http_version = buf;
  9519. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9520. return -1;
  9521. }
  9522. /* The second word is the status as a number */
  9523. tmp = buf;
  9524. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9525. return -1;
  9526. }
  9527. l = strtol(tmp, &tmp2, 10);
  9528. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9529. /* Everything else but a 3 digit code is invalid */
  9530. return -1;
  9531. }
  9532. ri->status_code = (int)l;
  9533. /* The rest of the line is the status text */
  9534. ri->status_text = buf;
  9535. /* Find end of status text */
  9536. /* isgraph or isspace = isprint */
  9537. while (isprint((unsigned char)*buf)) {
  9538. buf++;
  9539. }
  9540. if ((*buf != '\r') && (*buf != '\n')) {
  9541. return -1;
  9542. }
  9543. /* Terminate string and forward buf to next line */
  9544. do {
  9545. *buf = 0;
  9546. buf++;
  9547. } while (isspace((unsigned char)*buf));
  9548. /* Parse all HTTP headers */
  9549. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9550. if (ri->num_headers < 0) {
  9551. /* Error while parsing headers */
  9552. return -1;
  9553. }
  9554. return response_length + init_skip;
  9555. }
  9556. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9557. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9558. * buffer (which marks the end of HTTP request). Buffer buf may already
  9559. * have some data. The length of the data is stored in nread.
  9560. * Upon every read operation, increase nread by the number of bytes read. */
  9561. static int
  9562. read_message(FILE *fp,
  9563. struct mg_connection *conn,
  9564. char *buf,
  9565. int bufsiz,
  9566. int *nread)
  9567. {
  9568. int request_len, n = 0;
  9569. struct timespec last_action_time;
  9570. double request_timeout;
  9571. if (!conn) {
  9572. return 0;
  9573. }
  9574. memset(&last_action_time, 0, sizeof(last_action_time));
  9575. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9576. /* value of request_timeout is in seconds, config in milliseconds */
  9577. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9578. } else {
  9579. request_timeout =
  9580. atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  9581. }
  9582. if (conn->handled_requests > 0) {
  9583. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9584. request_timeout =
  9585. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9586. }
  9587. }
  9588. request_len = get_http_header_len(buf, *nread);
  9589. while (request_len == 0) {
  9590. /* Full request not yet received */
  9591. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9592. /* Server is to be stopped. */
  9593. return -1;
  9594. }
  9595. if (*nread >= bufsiz) {
  9596. /* Request too long */
  9597. return -2;
  9598. }
  9599. n = pull_inner(
  9600. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9601. if (n == -2) {
  9602. /* Receive error */
  9603. return -1;
  9604. }
  9605. /* update clock after every read request */
  9606. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9607. if (n > 0) {
  9608. *nread += n;
  9609. request_len = get_http_header_len(buf, *nread);
  9610. }
  9611. if ((request_len == 0) && (request_timeout >= 0)) {
  9612. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9613. > request_timeout) {
  9614. /* Timeout */
  9615. return -1;
  9616. }
  9617. }
  9618. }
  9619. return request_len;
  9620. }
  9621. #if !defined(NO_CGI) || !defined(NO_FILES)
  9622. static int
  9623. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9624. {
  9625. const char *expect;
  9626. char buf[MG_BUF_LEN];
  9627. int success = 0;
  9628. if (!conn) {
  9629. return 0;
  9630. }
  9631. expect = mg_get_header(conn, "Expect");
  9632. DEBUG_ASSERT(fp != NULL);
  9633. if (!fp) {
  9634. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9635. return 0;
  9636. }
  9637. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9638. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9639. */
  9640. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9641. } else {
  9642. if (expect != NULL) {
  9643. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9644. conn->status_code = 100;
  9645. } else {
  9646. conn->status_code = 200;
  9647. }
  9648. DEBUG_ASSERT(conn->consumed_content == 0);
  9649. if (conn->consumed_content != 0) {
  9650. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9651. return 0;
  9652. }
  9653. for (;;) {
  9654. int nread = mg_read(conn, buf, sizeof(buf));
  9655. if (nread <= 0) {
  9656. success = (nread == 0);
  9657. break;
  9658. }
  9659. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9660. break;
  9661. }
  9662. }
  9663. /* Each error code path in this function must send an error */
  9664. if (!success) {
  9665. /* NOTE: Maybe some data has already been sent. */
  9666. /* TODO (low): If some data has been sent, a correct error
  9667. * reply can no longer be sent, so just close the connection */
  9668. mg_send_http_error(conn, 500, "%s", "");
  9669. }
  9670. }
  9671. return success;
  9672. }
  9673. #endif
  9674. #if defined(USE_TIMERS)
  9675. #define TIMER_API static
  9676. #include "timer.inl"
  9677. #endif /* USE_TIMERS */
  9678. #if !defined(NO_CGI)
  9679. /* This structure helps to create an environment for the spawned CGI
  9680. * program.
  9681. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9682. * last element must be NULL.
  9683. * However, on Windows there is a requirement that all these
  9684. * VARIABLE=VALUE\0
  9685. * strings must reside in a contiguous buffer. The end of the buffer is
  9686. * marked by two '\0' characters.
  9687. * We satisfy both worlds: we create an envp array (which is vars), all
  9688. * entries are actually pointers inside buf. */
  9689. struct cgi_environment {
  9690. struct mg_connection *conn;
  9691. /* Data block */
  9692. char *buf; /* Environment buffer */
  9693. size_t buflen; /* Space available in buf */
  9694. size_t bufused; /* Space taken in buf */
  9695. /* Index block */
  9696. char **var; /* char **envp */
  9697. size_t varlen; /* Number of variables available in var */
  9698. size_t varused; /* Number of variables stored in var */
  9699. };
  9700. static void addenv(struct cgi_environment *env,
  9701. PRINTF_FORMAT_STRING(const char *fmt),
  9702. ...) PRINTF_ARGS(2, 3);
  9703. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9704. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9705. static void
  9706. addenv(struct cgi_environment *env, const char *fmt, ...)
  9707. {
  9708. size_t i, n, space;
  9709. int truncated = 0;
  9710. char *added;
  9711. va_list ap;
  9712. if ((env->varlen - env->varused) < 2) {
  9713. mg_cry_internal(env->conn,
  9714. "%s: Cannot register CGI variable [%s]",
  9715. __func__,
  9716. fmt);
  9717. return;
  9718. }
  9719. /* Calculate how much space is left in the buffer */
  9720. space = (env->buflen - env->bufused);
  9721. do {
  9722. /* Space for "\0\0" is always needed. */
  9723. if (space <= 2) {
  9724. /* Allocate new buffer */
  9725. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9726. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9727. if (!added) {
  9728. /* Out of memory */
  9729. mg_cry_internal(
  9730. env->conn,
  9731. "%s: Cannot allocate memory for CGI variable [%s]",
  9732. __func__,
  9733. fmt);
  9734. return;
  9735. }
  9736. /* Retarget pointers */
  9737. env->buf = added;
  9738. env->buflen = n;
  9739. for (i = 0, n = 0; i < env->varused; i++) {
  9740. env->var[i] = added + n;
  9741. n += strlen(added + n) + 1;
  9742. }
  9743. space = (env->buflen - env->bufused);
  9744. }
  9745. /* Make a pointer to the free space int the buffer */
  9746. added = env->buf + env->bufused;
  9747. /* Copy VARIABLE=VALUE\0 string into the free space */
  9748. va_start(ap, fmt);
  9749. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9750. va_end(ap);
  9751. /* Do not add truncated strings to the environment */
  9752. if (truncated) {
  9753. /* Reallocate the buffer */
  9754. space = 0;
  9755. }
  9756. } while (truncated);
  9757. /* Calculate number of bytes added to the environment */
  9758. n = strlen(added) + 1;
  9759. env->bufused += n;
  9760. /* Append a pointer to the added string into the envp array */
  9761. env->var[env->varused] = added;
  9762. env->varused++;
  9763. }
  9764. /* Return 0 on success, non-zero if an error occurs. */
  9765. static int
  9766. prepare_cgi_environment(struct mg_connection *conn,
  9767. const char *prog,
  9768. struct cgi_environment *env)
  9769. {
  9770. const char *s;
  9771. struct vec var_vec;
  9772. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9773. int i, truncated, uri_len;
  9774. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9775. return -1;
  9776. }
  9777. env->conn = conn;
  9778. env->buflen = CGI_ENVIRONMENT_SIZE;
  9779. env->bufused = 0;
  9780. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9781. if (env->buf == NULL) {
  9782. mg_cry_internal(conn,
  9783. "%s: Not enough memory for environmental buffer",
  9784. __func__);
  9785. return -1;
  9786. }
  9787. env->varlen = MAX_CGI_ENVIR_VARS;
  9788. env->varused = 0;
  9789. env->var =
  9790. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9791. if (env->var == NULL) {
  9792. mg_cry_internal(conn,
  9793. "%s: Not enough memory for environmental variables",
  9794. __func__);
  9795. mg_free(env->buf);
  9796. return -1;
  9797. }
  9798. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9799. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9800. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9801. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9802. /* Prepare the environment block */
  9803. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9804. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9805. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9806. addenv(env, "SERVER_PORT=%d", ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)));
  9807. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9808. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9809. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9810. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9811. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9812. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9813. /* SCRIPT_NAME */
  9814. uri_len = (int)strlen(conn->request_info.local_uri);
  9815. if (conn->path_info == NULL) {
  9816. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9817. /* URI: /path_to_script/script.cgi */
  9818. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9819. } else {
  9820. /* URI: /path_to_script/ ... using index.cgi */
  9821. const char *index_file = strrchr(prog, '/');
  9822. if (index_file) {
  9823. addenv(env,
  9824. "SCRIPT_NAME=%s%s",
  9825. conn->request_info.local_uri,
  9826. index_file + 1);
  9827. }
  9828. }
  9829. } else {
  9830. /* URI: /path_to_script/script.cgi/path_info */
  9831. addenv(env,
  9832. "SCRIPT_NAME=%.*s",
  9833. uri_len - (int)strlen(conn->path_info),
  9834. conn->request_info.local_uri);
  9835. }
  9836. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9837. if (conn->path_info == NULL) {
  9838. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9839. } else {
  9840. addenv(env,
  9841. "PATH_TRANSLATED=%s%s",
  9842. conn->dom_ctx->config[DOCUMENT_ROOT],
  9843. conn->path_info);
  9844. }
  9845. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9846. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9847. addenv(env, "CONTENT_TYPE=%s", s);
  9848. }
  9849. if (conn->request_info.query_string != NULL) {
  9850. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9851. }
  9852. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9853. addenv(env, "CONTENT_LENGTH=%s", s);
  9854. }
  9855. if ((s = getenv("PATH")) != NULL) {
  9856. addenv(env, "PATH=%s", s);
  9857. }
  9858. if (conn->path_info != NULL) {
  9859. addenv(env, "PATH_INFO=%s", conn->path_info);
  9860. }
  9861. if (conn->status_code > 0) {
  9862. /* CGI error handler should show the status code */
  9863. addenv(env, "STATUS=%d", conn->status_code);
  9864. }
  9865. #if defined(_WIN32)
  9866. if ((s = getenv("COMSPEC")) != NULL) {
  9867. addenv(env, "COMSPEC=%s", s);
  9868. }
  9869. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9870. addenv(env, "SYSTEMROOT=%s", s);
  9871. }
  9872. if ((s = getenv("SystemDrive")) != NULL) {
  9873. addenv(env, "SystemDrive=%s", s);
  9874. }
  9875. if ((s = getenv("ProgramFiles")) != NULL) {
  9876. addenv(env, "ProgramFiles=%s", s);
  9877. }
  9878. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9879. addenv(env, "ProgramFiles(x86)=%s", s);
  9880. }
  9881. #else
  9882. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9883. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9884. }
  9885. #endif /* _WIN32 */
  9886. if ((s = getenv("PERLLIB")) != NULL) {
  9887. addenv(env, "PERLLIB=%s", s);
  9888. }
  9889. if (conn->request_info.remote_user != NULL) {
  9890. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9891. addenv(env, "%s", "AUTH_TYPE=Digest");
  9892. }
  9893. /* Add all headers as HTTP_* variables */
  9894. for (i = 0; i < conn->request_info.num_headers; i++) {
  9895. (void)mg_snprintf(conn,
  9896. &truncated,
  9897. http_var_name,
  9898. sizeof(http_var_name),
  9899. "HTTP_%s",
  9900. conn->request_info.http_headers[i].name);
  9901. if (truncated) {
  9902. mg_cry_internal(conn,
  9903. "%s: HTTP header variable too long [%s]",
  9904. __func__,
  9905. conn->request_info.http_headers[i].name);
  9906. continue;
  9907. }
  9908. /* Convert variable name into uppercase, and change - to _ */
  9909. for (p = http_var_name; *p != '\0'; p++) {
  9910. if (*p == '-') {
  9911. *p = '_';
  9912. }
  9913. *p = (char)toupper((unsigned char)*p);
  9914. }
  9915. addenv(env,
  9916. "%s=%s",
  9917. http_var_name,
  9918. conn->request_info.http_headers[i].value);
  9919. }
  9920. /* Add user-specified variables */
  9921. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9922. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9923. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9924. }
  9925. env->var[env->varused] = NULL;
  9926. env->buf[env->bufused] = '\0';
  9927. return 0;
  9928. }
  9929. /* Data for CGI process control: PID and number of references */
  9930. struct process_control_data {
  9931. pid_t pid;
  9932. ptrdiff_t references;
  9933. };
  9934. static int
  9935. abort_cgi_process(void *data)
  9936. {
  9937. /* Waitpid checks for child status and won't work for a pid that does
  9938. * not identify a child of the current process. Thus, if the pid is
  9939. * reused, we will not affect a different process. */
  9940. struct process_control_data *proc = (struct process_control_data *)data;
  9941. int status = 0;
  9942. ptrdiff_t refs;
  9943. pid_t ret_pid;
  9944. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9945. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9946. /* Stop child process */
  9947. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9948. kill(proc->pid, SIGABRT);
  9949. /* Wait until process is terminated (don't leave zombies) */
  9950. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9951. ;
  9952. } else {
  9953. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9954. }
  9955. /* Dec reference counter */
  9956. refs = mg_atomic_dec(&proc->references);
  9957. if (refs == 0) {
  9958. /* no more references - free data */
  9959. mg_free(data);
  9960. }
  9961. return 0;
  9962. }
  9963. /* Local (static) function assumes all arguments are valid. */
  9964. static void
  9965. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9966. {
  9967. char *buf;
  9968. size_t buflen;
  9969. int headers_len, data_len, i, truncated;
  9970. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9971. const char *status, *status_text, *connection_state;
  9972. char *pbuf, dir[PATH_MAX], *p;
  9973. struct mg_request_info ri;
  9974. struct cgi_environment blk;
  9975. FILE *in = NULL, *out = NULL, *err = NULL;
  9976. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9977. pid_t pid = (pid_t)-1;
  9978. struct process_control_data *proc = NULL;
  9979. #if defined(USE_TIMERS)
  9980. double cgi_timeout;
  9981. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9982. /* Get timeout in seconds */
  9983. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9984. } else {
  9985. cgi_timeout =
  9986. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9987. }
  9988. #endif
  9989. buf = NULL;
  9990. buflen = conn->phys_ctx->max_request_size;
  9991. i = prepare_cgi_environment(conn, prog, &blk);
  9992. if (i != 0) {
  9993. blk.buf = NULL;
  9994. blk.var = NULL;
  9995. goto done;
  9996. }
  9997. /* CGI must be executed in its own directory. 'dir' must point to the
  9998. * directory containing executable program, 'p' must point to the
  9999. * executable program name relative to 'dir'. */
  10000. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10001. if (truncated) {
  10002. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10003. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10004. goto done;
  10005. }
  10006. if ((p = strrchr(dir, '/')) != NULL) {
  10007. *p++ = '\0';
  10008. } else {
  10009. dir[0] = '.';
  10010. dir[1] = '\0';
  10011. p = (char *)prog;
  10012. }
  10013. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10014. status = strerror(ERRNO);
  10015. mg_cry_internal(
  10016. conn,
  10017. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10018. prog,
  10019. status);
  10020. mg_send_http_error(conn,
  10021. 500,
  10022. "Error: Cannot create CGI pipe: %s",
  10023. status);
  10024. goto done;
  10025. }
  10026. proc = (struct process_control_data *)
  10027. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10028. if (proc == NULL) {
  10029. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10030. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10031. goto done;
  10032. }
  10033. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10034. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  10035. if (pid == (pid_t)-1) {
  10036. status = strerror(ERRNO);
  10037. mg_cry_internal(
  10038. conn,
  10039. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10040. prog,
  10041. status);
  10042. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10043. mg_free(proc);
  10044. proc = NULL;
  10045. goto done;
  10046. }
  10047. /* Store data in shared process_control_data */
  10048. proc->pid = pid;
  10049. proc->references = 1;
  10050. #if defined(USE_TIMERS)
  10051. if (cgi_timeout > 0.0) {
  10052. proc->references = 2;
  10053. // Start a timer for CGI
  10054. timer_add(conn->phys_ctx,
  10055. cgi_timeout /* in seconds */,
  10056. 0.0,
  10057. 1,
  10058. abort_cgi_process,
  10059. (void *)proc,
  10060. NULL);
  10061. }
  10062. #endif
  10063. /* Parent closes only one side of the pipes.
  10064. * If we don't mark them as closed, close() attempt before
  10065. * return from this function throws an exception on Windows.
  10066. * Windows does not like when closed descriptor is closed again. */
  10067. (void)close(fdin[0]);
  10068. (void)close(fdout[1]);
  10069. (void)close(fderr[1]);
  10070. fdin[0] = fdout[1] = fderr[1] = -1;
  10071. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10072. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10073. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10074. status = strerror(ERRNO);
  10075. mg_cry_internal(conn,
  10076. "Error: CGI program \"%s\": Can not open fd: %s",
  10077. prog,
  10078. status);
  10079. mg_send_http_error(conn,
  10080. 500,
  10081. "Error: CGI can not open fd\nfdopen: %s",
  10082. status);
  10083. goto done;
  10084. }
  10085. setbuf(in, NULL);
  10086. setbuf(out, NULL);
  10087. setbuf(err, NULL);
  10088. fout.access.fp = out;
  10089. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10090. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10091. conn->content_len);
  10092. /* This is a POST/PUT request, or another request with body data. */
  10093. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10094. /* Error sending the body data */
  10095. mg_cry_internal(
  10096. conn,
  10097. "Error: CGI program \"%s\": Forward body data failed",
  10098. prog);
  10099. goto done;
  10100. }
  10101. }
  10102. /* Close so child gets an EOF. */
  10103. fclose(in);
  10104. in = NULL;
  10105. fdin[1] = -1;
  10106. /* Now read CGI reply into a buffer. We need to set correct
  10107. * status code, thus we need to see all HTTP headers first.
  10108. * Do not send anything back to client, until we buffer in all
  10109. * HTTP headers. */
  10110. data_len = 0;
  10111. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10112. if (buf == NULL) {
  10113. mg_send_http_error(conn,
  10114. 500,
  10115. "Error: Not enough memory for CGI buffer (%u bytes)",
  10116. (unsigned int)buflen);
  10117. mg_cry_internal(
  10118. conn,
  10119. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10120. "bytes)",
  10121. prog,
  10122. (unsigned int)buflen);
  10123. goto done;
  10124. }
  10125. DEBUG_TRACE("CGI: %s", "wait for response");
  10126. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10127. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10128. if (headers_len <= 0) {
  10129. /* Could not parse the CGI response. Check if some error message on
  10130. * stderr. */
  10131. i = pull_all(err, conn, buf, (int)buflen);
  10132. if (i > 0) {
  10133. /* CGI program explicitly sent an error */
  10134. /* Write the error message to the internal log */
  10135. mg_cry_internal(conn,
  10136. "Error: CGI program \"%s\" sent error "
  10137. "message: [%.*s]",
  10138. prog,
  10139. i,
  10140. buf);
  10141. /* Don't send the error message back to the client */
  10142. mg_send_http_error(conn,
  10143. 500,
  10144. "Error: CGI program \"%s\" failed.",
  10145. prog);
  10146. } else {
  10147. /* CGI program did not explicitly send an error, but a broken
  10148. * respon header */
  10149. mg_cry_internal(conn,
  10150. "Error: CGI program sent malformed or too big "
  10151. "(>%u bytes) HTTP headers: [%.*s]",
  10152. (unsigned)buflen,
  10153. data_len,
  10154. buf);
  10155. mg_send_http_error(conn,
  10156. 500,
  10157. "Error: CGI program sent malformed or too big "
  10158. "(>%u bytes) HTTP headers: [%.*s]",
  10159. (unsigned)buflen,
  10160. data_len,
  10161. buf);
  10162. }
  10163. /* in both cases, abort processing CGI */
  10164. goto done;
  10165. }
  10166. pbuf = buf;
  10167. buf[headers_len - 1] = '\0';
  10168. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10169. /* Make up and send the status line */
  10170. status_text = "OK";
  10171. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10172. != NULL) {
  10173. conn->status_code = atoi(status);
  10174. status_text = status;
  10175. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10176. status_text++;
  10177. }
  10178. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10179. != NULL) {
  10180. conn->status_code = 307;
  10181. } else {
  10182. conn->status_code = 200;
  10183. }
  10184. connection_state =
  10185. get_header(ri.http_headers, ri.num_headers, "Connection");
  10186. if (!header_has_option(connection_state, "keep-alive")) {
  10187. conn->must_close = 1;
  10188. }
  10189. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10190. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10191. /* Send headers */
  10192. for (i = 0; i < ri.num_headers; i++) {
  10193. DEBUG_TRACE("CGI header: %s: %s",
  10194. ri.http_headers[i].name,
  10195. ri.http_headers[i].value);
  10196. mg_printf(conn,
  10197. "%s: %s\r\n",
  10198. ri.http_headers[i].name,
  10199. ri.http_headers[i].value);
  10200. }
  10201. mg_write(conn, "\r\n", 2);
  10202. /* Send chunk of data that may have been read after the headers */
  10203. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10204. /* Read the rest of CGI output and send to the client */
  10205. DEBUG_TRACE("CGI: %s", "forward all data");
  10206. send_file_data(conn, &fout, 0, INT64_MAX);
  10207. DEBUG_TRACE("CGI: %s", "all data sent");
  10208. done:
  10209. mg_free(blk.var);
  10210. mg_free(blk.buf);
  10211. if (pid != (pid_t)-1) {
  10212. abort_cgi_process((void *)proc);
  10213. }
  10214. if (fdin[0] != -1) {
  10215. close(fdin[0]);
  10216. }
  10217. if (fdout[1] != -1) {
  10218. close(fdout[1]);
  10219. }
  10220. if (fderr[1] != -1) {
  10221. close(fderr[1]);
  10222. }
  10223. if (in != NULL) {
  10224. fclose(in);
  10225. } else if (fdin[1] != -1) {
  10226. close(fdin[1]);
  10227. }
  10228. if (out != NULL) {
  10229. fclose(out);
  10230. } else if (fdout[0] != -1) {
  10231. close(fdout[0]);
  10232. }
  10233. if (err != NULL) {
  10234. fclose(err);
  10235. } else if (fderr[0] != -1) {
  10236. close(fderr[0]);
  10237. }
  10238. mg_free(buf);
  10239. }
  10240. #endif /* !NO_CGI */
  10241. #if !defined(NO_FILES)
  10242. static void
  10243. mkcol(struct mg_connection *conn, const char *path)
  10244. {
  10245. int rc, body_len;
  10246. struct de de;
  10247. if (conn == NULL) {
  10248. return;
  10249. }
  10250. /* TODO (mid): Check the mg_send_http_error situations in this function
  10251. */
  10252. memset(&de.file, 0, sizeof(de.file));
  10253. if (!mg_stat(conn, path, &de.file)) {
  10254. mg_cry_internal(conn,
  10255. "%s: mg_stat(%s) failed: %s",
  10256. __func__,
  10257. path,
  10258. strerror(ERRNO));
  10259. }
  10260. if (de.file.last_modified) {
  10261. /* TODO (mid): This check does not seem to make any sense ! */
  10262. /* TODO (mid): Add a webdav unit test first, before changing
  10263. * anything here. */
  10264. mg_send_http_error(
  10265. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10266. return;
  10267. }
  10268. body_len = conn->data_len - conn->request_len;
  10269. if (body_len > 0) {
  10270. mg_send_http_error(
  10271. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10272. return;
  10273. }
  10274. rc = mg_mkdir(conn, path, 0755);
  10275. if (rc == 0) {
  10276. /* Create 201 "Created" response */
  10277. mg_response_header_start(conn, 201);
  10278. send_static_cache_header(conn);
  10279. send_additional_header(conn);
  10280. mg_response_header_add(conn, "Content-Length", "0", -1);
  10281. /* Send all headers - there is no body */
  10282. mg_response_header_send(conn);
  10283. } else {
  10284. if (errno == EEXIST) {
  10285. mg_send_http_error(
  10286. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10287. } else if (errno == EACCES) {
  10288. mg_send_http_error(
  10289. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10290. } else if (errno == ENOENT) {
  10291. mg_send_http_error(
  10292. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10293. } else {
  10294. mg_send_http_error(
  10295. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10296. }
  10297. }
  10298. }
  10299. static void
  10300. put_file(struct mg_connection *conn, const char *path)
  10301. {
  10302. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10303. const char *range;
  10304. int64_t r1, r2;
  10305. int rc;
  10306. if (conn == NULL) {
  10307. return;
  10308. }
  10309. if (mg_stat(conn, path, &file.stat)) {
  10310. /* File already exists */
  10311. conn->status_code = 200;
  10312. if (file.stat.is_directory) {
  10313. /* This is an already existing directory,
  10314. * so there is nothing to do for the server. */
  10315. rc = 0;
  10316. } else {
  10317. /* File exists and is not a directory. */
  10318. /* Can it be replaced? */
  10319. /* Check if the server may write this file */
  10320. if (access(path, W_OK) == 0) {
  10321. /* Access granted */
  10322. rc = 1;
  10323. } else {
  10324. mg_send_http_error(
  10325. conn,
  10326. 403,
  10327. "Error: Put not possible\nReplacing %s is not allowed",
  10328. path);
  10329. return;
  10330. }
  10331. }
  10332. } else {
  10333. /* File should be created */
  10334. conn->status_code = 201;
  10335. rc = put_dir(conn, path);
  10336. }
  10337. if (rc == 0) {
  10338. /* put_dir returns 0 if path is a directory */
  10339. /* Create response */
  10340. mg_response_header_start(conn, conn->status_code);
  10341. send_no_cache_header(conn);
  10342. send_additional_header(conn);
  10343. mg_response_header_add(conn, "Content-Length", "0", -1);
  10344. /* Send all headers - there is no body */
  10345. mg_response_header_send(conn);
  10346. /* Request to create a directory has been fulfilled successfully.
  10347. * No need to put a file. */
  10348. return;
  10349. }
  10350. if (rc == -1) {
  10351. /* put_dir returns -1 if the path is too long */
  10352. mg_send_http_error(conn,
  10353. 414,
  10354. "Error: Path too long\nput_dir(%s): %s",
  10355. path,
  10356. strerror(ERRNO));
  10357. return;
  10358. }
  10359. if (rc == -2) {
  10360. /* put_dir returns -2 if the directory can not be created */
  10361. mg_send_http_error(conn,
  10362. 500,
  10363. "Error: Can not create directory\nput_dir(%s): %s",
  10364. path,
  10365. strerror(ERRNO));
  10366. return;
  10367. }
  10368. /* A file should be created or overwritten. */
  10369. /* Currently CivetWeb does not nead read+write access. */
  10370. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10371. || file.access.fp == NULL) {
  10372. (void)mg_fclose(&file.access);
  10373. mg_send_http_error(conn,
  10374. 500,
  10375. "Error: Can not create file\nfopen(%s): %s",
  10376. path,
  10377. strerror(ERRNO));
  10378. return;
  10379. }
  10380. fclose_on_exec(&file.access, conn);
  10381. range = mg_get_header(conn, "Content-Range");
  10382. r1 = r2 = 0;
  10383. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10384. conn->status_code = 206; /* Partial content */
  10385. fseeko(file.access.fp, r1, SEEK_SET);
  10386. }
  10387. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10388. /* forward_body_data failed.
  10389. * The error code has already been sent to the client,
  10390. * and conn->status_code is already set. */
  10391. (void)mg_fclose(&file.access);
  10392. return;
  10393. }
  10394. if (mg_fclose(&file.access) != 0) {
  10395. /* fclose failed. This might have different reasons, but a likely
  10396. * one is "no space on disk", http 507. */
  10397. conn->status_code = 507;
  10398. }
  10399. /* Create response (status_code has been set before) */
  10400. mg_response_header_start(conn, conn->status_code);
  10401. send_no_cache_header(conn);
  10402. send_additional_header(conn);
  10403. mg_response_header_add(conn, "Content-Length", "0", -1);
  10404. /* Send all headers - there is no body */
  10405. mg_response_header_send(conn);
  10406. }
  10407. static void
  10408. delete_file(struct mg_connection *conn, const char *path)
  10409. {
  10410. struct de de;
  10411. memset(&de.file, 0, sizeof(de.file));
  10412. if (!mg_stat(conn, path, &de.file)) {
  10413. /* mg_stat returns 0 if the file does not exist */
  10414. mg_send_http_error(conn,
  10415. 404,
  10416. "Error: Cannot delete file\nFile %s not found",
  10417. path);
  10418. return;
  10419. }
  10420. if (de.file.is_directory) {
  10421. if (remove_directory(conn, path)) {
  10422. /* Delete is successful: Return 204 without content. */
  10423. mg_send_http_error(conn, 204, "%s", "");
  10424. } else {
  10425. /* Delete is not successful: Return 500 (Server error). */
  10426. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10427. }
  10428. return;
  10429. }
  10430. /* This is an existing file (not a directory).
  10431. * Check if write permission is granted. */
  10432. if (access(path, W_OK) != 0) {
  10433. /* File is read only */
  10434. mg_send_http_error(
  10435. conn,
  10436. 403,
  10437. "Error: Delete not possible\nDeleting %s is not allowed",
  10438. path);
  10439. return;
  10440. }
  10441. /* Try to delete it. */
  10442. if (mg_remove(conn, path) == 0) {
  10443. /* Delete was successful: Return 204 without content. */
  10444. mg_response_header_start(conn, 204);
  10445. send_no_cache_header(conn);
  10446. send_additional_header(conn);
  10447. mg_response_header_add(conn, "Content-Length", "0", -1);
  10448. mg_response_header_send(conn);
  10449. } else {
  10450. /* Delete not successful (file locked). */
  10451. mg_send_http_error(conn,
  10452. 423,
  10453. "Error: Cannot delete file\nremove(%s): %s",
  10454. path,
  10455. strerror(ERRNO));
  10456. }
  10457. }
  10458. #endif /* !NO_FILES */
  10459. #if !defined(NO_FILESYSTEMS)
  10460. static void
  10461. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10462. static void
  10463. do_ssi_include(struct mg_connection *conn,
  10464. const char *ssi,
  10465. char *tag,
  10466. int include_level)
  10467. {
  10468. char file_name[MG_BUF_LEN], path[512], *p;
  10469. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10470. size_t len;
  10471. int truncated = 0;
  10472. if (conn == NULL) {
  10473. return;
  10474. }
  10475. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10476. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10477. * always < MG_BUF_LEN. */
  10478. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10479. /* File name is relative to the webserver root */
  10480. file_name[511] = 0;
  10481. (void)mg_snprintf(conn,
  10482. &truncated,
  10483. path,
  10484. sizeof(path),
  10485. "%s/%s",
  10486. conn->dom_ctx->config[DOCUMENT_ROOT],
  10487. file_name);
  10488. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10489. /* File name is relative to the webserver working directory
  10490. * or it is absolute system path */
  10491. file_name[511] = 0;
  10492. (void)
  10493. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10494. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10495. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10496. /* File name is relative to the currect document */
  10497. file_name[511] = 0;
  10498. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10499. if (!truncated) {
  10500. if ((p = strrchr(path, '/')) != NULL) {
  10501. p[1] = '\0';
  10502. }
  10503. len = strlen(path);
  10504. (void)mg_snprintf(conn,
  10505. &truncated,
  10506. path + len,
  10507. sizeof(path) - len,
  10508. "%s",
  10509. file_name);
  10510. }
  10511. } else {
  10512. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10513. return;
  10514. }
  10515. if (truncated) {
  10516. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10517. return;
  10518. }
  10519. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10520. mg_cry_internal(conn,
  10521. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10522. tag,
  10523. path,
  10524. strerror(ERRNO));
  10525. } else {
  10526. fclose_on_exec(&file.access, conn);
  10527. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10528. > 0) {
  10529. send_ssi_file(conn, path, &file, include_level + 1);
  10530. } else {
  10531. send_file_data(conn, &file, 0, INT64_MAX);
  10532. }
  10533. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10534. }
  10535. }
  10536. #if !defined(NO_POPEN)
  10537. static void
  10538. do_ssi_exec(struct mg_connection *conn, char *tag)
  10539. {
  10540. char cmd[1024] = "";
  10541. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10542. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10543. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10544. } else {
  10545. cmd[1023] = 0;
  10546. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10547. mg_cry_internal(conn,
  10548. "Cannot SSI #exec: [%s]: %s",
  10549. cmd,
  10550. strerror(ERRNO));
  10551. } else {
  10552. send_file_data(conn, &file, 0, INT64_MAX);
  10553. pclose(file.access.fp);
  10554. }
  10555. }
  10556. }
  10557. #endif /* !NO_POPEN */
  10558. static int
  10559. mg_fgetc(struct mg_file *filep)
  10560. {
  10561. if (filep == NULL) {
  10562. return EOF;
  10563. }
  10564. if (filep->access.fp != NULL) {
  10565. return fgetc(filep->access.fp);
  10566. } else {
  10567. return EOF;
  10568. }
  10569. }
  10570. static void
  10571. send_ssi_file(struct mg_connection *conn,
  10572. const char *path,
  10573. struct mg_file *filep,
  10574. int include_level)
  10575. {
  10576. char buf[MG_BUF_LEN];
  10577. int ch, len, in_tag, in_ssi_tag;
  10578. if (include_level > 10) {
  10579. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10580. return;
  10581. }
  10582. in_tag = in_ssi_tag = len = 0;
  10583. /* Read file, byte by byte, and look for SSI include tags */
  10584. while ((ch = mg_fgetc(filep)) != EOF) {
  10585. if (in_tag) {
  10586. /* We are in a tag, either SSI tag or html tag */
  10587. if (ch == '>') {
  10588. /* Tag is closing */
  10589. buf[len++] = '>';
  10590. if (in_ssi_tag) {
  10591. /* Handle SSI tag */
  10592. buf[len] = 0;
  10593. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10594. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10595. #if !defined(NO_POPEN)
  10596. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10597. do_ssi_exec(conn, buf + 9);
  10598. #endif /* !NO_POPEN */
  10599. } else {
  10600. mg_cry_internal(conn,
  10601. "%s: unknown SSI "
  10602. "command: \"%s\"",
  10603. path,
  10604. buf);
  10605. }
  10606. len = 0;
  10607. in_ssi_tag = in_tag = 0;
  10608. } else {
  10609. /* Not an SSI tag */
  10610. /* Flush buffer */
  10611. (void)mg_write(conn, buf, (size_t)len);
  10612. len = 0;
  10613. in_tag = 0;
  10614. }
  10615. } else {
  10616. /* Tag is still open */
  10617. buf[len++] = (char)(ch & 0xff);
  10618. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10619. /* All SSI tags start with <!--# */
  10620. in_ssi_tag = 1;
  10621. }
  10622. if ((len + 2) > (int)sizeof(buf)) {
  10623. /* Tag to long for buffer */
  10624. mg_cry_internal(conn, "%s: tag is too large", path);
  10625. return;
  10626. }
  10627. }
  10628. } else {
  10629. /* We are not in a tag yet. */
  10630. if (ch == '<') {
  10631. /* Tag is opening */
  10632. in_tag = 1;
  10633. if (len > 0) {
  10634. /* Flush current buffer.
  10635. * Buffer is filled with "len" bytes. */
  10636. (void)mg_write(conn, buf, (size_t)len);
  10637. }
  10638. /* Store the < */
  10639. len = 1;
  10640. buf[0] = '<';
  10641. } else {
  10642. /* No Tag */
  10643. /* Add data to buffer */
  10644. buf[len++] = (char)(ch & 0xff);
  10645. /* Flush if buffer is full */
  10646. if (len == (int)sizeof(buf)) {
  10647. mg_write(conn, buf, (size_t)len);
  10648. len = 0;
  10649. }
  10650. }
  10651. }
  10652. }
  10653. /* Send the rest of buffered data */
  10654. if (len > 0) {
  10655. mg_write(conn, buf, (size_t)len);
  10656. }
  10657. }
  10658. static void
  10659. handle_ssi_file_request(struct mg_connection *conn,
  10660. const char *path,
  10661. struct mg_file *filep)
  10662. {
  10663. char date[64];
  10664. time_t curtime = time(NULL);
  10665. const char *cors_orig_cfg;
  10666. const char *cors1, *cors2;
  10667. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10668. return;
  10669. }
  10670. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10671. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10672. /* Cross-origin resource sharing (CORS). */
  10673. cors1 = "Access-Control-Allow-Origin";
  10674. cors2 = cors_orig_cfg;
  10675. } else {
  10676. cors1 = cors2 = "";
  10677. }
  10678. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10679. /* File exists (precondition for calling this function),
  10680. * but can not be opened by the server. */
  10681. mg_send_http_error(conn,
  10682. 500,
  10683. "Error: Cannot read file\nfopen(%s): %s",
  10684. path,
  10685. strerror(ERRNO));
  10686. } else {
  10687. /* Set "must_close" for HTTP/1.x, since we do not know the
  10688. * content length */
  10689. conn->must_close = 1;
  10690. gmt_time_string(date, sizeof(date), &curtime);
  10691. fclose_on_exec(&filep->access, conn);
  10692. /* 200 OK response */
  10693. mg_response_header_start(conn, 200);
  10694. send_no_cache_header(conn);
  10695. send_additional_header(conn);
  10696. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10697. if (cors1[0]) {
  10698. mg_response_header_add(conn, cors1, cors2, -1);
  10699. }
  10700. mg_response_header_send(conn);
  10701. /* Header sent, now send body */
  10702. send_ssi_file(conn, path, filep, 0);
  10703. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10704. }
  10705. }
  10706. #endif /* NO_FILESYSTEMS */
  10707. #if !defined(NO_FILES)
  10708. static void
  10709. send_options(struct mg_connection *conn)
  10710. {
  10711. if (!conn) {
  10712. return;
  10713. }
  10714. /* We do not set a "Cache-Control" header here, but leave the default.
  10715. * Since browsers do not send an OPTIONS request, we can not test the
  10716. * effect anyway. */
  10717. mg_response_header_start(conn, 200);
  10718. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10719. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10720. /* Use the same as before */
  10721. mg_response_header_add(
  10722. conn,
  10723. "Allow",
  10724. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10725. -1);
  10726. mg_response_header_add(conn, "DAV", "1", -1);
  10727. } else {
  10728. /* TODO: Check this later for HTTP/2 */
  10729. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10730. }
  10731. send_additional_header(conn);
  10732. mg_response_header_send(conn);
  10733. }
  10734. /* Writes PROPFIND properties for a collection element */
  10735. static int
  10736. print_props(struct mg_connection *conn,
  10737. const char *uri,
  10738. const char *name,
  10739. struct mg_file_stat *filep)
  10740. {
  10741. size_t href_size, i, j;
  10742. int len;
  10743. char *href, mtime[64];
  10744. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10745. return 0;
  10746. }
  10747. /* Estimate worst case size for encoding */
  10748. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10749. href = (char *)mg_malloc(href_size);
  10750. if (href == NULL) {
  10751. return 0;
  10752. }
  10753. len = mg_url_encode(uri, href, href_size);
  10754. if (len >= 0) {
  10755. /* Append an extra string */
  10756. mg_url_encode(name, href + len, href_size - (size_t)len);
  10757. }
  10758. /* Directory separator should be preserved. */
  10759. for (i = j = 0; href[i]; j++) {
  10760. if (!strncmp(href + i, "%2f", 3)) {
  10761. href[j] = '/';
  10762. i += 3;
  10763. } else {
  10764. href[j] = href[i++];
  10765. }
  10766. }
  10767. href[j] = '\0';
  10768. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10769. mg_printf(conn,
  10770. "<d:response>"
  10771. "<d:href>%s</d:href>"
  10772. "<d:propstat>"
  10773. "<d:prop>"
  10774. "<d:resourcetype>%s</d:resourcetype>"
  10775. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10776. "<d:getlastmodified>%s</d:getlastmodified>"
  10777. "</d:prop>"
  10778. "<d:status>HTTP/1.1 200 OK</d:status>"
  10779. "</d:propstat>"
  10780. "</d:response>\n",
  10781. href,
  10782. filep->is_directory ? "<d:collection/>" : "",
  10783. filep->size,
  10784. mtime);
  10785. mg_free(href);
  10786. return 1;
  10787. }
  10788. static int
  10789. print_dav_dir_entry(struct de *de, void *data)
  10790. {
  10791. struct mg_connection *conn = (struct mg_connection *)data;
  10792. if (!de || !conn
  10793. || !print_props(
  10794. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10795. /* stop scan */
  10796. return 1;
  10797. }
  10798. return 0;
  10799. }
  10800. static void
  10801. handle_propfind(struct mg_connection *conn,
  10802. const char *path,
  10803. struct mg_file_stat *filep)
  10804. {
  10805. const char *depth = mg_get_header(conn, "Depth");
  10806. char date[64];
  10807. time_t curtime = time(NULL);
  10808. gmt_time_string(date, sizeof(date), &curtime);
  10809. if (!conn || !path || !filep || !conn->dom_ctx) {
  10810. return;
  10811. }
  10812. conn->must_close = 1;
  10813. /* return 207 "Multi-Status" */
  10814. mg_response_header_start(conn, 207);
  10815. send_static_cache_header(conn);
  10816. send_additional_header(conn);
  10817. mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10818. mg_response_header_send(conn);
  10819. /* Content */
  10820. mg_printf(conn,
  10821. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10822. "<d:multistatus xmlns:d='DAV:'>\n");
  10823. /* Print properties for the requested resource itself */
  10824. print_props(conn, conn->request_info.local_uri, "", filep);
  10825. /* If it is a directory, print directory entries too if Depth is not 0
  10826. */
  10827. if (filep->is_directory
  10828. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10829. "yes")
  10830. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10831. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10832. }
  10833. mg_printf(conn, "%s\n", "</d:multistatus>");
  10834. }
  10835. #endif
  10836. void
  10837. mg_lock_connection(struct mg_connection *conn)
  10838. {
  10839. if (conn) {
  10840. (void)pthread_mutex_lock(&conn->mutex);
  10841. }
  10842. }
  10843. void
  10844. mg_unlock_connection(struct mg_connection *conn)
  10845. {
  10846. if (conn) {
  10847. (void)pthread_mutex_unlock(&conn->mutex);
  10848. }
  10849. }
  10850. void
  10851. mg_lock_context(struct mg_context *ctx)
  10852. {
  10853. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10854. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10855. }
  10856. }
  10857. void
  10858. mg_unlock_context(struct mg_context *ctx)
  10859. {
  10860. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10861. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10862. }
  10863. }
  10864. #if defined(USE_LUA)
  10865. #include "mod_lua.inl"
  10866. #endif /* USE_LUA */
  10867. #if defined(USE_DUKTAPE)
  10868. #include "mod_duktape.inl"
  10869. #endif /* USE_DUKTAPE */
  10870. #if defined(USE_WEBSOCKET)
  10871. #if !defined(NO_SSL_DL)
  10872. #define SHA_API static
  10873. #include "sha1.inl"
  10874. #endif
  10875. static int
  10876. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10877. {
  10878. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10879. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10880. SHA_CTX sha_ctx;
  10881. int truncated;
  10882. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10883. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10884. if (truncated) {
  10885. conn->must_close = 1;
  10886. return 0;
  10887. }
  10888. DEBUG_TRACE("%s", "Send websocket handshake");
  10889. SHA1_Init(&sha_ctx);
  10890. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10891. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10892. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10893. mg_printf(conn,
  10894. "HTTP/1.1 101 Switching Protocols\r\n"
  10895. "Upgrade: websocket\r\n"
  10896. "Connection: Upgrade\r\n"
  10897. "Sec-WebSocket-Accept: %s\r\n",
  10898. b64_sha);
  10899. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10900. // Send negotiated compression extension parameters
  10901. websocket_deflate_response(conn);
  10902. #endif
  10903. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10904. mg_printf(conn,
  10905. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10906. conn->request_info.acceptedWebSocketSubprotocol);
  10907. } else {
  10908. mg_printf(conn, "%s", "\r\n");
  10909. }
  10910. return 1;
  10911. }
  10912. #if !defined(MG_MAX_UNANSWERED_PING)
  10913. /* Configuration of the maximum number of websocket PINGs that might
  10914. * stay unanswered before the connection is considered broken.
  10915. * Note: The name of this define may still change (until it is
  10916. * defined as a compile parameter in a documentation).
  10917. */
  10918. #define MG_MAX_UNANSWERED_PING (5)
  10919. #endif
  10920. static void
  10921. read_websocket(struct mg_connection *conn,
  10922. mg_websocket_data_handler ws_data_handler,
  10923. void *callback_data)
  10924. {
  10925. /* Pointer to the beginning of the portion of the incoming websocket
  10926. * message queue.
  10927. * The original websocket upgrade request is never removed, so the queue
  10928. * begins after it. */
  10929. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10930. int n, error, exit_by_callback;
  10931. int ret;
  10932. /* body_len is the length of the entire queue in bytes
  10933. * len is the length of the current message
  10934. * data_len is the length of the current message's data payload
  10935. * header_len is the length of the current message's header */
  10936. size_t i, len, mask_len = 0, header_len, body_len;
  10937. uint64_t data_len = 0;
  10938. /* "The masking key is a 32-bit value chosen at random by the client."
  10939. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10940. */
  10941. unsigned char mask[4];
  10942. /* data points to the place where the message is stored when passed to
  10943. * the websocket_data callback. This is either mem on the stack, or a
  10944. * dynamically allocated buffer if it is too large. */
  10945. unsigned char mem[4096];
  10946. unsigned char mop; /* mask flag and opcode */
  10947. /* Variables used for connection monitoring */
  10948. double timeout = -1.0;
  10949. int enable_ping_pong = 0;
  10950. int ping_count = 0;
  10951. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10952. enable_ping_pong =
  10953. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10954. "yes");
  10955. }
  10956. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10957. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10958. }
  10959. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10960. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10961. }
  10962. if (timeout <= 0.0) {
  10963. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  10964. }
  10965. /* Enter data processing loop */
  10966. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10967. conn->request_info.remote_addr,
  10968. conn->request_info.remote_port);
  10969. conn->in_websocket_handling = 1;
  10970. mg_set_thread_name("wsock");
  10971. /* Loop continuously, reading messages from the socket, invoking the
  10972. * callback, and waiting repeatedly until an error occurs. */
  10973. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10974. && (!conn->must_close)) {
  10975. header_len = 0;
  10976. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10977. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10978. len = buf[1] & 127;
  10979. mask_len = (buf[1] & 128) ? 4 : 0;
  10980. if ((len < 126) && (body_len >= mask_len)) {
  10981. /* inline 7-bit length field */
  10982. data_len = len;
  10983. header_len = 2 + mask_len;
  10984. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10985. /* 16-bit length field */
  10986. header_len = 4 + mask_len;
  10987. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10988. } else if (body_len >= (10 + mask_len)) {
  10989. /* 64-bit length field */
  10990. uint32_t l1, l2;
  10991. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10992. memcpy(&l2, &buf[6], 4);
  10993. header_len = 10 + mask_len;
  10994. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10995. if (data_len > (uint64_t)0x7FFF0000ul) {
  10996. /* no can do */
  10997. mg_cry_internal(
  10998. conn,
  10999. "%s",
  11000. "websocket out of memory; closing connection");
  11001. break;
  11002. }
  11003. }
  11004. }
  11005. if ((header_len > 0) && (body_len >= header_len)) {
  11006. /* Allocate space to hold websocket payload */
  11007. unsigned char *data = mem;
  11008. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11009. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11010. conn->phys_ctx);
  11011. if (data == NULL) {
  11012. /* Allocation failed, exit the loop and then close the
  11013. * connection */
  11014. mg_cry_internal(
  11015. conn,
  11016. "%s",
  11017. "websocket out of memory; closing connection");
  11018. break;
  11019. }
  11020. }
  11021. /* Copy the mask before we shift the queue and destroy it */
  11022. if (mask_len > 0) {
  11023. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11024. } else {
  11025. memset(mask, 0, sizeof(mask));
  11026. }
  11027. /* Read frame payload from the first message in the queue into
  11028. * data and advance the queue by moving the memory in place. */
  11029. DEBUG_ASSERT(body_len >= header_len);
  11030. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11031. mop = buf[0]; /* current mask and opcode */
  11032. /* Overflow case */
  11033. len = body_len - header_len;
  11034. memcpy(data, buf + header_len, len);
  11035. error = 0;
  11036. while ((uint64_t)len < data_len) {
  11037. n = pull_inner(NULL,
  11038. conn,
  11039. (char *)(data + len),
  11040. (int)(data_len - len),
  11041. timeout);
  11042. if (n <= -2) {
  11043. error = 1;
  11044. break;
  11045. } else if (n > 0) {
  11046. len += (size_t)n;
  11047. } else {
  11048. /* Timeout: should retry */
  11049. /* TODO: retry condition */
  11050. }
  11051. }
  11052. if (error) {
  11053. mg_cry_internal(
  11054. conn,
  11055. "%s",
  11056. "Websocket pull failed; closing connection");
  11057. if (data != mem) {
  11058. mg_free(data);
  11059. }
  11060. break;
  11061. }
  11062. conn->data_len = conn->request_len;
  11063. } else {
  11064. mop = buf[0]; /* current mask and opcode, overwritten by
  11065. * memmove() */
  11066. /* Length of the message being read at the front of the
  11067. * queue. Cast to 31 bit is OK, since we limited
  11068. * data_len before. */
  11069. len = (size_t)data_len + header_len;
  11070. /* Copy the data payload into the data pointer for the
  11071. * callback. Cast to 31 bit is OK, since we
  11072. * limited data_len */
  11073. memcpy(data, buf + header_len, (size_t)data_len);
  11074. /* Move the queue forward len bytes */
  11075. memmove(buf, buf + len, body_len - len);
  11076. /* Mark the queue as advanced */
  11077. conn->data_len -= (int)len;
  11078. }
  11079. /* Apply mask if necessary */
  11080. if (mask_len > 0) {
  11081. for (i = 0; i < (size_t)data_len; i++) {
  11082. data[i] ^= mask[i & 3];
  11083. }
  11084. }
  11085. exit_by_callback = 0;
  11086. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11087. /* filter PONG messages */
  11088. DEBUG_TRACE("PONG from %s:%u",
  11089. conn->request_info.remote_addr,
  11090. conn->request_info.remote_port);
  11091. /* No unanwered PINGs left */
  11092. ping_count = 0;
  11093. } else if (enable_ping_pong
  11094. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11095. /* reply PING messages */
  11096. DEBUG_TRACE("Reply PING from %s:%u",
  11097. conn->request_info.remote_addr,
  11098. conn->request_info.remote_port);
  11099. ret = mg_websocket_write(conn,
  11100. MG_WEBSOCKET_OPCODE_PONG,
  11101. (char *)data,
  11102. (size_t)data_len);
  11103. if (ret <= 0) {
  11104. /* Error: send failed */
  11105. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11106. break;
  11107. }
  11108. } else {
  11109. /* Exit the loop if callback signals to exit (server side),
  11110. * or "connection close" opcode received (client side). */
  11111. if (ws_data_handler != NULL) {
  11112. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11113. if (mop & 0x40) {
  11114. /* Inflate the data received if bit RSV1 is set. */
  11115. if (!conn->websocket_deflate_initialized) {
  11116. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11117. exit_by_callback = 1;
  11118. }
  11119. if (!exit_by_callback) {
  11120. size_t inflate_buf_size_old = 0;
  11121. size_t inflate_buf_size =
  11122. data_len
  11123. * 4; // Initial guess of the inflated message
  11124. // size. We double the memory when needed.
  11125. Bytef *inflated;
  11126. Bytef *new_mem;
  11127. conn->websocket_inflate_state.avail_in =
  11128. (uInt)(data_len + 4);
  11129. conn->websocket_inflate_state.next_in = data;
  11130. // Add trailing 0x00 0x00 0xff 0xff bytes
  11131. data[data_len] = '\x00';
  11132. data[data_len + 1] = '\x00';
  11133. data[data_len + 2] = '\xff';
  11134. data[data_len + 3] = '\xff';
  11135. do {
  11136. if (inflate_buf_size_old == 0) {
  11137. new_mem = mg_calloc(inflate_buf_size,
  11138. sizeof(Bytef));
  11139. } else {
  11140. inflate_buf_size *= 2;
  11141. new_mem =
  11142. mg_realloc(inflated, inflate_buf_size);
  11143. }
  11144. if (new_mem == NULL) {
  11145. mg_cry_internal(
  11146. conn,
  11147. "Out of memory: Cannot allocate "
  11148. "inflate buffer of %i bytes",
  11149. inflate_buf_size);
  11150. exit_by_callback = 1;
  11151. break;
  11152. }
  11153. inflated = new_mem;
  11154. conn->websocket_inflate_state.avail_out =
  11155. (uInt)(inflate_buf_size
  11156. - inflate_buf_size_old);
  11157. conn->websocket_inflate_state.next_out =
  11158. inflated + inflate_buf_size_old;
  11159. int ret =
  11160. inflate(&conn->websocket_inflate_state,
  11161. Z_SYNC_FLUSH);
  11162. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11163. || ret == Z_MEM_ERROR || ret < 0) {
  11164. mg_cry_internal(
  11165. conn,
  11166. "ZLIB inflate error: %i %s",
  11167. ret,
  11168. (conn->websocket_inflate_state.msg
  11169. ? conn->websocket_inflate_state.msg
  11170. : "<no error message>"));
  11171. exit_by_callback = 1;
  11172. break;
  11173. }
  11174. inflate_buf_size_old = inflate_buf_size;
  11175. } while (conn->websocket_inflate_state.avail_out
  11176. == 0);
  11177. inflate_buf_size -=
  11178. conn->websocket_inflate_state.avail_out;
  11179. if (!ws_data_handler(conn,
  11180. mop,
  11181. (char *)inflated,
  11182. inflate_buf_size,
  11183. callback_data)) {
  11184. exit_by_callback = 1;
  11185. }
  11186. mg_free(inflated);
  11187. }
  11188. } else
  11189. #endif
  11190. if (!ws_data_handler(conn,
  11191. mop,
  11192. (char *)data,
  11193. (size_t)data_len,
  11194. callback_data)) {
  11195. exit_by_callback = 1;
  11196. }
  11197. }
  11198. }
  11199. /* It a buffer has been allocated, free it again */
  11200. if (data != mem) {
  11201. mg_free(data);
  11202. }
  11203. if (exit_by_callback) {
  11204. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11205. conn->request_info.remote_addr,
  11206. conn->request_info.remote_port);
  11207. break;
  11208. }
  11209. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11210. /* Opcode == 8, connection close */
  11211. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11212. conn->request_info.remote_addr,
  11213. conn->request_info.remote_port);
  11214. break;
  11215. }
  11216. /* Not breaking the loop, process next websocket frame. */
  11217. } else {
  11218. /* Read from the socket into the next available location in the
  11219. * message queue. */
  11220. n = pull_inner(NULL,
  11221. conn,
  11222. conn->buf + conn->data_len,
  11223. conn->buf_size - conn->data_len,
  11224. timeout);
  11225. if (n <= -2) {
  11226. /* Error, no bytes read */
  11227. DEBUG_TRACE("PULL from %s:%u failed",
  11228. conn->request_info.remote_addr,
  11229. conn->request_info.remote_port);
  11230. break;
  11231. }
  11232. if (n > 0) {
  11233. conn->data_len += n;
  11234. /* Reset open PING count */
  11235. ping_count = 0;
  11236. } else {
  11237. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11238. && (!conn->must_close)) {
  11239. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11240. /* Stop sending PING */
  11241. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11242. "- closing connection",
  11243. ping_count,
  11244. conn->request_info.remote_addr,
  11245. conn->request_info.remote_port);
  11246. break;
  11247. }
  11248. if (enable_ping_pong) {
  11249. /* Send Websocket PING message */
  11250. DEBUG_TRACE("PING to %s:%u",
  11251. conn->request_info.remote_addr,
  11252. conn->request_info.remote_port);
  11253. ret = mg_websocket_write(conn,
  11254. MG_WEBSOCKET_OPCODE_PING,
  11255. NULL,
  11256. 0);
  11257. if (ret <= 0) {
  11258. /* Error: send failed */
  11259. DEBUG_TRACE("Send PING failed (%i)", ret);
  11260. break;
  11261. }
  11262. ping_count++;
  11263. }
  11264. }
  11265. /* Timeout: should retry */
  11266. /* TODO: get timeout def */
  11267. }
  11268. }
  11269. }
  11270. /* Leave data processing loop */
  11271. mg_set_thread_name("worker");
  11272. conn->in_websocket_handling = 0;
  11273. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11274. conn->request_info.remote_addr,
  11275. conn->request_info.remote_port);
  11276. }
  11277. static int
  11278. mg_websocket_write_exec(struct mg_connection *conn,
  11279. int opcode,
  11280. const char *data,
  11281. size_t dataLen,
  11282. uint32_t masking_key)
  11283. {
  11284. unsigned char header[14];
  11285. size_t headerLen;
  11286. int retval;
  11287. #if defined(GCC_DIAGNOSTIC)
  11288. /* Disable spurious conversion warning for GCC */
  11289. #pragma GCC diagnostic push
  11290. #pragma GCC diagnostic ignored "-Wconversion"
  11291. #endif
  11292. /* Note that POSIX/Winsock's send() is threadsafe
  11293. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11294. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11295. * push(), although that is only a problem if the packet is large or
  11296. * outgoing buffer is full). */
  11297. /* TODO: Check if this lock should be moved to user land.
  11298. * Currently the server sets this lock for websockets, but
  11299. * not for any other connection. It must be set for every
  11300. * conn read/written by more than one thread, no matter if
  11301. * it is a websocket or regular connection. */
  11302. (void)mg_lock_connection(conn);
  11303. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11304. size_t deflated_size;
  11305. Bytef *deflated;
  11306. // Deflate websocket messages over 100kb
  11307. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11308. if (use_deflate) {
  11309. if (!conn->websocket_deflate_initialized) {
  11310. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11311. return 0;
  11312. }
  11313. // Deflating the message
  11314. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11315. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11316. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11317. deflated_size = compressBound((uLong)dataLen);
  11318. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11319. if (deflated == NULL) {
  11320. mg_cry_internal(
  11321. conn,
  11322. "Out of memory: Cannot allocate deflate buffer of %i bytes",
  11323. deflated_size);
  11324. mg_unlock_connection(conn);
  11325. return -1;
  11326. }
  11327. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11328. conn->websocket_deflate_state.next_out = deflated;
  11329. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11330. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11331. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11332. } else
  11333. #endif
  11334. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11335. #if defined(GCC_DIAGNOSTIC)
  11336. #pragma GCC diagnostic pop
  11337. #endif
  11338. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11339. if (dataLen < 126) {
  11340. /* inline 7-bit length field */
  11341. header[1] = (unsigned char)dataLen;
  11342. headerLen = 2;
  11343. } else if (dataLen <= 0xFFFF) {
  11344. /* 16-bit length field */
  11345. uint16_t len = htons((uint16_t)dataLen);
  11346. header[1] = 126;
  11347. memcpy(header + 2, &len, 2);
  11348. headerLen = 4;
  11349. } else {
  11350. /* 64-bit length field */
  11351. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11352. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11353. header[1] = 127;
  11354. memcpy(header + 2, &len1, 4);
  11355. memcpy(header + 6, &len2, 4);
  11356. headerLen = 10;
  11357. }
  11358. if (masking_key) {
  11359. /* add mask */
  11360. header[1] |= 0x80;
  11361. memcpy(header + headerLen, &masking_key, 4);
  11362. headerLen += 4;
  11363. }
  11364. retval = mg_write(conn, header, headerLen);
  11365. if (retval != (int)headerLen) {
  11366. /* Did not send complete header */
  11367. retval = -1;
  11368. } else {
  11369. if (dataLen > 0) {
  11370. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11371. if (use_deflate) {
  11372. retval = mg_write(conn, deflated, dataLen);
  11373. mg_free(deflated);
  11374. } else
  11375. #endif
  11376. retval = mg_write(conn, data, dataLen);
  11377. }
  11378. /* if dataLen == 0, the header length (2) is returned */
  11379. }
  11380. /* TODO: Remove this unlock as well, when lock is removed. */
  11381. mg_unlock_connection(conn);
  11382. return retval;
  11383. }
  11384. int
  11385. mg_websocket_write(struct mg_connection *conn,
  11386. int opcode,
  11387. const char *data,
  11388. size_t dataLen)
  11389. {
  11390. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11391. }
  11392. static void
  11393. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11394. {
  11395. size_t i = 0;
  11396. i = 0;
  11397. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11398. /* Convert in 32 bit words, if data is 4 byte aligned */
  11399. while (i < (in_len - 3)) {
  11400. *(uint32_t *)(void *)(out + i) =
  11401. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11402. i += 4;
  11403. }
  11404. }
  11405. if (i != in_len) {
  11406. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11407. while (i < in_len) {
  11408. *(uint8_t *)(void *)(out + i) =
  11409. *(uint8_t *)(void *)(in + i)
  11410. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11411. i++;
  11412. }
  11413. }
  11414. }
  11415. int
  11416. mg_websocket_client_write(struct mg_connection *conn,
  11417. int opcode,
  11418. const char *data,
  11419. size_t dataLen)
  11420. {
  11421. int retval = -1;
  11422. char *masked_data =
  11423. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11424. uint32_t masking_key = 0;
  11425. if (masked_data == NULL) {
  11426. /* Return -1 in an error case */
  11427. mg_cry_internal(conn,
  11428. "%s",
  11429. "Cannot allocate buffer for masked websocket response: "
  11430. "Out of memory");
  11431. return -1;
  11432. }
  11433. do {
  11434. /* Get a masking key - but not 0 */
  11435. masking_key = (uint32_t)get_random();
  11436. } while (masking_key == 0);
  11437. mask_data(data, dataLen, masking_key, masked_data);
  11438. retval = mg_websocket_write_exec(
  11439. conn, opcode, masked_data, dataLen, masking_key);
  11440. mg_free(masked_data);
  11441. return retval;
  11442. }
  11443. static void
  11444. handle_websocket_request(struct mg_connection *conn,
  11445. const char *path,
  11446. int is_callback_resource,
  11447. struct mg_websocket_subprotocols *subprotocols,
  11448. mg_websocket_connect_handler ws_connect_handler,
  11449. mg_websocket_ready_handler ws_ready_handler,
  11450. mg_websocket_data_handler ws_data_handler,
  11451. mg_websocket_close_handler ws_close_handler,
  11452. void *cbData)
  11453. {
  11454. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11455. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11456. ptrdiff_t lua_websock = 0;
  11457. #if !defined(USE_LUA)
  11458. (void)path;
  11459. #endif
  11460. /* Step 1: Check websocket protocol version. */
  11461. /* Step 1.1: Check Sec-WebSocket-Key. */
  11462. if (!websock_key) {
  11463. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11464. * requires a Sec-WebSocket-Key header.
  11465. */
  11466. /* It could be the hixie draft version
  11467. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11468. */
  11469. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11470. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11471. char key3[8];
  11472. if ((key1 != NULL) && (key2 != NULL)) {
  11473. /* This version uses 8 byte body data in a GET request */
  11474. conn->content_len = 8;
  11475. if (8 == mg_read(conn, key3, 8)) {
  11476. /* This is the hixie version */
  11477. mg_send_http_error(conn,
  11478. 426,
  11479. "%s",
  11480. "Protocol upgrade to RFC 6455 required");
  11481. return;
  11482. }
  11483. }
  11484. /* This is an unknown version */
  11485. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11486. return;
  11487. }
  11488. /* Step 1.2: Check websocket protocol version. */
  11489. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11490. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11491. /* Reject wrong versions */
  11492. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11493. return;
  11494. }
  11495. /* Step 1.3: Could check for "Host", but we do not really nead this
  11496. * value for anything, so just ignore it. */
  11497. /* Step 2: If a callback is responsible, call it. */
  11498. if (is_callback_resource) {
  11499. /* Step 2.1 check and select subprotocol */
  11500. const char *protocols[64]; // max 64 headers
  11501. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11502. "Sec-WebSocket-Protocol",
  11503. protocols,
  11504. 64);
  11505. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11506. int cnt = 0;
  11507. int idx;
  11508. unsigned long len;
  11509. const char *sep, *curSubProtocol,
  11510. *acceptedWebSocketSubprotocol = NULL;
  11511. /* look for matching subprotocol */
  11512. do {
  11513. const char *protocol = protocols[cnt];
  11514. do {
  11515. sep = strchr(protocol, ',');
  11516. curSubProtocol = protocol;
  11517. len = sep ? (unsigned long)(sep - protocol)
  11518. : (unsigned long)strlen(protocol);
  11519. while (sep && isspace((unsigned char)*++sep))
  11520. ; // ignore leading whitespaces
  11521. protocol = sep;
  11522. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11523. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11524. && (strncmp(curSubProtocol,
  11525. subprotocols->subprotocols[idx],
  11526. len)
  11527. == 0)) {
  11528. acceptedWebSocketSubprotocol =
  11529. subprotocols->subprotocols[idx];
  11530. break;
  11531. }
  11532. }
  11533. } while (sep && !acceptedWebSocketSubprotocol);
  11534. } while (++cnt < nbSubprotocolHeader
  11535. && !acceptedWebSocketSubprotocol);
  11536. conn->request_info.acceptedWebSocketSubprotocol =
  11537. acceptedWebSocketSubprotocol;
  11538. } else if (nbSubprotocolHeader > 0) {
  11539. /* keep legacy behavior */
  11540. const char *protocol = protocols[0];
  11541. /* The protocol is a comma separated list of names. */
  11542. /* The server must only return one value from this list. */
  11543. /* First check if it is a list or just a single value. */
  11544. const char *sep = strrchr(protocol, ',');
  11545. if (sep == NULL) {
  11546. /* Just a single protocol -> accept it. */
  11547. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11548. } else {
  11549. /* Multiple protocols -> accept the last one. */
  11550. /* This is just a quick fix if the client offers multiple
  11551. * protocols. The handler should have a list of accepted
  11552. * protocols on his own
  11553. * and use it to select one protocol among those the client
  11554. * has
  11555. * offered.
  11556. */
  11557. while (isspace((unsigned char)*++sep)) {
  11558. ; /* ignore leading whitespaces */
  11559. }
  11560. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11561. }
  11562. }
  11563. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11564. websocket_deflate_negotiate(conn);
  11565. #endif
  11566. if ((ws_connect_handler != NULL)
  11567. && (ws_connect_handler(conn, cbData) != 0)) {
  11568. /* C callback has returned non-zero, do not proceed with
  11569. * handshake.
  11570. */
  11571. /* Note that C callbacks are no longer called when Lua is
  11572. * responsible, so C can no longer filter callbacks for Lua. */
  11573. return;
  11574. }
  11575. }
  11576. #if defined(USE_LUA)
  11577. /* Step 3: No callback. Check if Lua is responsible. */
  11578. else {
  11579. /* Step 3.1: Check if Lua is responsible. */
  11580. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11581. lua_websock = match_prefix_strlen(
  11582. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11583. }
  11584. if (lua_websock) {
  11585. /* Step 3.2: Lua is responsible: call it. */
  11586. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11587. if (!conn->lua_websocket_state) {
  11588. /* Lua rejected the new client */
  11589. return;
  11590. }
  11591. }
  11592. }
  11593. #endif
  11594. /* Step 4: Check if there is a responsible websocket handler. */
  11595. if (!is_callback_resource && !lua_websock) {
  11596. /* There is no callback, and Lua is not responsible either. */
  11597. /* Reply with a 404 Not Found. We are still at a standard
  11598. * HTTP request here, before the websocket handshake, so
  11599. * we can still send standard HTTP error replies. */
  11600. mg_send_http_error(conn, 404, "%s", "Not found");
  11601. return;
  11602. }
  11603. /* Step 5: The websocket connection has been accepted */
  11604. if (!send_websocket_handshake(conn, websock_key)) {
  11605. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11606. return;
  11607. }
  11608. /* Step 6: Call the ready handler */
  11609. if (is_callback_resource) {
  11610. if (ws_ready_handler != NULL) {
  11611. ws_ready_handler(conn, cbData);
  11612. }
  11613. #if defined(USE_LUA)
  11614. } else if (lua_websock) {
  11615. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11616. /* the ready handler returned false */
  11617. return;
  11618. }
  11619. #endif
  11620. }
  11621. /* Step 7: Enter the read loop */
  11622. if (is_callback_resource) {
  11623. read_websocket(conn, ws_data_handler, cbData);
  11624. #if defined(USE_LUA)
  11625. } else if (lua_websock) {
  11626. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11627. #endif
  11628. }
  11629. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11630. /* Step 8: Close the deflate & inflate buffers */
  11631. if (conn->websocket_deflate_initialized) {
  11632. deflateEnd(&conn->websocket_deflate_state);
  11633. inflateEnd(&conn->websocket_inflate_state);
  11634. }
  11635. #endif
  11636. /* Step 9: Call the close handler */
  11637. if (ws_close_handler) {
  11638. ws_close_handler(conn, cbData);
  11639. }
  11640. }
  11641. #endif /* !USE_WEBSOCKET */
  11642. /* Is upgrade request:
  11643. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11644. * 1 = upgrade to websocket
  11645. * 2 = upgrade to HTTP/2
  11646. * -1 = upgrade to unknown protocol
  11647. */
  11648. static int
  11649. should_switch_to_protocol(const struct mg_connection *conn)
  11650. {
  11651. const char *upgrade, *connection;
  11652. /* A websocket protocoll has the following HTTP headers:
  11653. *
  11654. * Connection: Upgrade
  11655. * Upgrade: Websocket
  11656. */
  11657. connection = mg_get_header(conn, "Connection");
  11658. if (connection == NULL) {
  11659. return PROTOCOL_TYPE_HTTP1;
  11660. }
  11661. if (!mg_strcasestr(connection, "upgrade")) {
  11662. return PROTOCOL_TYPE_HTTP1;
  11663. }
  11664. upgrade = mg_get_header(conn, "Upgrade");
  11665. if (upgrade == NULL) {
  11666. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11667. return -1;
  11668. }
  11669. /* Upgrade to ... */
  11670. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11671. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11672. * "Sec-WebSocket-Version" are also required.
  11673. * Don't check them here, since even an unsupported websocket protocol
  11674. * request still IS a websocket request (in contrast to a standard HTTP
  11675. * request). It will fail later in handle_websocket_request.
  11676. */
  11677. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11678. }
  11679. if (0 != mg_strcasestr(upgrade, "h2")) {
  11680. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11681. }
  11682. /* Upgrade to another protocol */
  11683. return -1;
  11684. }
  11685. static int
  11686. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11687. {
  11688. int n;
  11689. unsigned int a, b, c, d, slash;
  11690. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11691. slash = 32;
  11692. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11693. n = 0;
  11694. }
  11695. }
  11696. if ((n > 0) && ((size_t)n == vec->len)) {
  11697. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11698. /* IPv4 format */
  11699. if (sa->sa.sa_family == AF_INET) {
  11700. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11701. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11702. | ((uint32_t)c << 8) | (uint32_t)d;
  11703. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11704. return (ip & mask) == net;
  11705. }
  11706. return 0;
  11707. }
  11708. }
  11709. #if defined(USE_IPV6)
  11710. else {
  11711. char ad[50];
  11712. const char *p;
  11713. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11714. slash = 128;
  11715. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11716. n = 0;
  11717. }
  11718. }
  11719. if ((n <= 0) && no_strict) {
  11720. /* no square brackets? */
  11721. p = strchr(vec->ptr, '/');
  11722. if (p && (p < (vec->ptr + vec->len))) {
  11723. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11724. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11725. n += (int)(p - vec->ptr);
  11726. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11727. } else {
  11728. n = 0;
  11729. }
  11730. } else if (vec->len < sizeof(ad)) {
  11731. n = (int)vec->len;
  11732. slash = 128;
  11733. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11734. }
  11735. }
  11736. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11737. p = ad;
  11738. c = 0;
  11739. /* zone indexes are unsupported, at least two colons are needed */
  11740. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11741. if (*(p++) == ':') {
  11742. c++;
  11743. }
  11744. }
  11745. if ((*p == '\0') && (c >= 2)) {
  11746. struct sockaddr_in6 sin6;
  11747. unsigned int i;
  11748. /* for strict validation, an actual IPv6 argument is needed */
  11749. if (sa->sa.sa_family != AF_INET6) {
  11750. return 0;
  11751. }
  11752. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11753. /* IPv6 format */
  11754. for (i = 0; i < 16; i++) {
  11755. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11756. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11757. uint8_t mask = 0;
  11758. if (8 * i + 8 < slash) {
  11759. mask = 0xFFu;
  11760. } else if (8 * i < slash) {
  11761. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11762. }
  11763. if ((ip & mask) != net) {
  11764. return 0;
  11765. }
  11766. }
  11767. return 1;
  11768. }
  11769. }
  11770. }
  11771. }
  11772. #else
  11773. (void)no_strict;
  11774. #endif
  11775. /* malformed */
  11776. return -1;
  11777. }
  11778. static int
  11779. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11780. {
  11781. int throttle = 0;
  11782. struct vec vec, val;
  11783. char mult;
  11784. double v;
  11785. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11786. mult = ',';
  11787. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11788. || (v < 0)
  11789. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11790. && (mult != ','))) {
  11791. continue;
  11792. }
  11793. v *= (lowercase(&mult) == 'k')
  11794. ? 1024
  11795. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11796. if (vec.len == 1 && vec.ptr[0] == '*') {
  11797. throttle = (int)v;
  11798. } else {
  11799. int matched = parse_match_net(&vec, rsa, 0);
  11800. if (matched >= 0) {
  11801. /* a valid IP subnet */
  11802. if (matched) {
  11803. throttle = (int)v;
  11804. }
  11805. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11806. throttle = (int)v;
  11807. }
  11808. }
  11809. }
  11810. return throttle;
  11811. }
  11812. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11813. #include "handle_form.inl"
  11814. static int
  11815. get_first_ssl_listener_index(const struct mg_context *ctx)
  11816. {
  11817. unsigned int i;
  11818. int idx = -1;
  11819. if (ctx) {
  11820. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11821. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11822. }
  11823. }
  11824. return idx;
  11825. }
  11826. /* Return host (without port) */
  11827. static void
  11828. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11829. {
  11830. const char *host_header =
  11831. get_header(ri->http_headers, ri->num_headers, "Host");
  11832. host->ptr = NULL;
  11833. host->len = 0;
  11834. if (host_header != NULL) {
  11835. char *pos;
  11836. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11837. * is found. */
  11838. if (*host_header == '[') {
  11839. pos = strchr(host_header, ']');
  11840. if (!pos) {
  11841. /* Malformed hostname starts with '[', but no ']' found */
  11842. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11843. return;
  11844. }
  11845. /* terminate after ']' */
  11846. host->ptr = host_header;
  11847. host->len = (size_t)(pos + 1 - host_header);
  11848. } else {
  11849. /* Otherwise, a ':' separates hostname and port number */
  11850. pos = strchr(host_header, ':');
  11851. if (pos != NULL) {
  11852. host->len = (size_t)(pos - host_header);
  11853. } else {
  11854. host->len = strlen(host_header);
  11855. }
  11856. host->ptr = host_header;
  11857. }
  11858. }
  11859. }
  11860. static int
  11861. switch_domain_context(struct mg_connection *conn)
  11862. {
  11863. struct vec host;
  11864. get_host_from_request_info(&host, &conn->request_info);
  11865. if (host.ptr) {
  11866. if (conn->ssl) {
  11867. /* This is a HTTPS connection, maybe we have a hostname
  11868. * from SNI (set in ssl_servername_callback). */
  11869. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11870. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11871. /* We are not using the default domain */
  11872. if ((strlen(sslhost) != host.len)
  11873. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11874. /* Mismatch between SNI domain and HTTP domain */
  11875. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11876. sslhost,
  11877. (int)host.len,
  11878. host.ptr);
  11879. return 0;
  11880. }
  11881. }
  11882. } else {
  11883. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11884. while (dom) {
  11885. if ((strlen(dom->config[AUTHENTICATION_DOMAIN]) == host.len)
  11886. && !mg_strncasecmp(host.ptr,
  11887. dom->config[AUTHENTICATION_DOMAIN],
  11888. host.len)) {
  11889. /* Found matching domain */
  11890. DEBUG_TRACE("HTTP domain %s found",
  11891. dom->config[AUTHENTICATION_DOMAIN]);
  11892. /* TODO: Check if this is a HTTP or HTTPS domain */
  11893. conn->dom_ctx = dom;
  11894. break;
  11895. }
  11896. mg_lock_context(conn->phys_ctx);
  11897. dom = dom->next;
  11898. mg_unlock_context(conn->phys_ctx);
  11899. }
  11900. }
  11901. } else {
  11902. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11903. return 1;
  11904. }
  11905. DEBUG_TRACE("HTTP%s Host: %.*s",
  11906. conn->ssl ? "S" : "",
  11907. (int)host.len,
  11908. host.ptr);
  11909. return 1;
  11910. }
  11911. static int mg_construct_local_link(const struct mg_connection *conn,
  11912. char *buf,
  11913. size_t buflen,
  11914. const char *define_proto,
  11915. int define_port,
  11916. const char *define_uri);
  11917. static void
  11918. redirect_to_https_port(struct mg_connection *conn, int port)
  11919. {
  11920. char target_url[MG_BUF_LEN];
  11921. int truncated = 0;
  11922. const char *expect_proto =
  11923. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11924. /* Use "308 Permanent Redirect" */
  11925. int redirect_code = 308;
  11926. /* In any case, close the current connection */
  11927. conn->must_close = 1;
  11928. /* Send host, port, uri and (if it exists) ?query_string */
  11929. if (mg_construct_local_link(
  11930. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11931. < 0) {
  11932. truncated = 1;
  11933. } else if (conn->request_info.query_string != NULL) {
  11934. size_t slen1 = strlen(target_url);
  11935. size_t slen2 = strlen(conn->request_info.query_string);
  11936. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11937. target_url[slen1] = '?';
  11938. memcpy(target_url + slen1 + 1,
  11939. conn->request_info.query_string,
  11940. slen2);
  11941. target_url[slen1 + slen2 + 1] = 0;
  11942. } else {
  11943. truncated = 1;
  11944. }
  11945. }
  11946. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11947. * is used as buffer size) */
  11948. if (truncated) {
  11949. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11950. return;
  11951. }
  11952. /* Use redirect helper function */
  11953. mg_send_http_redirect(conn, target_url, redirect_code);
  11954. }
  11955. static void
  11956. mg_set_handler_type(struct mg_context *phys_ctx,
  11957. struct mg_domain_context *dom_ctx,
  11958. const char *uri,
  11959. int handler_type,
  11960. int is_delete_request,
  11961. mg_request_handler handler,
  11962. struct mg_websocket_subprotocols *subprotocols,
  11963. mg_websocket_connect_handler connect_handler,
  11964. mg_websocket_ready_handler ready_handler,
  11965. mg_websocket_data_handler data_handler,
  11966. mg_websocket_close_handler close_handler,
  11967. mg_authorization_handler auth_handler,
  11968. void *cbdata)
  11969. {
  11970. struct mg_handler_info *tmp_rh, **lastref;
  11971. size_t urilen = strlen(uri);
  11972. if (handler_type == WEBSOCKET_HANDLER) {
  11973. DEBUG_ASSERT(handler == NULL);
  11974. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11975. || ready_handler != NULL || data_handler != NULL
  11976. || close_handler != NULL);
  11977. DEBUG_ASSERT(auth_handler == NULL);
  11978. if (handler != NULL) {
  11979. return;
  11980. }
  11981. if (!is_delete_request && (connect_handler == NULL)
  11982. && (ready_handler == NULL) && (data_handler == NULL)
  11983. && (close_handler == NULL)) {
  11984. return;
  11985. }
  11986. if (auth_handler != NULL) {
  11987. return;
  11988. }
  11989. } else if (handler_type == REQUEST_HANDLER) {
  11990. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11991. && data_handler == NULL && close_handler == NULL);
  11992. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11993. DEBUG_ASSERT(auth_handler == NULL);
  11994. if ((connect_handler != NULL) || (ready_handler != NULL)
  11995. || (data_handler != NULL) || (close_handler != NULL)) {
  11996. return;
  11997. }
  11998. if (!is_delete_request && (handler == NULL)) {
  11999. return;
  12000. }
  12001. if (auth_handler != NULL) {
  12002. return;
  12003. }
  12004. } else { /* AUTH_HANDLER */
  12005. DEBUG_ASSERT(handler == NULL);
  12006. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12007. && data_handler == NULL && close_handler == NULL);
  12008. DEBUG_ASSERT(auth_handler != NULL);
  12009. if (handler != NULL) {
  12010. return;
  12011. }
  12012. if ((connect_handler != NULL) || (ready_handler != NULL)
  12013. || (data_handler != NULL) || (close_handler != NULL)) {
  12014. return;
  12015. }
  12016. if (!is_delete_request && (auth_handler == NULL)) {
  12017. return;
  12018. }
  12019. }
  12020. if (!phys_ctx || !dom_ctx) {
  12021. return;
  12022. }
  12023. mg_lock_context(phys_ctx);
  12024. /* first try to find an existing handler */
  12025. do {
  12026. lastref = &(dom_ctx->handlers);
  12027. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12028. tmp_rh = tmp_rh->next) {
  12029. if (tmp_rh->handler_type == handler_type
  12030. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12031. if (!is_delete_request) {
  12032. /* update existing handler */
  12033. if (handler_type == REQUEST_HANDLER) {
  12034. /* Wait for end of use before updating */
  12035. if (tmp_rh->refcount) {
  12036. mg_unlock_context(phys_ctx);
  12037. mg_sleep(1);
  12038. mg_lock_context(phys_ctx);
  12039. /* tmp_rh might have been freed, search again. */
  12040. break;
  12041. }
  12042. /* Ok, the handler is no more use -> Update it */
  12043. tmp_rh->handler = handler;
  12044. } else if (handler_type == WEBSOCKET_HANDLER) {
  12045. tmp_rh->subprotocols = subprotocols;
  12046. tmp_rh->connect_handler = connect_handler;
  12047. tmp_rh->ready_handler = ready_handler;
  12048. tmp_rh->data_handler = data_handler;
  12049. tmp_rh->close_handler = close_handler;
  12050. } else { /* AUTH_HANDLER */
  12051. tmp_rh->auth_handler = auth_handler;
  12052. }
  12053. tmp_rh->cbdata = cbdata;
  12054. } else {
  12055. /* remove existing handler */
  12056. if (handler_type == REQUEST_HANDLER) {
  12057. /* Wait for end of use before removing */
  12058. if (tmp_rh->refcount) {
  12059. tmp_rh->removing = 1;
  12060. mg_unlock_context(phys_ctx);
  12061. mg_sleep(1);
  12062. mg_lock_context(phys_ctx);
  12063. /* tmp_rh might have been freed, search again. */
  12064. break;
  12065. }
  12066. /* Ok, the handler is no more used */
  12067. }
  12068. *lastref = tmp_rh->next;
  12069. mg_free(tmp_rh->uri);
  12070. mg_free(tmp_rh);
  12071. }
  12072. mg_unlock_context(phys_ctx);
  12073. return;
  12074. }
  12075. lastref = &(tmp_rh->next);
  12076. }
  12077. } while (tmp_rh != NULL);
  12078. if (is_delete_request) {
  12079. /* no handler to set, this was a remove request to a non-existing
  12080. * handler */
  12081. mg_unlock_context(phys_ctx);
  12082. return;
  12083. }
  12084. tmp_rh =
  12085. (struct mg_handler_info *)mg_calloc_ctx(1,
  12086. sizeof(struct mg_handler_info),
  12087. phys_ctx);
  12088. if (tmp_rh == NULL) {
  12089. mg_unlock_context(phys_ctx);
  12090. mg_cry_ctx_internal(phys_ctx,
  12091. "%s",
  12092. "Cannot create new request handler struct, OOM");
  12093. return;
  12094. }
  12095. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12096. if (!tmp_rh->uri) {
  12097. mg_unlock_context(phys_ctx);
  12098. mg_free(tmp_rh);
  12099. mg_cry_ctx_internal(phys_ctx,
  12100. "%s",
  12101. "Cannot create new request handler struct, OOM");
  12102. return;
  12103. }
  12104. tmp_rh->uri_len = urilen;
  12105. if (handler_type == REQUEST_HANDLER) {
  12106. tmp_rh->refcount = 0;
  12107. tmp_rh->removing = 0;
  12108. tmp_rh->handler = handler;
  12109. } else if (handler_type == WEBSOCKET_HANDLER) {
  12110. tmp_rh->subprotocols = subprotocols;
  12111. tmp_rh->connect_handler = connect_handler;
  12112. tmp_rh->ready_handler = ready_handler;
  12113. tmp_rh->data_handler = data_handler;
  12114. tmp_rh->close_handler = close_handler;
  12115. } else { /* AUTH_HANDLER */
  12116. tmp_rh->auth_handler = auth_handler;
  12117. }
  12118. tmp_rh->cbdata = cbdata;
  12119. tmp_rh->handler_type = handler_type;
  12120. tmp_rh->next = NULL;
  12121. *lastref = tmp_rh;
  12122. mg_unlock_context(phys_ctx);
  12123. }
  12124. void
  12125. mg_set_request_handler(struct mg_context *ctx,
  12126. const char *uri,
  12127. mg_request_handler handler,
  12128. void *cbdata)
  12129. {
  12130. mg_set_handler_type(ctx,
  12131. &(ctx->dd),
  12132. uri,
  12133. REQUEST_HANDLER,
  12134. handler == NULL,
  12135. handler,
  12136. NULL,
  12137. NULL,
  12138. NULL,
  12139. NULL,
  12140. NULL,
  12141. NULL,
  12142. cbdata);
  12143. }
  12144. void
  12145. mg_set_websocket_handler(struct mg_context *ctx,
  12146. const char *uri,
  12147. mg_websocket_connect_handler connect_handler,
  12148. mg_websocket_ready_handler ready_handler,
  12149. mg_websocket_data_handler data_handler,
  12150. mg_websocket_close_handler close_handler,
  12151. void *cbdata)
  12152. {
  12153. mg_set_websocket_handler_with_subprotocols(ctx,
  12154. uri,
  12155. NULL,
  12156. connect_handler,
  12157. ready_handler,
  12158. data_handler,
  12159. close_handler,
  12160. cbdata);
  12161. }
  12162. void
  12163. mg_set_websocket_handler_with_subprotocols(
  12164. struct mg_context *ctx,
  12165. const char *uri,
  12166. struct mg_websocket_subprotocols *subprotocols,
  12167. mg_websocket_connect_handler connect_handler,
  12168. mg_websocket_ready_handler ready_handler,
  12169. mg_websocket_data_handler data_handler,
  12170. mg_websocket_close_handler close_handler,
  12171. void *cbdata)
  12172. {
  12173. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12174. && (data_handler == NULL)
  12175. && (close_handler == NULL);
  12176. mg_set_handler_type(ctx,
  12177. &(ctx->dd),
  12178. uri,
  12179. WEBSOCKET_HANDLER,
  12180. is_delete_request,
  12181. NULL,
  12182. subprotocols,
  12183. connect_handler,
  12184. ready_handler,
  12185. data_handler,
  12186. close_handler,
  12187. NULL,
  12188. cbdata);
  12189. }
  12190. void
  12191. mg_set_auth_handler(struct mg_context *ctx,
  12192. const char *uri,
  12193. mg_authorization_handler handler,
  12194. void *cbdata)
  12195. {
  12196. mg_set_handler_type(ctx,
  12197. &(ctx->dd),
  12198. uri,
  12199. AUTH_HANDLER,
  12200. handler == NULL,
  12201. NULL,
  12202. NULL,
  12203. NULL,
  12204. NULL,
  12205. NULL,
  12206. NULL,
  12207. handler,
  12208. cbdata);
  12209. }
  12210. static int
  12211. get_request_handler(struct mg_connection *conn,
  12212. int handler_type,
  12213. mg_request_handler *handler,
  12214. struct mg_websocket_subprotocols **subprotocols,
  12215. mg_websocket_connect_handler *connect_handler,
  12216. mg_websocket_ready_handler *ready_handler,
  12217. mg_websocket_data_handler *data_handler,
  12218. mg_websocket_close_handler *close_handler,
  12219. mg_authorization_handler *auth_handler,
  12220. void **cbdata,
  12221. struct mg_handler_info **handler_info)
  12222. {
  12223. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12224. if (request_info) {
  12225. const char *uri = request_info->local_uri;
  12226. size_t urilen = strlen(uri);
  12227. struct mg_handler_info *tmp_rh;
  12228. int step, matched;
  12229. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12230. return 0;
  12231. }
  12232. mg_lock_context(conn->phys_ctx);
  12233. for (step = 0; step < 3; step++) {
  12234. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12235. tmp_rh = tmp_rh->next) {
  12236. if (tmp_rh->handler_type != handler_type) {
  12237. continue;
  12238. }
  12239. if (step == 0) {
  12240. /* first try for an exact match */
  12241. matched = (tmp_rh->uri_len == urilen)
  12242. && (strcmp(tmp_rh->uri, uri) == 0);
  12243. } else if (step == 1) {
  12244. /* next try for a partial match, we will accept
  12245. uri/something */
  12246. matched =
  12247. (tmp_rh->uri_len < urilen)
  12248. && (uri[tmp_rh->uri_len] == '/')
  12249. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12250. } else {
  12251. /* finally try for pattern match */
  12252. matched =
  12253. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12254. }
  12255. if (matched) {
  12256. if (handler_type == WEBSOCKET_HANDLER) {
  12257. *subprotocols = tmp_rh->subprotocols;
  12258. *connect_handler = tmp_rh->connect_handler;
  12259. *ready_handler = tmp_rh->ready_handler;
  12260. *data_handler = tmp_rh->data_handler;
  12261. *close_handler = tmp_rh->close_handler;
  12262. } else if (handler_type == REQUEST_HANDLER) {
  12263. if (tmp_rh->removing) {
  12264. /* Treat as none found */
  12265. step = 2;
  12266. break;
  12267. }
  12268. *handler = tmp_rh->handler;
  12269. /* Acquire handler and give it back */
  12270. tmp_rh->refcount++;
  12271. *handler_info = tmp_rh;
  12272. } else { /* AUTH_HANDLER */
  12273. *auth_handler = tmp_rh->auth_handler;
  12274. }
  12275. *cbdata = tmp_rh->cbdata;
  12276. mg_unlock_context(conn->phys_ctx);
  12277. return 1;
  12278. }
  12279. }
  12280. }
  12281. mg_unlock_context(conn->phys_ctx);
  12282. }
  12283. return 0; /* none found */
  12284. }
  12285. /* Check if the script file is in a path, allowed for script files.
  12286. * This can be used if uploading files is possible not only for the server
  12287. * admin, and the upload mechanism does not check the file extension.
  12288. */
  12289. static int
  12290. is_in_script_path(const struct mg_connection *conn, const char *path)
  12291. {
  12292. /* TODO (Feature): Add config value for allowed script path.
  12293. * Default: All allowed. */
  12294. (void)conn;
  12295. (void)path;
  12296. return 1;
  12297. }
  12298. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12299. static int
  12300. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12301. int bits,
  12302. char *data,
  12303. size_t len,
  12304. void *cbdata)
  12305. {
  12306. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12307. if (pcallbacks->websocket_data) {
  12308. return pcallbacks->websocket_data(conn, bits, data, len);
  12309. }
  12310. /* No handler set - assume "OK" */
  12311. return 1;
  12312. }
  12313. static void
  12314. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12315. void *cbdata)
  12316. {
  12317. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12318. if (pcallbacks->connection_close) {
  12319. pcallbacks->connection_close(conn);
  12320. }
  12321. }
  12322. #endif
  12323. /* This is the heart of the Civetweb's logic.
  12324. * This function is called when the request is read, parsed and validated,
  12325. * and Civetweb must decide what action to take: serve a file, or
  12326. * a directory, or call embedded function, etcetera. */
  12327. static void
  12328. handle_request(struct mg_connection *conn)
  12329. {
  12330. struct mg_request_info *ri = &conn->request_info;
  12331. char path[PATH_MAX];
  12332. int uri_len, ssl_index;
  12333. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12334. is_put_or_delete_request = 0, is_callback_resource = 0,
  12335. is_template_text_file = 0;
  12336. int i;
  12337. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12338. mg_request_handler callback_handler = NULL;
  12339. struct mg_handler_info *handler_info = NULL;
  12340. struct mg_websocket_subprotocols *subprotocols;
  12341. mg_websocket_connect_handler ws_connect_handler = NULL;
  12342. mg_websocket_ready_handler ws_ready_handler = NULL;
  12343. mg_websocket_data_handler ws_data_handler = NULL;
  12344. mg_websocket_close_handler ws_close_handler = NULL;
  12345. void *callback_data = NULL;
  12346. mg_authorization_handler auth_handler = NULL;
  12347. void *auth_callback_data = NULL;
  12348. int handler_type;
  12349. time_t curtime = time(NULL);
  12350. char date[64];
  12351. path[0] = 0;
  12352. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12353. conn->request_state = 0;
  12354. /* 1. get the request url */
  12355. /* 1.1. split into url and query string */
  12356. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12357. != NULL) {
  12358. *((char *)conn->request_info.query_string++) = '\0';
  12359. }
  12360. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12361. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12362. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12363. if (ssl_index >= 0) {
  12364. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12365. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12366. redirect_to_https_port(conn, port);
  12367. } else {
  12368. /* A http to https forward port has been specified,
  12369. * but no https port to forward to. */
  12370. mg_send_http_error(conn,
  12371. 503,
  12372. "%s",
  12373. "Error: SSL forward not configured properly");
  12374. mg_cry_internal(conn,
  12375. "%s",
  12376. "Can not redirect to SSL, no SSL port available");
  12377. }
  12378. return;
  12379. }
  12380. uri_len = (int)strlen(ri->local_uri);
  12381. /* 1.3. decode url (if config says so) */
  12382. if (should_decode_url(conn)) {
  12383. mg_url_decode(
  12384. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12385. if (conn->request_info.query_string) {
  12386. url_decode_in_place((char *)conn->request_info.query_string);
  12387. }
  12388. }
  12389. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12390. * not possible */
  12391. remove_dot_segments((char *)ri->local_uri);
  12392. /* step 1. completed, the url is known now */
  12393. uri_len = (int)strlen(ri->local_uri);
  12394. DEBUG_TRACE("URL: %s", ri->local_uri);
  12395. /* 2. if this ip has limited speed, set it for this connection */
  12396. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12397. &conn->client.rsa,
  12398. ri->local_uri);
  12399. /* 3. call a "handle everything" callback, if registered */
  12400. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12401. /* Note that since V1.7 the "begin_request" function is called
  12402. * before an authorization check. If an authorization check is
  12403. * required, use a request_handler instead. */
  12404. i = conn->phys_ctx->callbacks.begin_request(conn);
  12405. if (i > 0) {
  12406. /* callback already processed the request. Store the
  12407. return value as a status code for the access log. */
  12408. conn->status_code = i;
  12409. if (!conn->must_close) {
  12410. discard_unread_request_data(conn);
  12411. }
  12412. return;
  12413. } else if (i == 0) {
  12414. /* civetweb should process the request */
  12415. } else {
  12416. /* unspecified - may change with the next version */
  12417. return;
  12418. }
  12419. }
  12420. /* request not yet handled by a handler or redirect, so the request
  12421. * is processed here */
  12422. /* 4. Check for CORS preflight requests and handle them (if configured).
  12423. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12424. */
  12425. if (!strcmp(ri->request_method, "OPTIONS")) {
  12426. /* Send a response to CORS preflights only if
  12427. * access_control_allow_methods is not NULL and not an empty string.
  12428. * In this case, scripts can still handle CORS. */
  12429. const char *cors_meth_cfg =
  12430. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12431. const char *cors_orig_cfg =
  12432. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12433. const char *cors_origin =
  12434. get_header(ri->http_headers, ri->num_headers, "Origin");
  12435. const char *cors_acrm = get_header(ri->http_headers,
  12436. ri->num_headers,
  12437. "Access-Control-Request-Method");
  12438. /* Todo: check if cors_origin is in cors_orig_cfg.
  12439. * Or, let the client check this. */
  12440. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12441. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12442. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12443. /* This is a valid CORS preflight, and the server is configured
  12444. * to handle it automatically. */
  12445. const char *cors_acrh =
  12446. get_header(ri->http_headers,
  12447. ri->num_headers,
  12448. "Access-Control-Request-Headers");
  12449. gmt_time_string(date, sizeof(date), &curtime);
  12450. mg_printf(conn,
  12451. "HTTP/1.1 200 OK\r\n"
  12452. "Date: %s\r\n"
  12453. "Access-Control-Allow-Origin: %s\r\n"
  12454. "Access-Control-Allow-Methods: %s\r\n"
  12455. "Content-Length: 0\r\n"
  12456. "Connection: %s\r\n",
  12457. date,
  12458. cors_orig_cfg,
  12459. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12460. suggest_connection_header(conn));
  12461. if (cors_acrh != NULL) {
  12462. /* CORS request is asking for additional headers */
  12463. const char *cors_hdr_cfg =
  12464. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12465. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12466. /* Allow only if access_control_allow_headers is
  12467. * not NULL and not an empty string. If this
  12468. * configuration is set to *, allow everything.
  12469. * Otherwise this configuration must be a list
  12470. * of allowed HTTP header names. */
  12471. mg_printf(conn,
  12472. "Access-Control-Allow-Headers: %s\r\n",
  12473. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12474. : cors_hdr_cfg));
  12475. }
  12476. }
  12477. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12478. mg_printf(conn, "\r\n");
  12479. return;
  12480. }
  12481. }
  12482. /* 5. interpret the url to find out how the request must be handled
  12483. */
  12484. /* 5.1. first test, if the request targets the regular http(s)://
  12485. * protocol namespace or the websocket ws(s):// protocol namespace.
  12486. */
  12487. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12488. #if defined(USE_WEBSOCKET)
  12489. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12490. #else
  12491. handler_type = REQUEST_HANDLER;
  12492. #endif /* defined(USE_WEBSOCKET) */
  12493. if (is_websocket_request) {
  12494. HTTP1_only;
  12495. }
  12496. /* 5.2. check if the request will be handled by a callback */
  12497. if (get_request_handler(conn,
  12498. handler_type,
  12499. &callback_handler,
  12500. &subprotocols,
  12501. &ws_connect_handler,
  12502. &ws_ready_handler,
  12503. &ws_data_handler,
  12504. &ws_close_handler,
  12505. NULL,
  12506. &callback_data,
  12507. &handler_info)) {
  12508. /* 5.2.1. A callback will handle this request. All requests
  12509. * handled by a callback have to be considered as requests
  12510. * to a script resource. */
  12511. is_callback_resource = 1;
  12512. is_script_resource = 1;
  12513. is_put_or_delete_request = is_put_or_delete_method(conn);
  12514. } else {
  12515. no_callback_resource:
  12516. /* 5.2.2. No callback is responsible for this request. The URI
  12517. * addresses a file based resource (static content or Lua/cgi
  12518. * scripts in the file system). */
  12519. is_callback_resource = 0;
  12520. interpret_uri(conn,
  12521. path,
  12522. sizeof(path),
  12523. &file.stat,
  12524. &is_found,
  12525. &is_script_resource,
  12526. &is_websocket_request,
  12527. &is_put_or_delete_request,
  12528. &is_template_text_file);
  12529. }
  12530. /* 6. authorization check */
  12531. /* 6.1. a custom authorization handler is installed */
  12532. if (get_request_handler(conn,
  12533. AUTH_HANDLER,
  12534. NULL,
  12535. NULL,
  12536. NULL,
  12537. NULL,
  12538. NULL,
  12539. NULL,
  12540. &auth_handler,
  12541. &auth_callback_data,
  12542. NULL)) {
  12543. if (!auth_handler(conn, auth_callback_data)) {
  12544. return;
  12545. }
  12546. } else if (is_put_or_delete_request && !is_script_resource
  12547. && !is_callback_resource) {
  12548. HTTP1_only;
  12549. /* 6.2. this request is a PUT/DELETE to a real file */
  12550. /* 6.2.1. thus, the server must have real files */
  12551. #if defined(NO_FILES)
  12552. if (1) {
  12553. #else
  12554. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12555. #endif
  12556. /* This server does not have any real files, thus the
  12557. * PUT/DELETE methods are not valid. */
  12558. mg_send_http_error(conn,
  12559. 405,
  12560. "%s method not allowed",
  12561. conn->request_info.request_method);
  12562. return;
  12563. }
  12564. #if !defined(NO_FILES)
  12565. /* 6.2.2. Check if put authorization for static files is
  12566. * available.
  12567. */
  12568. if (!is_authorized_for_put(conn)) {
  12569. send_authorization_request(conn, NULL);
  12570. return;
  12571. }
  12572. #endif
  12573. } else {
  12574. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12575. * or it is a PUT or DELETE request to a resource that does not
  12576. * correspond to a file. Check authorization. */
  12577. if (!check_authorization(conn, path)) {
  12578. send_authorization_request(conn, NULL);
  12579. return;
  12580. }
  12581. }
  12582. /* request is authorized or does not need authorization */
  12583. /* 7. check if there are request handlers for this uri */
  12584. if (is_callback_resource) {
  12585. HTTP1_only;
  12586. if (!is_websocket_request) {
  12587. i = callback_handler(conn, callback_data);
  12588. /* Callback handler will not be used anymore. Release it */
  12589. mg_lock_context(conn->phys_ctx);
  12590. handler_info->refcount--;
  12591. mg_unlock_context(conn->phys_ctx);
  12592. if (i > 0) {
  12593. /* Do nothing, callback has served the request. Store
  12594. * then return value as status code for the log and discard
  12595. * all data from the client not used by the callback. */
  12596. conn->status_code = i;
  12597. if (!conn->must_close) {
  12598. discard_unread_request_data(conn);
  12599. }
  12600. } else {
  12601. /* The handler did NOT handle the request. */
  12602. /* Some proper reactions would be:
  12603. * a) close the connections without sending anything
  12604. * b) send a 404 not found
  12605. * c) try if there is a file matching the URI
  12606. * It would be possible to do a, b or c in the callback
  12607. * implementation, and return 1 - we cannot do anything
  12608. * here, that is not possible in the callback.
  12609. *
  12610. * TODO: What would be the best reaction here?
  12611. * (Note: The reaction may change, if there is a better
  12612. * idea.)
  12613. */
  12614. /* For the moment, use option c: We look for a proper file,
  12615. * but since a file request is not always a script resource,
  12616. * the authorization check might be different. */
  12617. interpret_uri(conn,
  12618. path,
  12619. sizeof(path),
  12620. &file.stat,
  12621. &is_found,
  12622. &is_script_resource,
  12623. &is_websocket_request,
  12624. &is_put_or_delete_request,
  12625. &is_template_text_file);
  12626. callback_handler = NULL;
  12627. /* Here we are at a dead end:
  12628. * According to URI matching, a callback should be
  12629. * responsible for handling the request,
  12630. * we called it, but the callback declared itself
  12631. * not responsible.
  12632. * We use a goto here, to get out of this dead end,
  12633. * and continue with the default handling.
  12634. * A goto here is simpler and better to understand
  12635. * than some curious loop. */
  12636. goto no_callback_resource;
  12637. }
  12638. } else {
  12639. #if defined(USE_WEBSOCKET)
  12640. handle_websocket_request(conn,
  12641. path,
  12642. is_callback_resource,
  12643. subprotocols,
  12644. ws_connect_handler,
  12645. ws_ready_handler,
  12646. ws_data_handler,
  12647. ws_close_handler,
  12648. callback_data);
  12649. #endif
  12650. }
  12651. return;
  12652. }
  12653. /* 8. handle websocket requests */
  12654. #if defined(USE_WEBSOCKET)
  12655. if (is_websocket_request) {
  12656. HTTP1_only;
  12657. if (is_script_resource) {
  12658. if (is_in_script_path(conn, path)) {
  12659. /* Websocket Lua script */
  12660. handle_websocket_request(conn,
  12661. path,
  12662. 0 /* Lua Script */,
  12663. NULL,
  12664. NULL,
  12665. NULL,
  12666. NULL,
  12667. NULL,
  12668. conn->phys_ctx->user_data);
  12669. } else {
  12670. /* Script was in an illegal path */
  12671. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12672. }
  12673. } else {
  12674. mg_send_http_error(conn, 404, "%s", "Not found");
  12675. }
  12676. return;
  12677. } else
  12678. #endif
  12679. #if defined(NO_FILES)
  12680. /* 9a. In case the server uses only callbacks, this uri is
  12681. * unknown.
  12682. * Then, all request handling ends here. */
  12683. mg_send_http_error(conn, 404, "%s", "Not Found");
  12684. #else
  12685. /* 9b. This request is either for a static file or resource handled
  12686. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12687. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12688. mg_send_http_error(conn, 404, "%s", "Not Found");
  12689. return;
  12690. }
  12691. /* 10. Request is handled by a script */
  12692. if (is_script_resource) {
  12693. HTTP1_only;
  12694. handle_file_based_request(conn, path, &file);
  12695. return;
  12696. }
  12697. /* 11. Handle put/delete/mkcol requests */
  12698. if (is_put_or_delete_request) {
  12699. HTTP1_only;
  12700. /* 11.1. PUT method */
  12701. if (!strcmp(ri->request_method, "PUT")) {
  12702. put_file(conn, path);
  12703. return;
  12704. }
  12705. /* 11.2. DELETE method */
  12706. if (!strcmp(ri->request_method, "DELETE")) {
  12707. delete_file(conn, path);
  12708. return;
  12709. }
  12710. /* 11.3. MKCOL method */
  12711. if (!strcmp(ri->request_method, "MKCOL")) {
  12712. mkcol(conn, path);
  12713. return;
  12714. }
  12715. /* 11.4. PATCH method
  12716. * This method is not supported for static resources,
  12717. * only for scripts (Lua, CGI) and callbacks. */
  12718. mg_send_http_error(conn,
  12719. 405,
  12720. "%s method not allowed",
  12721. conn->request_info.request_method);
  12722. return;
  12723. }
  12724. /* 11. File does not exist, or it was configured that it should be
  12725. * hidden */
  12726. if (!is_found || (must_hide_file(conn, path))) {
  12727. mg_send_http_error(conn, 404, "%s", "Not found");
  12728. return;
  12729. }
  12730. /* 12. Directory uris should end with a slash */
  12731. if (file.stat.is_directory && (uri_len > 0)
  12732. && (ri->local_uri[uri_len - 1] != '/')) {
  12733. size_t len = strlen(ri->request_uri);
  12734. char *new_path = mg_malloc_ctx(len + 2, conn->phys_ctx);
  12735. if (!new_path) {
  12736. mg_send_http_error(conn, 500, "out or memory");
  12737. } else {
  12738. memcpy(new_path, ri->request_uri, len);
  12739. new_path[len] = '/';
  12740. new_path[len + 1] = 0;
  12741. mg_send_http_redirect(conn, new_path, 301);
  12742. }
  12743. return;
  12744. }
  12745. /* 13. Handle other methods than GET/HEAD */
  12746. /* 13.1. Handle PROPFIND */
  12747. if (!strcmp(ri->request_method, "PROPFIND")) {
  12748. handle_propfind(conn, path, &file.stat);
  12749. return;
  12750. }
  12751. /* 13.2. Handle OPTIONS for files */
  12752. if (!strcmp(ri->request_method, "OPTIONS")) {
  12753. /* This standard handler is only used for real files.
  12754. * Scripts should support the OPTIONS method themselves, to allow a
  12755. * maximum flexibility.
  12756. * Lua and CGI scripts may fully support CORS this way (including
  12757. * preflights). */
  12758. send_options(conn);
  12759. return;
  12760. }
  12761. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12762. if ((0 != strcmp(ri->request_method, "GET"))
  12763. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12764. mg_send_http_error(conn,
  12765. 405,
  12766. "%s method not allowed",
  12767. conn->request_info.request_method);
  12768. return;
  12769. }
  12770. /* 14. directories */
  12771. if (file.stat.is_directory) {
  12772. /* Substitute files have already been handled above. */
  12773. /* Here we can either generate and send a directory listing,
  12774. * or send an "access denied" error. */
  12775. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12776. "yes")) {
  12777. handle_directory_request(conn, path);
  12778. } else {
  12779. mg_send_http_error(conn,
  12780. 403,
  12781. "%s",
  12782. "Error: Directory listing denied");
  12783. }
  12784. return;
  12785. }
  12786. /* 15. Files with search/replace patterns: LSP and SSI */
  12787. if (is_template_text_file) {
  12788. HTTP1_only;
  12789. handle_file_based_request(conn, path, &file);
  12790. return;
  12791. }
  12792. /* 16. Static file - maybe cached */
  12793. #if !defined(NO_CACHING)
  12794. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12795. /* Send 304 "Not Modified" - this must not send any body data */
  12796. handle_not_modified_static_file_request(conn, &file);
  12797. return;
  12798. }
  12799. #endif /* !NO_CACHING */
  12800. /* 17. Static file - not cached */
  12801. handle_static_file_request(conn, path, &file, NULL, NULL);
  12802. #endif /* !defined(NO_FILES) */
  12803. }
  12804. #if !defined(NO_FILESYSTEMS)
  12805. static void
  12806. handle_file_based_request(struct mg_connection *conn,
  12807. const char *path,
  12808. struct mg_file *file)
  12809. {
  12810. if (!conn || !conn->dom_ctx) {
  12811. return;
  12812. }
  12813. if (0) {
  12814. #if defined(USE_LUA)
  12815. } else if (match_prefix_strlen(
  12816. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS], path)
  12817. > 0) {
  12818. if (is_in_script_path(conn, path)) {
  12819. /* Lua server page: an SSI like page containing mostly plain
  12820. * html code plus some tags with server generated contents. */
  12821. handle_lsp_request(conn, path, file, NULL);
  12822. } else {
  12823. /* Script was in an illegal path */
  12824. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12825. }
  12826. } else if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12827. path)
  12828. > 0) {
  12829. if (is_in_script_path(conn, path)) {
  12830. /* Lua in-server module script: a CGI like script used to
  12831. * generate
  12832. * the
  12833. * entire reply. */
  12834. mg_exec_lua_script(conn, path, NULL);
  12835. } else {
  12836. /* Script was in an illegal path */
  12837. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12838. }
  12839. #endif
  12840. #if defined(USE_DUKTAPE)
  12841. } else if (match_prefix_strlen(
  12842. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS], path)
  12843. > 0) {
  12844. if (is_in_script_path(conn, path)) {
  12845. /* Call duktape to generate the page */
  12846. mg_exec_duktape_script(conn, path);
  12847. } else {
  12848. /* Script was in an illegal path */
  12849. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12850. }
  12851. #endif
  12852. #if !defined(NO_CGI)
  12853. } else if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], path)
  12854. > 0) {
  12855. if (is_in_script_path(conn, path)) {
  12856. /* CGI scripts may support all HTTP methods */
  12857. handle_cgi_request(conn, path);
  12858. } else {
  12859. /* Script was in an illegal path */
  12860. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12861. }
  12862. #endif /* !NO_CGI */
  12863. } else if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  12864. > 0) {
  12865. if (is_in_script_path(conn, path)) {
  12866. handle_ssi_file_request(conn, path, file);
  12867. } else {
  12868. /* Script was in an illegal path */
  12869. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12870. }
  12871. #if !defined(NO_CACHING)
  12872. } else if ((!conn->in_error_handler)
  12873. && is_not_modified(conn, &file->stat)) {
  12874. /* Send 304 "Not Modified" - this must not send any body data */
  12875. handle_not_modified_static_file_request(conn, file);
  12876. #endif /* !NO_CACHING */
  12877. } else {
  12878. handle_static_file_request(conn, path, file, NULL, NULL);
  12879. }
  12880. }
  12881. #endif /* NO_FILESYSTEMS */
  12882. static void
  12883. close_all_listening_sockets(struct mg_context *ctx)
  12884. {
  12885. unsigned int i;
  12886. if (!ctx) {
  12887. return;
  12888. }
  12889. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12890. closesocket(ctx->listening_sockets[i].sock);
  12891. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12892. }
  12893. mg_free(ctx->listening_sockets);
  12894. ctx->listening_sockets = NULL;
  12895. mg_free(ctx->listening_socket_fds);
  12896. ctx->listening_socket_fds = NULL;
  12897. }
  12898. /* Valid listening port specification is: [ip_address:]port[s]
  12899. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12900. * Examples for IPv6: [::]:80, [::1]:80,
  12901. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12902. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12903. * In order to bind to both, IPv4 and IPv6, you can either add
  12904. * both ports using 8080,[::]:8080, or the short form +8080.
  12905. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12906. * one only accepting IPv4 the other only IPv6. +8080 creates
  12907. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12908. * environment, they might work differently, or might not work
  12909. * at all - it must be tested what options work best in the
  12910. * relevant network environment.
  12911. */
  12912. static int
  12913. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12914. {
  12915. unsigned int a, b, c, d;
  12916. unsigned port;
  12917. unsigned long portUL;
  12918. int ch, len;
  12919. const char *cb;
  12920. char *endptr;
  12921. #if defined(USE_IPV6)
  12922. char buf[100] = {0};
  12923. #endif
  12924. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12925. * Also, all-zeroes in the socket address means binding to all addresses
  12926. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12927. memset(so, 0, sizeof(*so));
  12928. so->lsa.sin.sin_family = AF_INET;
  12929. *ip_version = 0;
  12930. /* Initialize len as invalid. */
  12931. port = 0;
  12932. len = 0;
  12933. /* Test for different ways to format this string */
  12934. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12935. == 5) {
  12936. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12937. so->lsa.sin.sin_addr.s_addr =
  12938. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12939. so->lsa.sin.sin_port = htons((uint16_t)port);
  12940. *ip_version = 4;
  12941. #if defined(USE_IPV6)
  12942. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12943. && ((size_t)len <= vec->len)
  12944. && mg_inet_pton(
  12945. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12946. /* IPv6 address, examples: see above */
  12947. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12948. */
  12949. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12950. *ip_version = 6;
  12951. #endif
  12952. } else if ((vec->ptr[0] == '+')
  12953. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12954. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12955. /* Add 1 to len for the + character we skipped before */
  12956. len++;
  12957. #if defined(USE_IPV6)
  12958. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12959. so->lsa.sin6.sin6_family = AF_INET6;
  12960. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12961. *ip_version = 4 + 6;
  12962. #else
  12963. /* Bind to IPv4 only, since IPv6 is not built in. */
  12964. so->lsa.sin.sin_port = htons((uint16_t)port);
  12965. *ip_version = 4;
  12966. #endif
  12967. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12968. && (vec->ptr != endptr)) {
  12969. len = (int)(endptr - vec->ptr);
  12970. port = (uint16_t)portUL;
  12971. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12972. so->lsa.sin.sin_port = htons((uint16_t)port);
  12973. *ip_version = 4;
  12974. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12975. /* String could be a hostname. This check algotithm
  12976. * will only work for RFC 952 compliant hostnames,
  12977. * starting with a letter, containing only letters,
  12978. * digits and hyphen ('-'). Newer specs may allow
  12979. * more, but this is not guaranteed here, since it
  12980. * may interfere with rules for port option lists. */
  12981. /* According to RFC 1035, hostnames are restricted to 255 characters
  12982. * in total (63 between two dots). */
  12983. char hostname[256];
  12984. size_t hostnlen = (size_t)(cb - vec->ptr);
  12985. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12986. /* This would be invalid in any case */
  12987. *ip_version = 0;
  12988. return 0;
  12989. }
  12990. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12991. if (mg_inet_pton(
  12992. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12993. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12994. *ip_version = 4;
  12995. so->lsa.sin.sin_port = htons((uint16_t)port);
  12996. len += (int)(hostnlen + 1);
  12997. } else {
  12998. len = 0;
  12999. }
  13000. #if defined(USE_IPV6)
  13001. } else if (mg_inet_pton(AF_INET6,
  13002. hostname,
  13003. &so->lsa.sin6,
  13004. sizeof(so->lsa.sin6),
  13005. 1)) {
  13006. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13007. *ip_version = 6;
  13008. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13009. len += (int)(hostnlen + 1);
  13010. } else {
  13011. len = 0;
  13012. }
  13013. #endif
  13014. } else {
  13015. len = 0;
  13016. }
  13017. } else {
  13018. /* Parsing failure. */
  13019. len = 0;
  13020. }
  13021. /* sscanf and the option splitting code ensure the following condition
  13022. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13023. if ((len > 0) && is_valid_port(port)
  13024. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13025. /* Next character after the port number */
  13026. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13027. so->is_ssl = (ch == 's');
  13028. so->ssl_redir = (ch == 'r');
  13029. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13030. return 1;
  13031. }
  13032. }
  13033. /* Reset ip_version to 0 if there is an error */
  13034. *ip_version = 0;
  13035. return 0;
  13036. }
  13037. /* Is there any SSL port in use? */
  13038. static int
  13039. is_ssl_port_used(const char *ports)
  13040. {
  13041. if (ports) {
  13042. /* There are several different allowed syntax variants:
  13043. * - "80" for a single port using every network interface
  13044. * - "localhost:80" for a single port using only localhost
  13045. * - "80,localhost:8080" for two ports, one bound to localhost
  13046. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13047. * to IPv4 localhost, one to IPv6 localhost
  13048. * - "+80" use port 80 for IPv4 and IPv6
  13049. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13050. * for both: IPv4 and IPv4
  13051. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13052. * additionally port 8080 bound to localhost connections
  13053. *
  13054. * If we just look for 's' anywhere in the string, "localhost:80"
  13055. * will be detected as SSL (false positive).
  13056. * Looking for 's' after a digit may cause false positives in
  13057. * "my24service:8080".
  13058. * Looking from 's' backward if there are only ':' and numbers
  13059. * before will not work for "24service:8080" (non SSL, port 8080)
  13060. * or "24s" (SSL, port 24).
  13061. *
  13062. * Remark: Initially hostnames were not allowed to start with a
  13063. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13064. * Section 2.1).
  13065. *
  13066. * To get this correct, the entire string must be parsed as a whole,
  13067. * reading it as a list element for element and parsing with an
  13068. * algorithm equivalent to parse_port_string.
  13069. *
  13070. * In fact, we use local interface names here, not arbitrary
  13071. * hostnames, so in most cases the only name will be "localhost".
  13072. *
  13073. * So, for now, we use this simple algorithm, that may still return
  13074. * a false positive in bizarre cases.
  13075. */
  13076. int i;
  13077. int portslen = (int)strlen(ports);
  13078. char prevIsNumber = 0;
  13079. for (i = 0; i < portslen; i++) {
  13080. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13081. return 1;
  13082. }
  13083. if (ports[i] >= '0' && ports[i] <= '9') {
  13084. prevIsNumber = 1;
  13085. } else {
  13086. prevIsNumber = 0;
  13087. }
  13088. }
  13089. }
  13090. return 0;
  13091. }
  13092. static int
  13093. set_ports_option(struct mg_context *phys_ctx)
  13094. {
  13095. const char *list;
  13096. int on = 1;
  13097. #if defined(USE_IPV6)
  13098. int off = 0;
  13099. #endif
  13100. struct vec vec;
  13101. struct socket so, *ptr;
  13102. struct mg_pollfd *pfd;
  13103. union usa usa;
  13104. socklen_t len;
  13105. int ip_version;
  13106. int portsTotal = 0;
  13107. int portsOk = 0;
  13108. const char *opt_txt;
  13109. long opt_listen_backlog;
  13110. if (!phys_ctx) {
  13111. return 0;
  13112. }
  13113. memset(&so, 0, sizeof(so));
  13114. memset(&usa, 0, sizeof(usa));
  13115. len = sizeof(usa);
  13116. list = phys_ctx->dd.config[LISTENING_PORTS];
  13117. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13118. portsTotal++;
  13119. if (!parse_port_string(&vec, &so, &ip_version)) {
  13120. mg_cry_ctx_internal(
  13121. phys_ctx,
  13122. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13123. (int)vec.len,
  13124. vec.ptr,
  13125. portsTotal,
  13126. "[IP_ADDRESS:]PORT[s|r]");
  13127. continue;
  13128. }
  13129. #if !defined(NO_SSL)
  13130. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13131. mg_cry_ctx_internal(phys_ctx,
  13132. "Cannot add SSL socket (entry %i)",
  13133. portsTotal);
  13134. continue;
  13135. }
  13136. #endif
  13137. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  13138. == INVALID_SOCKET) {
  13139. mg_cry_ctx_internal(phys_ctx,
  13140. "cannot create socket (entry %i)",
  13141. portsTotal);
  13142. continue;
  13143. }
  13144. #if defined(_WIN32)
  13145. /* Windows SO_REUSEADDR lets many procs binds to a
  13146. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13147. * if someone already has the socket -- DTL */
  13148. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13149. * Windows might need a few seconds before
  13150. * the same port can be used again in the
  13151. * same process, so a short Sleep may be
  13152. * required between mg_stop and mg_start.
  13153. */
  13154. if (setsockopt(so.sock,
  13155. SOL_SOCKET,
  13156. SO_EXCLUSIVEADDRUSE,
  13157. (SOCK_OPT_TYPE)&on,
  13158. sizeof(on))
  13159. != 0) {
  13160. /* Set reuse option, but don't abort on errors. */
  13161. mg_cry_ctx_internal(
  13162. phys_ctx,
  13163. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13164. portsTotal);
  13165. }
  13166. #else
  13167. if (setsockopt(so.sock,
  13168. SOL_SOCKET,
  13169. SO_REUSEADDR,
  13170. (SOCK_OPT_TYPE)&on,
  13171. sizeof(on))
  13172. != 0) {
  13173. /* Set reuse option, but don't abort on errors. */
  13174. mg_cry_ctx_internal(
  13175. phys_ctx,
  13176. "cannot set socket option SO_REUSEADDR (entry %i)",
  13177. portsTotal);
  13178. }
  13179. #endif
  13180. if (ip_version > 4) {
  13181. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13182. #if defined(USE_IPV6)
  13183. if (ip_version > 6) {
  13184. if (so.lsa.sa.sa_family == AF_INET6
  13185. && setsockopt(so.sock,
  13186. IPPROTO_IPV6,
  13187. IPV6_V6ONLY,
  13188. (void *)&off,
  13189. sizeof(off))
  13190. != 0) {
  13191. /* Set IPv6 only option, but don't abort on errors. */
  13192. mg_cry_ctx_internal(phys_ctx,
  13193. "cannot set socket option "
  13194. "IPV6_V6ONLY=off (entry %i)",
  13195. portsTotal);
  13196. }
  13197. } else {
  13198. if (so.lsa.sa.sa_family == AF_INET6
  13199. && setsockopt(so.sock,
  13200. IPPROTO_IPV6,
  13201. IPV6_V6ONLY,
  13202. (void *)&on,
  13203. sizeof(on))
  13204. != 0) {
  13205. /* Set IPv6 only option, but don't abort on errors. */
  13206. mg_cry_ctx_internal(phys_ctx,
  13207. "cannot set socket option "
  13208. "IPV6_V6ONLY=on (entry %i)",
  13209. portsTotal);
  13210. }
  13211. }
  13212. #else
  13213. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13214. closesocket(so.sock);
  13215. so.sock = INVALID_SOCKET;
  13216. continue;
  13217. #endif
  13218. }
  13219. if (so.lsa.sa.sa_family == AF_INET) {
  13220. len = sizeof(so.lsa.sin);
  13221. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13222. mg_cry_ctx_internal(phys_ctx,
  13223. "cannot bind to %.*s: %d (%s)",
  13224. (int)vec.len,
  13225. vec.ptr,
  13226. (int)ERRNO,
  13227. strerror(errno));
  13228. closesocket(so.sock);
  13229. so.sock = INVALID_SOCKET;
  13230. continue;
  13231. }
  13232. }
  13233. #if defined(USE_IPV6)
  13234. else if (so.lsa.sa.sa_family == AF_INET6) {
  13235. len = sizeof(so.lsa.sin6);
  13236. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13237. mg_cry_ctx_internal(phys_ctx,
  13238. "cannot bind to IPv6 %.*s: %d (%s)",
  13239. (int)vec.len,
  13240. vec.ptr,
  13241. (int)ERRNO,
  13242. strerror(errno));
  13243. closesocket(so.sock);
  13244. so.sock = INVALID_SOCKET;
  13245. continue;
  13246. }
  13247. }
  13248. #endif
  13249. else {
  13250. mg_cry_ctx_internal(
  13251. phys_ctx,
  13252. "cannot bind: address family not supported (entry %i)",
  13253. portsTotal);
  13254. closesocket(so.sock);
  13255. so.sock = INVALID_SOCKET;
  13256. continue;
  13257. }
  13258. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13259. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13260. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13261. mg_cry_ctx_internal(phys_ctx,
  13262. "%s value \"%s\" is invalid",
  13263. config_options[LISTEN_BACKLOG_SIZE].name,
  13264. opt_txt);
  13265. closesocket(so.sock);
  13266. so.sock = INVALID_SOCKET;
  13267. continue;
  13268. }
  13269. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13270. mg_cry_ctx_internal(phys_ctx,
  13271. "cannot listen to %.*s: %d (%s)",
  13272. (int)vec.len,
  13273. vec.ptr,
  13274. (int)ERRNO,
  13275. strerror(errno));
  13276. closesocket(so.sock);
  13277. so.sock = INVALID_SOCKET;
  13278. continue;
  13279. }
  13280. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13281. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13282. int err = (int)ERRNO;
  13283. mg_cry_ctx_internal(phys_ctx,
  13284. "call to getsockname failed %.*s: %d (%s)",
  13285. (int)vec.len,
  13286. vec.ptr,
  13287. err,
  13288. strerror(errno));
  13289. closesocket(so.sock);
  13290. so.sock = INVALID_SOCKET;
  13291. continue;
  13292. }
  13293. /* Update lsa port in case of random free ports */
  13294. #if defined(USE_IPV6)
  13295. if (so.lsa.sa.sa_family == AF_INET6) {
  13296. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13297. } else
  13298. #endif
  13299. {
  13300. so.lsa.sin.sin_port = usa.sin.sin_port;
  13301. }
  13302. if ((ptr = (struct socket *)
  13303. mg_realloc_ctx(phys_ctx->listening_sockets,
  13304. (phys_ctx->num_listening_sockets + 1)
  13305. * sizeof(phys_ctx->listening_sockets[0]),
  13306. phys_ctx))
  13307. == NULL) {
  13308. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13309. closesocket(so.sock);
  13310. so.sock = INVALID_SOCKET;
  13311. continue;
  13312. }
  13313. if ((pfd = (struct mg_pollfd *)
  13314. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13315. (phys_ctx->num_listening_sockets + 1)
  13316. * sizeof(phys_ctx->listening_socket_fds[0]),
  13317. phys_ctx))
  13318. == NULL) {
  13319. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13320. closesocket(so.sock);
  13321. so.sock = INVALID_SOCKET;
  13322. mg_free(ptr);
  13323. continue;
  13324. }
  13325. set_close_on_exec(so.sock, NULL, phys_ctx);
  13326. phys_ctx->listening_sockets = ptr;
  13327. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13328. phys_ctx->listening_socket_fds = pfd;
  13329. phys_ctx->num_listening_sockets++;
  13330. portsOk++;
  13331. }
  13332. if (portsOk != portsTotal) {
  13333. close_all_listening_sockets(phys_ctx);
  13334. portsOk = 0;
  13335. }
  13336. return portsOk;
  13337. }
  13338. static const char *
  13339. header_val(const struct mg_connection *conn, const char *header)
  13340. {
  13341. const char *header_value;
  13342. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13343. return "-";
  13344. } else {
  13345. return header_value;
  13346. }
  13347. }
  13348. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13349. static void log_access(const struct mg_connection *conn);
  13350. #include "external_log_access.inl"
  13351. #elif !defined(NO_FILESYSTEMS)
  13352. static void
  13353. log_access(const struct mg_connection *conn)
  13354. {
  13355. const struct mg_request_info *ri;
  13356. struct mg_file fi;
  13357. char date[64], src_addr[IP_ADDR_STR_LEN];
  13358. struct tm *tm;
  13359. const char *referer;
  13360. const char *user_agent;
  13361. char buf[4096];
  13362. if (!conn || !conn->dom_ctx) {
  13363. return;
  13364. }
  13365. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13366. if (mg_fopen(conn,
  13367. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13368. MG_FOPEN_MODE_APPEND,
  13369. &fi)
  13370. == 0) {
  13371. fi.access.fp = NULL;
  13372. }
  13373. } else {
  13374. fi.access.fp = NULL;
  13375. }
  13376. /* Log is written to a file and/or a callback. If both are not set,
  13377. * executing the rest of the function is pointless. */
  13378. if ((fi.access.fp == NULL)
  13379. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13380. return;
  13381. }
  13382. tm = localtime(&conn->conn_birth_time);
  13383. if (tm != NULL) {
  13384. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13385. } else {
  13386. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13387. date[sizeof(date) - 1] = '\0';
  13388. }
  13389. ri = &conn->request_info;
  13390. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13391. referer = header_val(conn, "Referer");
  13392. user_agent = header_val(conn, "User-Agent");
  13393. mg_snprintf(conn,
  13394. NULL, /* Ignore truncation in access log */
  13395. buf,
  13396. sizeof(buf),
  13397. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13398. src_addr,
  13399. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13400. date,
  13401. ri->request_method ? ri->request_method : "-",
  13402. ri->request_uri ? ri->request_uri : "-",
  13403. ri->query_string ? "?" : "",
  13404. ri->query_string ? ri->query_string : "",
  13405. ri->http_version,
  13406. conn->status_code,
  13407. conn->num_bytes_sent,
  13408. referer,
  13409. user_agent);
  13410. if (conn->phys_ctx->callbacks.log_access) {
  13411. conn->phys_ctx->callbacks.log_access(conn, buf);
  13412. }
  13413. if (fi.access.fp) {
  13414. int ok = 1;
  13415. flockfile(fi.access.fp);
  13416. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13417. ok = 0;
  13418. }
  13419. if (fflush(fi.access.fp) != 0) {
  13420. ok = 0;
  13421. }
  13422. funlockfile(fi.access.fp);
  13423. if (mg_fclose(&fi.access) != 0) {
  13424. ok = 0;
  13425. }
  13426. if (!ok) {
  13427. mg_cry_internal(conn,
  13428. "Error writing log file %s",
  13429. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13430. }
  13431. }
  13432. }
  13433. #else
  13434. #error Must either enable filesystems or provide a custom log_access implementation
  13435. #endif /* Externally provided function */
  13436. /* Verify given socket address against the ACL.
  13437. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13438. */
  13439. static int
  13440. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13441. {
  13442. int allowed, flag, matched;
  13443. struct vec vec;
  13444. if (phys_ctx) {
  13445. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13446. /* If any ACL is set, deny by default */
  13447. allowed = (list == NULL) ? '+' : '-';
  13448. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13449. flag = vec.ptr[0];
  13450. matched = -1;
  13451. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13452. vec.ptr++;
  13453. vec.len--;
  13454. matched = parse_match_net(&vec, sa, 1);
  13455. }
  13456. if (matched < 0) {
  13457. mg_cry_ctx_internal(phys_ctx,
  13458. "%s: subnet must be [+|-]IP-addr[/x]",
  13459. __func__);
  13460. return -1;
  13461. }
  13462. if (matched) {
  13463. allowed = flag;
  13464. }
  13465. }
  13466. return allowed == '+';
  13467. }
  13468. return -1;
  13469. }
  13470. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13471. static int
  13472. set_uid_option(struct mg_context *phys_ctx)
  13473. {
  13474. int success = 0;
  13475. if (phys_ctx) {
  13476. /* We are currently running as curr_uid. */
  13477. const uid_t curr_uid = getuid();
  13478. /* If set, we want to run as run_as_user. */
  13479. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13480. const struct passwd *to_pw = NULL;
  13481. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13482. /* run_as_user does not exist on the system. We can't proceed
  13483. * further. */
  13484. mg_cry_ctx_internal(phys_ctx,
  13485. "%s: unknown user [%s]",
  13486. __func__,
  13487. run_as_user);
  13488. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13489. /* There was either no request to change user, or we're already
  13490. * running as run_as_user. Nothing else to do.
  13491. */
  13492. success = 1;
  13493. } else {
  13494. /* Valid change request. */
  13495. if (setgid(to_pw->pw_gid) == -1) {
  13496. mg_cry_ctx_internal(phys_ctx,
  13497. "%s: setgid(%s): %s",
  13498. __func__,
  13499. run_as_user,
  13500. strerror(errno));
  13501. } else if (setgroups(0, NULL) == -1) {
  13502. mg_cry_ctx_internal(phys_ctx,
  13503. "%s: setgroups(): %s",
  13504. __func__,
  13505. strerror(errno));
  13506. } else if (setuid(to_pw->pw_uid) == -1) {
  13507. mg_cry_ctx_internal(phys_ctx,
  13508. "%s: setuid(%s): %s",
  13509. __func__,
  13510. run_as_user,
  13511. strerror(errno));
  13512. } else {
  13513. success = 1;
  13514. }
  13515. }
  13516. }
  13517. return success;
  13518. }
  13519. #endif /* !_WIN32 */
  13520. static void
  13521. tls_dtor(void *key)
  13522. {
  13523. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13524. /* key == pthread_getspecific(sTlsKey); */
  13525. if (tls) {
  13526. if (tls->is_master == 2) {
  13527. tls->is_master = -3; /* Mark memory as dead */
  13528. mg_free(tls);
  13529. }
  13530. }
  13531. pthread_setspecific(sTlsKey, NULL);
  13532. }
  13533. #if !defined(NO_SSL)
  13534. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13535. struct mg_domain_context *dom_ctx,
  13536. const char *pem,
  13537. const char *chain);
  13538. static const char *ssl_error(void);
  13539. static int
  13540. refresh_trust(struct mg_connection *conn)
  13541. {
  13542. struct stat cert_buf;
  13543. int64_t t = 0;
  13544. const char *pem;
  13545. const char *chain;
  13546. int should_verify_peer;
  13547. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13548. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13549. * refresh_trust still can not work. */
  13550. return 0;
  13551. }
  13552. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13553. if (chain == NULL) {
  13554. /* pem is not NULL here */
  13555. chain = pem;
  13556. }
  13557. if (*chain == 0) {
  13558. chain = NULL;
  13559. }
  13560. if (stat(pem, &cert_buf) != -1) {
  13561. t = (int64_t)cert_buf.st_mtime;
  13562. }
  13563. mg_lock_context(conn->phys_ctx);
  13564. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13565. conn->dom_ctx->ssl_cert_last_mtime = t;
  13566. should_verify_peer = 0;
  13567. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13568. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13569. == 0) {
  13570. should_verify_peer = 1;
  13571. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13572. "optional")
  13573. == 0) {
  13574. should_verify_peer = 1;
  13575. }
  13576. }
  13577. if (should_verify_peer) {
  13578. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13579. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13580. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13581. ca_file,
  13582. ca_path)
  13583. != 1) {
  13584. mg_unlock_context(conn->phys_ctx);
  13585. mg_cry_ctx_internal(
  13586. conn->phys_ctx,
  13587. "SSL_CTX_load_verify_locations error: %s "
  13588. "ssl_verify_peer requires setting "
  13589. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13590. "present in "
  13591. "the .conf file?",
  13592. ssl_error());
  13593. return 0;
  13594. }
  13595. }
  13596. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13597. mg_unlock_context(conn->phys_ctx);
  13598. return 0;
  13599. }
  13600. }
  13601. mg_unlock_context(conn->phys_ctx);
  13602. return 1;
  13603. }
  13604. #if defined(OPENSSL_API_1_1)
  13605. #else
  13606. static pthread_mutex_t *ssl_mutexes;
  13607. #endif /* OPENSSL_API_1_1 */
  13608. static int
  13609. sslize(struct mg_connection *conn,
  13610. int (*func)(SSL *),
  13611. const struct mg_client_options *client_options)
  13612. {
  13613. int ret, err;
  13614. int short_trust;
  13615. unsigned timeout = 1024;
  13616. unsigned i;
  13617. if (!conn) {
  13618. return 0;
  13619. }
  13620. short_trust =
  13621. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13622. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13623. if (short_trust) {
  13624. int trust_ret = refresh_trust(conn);
  13625. if (!trust_ret) {
  13626. return trust_ret;
  13627. }
  13628. }
  13629. mg_lock_context(conn->phys_ctx);
  13630. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13631. mg_unlock_context(conn->phys_ctx);
  13632. if (conn->ssl == NULL) {
  13633. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13634. OPENSSL_REMOVE_THREAD_STATE();
  13635. return 0;
  13636. }
  13637. SSL_set_app_data(conn->ssl, (char *)conn);
  13638. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13639. if (ret != 1) {
  13640. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13641. SSL_free(conn->ssl);
  13642. conn->ssl = NULL;
  13643. OPENSSL_REMOVE_THREAD_STATE();
  13644. return 0;
  13645. }
  13646. if (client_options) {
  13647. if (client_options->host_name) {
  13648. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13649. }
  13650. }
  13651. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13652. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13653. /* NOTE: The loop below acts as a back-off, so we can end
  13654. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13655. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13656. if (to >= 0) {
  13657. timeout = (unsigned)to;
  13658. }
  13659. }
  13660. /* SSL functions may fail and require to be called again:
  13661. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13662. * Here "func" could be SSL_connect or SSL_accept. */
  13663. for (i = 0; i <= timeout; i += 50) {
  13664. ERR_clear_error();
  13665. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13666. ret = func(conn->ssl);
  13667. if (ret != 1) {
  13668. err = SSL_get_error(conn->ssl, ret);
  13669. if ((err == SSL_ERROR_WANT_CONNECT)
  13670. || (err == SSL_ERROR_WANT_ACCEPT)
  13671. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13672. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13673. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13674. /* Don't wait if the server is going to be stopped. */
  13675. break;
  13676. }
  13677. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13678. /* Simply retry the function call. */
  13679. mg_sleep(50);
  13680. } else {
  13681. /* Need to retry the function call "later".
  13682. * See https://linux.die.net/man/3/ssl_get_error
  13683. * This is typical for non-blocking sockets. */
  13684. struct mg_pollfd pfd;
  13685. int pollres;
  13686. pfd.fd = conn->client.sock;
  13687. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13688. || (err == SSL_ERROR_WANT_WRITE))
  13689. ? POLLOUT
  13690. : POLLIN;
  13691. pollres =
  13692. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13693. if (pollres < 0) {
  13694. /* Break if error occured (-1)
  13695. * or server shutdown (-2) */
  13696. break;
  13697. }
  13698. }
  13699. } else if (err == SSL_ERROR_SYSCALL) {
  13700. /* This is an IO error. Look at errno. */
  13701. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13702. break;
  13703. } else {
  13704. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13705. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13706. break;
  13707. }
  13708. } else {
  13709. /* success */
  13710. break;
  13711. }
  13712. }
  13713. ERR_clear_error();
  13714. if (ret != 1) {
  13715. SSL_free(conn->ssl);
  13716. conn->ssl = NULL;
  13717. OPENSSL_REMOVE_THREAD_STATE();
  13718. return 0;
  13719. }
  13720. return 1;
  13721. }
  13722. /* Return OpenSSL error message (from CRYPTO lib) */
  13723. static const char *
  13724. ssl_error(void)
  13725. {
  13726. unsigned long err;
  13727. err = ERR_get_error();
  13728. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13729. }
  13730. static int
  13731. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13732. {
  13733. int i;
  13734. const char hexdigit[] = "0123456789abcdef";
  13735. if ((memlen <= 0) || (buflen <= 0)) {
  13736. return 0;
  13737. }
  13738. if (buflen < (3 * memlen)) {
  13739. return 0;
  13740. }
  13741. for (i = 0; i < memlen; i++) {
  13742. if (i > 0) {
  13743. buf[3 * i - 1] = ' ';
  13744. }
  13745. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13746. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13747. }
  13748. buf[3 * memlen - 1] = 0;
  13749. return 1;
  13750. }
  13751. static int
  13752. ssl_get_client_cert_info(const struct mg_connection *conn,
  13753. struct mg_client_cert *client_cert)
  13754. {
  13755. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13756. if (cert) {
  13757. char str_buf[1024];
  13758. unsigned char buf[256];
  13759. char *str_serial = NULL;
  13760. unsigned int ulen;
  13761. int ilen;
  13762. unsigned char *tmp_buf;
  13763. unsigned char *tmp_p;
  13764. /* Handle to algorithm used for fingerprint */
  13765. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13766. /* Get Subject and issuer */
  13767. X509_NAME *subj = X509_get_subject_name(cert);
  13768. X509_NAME *iss = X509_get_issuer_name(cert);
  13769. /* Get serial number */
  13770. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13771. /* Translate serial number to a hex string */
  13772. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13773. if (serial_bn) {
  13774. str_serial = BN_bn2hex(serial_bn);
  13775. BN_free(serial_bn);
  13776. }
  13777. client_cert->serial =
  13778. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13779. /* Translate subject and issuer to a string */
  13780. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13781. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13782. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13783. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13784. /* Calculate SHA1 fingerprint and store as a hex string */
  13785. ulen = 0;
  13786. /* ASN1_digest is deprecated. Do the calculation manually,
  13787. * using EVP_Digest. */
  13788. ilen = i2d_X509(cert, NULL);
  13789. tmp_buf = (ilen > 0)
  13790. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13791. conn->phys_ctx)
  13792. : NULL;
  13793. if (tmp_buf) {
  13794. tmp_p = tmp_buf;
  13795. (void)i2d_X509(cert, &tmp_p);
  13796. if (!EVP_Digest(
  13797. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13798. ulen = 0;
  13799. }
  13800. mg_free(tmp_buf);
  13801. }
  13802. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13803. *str_buf = 0;
  13804. }
  13805. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13806. client_cert->peer_cert = (void *)cert;
  13807. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13808. * see https://linux.die.net/man/3/bn_bn2hex */
  13809. OPENSSL_free(str_serial);
  13810. return 1;
  13811. }
  13812. return 0;
  13813. }
  13814. #if defined(OPENSSL_API_1_1)
  13815. #else
  13816. static void
  13817. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13818. {
  13819. (void)line;
  13820. (void)file;
  13821. if (mode & 1) {
  13822. /* 1 is CRYPTO_LOCK */
  13823. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13824. } else {
  13825. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13826. }
  13827. }
  13828. #endif /* OPENSSL_API_1_1 */
  13829. #if !defined(NO_SSL_DL)
  13830. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13831. static void *
  13832. load_tls_dll(char *ebuf,
  13833. size_t ebuf_len,
  13834. const char *dll_name,
  13835. struct ssl_func *sw,
  13836. int *feature_missing)
  13837. {
  13838. union {
  13839. void *p;
  13840. void (*fp)(void);
  13841. } u;
  13842. void *dll_handle;
  13843. struct ssl_func *fp;
  13844. int ok;
  13845. int truncated = 0;
  13846. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13847. mg_snprintf(NULL,
  13848. NULL, /* No truncation check for ebuf */
  13849. ebuf,
  13850. ebuf_len,
  13851. "%s: cannot load %s",
  13852. __func__,
  13853. dll_name);
  13854. return NULL;
  13855. }
  13856. ok = 1;
  13857. for (fp = sw; fp->name != NULL; fp++) {
  13858. #if defined(_WIN32)
  13859. /* GetProcAddress() returns pointer to function */
  13860. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13861. #else
  13862. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13863. * pointers to function pointers. We need to use a union to make a
  13864. * cast. */
  13865. u.p = dlsym(dll_handle, fp->name);
  13866. #endif /* _WIN32 */
  13867. /* Set pointer (might be NULL) */
  13868. fp->ptr = u.fp;
  13869. if (u.fp == NULL) {
  13870. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13871. if (feature_missing) {
  13872. feature_missing[fp->required]++;
  13873. }
  13874. if (fp->required == TLS_Mandatory) {
  13875. /* Mandatory function is missing */
  13876. if (ok) {
  13877. /* This is the first missing function.
  13878. * Create a new error message. */
  13879. mg_snprintf(NULL,
  13880. &truncated,
  13881. ebuf,
  13882. ebuf_len,
  13883. "%s: %s: cannot find %s",
  13884. __func__,
  13885. dll_name,
  13886. fp->name);
  13887. ok = 0;
  13888. } else {
  13889. /* This is yet anothermissing function.
  13890. * Append existing error message. */
  13891. size_t cur_len = strlen(ebuf);
  13892. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13893. mg_snprintf(NULL,
  13894. &truncated,
  13895. ebuf + cur_len,
  13896. ebuf_len - cur_len - 3,
  13897. ", %s",
  13898. fp->name);
  13899. if (truncated) {
  13900. /* If truncated, add "..." */
  13901. strcat(ebuf, "...");
  13902. }
  13903. }
  13904. }
  13905. }
  13906. }
  13907. }
  13908. if (!ok) {
  13909. (void)dlclose(dll_handle);
  13910. return NULL;
  13911. }
  13912. return dll_handle;
  13913. }
  13914. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13915. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13916. #endif /* NO_SSL_DL */
  13917. #if defined(SSL_ALREADY_INITIALIZED)
  13918. static volatile ptrdiff_t cryptolib_users =
  13919. 1; /* Reference counter for crypto library. */
  13920. #else
  13921. static volatile ptrdiff_t cryptolib_users =
  13922. 0; /* Reference counter for crypto library. */
  13923. #endif
  13924. static int
  13925. initialize_ssl(char *ebuf, size_t ebuf_len)
  13926. {
  13927. #if !defined(OPENSSL_API_1_1)
  13928. int i, num_locks;
  13929. size_t size;
  13930. #endif
  13931. if (ebuf_len > 0) {
  13932. ebuf[0] = 0;
  13933. }
  13934. #if !defined(NO_SSL_DL)
  13935. if (!cryptolib_dll_handle) {
  13936. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13937. cryptolib_dll_handle = load_tls_dll(
  13938. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13939. if (!cryptolib_dll_handle) {
  13940. mg_snprintf(NULL,
  13941. NULL, /* No truncation check for ebuf */
  13942. ebuf,
  13943. ebuf_len,
  13944. "%s: error loading library %s",
  13945. __func__,
  13946. CRYPTO_LIB);
  13947. DEBUG_TRACE("%s", ebuf);
  13948. return 0;
  13949. }
  13950. }
  13951. #endif /* NO_SSL_DL */
  13952. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13953. return 1;
  13954. }
  13955. #if !defined(OPENSSL_API_1_1)
  13956. /* Initialize locking callbacks, needed for thread safety.
  13957. * http://www.openssl.org/support/faq.html#PROG1
  13958. */
  13959. num_locks = CRYPTO_num_locks();
  13960. if (num_locks < 0) {
  13961. num_locks = 0;
  13962. }
  13963. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13964. /* allocate mutex array, if required */
  13965. if (num_locks == 0) {
  13966. /* No mutex array required */
  13967. ssl_mutexes = NULL;
  13968. } else {
  13969. /* Mutex array required - allocate it */
  13970. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13971. /* Check OOM */
  13972. if (ssl_mutexes == NULL) {
  13973. mg_snprintf(NULL,
  13974. NULL, /* No truncation check for ebuf */
  13975. ebuf,
  13976. ebuf_len,
  13977. "%s: cannot allocate mutexes: %s",
  13978. __func__,
  13979. ssl_error());
  13980. DEBUG_TRACE("%s", ebuf);
  13981. return 0;
  13982. }
  13983. /* initialize mutex array */
  13984. for (i = 0; i < num_locks; i++) {
  13985. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13986. mg_snprintf(NULL,
  13987. NULL, /* No truncation check for ebuf */
  13988. ebuf,
  13989. ebuf_len,
  13990. "%s: error initializing mutex %i of %i",
  13991. __func__,
  13992. i,
  13993. num_locks);
  13994. DEBUG_TRACE("%s", ebuf);
  13995. mg_free(ssl_mutexes);
  13996. return 0;
  13997. }
  13998. }
  13999. }
  14000. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14001. CRYPTO_set_id_callback(&mg_current_thread_id);
  14002. #endif /* OPENSSL_API_1_1 */
  14003. #if !defined(NO_SSL_DL)
  14004. if (!ssllib_dll_handle) {
  14005. ssllib_dll_handle =
  14006. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14007. if (!ssllib_dll_handle) {
  14008. #if !defined(OPENSSL_API_1_1)
  14009. mg_free(ssl_mutexes);
  14010. #endif
  14011. DEBUG_TRACE("%s", ebuf);
  14012. return 0;
  14013. }
  14014. }
  14015. #endif /* NO_SSL_DL */
  14016. #if defined(OPENSSL_API_1_1)
  14017. /* Initialize SSL library */
  14018. OPENSSL_init_ssl(0, NULL);
  14019. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14020. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14021. NULL);
  14022. #else
  14023. /* Initialize SSL library */
  14024. SSL_library_init();
  14025. SSL_load_error_strings();
  14026. #endif
  14027. return 1;
  14028. }
  14029. static int
  14030. ssl_use_pem_file(struct mg_context *phys_ctx,
  14031. struct mg_domain_context *dom_ctx,
  14032. const char *pem,
  14033. const char *chain)
  14034. {
  14035. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14036. mg_cry_ctx_internal(phys_ctx,
  14037. "%s: cannot open certificate file %s: %s",
  14038. __func__,
  14039. pem,
  14040. ssl_error());
  14041. return 0;
  14042. }
  14043. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14044. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14045. mg_cry_ctx_internal(phys_ctx,
  14046. "%s: cannot open private key file %s: %s",
  14047. __func__,
  14048. pem,
  14049. ssl_error());
  14050. return 0;
  14051. }
  14052. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14053. mg_cry_ctx_internal(phys_ctx,
  14054. "%s: certificate and private key do not match: %s",
  14055. __func__,
  14056. pem);
  14057. return 0;
  14058. }
  14059. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14060. * chain files that contain private keys and certificates in
  14061. * SSL_CTX_use_certificate_chain_file.
  14062. * The CivetWeb-Server used pem-Files that contained both information.
  14063. * In order to make wolfSSL work, it is split in two files.
  14064. * One file that contains key and certificate used by the server and
  14065. * an optional chain file for the ssl stack.
  14066. */
  14067. if (chain) {
  14068. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14069. mg_cry_ctx_internal(phys_ctx,
  14070. "%s: cannot use certificate chain file %s: %s",
  14071. __func__,
  14072. chain,
  14073. ssl_error());
  14074. return 0;
  14075. }
  14076. }
  14077. return 1;
  14078. }
  14079. #if defined(OPENSSL_API_1_1)
  14080. static unsigned long
  14081. ssl_get_protocol(int version_id)
  14082. {
  14083. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14084. if (version_id > 0)
  14085. ret |= SSL_OP_NO_SSLv2;
  14086. if (version_id > 1)
  14087. ret |= SSL_OP_NO_SSLv3;
  14088. if (version_id > 2)
  14089. ret |= SSL_OP_NO_TLSv1;
  14090. if (version_id > 3)
  14091. ret |= SSL_OP_NO_TLSv1_1;
  14092. if (version_id > 4)
  14093. ret |= SSL_OP_NO_TLSv1_2;
  14094. #if defined(SSL_OP_NO_TLSv1_3)
  14095. if (version_id > 5)
  14096. ret |= SSL_OP_NO_TLSv1_3;
  14097. #endif
  14098. return ret;
  14099. }
  14100. #else
  14101. static long
  14102. ssl_get_protocol(int version_id)
  14103. {
  14104. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14105. if (version_id > 0)
  14106. ret |= SSL_OP_NO_SSLv2;
  14107. if (version_id > 1)
  14108. ret |= SSL_OP_NO_SSLv3;
  14109. if (version_id > 2)
  14110. ret |= SSL_OP_NO_TLSv1;
  14111. if (version_id > 3)
  14112. ret |= SSL_OP_NO_TLSv1_1;
  14113. if (version_id > 4)
  14114. ret |= SSL_OP_NO_TLSv1_2;
  14115. #if defined(SSL_OP_NO_TLSv1_3)
  14116. if (version_id > 5)
  14117. ret |= SSL_OP_NO_TLSv1_3;
  14118. #endif
  14119. return (long)ret;
  14120. }
  14121. #endif /* OPENSSL_API_1_1 */
  14122. /* SSL callback documentation:
  14123. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14124. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14125. * https://linux.die.net/man/3/ssl_set_info_callback */
  14126. /* Note: There is no "const" for the first argument in the documentation
  14127. * examples, however some (maybe most, but not all) headers of OpenSSL
  14128. * versions / OpenSSL compatibility layers have it. Having a different
  14129. * definition will cause a warning in C and an error in C++. Use "const SSL
  14130. * *", while automatical conversion from "SSL *" works for all compilers,
  14131. * but not other way around */
  14132. static void
  14133. ssl_info_callback(const SSL *ssl, int what, int ret)
  14134. {
  14135. (void)ret;
  14136. if (what & SSL_CB_HANDSHAKE_START) {
  14137. SSL_get_app_data(ssl);
  14138. }
  14139. if (what & SSL_CB_HANDSHAKE_DONE) {
  14140. /* TODO: check for openSSL 1.1 */
  14141. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14142. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14143. }
  14144. }
  14145. static int
  14146. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14147. {
  14148. #if defined(GCC_DIAGNOSTIC)
  14149. #pragma GCC diagnostic push
  14150. #pragma GCC diagnostic ignored "-Wcast-align"
  14151. #endif /* defined(GCC_DIAGNOSTIC) */
  14152. /* We used an aligned pointer in SSL_set_app_data */
  14153. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14154. #if defined(GCC_DIAGNOSTIC)
  14155. #pragma GCC diagnostic pop
  14156. #endif /* defined(GCC_DIAGNOSTIC) */
  14157. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14158. (void)ad;
  14159. (void)arg;
  14160. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14161. DEBUG_ASSERT(0);
  14162. return SSL_TLSEXT_ERR_NOACK;
  14163. }
  14164. conn->dom_ctx = &(conn->phys_ctx->dd);
  14165. /* Old clients (Win XP) will not support SNI. Then, there
  14166. * is no server name available in the request - we can
  14167. * only work with the default certificate.
  14168. * Multiple HTTPS hosts on one IP+port are only possible
  14169. * with a certificate containing all alternative names.
  14170. */
  14171. if ((servername == NULL) || (*servername == 0)) {
  14172. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14173. mg_lock_context(conn->phys_ctx);
  14174. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14175. mg_unlock_context(conn->phys_ctx);
  14176. return SSL_TLSEXT_ERR_NOACK;
  14177. }
  14178. DEBUG_TRACE("TLS connection to host %s", servername);
  14179. while (conn->dom_ctx) {
  14180. if (!mg_strcasecmp(servername,
  14181. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14182. /* Found matching domain */
  14183. DEBUG_TRACE("TLS domain %s found",
  14184. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14185. break;
  14186. }
  14187. mg_lock_context(conn->phys_ctx);
  14188. conn->dom_ctx = conn->dom_ctx->next;
  14189. mg_unlock_context(conn->phys_ctx);
  14190. }
  14191. if (conn->dom_ctx == NULL) {
  14192. /* Default domain */
  14193. DEBUG_TRACE("TLS default domain %s used",
  14194. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14195. conn->dom_ctx = &(conn->phys_ctx->dd);
  14196. }
  14197. mg_lock_context(conn->phys_ctx);
  14198. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14199. mg_unlock_context(conn->phys_ctx);
  14200. return SSL_TLSEXT_ERR_OK;
  14201. }
  14202. #if defined(USE_ALPN)
  14203. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14204. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14205. alpn_proto_list + 3 + 8,
  14206. NULL};
  14207. #if defined(USE_HTTP2)
  14208. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14209. alpn_proto_list + 3,
  14210. alpn_proto_list + 3 + 8,
  14211. NULL};
  14212. #endif
  14213. static int
  14214. alpn_select_cb(SSL *ssl,
  14215. const unsigned char **out,
  14216. unsigned char *outlen,
  14217. const unsigned char *in,
  14218. unsigned int inlen,
  14219. void *arg)
  14220. {
  14221. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14222. unsigned int i, j, enable_http2 = 0;
  14223. const char **alpn_proto_order = alpn_proto_order_http1;
  14224. struct mg_workerTLS *tls =
  14225. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14226. (void)ssl;
  14227. if (tls == NULL) {
  14228. /* Need to store protocol in Thread Local Storage */
  14229. /* If there is no Thread Local Storage, don't use ALPN */
  14230. return SSL_TLSEXT_ERR_NOACK;
  14231. }
  14232. #if defined(USE_HTTP2)
  14233. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14234. if (enable_http2) {
  14235. alpn_proto_order = alpn_proto_order_http2;
  14236. }
  14237. #endif
  14238. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14239. /* check all accepted protocols in this order */
  14240. const char *alpn_proto = alpn_proto_order[j];
  14241. /* search input for matching protocol */
  14242. for (i = 0; i < inlen; i++) {
  14243. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14244. *out = in + i + 1;
  14245. *outlen = in[i];
  14246. tls->alpn_proto = alpn_proto;
  14247. return SSL_TLSEXT_ERR_OK;
  14248. }
  14249. }
  14250. }
  14251. /* Nothing found */
  14252. return SSL_TLSEXT_ERR_NOACK;
  14253. }
  14254. static int
  14255. next_protos_advertised_cb(SSL *ssl,
  14256. const unsigned char **data,
  14257. unsigned int *len,
  14258. void *arg)
  14259. {
  14260. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14261. *data = (const unsigned char *)alpn_proto_list;
  14262. *len = (unsigned int)strlen((const char *)data);
  14263. (void)ssl;
  14264. (void)dom_ctx;
  14265. return SSL_TLSEXT_ERR_OK;
  14266. }
  14267. static int
  14268. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14269. {
  14270. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14271. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14272. (const unsigned char *)alpn_proto_list,
  14273. alpn_len);
  14274. if (ret != 0) {
  14275. mg_cry_ctx_internal(phys_ctx,
  14276. "SSL_CTX_set_alpn_protos error: %s",
  14277. ssl_error());
  14278. }
  14279. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14280. alpn_select_cb,
  14281. (void *)dom_ctx);
  14282. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14283. next_protos_advertised_cb,
  14284. (void *)dom_ctx);
  14285. return ret;
  14286. }
  14287. #endif
  14288. /* Setup SSL CTX as required by CivetWeb */
  14289. static int
  14290. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14291. struct mg_domain_context *dom_ctx,
  14292. const char *pem,
  14293. const char *chain)
  14294. {
  14295. int callback_ret;
  14296. int should_verify_peer;
  14297. int peer_certificate_optional;
  14298. const char *ca_path;
  14299. const char *ca_file;
  14300. int use_default_verify_paths;
  14301. int verify_depth;
  14302. struct timespec now_mt;
  14303. md5_byte_t ssl_context_id[16];
  14304. md5_state_t md5state;
  14305. int protocol_ver;
  14306. int ssl_cache_timeout;
  14307. #if defined(OPENSSL_API_1_1)
  14308. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14309. mg_cry_ctx_internal(phys_ctx,
  14310. "SSL_CTX_new (server) error: %s",
  14311. ssl_error());
  14312. return 0;
  14313. }
  14314. #else
  14315. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14316. mg_cry_ctx_internal(phys_ctx,
  14317. "SSL_CTX_new (server) error: %s",
  14318. ssl_error());
  14319. return 0;
  14320. }
  14321. #endif /* OPENSSL_API_1_1 */
  14322. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14323. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14324. | SSL_OP_NO_TLSv1_1);
  14325. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14326. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14327. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14328. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14329. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14330. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14331. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14332. #if defined(SSL_OP_NO_RENEGOTIATION)
  14333. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14334. #endif
  14335. #if !defined(NO_SSL_DL)
  14336. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14337. #endif /* NO_SSL_DL */
  14338. /* In SSL documentation examples callback defined without const
  14339. * specifier 'void (*)(SSL *, int, int)' See:
  14340. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14341. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14342. * But in the source code const SSL is used:
  14343. * 'void (*)(const SSL *, int, int)' See:
  14344. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14345. * Problem about wrong documentation described, but not resolved:
  14346. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14347. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14348. * But when compiled with modern C++ compiler, correct const should be
  14349. * provided
  14350. */
  14351. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14352. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14353. ssl_servername_callback);
  14354. /* If a callback has been specified, call it. */
  14355. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14356. ? 0
  14357. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14358. phys_ctx->user_data));
  14359. /* If callback returns 0, civetweb sets up the SSL certificate.
  14360. * If it returns 1, civetweb assumes the calback already did this.
  14361. * If it returns -1, initializing ssl fails. */
  14362. if (callback_ret < 0) {
  14363. mg_cry_ctx_internal(phys_ctx,
  14364. "SSL callback returned error: %i",
  14365. callback_ret);
  14366. return 0;
  14367. }
  14368. if (callback_ret > 0) {
  14369. /* Callback did everything. */
  14370. return 1;
  14371. }
  14372. /* If a domain callback has been specified, call it. */
  14373. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14374. ? 0
  14375. : (phys_ctx->callbacks.init_ssl_domain(
  14376. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14377. dom_ctx->ssl_ctx,
  14378. phys_ctx->user_data));
  14379. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14380. * If it returns 1, civetweb assumes the calback already did this.
  14381. * If it returns -1, initializing ssl fails. */
  14382. if (callback_ret < 0) {
  14383. mg_cry_ctx_internal(phys_ctx,
  14384. "Domain SSL callback returned error: %i",
  14385. callback_ret);
  14386. return 0;
  14387. }
  14388. if (callback_ret > 0) {
  14389. /* Domain callback did everything. */
  14390. return 1;
  14391. }
  14392. /* Use some combination of start time, domain and port as a SSL
  14393. * context ID. This should be unique on the current machine. */
  14394. md5_init(&md5state);
  14395. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14396. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14397. md5_append(&md5state,
  14398. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14399. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14400. md5_append(&md5state,
  14401. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14402. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14403. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14404. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14405. md5_finish(&md5state, ssl_context_id);
  14406. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14407. (unsigned char *)ssl_context_id,
  14408. sizeof(ssl_context_id));
  14409. if (pem != NULL) {
  14410. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14411. return 0;
  14412. }
  14413. }
  14414. /* Should we support client certificates? */
  14415. /* Default is "no". */
  14416. should_verify_peer = 0;
  14417. peer_certificate_optional = 0;
  14418. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14419. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14420. /* Yes, they are mandatory */
  14421. should_verify_peer = 1;
  14422. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14423. "optional")
  14424. == 0) {
  14425. /* Yes, they are optional */
  14426. should_verify_peer = 1;
  14427. peer_certificate_optional = 1;
  14428. }
  14429. }
  14430. use_default_verify_paths =
  14431. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14432. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14433. == 0);
  14434. if (should_verify_peer) {
  14435. ca_path = dom_ctx->config[SSL_CA_PATH];
  14436. ca_file = dom_ctx->config[SSL_CA_FILE];
  14437. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14438. != 1) {
  14439. mg_cry_ctx_internal(phys_ctx,
  14440. "SSL_CTX_load_verify_locations error: %s "
  14441. "ssl_verify_peer requires setting "
  14442. "either ssl_ca_path or ssl_ca_file. "
  14443. "Is any of them present in the "
  14444. ".conf file?",
  14445. ssl_error());
  14446. return 0;
  14447. }
  14448. if (peer_certificate_optional) {
  14449. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14450. } else {
  14451. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14452. SSL_VERIFY_PEER
  14453. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14454. NULL);
  14455. }
  14456. if (use_default_verify_paths
  14457. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14458. mg_cry_ctx_internal(phys_ctx,
  14459. "SSL_CTX_set_default_verify_paths error: %s",
  14460. ssl_error());
  14461. return 0;
  14462. }
  14463. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14464. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14465. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14466. }
  14467. }
  14468. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14469. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14470. dom_ctx->config[SSL_CIPHER_LIST])
  14471. != 1) {
  14472. mg_cry_ctx_internal(phys_ctx,
  14473. "SSL_CTX_set_cipher_list error: %s",
  14474. ssl_error());
  14475. }
  14476. }
  14477. /* SSL session caching */
  14478. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14479. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14480. : 0);
  14481. if (ssl_cache_timeout > 0) {
  14482. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14483. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14484. * default */
  14485. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14486. }
  14487. #if defined(USE_ALPN)
  14488. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14489. #if !defined(NO_SSL_DL)
  14490. if (!tls_feature_missing[TLS_ALPN])
  14491. #endif
  14492. {
  14493. init_alpn(phys_ctx, dom_ctx);
  14494. }
  14495. #endif
  14496. return 1;
  14497. }
  14498. /* Check if SSL is required.
  14499. * If so, dynamically load SSL library
  14500. * and set up ctx->ssl_ctx pointer. */
  14501. static int
  14502. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14503. {
  14504. void *ssl_ctx = 0;
  14505. int callback_ret;
  14506. const char *pem;
  14507. const char *chain;
  14508. char ebuf[128];
  14509. if (!phys_ctx) {
  14510. return 0;
  14511. }
  14512. if (!dom_ctx) {
  14513. dom_ctx = &(phys_ctx->dd);
  14514. }
  14515. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14516. /* No SSL port is set. No need to setup SSL. */
  14517. return 1;
  14518. }
  14519. /* Check for external SSL_CTX */
  14520. callback_ret =
  14521. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14522. ? 0
  14523. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14524. phys_ctx->user_data));
  14525. if (callback_ret < 0) {
  14526. /* Callback exists and returns <0: Initializing failed. */
  14527. mg_cry_ctx_internal(phys_ctx,
  14528. "external_ssl_ctx callback returned error: %i",
  14529. callback_ret);
  14530. return 0;
  14531. } else if (callback_ret > 0) {
  14532. /* Callback exists and returns >0: Initializing complete,
  14533. * civetweb should not modify the SSL context. */
  14534. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14535. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14536. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14537. return 0;
  14538. }
  14539. return 1;
  14540. }
  14541. /* If the callback does not exist or return 0, civetweb must initialize
  14542. * the SSL context. Handle "domain" callback next. */
  14543. /* Check for external domain SSL_CTX callback. */
  14544. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14545. ? 0
  14546. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14547. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14548. &ssl_ctx,
  14549. phys_ctx->user_data));
  14550. if (callback_ret < 0) {
  14551. /* Callback < 0: Error. Abort init. */
  14552. mg_cry_ctx_internal(
  14553. phys_ctx,
  14554. "external_ssl_ctx_domain callback returned error: %i",
  14555. callback_ret);
  14556. return 0;
  14557. } else if (callback_ret > 0) {
  14558. /* Callback > 0: Consider init done. */
  14559. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14560. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14561. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14562. return 0;
  14563. }
  14564. return 1;
  14565. }
  14566. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14567. * 0, CivetWeb should continue initializing SSL */
  14568. /* If PEM file is not specified and the init_ssl callbacks
  14569. * are not specified, setup will fail. */
  14570. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14571. && (phys_ctx->callbacks.init_ssl == NULL)
  14572. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14573. /* No certificate and no init_ssl callbacks:
  14574. * Essential data to set up TLS is missing.
  14575. */
  14576. mg_cry_ctx_internal(phys_ctx,
  14577. "Initializing SSL failed: -%s is not set",
  14578. config_options[SSL_CERTIFICATE].name);
  14579. return 0;
  14580. }
  14581. /* If a certificate chain is configured, use it. */
  14582. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14583. if (chain == NULL) {
  14584. /* Default: certificate chain in PEM file */
  14585. chain = pem;
  14586. }
  14587. if ((chain != NULL) && (*chain == 0)) {
  14588. /* If the chain is an empty string, don't use it. */
  14589. chain = NULL;
  14590. }
  14591. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14592. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14593. return 0;
  14594. }
  14595. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14596. }
  14597. static void
  14598. uninitialize_ssl(void)
  14599. {
  14600. #if defined(OPENSSL_API_1_1)
  14601. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14602. /* Shutdown according to
  14603. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14604. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14605. */
  14606. CONF_modules_unload(1);
  14607. #else
  14608. int i;
  14609. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14610. /* Shutdown according to
  14611. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14612. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14613. */
  14614. CRYPTO_set_locking_callback(NULL);
  14615. CRYPTO_set_id_callback(NULL);
  14616. ENGINE_cleanup();
  14617. CONF_modules_unload(1);
  14618. ERR_free_strings();
  14619. EVP_cleanup();
  14620. CRYPTO_cleanup_all_ex_data();
  14621. OPENSSL_REMOVE_THREAD_STATE();
  14622. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14623. pthread_mutex_destroy(&ssl_mutexes[i]);
  14624. }
  14625. mg_free(ssl_mutexes);
  14626. ssl_mutexes = NULL;
  14627. #endif /* OPENSSL_API_1_1 */
  14628. }
  14629. }
  14630. #endif /* !NO_SSL */
  14631. #if defined(USE_MBEDTLS)
  14632. /* Check if SSL is required.
  14633. * If so, set up ctx->ssl_ctx pointer. */
  14634. static int
  14635. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14636. {
  14637. if (!phys_ctx) {
  14638. return 0;
  14639. }
  14640. if (!dom_ctx) {
  14641. dom_ctx = &(phys_ctx->dd);
  14642. }
  14643. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14644. /* No SSL port is set. No need to setup SSL. */
  14645. return 1;
  14646. }
  14647. dom_ctx->ssl_ctx = mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14648. if (dom_ctx->ssl_ctx == NULL) {
  14649. fprintf(stderr, "ssl_ctx malloc failed\n");
  14650. return 0;
  14651. }
  14652. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE]) == 0 ? 1 : 0;
  14653. }
  14654. #endif /* USE_MBEDTLS */
  14655. #if !defined(NO_FILESYSTEMS)
  14656. static int
  14657. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14658. {
  14659. if (phys_ctx) {
  14660. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14661. const char *path;
  14662. struct mg_connection fc;
  14663. if (!dom_ctx) {
  14664. dom_ctx = &(phys_ctx->dd);
  14665. }
  14666. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14667. if ((path != NULL)
  14668. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14669. mg_cry_ctx_internal(phys_ctx,
  14670. "Cannot open %s: %s",
  14671. path,
  14672. strerror(ERRNO));
  14673. return 0;
  14674. }
  14675. return 1;
  14676. }
  14677. return 0;
  14678. }
  14679. #endif /* NO_FILESYSTEMS */
  14680. static int
  14681. set_acl_option(struct mg_context *phys_ctx)
  14682. {
  14683. union usa sa;
  14684. memset(&sa, 0, sizeof(sa));
  14685. #if defined(USE_IPV6)
  14686. sa.sin6.sin6_family = AF_INET6;
  14687. #else
  14688. sa.sin.sin_family = AF_INET;
  14689. #endif
  14690. return check_acl(phys_ctx, &sa) != -1;
  14691. }
  14692. static void
  14693. reset_per_request_attributes(struct mg_connection *conn)
  14694. {
  14695. if (!conn) {
  14696. return;
  14697. }
  14698. conn->num_bytes_sent = conn->consumed_content = 0;
  14699. conn->path_info = NULL;
  14700. conn->status_code = -1;
  14701. conn->content_len = -1;
  14702. conn->is_chunked = 0;
  14703. conn->must_close = 0;
  14704. conn->request_len = 0;
  14705. conn->request_state = 0;
  14706. conn->throttle = 0;
  14707. conn->accept_gzip = 0;
  14708. conn->response_info.content_length = conn->request_info.content_length = -1;
  14709. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14710. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14711. conn->response_info.status_text = NULL;
  14712. conn->response_info.status_code = 0;
  14713. conn->request_info.remote_user = NULL;
  14714. conn->request_info.request_method = NULL;
  14715. conn->request_info.request_uri = NULL;
  14716. conn->request_info.local_uri = NULL;
  14717. #if defined(MG_LEGACY_INTERFACE)
  14718. /* Legacy before split into local_uri and request_uri */
  14719. conn->request_info.uri = NULL;
  14720. #endif
  14721. }
  14722. static int
  14723. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14724. {
  14725. if (setsockopt(sock,
  14726. IPPROTO_TCP,
  14727. TCP_NODELAY,
  14728. (SOCK_OPT_TYPE)&nodelay_on,
  14729. sizeof(nodelay_on))
  14730. != 0) {
  14731. /* Error */
  14732. return 1;
  14733. }
  14734. /* OK */
  14735. return 0;
  14736. }
  14737. #if !defined(__ZEPHYR__)
  14738. static void
  14739. close_socket_gracefully(struct mg_connection *conn)
  14740. {
  14741. #if defined(_WIN32)
  14742. char buf[MG_BUF_LEN];
  14743. int n;
  14744. #endif
  14745. struct linger linger;
  14746. int error_code = 0;
  14747. int linger_timeout = -2;
  14748. socklen_t opt_len = sizeof(error_code);
  14749. if (!conn) {
  14750. return;
  14751. }
  14752. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14753. * "Note that enabling a nonzero timeout on a nonblocking socket
  14754. * is not recommended.", so set it to blocking now */
  14755. set_blocking_mode(conn->client.sock);
  14756. /* Send FIN to the client */
  14757. shutdown(conn->client.sock, SHUTDOWN_WR);
  14758. #if defined(_WIN32)
  14759. /* Read and discard pending incoming data. If we do not do that and
  14760. * close
  14761. * the socket, the data in the send buffer may be discarded. This
  14762. * behaviour is seen on Windows, when client keeps sending data
  14763. * when server decides to close the connection; then when client
  14764. * does recv() it gets no data back. */
  14765. do {
  14766. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14767. } while (n > 0);
  14768. #endif
  14769. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14770. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14771. }
  14772. /* Set linger option according to configuration */
  14773. if (linger_timeout >= 0) {
  14774. /* Set linger option to avoid socket hanging out after close. This
  14775. * prevent ephemeral port exhaust problem under high QPS. */
  14776. linger.l_onoff = 1;
  14777. #if defined(_MSC_VER)
  14778. #pragma warning(push)
  14779. #pragma warning(disable : 4244)
  14780. #endif
  14781. #if defined(GCC_DIAGNOSTIC)
  14782. #pragma GCC diagnostic push
  14783. #pragma GCC diagnostic ignored "-Wconversion"
  14784. #endif
  14785. /* Data type of linger structure elements may differ,
  14786. * so we don't know what cast we need here.
  14787. * Disable type conversion warnings. */
  14788. linger.l_linger = (linger_timeout + 999) / 1000;
  14789. #if defined(GCC_DIAGNOSTIC)
  14790. #pragma GCC diagnostic pop
  14791. #endif
  14792. #if defined(_MSC_VER)
  14793. #pragma warning(pop)
  14794. #endif
  14795. } else {
  14796. linger.l_onoff = 0;
  14797. linger.l_linger = 0;
  14798. }
  14799. if (linger_timeout < -1) {
  14800. /* Default: don't configure any linger */
  14801. } else if (getsockopt(conn->client.sock,
  14802. SOL_SOCKET,
  14803. SO_ERROR,
  14804. #if defined(_WIN32) /* WinSock uses different data type here */
  14805. (char *)&error_code,
  14806. #else
  14807. &error_code,
  14808. #endif
  14809. &opt_len)
  14810. != 0) {
  14811. /* Cannot determine if socket is already closed. This should
  14812. * not occur and never did in a test. Log an error message
  14813. * and continue. */
  14814. mg_cry_internal(conn,
  14815. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14816. __func__,
  14817. strerror(ERRNO));
  14818. #if defined(_WIN32)
  14819. } else if (error_code == WSAECONNRESET) {
  14820. #else
  14821. } else if (error_code == ECONNRESET) {
  14822. #endif
  14823. /* Socket already closed by client/peer, close socket without linger
  14824. */
  14825. } else {
  14826. /* Set linger timeout */
  14827. if (setsockopt(conn->client.sock,
  14828. SOL_SOCKET,
  14829. SO_LINGER,
  14830. (char *)&linger,
  14831. sizeof(linger))
  14832. != 0) {
  14833. mg_cry_internal(
  14834. conn,
  14835. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14836. __func__,
  14837. linger.l_onoff,
  14838. linger.l_linger,
  14839. strerror(ERRNO));
  14840. }
  14841. }
  14842. /* Now we know that our FIN is ACK-ed, safe to close */
  14843. closesocket(conn->client.sock);
  14844. conn->client.sock = INVALID_SOCKET;
  14845. }
  14846. #endif
  14847. static void
  14848. close_connection(struct mg_connection *conn)
  14849. {
  14850. #if defined(USE_SERVER_STATS)
  14851. conn->conn_state = 6; /* to close */
  14852. #endif
  14853. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14854. if (conn->lua_websocket_state) {
  14855. lua_websocket_close(conn, conn->lua_websocket_state);
  14856. conn->lua_websocket_state = NULL;
  14857. }
  14858. #endif
  14859. mg_lock_connection(conn);
  14860. /* Set close flag, so keep-alive loops will stop */
  14861. conn->must_close = 1;
  14862. /* call the connection_close callback if assigned */
  14863. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14864. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14865. conn->phys_ctx->callbacks.connection_close(conn);
  14866. }
  14867. }
  14868. /* Reset user data, after close callback is called.
  14869. * Do not reuse it. If the user needs a destructor,
  14870. * it must be done in the connection_close callback. */
  14871. mg_set_user_connection_data(conn, NULL);
  14872. #if defined(USE_SERVER_STATS)
  14873. conn->conn_state = 7; /* closing */
  14874. #endif
  14875. #if defined(USE_MBEDTLS)
  14876. if (conn->ssl != NULL) {
  14877. mbed_ssl_close(conn->ssl);
  14878. mg_free(conn->ssl);
  14879. conn->ssl = NULL;
  14880. }
  14881. #endif
  14882. #if !defined(NO_SSL)
  14883. if (conn->ssl != NULL) {
  14884. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14885. */
  14886. SSL_shutdown(conn->ssl);
  14887. SSL_free(conn->ssl);
  14888. OPENSSL_REMOVE_THREAD_STATE();
  14889. conn->ssl = NULL;
  14890. }
  14891. #endif
  14892. if (conn->client.sock != INVALID_SOCKET) {
  14893. #if defined(__ZEPHYR__)
  14894. closesocket(conn->client.sock);
  14895. #else
  14896. close_socket_gracefully(conn);
  14897. #endif
  14898. conn->client.sock = INVALID_SOCKET;
  14899. }
  14900. mg_unlock_connection(conn);
  14901. #if defined(USE_SERVER_STATS)
  14902. conn->conn_state = 8; /* closed */
  14903. #endif
  14904. }
  14905. void
  14906. mg_close_connection(struct mg_connection *conn)
  14907. {
  14908. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14909. return;
  14910. }
  14911. #if defined(USE_WEBSOCKET)
  14912. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14913. if (conn->in_websocket_handling) {
  14914. /* Set close flag, so the server thread can exit. */
  14915. conn->must_close = 1;
  14916. return;
  14917. }
  14918. }
  14919. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14920. unsigned int i;
  14921. /* client context: loops must end */
  14922. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14923. conn->must_close = 1;
  14924. /* We need to get the client thread out of the select/recv call
  14925. * here. */
  14926. /* Since we use a sleep quantum of some seconds to check for recv
  14927. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14928. /* join worker thread */
  14929. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14930. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14931. }
  14932. }
  14933. #endif /* defined(USE_WEBSOCKET) */
  14934. close_connection(conn);
  14935. #if !defined(NO_SSL)
  14936. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14937. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14938. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14939. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14940. }
  14941. #endif
  14942. #if defined(USE_WEBSOCKET)
  14943. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14944. mg_free(conn->phys_ctx->worker_threadids);
  14945. (void)pthread_mutex_destroy(&conn->mutex);
  14946. mg_free(conn);
  14947. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14948. (void)pthread_mutex_destroy(&conn->mutex);
  14949. mg_free(conn);
  14950. }
  14951. #else
  14952. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14953. (void)pthread_mutex_destroy(&conn->mutex);
  14954. mg_free(conn);
  14955. }
  14956. #endif /* defined(USE_WEBSOCKET) */
  14957. }
  14958. static struct mg_connection *
  14959. mg_connect_client_impl(const struct mg_client_options *client_options,
  14960. int use_ssl,
  14961. char *ebuf,
  14962. size_t ebuf_len)
  14963. {
  14964. struct mg_connection *conn = NULL;
  14965. SOCKET sock;
  14966. union usa sa;
  14967. struct sockaddr *psa;
  14968. socklen_t len;
  14969. unsigned max_req_size =
  14970. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14971. /* Size of structures, aligned to 8 bytes */
  14972. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14973. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14974. conn =
  14975. (struct mg_connection *)mg_calloc(1,
  14976. conn_size + ctx_size + max_req_size);
  14977. if (conn == NULL) {
  14978. mg_snprintf(NULL,
  14979. NULL, /* No truncation check for ebuf */
  14980. ebuf,
  14981. ebuf_len,
  14982. "calloc(): %s",
  14983. strerror(ERRNO));
  14984. return NULL;
  14985. }
  14986. #if defined(GCC_DIAGNOSTIC)
  14987. #pragma GCC diagnostic push
  14988. #pragma GCC diagnostic ignored "-Wcast-align"
  14989. #endif /* defined(GCC_DIAGNOSTIC) */
  14990. /* conn_size is aligned to 8 bytes */
  14991. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14992. #if defined(GCC_DIAGNOSTIC)
  14993. #pragma GCC diagnostic pop
  14994. #endif /* defined(GCC_DIAGNOSTIC) */
  14995. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14996. conn->buf_size = (int)max_req_size;
  14997. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14998. conn->dom_ctx = &(conn->phys_ctx->dd);
  14999. if (!connect_socket(conn->phys_ctx,
  15000. client_options->host,
  15001. client_options->port,
  15002. use_ssl,
  15003. ebuf,
  15004. ebuf_len,
  15005. &sock,
  15006. &sa)) {
  15007. /* ebuf is set by connect_socket,
  15008. * free all memory and return NULL; */
  15009. mg_free(conn);
  15010. return NULL;
  15011. }
  15012. #if !defined(NO_SSL)
  15013. #if defined(OPENSSL_API_1_1)
  15014. if (use_ssl
  15015. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15016. == NULL) {
  15017. mg_snprintf(NULL,
  15018. NULL, /* No truncation check for ebuf */
  15019. ebuf,
  15020. ebuf_len,
  15021. "SSL_CTX_new error: %s",
  15022. ssl_error());
  15023. closesocket(sock);
  15024. mg_free(conn);
  15025. return NULL;
  15026. }
  15027. #else
  15028. if (use_ssl
  15029. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15030. == NULL) {
  15031. mg_snprintf(NULL,
  15032. NULL, /* No truncation check for ebuf */
  15033. ebuf,
  15034. ebuf_len,
  15035. "SSL_CTX_new error: %s",
  15036. ssl_error());
  15037. closesocket(sock);
  15038. mg_free(conn);
  15039. return NULL;
  15040. }
  15041. #endif /* OPENSSL_API_1_1 */
  15042. #endif /* NO_SSL */
  15043. #if defined(USE_IPV6)
  15044. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15045. : sizeof(conn->client.rsa.sin6);
  15046. psa = (sa.sa.sa_family == AF_INET)
  15047. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15048. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15049. #else
  15050. len = sizeof(conn->client.rsa.sin);
  15051. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15052. #endif
  15053. conn->client.sock = sock;
  15054. conn->client.lsa = sa;
  15055. if (getsockname(sock, psa, &len) != 0) {
  15056. mg_cry_internal(conn,
  15057. "%s: getsockname() failed: %s",
  15058. __func__,
  15059. strerror(ERRNO));
  15060. }
  15061. conn->client.is_ssl = use_ssl ? 1 : 0;
  15062. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15063. mg_snprintf(NULL,
  15064. NULL, /* No truncation check for ebuf */
  15065. ebuf,
  15066. ebuf_len,
  15067. "Can not create mutex");
  15068. #if !defined(NO_SSL)
  15069. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15070. #endif
  15071. closesocket(sock);
  15072. mg_free(conn);
  15073. return NULL;
  15074. }
  15075. #if !defined(NO_SSL)
  15076. if (use_ssl) {
  15077. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15078. * SSL_CTX_set_verify call is needed to switch off server
  15079. * certificate checking, which is off by default in OpenSSL and
  15080. * on in yaSSL. */
  15081. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15082. * SSL_VERIFY_PEER, verify_ssl_server); */
  15083. if (client_options->client_cert) {
  15084. if (!ssl_use_pem_file(conn->phys_ctx,
  15085. conn->dom_ctx,
  15086. client_options->client_cert,
  15087. NULL)) {
  15088. mg_snprintf(NULL,
  15089. NULL, /* No truncation check for ebuf */
  15090. ebuf,
  15091. ebuf_len,
  15092. "Can not use SSL client certificate");
  15093. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15094. closesocket(sock);
  15095. mg_free(conn);
  15096. return NULL;
  15097. }
  15098. }
  15099. if (client_options->server_cert) {
  15100. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15101. client_options->server_cert,
  15102. NULL)
  15103. != 1) {
  15104. mg_cry_internal(conn,
  15105. "SSL_CTX_load_verify_locations error: %s ",
  15106. ssl_error());
  15107. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15108. closesocket(sock);
  15109. mg_free(conn);
  15110. return NULL;
  15111. }
  15112. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15113. } else {
  15114. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15115. }
  15116. if (!sslize(conn, SSL_connect, client_options)) {
  15117. mg_snprintf(NULL,
  15118. NULL, /* No truncation check for ebuf */
  15119. ebuf,
  15120. ebuf_len,
  15121. "SSL connection error");
  15122. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15123. closesocket(sock);
  15124. mg_free(conn);
  15125. return NULL;
  15126. }
  15127. }
  15128. #endif
  15129. return conn;
  15130. }
  15131. CIVETWEB_API struct mg_connection *
  15132. mg_connect_client_secure(const struct mg_client_options *client_options,
  15133. char *error_buffer,
  15134. size_t error_buffer_size)
  15135. {
  15136. return mg_connect_client_impl(client_options,
  15137. 1,
  15138. error_buffer,
  15139. error_buffer_size);
  15140. }
  15141. struct mg_connection *
  15142. mg_connect_client(const char *host,
  15143. int port,
  15144. int use_ssl,
  15145. char *error_buffer,
  15146. size_t error_buffer_size)
  15147. {
  15148. struct mg_client_options opts;
  15149. memset(&opts, 0, sizeof(opts));
  15150. opts.host = host;
  15151. opts.port = port;
  15152. return mg_connect_client_impl(&opts,
  15153. use_ssl,
  15154. error_buffer,
  15155. error_buffer_size);
  15156. }
  15157. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15158. struct mg_connection *
  15159. mg_connect_client2(const char *host,
  15160. const char *protocol,
  15161. int port,
  15162. const char *path,
  15163. struct mg_init_data *init,
  15164. struct mg_error_data *error)
  15165. {
  15166. int is_ssl, is_ws;
  15167. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15168. if (error != NULL) {
  15169. error->code = 0;
  15170. if (error->text_buffer_size > 0) {
  15171. *error->text = 0;
  15172. }
  15173. }
  15174. if ((host == NULL) || (protocol == NULL)) {
  15175. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15176. mg_snprintf(NULL,
  15177. NULL, /* No truncation check for error buffers */
  15178. error->text,
  15179. error->text_buffer_size,
  15180. "%s",
  15181. "Invalid parameters");
  15182. }
  15183. return NULL;
  15184. }
  15185. /* check all known protocolls */
  15186. if (!mg_strcasecmp(protocol, "http")) {
  15187. is_ssl = 0;
  15188. is_ws = 0;
  15189. } else if (!mg_strcasecmp(protocol, "https")) {
  15190. is_ssl = 1;
  15191. is_ws = 0;
  15192. #if defined(USE_WEBSOCKET)
  15193. } else if (!mg_strcasecmp(protocol, "ws")) {
  15194. is_ssl = 0;
  15195. is_ws = 1;
  15196. } else if (!mg_strcasecmp(protocol, "wss")) {
  15197. is_ssl = 1;
  15198. is_ws = 1;
  15199. #endif
  15200. } else {
  15201. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15202. mg_snprintf(NULL,
  15203. NULL, /* No truncation check for error buffers */
  15204. error->text,
  15205. error->text_buffer_size,
  15206. "Protocol %s not supported",
  15207. protocol);
  15208. }
  15209. return NULL;
  15210. }
  15211. /* TODO: The current implementation here just calls the old
  15212. * implementations, without using any new options. This is just a first
  15213. * step to test the new interfaces. */
  15214. #if defined(USE_WEBSOCKET)
  15215. if (is_ws) {
  15216. /* TODO: implement all options */
  15217. return mg_connect_websocket_client(
  15218. host,
  15219. port,
  15220. is_ssl,
  15221. ((error != NULL) ? error->text : NULL),
  15222. ((error != NULL) ? error->text_buffer_size : 0),
  15223. (path ? path : ""),
  15224. NULL /* TODO: origin */,
  15225. experimental_websocket_client_data_wrapper,
  15226. experimental_websocket_client_close_wrapper,
  15227. (void *)init->callbacks);
  15228. }
  15229. #endif
  15230. /* TODO: all additional options */
  15231. struct mg_client_options opts;
  15232. memset(&opts, 0, sizeof(opts));
  15233. opts.host = host;
  15234. opts.port = port;
  15235. return mg_connect_client_impl(&opts,
  15236. is_ssl,
  15237. ((error != NULL) ? error->text : NULL),
  15238. ((error != NULL) ? error->text_buffer_size
  15239. : 0));
  15240. }
  15241. #endif
  15242. static const struct {
  15243. const char *proto;
  15244. size_t proto_len;
  15245. unsigned default_port;
  15246. } abs_uri_protocols[] = {{"http://", 7, 80},
  15247. {"https://", 8, 443},
  15248. {"ws://", 5, 80},
  15249. {"wss://", 6, 443},
  15250. {NULL, 0, 0}};
  15251. /* Check if the uri is valid.
  15252. * return 0 for invalid uri,
  15253. * return 1 for *,
  15254. * return 2 for relative uri,
  15255. * return 3 for absolute uri without port,
  15256. * return 4 for absolute uri with port */
  15257. static int
  15258. get_uri_type(const char *uri)
  15259. {
  15260. int i;
  15261. const char *hostend, *portbegin;
  15262. char *portend;
  15263. unsigned long port;
  15264. /* According to the HTTP standard
  15265. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15266. * URI can be an asterisk (*) or should start with slash (relative uri),
  15267. * or it should start with the protocol (absolute uri). */
  15268. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15269. /* asterisk */
  15270. return 1;
  15271. }
  15272. /* Valid URIs according to RFC 3986
  15273. * (https://www.ietf.org/rfc/rfc3986.txt)
  15274. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15275. * and unreserved characters A-Z a-z 0-9 and -._~
  15276. * and % encoded symbols.
  15277. */
  15278. for (i = 0; uri[i] != 0; i++) {
  15279. if (uri[i] < 33) {
  15280. /* control characters and spaces are invalid */
  15281. return 0;
  15282. }
  15283. /* Allow everything else here (See #894) */
  15284. }
  15285. /* A relative uri starts with a / character */
  15286. if (uri[0] == '/') {
  15287. /* relative uri */
  15288. return 2;
  15289. }
  15290. /* It could be an absolute uri: */
  15291. /* This function only checks if the uri is valid, not if it is
  15292. * addressing the current server. So civetweb can also be used
  15293. * as a proxy server. */
  15294. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15295. if (mg_strncasecmp(uri,
  15296. abs_uri_protocols[i].proto,
  15297. abs_uri_protocols[i].proto_len)
  15298. == 0) {
  15299. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15300. if (!hostend) {
  15301. return 0;
  15302. }
  15303. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15304. if (!portbegin) {
  15305. return 3;
  15306. }
  15307. port = strtoul(portbegin + 1, &portend, 10);
  15308. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15309. return 0;
  15310. }
  15311. return 4;
  15312. }
  15313. }
  15314. return 0;
  15315. }
  15316. /* Return NULL or the relative uri at the current server */
  15317. static const char *
  15318. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15319. {
  15320. const char *server_domain;
  15321. size_t server_domain_len;
  15322. size_t request_domain_len = 0;
  15323. unsigned long port = 0;
  15324. int i, auth_domain_check_enabled;
  15325. const char *hostbegin = NULL;
  15326. const char *hostend = NULL;
  15327. const char *portbegin;
  15328. char *portend;
  15329. auth_domain_check_enabled =
  15330. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15331. /* DNS is case insensitive, so use case insensitive string compare here
  15332. */
  15333. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15334. if (mg_strncasecmp(uri,
  15335. abs_uri_protocols[i].proto,
  15336. abs_uri_protocols[i].proto_len)
  15337. == 0) {
  15338. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15339. hostend = strchr(hostbegin, '/');
  15340. if (!hostend) {
  15341. return 0;
  15342. }
  15343. portbegin = strchr(hostbegin, ':');
  15344. if ((!portbegin) || (portbegin > hostend)) {
  15345. port = abs_uri_protocols[i].default_port;
  15346. request_domain_len = (size_t)(hostend - hostbegin);
  15347. } else {
  15348. port = strtoul(portbegin + 1, &portend, 10);
  15349. if ((portend != hostend) || (port <= 0)
  15350. || !is_valid_port(port)) {
  15351. return 0;
  15352. }
  15353. request_domain_len = (size_t)(portbegin - hostbegin);
  15354. }
  15355. /* protocol found, port set */
  15356. break;
  15357. }
  15358. }
  15359. if (!port) {
  15360. /* port remains 0 if the protocol is not found */
  15361. return 0;
  15362. }
  15363. /* Check if the request is directed to a different server. */
  15364. /* First check if the port is the same. */
  15365. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15366. /* Request is directed to a different port */
  15367. return 0;
  15368. }
  15369. /* Finally check if the server corresponds to the authentication
  15370. * domain of the server (the server domain).
  15371. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15372. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15373. * but do not allow substrings (like
  15374. * http://notmydomain.com/path/file.ext
  15375. * or http://mydomain.com.fake/path/file.ext).
  15376. */
  15377. if (auth_domain_check_enabled) {
  15378. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15379. server_domain_len = strlen(server_domain);
  15380. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15381. return 0;
  15382. }
  15383. if ((request_domain_len == server_domain_len)
  15384. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15385. /* Request is directed to this server - full name match. */
  15386. } else {
  15387. if (request_domain_len < (server_domain_len + 2)) {
  15388. /* Request is directed to another server: The server name
  15389. * is longer than the request name.
  15390. * Drop this case here to avoid overflows in the
  15391. * following checks. */
  15392. return 0;
  15393. }
  15394. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15395. /* Request is directed to another server: It could be a
  15396. * substring
  15397. * like notmyserver.com */
  15398. return 0;
  15399. }
  15400. if (0
  15401. != memcmp(server_domain,
  15402. hostbegin + request_domain_len - server_domain_len,
  15403. server_domain_len)) {
  15404. /* Request is directed to another server:
  15405. * The server name is different. */
  15406. return 0;
  15407. }
  15408. }
  15409. }
  15410. return hostend;
  15411. }
  15412. static int
  15413. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15414. {
  15415. if (ebuf_len > 0) {
  15416. ebuf[0] = '\0';
  15417. }
  15418. *err = 0;
  15419. reset_per_request_attributes(conn);
  15420. if (!conn) {
  15421. mg_snprintf(conn,
  15422. NULL, /* No truncation check for ebuf */
  15423. ebuf,
  15424. ebuf_len,
  15425. "%s",
  15426. "Internal error");
  15427. *err = 500;
  15428. return 0;
  15429. }
  15430. /* Set the time the request was received. This value should be used for
  15431. * timeouts. */
  15432. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15433. conn->request_len =
  15434. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15435. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15436. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15437. mg_snprintf(conn,
  15438. NULL, /* No truncation check for ebuf */
  15439. ebuf,
  15440. ebuf_len,
  15441. "%s",
  15442. "Invalid message size");
  15443. *err = 500;
  15444. return 0;
  15445. }
  15446. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15447. mg_snprintf(conn,
  15448. NULL, /* No truncation check for ebuf */
  15449. ebuf,
  15450. ebuf_len,
  15451. "%s",
  15452. "Message too large");
  15453. *err = 413;
  15454. return 0;
  15455. }
  15456. if (conn->request_len <= 0) {
  15457. if (conn->data_len > 0) {
  15458. mg_snprintf(conn,
  15459. NULL, /* No truncation check for ebuf */
  15460. ebuf,
  15461. ebuf_len,
  15462. "%s",
  15463. "Malformed message");
  15464. *err = 400;
  15465. } else {
  15466. /* Server did not recv anything -> just close the connection */
  15467. conn->must_close = 1;
  15468. mg_snprintf(conn,
  15469. NULL, /* No truncation check for ebuf */
  15470. ebuf,
  15471. ebuf_len,
  15472. "%s",
  15473. "No data received");
  15474. *err = 0;
  15475. }
  15476. return 0;
  15477. }
  15478. return 1;
  15479. }
  15480. static int
  15481. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15482. {
  15483. const char *cl;
  15484. conn->connection_type =
  15485. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15486. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15487. return 0;
  15488. }
  15489. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15490. <= 0) {
  15491. mg_snprintf(conn,
  15492. NULL, /* No truncation check for ebuf */
  15493. ebuf,
  15494. ebuf_len,
  15495. "%s",
  15496. "Bad request");
  15497. *err = 400;
  15498. return 0;
  15499. }
  15500. /* Message is a valid request */
  15501. if (!switch_domain_context(conn)) {
  15502. mg_snprintf(conn,
  15503. NULL, /* No truncation check for ebuf */
  15504. ebuf,
  15505. ebuf_len,
  15506. "%s",
  15507. "Bad request: Host mismatch");
  15508. *err = 400;
  15509. return 0;
  15510. }
  15511. if (((cl = get_header(conn->request_info.http_headers,
  15512. conn->request_info.num_headers,
  15513. "Transfer-Encoding"))
  15514. != NULL)
  15515. && mg_strcasecmp(cl, "identity")) {
  15516. if (mg_strcasecmp(cl, "chunked")) {
  15517. mg_snprintf(conn,
  15518. NULL, /* No truncation check for ebuf */
  15519. ebuf,
  15520. ebuf_len,
  15521. "%s",
  15522. "Bad request");
  15523. *err = 400;
  15524. return 0;
  15525. }
  15526. conn->is_chunked = 1;
  15527. conn->content_len = 0; /* not yet read */
  15528. } else if ((cl = get_header(conn->request_info.http_headers,
  15529. conn->request_info.num_headers,
  15530. "Content-Length"))
  15531. != NULL) {
  15532. /* Request has content length set */
  15533. char *endptr = NULL;
  15534. conn->content_len = strtoll(cl, &endptr, 10);
  15535. if ((endptr == cl) || (conn->content_len < 0)) {
  15536. mg_snprintf(conn,
  15537. NULL, /* No truncation check for ebuf */
  15538. ebuf,
  15539. ebuf_len,
  15540. "%s",
  15541. "Bad request");
  15542. *err = 411;
  15543. return 0;
  15544. }
  15545. /* Publish the content length back to the request info. */
  15546. conn->request_info.content_length = conn->content_len;
  15547. } else {
  15548. /* There is no exception, see RFC7230. */
  15549. conn->content_len = 0;
  15550. }
  15551. return 1;
  15552. }
  15553. /* conn is assumed to be valid in this internal function */
  15554. static int
  15555. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15556. {
  15557. const char *cl;
  15558. conn->connection_type =
  15559. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15560. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15561. return 0;
  15562. }
  15563. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15564. <= 0) {
  15565. mg_snprintf(conn,
  15566. NULL, /* No truncation check for ebuf */
  15567. ebuf,
  15568. ebuf_len,
  15569. "%s",
  15570. "Bad response");
  15571. *err = 400;
  15572. return 0;
  15573. }
  15574. /* Message is a valid response */
  15575. if (((cl = get_header(conn->response_info.http_headers,
  15576. conn->response_info.num_headers,
  15577. "Transfer-Encoding"))
  15578. != NULL)
  15579. && mg_strcasecmp(cl, "identity")) {
  15580. if (mg_strcasecmp(cl, "chunked")) {
  15581. mg_snprintf(conn,
  15582. NULL, /* No truncation check for ebuf */
  15583. ebuf,
  15584. ebuf_len,
  15585. "%s",
  15586. "Bad request");
  15587. *err = 400;
  15588. return 0;
  15589. }
  15590. conn->is_chunked = 1;
  15591. conn->content_len = 0; /* not yet read */
  15592. } else if ((cl = get_header(conn->response_info.http_headers,
  15593. conn->response_info.num_headers,
  15594. "Content-Length"))
  15595. != NULL) {
  15596. char *endptr = NULL;
  15597. conn->content_len = strtoll(cl, &endptr, 10);
  15598. if ((endptr == cl) || (conn->content_len < 0)) {
  15599. mg_snprintf(conn,
  15600. NULL, /* No truncation check for ebuf */
  15601. ebuf,
  15602. ebuf_len,
  15603. "%s",
  15604. "Bad request");
  15605. *err = 411;
  15606. return 0;
  15607. }
  15608. /* Publish the content length back to the response info. */
  15609. conn->response_info.content_length = conn->content_len;
  15610. /* TODO: check if it is still used in response_info */
  15611. conn->request_info.content_length = conn->content_len;
  15612. /* TODO: we should also consider HEAD method */
  15613. if (conn->response_info.status_code == 304) {
  15614. conn->content_len = 0;
  15615. }
  15616. } else {
  15617. /* TODO: we should also consider HEAD method */
  15618. if (((conn->response_info.status_code >= 100)
  15619. && (conn->response_info.status_code <= 199))
  15620. || (conn->response_info.status_code == 204)
  15621. || (conn->response_info.status_code == 304)) {
  15622. conn->content_len = 0;
  15623. } else {
  15624. conn->content_len = -1; /* unknown content length */
  15625. }
  15626. }
  15627. return 1;
  15628. }
  15629. int
  15630. mg_get_response(struct mg_connection *conn,
  15631. char *ebuf,
  15632. size_t ebuf_len,
  15633. int timeout)
  15634. {
  15635. int err, ret;
  15636. char txt[32]; /* will not overflow */
  15637. char *save_timeout;
  15638. char *new_timeout;
  15639. if (ebuf_len > 0) {
  15640. ebuf[0] = '\0';
  15641. }
  15642. if (!conn) {
  15643. mg_snprintf(conn,
  15644. NULL, /* No truncation check for ebuf */
  15645. ebuf,
  15646. ebuf_len,
  15647. "%s",
  15648. "Parameter error");
  15649. return -1;
  15650. }
  15651. /* Reset the previous responses */
  15652. conn->data_len = 0;
  15653. /* Implementation of API function for HTTP clients */
  15654. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15655. if (timeout >= 0) {
  15656. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15657. new_timeout = txt;
  15658. } else {
  15659. new_timeout = NULL;
  15660. }
  15661. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15662. ret = get_response(conn, ebuf, ebuf_len, &err);
  15663. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15664. #if defined(MG_LEGACY_INTERFACE)
  15665. /* TODO: 1) uri is deprecated;
  15666. * 2) here, ri.uri is the http response code */
  15667. conn->request_info.uri = conn->request_info.request_uri;
  15668. #endif
  15669. conn->request_info.local_uri = conn->request_info.request_uri;
  15670. /* TODO (mid): Define proper return values - maybe return length?
  15671. * For the first test use <0 for error and >0 for OK */
  15672. return (ret == 0) ? -1 : +1;
  15673. }
  15674. struct mg_connection *
  15675. mg_download(const char *host,
  15676. int port,
  15677. int use_ssl,
  15678. char *ebuf,
  15679. size_t ebuf_len,
  15680. const char *fmt,
  15681. ...)
  15682. {
  15683. struct mg_connection *conn;
  15684. va_list ap;
  15685. int i;
  15686. int reqerr;
  15687. if (ebuf_len > 0) {
  15688. ebuf[0] = '\0';
  15689. }
  15690. va_start(ap, fmt);
  15691. /* open a connection */
  15692. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15693. if (conn != NULL) {
  15694. i = mg_vprintf(conn, fmt, ap);
  15695. if (i <= 0) {
  15696. mg_snprintf(conn,
  15697. NULL, /* No truncation check for ebuf */
  15698. ebuf,
  15699. ebuf_len,
  15700. "%s",
  15701. "Error sending request");
  15702. } else {
  15703. /* make sure the buffer is clear */
  15704. conn->data_len = 0;
  15705. get_response(conn, ebuf, ebuf_len, &reqerr);
  15706. #if defined(MG_LEGACY_INTERFACE)
  15707. /* TODO: 1) uri is deprecated;
  15708. * 2) here, ri.uri is the http response code */
  15709. conn->request_info.uri = conn->request_info.request_uri;
  15710. #endif
  15711. conn->request_info.local_uri = conn->request_info.request_uri;
  15712. }
  15713. }
  15714. /* if an error occurred, close the connection */
  15715. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15716. mg_close_connection(conn);
  15717. conn = NULL;
  15718. }
  15719. va_end(ap);
  15720. return conn;
  15721. }
  15722. struct websocket_client_thread_data {
  15723. struct mg_connection *conn;
  15724. mg_websocket_data_handler data_handler;
  15725. mg_websocket_close_handler close_handler;
  15726. void *callback_data;
  15727. };
  15728. #if defined(USE_WEBSOCKET)
  15729. #if defined(_WIN32)
  15730. static unsigned __stdcall websocket_client_thread(void *data)
  15731. #else
  15732. static void *
  15733. websocket_client_thread(void *data)
  15734. #endif
  15735. {
  15736. struct websocket_client_thread_data *cdata =
  15737. (struct websocket_client_thread_data *)data;
  15738. void *user_thread_ptr = NULL;
  15739. #if !defined(_WIN32)
  15740. struct sigaction sa;
  15741. /* Ignore SIGPIPE */
  15742. memset(&sa, 0, sizeof(sa));
  15743. sa.sa_handler = SIG_IGN;
  15744. sigaction(SIGPIPE, &sa, NULL);
  15745. #endif
  15746. mg_set_thread_name("ws-clnt");
  15747. if (cdata->conn->phys_ctx) {
  15748. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15749. /* 3 indicates a websocket client thread */
  15750. /* TODO: check if conn->phys_ctx can be set */
  15751. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15752. cdata->conn->phys_ctx, 3);
  15753. }
  15754. }
  15755. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15756. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15757. if (cdata->close_handler != NULL) {
  15758. cdata->close_handler(cdata->conn, cdata->callback_data);
  15759. }
  15760. /* The websocket_client context has only this thread. If it runs out,
  15761. set the stop_flag to 2 (= "stopped"). */
  15762. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15763. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15764. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15765. 3,
  15766. user_thread_ptr);
  15767. }
  15768. mg_free((void *)cdata);
  15769. #if defined(_WIN32)
  15770. return 0;
  15771. #else
  15772. return NULL;
  15773. #endif
  15774. }
  15775. #endif
  15776. static struct mg_connection *
  15777. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15778. int use_ssl,
  15779. char *error_buffer,
  15780. size_t error_buffer_size,
  15781. const char *path,
  15782. const char *origin,
  15783. mg_websocket_data_handler data_func,
  15784. mg_websocket_close_handler close_func,
  15785. void *user_data)
  15786. {
  15787. struct mg_connection *conn = NULL;
  15788. #if defined(USE_WEBSOCKET)
  15789. struct websocket_client_thread_data *thread_data;
  15790. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15791. const char *handshake_req;
  15792. const char *host = client_options->host;
  15793. int i;
  15794. if (origin != NULL) {
  15795. handshake_req = "GET %s HTTP/1.1\r\n"
  15796. "Host: %s\r\n"
  15797. "Upgrade: websocket\r\n"
  15798. "Connection: Upgrade\r\n"
  15799. "Sec-WebSocket-Key: %s\r\n"
  15800. "Sec-WebSocket-Version: 13\r\n"
  15801. "Origin: %s\r\n"
  15802. "\r\n";
  15803. } else {
  15804. handshake_req = "GET %s HTTP/1.1\r\n"
  15805. "Host: %s\r\n"
  15806. "Upgrade: websocket\r\n"
  15807. "Connection: Upgrade\r\n"
  15808. "Sec-WebSocket-Key: %s\r\n"
  15809. "Sec-WebSocket-Version: 13\r\n"
  15810. "\r\n";
  15811. }
  15812. #if defined(__clang__)
  15813. #pragma clang diagnostic push
  15814. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15815. #endif
  15816. /* Establish the client connection and request upgrade */
  15817. conn = mg_connect_client_impl(client_options,
  15818. use_ssl,
  15819. error_buffer,
  15820. error_buffer_size);
  15821. /* Connection object will be null if something goes wrong */
  15822. if (conn == NULL) {
  15823. /* error_buffer should be already filled ... */
  15824. if (!error_buffer[0]) {
  15825. /* ... if not add an error message */
  15826. mg_snprintf(conn,
  15827. NULL, /* No truncation check for ebuf */
  15828. error_buffer,
  15829. error_buffer_size,
  15830. "Unexpected error");
  15831. }
  15832. return NULL;
  15833. }
  15834. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15835. if (i <= 0) {
  15836. mg_snprintf(conn,
  15837. NULL, /* No truncation check for ebuf */
  15838. error_buffer,
  15839. error_buffer_size,
  15840. "%s",
  15841. "Error sending request");
  15842. mg_close_connection(conn);
  15843. return NULL;
  15844. }
  15845. conn->data_len = 0;
  15846. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15847. mg_close_connection(conn);
  15848. return NULL;
  15849. }
  15850. conn->request_info.local_uri = conn->request_info.request_uri;
  15851. #if defined(__clang__)
  15852. #pragma clang diagnostic pop
  15853. #endif
  15854. if (conn->response_info.status_code != 101) {
  15855. /* We sent an "upgrade" request. For a correct websocket
  15856. * protocol handshake, we expect a "101 Continue" response.
  15857. * Otherwise it is a protocol violation. Maybe the HTTP
  15858. * Server does not know websockets. */
  15859. if (!*error_buffer) {
  15860. /* set an error, if not yet set */
  15861. mg_snprintf(conn,
  15862. NULL, /* No truncation check for ebuf */
  15863. error_buffer,
  15864. error_buffer_size,
  15865. "Unexpected server reply");
  15866. }
  15867. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15868. mg_close_connection(conn);
  15869. return NULL;
  15870. }
  15871. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15872. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15873. if (!thread_data) {
  15874. DEBUG_TRACE("%s\r\n", "Out of memory");
  15875. mg_close_connection(conn);
  15876. return NULL;
  15877. }
  15878. thread_data->conn = conn;
  15879. thread_data->data_handler = data_func;
  15880. thread_data->close_handler = close_func;
  15881. thread_data->callback_data = user_data;
  15882. conn->phys_ctx->worker_threadids =
  15883. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15884. if (!conn->phys_ctx->worker_threadids) {
  15885. DEBUG_TRACE("%s\r\n", "Out of memory");
  15886. mg_free(thread_data);
  15887. mg_close_connection(conn);
  15888. return NULL;
  15889. }
  15890. /* Now upgrade to ws/wss client context */
  15891. conn->phys_ctx->user_data = user_data;
  15892. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15893. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15894. /* Start a thread to read the websocket client connection
  15895. * This thread will automatically stop when mg_disconnect is
  15896. * called on the client connection */
  15897. if (mg_start_thread_with_id(websocket_client_thread,
  15898. thread_data,
  15899. conn->phys_ctx->worker_threadids)
  15900. != 0) {
  15901. conn->phys_ctx->cfg_worker_threads = 0;
  15902. mg_free(thread_data);
  15903. mg_close_connection(conn);
  15904. conn = NULL;
  15905. DEBUG_TRACE("%s",
  15906. "Websocket client connect thread could not be started\r\n");
  15907. }
  15908. #else
  15909. /* Appease "unused parameter" warnings */
  15910. (void)client_options;
  15911. (void)use_ssl;
  15912. (void)error_buffer;
  15913. (void)error_buffer_size;
  15914. (void)path;
  15915. (void)origin;
  15916. (void)user_data;
  15917. (void)data_func;
  15918. (void)close_func;
  15919. #endif
  15920. return conn;
  15921. }
  15922. struct mg_connection *
  15923. mg_connect_websocket_client(const char *host,
  15924. int port,
  15925. int use_ssl,
  15926. char *error_buffer,
  15927. size_t error_buffer_size,
  15928. const char *path,
  15929. const char *origin,
  15930. mg_websocket_data_handler data_func,
  15931. mg_websocket_close_handler close_func,
  15932. void *user_data)
  15933. {
  15934. struct mg_client_options client_options;
  15935. memset(&client_options, 0, sizeof(client_options));
  15936. client_options.host = host;
  15937. client_options.port = port;
  15938. return mg_connect_websocket_client_impl(&client_options,
  15939. use_ssl,
  15940. error_buffer,
  15941. error_buffer_size,
  15942. path,
  15943. origin,
  15944. data_func,
  15945. close_func,
  15946. user_data);
  15947. }
  15948. struct mg_connection *
  15949. mg_connect_websocket_client_secure(
  15950. const struct mg_client_options *client_options,
  15951. char *error_buffer,
  15952. size_t error_buffer_size,
  15953. const char *path,
  15954. const char *origin,
  15955. mg_websocket_data_handler data_func,
  15956. mg_websocket_close_handler close_func,
  15957. void *user_data)
  15958. {
  15959. if (!client_options) {
  15960. return NULL;
  15961. }
  15962. return mg_connect_websocket_client_impl(client_options,
  15963. 1,
  15964. error_buffer,
  15965. error_buffer_size,
  15966. path,
  15967. origin,
  15968. data_func,
  15969. close_func,
  15970. user_data);
  15971. }
  15972. /* Prepare connection data structure */
  15973. static void
  15974. init_connection(struct mg_connection *conn)
  15975. {
  15976. /* Is keep alive allowed by the server */
  15977. int keep_alive_enabled =
  15978. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15979. if (!keep_alive_enabled) {
  15980. conn->must_close = 1;
  15981. }
  15982. /* Important: on new connection, reset the receiving buffer. Credit
  15983. * goes to crule42. */
  15984. conn->data_len = 0;
  15985. conn->handled_requests = 0;
  15986. conn->connection_type = CONNECTION_TYPE_INVALID;
  15987. mg_set_user_connection_data(conn, NULL);
  15988. #if defined(USE_SERVER_STATS)
  15989. conn->conn_state = 2; /* init */
  15990. #endif
  15991. /* call the init_connection callback if assigned */
  15992. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15993. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15994. void *conn_data = NULL;
  15995. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15996. mg_set_user_connection_data(conn, conn_data);
  15997. }
  15998. }
  15999. }
  16000. /* Process a connection - may handle multiple requests
  16001. * using the same connection.
  16002. * Must be called with a valid connection (conn and
  16003. * conn->phys_ctx must be valid).
  16004. */
  16005. static void
  16006. process_new_connection(struct mg_connection *conn)
  16007. {
  16008. struct mg_request_info *ri = &conn->request_info;
  16009. int keep_alive, discard_len;
  16010. char ebuf[100];
  16011. const char *hostend;
  16012. int reqerr, uri_type;
  16013. #if defined(USE_SERVER_STATS)
  16014. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16015. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16016. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16017. #endif
  16018. DEBUG_TRACE("Start processing connection from %s",
  16019. conn->request_info.remote_addr);
  16020. /* Loop over multiple requests sent using the same connection
  16021. * (while "keep alive"). */
  16022. do {
  16023. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16024. conn->handled_requests + 1);
  16025. #if defined(USE_SERVER_STATS)
  16026. conn->conn_state = 3; /* ready */
  16027. #endif
  16028. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16029. /* The request sent by the client could not be understood by
  16030. * the server, or it was incomplete or a timeout. Send an
  16031. * error message and close the connection. */
  16032. if (reqerr > 0) {
  16033. DEBUG_ASSERT(ebuf[0] != '\0');
  16034. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16035. }
  16036. } else if (strcmp(ri->http_version, "1.0")
  16037. && strcmp(ri->http_version, "1.1")) {
  16038. /* HTTP/2 is not allowed here */
  16039. mg_snprintf(conn,
  16040. NULL, /* No truncation check for ebuf */
  16041. ebuf,
  16042. sizeof(ebuf),
  16043. "Bad HTTP version: [%s]",
  16044. ri->http_version);
  16045. mg_send_http_error(conn, 505, "%s", ebuf);
  16046. }
  16047. if (ebuf[0] == '\0') {
  16048. uri_type = get_uri_type(conn->request_info.request_uri);
  16049. switch (uri_type) {
  16050. case 1:
  16051. /* Asterisk */
  16052. conn->request_info.local_uri = 0;
  16053. /* TODO: Deal with '*'. */
  16054. break;
  16055. case 2:
  16056. /* relative uri */
  16057. conn->request_info.local_uri = conn->request_info.request_uri;
  16058. break;
  16059. case 3:
  16060. case 4:
  16061. /* absolute uri (with/without port) */
  16062. hostend = get_rel_url_at_current_server(
  16063. conn->request_info.request_uri, conn);
  16064. if (hostend) {
  16065. conn->request_info.local_uri = hostend;
  16066. } else {
  16067. conn->request_info.local_uri = NULL;
  16068. }
  16069. break;
  16070. default:
  16071. mg_snprintf(conn,
  16072. NULL, /* No truncation check for ebuf */
  16073. ebuf,
  16074. sizeof(ebuf),
  16075. "Invalid URI");
  16076. mg_send_http_error(conn, 400, "%s", ebuf);
  16077. conn->request_info.local_uri = NULL;
  16078. break;
  16079. }
  16080. #if defined(MG_LEGACY_INTERFACE)
  16081. /* Legacy before split into local_uri and request_uri */
  16082. conn->request_info.uri = conn->request_info.local_uri;
  16083. #endif
  16084. }
  16085. if (ebuf[0] != '\0') {
  16086. conn->protocol_type = -1;
  16087. } else {
  16088. /* HTTP/1 allows protocol upgrade */
  16089. conn->protocol_type = should_switch_to_protocol(conn);
  16090. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16091. /* This will occur, if a HTTP/1.1 request should be upgraded
  16092. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16093. * Since most (all?) major browsers only support HTTP/2 using
  16094. * ALPN, this is hard to test and very low priority.
  16095. * Deactivate it (at least for now).
  16096. */
  16097. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16098. }
  16099. }
  16100. DEBUG_TRACE("http: %s, error: %s",
  16101. (ri->http_version ? ri->http_version : "none"),
  16102. (ebuf[0] ? ebuf : "none"));
  16103. if (ebuf[0] == '\0') {
  16104. if (conn->request_info.local_uri) {
  16105. /* handle request to local server */
  16106. #if defined(USE_SERVER_STATS)
  16107. conn->conn_state = 4; /* processing */
  16108. #endif
  16109. handle_request(conn);
  16110. #if defined(USE_SERVER_STATS)
  16111. conn->conn_state = 5; /* processed */
  16112. mg_atomic_add64(&(conn->phys_ctx->total_data_read),
  16113. conn->consumed_content);
  16114. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  16115. conn->num_bytes_sent);
  16116. #endif
  16117. DEBUG_TRACE("%s", "handle_request done");
  16118. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16119. conn->phys_ctx->callbacks.end_request(conn,
  16120. conn->status_code);
  16121. DEBUG_TRACE("%s", "end_request callback done");
  16122. }
  16123. log_access(conn);
  16124. } else {
  16125. /* TODO: handle non-local request (PROXY) */
  16126. conn->must_close = 1;
  16127. }
  16128. } else {
  16129. conn->must_close = 1;
  16130. }
  16131. /* Response complete. Free header buffer */
  16132. free_buffered_response_header_list(conn);
  16133. if (ri->remote_user != NULL) {
  16134. mg_free((void *)ri->remote_user);
  16135. /* Important! When having connections with and without auth
  16136. * would cause double free and then crash */
  16137. ri->remote_user = NULL;
  16138. }
  16139. /* NOTE(lsm): order is important here. should_keep_alive() call
  16140. * is using parsed request, which will be invalid after
  16141. * memmove's below.
  16142. * Therefore, memorize should_keep_alive() result now for later
  16143. * use in loop exit condition. */
  16144. /* Enable it only if this request is completely discardable. */
  16145. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16146. && should_keep_alive(conn) && (conn->content_len >= 0)
  16147. && (conn->request_len > 0)
  16148. && ((conn->is_chunked == 4)
  16149. || (!conn->is_chunked
  16150. && ((conn->consumed_content == conn->content_len)
  16151. || ((conn->request_len + conn->content_len)
  16152. <= conn->data_len))))
  16153. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16154. if (keep_alive) {
  16155. /* Discard all buffered data for this request */
  16156. discard_len =
  16157. ((conn->request_len + conn->content_len) < conn->data_len)
  16158. ? (int)(conn->request_len + conn->content_len)
  16159. : conn->data_len;
  16160. conn->data_len -= discard_len;
  16161. if (conn->data_len > 0) {
  16162. DEBUG_TRACE("discard_len = %d", discard_len);
  16163. memmove(conn->buf,
  16164. conn->buf + discard_len,
  16165. (size_t)conn->data_len);
  16166. }
  16167. }
  16168. DEBUG_ASSERT(conn->data_len >= 0);
  16169. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16170. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16171. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16172. (long int)conn->data_len,
  16173. (long int)conn->buf_size);
  16174. break;
  16175. }
  16176. conn->handled_requests++;
  16177. } while (keep_alive);
  16178. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16179. conn->request_info.remote_addr,
  16180. difftime(time(NULL), conn->conn_birth_time));
  16181. close_connection(conn);
  16182. #if defined(USE_SERVER_STATS)
  16183. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16184. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16185. #endif
  16186. }
  16187. #if defined(ALTERNATIVE_QUEUE)
  16188. static void
  16189. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16190. {
  16191. unsigned int i;
  16192. while (!ctx->stop_flag) {
  16193. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16194. /* find a free worker slot and signal it */
  16195. if (ctx->client_socks[i].in_use == 2) {
  16196. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16197. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16198. ctx->client_socks[i] = *sp;
  16199. ctx->client_socks[i].in_use = 1;
  16200. /* socket has been moved to the consumer */
  16201. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16202. (void)event_signal(ctx->client_wait_events[i]);
  16203. return;
  16204. }
  16205. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16206. }
  16207. }
  16208. /* queue is full */
  16209. mg_sleep(1);
  16210. }
  16211. /* must consume */
  16212. set_blocking_mode(sp->sock);
  16213. closesocket(sp->sock);
  16214. }
  16215. static int
  16216. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16217. {
  16218. DEBUG_TRACE("%s", "going idle");
  16219. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16220. ctx->client_socks[thread_index].in_use = 2;
  16221. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16222. event_wait(ctx->client_wait_events[thread_index]);
  16223. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16224. *sp = ctx->client_socks[thread_index];
  16225. if (ctx->stop_flag) {
  16226. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16227. if (sp->in_use == 1) {
  16228. /* must consume */
  16229. set_blocking_mode(sp->sock);
  16230. closesocket(sp->sock);
  16231. }
  16232. return 0;
  16233. }
  16234. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16235. if (sp->in_use == 1) {
  16236. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16237. return 1;
  16238. }
  16239. /* must not reach here */
  16240. DEBUG_ASSERT(0);
  16241. return 0;
  16242. }
  16243. #else /* ALTERNATIVE_QUEUE */
  16244. /* Worker threads take accepted socket from the queue */
  16245. static int
  16246. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16247. {
  16248. (void)thread_index;
  16249. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16250. DEBUG_TRACE("%s", "going idle");
  16251. /* If the queue is empty, wait. We're idle at this point. */
  16252. while ((ctx->sq_head == ctx->sq_tail)
  16253. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16254. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16255. }
  16256. /* If we're stopping, sq_head may be equal to sq_tail. */
  16257. if (ctx->sq_head > ctx->sq_tail) {
  16258. /* Copy socket from the queue and increment tail */
  16259. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16260. ctx->sq_tail++;
  16261. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16262. /* Wrap pointers if needed */
  16263. while (ctx->sq_tail > ctx->sq_size) {
  16264. ctx->sq_tail -= ctx->sq_size;
  16265. ctx->sq_head -= ctx->sq_size;
  16266. }
  16267. }
  16268. (void)pthread_cond_signal(&ctx->sq_empty);
  16269. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16270. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16271. }
  16272. /* Master thread adds accepted socket to a queue */
  16273. static void
  16274. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16275. {
  16276. int queue_filled;
  16277. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16278. queue_filled = ctx->sq_head - ctx->sq_tail;
  16279. /* If the queue is full, wait */
  16280. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16281. && (queue_filled >= ctx->sq_size)) {
  16282. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16283. #if defined(USE_SERVER_STATS)
  16284. if (queue_filled > ctx->sq_max_fill) {
  16285. ctx->sq_max_fill = queue_filled;
  16286. }
  16287. #endif
  16288. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16289. ctx->sq_blocked = 0; /* Not blocked now */
  16290. queue_filled = ctx->sq_head - ctx->sq_tail;
  16291. }
  16292. if (queue_filled < ctx->sq_size) {
  16293. /* Copy socket to the queue and increment head */
  16294. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16295. ctx->sq_head++;
  16296. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16297. }
  16298. queue_filled = ctx->sq_head - ctx->sq_tail;
  16299. #if defined(USE_SERVER_STATS)
  16300. if (queue_filled > ctx->sq_max_fill) {
  16301. ctx->sq_max_fill = queue_filled;
  16302. }
  16303. #endif
  16304. (void)pthread_cond_signal(&ctx->sq_full);
  16305. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16306. }
  16307. #endif /* ALTERNATIVE_QUEUE */
  16308. static void
  16309. worker_thread_run(struct mg_connection *conn)
  16310. {
  16311. struct mg_context *ctx = conn->phys_ctx;
  16312. int thread_index;
  16313. struct mg_workerTLS tls;
  16314. mg_set_thread_name("worker");
  16315. tls.is_master = 0;
  16316. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16317. #if defined(_WIN32)
  16318. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16319. #endif
  16320. /* Initialize thread local storage before calling any callback */
  16321. pthread_setspecific(sTlsKey, &tls);
  16322. /* Check if there is a user callback */
  16323. if (ctx->callbacks.init_thread) {
  16324. /* call init_thread for a worker thread (type 1), and store the
  16325. * return value */
  16326. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16327. } else {
  16328. /* No callback: set user pointer to NULL */
  16329. tls.user_ptr = NULL;
  16330. }
  16331. /* Connection structure has been pre-allocated */
  16332. thread_index = (int)(conn - ctx->worker_connections);
  16333. if ((thread_index < 0)
  16334. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16335. mg_cry_ctx_internal(ctx,
  16336. "Internal error: Invalid worker index %i",
  16337. thread_index);
  16338. return;
  16339. }
  16340. /* Request buffers are not pre-allocated. They are private to the
  16341. * request and do not contain any state information that might be
  16342. * of interest to anyone observing a server status. */
  16343. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16344. if (conn->buf == NULL) {
  16345. mg_cry_ctx_internal(
  16346. ctx,
  16347. "Out of memory: Cannot allocate buffer for worker %i",
  16348. thread_index);
  16349. return;
  16350. }
  16351. conn->buf_size = (int)ctx->max_request_size;
  16352. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16353. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16354. conn->request_info.user_data = ctx->user_data;
  16355. /* Allocate a mutex for this connection to allow communication both
  16356. * within the request handler and from elsewhere in the application
  16357. */
  16358. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16359. mg_free(conn->buf);
  16360. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16361. return;
  16362. }
  16363. #if defined(USE_SERVER_STATS)
  16364. conn->conn_state = 1; /* not consumed */
  16365. #endif
  16366. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16367. * signal sq_empty condvar to wake up the master waiting in
  16368. * produce_socket() */
  16369. while (consume_socket(ctx, &conn->client, thread_index)) {
  16370. /* New connections must start with new protocol negotiation */
  16371. tls.alpn_proto = NULL;
  16372. #if defined(USE_SERVER_STATS)
  16373. conn->conn_close_time = 0;
  16374. #endif
  16375. conn->conn_birth_time = time(NULL);
  16376. /* Fill in IP, port info early so even if SSL setup below fails,
  16377. * error handler would have the corresponding info.
  16378. * Thanks to Johannes Winkelmann for the patch.
  16379. */
  16380. conn->request_info.remote_port =
  16381. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16382. sockaddr_to_string(conn->request_info.remote_addr,
  16383. sizeof(conn->request_info.remote_addr),
  16384. &conn->client.rsa);
  16385. DEBUG_TRACE("Start processing connection from %s",
  16386. conn->request_info.remote_addr);
  16387. conn->request_info.is_ssl = conn->client.is_ssl;
  16388. if (conn->client.is_ssl) {
  16389. #if defined(USE_MBEDTLS)
  16390. /* HTTPS connection */
  16391. if (mbed_ssl_accept(&conn->ssl,
  16392. conn->dom_ctx->ssl_ctx, &conn->client.sock) == 0) {
  16393. /* conn->dom_ctx is set in get_request */
  16394. /* process HTTPS connection */
  16395. process_new_connection(conn);
  16396. } else {
  16397. /* make sure the connection is cleaned up on SSL failure */
  16398. close_connection(conn);
  16399. }
  16400. #endif
  16401. #if !defined(NO_SSL)
  16402. /* HTTPS connection */
  16403. if (sslize(conn, SSL_accept, NULL)) {
  16404. /* conn->dom_ctx is set in get_request */
  16405. /* Get SSL client certificate information (if set) */
  16406. struct mg_client_cert client_cert;
  16407. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16408. conn->request_info.client_cert = &client_cert;
  16409. }
  16410. /* process HTTPS connection */
  16411. #if defined(USE_HTTP2)
  16412. if ((tls.alpn_proto != NULL)
  16413. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16414. /* process HTTPS/2 connection */
  16415. init_connection(conn);
  16416. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16417. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16418. conn->content_len =
  16419. -1; /* content length is not predefined */
  16420. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16421. process_new_http2_connection(conn);
  16422. } else
  16423. #endif
  16424. {
  16425. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16426. init_connection(conn);
  16427. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16428. /* Start with HTTP, WS will be an "upgrade" request later */
  16429. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16430. process_new_connection(conn);
  16431. }
  16432. /* Free client certificate info */
  16433. if (conn->request_info.client_cert) {
  16434. mg_free((void *)(conn->request_info.client_cert->subject));
  16435. mg_free((void *)(conn->request_info.client_cert->issuer));
  16436. mg_free((void *)(conn->request_info.client_cert->serial));
  16437. mg_free((void *)(conn->request_info.client_cert->finger));
  16438. /* Free certificate memory */
  16439. X509_free(
  16440. (X509 *)conn->request_info.client_cert->peer_cert);
  16441. conn->request_info.client_cert->peer_cert = 0;
  16442. conn->request_info.client_cert->subject = 0;
  16443. conn->request_info.client_cert->issuer = 0;
  16444. conn->request_info.client_cert->serial = 0;
  16445. conn->request_info.client_cert->finger = 0;
  16446. conn->request_info.client_cert = 0;
  16447. }
  16448. } else {
  16449. /* make sure the connection is cleaned up on SSL failure */
  16450. close_connection(conn);
  16451. }
  16452. #endif
  16453. } else {
  16454. /* process HTTP connection */
  16455. init_connection(conn);
  16456. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16457. /* Start with HTTP, WS will be an "upgrade" request later */
  16458. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16459. process_new_connection(conn);
  16460. }
  16461. DEBUG_TRACE("%s", "Connection closed");
  16462. #if defined(USE_SERVER_STATS)
  16463. conn->conn_close_time = time(NULL);
  16464. #endif
  16465. }
  16466. /* Call exit thread user callback */
  16467. if (ctx->callbacks.exit_thread) {
  16468. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16469. }
  16470. /* delete thread local storage objects */
  16471. pthread_setspecific(sTlsKey, NULL);
  16472. #if defined(_WIN32)
  16473. CloseHandle(tls.pthread_cond_helper_mutex);
  16474. #endif
  16475. pthread_mutex_destroy(&conn->mutex);
  16476. /* Free the request buffer. */
  16477. conn->buf_size = 0;
  16478. mg_free(conn->buf);
  16479. conn->buf = NULL;
  16480. #if defined(USE_SERVER_STATS)
  16481. conn->conn_state = 9; /* done */
  16482. #endif
  16483. DEBUG_TRACE("%s", "exiting");
  16484. }
  16485. /* Threads have different return types on Windows and Unix. */
  16486. #if defined(_WIN32)
  16487. static unsigned __stdcall worker_thread(void *thread_func_param)
  16488. {
  16489. worker_thread_run((struct mg_connection *)thread_func_param);
  16490. return 0;
  16491. }
  16492. #else
  16493. static void *
  16494. worker_thread(void *thread_func_param)
  16495. {
  16496. #if !defined(__ZEPHYR__)
  16497. struct sigaction sa;
  16498. /* Ignore SIGPIPE */
  16499. memset(&sa, 0, sizeof(sa));
  16500. sa.sa_handler = SIG_IGN;
  16501. sigaction(SIGPIPE, &sa, NULL);
  16502. #endif
  16503. worker_thread_run((struct mg_connection *)thread_func_param);
  16504. return NULL;
  16505. }
  16506. #endif /* _WIN32 */
  16507. /* This is an internal function, thus all arguments are expected to be
  16508. * valid - a NULL check is not required. */
  16509. static void
  16510. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16511. {
  16512. struct socket so;
  16513. char src_addr[IP_ADDR_STR_LEN];
  16514. socklen_t len = sizeof(so.rsa);
  16515. #if !defined(__ZEPHYR__)
  16516. int on = 1;
  16517. #endif
  16518. memset(&so, 0, sizeof(so));
  16519. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16520. == INVALID_SOCKET) {
  16521. } else if (check_acl(ctx, &so.rsa) != 1) {
  16522. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16523. mg_cry_ctx_internal(ctx,
  16524. "%s: %s is not allowed to connect",
  16525. __func__,
  16526. src_addr);
  16527. closesocket(so.sock);
  16528. } else {
  16529. /* Put so socket structure into the queue */
  16530. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16531. set_close_on_exec(so.sock, NULL, ctx);
  16532. so.is_ssl = listener->is_ssl;
  16533. so.ssl_redir = listener->ssl_redir;
  16534. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16535. mg_cry_ctx_internal(ctx,
  16536. "%s: getsockname() failed: %s",
  16537. __func__,
  16538. strerror(ERRNO));
  16539. }
  16540. #if !defined(__ZEPHYR__)
  16541. /* Set TCP keep-alive. This is needed because if HTTP-level
  16542. * keep-alive
  16543. * is enabled, and client resets the connection, server won't get
  16544. * TCP FIN or RST and will keep the connection open forever. With
  16545. * TCP keep-alive, next keep-alive handshake will figure out that
  16546. * the client is down and will close the server end.
  16547. * Thanks to Igor Klopov who suggested the patch. */
  16548. if (setsockopt(so.sock,
  16549. SOL_SOCKET,
  16550. SO_KEEPALIVE,
  16551. (SOCK_OPT_TYPE)&on,
  16552. sizeof(on))
  16553. != 0) {
  16554. mg_cry_ctx_internal(
  16555. ctx,
  16556. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16557. __func__,
  16558. strerror(ERRNO));
  16559. }
  16560. #endif
  16561. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16562. * to effectively fill up the underlying IP packet payload and
  16563. * reduce the overhead of sending lots of small buffers. However
  16564. * this hurts the server's throughput (ie. operations per second)
  16565. * when HTTP 1.1 persistent connections are used and the responses
  16566. * are relatively small (eg. less than 1400 bytes).
  16567. */
  16568. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16569. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16570. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16571. mg_cry_ctx_internal(
  16572. ctx,
  16573. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16574. __func__,
  16575. strerror(ERRNO));
  16576. }
  16577. }
  16578. /* The "non blocking" property should already be
  16579. * inherited from the parent socket. Set it for
  16580. * non-compliant socket implementations. */
  16581. set_non_blocking_mode(so.sock);
  16582. so.in_use = 0;
  16583. produce_socket(ctx, &so);
  16584. }
  16585. }
  16586. static void
  16587. master_thread_run(struct mg_context *ctx)
  16588. {
  16589. struct mg_workerTLS tls;
  16590. struct mg_pollfd *pfd;
  16591. unsigned int i;
  16592. unsigned int workerthreadcount;
  16593. if (!ctx) {
  16594. return;
  16595. }
  16596. mg_set_thread_name("master");
  16597. /* Increase priority of the master thread */
  16598. #if defined(_WIN32)
  16599. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16600. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16601. int min_prio = sched_get_priority_min(SCHED_RR);
  16602. int max_prio = sched_get_priority_max(SCHED_RR);
  16603. if ((min_prio >= 0) && (max_prio >= 0)
  16604. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16605. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16606. struct sched_param sched_param = {0};
  16607. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16608. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16609. }
  16610. #endif
  16611. /* Initialize thread local storage */
  16612. #if defined(_WIN32)
  16613. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16614. #endif
  16615. tls.is_master = 1;
  16616. pthread_setspecific(sTlsKey, &tls);
  16617. if (ctx->callbacks.init_thread) {
  16618. /* Callback for the master thread (type 0) */
  16619. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16620. } else {
  16621. tls.user_ptr = NULL;
  16622. }
  16623. /* Server starts *now* */
  16624. ctx->start_time = time(NULL);
  16625. /* Start the server */
  16626. pfd = ctx->listening_socket_fds;
  16627. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16628. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16629. pfd[i].fd = ctx->listening_sockets[i].sock;
  16630. pfd[i].events = POLLIN;
  16631. }
  16632. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16633. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16634. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16635. * successful poll, and POLLIN is defined as
  16636. * (POLLRDNORM | POLLRDBAND)
  16637. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16638. * pfd[i].revents == POLLIN. */
  16639. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16640. && (pfd[i].revents & POLLIN)) {
  16641. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16642. }
  16643. }
  16644. }
  16645. }
  16646. /* Here stop_flag is 1 - Initiate shutdown. */
  16647. DEBUG_TRACE("%s", "stopping workers");
  16648. /* Stop signal received: somebody called mg_stop. Quit. */
  16649. close_all_listening_sockets(ctx);
  16650. /* Wakeup workers that are waiting for connections to handle. */
  16651. #if defined(ALTERNATIVE_QUEUE)
  16652. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16653. event_signal(ctx->client_wait_events[i]);
  16654. }
  16655. #else
  16656. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16657. pthread_cond_broadcast(&ctx->sq_full);
  16658. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16659. #endif
  16660. /* Join all worker threads to avoid leaking threads. */
  16661. workerthreadcount = ctx->cfg_worker_threads;
  16662. for (i = 0; i < workerthreadcount; i++) {
  16663. if (ctx->worker_threadids[i] != 0) {
  16664. mg_join_thread(ctx->worker_threadids[i]);
  16665. }
  16666. }
  16667. #if defined(USE_LUA)
  16668. /* Free Lua state of lua background task */
  16669. if (ctx->lua_background_state) {
  16670. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16671. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16672. if (lua_istable(lstate, -1)) {
  16673. reg_boolean(lstate, "shutdown", 1);
  16674. lua_pop(lstate, 1);
  16675. mg_sleep(2);
  16676. }
  16677. lua_close(lstate);
  16678. ctx->lua_background_state = 0;
  16679. }
  16680. #endif
  16681. DEBUG_TRACE("%s", "exiting");
  16682. /* call exit thread callback */
  16683. if (ctx->callbacks.exit_thread) {
  16684. /* Callback for the master thread (type 0) */
  16685. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16686. }
  16687. #if defined(_WIN32)
  16688. CloseHandle(tls.pthread_cond_helper_mutex);
  16689. #endif
  16690. pthread_setspecific(sTlsKey, NULL);
  16691. /* Signal mg_stop() that we're done.
  16692. * WARNING: This must be the very last thing this
  16693. * thread does, as ctx becomes invalid after this line. */
  16694. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16695. }
  16696. /* Threads have different return types on Windows and Unix. */
  16697. #if defined(_WIN32)
  16698. static unsigned __stdcall master_thread(void *thread_func_param)
  16699. {
  16700. master_thread_run((struct mg_context *)thread_func_param);
  16701. return 0;
  16702. }
  16703. #else
  16704. static void *
  16705. master_thread(void *thread_func_param)
  16706. {
  16707. #if !defined(__ZEPHYR__)
  16708. struct sigaction sa;
  16709. /* Ignore SIGPIPE */
  16710. memset(&sa, 0, sizeof(sa));
  16711. sa.sa_handler = SIG_IGN;
  16712. sigaction(SIGPIPE, &sa, NULL);
  16713. #endif
  16714. master_thread_run((struct mg_context *)thread_func_param);
  16715. return NULL;
  16716. }
  16717. #endif /* _WIN32 */
  16718. static void
  16719. free_context(struct mg_context *ctx)
  16720. {
  16721. int i;
  16722. struct mg_handler_info *tmp_rh;
  16723. if (ctx == NULL) {
  16724. return;
  16725. }
  16726. /* Call user callback */
  16727. if (ctx->callbacks.exit_context) {
  16728. ctx->callbacks.exit_context(ctx);
  16729. }
  16730. /* All threads exited, no sync is needed. Destroy thread mutex and
  16731. * condvars
  16732. */
  16733. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16734. #if defined(ALTERNATIVE_QUEUE)
  16735. mg_free(ctx->client_socks);
  16736. if (ctx->client_wait_events != NULL) {
  16737. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16738. event_destroy(ctx->client_wait_events[i]);
  16739. }
  16740. mg_free(ctx->client_wait_events);
  16741. }
  16742. #else
  16743. (void)pthread_cond_destroy(&ctx->sq_empty);
  16744. (void)pthread_cond_destroy(&ctx->sq_full);
  16745. mg_free(ctx->squeue);
  16746. #endif
  16747. /* Destroy other context global data structures mutex */
  16748. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16749. /* Deallocate config parameters */
  16750. for (i = 0; i < NUM_OPTIONS; i++) {
  16751. if (ctx->dd.config[i] != NULL) {
  16752. #if defined(_MSC_VER)
  16753. #pragma warning(suppress : 6001)
  16754. #endif
  16755. mg_free(ctx->dd.config[i]);
  16756. }
  16757. }
  16758. /* Deallocate request handlers */
  16759. while (ctx->dd.handlers) {
  16760. tmp_rh = ctx->dd.handlers;
  16761. ctx->dd.handlers = tmp_rh->next;
  16762. mg_free(tmp_rh->uri);
  16763. mg_free(tmp_rh);
  16764. }
  16765. #if defined(USE_MBEDTLS)
  16766. if (ctx->dd.ssl_ctx != NULL) {
  16767. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  16768. mg_free(ctx->dd.ssl_ctx);
  16769. ctx->dd.ssl_ctx = NULL;
  16770. }
  16771. #endif
  16772. #if !defined(NO_SSL)
  16773. /* Deallocate SSL context */
  16774. if (ctx->dd.ssl_ctx != NULL) {
  16775. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16776. int callback_ret =
  16777. (ctx->callbacks.external_ssl_ctx == NULL)
  16778. ? 0
  16779. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16780. if (callback_ret == 0) {
  16781. SSL_CTX_free(ctx->dd.ssl_ctx);
  16782. }
  16783. /* else: ignore error and ommit SSL_CTX_free in case
  16784. * callback_ret is 1 */
  16785. }
  16786. #endif /* !NO_SSL */
  16787. /* Deallocate worker thread ID array */
  16788. mg_free(ctx->worker_threadids);
  16789. /* Deallocate worker thread ID array */
  16790. mg_free(ctx->worker_connections);
  16791. /* deallocate system name string */
  16792. mg_free(ctx->systemName);
  16793. /* Deallocate context itself */
  16794. mg_free(ctx);
  16795. }
  16796. void
  16797. mg_stop(struct mg_context *ctx)
  16798. {
  16799. pthread_t mt;
  16800. if (!ctx) {
  16801. return;
  16802. }
  16803. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16804. * two threads is not allowed. */
  16805. mt = ctx->masterthreadid;
  16806. if (mt == 0) {
  16807. return;
  16808. }
  16809. ctx->masterthreadid = 0;
  16810. /* Set stop flag, so all threads know they have to exit. */
  16811. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16812. /* Join timer thread */
  16813. #if defined(USE_TIMERS)
  16814. timers_exit(ctx);
  16815. #endif
  16816. /* Wait until everything has stopped. */
  16817. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16818. (void)mg_sleep(10);
  16819. }
  16820. /* Wait to stop master thread */
  16821. mg_join_thread(mt);
  16822. /* Close remaining Lua states */
  16823. #if defined(USE_LUA)
  16824. lua_ctx_exit(ctx);
  16825. #endif
  16826. /* Free memory */
  16827. free_context(ctx);
  16828. }
  16829. static void
  16830. get_system_name(char **sysName)
  16831. {
  16832. #if defined(_WIN32)
  16833. #if defined(_WIN32_WCE)
  16834. *sysName = mg_strdup("WinCE");
  16835. #else
  16836. char name[128];
  16837. DWORD dwVersion = 0;
  16838. DWORD dwMajorVersion = 0;
  16839. DWORD dwMinorVersion = 0;
  16840. DWORD dwBuild = 0;
  16841. BOOL wowRet, isWoW = FALSE;
  16842. #if defined(_MSC_VER)
  16843. #pragma warning(push)
  16844. /* GetVersion was declared deprecated */
  16845. #pragma warning(disable : 4996)
  16846. #endif
  16847. dwVersion = GetVersion();
  16848. #if defined(_MSC_VER)
  16849. #pragma warning(pop)
  16850. #endif
  16851. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16852. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16853. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16854. (void)dwBuild;
  16855. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16856. sprintf(name,
  16857. "Windows %u.%u%s",
  16858. (unsigned)dwMajorVersion,
  16859. (unsigned)dwMinorVersion,
  16860. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16861. *sysName = mg_strdup(name);
  16862. #endif
  16863. #elif defined(__ZEPHYR__)
  16864. *sysName = mg_strdup("Zephyr OS");
  16865. #else
  16866. struct utsname name;
  16867. memset(&name, 0, sizeof(name));
  16868. uname(&name);
  16869. *sysName = mg_strdup(name.sysname);
  16870. #endif
  16871. }
  16872. static void
  16873. legacy_init(const char **options)
  16874. {
  16875. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16876. if (options) {
  16877. const char **run_options = options;
  16878. const char *optname = config_options[LISTENING_PORTS].name;
  16879. /* Try to find the "listening_ports" option */
  16880. while (*run_options) {
  16881. if (!strcmp(*run_options, optname)) {
  16882. ports_option = run_options[1];
  16883. }
  16884. run_options += 2;
  16885. }
  16886. }
  16887. if (is_ssl_port_used(ports_option)) {
  16888. /* Initialize with SSL support */
  16889. mg_init_library(MG_FEATURES_TLS);
  16890. } else {
  16891. /* Initialize without SSL support */
  16892. mg_init_library(MG_FEATURES_DEFAULT);
  16893. }
  16894. }
  16895. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16896. static
  16897. #endif
  16898. struct mg_context *
  16899. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16900. {
  16901. struct mg_context *ctx;
  16902. const char *name, *value, *default_value;
  16903. int idx, ok, workerthreadcount;
  16904. unsigned int i;
  16905. int itmp;
  16906. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16907. const char **options =
  16908. ((init != NULL) ? (init->configuration_options) : (NULL));
  16909. struct mg_workerTLS tls;
  16910. if (error != NULL) {
  16911. error->code = 0;
  16912. if (error->text_buffer_size > 0) {
  16913. *error->text = 0;
  16914. }
  16915. }
  16916. if (mg_init_library_called == 0) {
  16917. /* Legacy INIT, if mg_start is called without mg_init_library.
  16918. * Note: This will cause a memory leak when unloading the library.
  16919. */
  16920. legacy_init(options);
  16921. }
  16922. if (mg_init_library_called == 0) {
  16923. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16924. mg_snprintf(NULL,
  16925. NULL, /* No truncation check for error buffers */
  16926. error->text,
  16927. error->text_buffer_size,
  16928. "%s",
  16929. "Library uninitialized");
  16930. }
  16931. return NULL;
  16932. }
  16933. /* Allocate context and initialize reasonable general case defaults. */
  16934. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16935. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16936. mg_snprintf(NULL,
  16937. NULL, /* No truncation check for error buffers */
  16938. error->text,
  16939. error->text_buffer_size,
  16940. "%s",
  16941. "Out of memory");
  16942. }
  16943. return NULL;
  16944. }
  16945. /* Random number generator will initialize at the first call */
  16946. ctx->dd.auth_nonce_mask =
  16947. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16948. /* Save started thread index to reuse in other external API calls
  16949. * For the sake of thread synchronization all non-civetweb threads
  16950. * can be considered as single external thread */
  16951. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16952. tls.is_master = -1; /* Thread calling mg_start */
  16953. tls.thread_idx = ctx->starter_thread_idx;
  16954. #if defined(_WIN32)
  16955. tls.pthread_cond_helper_mutex = NULL;
  16956. #endif
  16957. pthread_setspecific(sTlsKey, &tls);
  16958. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16959. #if !defined(ALTERNATIVE_QUEUE)
  16960. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16961. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16962. ctx->sq_blocked = 0;
  16963. #endif
  16964. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16965. if (!ok) {
  16966. const char *err_msg =
  16967. "Cannot initialize thread synchronization objects";
  16968. /* Fatal error - abort start. However, this situation should never
  16969. * occur in practice. */
  16970. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16971. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16972. mg_snprintf(NULL,
  16973. NULL, /* No truncation check for error buffers */
  16974. error->text,
  16975. error->text_buffer_size,
  16976. "%s",
  16977. err_msg);
  16978. }
  16979. mg_free(ctx);
  16980. pthread_setspecific(sTlsKey, NULL);
  16981. return NULL;
  16982. }
  16983. if ((init != NULL) && (init->callbacks != NULL)) {
  16984. /* Set all callbacks except exit_context. */
  16985. ctx->callbacks = *init->callbacks;
  16986. exit_callback = init->callbacks->exit_context;
  16987. /* The exit callback is activated once the context is successfully
  16988. * created. It should not be called, if an incomplete context object
  16989. * is deleted during a failed initialization. */
  16990. ctx->callbacks.exit_context = 0;
  16991. }
  16992. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16993. ctx->dd.handlers = NULL;
  16994. ctx->dd.next = NULL;
  16995. #if defined(USE_LUA)
  16996. lua_ctx_init(ctx);
  16997. #endif
  16998. /* Store options */
  16999. while (options && (name = *options++) != NULL) {
  17000. if ((idx = get_option_index(name)) == -1) {
  17001. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17002. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17003. mg_snprintf(NULL,
  17004. NULL, /* No truncation check for error buffers */
  17005. error->text,
  17006. error->text_buffer_size,
  17007. "Invalid configuration option: %s",
  17008. name);
  17009. }
  17010. free_context(ctx);
  17011. pthread_setspecific(sTlsKey, NULL);
  17012. return NULL;
  17013. } else if ((value = *options++) == NULL) {
  17014. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17015. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17016. mg_snprintf(NULL,
  17017. NULL, /* No truncation check for error buffers */
  17018. error->text,
  17019. error->text_buffer_size,
  17020. "Invalid configuration option value: %s",
  17021. name);
  17022. }
  17023. free_context(ctx);
  17024. pthread_setspecific(sTlsKey, NULL);
  17025. return NULL;
  17026. }
  17027. if (ctx->dd.config[idx] != NULL) {
  17028. /* A duplicate configuration option is not an error - the last
  17029. * option value will be used. */
  17030. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17031. mg_free(ctx->dd.config[idx]);
  17032. }
  17033. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17034. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17035. }
  17036. /* Set default value if needed */
  17037. for (i = 0; config_options[i].name != NULL; i++) {
  17038. default_value = config_options[i].default_value;
  17039. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17040. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17041. }
  17042. }
  17043. /* Request size option */
  17044. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17045. if (itmp < 1024) {
  17046. mg_cry_ctx_internal(ctx,
  17047. "%s too small",
  17048. config_options[MAX_REQUEST_SIZE].name);
  17049. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17050. mg_snprintf(NULL,
  17051. NULL, /* No truncation check for error buffers */
  17052. error->text,
  17053. error->text_buffer_size,
  17054. "Invalid configuration option value: %s",
  17055. config_options[MAX_REQUEST_SIZE].name);
  17056. }
  17057. free_context(ctx);
  17058. pthread_setspecific(sTlsKey, NULL);
  17059. return NULL;
  17060. }
  17061. ctx->max_request_size = (unsigned)itmp;
  17062. /* Queue length */
  17063. #if !defined(ALTERNATIVE_QUEUE)
  17064. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17065. if (itmp < 1) {
  17066. mg_cry_ctx_internal(ctx,
  17067. "%s too small",
  17068. config_options[CONNECTION_QUEUE_SIZE].name);
  17069. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17070. mg_snprintf(NULL,
  17071. NULL, /* No truncation check for error buffers */
  17072. error->text,
  17073. error->text_buffer_size,
  17074. "Invalid configuration option value: %s",
  17075. config_options[CONNECTION_QUEUE_SIZE].name);
  17076. }
  17077. free_context(ctx);
  17078. pthread_setspecific(sTlsKey, NULL);
  17079. return NULL;
  17080. }
  17081. ctx->squeue =
  17082. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17083. if (ctx->squeue == NULL) {
  17084. mg_cry_ctx_internal(ctx,
  17085. "Out of memory: Cannot allocate %s",
  17086. config_options[CONNECTION_QUEUE_SIZE].name);
  17087. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17088. mg_snprintf(NULL,
  17089. NULL, /* No truncation check for error buffers */
  17090. error->text,
  17091. error->text_buffer_size,
  17092. "Out of memory: Cannot allocate %s",
  17093. config_options[CONNECTION_QUEUE_SIZE].name);
  17094. }
  17095. free_context(ctx);
  17096. pthread_setspecific(sTlsKey, NULL);
  17097. return NULL;
  17098. }
  17099. ctx->sq_size = itmp;
  17100. #endif
  17101. /* Worker thread count option */
  17102. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17103. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17104. if (workerthreadcount <= 0) {
  17105. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17106. } else {
  17107. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17108. }
  17109. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17110. mg_snprintf(NULL,
  17111. NULL, /* No truncation check for error buffers */
  17112. error->text,
  17113. error->text_buffer_size,
  17114. "Invalid configuration option value: %s",
  17115. config_options[NUM_THREADS].name);
  17116. }
  17117. free_context(ctx);
  17118. pthread_setspecific(sTlsKey, NULL);
  17119. return NULL;
  17120. }
  17121. /* Document root */
  17122. #if defined(NO_FILES)
  17123. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17124. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17125. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17126. mg_snprintf(NULL,
  17127. NULL, /* No truncation check for error buffers */
  17128. error->text,
  17129. error->text_buffer_size,
  17130. "Invalid configuration option value: %s",
  17131. config_options[DOCUMENT_ROOT].name);
  17132. }
  17133. free_context(ctx);
  17134. pthread_setspecific(sTlsKey, NULL);
  17135. return NULL;
  17136. }
  17137. #endif
  17138. get_system_name(&ctx->systemName);
  17139. #if defined(USE_LUA)
  17140. /* If a Lua background script has been configured, start it. */
  17141. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17142. char ebuf[256];
  17143. struct vec opt_vec;
  17144. struct vec eq_vec;
  17145. const char *sparams;
  17146. lua_State *state = mg_prepare_lua_context_script(
  17147. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17148. if (!state) {
  17149. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  17150. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17151. mg_snprintf(NULL,
  17152. NULL, /* No truncation check for error buffers */
  17153. error->text,
  17154. error->text_buffer_size,
  17155. "Error in script %s: %s",
  17156. config_options[DOCUMENT_ROOT].name,
  17157. ebuf);
  17158. }
  17159. free_context(ctx);
  17160. pthread_setspecific(sTlsKey, NULL);
  17161. return NULL;
  17162. }
  17163. ctx->lua_background_state = (void *)state;
  17164. lua_newtable(state);
  17165. reg_boolean(state, "shutdown", 0);
  17166. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17167. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17168. reg_llstring(
  17169. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17170. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17171. break;
  17172. }
  17173. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17174. } else {
  17175. ctx->lua_background_state = 0;
  17176. }
  17177. #endif
  17178. /* Step by step initialization of ctx - depending on build options */
  17179. #if !defined(NO_FILESYSTEMS)
  17180. if (!set_gpass_option(ctx, NULL)) {
  17181. const char *err_msg = "Invalid global password file";
  17182. /* Fatal error - abort start. */
  17183. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17184. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17185. mg_snprintf(NULL,
  17186. NULL, /* No truncation check for error buffers */
  17187. error->text,
  17188. error->text_buffer_size,
  17189. "%s",
  17190. err_msg);
  17191. }
  17192. free_context(ctx);
  17193. pthread_setspecific(sTlsKey, NULL);
  17194. return NULL;
  17195. }
  17196. #endif
  17197. #if defined(USE_MBEDTLS)
  17198. if (!mg_sslctx_init(ctx, NULL)) {
  17199. const char *err_msg = "Error initializing SSL context";
  17200. /* Fatal error - abort start. */
  17201. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17202. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17203. mg_snprintf(NULL,
  17204. NULL, /* No truncation check for error buffers */
  17205. error->text,
  17206. error->text_buffer_size,
  17207. "%s",
  17208. err_msg);
  17209. }
  17210. free_context(ctx);
  17211. pthread_setspecific(sTlsKey, NULL);
  17212. return NULL;
  17213. }
  17214. #endif
  17215. #if !defined(NO_SSL)
  17216. if (!init_ssl_ctx(ctx, NULL)) {
  17217. const char *err_msg = "Error initializing SSL context";
  17218. /* Fatal error - abort start. */
  17219. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17220. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17221. mg_snprintf(NULL,
  17222. NULL, /* No truncation check for error buffers */
  17223. error->text,
  17224. error->text_buffer_size,
  17225. "%s",
  17226. err_msg);
  17227. }
  17228. free_context(ctx);
  17229. pthread_setspecific(sTlsKey, NULL);
  17230. return NULL;
  17231. }
  17232. #endif
  17233. if (!set_ports_option(ctx)) {
  17234. const char *err_msg = "Failed to setup server ports";
  17235. /* Fatal error - abort start. */
  17236. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17237. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17238. mg_snprintf(NULL,
  17239. NULL, /* No truncation check for error buffers */
  17240. error->text,
  17241. error->text_buffer_size,
  17242. "%s",
  17243. err_msg);
  17244. }
  17245. free_context(ctx);
  17246. pthread_setspecific(sTlsKey, NULL);
  17247. return NULL;
  17248. }
  17249. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17250. if (!set_uid_option(ctx)) {
  17251. const char *err_msg = "Failed to run as configured user";
  17252. /* Fatal error - abort start. */
  17253. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17254. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17255. mg_snprintf(NULL,
  17256. NULL, /* No truncation check for error buffers */
  17257. error->text,
  17258. error->text_buffer_size,
  17259. "%s",
  17260. err_msg);
  17261. }
  17262. free_context(ctx);
  17263. pthread_setspecific(sTlsKey, NULL);
  17264. return NULL;
  17265. }
  17266. #endif
  17267. if (!set_acl_option(ctx)) {
  17268. const char *err_msg = "Failed to setup access control list";
  17269. /* Fatal error - abort start. */
  17270. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17271. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17272. mg_snprintf(NULL,
  17273. NULL, /* No truncation check for error buffers */
  17274. error->text,
  17275. error->text_buffer_size,
  17276. "%s",
  17277. err_msg);
  17278. }
  17279. free_context(ctx);
  17280. pthread_setspecific(sTlsKey, NULL);
  17281. return NULL;
  17282. }
  17283. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17284. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17285. sizeof(pthread_t),
  17286. ctx);
  17287. if (ctx->worker_threadids == NULL) {
  17288. const char *err_msg = "Not enough memory for worker thread ID array";
  17289. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17290. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17291. mg_snprintf(NULL,
  17292. NULL, /* No truncation check for error buffers */
  17293. error->text,
  17294. error->text_buffer_size,
  17295. "%s",
  17296. err_msg);
  17297. }
  17298. free_context(ctx);
  17299. pthread_setspecific(sTlsKey, NULL);
  17300. return NULL;
  17301. }
  17302. ctx->worker_connections =
  17303. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17304. sizeof(struct mg_connection),
  17305. ctx);
  17306. if (ctx->worker_connections == NULL) {
  17307. const char *err_msg =
  17308. "Not enough memory for worker thread connection array";
  17309. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17310. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17311. mg_snprintf(NULL,
  17312. NULL, /* No truncation check for error buffers */
  17313. error->text,
  17314. error->text_buffer_size,
  17315. "%s",
  17316. err_msg);
  17317. }
  17318. free_context(ctx);
  17319. pthread_setspecific(sTlsKey, NULL);
  17320. return NULL;
  17321. }
  17322. #if defined(ALTERNATIVE_QUEUE)
  17323. ctx->client_wait_events =
  17324. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17325. sizeof(ctx->client_wait_events[0]),
  17326. ctx);
  17327. if (ctx->client_wait_events == NULL) {
  17328. const char *err_msg = "Not enough memory for worker event array";
  17329. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17330. mg_free(ctx->worker_threadids);
  17331. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17332. mg_snprintf(NULL,
  17333. NULL, /* No truncation check for error buffers */
  17334. error->text,
  17335. error->text_buffer_size,
  17336. "%s",
  17337. err_msg);
  17338. }
  17339. free_context(ctx);
  17340. pthread_setspecific(sTlsKey, NULL);
  17341. return NULL;
  17342. }
  17343. ctx->client_socks =
  17344. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17345. sizeof(ctx->client_socks[0]),
  17346. ctx);
  17347. if (ctx->client_socks == NULL) {
  17348. const char *err_msg = "Not enough memory for worker socket array";
  17349. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17350. mg_free(ctx->client_wait_events);
  17351. mg_free(ctx->worker_threadids);
  17352. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17353. mg_snprintf(NULL,
  17354. NULL, /* No truncation check for error buffers */
  17355. error->text,
  17356. error->text_buffer_size,
  17357. "%s",
  17358. err_msg);
  17359. }
  17360. free_context(ctx);
  17361. pthread_setspecific(sTlsKey, NULL);
  17362. return NULL;
  17363. }
  17364. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17365. ctx->client_wait_events[i] = event_create();
  17366. if (ctx->client_wait_events[i] == 0) {
  17367. const char *err_msg = "Error creating worker event %i";
  17368. mg_cry_ctx_internal(ctx, err_msg, i);
  17369. while (i > 0) {
  17370. i--;
  17371. event_destroy(ctx->client_wait_events[i]);
  17372. }
  17373. mg_free(ctx->client_socks);
  17374. mg_free(ctx->client_wait_events);
  17375. mg_free(ctx->worker_threadids);
  17376. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17377. mg_snprintf(NULL,
  17378. NULL, /* No truncation check for error buffers */
  17379. error->text,
  17380. error->text_buffer_size,
  17381. err_msg,
  17382. i);
  17383. }
  17384. free_context(ctx);
  17385. pthread_setspecific(sTlsKey, NULL);
  17386. return NULL;
  17387. }
  17388. }
  17389. #endif
  17390. #if defined(USE_TIMERS)
  17391. if (timers_init(ctx) != 0) {
  17392. const char *err_msg = "Error creating timers";
  17393. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17394. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17395. mg_snprintf(NULL,
  17396. NULL, /* No truncation check for error buffers */
  17397. error->text,
  17398. error->text_buffer_size,
  17399. "%s",
  17400. err_msg);
  17401. }
  17402. free_context(ctx);
  17403. pthread_setspecific(sTlsKey, NULL);
  17404. return NULL;
  17405. }
  17406. #endif
  17407. /* Context has been created - init user libraries */
  17408. if (ctx->callbacks.init_context) {
  17409. ctx->callbacks.init_context(ctx);
  17410. }
  17411. /* From now, the context is successfully created.
  17412. * When it is destroyed, the exit callback should be called. */
  17413. ctx->callbacks.exit_context = exit_callback;
  17414. ctx->context_type = CONTEXT_SERVER; /* server context */
  17415. /* Start worker threads */
  17416. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17417. /* worker_thread sets up the other fields */
  17418. ctx->worker_connections[i].phys_ctx = ctx;
  17419. if (mg_start_thread_with_id(worker_thread,
  17420. &ctx->worker_connections[i],
  17421. &ctx->worker_threadids[i])
  17422. != 0) {
  17423. long error_no = (long)ERRNO;
  17424. /* thread was not created */
  17425. if (i > 0) {
  17426. /* If the second, third, ... thread cannot be created, set a
  17427. * warning, but keep running. */
  17428. mg_cry_ctx_internal(ctx,
  17429. "Cannot start worker thread %i: error %ld",
  17430. i + 1,
  17431. error_no);
  17432. /* If the server initialization should stop here, all
  17433. * threads that have already been created must be stopped
  17434. * first, before any free_context(ctx) call.
  17435. */
  17436. } else {
  17437. /* If the first worker thread cannot be created, stop
  17438. * initialization and free the entire server context. */
  17439. mg_cry_ctx_internal(ctx,
  17440. "Cannot create threads: error %ld",
  17441. error_no);
  17442. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17443. mg_snprintf(
  17444. NULL,
  17445. NULL, /* No truncation check for error buffers */
  17446. error->text,
  17447. error->text_buffer_size,
  17448. "Cannot create first worker thread: error %ld",
  17449. error_no);
  17450. }
  17451. free_context(ctx);
  17452. pthread_setspecific(sTlsKey, NULL);
  17453. return NULL;
  17454. }
  17455. break;
  17456. }
  17457. }
  17458. /* Start master (listening) thread */
  17459. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17460. pthread_setspecific(sTlsKey, NULL);
  17461. return ctx;
  17462. }
  17463. struct mg_context *
  17464. mg_start(const struct mg_callbacks *callbacks,
  17465. void *user_data,
  17466. const char **options)
  17467. {
  17468. struct mg_init_data init = {0};
  17469. init.callbacks = callbacks;
  17470. init.user_data = user_data;
  17471. init.configuration_options = options;
  17472. return mg_start2(&init, NULL);
  17473. }
  17474. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17475. /* Add an additional domain to an already running web server. */
  17476. int
  17477. mg_start_domain2(struct mg_context *ctx,
  17478. const char **options,
  17479. struct mg_error_data *error)
  17480. {
  17481. const char *name;
  17482. const char *value;
  17483. const char *default_value;
  17484. struct mg_domain_context *new_dom;
  17485. struct mg_domain_context *dom;
  17486. int idx, i;
  17487. if (error != NULL) {
  17488. error->code = 0;
  17489. if (error->text_buffer_size > 0) {
  17490. *error->text = 0;
  17491. }
  17492. }
  17493. if ((ctx == NULL) || (options == NULL)) {
  17494. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17495. mg_snprintf(NULL,
  17496. NULL, /* No truncation check for error buffers */
  17497. error->text,
  17498. error->text_buffer_size,
  17499. "%s",
  17500. "Invalid parameters");
  17501. }
  17502. return -1;
  17503. }
  17504. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17505. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17506. mg_snprintf(NULL,
  17507. NULL, /* No truncation check for error buffers */
  17508. error->text,
  17509. error->text_buffer_size,
  17510. "%s",
  17511. "Server already stopped");
  17512. }
  17513. return -1;
  17514. }
  17515. new_dom = (struct mg_domain_context *)
  17516. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17517. if (!new_dom) {
  17518. /* Out of memory */
  17519. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17520. mg_snprintf(NULL,
  17521. NULL, /* No truncation check for error buffers */
  17522. error->text,
  17523. error->text_buffer_size,
  17524. "%s",
  17525. "Out or memory");
  17526. }
  17527. return -6;
  17528. }
  17529. /* Store options - TODO: unite duplicate code */
  17530. while (options && (name = *options++) != NULL) {
  17531. if ((idx = get_option_index(name)) == -1) {
  17532. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17533. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17534. mg_snprintf(NULL,
  17535. NULL, /* No truncation check for error buffers */
  17536. error->text,
  17537. error->text_buffer_size,
  17538. "Invalid option: %s",
  17539. name);
  17540. }
  17541. mg_free(new_dom);
  17542. return -2;
  17543. } else if ((value = *options++) == NULL) {
  17544. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17545. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17546. mg_snprintf(NULL,
  17547. NULL, /* No truncation check for error buffers */
  17548. error->text,
  17549. error->text_buffer_size,
  17550. "Invalid option value: %s",
  17551. name);
  17552. }
  17553. mg_free(new_dom);
  17554. return -2;
  17555. }
  17556. if (new_dom->config[idx] != NULL) {
  17557. /* Duplicate option: Later values overwrite earlier ones. */
  17558. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17559. mg_free(new_dom->config[idx]);
  17560. }
  17561. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17562. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17563. }
  17564. /* Authentication domain is mandatory */
  17565. /* TODO: Maybe use a new option hostname? */
  17566. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17567. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17568. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17569. mg_snprintf(NULL,
  17570. NULL, /* No truncation check for error buffers */
  17571. error->text,
  17572. error->text_buffer_size,
  17573. "Mandatory option %s missing",
  17574. config_options[AUTHENTICATION_DOMAIN].name);
  17575. }
  17576. mg_free(new_dom);
  17577. return -4;
  17578. }
  17579. /* Set default value if needed. Take the config value from
  17580. * ctx as a default value. */
  17581. for (i = 0; config_options[i].name != NULL; i++) {
  17582. default_value = ctx->dd.config[i];
  17583. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17584. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17585. }
  17586. }
  17587. new_dom->handlers = NULL;
  17588. new_dom->next = NULL;
  17589. new_dom->nonce_count = 0;
  17590. new_dom->auth_nonce_mask =
  17591. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17592. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17593. new_dom->shared_lua_websockets = NULL;
  17594. #endif
  17595. #if !defined(NO_SSL)
  17596. if (!init_ssl_ctx(ctx, new_dom)) {
  17597. /* Init SSL failed */
  17598. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17599. mg_snprintf(NULL,
  17600. NULL, /* No truncation check for error buffers */
  17601. error->text,
  17602. error->text_buffer_size,
  17603. "%s",
  17604. "Initializing SSL context failed");
  17605. }
  17606. mg_free(new_dom);
  17607. return -3;
  17608. }
  17609. #endif
  17610. /* Add element to linked list. */
  17611. mg_lock_context(ctx);
  17612. idx = 0;
  17613. dom = &(ctx->dd);
  17614. for (;;) {
  17615. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17616. dom->config[AUTHENTICATION_DOMAIN])) {
  17617. /* Domain collision */
  17618. mg_cry_ctx_internal(ctx,
  17619. "domain %s already in use",
  17620. new_dom->config[AUTHENTICATION_DOMAIN]);
  17621. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17622. mg_snprintf(NULL,
  17623. NULL, /* No truncation check for error buffers */
  17624. error->text,
  17625. error->text_buffer_size,
  17626. "Domain %s specified by %s is already in use",
  17627. new_dom->config[AUTHENTICATION_DOMAIN],
  17628. config_options[AUTHENTICATION_DOMAIN].name);
  17629. }
  17630. mg_free(new_dom);
  17631. mg_unlock_context(ctx);
  17632. return -5;
  17633. }
  17634. /* Count number of domains */
  17635. idx++;
  17636. if (dom->next == NULL) {
  17637. dom->next = new_dom;
  17638. break;
  17639. }
  17640. dom = dom->next;
  17641. }
  17642. mg_unlock_context(ctx);
  17643. /* Return domain number */
  17644. return idx;
  17645. }
  17646. int
  17647. mg_start_domain(struct mg_context *ctx, const char **options)
  17648. {
  17649. return mg_start_domain2(ctx, options, NULL);
  17650. }
  17651. #endif
  17652. /* Feature check API function */
  17653. unsigned
  17654. mg_check_feature(unsigned feature)
  17655. {
  17656. static const unsigned feature_set = 0
  17657. /* Set bits for available features according to API documentation.
  17658. * This bit mask is created at compile time, according to the active
  17659. * preprocessor defines. It is a single const value at runtime. */
  17660. #if !defined(NO_FILES)
  17661. | MG_FEATURES_FILES
  17662. #endif
  17663. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  17664. | MG_FEATURES_SSL
  17665. #endif
  17666. #if !defined(NO_CGI)
  17667. | MG_FEATURES_CGI
  17668. #endif
  17669. #if defined(USE_IPV6)
  17670. | MG_FEATURES_IPV6
  17671. #endif
  17672. #if defined(USE_WEBSOCKET)
  17673. | MG_FEATURES_WEBSOCKET
  17674. #endif
  17675. #if defined(USE_LUA)
  17676. | MG_FEATURES_LUA
  17677. #endif
  17678. #if defined(USE_DUKTAPE)
  17679. | MG_FEATURES_SSJS
  17680. #endif
  17681. #if !defined(NO_CACHING)
  17682. | MG_FEATURES_CACHE
  17683. #endif
  17684. #if defined(USE_SERVER_STATS)
  17685. | MG_FEATURES_STATS
  17686. #endif
  17687. #if defined(USE_ZLIB)
  17688. | MG_FEATURES_COMPRESSION
  17689. #endif
  17690. /* Set some extra bits not defined in the API documentation.
  17691. * These bits may change without further notice. */
  17692. #if defined(MG_LEGACY_INTERFACE)
  17693. | 0x00008000u
  17694. #endif
  17695. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17696. | 0x00004000u
  17697. #endif
  17698. #if defined(MEMORY_DEBUGGING)
  17699. | 0x00001000u
  17700. #endif
  17701. #if defined(USE_TIMERS)
  17702. | 0x00020000u
  17703. #endif
  17704. #if !defined(NO_NONCE_CHECK)
  17705. | 0x00040000u
  17706. #endif
  17707. #if !defined(NO_POPEN)
  17708. | 0x00080000u
  17709. #endif
  17710. ;
  17711. return (feature & feature_set);
  17712. }
  17713. static size_t
  17714. mg_str_append(char **dst, char *end, const char *src)
  17715. {
  17716. size_t len = strlen(src);
  17717. if (*dst != end) {
  17718. /* Append src if enough space, or close dst. */
  17719. if ((size_t)(end - *dst) > len) {
  17720. strcpy(*dst, src);
  17721. *dst += len;
  17722. } else {
  17723. *dst = end;
  17724. }
  17725. }
  17726. return len;
  17727. }
  17728. /* Get system information. It can be printed or stored by the caller.
  17729. * Return the size of available information. */
  17730. int
  17731. mg_get_system_info(char *buffer, int buflen)
  17732. {
  17733. char *end, *append_eoobj = NULL, block[256];
  17734. size_t system_info_length = 0;
  17735. #if defined(_WIN32)
  17736. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17737. #else
  17738. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17739. #endif
  17740. if ((buffer == NULL) || (buflen < 1)) {
  17741. buflen = 0;
  17742. end = buffer;
  17743. } else {
  17744. *buffer = 0;
  17745. end = buffer + buflen;
  17746. }
  17747. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17748. /* has enough space to append eoobj */
  17749. append_eoobj = buffer;
  17750. if (end) {
  17751. end -= sizeof(eoobj) - 1;
  17752. }
  17753. }
  17754. system_info_length += mg_str_append(&buffer, end, "{");
  17755. /* Server version */
  17756. {
  17757. const char *version = mg_version();
  17758. mg_snprintf(NULL,
  17759. NULL,
  17760. block,
  17761. sizeof(block),
  17762. "%s\"version\" : \"%s\"",
  17763. eol,
  17764. version);
  17765. system_info_length += mg_str_append(&buffer, end, block);
  17766. }
  17767. /* System info */
  17768. {
  17769. #if defined(_WIN32)
  17770. DWORD dwVersion = 0;
  17771. DWORD dwMajorVersion = 0;
  17772. DWORD dwMinorVersion = 0;
  17773. SYSTEM_INFO si;
  17774. GetSystemInfo(&si);
  17775. #if defined(_MSC_VER)
  17776. #pragma warning(push)
  17777. /* GetVersion was declared deprecated */
  17778. #pragma warning(disable : 4996)
  17779. #endif
  17780. dwVersion = GetVersion();
  17781. #if defined(_MSC_VER)
  17782. #pragma warning(pop)
  17783. #endif
  17784. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17785. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17786. mg_snprintf(NULL,
  17787. NULL,
  17788. block,
  17789. sizeof(block),
  17790. ",%s\"os\" : \"Windows %u.%u\"",
  17791. eol,
  17792. (unsigned)dwMajorVersion,
  17793. (unsigned)dwMinorVersion);
  17794. system_info_length += mg_str_append(&buffer, end, block);
  17795. mg_snprintf(NULL,
  17796. NULL,
  17797. block,
  17798. sizeof(block),
  17799. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17800. eol,
  17801. (unsigned)si.wProcessorArchitecture,
  17802. (unsigned)si.dwNumberOfProcessors,
  17803. (unsigned)si.dwActiveProcessorMask);
  17804. system_info_length += mg_str_append(&buffer, end, block);
  17805. #elif defined(__ZEPHYR__)
  17806. mg_snprintf(NULL,
  17807. NULL,
  17808. block,
  17809. sizeof(block),
  17810. ",%s\"os\" : \"%s %s\"",
  17811. eol,
  17812. "Zephyr OS",
  17813. ZEPHYR_VERSION);
  17814. system_info_length += mg_str_append(&buffer, end, block);
  17815. #else
  17816. struct utsname name;
  17817. memset(&name, 0, sizeof(name));
  17818. uname(&name);
  17819. mg_snprintf(NULL,
  17820. NULL,
  17821. block,
  17822. sizeof(block),
  17823. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17824. eol,
  17825. name.sysname,
  17826. name.version,
  17827. name.release,
  17828. name.machine);
  17829. system_info_length += mg_str_append(&buffer, end, block);
  17830. #endif
  17831. }
  17832. /* Features */
  17833. {
  17834. mg_snprintf(NULL,
  17835. NULL,
  17836. block,
  17837. sizeof(block),
  17838. ",%s\"features\" : %lu"
  17839. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17840. eol,
  17841. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17842. eol,
  17843. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17844. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17845. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17846. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17847. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17848. : "",
  17849. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17850. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17851. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17852. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17853. system_info_length += mg_str_append(&buffer, end, block);
  17854. #if defined(USE_LUA)
  17855. mg_snprintf(NULL,
  17856. NULL,
  17857. block,
  17858. sizeof(block),
  17859. ",%s\"lua_version\" : \"%u (%s)\"",
  17860. eol,
  17861. (unsigned)LUA_VERSION_NUM,
  17862. LUA_RELEASE);
  17863. system_info_length += mg_str_append(&buffer, end, block);
  17864. #endif
  17865. #if defined(USE_DUKTAPE)
  17866. mg_snprintf(NULL,
  17867. NULL,
  17868. block,
  17869. sizeof(block),
  17870. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17871. eol,
  17872. (unsigned)DUK_VERSION / 10000,
  17873. ((unsigned)DUK_VERSION / 100) % 100,
  17874. (unsigned)DUK_VERSION % 100);
  17875. system_info_length += mg_str_append(&buffer, end, block);
  17876. #endif
  17877. }
  17878. /* Build date */
  17879. {
  17880. #if defined(GCC_DIAGNOSTIC)
  17881. #if GCC_VERSION >= 40900
  17882. #pragma GCC diagnostic push
  17883. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17884. #pragma GCC diagnostic ignored "-Wdate-time"
  17885. #endif
  17886. #endif
  17887. #ifdef BUILD_DATE
  17888. const char *bd = BUILD_DATE;
  17889. #else
  17890. const char *bd = __DATE__;
  17891. #endif
  17892. mg_snprintf(
  17893. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  17894. #if defined(GCC_DIAGNOSTIC)
  17895. #if GCC_VERSION >= 40900
  17896. #pragma GCC diagnostic pop
  17897. #endif
  17898. #endif
  17899. system_info_length += mg_str_append(&buffer, end, block);
  17900. }
  17901. /* Compiler information */
  17902. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17903. {
  17904. #if defined(_MSC_VER)
  17905. mg_snprintf(NULL,
  17906. NULL,
  17907. block,
  17908. sizeof(block),
  17909. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17910. eol,
  17911. (unsigned)_MSC_VER,
  17912. (unsigned)_MSC_FULL_VER);
  17913. system_info_length += mg_str_append(&buffer, end, block);
  17914. #elif defined(__MINGW64__)
  17915. mg_snprintf(NULL,
  17916. NULL,
  17917. block,
  17918. sizeof(block),
  17919. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17920. eol,
  17921. (unsigned)__MINGW64_VERSION_MAJOR,
  17922. (unsigned)__MINGW64_VERSION_MINOR);
  17923. system_info_length += mg_str_append(&buffer, end, block);
  17924. mg_snprintf(NULL,
  17925. NULL,
  17926. block,
  17927. sizeof(block),
  17928. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17929. eol,
  17930. (unsigned)__MINGW32_MAJOR_VERSION,
  17931. (unsigned)__MINGW32_MINOR_VERSION);
  17932. system_info_length += mg_str_append(&buffer, end, block);
  17933. #elif defined(__MINGW32__)
  17934. mg_snprintf(NULL,
  17935. NULL,
  17936. block,
  17937. sizeof(block),
  17938. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17939. eol,
  17940. (unsigned)__MINGW32_MAJOR_VERSION,
  17941. (unsigned)__MINGW32_MINOR_VERSION);
  17942. system_info_length += mg_str_append(&buffer, end, block);
  17943. #elif defined(__clang__)
  17944. mg_snprintf(NULL,
  17945. NULL,
  17946. block,
  17947. sizeof(block),
  17948. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17949. eol,
  17950. __clang_major__,
  17951. __clang_minor__,
  17952. __clang_patchlevel__,
  17953. __clang_version__);
  17954. system_info_length += mg_str_append(&buffer, end, block);
  17955. #elif defined(__GNUC__)
  17956. mg_snprintf(NULL,
  17957. NULL,
  17958. block,
  17959. sizeof(block),
  17960. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17961. eol,
  17962. (unsigned)__GNUC__,
  17963. (unsigned)__GNUC_MINOR__,
  17964. (unsigned)__GNUC_PATCHLEVEL__);
  17965. system_info_length += mg_str_append(&buffer, end, block);
  17966. #elif defined(__INTEL_COMPILER)
  17967. mg_snprintf(NULL,
  17968. NULL,
  17969. block,
  17970. sizeof(block),
  17971. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17972. eol,
  17973. (unsigned)__INTEL_COMPILER);
  17974. system_info_length += mg_str_append(&buffer, end, block);
  17975. #elif defined(__BORLANDC__)
  17976. mg_snprintf(NULL,
  17977. NULL,
  17978. block,
  17979. sizeof(block),
  17980. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17981. eol,
  17982. (unsigned)__BORLANDC__);
  17983. system_info_length += mg_str_append(&buffer, end, block);
  17984. #elif defined(__SUNPRO_C)
  17985. mg_snprintf(NULL,
  17986. NULL,
  17987. block,
  17988. sizeof(block),
  17989. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17990. eol,
  17991. (unsigned)__SUNPRO_C);
  17992. system_info_length += mg_str_append(&buffer, end, block);
  17993. #else
  17994. mg_snprintf(NULL,
  17995. NULL,
  17996. block,
  17997. sizeof(block),
  17998. ",%s\"compiler\" : \"other\"",
  17999. eol);
  18000. system_info_length += mg_str_append(&buffer, end, block);
  18001. #endif
  18002. }
  18003. /* Determine 32/64 bit data mode.
  18004. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18005. {
  18006. mg_snprintf(NULL,
  18007. NULL,
  18008. block,
  18009. sizeof(block),
  18010. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18011. "char:%u/%u, "
  18012. "ptr:%u, size:%u, time:%u\"",
  18013. eol,
  18014. (unsigned)sizeof(short),
  18015. (unsigned)sizeof(int),
  18016. (unsigned)sizeof(long),
  18017. (unsigned)sizeof(long long),
  18018. (unsigned)sizeof(float),
  18019. (unsigned)sizeof(double),
  18020. (unsigned)sizeof(long double),
  18021. (unsigned)sizeof(char),
  18022. (unsigned)sizeof(wchar_t),
  18023. (unsigned)sizeof(void *),
  18024. (unsigned)sizeof(size_t),
  18025. (unsigned)sizeof(time_t));
  18026. system_info_length += mg_str_append(&buffer, end, block);
  18027. }
  18028. /* Terminate string */
  18029. if (append_eoobj) {
  18030. strcat(append_eoobj, eoobj);
  18031. }
  18032. system_info_length += sizeof(eoobj) - 1;
  18033. return (int)system_info_length;
  18034. }
  18035. /* Get context information. It can be printed or stored by the caller.
  18036. * Return the size of available information. */
  18037. int
  18038. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18039. {
  18040. #if defined(USE_SERVER_STATS)
  18041. char *end, *append_eoobj = NULL, block[256];
  18042. size_t context_info_length = 0;
  18043. #if defined(_WIN32)
  18044. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18045. #else
  18046. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18047. #endif
  18048. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18049. if ((buffer == NULL) || (buflen < 1)) {
  18050. buflen = 0;
  18051. end = buffer;
  18052. } else {
  18053. *buffer = 0;
  18054. end = buffer + buflen;
  18055. }
  18056. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18057. /* has enough space to append eoobj */
  18058. append_eoobj = buffer;
  18059. end -= sizeof(eoobj) - 1;
  18060. }
  18061. context_info_length += mg_str_append(&buffer, end, "{");
  18062. if (ms) { /* <-- should be always true */
  18063. /* Memory information */
  18064. int blockCount = (int)ms->blockCount;
  18065. int64_t totalMemUsed = ms->totalMemUsed;
  18066. int64_t maxMemUsed = ms->maxMemUsed;
  18067. if (totalMemUsed > maxMemUsed) {
  18068. maxMemUsed = totalMemUsed;
  18069. }
  18070. mg_snprintf(NULL,
  18071. NULL,
  18072. block,
  18073. sizeof(block),
  18074. "%s\"memory\" : {%s"
  18075. "\"blocks\" : %i,%s"
  18076. "\"used\" : %" INT64_FMT ",%s"
  18077. "\"maxUsed\" : %" INT64_FMT "%s"
  18078. "}",
  18079. eol,
  18080. eol,
  18081. blockCount,
  18082. eol,
  18083. totalMemUsed,
  18084. eol,
  18085. maxMemUsed,
  18086. eol);
  18087. context_info_length += mg_str_append(&buffer, end, block);
  18088. }
  18089. if (ctx) {
  18090. /* Declare all variables at begin of the block, to comply
  18091. * with old C standards. */
  18092. char start_time_str[64] = {0};
  18093. char now_str[64] = {0};
  18094. time_t start_time = ctx->start_time;
  18095. time_t now = time(NULL);
  18096. int64_t total_data_read, total_data_written;
  18097. int active_connections = (int)ctx->active_connections;
  18098. int max_active_connections = (int)ctx->max_active_connections;
  18099. int total_connections = (int)ctx->total_connections;
  18100. if (active_connections > max_active_connections) {
  18101. max_active_connections = active_connections;
  18102. }
  18103. if (active_connections > total_connections) {
  18104. total_connections = active_connections;
  18105. }
  18106. /* Connections information */
  18107. mg_snprintf(NULL,
  18108. NULL,
  18109. block,
  18110. sizeof(block),
  18111. ",%s\"connections\" : {%s"
  18112. "\"active\" : %i,%s"
  18113. "\"maxActive\" : %i,%s"
  18114. "\"total\" : %i%s"
  18115. "}",
  18116. eol,
  18117. eol,
  18118. active_connections,
  18119. eol,
  18120. max_active_connections,
  18121. eol,
  18122. total_connections,
  18123. eol);
  18124. context_info_length += mg_str_append(&buffer, end, block);
  18125. /* Queue information */
  18126. #if !defined(ALTERNATIVE_QUEUE)
  18127. mg_snprintf(NULL,
  18128. NULL,
  18129. block,
  18130. sizeof(block),
  18131. ",%s\"queue\" : {%s"
  18132. "\"length\" : %i,%s"
  18133. "\"filled\" : %i,%s"
  18134. "\"maxFilled\" : %i,%s"
  18135. "\"full\" : %s%s"
  18136. "}",
  18137. eol,
  18138. eol,
  18139. ctx->sq_size,
  18140. eol,
  18141. ctx->sq_head - ctx->sq_tail,
  18142. eol,
  18143. ctx->sq_max_fill,
  18144. eol,
  18145. (ctx->sq_blocked ? "true" : "false"),
  18146. eol);
  18147. context_info_length += mg_str_append(&buffer, end, block);
  18148. #endif
  18149. /* Requests information */
  18150. mg_snprintf(NULL,
  18151. NULL,
  18152. block,
  18153. sizeof(block),
  18154. ",%s\"requests\" : {%s"
  18155. "\"total\" : %lu%s"
  18156. "}",
  18157. eol,
  18158. eol,
  18159. (unsigned long)ctx->total_requests,
  18160. eol);
  18161. context_info_length += mg_str_append(&buffer, end, block);
  18162. /* Data information */
  18163. total_data_read =
  18164. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18165. total_data_written =
  18166. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18167. mg_snprintf(NULL,
  18168. NULL,
  18169. block,
  18170. sizeof(block),
  18171. ",%s\"data\" : {%s"
  18172. "\"read\" : %" INT64_FMT ",%s"
  18173. "\"written\" : %" INT64_FMT "%s"
  18174. "}",
  18175. eol,
  18176. eol,
  18177. total_data_read,
  18178. eol,
  18179. total_data_written,
  18180. eol);
  18181. context_info_length += mg_str_append(&buffer, end, block);
  18182. /* Execution time information */
  18183. gmt_time_string(start_time_str,
  18184. sizeof(start_time_str) - 1,
  18185. &start_time);
  18186. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18187. mg_snprintf(NULL,
  18188. NULL,
  18189. block,
  18190. sizeof(block),
  18191. ",%s\"time\" : {%s"
  18192. "\"uptime\" : %.0f,%s"
  18193. "\"start\" : \"%s\",%s"
  18194. "\"now\" : \"%s\"%s"
  18195. "}",
  18196. eol,
  18197. eol,
  18198. difftime(now, start_time),
  18199. eol,
  18200. start_time_str,
  18201. eol,
  18202. now_str,
  18203. eol);
  18204. context_info_length += mg_str_append(&buffer, end, block);
  18205. }
  18206. /* Terminate string */
  18207. if (append_eoobj) {
  18208. strcat(append_eoobj, eoobj);
  18209. }
  18210. context_info_length += sizeof(eoobj) - 1;
  18211. return (int)context_info_length;
  18212. #else
  18213. (void)ctx;
  18214. if ((buffer != NULL) && (buflen > 0)) {
  18215. *buffer = 0;
  18216. }
  18217. return 0;
  18218. #endif
  18219. }
  18220. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18221. /* Get connection information. It can be printed or stored by the caller.
  18222. * Return the size of available information. */
  18223. int
  18224. mg_get_connection_info(const struct mg_context *ctx,
  18225. int idx,
  18226. char *buffer,
  18227. int buflen)
  18228. {
  18229. const struct mg_connection *conn;
  18230. const struct mg_request_info *ri;
  18231. char *end, *append_eoobj = NULL, block[256];
  18232. size_t connection_info_length = 0;
  18233. int state = 0;
  18234. const char *state_str = "unknown";
  18235. #if defined(_WIN32)
  18236. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18237. #else
  18238. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18239. #endif
  18240. if ((buffer == NULL) || (buflen < 1)) {
  18241. buflen = 0;
  18242. end = buffer;
  18243. } else {
  18244. *buffer = 0;
  18245. end = buffer + buflen;
  18246. }
  18247. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18248. /* has enough space to append eoobj */
  18249. append_eoobj = buffer;
  18250. end -= sizeof(eoobj) - 1;
  18251. }
  18252. if ((ctx == NULL) || (idx < 0)) {
  18253. /* Parameter error */
  18254. return 0;
  18255. }
  18256. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18257. /* Out of range */
  18258. return 0;
  18259. }
  18260. /* Take connection [idx]. This connection is not locked in
  18261. * any way, so some other thread might use it. */
  18262. conn = (ctx->worker_connections) + idx;
  18263. /* Initialize output string */
  18264. connection_info_length += mg_str_append(&buffer, end, "{");
  18265. /* Init variables */
  18266. ri = &(conn->request_info);
  18267. #if defined(USE_SERVER_STATS)
  18268. state = conn->conn_state;
  18269. /* State as string */
  18270. switch (state) {
  18271. case 0:
  18272. state_str = "undefined";
  18273. break;
  18274. case 1:
  18275. state_str = "not used";
  18276. break;
  18277. case 2:
  18278. state_str = "init";
  18279. break;
  18280. case 3:
  18281. state_str = "ready";
  18282. break;
  18283. case 4:
  18284. state_str = "processing";
  18285. break;
  18286. case 5:
  18287. state_str = "processed";
  18288. break;
  18289. case 6:
  18290. state_str = "to close";
  18291. break;
  18292. case 7:
  18293. state_str = "closing";
  18294. break;
  18295. case 8:
  18296. state_str = "closed";
  18297. break;
  18298. case 9:
  18299. state_str = "done";
  18300. break;
  18301. }
  18302. #endif
  18303. /* Connection info */
  18304. if ((state >= 3) && (state < 9)) {
  18305. mg_snprintf(NULL,
  18306. NULL,
  18307. block,
  18308. sizeof(block),
  18309. "%s\"connection\" : {%s"
  18310. "\"remote\" : {%s"
  18311. "\"protocol\" : \"%s\",%s"
  18312. "\"addr\" : \"%s\",%s"
  18313. "\"port\" : %u%s"
  18314. "},%s"
  18315. "\"handled_requests\" : %u%s"
  18316. "}",
  18317. eol,
  18318. eol,
  18319. eol,
  18320. get_proto_name(conn),
  18321. eol,
  18322. ri->remote_addr,
  18323. eol,
  18324. ri->remote_port,
  18325. eol,
  18326. eol,
  18327. conn->handled_requests,
  18328. eol);
  18329. connection_info_length += mg_str_append(&buffer, end, block);
  18330. }
  18331. /* Request info */
  18332. if ((state >= 4) && (state < 6)) {
  18333. mg_snprintf(NULL,
  18334. NULL,
  18335. block,
  18336. sizeof(block),
  18337. "%s%s\"request_info\" : {%s"
  18338. "\"method\" : \"%s\",%s"
  18339. "\"uri\" : \"%s\",%s"
  18340. "\"query\" : %s%s%s%s"
  18341. "}",
  18342. (connection_info_length > 1 ? "," : ""),
  18343. eol,
  18344. eol,
  18345. ri->request_method,
  18346. eol,
  18347. ri->request_uri,
  18348. eol,
  18349. ri->query_string ? "\"" : "",
  18350. ri->query_string ? ri->query_string : "null",
  18351. ri->query_string ? "\"" : "",
  18352. eol);
  18353. connection_info_length += mg_str_append(&buffer, end, block);
  18354. }
  18355. /* Execution time information */
  18356. if ((state >= 2) && (state < 9)) {
  18357. char start_time_str[64] = {0};
  18358. char close_time_str[64] = {0};
  18359. time_t start_time = conn->conn_birth_time;
  18360. time_t close_time = 0;
  18361. double time_diff;
  18362. gmt_time_string(start_time_str,
  18363. sizeof(start_time_str) - 1,
  18364. &start_time);
  18365. #if defined(USE_SERVER_STATS)
  18366. close_time = conn->conn_close_time;
  18367. #endif
  18368. if (close_time != 0) {
  18369. time_diff = difftime(close_time, start_time);
  18370. gmt_time_string(close_time_str,
  18371. sizeof(close_time_str) - 1,
  18372. &close_time);
  18373. } else {
  18374. time_t now = time(NULL);
  18375. time_diff = difftime(now, start_time);
  18376. close_time_str[0] = 0; /* or use "now" ? */
  18377. }
  18378. mg_snprintf(NULL,
  18379. NULL,
  18380. block,
  18381. sizeof(block),
  18382. "%s%s\"time\" : {%s"
  18383. "\"uptime\" : %.0f,%s"
  18384. "\"start\" : \"%s\",%s"
  18385. "\"closed\" : \"%s\"%s"
  18386. "}",
  18387. (connection_info_length > 1 ? "," : ""),
  18388. eol,
  18389. eol,
  18390. time_diff,
  18391. eol,
  18392. start_time_str,
  18393. eol,
  18394. close_time_str,
  18395. eol);
  18396. connection_info_length += mg_str_append(&buffer, end, block);
  18397. }
  18398. /* Remote user name */
  18399. if ((ri->remote_user) && (state < 9)) {
  18400. mg_snprintf(NULL,
  18401. NULL,
  18402. block,
  18403. sizeof(block),
  18404. "%s%s\"user\" : {%s"
  18405. "\"name\" : \"%s\",%s"
  18406. "}",
  18407. (connection_info_length > 1 ? "," : ""),
  18408. eol,
  18409. eol,
  18410. ri->remote_user,
  18411. eol);
  18412. connection_info_length += mg_str_append(&buffer, end, block);
  18413. }
  18414. /* Data block */
  18415. if (state >= 3) {
  18416. mg_snprintf(NULL,
  18417. NULL,
  18418. block,
  18419. sizeof(block),
  18420. "%s%s\"data\" : {%s"
  18421. "\"read\" : %" INT64_FMT ",%s"
  18422. "\"written\" : %" INT64_FMT "%s"
  18423. "}",
  18424. (connection_info_length > 1 ? "," : ""),
  18425. eol,
  18426. eol,
  18427. conn->consumed_content,
  18428. eol,
  18429. conn->num_bytes_sent,
  18430. eol);
  18431. connection_info_length += mg_str_append(&buffer, end, block);
  18432. }
  18433. /* State */
  18434. mg_snprintf(NULL,
  18435. NULL,
  18436. block,
  18437. sizeof(block),
  18438. "%s%s\"state\" : \"%s\"",
  18439. (connection_info_length > 1 ? "," : ""),
  18440. eol,
  18441. state_str);
  18442. connection_info_length += mg_str_append(&buffer, end, block);
  18443. /* Terminate string */
  18444. if (append_eoobj) {
  18445. strcat(append_eoobj, eoobj);
  18446. }
  18447. connection_info_length += sizeof(eoobj) - 1;
  18448. return (int)connection_info_length;
  18449. }
  18450. #endif
  18451. /* Initialize this library. This function does not need to be thread safe.
  18452. */
  18453. unsigned
  18454. mg_init_library(unsigned features)
  18455. {
  18456. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18457. unsigned features_inited = features_to_init;
  18458. if (mg_init_library_called <= 0) {
  18459. /* Not initialized yet */
  18460. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18461. return 0;
  18462. }
  18463. }
  18464. mg_global_lock();
  18465. if (mg_init_library_called <= 0) {
  18466. #if defined(_WIN32)
  18467. int file_mutex_init = 1;
  18468. int wsa = 1;
  18469. #else
  18470. int mutexattr_init = 1;
  18471. #endif
  18472. int failed = 1;
  18473. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18474. if (key_create == 0) {
  18475. #if defined(_WIN32)
  18476. file_mutex_init =
  18477. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18478. if (file_mutex_init == 0) {
  18479. /* Start WinSock */
  18480. WSADATA data;
  18481. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18482. }
  18483. #else
  18484. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18485. if (mutexattr_init == 0) {
  18486. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18487. PTHREAD_MUTEX_RECURSIVE);
  18488. }
  18489. #endif
  18490. }
  18491. if (failed) {
  18492. #if defined(_WIN32)
  18493. if (wsa == 0) {
  18494. (void)WSACleanup();
  18495. }
  18496. if (file_mutex_init == 0) {
  18497. (void)pthread_mutex_destroy(&global_log_file_lock);
  18498. }
  18499. #else
  18500. if (mutexattr_init == 0) {
  18501. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18502. }
  18503. #endif
  18504. if (key_create == 0) {
  18505. (void)pthread_key_delete(sTlsKey);
  18506. }
  18507. mg_global_unlock();
  18508. (void)pthread_mutex_destroy(&global_lock_mutex);
  18509. return 0;
  18510. }
  18511. #if defined(USE_LUA)
  18512. lua_init_optional_libraries();
  18513. #endif
  18514. }
  18515. mg_global_unlock();
  18516. #if !defined(NO_SSL)
  18517. if (features_to_init & MG_FEATURES_SSL) {
  18518. if (!mg_ssl_initialized) {
  18519. char ebuf[128];
  18520. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18521. mg_ssl_initialized = 1;
  18522. } else {
  18523. (void)ebuf;
  18524. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18525. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18526. }
  18527. } else {
  18528. /* ssl already initialized */
  18529. }
  18530. }
  18531. #endif
  18532. mg_global_lock();
  18533. if (mg_init_library_called <= 0) {
  18534. mg_init_library_called = 1;
  18535. } else {
  18536. mg_init_library_called++;
  18537. }
  18538. mg_global_unlock();
  18539. return features_inited;
  18540. }
  18541. /* Un-initialize this library. */
  18542. unsigned
  18543. mg_exit_library(void)
  18544. {
  18545. if (mg_init_library_called <= 0) {
  18546. return 0;
  18547. }
  18548. mg_global_lock();
  18549. mg_init_library_called--;
  18550. if (mg_init_library_called == 0) {
  18551. #if !defined(NO_SSL)
  18552. if (mg_ssl_initialized) {
  18553. uninitialize_ssl();
  18554. mg_ssl_initialized = 0;
  18555. }
  18556. #endif
  18557. #if defined(_WIN32)
  18558. (void)WSACleanup();
  18559. (void)pthread_mutex_destroy(&global_log_file_lock);
  18560. #else
  18561. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18562. #endif
  18563. (void)pthread_key_delete(sTlsKey);
  18564. #if defined(USE_LUA)
  18565. lua_exit_optional_libraries();
  18566. #endif
  18567. mg_global_unlock();
  18568. (void)pthread_mutex_destroy(&global_lock_mutex);
  18569. return 1;
  18570. }
  18571. mg_global_unlock();
  18572. return 1;
  18573. }
  18574. /* End of civetweb.c */