civetweb.c 568 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210
  1. /* Copyright (c) 2013-2020 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__) || defined(__sun)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE 8096
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #ifndef DEBUG_TRACE_STREAM
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #define DEBUG_ASSERT(cond) \
  220. do { \
  221. if (!(cond)) { \
  222. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  223. exit(2); /* Exit with error */ \
  224. } \
  225. } while (0)
  226. #else
  227. #define DEBUG_ASSERT(cond)
  228. #endif /* DEBUG */
  229. #endif
  230. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  231. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  232. __attribute__((no_instrument_function));
  233. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  234. __attribute__((no_instrument_function));
  235. void
  236. __cyg_profile_func_enter(void *this_fn, void *call_site)
  237. {
  238. if ((void *)this_fn != (void *)printf) {
  239. printf("E %p %p\n", this_fn, call_site);
  240. }
  241. }
  242. void
  243. __cyg_profile_func_exit(void *this_fn, void *call_site)
  244. {
  245. if ((void *)this_fn != (void *)printf) {
  246. printf("X %p %p\n", this_fn, call_site);
  247. }
  248. }
  249. #endif
  250. #if !defined(IGNORE_UNUSED_RESULT)
  251. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  252. #endif
  253. #if defined(__GNUC__) || defined(__MINGW32__)
  254. /* GCC unused function attribute seems fundamentally broken.
  255. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  256. * OR UNUSED" for individual functions failed.
  257. * Either the compiler creates an "unused-function" warning if a
  258. * function is not marked with __attribute__((unused)).
  259. * On the other hand, if the function is marked with this attribute,
  260. * but is used, the compiler raises a completely idiotic
  261. * "used-but-marked-unused" warning - and
  262. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  263. * raises error: unknown option after "#pragma GCC diagnostic".
  264. * Disable this warning completely, until the GCC guys sober up
  265. * again.
  266. */
  267. #pragma GCC diagnostic ignored "-Wunused-function"
  268. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  269. #else
  270. #define FUNCTION_MAY_BE_UNUSED
  271. #endif
  272. /* Some ANSI #includes are not available on Windows CE */
  273. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  274. #include <errno.h>
  275. #include <fcntl.h>
  276. #include <signal.h>
  277. #include <stdlib.h>
  278. #include <sys/stat.h>
  279. #include <sys/types.h>
  280. #endif /* !_WIN32_WCE */
  281. #if defined(__clang__)
  282. /* When using -Weverything, clang does not accept it's own headers
  283. * in a release build configuration. Disable what is too much in
  284. * -Weverything. */
  285. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  286. #endif
  287. #if defined(__GNUC__) || defined(__MINGW32__)
  288. /* Who on earth came to the conclusion, using __DATE__ should rise
  289. * an "expansion of date or time macro is not reproducible"
  290. * warning. That's exactly what was intended by using this macro.
  291. * Just disable this nonsense warning. */
  292. /* And disabling them does not work either:
  293. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  294. * #pragma clang diagnostic ignored "-Wdate-time"
  295. * So we just have to disable ALL warnings for some lines
  296. * of code.
  297. * This seems to be a known GCC bug, not resolved since 2012:
  298. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  299. */
  300. #endif
  301. #if defined(__MACH__) /* Apple OSX section */
  302. #if defined(__clang__)
  303. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  304. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  305. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  306. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  307. #endif
  308. #endif
  309. #define CLOCK_MONOTONIC (1)
  310. #define CLOCK_REALTIME (2)
  311. #include <mach/clock.h>
  312. #include <mach/mach.h>
  313. #include <mach/mach_time.h>
  314. #include <sys/errno.h>
  315. #include <sys/time.h>
  316. /* clock_gettime is not implemented on OSX prior to 10.12 */
  317. static int
  318. _civet_clock_gettime(int clk_id, struct timespec *t)
  319. {
  320. memset(t, 0, sizeof(*t));
  321. if (clk_id == CLOCK_REALTIME) {
  322. struct timeval now;
  323. int rv = gettimeofday(&now, NULL);
  324. if (rv) {
  325. return rv;
  326. }
  327. t->tv_sec = now.tv_sec;
  328. t->tv_nsec = now.tv_usec * 1000;
  329. return 0;
  330. } else if (clk_id == CLOCK_MONOTONIC) {
  331. static uint64_t clock_start_time = 0;
  332. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  333. uint64_t now = mach_absolute_time();
  334. if (clock_start_time == 0) {
  335. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  336. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  337. /* appease "unused variable" warning for release builds */
  338. (void)mach_status;
  339. clock_start_time = now;
  340. }
  341. now = (uint64_t)((double)(now - clock_start_time)
  342. * (double)timebase_ifo.numer
  343. / (double)timebase_ifo.denom);
  344. t->tv_sec = now / 1000000000;
  345. t->tv_nsec = now % 1000000000;
  346. return 0;
  347. }
  348. return -1; /* EINVAL - Clock ID is unknown */
  349. }
  350. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  351. #if defined(__CLOCK_AVAILABILITY)
  352. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  353. * declared but it may be NULL at runtime. So we need to check before using
  354. * it. */
  355. static int
  356. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  357. {
  358. if (clock_gettime) {
  359. return clock_gettime(clk_id, t);
  360. }
  361. return _civet_clock_gettime(clk_id, t);
  362. }
  363. #define clock_gettime _civet_safe_clock_gettime
  364. #else
  365. #define clock_gettime _civet_clock_gettime
  366. #endif
  367. #endif
  368. /********************************************************************/
  369. /* CivetWeb configuration defines */
  370. /********************************************************************/
  371. /* Maximum number of threads that can be configured.
  372. * The number of threads actually created depends on the "num_threads"
  373. * configuration parameter, but this is the upper limit. */
  374. #if !defined(MAX_WORKER_THREADS)
  375. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  376. #endif
  377. /* Timeout interval for select/poll calls.
  378. * The timeouts depend on "*_timeout_ms" configuration values, but long
  379. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  380. * This reduces the time required to stop the server. */
  381. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  382. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  383. #endif
  384. /* Do not try to compress files smaller than this limit. */
  385. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  386. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  387. #endif
  388. #if !defined(PASSWORDS_FILE_NAME)
  389. #define PASSWORDS_FILE_NAME ".htpasswd"
  390. #endif
  391. /* Initial buffer size for all CGI environment variables. In case there is
  392. * not enough space, another block is allocated. */
  393. #if !defined(CGI_ENVIRONMENT_SIZE)
  394. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  395. #endif
  396. /* Maximum number of environment variables. */
  397. #if !defined(MAX_CGI_ENVIR_VARS)
  398. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  399. #endif
  400. /* General purpose buffer size. */
  401. #if !defined(MG_BUF_LEN) /* in bytes */
  402. #define MG_BUF_LEN (1024 * 8)
  403. #endif
  404. /********************************************************************/
  405. /* Helper makros */
  406. #if !defined(ARRAY_SIZE)
  407. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  408. #endif
  409. #include <stdint.h>
  410. /* Standard defines */
  411. #if !defined(INT64_MAX)
  412. #define INT64_MAX (9223372036854775807)
  413. #endif
  414. #define SHUTDOWN_RD (0)
  415. #define SHUTDOWN_WR (1)
  416. #define SHUTDOWN_BOTH (2)
  417. mg_static_assert(MAX_WORKER_THREADS >= 1,
  418. "worker threads must be a positive number");
  419. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  420. "size_t data type size check");
  421. #if defined(_WIN32) /* WINDOWS include block */
  422. #include <malloc.h> /* *alloc( */
  423. #include <stdlib.h> /* *alloc( */
  424. #include <time.h> /* struct timespec */
  425. #include <windows.h>
  426. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  427. #include <ws2tcpip.h>
  428. typedef const char *SOCK_OPT_TYPE;
  429. #if !defined(PATH_MAX)
  430. #define W_PATH_MAX (MAX_PATH)
  431. /* at most three UTF-8 chars per wchar_t */
  432. #define PATH_MAX (W_PATH_MAX * 3)
  433. #else
  434. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  435. #endif
  436. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  437. #if !defined(_IN_PORT_T)
  438. #if !defined(in_port_t)
  439. #define in_port_t u_short
  440. #endif
  441. #endif
  442. #if !defined(_WIN32_WCE)
  443. #include <direct.h>
  444. #include <io.h>
  445. #include <process.h>
  446. #else /* _WIN32_WCE */
  447. #define NO_CGI /* WinCE has no pipes */
  448. #define NO_POPEN /* WinCE has no popen */
  449. typedef long off_t;
  450. #define errno ((int)(GetLastError()))
  451. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  452. #endif /* _WIN32_WCE */
  453. #define MAKEUQUAD(lo, hi) \
  454. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  455. #define RATE_DIFF (10000000) /* 100 nsecs */
  456. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  457. #define SYS2UNIX_TIME(lo, hi) \
  458. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  459. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  460. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  461. * Also use _strtoui64 on modern M$ compilers */
  462. #if defined(_MSC_VER)
  463. #if (_MSC_VER < 1300)
  464. #define STRX(x) #x
  465. #define STR(x) STRX(x)
  466. #define __func__ __FILE__ ":" STR(__LINE__)
  467. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  468. #define strtoll(x, y, z) (_atoi64(x))
  469. #else
  470. #define __func__ __FUNCTION__
  471. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  472. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  473. #endif
  474. #endif /* _MSC_VER */
  475. #define ERRNO ((int)(GetLastError()))
  476. #define NO_SOCKLEN_T
  477. #if defined(_WIN64) || defined(__MINGW64__)
  478. #if !defined(SSL_LIB)
  479. #if defined(OPENSSL_API_1_1)
  480. #define SSL_LIB "libssl-1_1-x64.dll"
  481. #else /* OPENSSL_API_1_1 */
  482. #define SSL_LIB "ssleay64.dll"
  483. #endif /* OPENSSL_API_1_1 */
  484. #endif /* SSL_LIB */
  485. #if !defined(CRYPTO_LIB)
  486. #if defined(OPENSSL_API_1_1)
  487. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  488. #else /* OPENSSL_API_1_1 */
  489. #define CRYPTO_LIB "libeay64.dll"
  490. #endif /* OPENSSL_API_1_1 */
  491. #endif /* CRYPTO_LIB */
  492. #else /* defined(_WIN64) || defined(__MINGW64__) */
  493. #if !defined(SSL_LIB)
  494. #if defined(OPENSSL_API_1_1)
  495. #define SSL_LIB "libssl-1_1.dll"
  496. #else
  497. #define SSL_LIB "ssleay32.dll"
  498. #endif
  499. #endif /* SSL_LIB */
  500. #if !defined(CRYPTO_LIB)
  501. #if defined(OPENSSL_API_1_1)
  502. #define CRYPTO_LIB "libcrypto-1_1.dll"
  503. #else
  504. #define CRYPTO_LIB "libeay32.dll"
  505. #endif
  506. #endif /* CRYPTO_LIB */
  507. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  508. #define O_NONBLOCK (0)
  509. #if !defined(W_OK)
  510. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  511. #endif
  512. #define _POSIX_
  513. #define INT64_FMT "I64d"
  514. #define UINT64_FMT "I64u"
  515. #define WINCDECL __cdecl
  516. #define vsnprintf_impl _vsnprintf
  517. #define access _access
  518. #define mg_sleep(x) (Sleep(x))
  519. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  520. #if !defined(popen)
  521. #define popen(x, y) (_popen(x, y))
  522. #endif
  523. #if !defined(pclose)
  524. #define pclose(x) (_pclose(x))
  525. #endif
  526. #define close(x) (_close(x))
  527. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  528. #define RTLD_LAZY (0)
  529. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  530. #define fdopen(x, y) (_fdopen((x), (y)))
  531. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  532. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  533. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  534. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  535. #define sleep(x) (Sleep((x)*1000))
  536. #define rmdir(x) (_rmdir(x))
  537. #if defined(_WIN64) || !defined(__MINGW32__)
  538. /* Only MinGW 32 bit is missing this function */
  539. #define timegm(x) (_mkgmtime(x))
  540. #else
  541. time_t timegm(struct tm *tm);
  542. #define NEED_TIMEGM
  543. #endif
  544. #if !defined(fileno)
  545. #define fileno(x) (_fileno(x))
  546. #endif /* !fileno MINGW #defines fileno */
  547. typedef struct {
  548. CRITICAL_SECTION sec; /* Immovable */
  549. } pthread_mutex_t;
  550. typedef DWORD pthread_key_t;
  551. typedef HANDLE pthread_t;
  552. typedef struct {
  553. pthread_mutex_t threadIdSec;
  554. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  555. } pthread_cond_t;
  556. #if !defined(__clockid_t_defined)
  557. typedef DWORD clockid_t;
  558. #endif
  559. #if !defined(CLOCK_MONOTONIC)
  560. #define CLOCK_MONOTONIC (1)
  561. #endif
  562. #if !defined(CLOCK_REALTIME)
  563. #define CLOCK_REALTIME (2)
  564. #endif
  565. #if !defined(CLOCK_THREAD)
  566. #define CLOCK_THREAD (3)
  567. #endif
  568. #if !defined(CLOCK_PROCESS)
  569. #define CLOCK_PROCESS (4)
  570. #endif
  571. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  572. #define _TIMESPEC_DEFINED
  573. #endif
  574. #if !defined(_TIMESPEC_DEFINED)
  575. struct timespec {
  576. time_t tv_sec; /* seconds */
  577. long tv_nsec; /* nanoseconds */
  578. };
  579. #endif
  580. #if !defined(WIN_PTHREADS_TIME_H)
  581. #define MUST_IMPLEMENT_CLOCK_GETTIME
  582. #endif
  583. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  584. #define clock_gettime mg_clock_gettime
  585. static int
  586. clock_gettime(clockid_t clk_id, struct timespec *tp)
  587. {
  588. FILETIME ft;
  589. ULARGE_INTEGER li, li2;
  590. BOOL ok = FALSE;
  591. double d;
  592. static double perfcnt_per_sec = 0.0;
  593. static BOOL initialized = FALSE;
  594. if (!initialized) {
  595. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  596. perfcnt_per_sec = 1.0 / li.QuadPart;
  597. initialized = TRUE;
  598. }
  599. if (tp) {
  600. memset(tp, 0, sizeof(*tp));
  601. if (clk_id == CLOCK_REALTIME) {
  602. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  603. GetSystemTimeAsFileTime(&ft);
  604. li.LowPart = ft.dwLowDateTime;
  605. li.HighPart = ft.dwHighDateTime;
  606. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  607. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  608. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  609. ok = TRUE;
  610. /* END: CLOCK_REALTIME */
  611. } else if (clk_id == CLOCK_MONOTONIC) {
  612. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  613. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  614. d = li.QuadPart * perfcnt_per_sec;
  615. tp->tv_sec = (time_t)d;
  616. d -= (double)tp->tv_sec;
  617. tp->tv_nsec = (long)(d * 1.0E9);
  618. ok = TRUE;
  619. /* END: CLOCK_MONOTONIC */
  620. } else if (clk_id == CLOCK_THREAD) {
  621. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  622. FILETIME t_create, t_exit, t_kernel, t_user;
  623. if (GetThreadTimes(GetCurrentThread(),
  624. &t_create,
  625. &t_exit,
  626. &t_kernel,
  627. &t_user)) {
  628. li.LowPart = t_user.dwLowDateTime;
  629. li.HighPart = t_user.dwHighDateTime;
  630. li2.LowPart = t_kernel.dwLowDateTime;
  631. li2.HighPart = t_kernel.dwHighDateTime;
  632. li.QuadPart += li2.QuadPart;
  633. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  634. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  635. ok = TRUE;
  636. }
  637. /* END: CLOCK_THREAD */
  638. } else if (clk_id == CLOCK_PROCESS) {
  639. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  640. FILETIME t_create, t_exit, t_kernel, t_user;
  641. if (GetProcessTimes(GetCurrentProcess(),
  642. &t_create,
  643. &t_exit,
  644. &t_kernel,
  645. &t_user)) {
  646. li.LowPart = t_user.dwLowDateTime;
  647. li.HighPart = t_user.dwHighDateTime;
  648. li2.LowPart = t_kernel.dwLowDateTime;
  649. li2.HighPart = t_kernel.dwHighDateTime;
  650. li.QuadPart += li2.QuadPart;
  651. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  652. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  653. ok = TRUE;
  654. }
  655. /* END: CLOCK_PROCESS */
  656. } else {
  657. /* BEGIN: unknown clock */
  658. /* ok = FALSE; already set by init */
  659. /* END: unknown clock */
  660. }
  661. }
  662. return ok ? 0 : -1;
  663. }
  664. #endif
  665. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  666. static int pthread_mutex_lock(pthread_mutex_t *);
  667. static int pthread_mutex_unlock(pthread_mutex_t *);
  668. static void path_to_unicode(const struct mg_connection *conn,
  669. const char *path,
  670. wchar_t *wbuf,
  671. size_t wbuf_len);
  672. /* All file operations need to be rewritten to solve #246. */
  673. struct mg_file;
  674. static const char *
  675. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  676. /* POSIX dirent interface */
  677. struct dirent {
  678. char d_name[PATH_MAX];
  679. };
  680. typedef struct DIR {
  681. HANDLE handle;
  682. WIN32_FIND_DATAW info;
  683. struct dirent result;
  684. } DIR;
  685. #if defined(HAVE_POLL)
  686. #define mg_pollfd pollfd
  687. #else
  688. struct mg_pollfd {
  689. SOCKET fd;
  690. short events;
  691. short revents;
  692. };
  693. #endif
  694. /* Mark required libraries */
  695. #if defined(_MSC_VER)
  696. #pragma comment(lib, "Ws2_32.lib")
  697. #endif
  698. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  699. #include <inttypes.h>
  700. typedef const void *SOCK_OPT_TYPE;
  701. #if defined(ANDROID)
  702. typedef unsigned short int in_port_t;
  703. #endif
  704. #if !defined(__ZEPHYR__)
  705. #include <arpa/inet.h>
  706. #include <ctype.h>
  707. #include <dirent.h>
  708. #include <grp.h>
  709. #include <limits.h>
  710. #include <netdb.h>
  711. #include <netinet/in.h>
  712. #include <netinet/tcp.h>
  713. #include <pthread.h>
  714. #include <pwd.h>
  715. #include <stdarg.h>
  716. #include <stddef.h>
  717. #include <stdio.h>
  718. #include <stdlib.h>
  719. #include <string.h>
  720. #include <sys/poll.h>
  721. #include <sys/socket.h>
  722. #include <sys/time.h>
  723. #include <sys/utsname.h>
  724. #include <sys/wait.h>
  725. #include <time.h>
  726. #include <unistd.h>
  727. #endif
  728. #define vsnprintf_impl vsnprintf
  729. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  730. #include <dlfcn.h>
  731. #endif
  732. #if defined(__MACH__)
  733. #define SSL_LIB "libssl.dylib"
  734. #define CRYPTO_LIB "libcrypto.dylib"
  735. #else
  736. #if !defined(SSL_LIB)
  737. #define SSL_LIB "libssl.so"
  738. #endif
  739. #if !defined(CRYPTO_LIB)
  740. #define CRYPTO_LIB "libcrypto.so"
  741. #endif
  742. #endif
  743. #if !defined(O_BINARY)
  744. #define O_BINARY (0)
  745. #endif /* O_BINARY */
  746. #define closesocket(a) (close(a))
  747. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  748. #define mg_remove(conn, x) (remove(x))
  749. #define mg_sleep(x) (usleep((x)*1000))
  750. #define mg_opendir(conn, x) (opendir(x))
  751. #define mg_closedir(x) (closedir(x))
  752. #define mg_readdir(x) (readdir(x))
  753. #define ERRNO (errno)
  754. #define INVALID_SOCKET (-1)
  755. #define INT64_FMT PRId64
  756. #define UINT64_FMT PRIu64
  757. typedef int SOCKET;
  758. #define WINCDECL
  759. #if defined(__hpux)
  760. /* HPUX 11 does not have monotonic, fall back to realtime */
  761. #if !defined(CLOCK_MONOTONIC)
  762. #define CLOCK_MONOTONIC CLOCK_REALTIME
  763. #endif
  764. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  765. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  766. * the prototypes use int* rather than socklen_t* which matches the
  767. * actual library expectation. When called with the wrong size arg
  768. * accept() returns a zero client inet addr and check_acl() always
  769. * fails. Since socklen_t is widely used below, just force replace
  770. * their typedef with int. - DTL
  771. */
  772. #define socklen_t int
  773. #endif /* hpux */
  774. #define mg_pollfd pollfd
  775. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  776. /* In case our C library is missing "timegm", provide an implementation */
  777. #if defined(NEED_TIMEGM)
  778. static inline int
  779. is_leap(int y)
  780. {
  781. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  782. }
  783. static inline int
  784. count_leap(int y)
  785. {
  786. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  787. }
  788. time_t
  789. timegm(struct tm *tm)
  790. {
  791. static const unsigned short ydays[] = {
  792. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  793. int year = tm->tm_year + 1900;
  794. int mon = tm->tm_mon;
  795. int mday = tm->tm_mday - 1;
  796. int hour = tm->tm_hour;
  797. int min = tm->tm_min;
  798. int sec = tm->tm_sec;
  799. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  800. || (mday >= ydays[mon + 1] - ydays[mon]
  801. + (mon == 1 && is_leap(year) ? 1 : 0))
  802. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  803. return -1;
  804. time_t res = year - 1970;
  805. res *= 365;
  806. res += mday;
  807. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  808. res += count_leap(year);
  809. res *= 24;
  810. res += hour;
  811. res *= 60;
  812. res += min;
  813. res *= 60;
  814. res += sec;
  815. return res;
  816. }
  817. #endif /* NEED_TIMEGM */
  818. /* va_copy should always be a macro, C99 and C++11 - DTL */
  819. #if !defined(va_copy)
  820. #define va_copy(x, y) ((x) = (y))
  821. #endif
  822. #if defined(_WIN32)
  823. /* Create substitutes for POSIX functions in Win32. */
  824. #if defined(GCC_DIAGNOSTIC)
  825. /* Show no warning in case system functions are not used. */
  826. #pragma GCC diagnostic push
  827. #pragma GCC diagnostic ignored "-Wunused-function"
  828. #endif
  829. static pthread_mutex_t global_log_file_lock;
  830. FUNCTION_MAY_BE_UNUSED
  831. static DWORD
  832. pthread_self(void)
  833. {
  834. return GetCurrentThreadId();
  835. }
  836. FUNCTION_MAY_BE_UNUSED
  837. static int
  838. pthread_key_create(
  839. pthread_key_t *key,
  840. void (*_ignored)(void *) /* destructor not supported for Windows */
  841. )
  842. {
  843. (void)_ignored;
  844. if ((key != 0)) {
  845. *key = TlsAlloc();
  846. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  847. }
  848. return -2;
  849. }
  850. FUNCTION_MAY_BE_UNUSED
  851. static int
  852. pthread_key_delete(pthread_key_t key)
  853. {
  854. return TlsFree(key) ? 0 : 1;
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static int
  858. pthread_setspecific(pthread_key_t key, void *value)
  859. {
  860. return TlsSetValue(key, value) ? 0 : 1;
  861. }
  862. FUNCTION_MAY_BE_UNUSED
  863. static void *
  864. pthread_getspecific(pthread_key_t key)
  865. {
  866. return TlsGetValue(key);
  867. }
  868. #if defined(GCC_DIAGNOSTIC)
  869. /* Enable unused function warning again */
  870. #pragma GCC diagnostic pop
  871. #endif
  872. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  873. #else
  874. static pthread_mutexattr_t pthread_mutex_attr;
  875. #endif /* _WIN32 */
  876. #if defined(_WIN32_WCE)
  877. /* Create substitutes for POSIX functions in Win32. */
  878. #if defined(GCC_DIAGNOSTIC)
  879. /* Show no warning in case system functions are not used. */
  880. #pragma GCC diagnostic push
  881. #pragma GCC diagnostic ignored "-Wunused-function"
  882. #endif
  883. FUNCTION_MAY_BE_UNUSED
  884. static time_t
  885. time(time_t *ptime)
  886. {
  887. time_t t;
  888. SYSTEMTIME st;
  889. FILETIME ft;
  890. GetSystemTime(&st);
  891. SystemTimeToFileTime(&st, &ft);
  892. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  893. if (ptime != NULL) {
  894. *ptime = t;
  895. }
  896. return t;
  897. }
  898. FUNCTION_MAY_BE_UNUSED
  899. static struct tm *
  900. localtime_s(const time_t *ptime, struct tm *ptm)
  901. {
  902. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  903. FILETIME ft, lft;
  904. SYSTEMTIME st;
  905. TIME_ZONE_INFORMATION tzinfo;
  906. if (ptm == NULL) {
  907. return NULL;
  908. }
  909. *(int64_t *)&ft = t;
  910. FileTimeToLocalFileTime(&ft, &lft);
  911. FileTimeToSystemTime(&lft, &st);
  912. ptm->tm_year = st.wYear - 1900;
  913. ptm->tm_mon = st.wMonth - 1;
  914. ptm->tm_wday = st.wDayOfWeek;
  915. ptm->tm_mday = st.wDay;
  916. ptm->tm_hour = st.wHour;
  917. ptm->tm_min = st.wMinute;
  918. ptm->tm_sec = st.wSecond;
  919. ptm->tm_yday = 0; /* hope nobody uses this */
  920. ptm->tm_isdst =
  921. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  922. return ptm;
  923. }
  924. FUNCTION_MAY_BE_UNUSED
  925. static struct tm *
  926. gmtime_s(const time_t *ptime, struct tm *ptm)
  927. {
  928. /* FIXME(lsm): fix this. */
  929. return localtime_s(ptime, ptm);
  930. }
  931. static int mg_atomic_inc(volatile int *addr);
  932. static struct tm tm_array[MAX_WORKER_THREADS];
  933. static int tm_index = 0;
  934. FUNCTION_MAY_BE_UNUSED
  935. static struct tm *
  936. localtime(const time_t *ptime)
  937. {
  938. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  939. return localtime_s(ptime, tm_array + i);
  940. }
  941. FUNCTION_MAY_BE_UNUSED
  942. static struct tm *
  943. gmtime(const time_t *ptime)
  944. {
  945. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  946. return gmtime_s(ptime, tm_array + i);
  947. }
  948. FUNCTION_MAY_BE_UNUSED
  949. static size_t
  950. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  951. {
  952. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  953. * for WinCE"); */
  954. return 0;
  955. }
  956. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  957. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  958. #define remove(f) mg_remove(NULL, f)
  959. FUNCTION_MAY_BE_UNUSED
  960. static int
  961. rename(const char *a, const char *b)
  962. {
  963. wchar_t wa[W_PATH_MAX];
  964. wchar_t wb[W_PATH_MAX];
  965. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  966. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  967. return MoveFileW(wa, wb) ? 0 : -1;
  968. }
  969. struct stat {
  970. int64_t st_size;
  971. time_t st_mtime;
  972. };
  973. FUNCTION_MAY_BE_UNUSED
  974. static int
  975. stat(const char *name, struct stat *st)
  976. {
  977. wchar_t wbuf[W_PATH_MAX];
  978. WIN32_FILE_ATTRIBUTE_DATA attr;
  979. time_t creation_time, write_time;
  980. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  981. memset(&attr, 0, sizeof(attr));
  982. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  983. st->st_size =
  984. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  985. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  986. attr.ftLastWriteTime.dwHighDateTime);
  987. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  988. attr.ftCreationTime.dwHighDateTime);
  989. if (creation_time > write_time) {
  990. st->st_mtime = creation_time;
  991. } else {
  992. st->st_mtime = write_time;
  993. }
  994. return 0;
  995. }
  996. #define access(x, a) 1 /* not required anyway */
  997. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  998. /* Values from errno.h in Windows SDK (Visual Studio). */
  999. #define EEXIST 17
  1000. #define EACCES 13
  1001. #define ENOENT 2
  1002. #if defined(GCC_DIAGNOSTIC)
  1003. /* Enable unused function warning again */
  1004. #pragma GCC diagnostic pop
  1005. #endif
  1006. #endif /* defined(_WIN32_WCE) */
  1007. #if defined(GCC_DIAGNOSTIC)
  1008. /* Show no warning in case system functions are not used. */
  1009. #pragma GCC diagnostic push
  1010. #pragma GCC diagnostic ignored "-Wunused-function"
  1011. #endif /* defined(GCC_DIAGNOSTIC) */
  1012. #if defined(__clang__)
  1013. /* Show no warning in case system functions are not used. */
  1014. #pragma clang diagnostic push
  1015. #pragma clang diagnostic ignored "-Wunused-function"
  1016. #endif
  1017. static pthread_mutex_t global_lock_mutex;
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static void
  1020. mg_global_lock(void)
  1021. {
  1022. (void)pthread_mutex_lock(&global_lock_mutex);
  1023. }
  1024. FUNCTION_MAY_BE_UNUSED
  1025. static void
  1026. mg_global_unlock(void)
  1027. {
  1028. (void)pthread_mutex_unlock(&global_lock_mutex);
  1029. }
  1030. FUNCTION_MAY_BE_UNUSED
  1031. static int
  1032. mg_atomic_inc(volatile int *addr)
  1033. {
  1034. int ret;
  1035. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1036. /* Depending on the SDK, this function uses either
  1037. * (volatile unsigned int *) or (volatile LONG *),
  1038. * so whatever you use, the other SDK is likely to raise a warning. */
  1039. ret = InterlockedIncrement((volatile long *)addr);
  1040. #elif defined(__GNUC__) \
  1041. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1042. && !defined(NO_ATOMICS)
  1043. ret = __sync_add_and_fetch(addr, 1);
  1044. #else
  1045. mg_global_lock();
  1046. ret = (++(*addr));
  1047. mg_global_unlock();
  1048. #endif
  1049. return ret;
  1050. }
  1051. FUNCTION_MAY_BE_UNUSED
  1052. static int
  1053. mg_atomic_dec(volatile int *addr)
  1054. {
  1055. int ret;
  1056. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1057. /* Depending on the SDK, this function uses either
  1058. * (volatile unsigned int *) or (volatile LONG *),
  1059. * so whatever you use, the other SDK is likely to raise a warning. */
  1060. ret = InterlockedDecrement((volatile long *)addr);
  1061. #elif defined(__GNUC__) \
  1062. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1063. && !defined(NO_ATOMICS)
  1064. ret = __sync_sub_and_fetch(addr, 1);
  1065. #else
  1066. mg_global_lock();
  1067. ret = (--(*addr));
  1068. mg_global_unlock();
  1069. #endif
  1070. return ret;
  1071. }
  1072. #if defined(USE_SERVER_STATS)
  1073. static int64_t
  1074. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1075. {
  1076. int64_t ret;
  1077. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1078. ret = InterlockedAdd64(addr, value);
  1079. #elif defined(__GNUC__) \
  1080. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1081. && !defined(NO_ATOMICS)
  1082. ret = __sync_add_and_fetch(addr, value);
  1083. #else
  1084. mg_global_lock();
  1085. *addr += value;
  1086. ret = (*addr);
  1087. mg_global_unlock();
  1088. #endif
  1089. return ret;
  1090. }
  1091. #endif
  1092. #if defined(GCC_DIAGNOSTIC)
  1093. /* Show no warning in case system functions are not used. */
  1094. #pragma GCC diagnostic pop
  1095. #endif /* defined(GCC_DIAGNOSTIC) */
  1096. #if defined(__clang__)
  1097. /* Show no warning in case system functions are not used. */
  1098. #pragma clang diagnostic pop
  1099. #endif
  1100. #if defined(USE_SERVER_STATS)
  1101. struct mg_memory_stat {
  1102. volatile int64_t totalMemUsed;
  1103. volatile int64_t maxMemUsed;
  1104. volatile int blockCount;
  1105. };
  1106. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1107. static void *
  1108. mg_malloc_ex(size_t size,
  1109. struct mg_context *ctx,
  1110. const char *file,
  1111. unsigned line)
  1112. {
  1113. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1114. void *memory = 0;
  1115. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1116. #if defined(MEMORY_DEBUGGING)
  1117. char mallocStr[256];
  1118. #else
  1119. (void)file;
  1120. (void)line;
  1121. #endif
  1122. if (data) {
  1123. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1124. if (mmem > mstat->maxMemUsed) {
  1125. /* could use atomic compare exchange, but this
  1126. * seems overkill for statistics data */
  1127. mstat->maxMemUsed = mmem;
  1128. }
  1129. mg_atomic_inc(&mstat->blockCount);
  1130. ((uintptr_t *)data)[0] = size;
  1131. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1132. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1133. }
  1134. #if defined(MEMORY_DEBUGGING)
  1135. sprintf(mallocStr,
  1136. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1137. memory,
  1138. (unsigned long)size,
  1139. (unsigned long)mstat->totalMemUsed,
  1140. (unsigned long)mstat->blockCount,
  1141. file,
  1142. line);
  1143. #if defined(_WIN32)
  1144. OutputDebugStringA(mallocStr);
  1145. #else
  1146. DEBUG_TRACE("%s", mallocStr);
  1147. #endif
  1148. #endif
  1149. return memory;
  1150. }
  1151. static void *
  1152. mg_calloc_ex(size_t count,
  1153. size_t size,
  1154. struct mg_context *ctx,
  1155. const char *file,
  1156. unsigned line)
  1157. {
  1158. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1159. if (data) {
  1160. memset(data, 0, size * count);
  1161. }
  1162. return data;
  1163. }
  1164. static void
  1165. mg_free_ex(void *memory, const char *file, unsigned line)
  1166. {
  1167. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1168. #if defined(MEMORY_DEBUGGING)
  1169. char mallocStr[256];
  1170. #else
  1171. (void)file;
  1172. (void)line;
  1173. #endif
  1174. if (memory) {
  1175. uintptr_t size = ((uintptr_t *)data)[0];
  1176. struct mg_memory_stat *mstat =
  1177. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1178. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1179. mg_atomic_dec(&mstat->blockCount);
  1180. #if defined(MEMORY_DEBUGGING)
  1181. sprintf(mallocStr,
  1182. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1183. memory,
  1184. (unsigned long)size,
  1185. (unsigned long)mstat->totalMemUsed,
  1186. (unsigned long)mstat->blockCount,
  1187. file,
  1188. line);
  1189. #if defined(_WIN32)
  1190. OutputDebugStringA(mallocStr);
  1191. #else
  1192. DEBUG_TRACE("%s", mallocStr);
  1193. #endif
  1194. #endif
  1195. free(data);
  1196. }
  1197. }
  1198. static void *
  1199. mg_realloc_ex(void *memory,
  1200. size_t newsize,
  1201. struct mg_context *ctx,
  1202. const char *file,
  1203. unsigned line)
  1204. {
  1205. void *data;
  1206. void *_realloc;
  1207. uintptr_t oldsize;
  1208. #if defined(MEMORY_DEBUGGING)
  1209. char mallocStr[256];
  1210. #else
  1211. (void)file;
  1212. (void)line;
  1213. #endif
  1214. if (newsize) {
  1215. if (memory) {
  1216. /* Reallocate existing block */
  1217. struct mg_memory_stat *mstat;
  1218. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1219. oldsize = ((uintptr_t *)data)[0];
  1220. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1221. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1222. if (_realloc) {
  1223. data = _realloc;
  1224. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1225. #if defined(MEMORY_DEBUGGING)
  1226. sprintf(mallocStr,
  1227. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1228. memory,
  1229. (unsigned long)oldsize,
  1230. (unsigned long)mstat->totalMemUsed,
  1231. (unsigned long)mstat->blockCount,
  1232. file,
  1233. line);
  1234. #if defined(_WIN32)
  1235. OutputDebugStringA(mallocStr);
  1236. #else
  1237. DEBUG_TRACE("%s", mallocStr);
  1238. #endif
  1239. #endif
  1240. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1241. #if defined(MEMORY_DEBUGGING)
  1242. sprintf(mallocStr,
  1243. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1244. memory,
  1245. (unsigned long)newsize,
  1246. (unsigned long)mstat->totalMemUsed,
  1247. (unsigned long)mstat->blockCount,
  1248. file,
  1249. line);
  1250. #if defined(_WIN32)
  1251. OutputDebugStringA(mallocStr);
  1252. #else
  1253. DEBUG_TRACE("%s", mallocStr);
  1254. #endif
  1255. #endif
  1256. *(uintptr_t *)data = newsize;
  1257. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1258. } else {
  1259. #if defined(MEMORY_DEBUGGING)
  1260. #if defined(_WIN32)
  1261. OutputDebugStringA("MEM: realloc failed\n");
  1262. #else
  1263. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1264. #endif
  1265. #endif
  1266. return _realloc;
  1267. }
  1268. } else {
  1269. /* Allocate new block */
  1270. data = mg_malloc_ex(newsize, ctx, file, line);
  1271. }
  1272. } else {
  1273. /* Free existing block */
  1274. data = 0;
  1275. mg_free_ex(memory, file, line);
  1276. }
  1277. return data;
  1278. }
  1279. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1280. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1281. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1282. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1283. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1284. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1285. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1286. #else /* USE_SERVER_STATS */
  1287. static __inline void *
  1288. mg_malloc(size_t a)
  1289. {
  1290. return malloc(a);
  1291. }
  1292. static __inline void *
  1293. mg_calloc(size_t a, size_t b)
  1294. {
  1295. return calloc(a, b);
  1296. }
  1297. static __inline void *
  1298. mg_realloc(void *a, size_t b)
  1299. {
  1300. return realloc(a, b);
  1301. }
  1302. static __inline void
  1303. mg_free(void *a)
  1304. {
  1305. free(a);
  1306. }
  1307. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1308. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1309. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1310. #define mg_free_ctx(a, c) mg_free(a)
  1311. #endif /* USE_SERVER_STATS */
  1312. static void mg_vsnprintf(const struct mg_connection *conn,
  1313. int *truncated,
  1314. char *buf,
  1315. size_t buflen,
  1316. const char *fmt,
  1317. va_list ap);
  1318. static void mg_snprintf(const struct mg_connection *conn,
  1319. int *truncated,
  1320. char *buf,
  1321. size_t buflen,
  1322. PRINTF_FORMAT_STRING(const char *fmt),
  1323. ...) PRINTF_ARGS(5, 6);
  1324. /* This following lines are just meant as a reminder to use the mg-functions
  1325. * for memory management */
  1326. #if defined(malloc)
  1327. #undef malloc
  1328. #endif
  1329. #if defined(calloc)
  1330. #undef calloc
  1331. #endif
  1332. #if defined(realloc)
  1333. #undef realloc
  1334. #endif
  1335. #if defined(free)
  1336. #undef free
  1337. #endif
  1338. #if defined(snprintf)
  1339. #undef snprintf
  1340. #endif
  1341. #if defined(vsnprintf)
  1342. #undef vsnprintf
  1343. #endif
  1344. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1345. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1346. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1347. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1348. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1349. #if defined(_WIN32)
  1350. /* vsnprintf must not be used in any system,
  1351. * but this define only works well for Windows. */
  1352. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1353. #endif
  1354. /* mg_init_library counter */
  1355. static int mg_init_library_called = 0;
  1356. #if !defined(NO_SSL)
  1357. static int mg_ssl_initialized = 0;
  1358. #endif
  1359. static pthread_key_t sTlsKey; /* Thread local storage index */
  1360. static int thread_idx_max = 0;
  1361. #if defined(MG_LEGACY_INTERFACE)
  1362. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1363. #endif
  1364. struct mg_workerTLS {
  1365. int is_master;
  1366. unsigned long thread_idx;
  1367. void *user_ptr;
  1368. #if defined(_WIN32)
  1369. HANDLE pthread_cond_helper_mutex;
  1370. struct mg_workerTLS *next_waiting_thread;
  1371. #endif
  1372. const char *alpn_proto;
  1373. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1374. char txtbuf[4];
  1375. #endif
  1376. };
  1377. #if defined(GCC_DIAGNOSTIC)
  1378. /* Show no warning in case system functions are not used. */
  1379. #pragma GCC diagnostic push
  1380. #pragma GCC diagnostic ignored "-Wunused-function"
  1381. #endif /* defined(GCC_DIAGNOSTIC) */
  1382. #if defined(__clang__)
  1383. /* Show no warning in case system functions are not used. */
  1384. #pragma clang diagnostic push
  1385. #pragma clang diagnostic ignored "-Wunused-function"
  1386. #endif
  1387. /* Get a unique thread ID as unsigned long, independent from the data type
  1388. * of thread IDs defined by the operating system API.
  1389. * If two calls to mg_current_thread_id return the same value, they calls
  1390. * are done from the same thread. If they return different values, they are
  1391. * done from different threads. (Provided this function is used in the same
  1392. * process context and threads are not repeatedly created and deleted, but
  1393. * CivetWeb does not do that).
  1394. * This function must match the signature required for SSL id callbacks:
  1395. * CRYPTO_set_id_callback
  1396. */
  1397. FUNCTION_MAY_BE_UNUSED
  1398. static unsigned long
  1399. mg_current_thread_id(void)
  1400. {
  1401. #if defined(_WIN32)
  1402. return GetCurrentThreadId();
  1403. #else
  1404. #if defined(__clang__)
  1405. #pragma clang diagnostic push
  1406. #pragma clang diagnostic ignored "-Wunreachable-code"
  1407. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1408. * or not, so one of the two conditions will be unreachable by construction.
  1409. * Unfortunately the C standard does not define a way to check this at
  1410. * compile time, since the #if preprocessor conditions can not use the sizeof
  1411. * operator as an argument. */
  1412. #endif
  1413. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1414. /* This is the problematic case for CRYPTO_set_id_callback:
  1415. * The OS pthread_t can not be cast to unsigned long. */
  1416. struct mg_workerTLS *tls =
  1417. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1418. if (tls == NULL) {
  1419. /* SSL called from an unknown thread: Create some thread index.
  1420. */
  1421. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1422. tls->is_master = -2; /* -2 means "3rd party thread" */
  1423. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1424. pthread_setspecific(sTlsKey, tls);
  1425. }
  1426. return tls->thread_idx;
  1427. } else {
  1428. /* pthread_t may be any data type, so a simple cast to unsigned long
  1429. * can rise a warning/error, depending on the platform.
  1430. * Here memcpy is used as an anything-to-anything cast. */
  1431. unsigned long ret = 0;
  1432. pthread_t t = pthread_self();
  1433. memcpy(&ret, &t, sizeof(pthread_t));
  1434. return ret;
  1435. }
  1436. #if defined(__clang__)
  1437. #pragma clang diagnostic pop
  1438. #endif
  1439. #endif
  1440. }
  1441. FUNCTION_MAY_BE_UNUSED
  1442. static uint64_t
  1443. mg_get_current_time_ns(void)
  1444. {
  1445. struct timespec tsnow;
  1446. clock_gettime(CLOCK_REALTIME, &tsnow);
  1447. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1448. }
  1449. #if defined(GCC_DIAGNOSTIC)
  1450. /* Show no warning in case system functions are not used. */
  1451. #pragma GCC diagnostic pop
  1452. #endif /* defined(GCC_DIAGNOSTIC) */
  1453. #if defined(__clang__)
  1454. /* Show no warning in case system functions are not used. */
  1455. #pragma clang diagnostic pop
  1456. #endif
  1457. #if defined(NEED_DEBUG_TRACE_FUNC)
  1458. static void
  1459. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1460. {
  1461. va_list args;
  1462. struct timespec tsnow;
  1463. /* Get some operating system independent thread id */
  1464. unsigned long thread_id = mg_current_thread_id();
  1465. clock_gettime(CLOCK_REALTIME, &tsnow);
  1466. flockfile(DEBUG_TRACE_STREAM);
  1467. fprintf(DEBUG_TRACE_STREAM,
  1468. "*** %lu.%09lu %lu %s:%u: ",
  1469. (unsigned long)tsnow.tv_sec,
  1470. (unsigned long)tsnow.tv_nsec,
  1471. thread_id,
  1472. func,
  1473. line);
  1474. va_start(args, fmt);
  1475. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1476. va_end(args);
  1477. putc('\n', DEBUG_TRACE_STREAM);
  1478. fflush(DEBUG_TRACE_STREAM);
  1479. funlockfile(DEBUG_TRACE_STREAM);
  1480. }
  1481. #endif /* NEED_DEBUG_TRACE_FUNC */
  1482. #define MD5_STATIC static
  1483. #include "md5.inl"
  1484. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1485. #if defined(NO_SOCKLEN_T)
  1486. typedef int socklen_t;
  1487. #endif /* NO_SOCKLEN_T */
  1488. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1489. #if !defined(MSG_NOSIGNAL)
  1490. #define MSG_NOSIGNAL (0)
  1491. #endif
  1492. #if defined(NO_SSL)
  1493. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1494. typedef struct SSL_CTX SSL_CTX;
  1495. #else
  1496. #if defined(NO_SSL_DL)
  1497. #include <openssl/bn.h>
  1498. #include <openssl/conf.h>
  1499. #include <openssl/crypto.h>
  1500. #include <openssl/dh.h>
  1501. #include <openssl/engine.h>
  1502. #include <openssl/err.h>
  1503. #include <openssl/opensslv.h>
  1504. #include <openssl/pem.h>
  1505. #include <openssl/ssl.h>
  1506. #include <openssl/tls1.h>
  1507. #include <openssl/x509.h>
  1508. #if defined(WOLFSSL_VERSION)
  1509. /* Additional defines for WolfSSL, see
  1510. * https://github.com/civetweb/civetweb/issues/583 */
  1511. #include "wolfssl_extras.inl"
  1512. #endif
  1513. #if defined(OPENSSL_IS_BORINGSSL)
  1514. /* From boringssl/src/include/openssl/mem.h:
  1515. *
  1516. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1517. * However, that was written in a time before Valgrind and ASAN. Since we now
  1518. * have those tools, the OpenSSL allocation functions are simply macros around
  1519. * the standard memory functions.
  1520. *
  1521. * #define OPENSSL_free free */
  1522. #define free free
  1523. // disable for boringssl
  1524. #define CONF_modules_unload(a) ((void)0)
  1525. #define ENGINE_cleanup() ((void)0)
  1526. #endif
  1527. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1528. /* If OpenSSL headers are included, automatically select the API version */
  1529. #if !defined(OPENSSL_API_1_1)
  1530. #define OPENSSL_API_1_1
  1531. #endif
  1532. #define OPENSSL_REMOVE_THREAD_STATE()
  1533. #else
  1534. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1535. #endif
  1536. #else
  1537. /* SSL loaded dynamically from DLL.
  1538. * I put the prototypes here to be independent from OpenSSL source
  1539. * installation. */
  1540. typedef struct ssl_st SSL;
  1541. typedef struct ssl_method_st SSL_METHOD;
  1542. typedef struct ssl_ctx_st SSL_CTX;
  1543. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1544. typedef struct x509_name X509_NAME;
  1545. typedef struct asn1_integer ASN1_INTEGER;
  1546. typedef struct bignum BIGNUM;
  1547. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1548. typedef struct evp_md EVP_MD;
  1549. typedef struct x509 X509;
  1550. #define SSL_CTRL_OPTIONS (32)
  1551. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1552. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1553. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1554. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1555. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1556. #define SSL_VERIFY_NONE (0)
  1557. #define SSL_VERIFY_PEER (1)
  1558. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1559. #define SSL_VERIFY_CLIENT_ONCE (4)
  1560. #define SSL_OP_ALL (0x80000BFFul)
  1561. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1562. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1563. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1564. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1565. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1566. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1567. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1568. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1569. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1570. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1571. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1572. #define SSL_CB_HANDSHAKE_START (0x10)
  1573. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1574. #define SSL_ERROR_NONE (0)
  1575. #define SSL_ERROR_SSL (1)
  1576. #define SSL_ERROR_WANT_READ (2)
  1577. #define SSL_ERROR_WANT_WRITE (3)
  1578. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1579. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1580. #define SSL_ERROR_ZERO_RETURN (6)
  1581. #define SSL_ERROR_WANT_CONNECT (7)
  1582. #define SSL_ERROR_WANT_ACCEPT (8)
  1583. #define TLSEXT_TYPE_server_name (0)
  1584. #define TLSEXT_NAMETYPE_host_name (0)
  1585. #define SSL_TLSEXT_ERR_OK (0)
  1586. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1587. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1588. #define SSL_TLSEXT_ERR_NOACK (3)
  1589. enum ssl_func_category {
  1590. TLS_Mandatory, /* required for HTTPS */
  1591. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1592. TLS_END_OF_LIST
  1593. };
  1594. /* Check if all TLS functions/features are available */
  1595. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1596. struct ssl_func {
  1597. const char *name; /* SSL function name */
  1598. union {
  1599. enum ssl_func_category required; /* Mandatory or optional */
  1600. void (*ptr)(void); /* Function pointer */
  1601. };
  1602. };
  1603. #if defined(OPENSSL_API_1_1)
  1604. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1605. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1606. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1607. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1608. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1609. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1610. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1611. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1612. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1613. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1614. #define OPENSSL_init_ssl \
  1615. (*(int (*)(uint64_t opts, \
  1616. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1617. .ptr)
  1618. #define SSL_CTX_use_PrivateKey_file \
  1619. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1620. #define SSL_CTX_use_certificate_file \
  1621. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1622. #define SSL_CTX_set_default_passwd_cb \
  1623. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1624. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1625. #define SSL_CTX_use_certificate_chain_file \
  1626. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1627. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1628. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1629. #define SSL_CTX_set_verify \
  1630. (*(void (*)(SSL_CTX *, \
  1631. int, \
  1632. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1633. .ptr)
  1634. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1635. #define SSL_CTX_load_verify_locations \
  1636. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1637. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1638. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1639. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1640. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1641. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1642. #define SSL_CIPHER_get_name \
  1643. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1644. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1645. #define SSL_CTX_set_session_id_context \
  1646. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1647. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1648. #define SSL_CTX_set_cipher_list \
  1649. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1650. #define SSL_CTX_set_options \
  1651. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1652. #define SSL_CTX_set_info_callback \
  1653. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1654. ssl_sw[32] \
  1655. .ptr)
  1656. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1657. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1658. #define SSL_CTX_callback_ctrl \
  1659. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1660. #define SSL_get_servername \
  1661. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1662. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1663. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1664. #define SSL_CTX_set_alpn_protos \
  1665. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1666. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1667. const unsigned char **out,
  1668. unsigned char *outlen,
  1669. const unsigned char *in,
  1670. unsigned int inlen,
  1671. void *arg);
  1672. #define SSL_CTX_set_alpn_select_cb \
  1673. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1674. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1675. const unsigned char **out,
  1676. unsigned int *outlen,
  1677. void *arg);
  1678. #define SSL_CTX_set_next_protos_advertised_cb \
  1679. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1680. .ptr)
  1681. #define SSL_CTX_clear_options(ctx, op) \
  1682. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1683. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1684. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1685. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1686. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1687. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1688. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1689. SSL_CTX_callback_ctrl(ctx, \
  1690. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1691. (void (*)(void))cb)
  1692. #define SSL_set_tlsext_host_name(ctx, arg) \
  1693. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1694. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1695. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1696. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1697. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1698. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1699. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1700. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1701. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1702. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1703. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1704. #define X509_NAME_oneline \
  1705. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1706. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1707. #define EVP_get_digestbyname \
  1708. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1709. #define EVP_Digest \
  1710. (*(int (*)( \
  1711. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1712. crypto_sw[9] \
  1713. .ptr)
  1714. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1715. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1716. #define ASN1_INTEGER_to_BN \
  1717. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1718. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1719. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1720. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1721. #define OPENSSL_free(a) CRYPTO_free(a)
  1722. #define OPENSSL_REMOVE_THREAD_STATE()
  1723. /* init_ssl_ctx() function updates this array.
  1724. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1725. * of respective functions. The macros above (like SSL_connect()) are really
  1726. * just calling these functions indirectly via the pointer. */
  1727. static struct ssl_func ssl_sw[] = {
  1728. {"SSL_free", {TLS_Mandatory}},
  1729. {"SSL_accept", {TLS_Mandatory}},
  1730. {"SSL_connect", {TLS_Mandatory}},
  1731. {"SSL_read", {TLS_Mandatory}},
  1732. {"SSL_write", {TLS_Mandatory}},
  1733. {"SSL_get_error", {TLS_Mandatory}},
  1734. {"SSL_set_fd", {TLS_Mandatory}},
  1735. {"SSL_new", {TLS_Mandatory}},
  1736. {"SSL_CTX_new", {TLS_Mandatory}},
  1737. {"TLS_server_method", {TLS_Mandatory}},
  1738. {"OPENSSL_init_ssl", {TLS_Mandatory}},
  1739. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1740. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1741. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1742. {"SSL_CTX_free", {TLS_Mandatory}},
  1743. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1744. {"TLS_client_method", {TLS_Mandatory}},
  1745. {"SSL_pending", {TLS_Mandatory}},
  1746. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1747. {"SSL_shutdown", {TLS_Mandatory}},
  1748. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1749. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1750. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1751. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1752. {"SSL_get_version", {TLS_Mandatory}},
  1753. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1754. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1755. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1756. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1757. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1758. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1759. {"SSL_CTX_set_options", {TLS_Mandatory}},
  1760. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1761. {"SSL_get_ex_data", {TLS_Mandatory}},
  1762. {"SSL_set_ex_data", {TLS_Mandatory}},
  1763. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1764. {"SSL_get_servername", {TLS_Mandatory}},
  1765. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1766. {"SSL_ctrl", {TLS_Mandatory}},
  1767. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1768. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1769. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1770. {NULL, {TLS_END_OF_LIST}}};
  1771. /* Similar array as ssl_sw. These functions could be located in different
  1772. * lib. */
  1773. static struct ssl_func crypto_sw[] = {{"ERR_get_error", {TLS_Mandatory}},
  1774. {"ERR_error_string", {TLS_Mandatory}},
  1775. {"CONF_modules_unload", {TLS_Mandatory}},
  1776. {"X509_free", {TLS_Mandatory}},
  1777. {"X509_get_subject_name",
  1778. {TLS_Mandatory}},
  1779. {"X509_get_issuer_name", {TLS_Mandatory}},
  1780. {"X509_NAME_oneline", {TLS_Mandatory}},
  1781. {"X509_get_serialNumber",
  1782. {TLS_Mandatory}},
  1783. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1784. {"EVP_Digest", {TLS_Mandatory}},
  1785. {"i2d_X509", {TLS_Mandatory}},
  1786. {"BN_bn2hex", {TLS_Mandatory}},
  1787. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1788. {"BN_free", {TLS_Mandatory}},
  1789. {"CRYPTO_free", {TLS_Mandatory}},
  1790. {"ERR_clear_error", {TLS_Mandatory}},
  1791. {NULL, {TLS_END_OF_LIST}}};
  1792. #else
  1793. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1794. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1795. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1796. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1797. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1798. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1799. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1800. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1801. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1802. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1803. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1804. #define SSL_CTX_use_PrivateKey_file \
  1805. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1806. #define SSL_CTX_use_certificate_file \
  1807. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1808. #define SSL_CTX_set_default_passwd_cb \
  1809. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1810. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1811. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1812. #define SSL_CTX_use_certificate_chain_file \
  1813. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1814. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1815. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1816. #define SSL_CTX_set_verify \
  1817. (*(void (*)(SSL_CTX *, \
  1818. int, \
  1819. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1820. .ptr)
  1821. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1822. #define SSL_CTX_load_verify_locations \
  1823. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1824. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1825. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1826. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1827. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1828. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1829. #define SSL_CIPHER_get_name \
  1830. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1831. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1832. #define SSL_CTX_set_session_id_context \
  1833. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1834. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1835. #define SSL_CTX_set_cipher_list \
  1836. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1837. #define SSL_CTX_set_info_callback \
  1838. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1839. .ptr)
  1840. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1841. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1842. #define SSL_CTX_callback_ctrl \
  1843. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1844. #define SSL_get_servername \
  1845. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1846. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1847. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1848. #define SSL_CTX_set_alpn_protos \
  1849. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1850. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1851. const unsigned char **out,
  1852. unsigned char *outlen,
  1853. const unsigned char *in,
  1854. unsigned int inlen,
  1855. void *arg);
  1856. #define SSL_CTX_set_alpn_select_cb \
  1857. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1858. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1859. const unsigned char **out,
  1860. unsigned int *outlen,
  1861. void *arg);
  1862. #define SSL_CTX_set_next_protos_advertised_cb \
  1863. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1864. .ptr)
  1865. #define SSL_CTX_set_options(ctx, op) \
  1866. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1867. #define SSL_CTX_clear_options(ctx, op) \
  1868. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1869. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1870. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1871. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1872. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1873. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1874. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1875. SSL_CTX_callback_ctrl(ctx, \
  1876. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1877. (void (*)(void))cb)
  1878. #define SSL_set_tlsext_host_name(ctx, arg) \
  1879. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1880. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1881. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1882. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1883. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1884. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1885. #define CRYPTO_set_locking_callback \
  1886. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1887. #define CRYPTO_set_id_callback \
  1888. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1889. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1890. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1891. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1892. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1893. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1894. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1895. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1896. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1897. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1898. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1899. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1900. #define X509_NAME_oneline \
  1901. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1902. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1903. #define i2c_ASN1_INTEGER \
  1904. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1905. #define EVP_get_digestbyname \
  1906. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1907. #define EVP_Digest \
  1908. (*(int (*)( \
  1909. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1910. crypto_sw[18] \
  1911. .ptr)
  1912. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1913. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1914. #define ASN1_INTEGER_to_BN \
  1915. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1916. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1917. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1918. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1919. #define OPENSSL_free(a) CRYPTO_free(a)
  1920. /* use here ERR_remove_state,
  1921. * while on some platforms function is not included into library due to
  1922. * deprication */
  1923. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1924. /* init_ssl_ctx() function updates this array.
  1925. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1926. * of respective functions. The macros above (like SSL_connect()) are really
  1927. * just calling these functions indirectly via the pointer. */
  1928. static struct ssl_func ssl_sw[] = {
  1929. {"SSL_free", {TLS_Mandatory}},
  1930. {"SSL_accept", {TLS_Mandatory}},
  1931. {"SSL_connect", {TLS_Mandatory}},
  1932. {"SSL_read", {TLS_Mandatory}},
  1933. {"SSL_write", {TLS_Mandatory}},
  1934. {"SSL_get_error", {TLS_Mandatory}},
  1935. {"SSL_set_fd", {TLS_Mandatory}},
  1936. {"SSL_new", {TLS_Mandatory}},
  1937. {"SSL_CTX_new", {TLS_Mandatory}},
  1938. {"SSLv23_server_method", {TLS_Mandatory}},
  1939. {"SSL_library_init", {TLS_Mandatory}},
  1940. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1941. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1942. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1943. {"SSL_CTX_free", {TLS_Mandatory}},
  1944. {"SSL_load_error_strings", {TLS_Mandatory}},
  1945. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1946. {"SSLv23_client_method", {TLS_Mandatory}},
  1947. {"SSL_pending", {TLS_Mandatory}},
  1948. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1949. {"SSL_shutdown", {TLS_Mandatory}},
  1950. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1951. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1952. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1953. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1954. {"SSL_get_version", {TLS_Mandatory}},
  1955. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1956. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1957. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1958. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1959. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1960. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1961. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1962. {"SSL_get_ex_data", {TLS_Mandatory}},
  1963. {"SSL_set_ex_data", {TLS_Mandatory}},
  1964. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1965. {"SSL_get_servername", {TLS_Mandatory}},
  1966. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1967. {"SSL_ctrl", {TLS_Mandatory}},
  1968. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1969. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1970. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1971. {NULL, {TLS_END_OF_LIST}}};
  1972. /* Similar array as ssl_sw. These functions could be located in different
  1973. * lib. */
  1974. static struct ssl_func crypto_sw[] = {
  1975. {"CRYPTO_num_locks", {TLS_Mandatory}},
  1976. {"CRYPTO_set_locking_callback", {TLS_Mandatory}},
  1977. {"CRYPTO_set_id_callback", {TLS_Mandatory}},
  1978. {"ERR_get_error", {TLS_Mandatory}},
  1979. {"ERR_error_string", {TLS_Mandatory}},
  1980. {"ERR_remove_state", {TLS_Mandatory}},
  1981. {"ERR_free_strings", {TLS_Mandatory}},
  1982. {"ENGINE_cleanup", {TLS_Mandatory}},
  1983. {"CONF_modules_unload", {TLS_Mandatory}},
  1984. {"CRYPTO_cleanup_all_ex_data", {TLS_Mandatory}},
  1985. {"EVP_cleanup", {TLS_Mandatory}},
  1986. {"X509_free", {TLS_Mandatory}},
  1987. {"X509_get_subject_name", {TLS_Mandatory}},
  1988. {"X509_get_issuer_name", {TLS_Mandatory}},
  1989. {"X509_NAME_oneline", {TLS_Mandatory}},
  1990. {"X509_get_serialNumber", {TLS_Mandatory}},
  1991. {"i2c_ASN1_INTEGER", {TLS_Mandatory}},
  1992. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1993. {"EVP_Digest", {TLS_Mandatory}},
  1994. {"i2d_X509", {TLS_Mandatory}},
  1995. {"BN_bn2hex", {TLS_Mandatory}},
  1996. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1997. {"BN_free", {TLS_Mandatory}},
  1998. {"CRYPTO_free", {TLS_Mandatory}},
  1999. {"ERR_clear_error", {TLS_Mandatory}},
  2000. {NULL, {TLS_END_OF_LIST}}};
  2001. #endif /* OPENSSL_API_1_1 */
  2002. #endif /* NO_SSL_DL */
  2003. #endif /* NO_SSL */
  2004. #if !defined(NO_CACHING)
  2005. static const char month_names[][4] = {"Jan",
  2006. "Feb",
  2007. "Mar",
  2008. "Apr",
  2009. "May",
  2010. "Jun",
  2011. "Jul",
  2012. "Aug",
  2013. "Sep",
  2014. "Oct",
  2015. "Nov",
  2016. "Dec"};
  2017. #endif /* !NO_CACHING */
  2018. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2019. * the union u. */
  2020. union usa {
  2021. struct sockaddr sa;
  2022. struct sockaddr_in sin;
  2023. #if defined(USE_IPV6)
  2024. struct sockaddr_in6 sin6;
  2025. #endif
  2026. };
  2027. /* Describes a string (chunk of memory). */
  2028. struct vec {
  2029. const char *ptr;
  2030. size_t len;
  2031. };
  2032. struct mg_file_stat {
  2033. /* File properties filled by mg_stat: */
  2034. uint64_t size;
  2035. time_t last_modified;
  2036. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2037. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2038. * case we need a "Content-Eencoding: gzip" header */
  2039. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2040. };
  2041. struct mg_file_in_memory {
  2042. char *p;
  2043. uint32_t pos;
  2044. char mode;
  2045. };
  2046. struct mg_file_access {
  2047. /* File properties filled by mg_fopen: */
  2048. FILE *fp;
  2049. #if defined(MG_USE_OPEN_FILE)
  2050. /* TODO (low): Remove obsolete "file in memory" implementation.
  2051. * In an "early 2017" discussion at Google groups
  2052. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2053. * we decided to get rid of this feature (after some fade-out
  2054. * phase). */
  2055. const char *membuf;
  2056. #endif
  2057. };
  2058. struct mg_file {
  2059. struct mg_file_stat stat;
  2060. struct mg_file_access access;
  2061. };
  2062. #if defined(MG_USE_OPEN_FILE)
  2063. #define STRUCT_FILE_INITIALIZER \
  2064. { \
  2065. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2066. { \
  2067. (FILE *)NULL, (const char *)NULL \
  2068. } \
  2069. }
  2070. #else
  2071. #define STRUCT_FILE_INITIALIZER \
  2072. { \
  2073. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2074. { \
  2075. (FILE *)NULL \
  2076. } \
  2077. }
  2078. #endif
  2079. /* Describes listening socket, or socket which was accept()-ed by the master
  2080. * thread and queued for future handling by the worker thread. */
  2081. struct socket {
  2082. SOCKET sock; /* Listening socket */
  2083. union usa lsa; /* Local socket address */
  2084. union usa rsa; /* Remote socket address */
  2085. unsigned char is_ssl; /* Is port SSL-ed */
  2086. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2087. * port */
  2088. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2089. };
  2090. /* Enum const for all options must be in sync with
  2091. * static struct mg_option config_options[]
  2092. * This is tested in the unit test (test/private.c)
  2093. * "Private Config Options"
  2094. */
  2095. enum {
  2096. /* Once for each server */
  2097. LISTENING_PORTS,
  2098. NUM_THREADS,
  2099. RUN_AS_USER,
  2100. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2101. * socket option typedef TCP_NODELAY. */
  2102. MAX_REQUEST_SIZE,
  2103. LINGER_TIMEOUT,
  2104. CONNECTION_QUEUE_SIZE,
  2105. LISTEN_BACKLOG_SIZE,
  2106. #if defined(__linux__)
  2107. ALLOW_SENDFILE_CALL,
  2108. #endif
  2109. #if defined(_WIN32)
  2110. CASE_SENSITIVE_FILES,
  2111. #endif
  2112. THROTTLE,
  2113. ACCESS_LOG_FILE,
  2114. ERROR_LOG_FILE,
  2115. ENABLE_KEEP_ALIVE,
  2116. REQUEST_TIMEOUT,
  2117. KEEP_ALIVE_TIMEOUT,
  2118. #if defined(USE_WEBSOCKET)
  2119. WEBSOCKET_TIMEOUT,
  2120. ENABLE_WEBSOCKET_PING_PONG,
  2121. #endif
  2122. DECODE_URL,
  2123. #if defined(USE_LUA)
  2124. LUA_BACKGROUND_SCRIPT,
  2125. LUA_BACKGROUND_SCRIPT_PARAMS,
  2126. #endif
  2127. #if defined(USE_TIMERS)
  2128. CGI_TIMEOUT,
  2129. #endif
  2130. /* Once for each domain */
  2131. DOCUMENT_ROOT,
  2132. CGI_EXTENSIONS,
  2133. CGI_ENVIRONMENT,
  2134. PUT_DELETE_PASSWORDS_FILE,
  2135. CGI_INTERPRETER,
  2136. CGI_INTERPRETER_ARGS,
  2137. PROTECT_URI,
  2138. AUTHENTICATION_DOMAIN,
  2139. ENABLE_AUTH_DOMAIN_CHECK,
  2140. SSI_EXTENSIONS,
  2141. ENABLE_DIRECTORY_LISTING,
  2142. GLOBAL_PASSWORDS_FILE,
  2143. INDEX_FILES,
  2144. ACCESS_CONTROL_LIST,
  2145. EXTRA_MIME_TYPES,
  2146. SSL_CERTIFICATE,
  2147. SSL_CERTIFICATE_CHAIN,
  2148. URL_REWRITE_PATTERN,
  2149. HIDE_FILES,
  2150. SSL_DO_VERIFY_PEER,
  2151. SSL_CA_PATH,
  2152. SSL_CA_FILE,
  2153. SSL_VERIFY_DEPTH,
  2154. SSL_DEFAULT_VERIFY_PATHS,
  2155. SSL_CIPHER_LIST,
  2156. SSL_PROTOCOL_VERSION,
  2157. SSL_SHORT_TRUST,
  2158. #if defined(USE_LUA)
  2159. LUA_PRELOAD_FILE,
  2160. LUA_SCRIPT_EXTENSIONS,
  2161. LUA_SERVER_PAGE_EXTENSIONS,
  2162. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2163. LUA_DEBUG_PARAMS,
  2164. #endif
  2165. #endif
  2166. #if defined(USE_DUKTAPE)
  2167. DUKTAPE_SCRIPT_EXTENSIONS,
  2168. #endif
  2169. #if defined(USE_WEBSOCKET)
  2170. WEBSOCKET_ROOT,
  2171. #endif
  2172. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2173. LUA_WEBSOCKET_EXTENSIONS,
  2174. #endif
  2175. ACCESS_CONTROL_ALLOW_ORIGIN,
  2176. ACCESS_CONTROL_ALLOW_METHODS,
  2177. ACCESS_CONTROL_ALLOW_HEADERS,
  2178. ERROR_PAGES,
  2179. #if !defined(NO_CACHING)
  2180. STATIC_FILE_MAX_AGE,
  2181. STATIC_FILE_CACHE_CONTROL,
  2182. #endif
  2183. #if !defined(NO_SSL)
  2184. STRICT_HTTPS_MAX_AGE,
  2185. #endif
  2186. ADDITIONAL_HEADER,
  2187. ALLOW_INDEX_SCRIPT_SUB_RES,
  2188. #if defined(DAEMONIZE)
  2189. ENABLE_DAEMONIZE,
  2190. #endif
  2191. NUM_OPTIONS
  2192. };
  2193. /* Config option name, config types, default value.
  2194. * Must be in the same order as the enum const above.
  2195. */
  2196. static const struct mg_option config_options[] = {
  2197. /* Once for each server */
  2198. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2199. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2200. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2201. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2202. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2203. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2204. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2205. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2206. #if defined(__linux__)
  2207. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2208. #endif
  2209. #if defined(_WIN32)
  2210. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2211. #endif
  2212. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2213. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2214. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2215. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2216. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2217. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2218. #if defined(USE_WEBSOCKET)
  2219. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2220. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2221. #endif
  2222. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2223. #if defined(USE_LUA)
  2224. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2225. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2226. #endif
  2227. #if defined(USE_TIMERS)
  2228. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2229. #endif
  2230. /* Once for each domain */
  2231. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2232. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2233. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2234. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2235. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2236. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2237. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2238. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2239. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2240. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2241. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2242. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2243. {"index_files",
  2244. MG_CONFIG_TYPE_STRING_LIST,
  2245. #if defined(USE_LUA)
  2246. "index.xhtml,index.html,index.htm,"
  2247. "index.lp,index.lsp,index.lua,index.cgi,"
  2248. "index.shtml,index.php"},
  2249. #else
  2250. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2251. #endif
  2252. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2253. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2254. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2255. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2256. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2257. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2258. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2259. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2260. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2261. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2262. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2263. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2264. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2265. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2266. #if defined(USE_LUA)
  2267. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2268. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2269. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2270. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2271. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2272. #endif
  2273. #endif
  2274. #if defined(USE_DUKTAPE)
  2275. /* The support for duktape is still in alpha version state.
  2276. * The name of this config option might change. */
  2277. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2278. #endif
  2279. #if defined(USE_WEBSOCKET)
  2280. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2281. #endif
  2282. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2283. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2284. #endif
  2285. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2286. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2287. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2288. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2289. #if !defined(NO_CACHING)
  2290. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2291. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2292. #endif
  2293. #if !defined(NO_SSL)
  2294. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2295. #endif
  2296. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2297. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2298. #if defined(DAEMONIZE)
  2299. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2300. #endif
  2301. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2302. /* Check if the config_options and the corresponding enum have compatible
  2303. * sizes. */
  2304. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2305. == (NUM_OPTIONS + 1),
  2306. "config_options and enum not sync");
  2307. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2308. struct mg_handler_info {
  2309. /* Name/Pattern of the URI. */
  2310. char *uri;
  2311. size_t uri_len;
  2312. /* handler type */
  2313. int handler_type;
  2314. /* Handler for http/https or authorization requests. */
  2315. mg_request_handler handler;
  2316. unsigned int refcount;
  2317. int removing;
  2318. /* Handler for ws/wss (websocket) requests. */
  2319. mg_websocket_connect_handler connect_handler;
  2320. mg_websocket_ready_handler ready_handler;
  2321. mg_websocket_data_handler data_handler;
  2322. mg_websocket_close_handler close_handler;
  2323. /* accepted subprotocols for ws/wss requests. */
  2324. struct mg_websocket_subprotocols *subprotocols;
  2325. /* Handler for authorization requests */
  2326. mg_authorization_handler auth_handler;
  2327. /* User supplied argument for the handler function. */
  2328. void *cbdata;
  2329. /* next handler in a linked list */
  2330. struct mg_handler_info *next;
  2331. };
  2332. enum {
  2333. CONTEXT_INVALID,
  2334. CONTEXT_SERVER,
  2335. CONTEXT_HTTP_CLIENT,
  2336. CONTEXT_WS_CLIENT
  2337. };
  2338. struct mg_domain_context {
  2339. SSL_CTX *ssl_ctx; /* SSL context */
  2340. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2341. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2342. int64_t ssl_cert_last_mtime;
  2343. /* Server nonce */
  2344. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2345. unsigned long nonce_count; /* Used nonces, used for authentication */
  2346. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2347. /* linked list of shared lua websockets */
  2348. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2349. #endif
  2350. /* Linked list of domains */
  2351. struct mg_domain_context *next;
  2352. };
  2353. /* Stop flag can be "volatile" or require a lock */
  2354. typedef int volatile stop_flag_t;
  2355. #ifdef STOP_FLAG_NEEDS_LOCK
  2356. static int
  2357. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2358. {
  2359. int r;
  2360. mg_global_lock();
  2361. r = ((*f) == 0);
  2362. mg_global_unlock();
  2363. return r;
  2364. }
  2365. static int
  2366. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2367. {
  2368. int r;
  2369. mg_global_lock();
  2370. r = ((*f) == 2);
  2371. mg_global_unlock();
  2372. return r;
  2373. }
  2374. static void
  2375. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2376. {
  2377. mg_global_lock();
  2378. (*f) = v;
  2379. mg_global_unlock();
  2380. }
  2381. #else /* STOP_FLAG_NEEDS_LOCK */
  2382. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2383. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2384. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2385. #endif /* STOP_FLAG_NEEDS_LOCK */
  2386. struct mg_context {
  2387. /* Part 1 - Physical context:
  2388. * This holds threads, ports, timeouts, ...
  2389. * set for the entire server, independent from the
  2390. * addressed hostname.
  2391. */
  2392. /* Connection related */
  2393. int context_type; /* See CONTEXT_* above */
  2394. struct socket *listening_sockets;
  2395. struct mg_pollfd *listening_socket_fds;
  2396. unsigned int num_listening_sockets;
  2397. struct mg_connection *worker_connections; /* The connection struct, pre-
  2398. * allocated for each worker */
  2399. #if defined(USE_SERVER_STATS)
  2400. int active_connections;
  2401. int max_active_connections;
  2402. int64_t total_connections;
  2403. int64_t total_requests;
  2404. int64_t total_data_read;
  2405. int64_t total_data_written;
  2406. #endif
  2407. /* Thread related */
  2408. stop_flag_t stop_flag; /* Should we stop event loop */
  2409. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2410. pthread_t masterthreadid; /* The master thread ID */
  2411. unsigned int
  2412. cfg_worker_threads; /* The number of configured worker threads. */
  2413. pthread_t *worker_threadids; /* The worker thread IDs */
  2414. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2415. /* Connection to thread dispatching */
  2416. #if defined(ALTERNATIVE_QUEUE)
  2417. struct socket *client_socks;
  2418. void **client_wait_events;
  2419. #else
  2420. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2421. worker thread */
  2422. volatile int sq_head; /* Head of the socket queue */
  2423. volatile int sq_tail; /* Tail of the socket queue */
  2424. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2425. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2426. volatile int sq_blocked; /* Status information: sq is full */
  2427. int sq_size; /* No of elements in socket queue */
  2428. #if defined(USE_SERVER_STATS)
  2429. int sq_max_fill;
  2430. #endif /* USE_SERVER_STATS */
  2431. #endif /* ALTERNATIVE_QUEUE */
  2432. /* Memory related */
  2433. unsigned int max_request_size; /* The max request size */
  2434. #if defined(USE_SERVER_STATS)
  2435. struct mg_memory_stat ctx_memory;
  2436. #endif
  2437. /* Operating system related */
  2438. char *systemName; /* What operating system is running */
  2439. time_t start_time; /* Server start time, used for authentication
  2440. * and for diagnstics. */
  2441. #if defined(USE_TIMERS)
  2442. struct ttimers *timers;
  2443. #endif
  2444. /* Lua specific: Background operations and shared websockets */
  2445. #if defined(USE_LUA)
  2446. void *lua_background_state;
  2447. #endif
  2448. /* Server nonce */
  2449. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2450. * ssl_cert_last_mtime, nonce_count, and
  2451. * next (linked list) */
  2452. /* Server callbacks */
  2453. struct mg_callbacks callbacks; /* User-defined callback function */
  2454. void *user_data; /* User-defined data */
  2455. /* Part 2 - Logical domain:
  2456. * This holds hostname, TLS certificate, document root, ...
  2457. * set for a domain hosted at the server.
  2458. * There may be multiple domains hosted at one physical server.
  2459. * The default domain "dd" is the first element of a list of
  2460. * domains.
  2461. */
  2462. struct mg_domain_context dd; /* default domain */
  2463. };
  2464. #if defined(USE_SERVER_STATS)
  2465. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2466. static struct mg_memory_stat *
  2467. get_memory_stat(struct mg_context *ctx)
  2468. {
  2469. if (ctx) {
  2470. return &(ctx->ctx_memory);
  2471. }
  2472. return &mg_common_memory;
  2473. }
  2474. #endif
  2475. enum {
  2476. CONNECTION_TYPE_INVALID,
  2477. CONNECTION_TYPE_REQUEST,
  2478. CONNECTION_TYPE_RESPONSE
  2479. };
  2480. enum {
  2481. PROTOCOL_TYPE_HTTP1 = 0,
  2482. PROTOCOL_TYPE_WEBSOCKET = 1,
  2483. PROTOCOL_TYPE_HTTP2 = 2
  2484. };
  2485. struct mg_connection {
  2486. int connection_type; /* see CONNECTION_TYPE_* above */
  2487. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2488. struct mg_request_info request_info;
  2489. struct mg_response_info response_info;
  2490. struct mg_context *phys_ctx;
  2491. struct mg_domain_context *dom_ctx;
  2492. #if defined(USE_SERVER_STATS)
  2493. int conn_state; /* 0 = undef, numerical value may change in different
  2494. * versions. For the current definition, see
  2495. * mg_get_connection_info_impl */
  2496. #endif
  2497. SSL *ssl; /* SSL descriptor */
  2498. struct socket client; /* Connected client */
  2499. time_t conn_birth_time; /* Time (wall clock) when connection was
  2500. * established */
  2501. #if defined(USE_SERVER_STATS)
  2502. time_t conn_close_time; /* Time (wall clock) when connection was
  2503. * closed (or 0 if still open) */
  2504. #endif
  2505. struct timespec req_time; /* Time (since system start) when the request
  2506. * was received */
  2507. int64_t num_bytes_sent; /* Total bytes sent to client */
  2508. int64_t content_len; /* How many bytes of content can be read
  2509. * !is_chunked: Content-Length header value
  2510. * or -1 (until connection closed,
  2511. * not allowed for a request)
  2512. * is_chunked: >= 0, appended gradually
  2513. */
  2514. int64_t consumed_content; /* How many bytes of content have been read */
  2515. int is_chunked; /* Transfer-Encoding is chunked:
  2516. * 0 = not chunked,
  2517. * 1 = chunked, not yet, or some data read,
  2518. * 2 = chunked, has error,
  2519. * 3 = chunked, all data read except trailer,
  2520. * 4 = chunked, all data read
  2521. */
  2522. char *buf; /* Buffer for received data */
  2523. char *path_info; /* PATH_INFO part of the URL */
  2524. int must_close; /* 1 if connection must be closed */
  2525. int accept_gzip; /* 1 if gzip encoding is accepted */
  2526. int in_error_handler; /* 1 if in handler for user defined error
  2527. * pages */
  2528. #if defined(USE_WEBSOCKET)
  2529. int in_websocket_handling; /* 1 if in read_websocket */
  2530. #endif
  2531. int handled_requests; /* Number of requests handled by this connection
  2532. */
  2533. int buf_size; /* Buffer size */
  2534. int request_len; /* Size of the request + headers in a buffer */
  2535. int data_len; /* Total size of data in a buffer */
  2536. int status_code; /* HTTP reply status code, e.g. 200 */
  2537. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2538. * throttle */
  2539. time_t last_throttle_time; /* Last time throttled data was sent */
  2540. int last_throttle_bytes; /* Bytes sent this second */
  2541. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2542. * atomic transmissions for websockets */
  2543. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2544. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2545. #endif
  2546. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2547. * for quick access */
  2548. };
  2549. /* Directory entry */
  2550. struct de {
  2551. struct mg_connection *conn;
  2552. char *file_name;
  2553. struct mg_file_stat file;
  2554. };
  2555. #define mg_cry_internal(conn, fmt, ...) \
  2556. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2557. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2558. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2559. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2560. struct mg_context *ctx,
  2561. const char *func,
  2562. unsigned line,
  2563. const char *fmt,
  2564. ...) PRINTF_ARGS(5, 6);
  2565. #if !defined(NO_THREAD_NAME)
  2566. #if defined(_WIN32) && defined(_MSC_VER)
  2567. /* Set the thread name for debugging purposes in Visual Studio
  2568. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2569. */
  2570. #pragma pack(push, 8)
  2571. typedef struct tagTHREADNAME_INFO {
  2572. DWORD dwType; /* Must be 0x1000. */
  2573. LPCSTR szName; /* Pointer to name (in user addr space). */
  2574. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2575. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2576. } THREADNAME_INFO;
  2577. #pragma pack(pop)
  2578. #elif defined(__linux__)
  2579. #include <sys/prctl.h>
  2580. #include <sys/sendfile.h>
  2581. #if defined(ALTERNATIVE_QUEUE)
  2582. #include <sys/eventfd.h>
  2583. #endif /* ALTERNATIVE_QUEUE */
  2584. #if defined(ALTERNATIVE_QUEUE)
  2585. static void *
  2586. event_create(void)
  2587. {
  2588. int evhdl = eventfd(0, EFD_CLOEXEC);
  2589. int *ret;
  2590. if (evhdl == -1) {
  2591. /* Linux uses -1 on error, Windows NULL. */
  2592. /* However, Linux does not return 0 on success either. */
  2593. return 0;
  2594. }
  2595. ret = (int *)mg_malloc(sizeof(int));
  2596. if (ret) {
  2597. *ret = evhdl;
  2598. } else {
  2599. (void)close(evhdl);
  2600. }
  2601. return (void *)ret;
  2602. }
  2603. static int
  2604. event_wait(void *eventhdl)
  2605. {
  2606. uint64_t u;
  2607. int evhdl, s;
  2608. if (!eventhdl) {
  2609. /* error */
  2610. return 0;
  2611. }
  2612. evhdl = *(int *)eventhdl;
  2613. s = (int)read(evhdl, &u, sizeof(u));
  2614. if (s != sizeof(u)) {
  2615. /* error */
  2616. return 0;
  2617. }
  2618. (void)u; /* the value is not required */
  2619. return 1;
  2620. }
  2621. static int
  2622. event_signal(void *eventhdl)
  2623. {
  2624. uint64_t u = 1;
  2625. int evhdl, s;
  2626. if (!eventhdl) {
  2627. /* error */
  2628. return 0;
  2629. }
  2630. evhdl = *(int *)eventhdl;
  2631. s = (int)write(evhdl, &u, sizeof(u));
  2632. if (s != sizeof(u)) {
  2633. /* error */
  2634. return 0;
  2635. }
  2636. return 1;
  2637. }
  2638. static void
  2639. event_destroy(void *eventhdl)
  2640. {
  2641. int evhdl;
  2642. if (!eventhdl) {
  2643. /* error */
  2644. return;
  2645. }
  2646. evhdl = *(int *)eventhdl;
  2647. close(evhdl);
  2648. mg_free(eventhdl);
  2649. }
  2650. #endif
  2651. #endif
  2652. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2653. struct posix_event {
  2654. pthread_mutex_t mutex;
  2655. pthread_cond_t cond;
  2656. int signaled;
  2657. };
  2658. static void *
  2659. event_create(void)
  2660. {
  2661. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2662. if (ret == 0) {
  2663. /* out of memory */
  2664. return 0;
  2665. }
  2666. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2667. /* pthread mutex not available */
  2668. mg_free(ret);
  2669. return 0;
  2670. }
  2671. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2672. /* pthread cond not available */
  2673. pthread_mutex_destroy(&(ret->mutex));
  2674. mg_free(ret);
  2675. return 0;
  2676. }
  2677. ret->signaled = 0;
  2678. return (void *)ret;
  2679. }
  2680. static int
  2681. event_wait(void *eventhdl)
  2682. {
  2683. struct posix_event *ev = (struct posix_event *)eventhdl;
  2684. pthread_mutex_lock(&(ev->mutex));
  2685. while (!ev->signaled) {
  2686. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2687. }
  2688. ev->signaled = 0;
  2689. pthread_mutex_unlock(&(ev->mutex));
  2690. return 1;
  2691. }
  2692. static int
  2693. event_signal(void *eventhdl)
  2694. {
  2695. struct posix_event *ev = (struct posix_event *)eventhdl;
  2696. pthread_mutex_lock(&(ev->mutex));
  2697. pthread_cond_signal(&(ev->cond));
  2698. ev->signaled = 1;
  2699. pthread_mutex_unlock(&(ev->mutex));
  2700. return 1;
  2701. }
  2702. static void
  2703. event_destroy(void *eventhdl)
  2704. {
  2705. struct posix_event *ev = (struct posix_event *)eventhdl;
  2706. pthread_cond_destroy(&(ev->cond));
  2707. pthread_mutex_destroy(&(ev->mutex));
  2708. mg_free(ev);
  2709. }
  2710. #endif
  2711. static void
  2712. mg_set_thread_name(const char *name)
  2713. {
  2714. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2715. mg_snprintf(
  2716. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2717. #if defined(_WIN32)
  2718. #if defined(_MSC_VER)
  2719. /* Windows and Visual Studio Compiler */
  2720. __try {
  2721. THREADNAME_INFO info;
  2722. info.dwType = 0x1000;
  2723. info.szName = threadName;
  2724. info.dwThreadID = ~0U;
  2725. info.dwFlags = 0;
  2726. RaiseException(0x406D1388,
  2727. 0,
  2728. sizeof(info) / sizeof(ULONG_PTR),
  2729. (ULONG_PTR *)&info);
  2730. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2731. }
  2732. #elif defined(__MINGW32__)
  2733. /* No option known to set thread name for MinGW known */
  2734. #endif
  2735. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2736. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2737. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2738. #if defined(__MACH__)
  2739. /* OS X only current thread name can be changed */
  2740. (void)pthread_setname_np(threadName);
  2741. #else
  2742. (void)pthread_setname_np(pthread_self(), threadName);
  2743. #endif
  2744. #elif defined(__linux__)
  2745. /* On Linux we can use the prctl function.
  2746. * When building for Linux Standard Base (LSB) use
  2747. * NO_THREAD_NAME. However, thread names are a big
  2748. * help for debugging, so the stadard is to set them.
  2749. */
  2750. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2751. #endif
  2752. }
  2753. #else /* !defined(NO_THREAD_NAME) */
  2754. void
  2755. mg_set_thread_name(const char *threadName)
  2756. {
  2757. }
  2758. #endif
  2759. #if defined(MG_LEGACY_INTERFACE)
  2760. const char **
  2761. mg_get_valid_option_names(void)
  2762. {
  2763. /* This function is deprecated. Use mg_get_valid_options instead. */
  2764. static const char
  2765. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2766. int i;
  2767. for (i = 0; config_options[i].name != NULL; i++) {
  2768. data[i * 2] = config_options[i].name;
  2769. data[i * 2 + 1] = config_options[i].default_value;
  2770. }
  2771. return data;
  2772. }
  2773. #endif
  2774. const struct mg_option *
  2775. mg_get_valid_options(void)
  2776. {
  2777. return config_options;
  2778. }
  2779. /* Do not open file (used in is_file_in_memory) */
  2780. #define MG_FOPEN_MODE_NONE (0)
  2781. /* Open file for read only access */
  2782. #define MG_FOPEN_MODE_READ (1)
  2783. /* Open file for writing, create and overwrite */
  2784. #define MG_FOPEN_MODE_WRITE (2)
  2785. /* Open file for writing, create and append */
  2786. #define MG_FOPEN_MODE_APPEND (4)
  2787. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2788. * output filep and return 1, otherwise return 0 and don't modify anything.
  2789. */
  2790. static int
  2791. open_file_in_memory(const struct mg_connection *conn,
  2792. const char *path,
  2793. struct mg_file *filep,
  2794. int mode)
  2795. {
  2796. #if defined(MG_USE_OPEN_FILE)
  2797. size_t size = 0;
  2798. const char *buf = NULL;
  2799. if (!conn) {
  2800. return 0;
  2801. }
  2802. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2803. return 0;
  2804. }
  2805. if (conn->phys_ctx->callbacks.open_file) {
  2806. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2807. if (buf != NULL) {
  2808. if (filep == NULL) {
  2809. /* This is a file in memory, but we cannot store the
  2810. * properties
  2811. * now.
  2812. * Called from "is_file_in_memory" function. */
  2813. return 1;
  2814. }
  2815. /* NOTE: override filep->size only on success. Otherwise, it
  2816. * might
  2817. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2818. filep->access.membuf = buf;
  2819. filep->access.fp = NULL;
  2820. /* Size was set by the callback */
  2821. filep->stat.size = size;
  2822. /* Assume the data may change during runtime by setting
  2823. * last_modified = now */
  2824. filep->stat.last_modified = time(NULL);
  2825. filep->stat.is_directory = 0;
  2826. filep->stat.is_gzipped = 0;
  2827. }
  2828. }
  2829. return (buf != NULL);
  2830. #else
  2831. (void)conn;
  2832. (void)path;
  2833. (void)filep;
  2834. (void)mode;
  2835. return 0;
  2836. #endif
  2837. }
  2838. static int
  2839. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2840. {
  2841. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2842. }
  2843. static int
  2844. is_file_opened(const struct mg_file_access *fileacc)
  2845. {
  2846. if (!fileacc) {
  2847. return 0;
  2848. }
  2849. #if defined(MG_USE_OPEN_FILE)
  2850. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2851. #else
  2852. return (fileacc->fp != NULL);
  2853. #endif
  2854. }
  2855. #if !defined(NO_FILESYSTEMS)
  2856. static int mg_stat(const struct mg_connection *conn,
  2857. const char *path,
  2858. struct mg_file_stat *filep);
  2859. /* mg_fopen will open a file either in memory or on the disk.
  2860. * The input parameter path is a string in UTF-8 encoding.
  2861. * The input parameter mode is MG_FOPEN_MODE_*
  2862. * On success, either fp or membuf will be set in the output
  2863. * struct file. All status members will also be set.
  2864. * The function returns 1 on success, 0 on error. */
  2865. static int
  2866. mg_fopen(const struct mg_connection *conn,
  2867. const char *path,
  2868. int mode,
  2869. struct mg_file *filep)
  2870. {
  2871. int found;
  2872. if (!filep) {
  2873. return 0;
  2874. }
  2875. filep->access.fp = NULL;
  2876. #if defined(MG_USE_OPEN_FILE)
  2877. filep->access.membuf = NULL;
  2878. #endif
  2879. if (!is_file_in_memory(conn, path)) {
  2880. /* filep is initialized in mg_stat: all fields with memset to,
  2881. * some fields like size and modification date with values */
  2882. found = mg_stat(conn, path, &(filep->stat));
  2883. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2884. /* file does not exist and will not be created */
  2885. return 0;
  2886. }
  2887. #if defined(_WIN32)
  2888. {
  2889. wchar_t wbuf[W_PATH_MAX];
  2890. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2891. switch (mode) {
  2892. case MG_FOPEN_MODE_READ:
  2893. filep->access.fp = _wfopen(wbuf, L"rb");
  2894. break;
  2895. case MG_FOPEN_MODE_WRITE:
  2896. filep->access.fp = _wfopen(wbuf, L"wb");
  2897. break;
  2898. case MG_FOPEN_MODE_APPEND:
  2899. filep->access.fp = _wfopen(wbuf, L"ab");
  2900. break;
  2901. }
  2902. }
  2903. #else
  2904. /* Linux et al already use unicode. No need to convert. */
  2905. switch (mode) {
  2906. case MG_FOPEN_MODE_READ:
  2907. filep->access.fp = fopen(path, "r");
  2908. break;
  2909. case MG_FOPEN_MODE_WRITE:
  2910. filep->access.fp = fopen(path, "w");
  2911. break;
  2912. case MG_FOPEN_MODE_APPEND:
  2913. filep->access.fp = fopen(path, "a");
  2914. break;
  2915. }
  2916. #endif
  2917. if (!found) {
  2918. /* File did not exist before fopen was called.
  2919. * Maybe it has been created now. Get stat info
  2920. * like creation time now. */
  2921. found = mg_stat(conn, path, &(filep->stat));
  2922. (void)found;
  2923. }
  2924. /* file is on disk */
  2925. return (filep->access.fp != NULL);
  2926. } else {
  2927. #if defined(MG_USE_OPEN_FILE)
  2928. /* is_file_in_memory returned true */
  2929. if (open_file_in_memory(conn, path, filep, mode)) {
  2930. /* file is in memory */
  2931. return (filep->access.membuf != NULL);
  2932. }
  2933. #endif
  2934. }
  2935. /* Open failed */
  2936. return 0;
  2937. }
  2938. /* return 0 on success, just like fclose */
  2939. static int
  2940. mg_fclose(struct mg_file_access *fileacc)
  2941. {
  2942. int ret = -1;
  2943. if (fileacc != NULL) {
  2944. if (fileacc->fp != NULL) {
  2945. ret = fclose(fileacc->fp);
  2946. #if defined(MG_USE_OPEN_FILE)
  2947. } else if (fileacc->membuf != NULL) {
  2948. ret = 0;
  2949. #endif
  2950. }
  2951. /* reset all members of fileacc */
  2952. memset(fileacc, 0, sizeof(*fileacc));
  2953. }
  2954. return ret;
  2955. }
  2956. #endif /* NO_FILESYSTEMS */
  2957. static void
  2958. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2959. {
  2960. for (; *src != '\0' && n > 1; n--) {
  2961. *dst++ = *src++;
  2962. }
  2963. *dst = '\0';
  2964. }
  2965. static int
  2966. lowercase(const char *s)
  2967. {
  2968. return tolower((unsigned char)*s);
  2969. }
  2970. int
  2971. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2972. {
  2973. int diff = 0;
  2974. if (len > 0) {
  2975. do {
  2976. diff = lowercase(s1++) - lowercase(s2++);
  2977. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2978. }
  2979. return diff;
  2980. }
  2981. int
  2982. mg_strcasecmp(const char *s1, const char *s2)
  2983. {
  2984. int diff;
  2985. do {
  2986. diff = lowercase(s1++) - lowercase(s2++);
  2987. } while (diff == 0 && s1[-1] != '\0');
  2988. return diff;
  2989. }
  2990. static char *
  2991. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2992. {
  2993. char *p;
  2994. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2995. * defined */
  2996. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2997. mg_strlcpy(p, ptr, len + 1);
  2998. }
  2999. return p;
  3000. }
  3001. static char *
  3002. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3003. {
  3004. return mg_strndup_ctx(str, strlen(str), ctx);
  3005. }
  3006. static char *
  3007. mg_strdup(const char *str)
  3008. {
  3009. return mg_strndup_ctx(str, strlen(str), NULL);
  3010. }
  3011. static const char *
  3012. mg_strcasestr(const char *big_str, const char *small_str)
  3013. {
  3014. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3015. if (big_len >= small_len) {
  3016. for (i = 0; i <= (big_len - small_len); i++) {
  3017. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3018. return big_str + i;
  3019. }
  3020. }
  3021. }
  3022. return NULL;
  3023. }
  3024. /* Return null terminated string of given maximum length.
  3025. * Report errors if length is exceeded. */
  3026. static void
  3027. mg_vsnprintf(const struct mg_connection *conn,
  3028. int *truncated,
  3029. char *buf,
  3030. size_t buflen,
  3031. const char *fmt,
  3032. va_list ap)
  3033. {
  3034. int n, ok;
  3035. if (buflen == 0) {
  3036. if (truncated) {
  3037. *truncated = 1;
  3038. }
  3039. return;
  3040. }
  3041. #if defined(__clang__)
  3042. #pragma clang diagnostic push
  3043. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3044. /* Using fmt as a non-literal is intended here, since it is mostly called
  3045. * indirectly by mg_snprintf */
  3046. #endif
  3047. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3048. ok = (n >= 0) && ((size_t)n < buflen);
  3049. #if defined(__clang__)
  3050. #pragma clang diagnostic pop
  3051. #endif
  3052. if (ok) {
  3053. if (truncated) {
  3054. *truncated = 0;
  3055. }
  3056. } else {
  3057. if (truncated) {
  3058. *truncated = 1;
  3059. }
  3060. mg_cry_internal(conn,
  3061. "truncating vsnprintf buffer: [%.*s]",
  3062. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3063. buf);
  3064. n = (int)buflen - 1;
  3065. }
  3066. buf[n] = '\0';
  3067. }
  3068. static void
  3069. mg_snprintf(const struct mg_connection *conn,
  3070. int *truncated,
  3071. char *buf,
  3072. size_t buflen,
  3073. const char *fmt,
  3074. ...)
  3075. {
  3076. va_list ap;
  3077. va_start(ap, fmt);
  3078. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3079. va_end(ap);
  3080. }
  3081. static int
  3082. get_option_index(const char *name)
  3083. {
  3084. int i;
  3085. for (i = 0; config_options[i].name != NULL; i++) {
  3086. if (strcmp(config_options[i].name, name) == 0) {
  3087. return i;
  3088. }
  3089. }
  3090. return -1;
  3091. }
  3092. const char *
  3093. mg_get_option(const struct mg_context *ctx, const char *name)
  3094. {
  3095. int i;
  3096. if ((i = get_option_index(name)) == -1) {
  3097. return NULL;
  3098. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3099. return "";
  3100. } else {
  3101. return ctx->dd.config[i];
  3102. }
  3103. }
  3104. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3105. struct mg_context *
  3106. mg_get_context(const struct mg_connection *conn)
  3107. {
  3108. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3109. }
  3110. void *
  3111. mg_get_user_data(const struct mg_context *ctx)
  3112. {
  3113. return (ctx == NULL) ? NULL : ctx->user_data;
  3114. }
  3115. void *
  3116. mg_get_user_context_data(const struct mg_connection *conn)
  3117. {
  3118. return mg_get_user_data(mg_get_context(conn));
  3119. }
  3120. void *
  3121. mg_get_thread_pointer(const struct mg_connection *conn)
  3122. {
  3123. /* both methods should return the same pointer */
  3124. if (conn) {
  3125. /* quick access, in case conn is known */
  3126. return conn->tls_user_ptr;
  3127. } else {
  3128. /* otherwise get pointer from thread local storage (TLS) */
  3129. struct mg_workerTLS *tls =
  3130. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3131. return tls->user_ptr;
  3132. }
  3133. }
  3134. void
  3135. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3136. {
  3137. if (conn != NULL) {
  3138. conn->request_info.conn_data = data;
  3139. }
  3140. }
  3141. void *
  3142. mg_get_user_connection_data(const struct mg_connection *conn)
  3143. {
  3144. if (conn != NULL) {
  3145. return conn->request_info.conn_data;
  3146. }
  3147. return NULL;
  3148. }
  3149. #if defined(MG_LEGACY_INTERFACE)
  3150. /* Deprecated: Use mg_get_server_ports instead. */
  3151. size_t
  3152. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3153. {
  3154. size_t i;
  3155. if (!ctx) {
  3156. return 0;
  3157. }
  3158. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3159. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3160. ports[i] =
  3161. #if defined(USE_IPV6)
  3162. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3163. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3164. :
  3165. #endif
  3166. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3167. }
  3168. return i;
  3169. }
  3170. #endif
  3171. int
  3172. mg_get_server_ports(const struct mg_context *ctx,
  3173. int size,
  3174. struct mg_server_port *ports)
  3175. {
  3176. int i, cnt = 0;
  3177. if (size <= 0) {
  3178. return -1;
  3179. }
  3180. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3181. if (!ctx) {
  3182. return -1;
  3183. }
  3184. if (!ctx->listening_sockets) {
  3185. return -1;
  3186. }
  3187. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3188. ports[cnt].port =
  3189. #if defined(USE_IPV6)
  3190. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3191. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3192. :
  3193. #endif
  3194. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3195. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3196. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3197. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3198. /* IPv4 */
  3199. ports[cnt].protocol = 1;
  3200. cnt++;
  3201. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3202. /* IPv6 */
  3203. ports[cnt].protocol = 3;
  3204. cnt++;
  3205. }
  3206. }
  3207. return cnt;
  3208. }
  3209. static void
  3210. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3211. {
  3212. buf[0] = '\0';
  3213. if (!usa) {
  3214. return;
  3215. }
  3216. if (usa->sa.sa_family == AF_INET) {
  3217. getnameinfo(&usa->sa,
  3218. sizeof(usa->sin),
  3219. buf,
  3220. (unsigned)len,
  3221. NULL,
  3222. 0,
  3223. NI_NUMERICHOST);
  3224. }
  3225. #if defined(USE_IPV6)
  3226. else if (usa->sa.sa_family == AF_INET6) {
  3227. getnameinfo(&usa->sa,
  3228. sizeof(usa->sin6),
  3229. buf,
  3230. (unsigned)len,
  3231. NULL,
  3232. 0,
  3233. NI_NUMERICHOST);
  3234. }
  3235. #endif
  3236. }
  3237. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3238. * included in all responses other than 100, 101, 5xx. */
  3239. static void
  3240. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3241. {
  3242. #if !defined(REENTRANT_TIME)
  3243. struct tm *tm;
  3244. tm = ((t != NULL) ? gmtime(t) : NULL);
  3245. if (tm != NULL) {
  3246. #else
  3247. struct tm _tm;
  3248. struct tm *tm = &_tm;
  3249. if (t != NULL) {
  3250. gmtime_r(t, tm);
  3251. #endif
  3252. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3253. } else {
  3254. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3255. buf[buf_len - 1] = '\0';
  3256. }
  3257. }
  3258. /* difftime for struct timespec. Return value is in seconds. */
  3259. static double
  3260. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3261. {
  3262. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3263. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3264. }
  3265. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3266. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3267. const char *func,
  3268. unsigned line,
  3269. const char *fmt,
  3270. va_list ap);
  3271. #include "external_mg_cry_internal_impl.inl"
  3272. #elif !defined(NO_FILESYSTEMS)
  3273. /* Print error message to the opened error log stream. */
  3274. static void
  3275. mg_cry_internal_impl(const struct mg_connection *conn,
  3276. const char *func,
  3277. unsigned line,
  3278. const char *fmt,
  3279. va_list ap)
  3280. {
  3281. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3282. struct mg_file fi;
  3283. time_t timestamp;
  3284. /* Unused, in the RELEASE build */
  3285. (void)func;
  3286. (void)line;
  3287. #if defined(GCC_DIAGNOSTIC)
  3288. #pragma GCC diagnostic push
  3289. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3290. #endif
  3291. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3292. #if defined(GCC_DIAGNOSTIC)
  3293. #pragma GCC diagnostic pop
  3294. #endif
  3295. buf[sizeof(buf) - 1] = 0;
  3296. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3297. if (!conn) {
  3298. puts(buf);
  3299. return;
  3300. }
  3301. /* Do not lock when getting the callback value, here and below.
  3302. * I suppose this is fine, since function cannot disappear in the
  3303. * same way string option can. */
  3304. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3305. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3306. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3307. if (mg_fopen(conn,
  3308. conn->dom_ctx->config[ERROR_LOG_FILE],
  3309. MG_FOPEN_MODE_APPEND,
  3310. &fi)
  3311. == 0) {
  3312. fi.access.fp = NULL;
  3313. }
  3314. } else {
  3315. fi.access.fp = NULL;
  3316. }
  3317. if (fi.access.fp != NULL) {
  3318. flockfile(fi.access.fp);
  3319. timestamp = time(NULL);
  3320. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3321. fprintf(fi.access.fp,
  3322. "[%010lu] [error] [client %s] ",
  3323. (unsigned long)timestamp,
  3324. src_addr);
  3325. if (conn->request_info.request_method != NULL) {
  3326. fprintf(fi.access.fp,
  3327. "%s %s: ",
  3328. conn->request_info.request_method,
  3329. conn->request_info.request_uri
  3330. ? conn->request_info.request_uri
  3331. : "");
  3332. }
  3333. fprintf(fi.access.fp, "%s", buf);
  3334. fputc('\n', fi.access.fp);
  3335. fflush(fi.access.fp);
  3336. funlockfile(fi.access.fp);
  3337. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3338. * mg_cry here anyway ;-) */
  3339. }
  3340. }
  3341. }
  3342. #else
  3343. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3344. #endif /* Externally provided function */
  3345. /* Construct fake connection structure. Used for logging, if connection
  3346. * is not applicable at the moment of logging. */
  3347. static struct mg_connection *
  3348. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3349. {
  3350. static const struct mg_connection conn_zero = {0};
  3351. *fc = conn_zero;
  3352. fc->phys_ctx = ctx;
  3353. fc->dom_ctx = &(ctx->dd);
  3354. return fc;
  3355. }
  3356. static void
  3357. mg_cry_internal_wrap(const struct mg_connection *conn,
  3358. struct mg_context *ctx,
  3359. const char *func,
  3360. unsigned line,
  3361. const char *fmt,
  3362. ...)
  3363. {
  3364. va_list ap;
  3365. va_start(ap, fmt);
  3366. if (!conn && ctx) {
  3367. struct mg_connection fc;
  3368. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3369. } else {
  3370. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3371. }
  3372. va_end(ap);
  3373. }
  3374. void
  3375. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3376. {
  3377. va_list ap;
  3378. va_start(ap, fmt);
  3379. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3380. va_end(ap);
  3381. }
  3382. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3383. const char *
  3384. mg_version(void)
  3385. {
  3386. return CIVETWEB_VERSION;
  3387. }
  3388. const struct mg_request_info *
  3389. mg_get_request_info(const struct mg_connection *conn)
  3390. {
  3391. if (!conn) {
  3392. return NULL;
  3393. }
  3394. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3395. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3396. char txt[16];
  3397. struct mg_workerTLS *tls =
  3398. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3399. sprintf(txt, "%03i", conn->response_info.status_code);
  3400. if (strlen(txt) == 3) {
  3401. memcpy(tls->txtbuf, txt, 4);
  3402. } else {
  3403. strcpy(tls->txtbuf, "ERR");
  3404. }
  3405. ((struct mg_connection *)conn)->request_info.local_uri =
  3406. ((struct mg_connection *)conn)->request_info.request_uri =
  3407. tls->txtbuf; /* use thread safe buffer */
  3408. ((struct mg_connection *)conn)->request_info.num_headers =
  3409. conn->response_info.num_headers;
  3410. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3411. conn->response_info.http_headers,
  3412. sizeof(conn->response_info.http_headers));
  3413. } else
  3414. #endif
  3415. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3416. return NULL;
  3417. }
  3418. return &conn->request_info;
  3419. }
  3420. const struct mg_response_info *
  3421. mg_get_response_info(const struct mg_connection *conn)
  3422. {
  3423. if (!conn) {
  3424. return NULL;
  3425. }
  3426. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3427. return NULL;
  3428. }
  3429. return &conn->response_info;
  3430. }
  3431. static const char *
  3432. get_proto_name(const struct mg_connection *conn)
  3433. {
  3434. #if defined(__clang__)
  3435. #pragma clang diagnostic push
  3436. #pragma clang diagnostic ignored "-Wunreachable-code"
  3437. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3438. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3439. * unreachable, but splitting into four different #ifdef clauses here is more
  3440. * complicated.
  3441. */
  3442. #endif
  3443. const struct mg_request_info *ri = &conn->request_info;
  3444. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3445. ? (ri->is_ssl ? "wss" : "ws")
  3446. : (ri->is_ssl ? "https" : "http"));
  3447. return proto;
  3448. #if defined(__clang__)
  3449. #pragma clang diagnostic pop
  3450. #endif
  3451. }
  3452. int
  3453. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3454. {
  3455. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3456. return -1;
  3457. } else {
  3458. int truncated = 0;
  3459. const struct mg_request_info *ri = &conn->request_info;
  3460. const char *proto = get_proto_name(conn);
  3461. if (ri->local_uri == NULL) {
  3462. return -1;
  3463. }
  3464. if ((ri->request_uri != NULL)
  3465. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3466. /* The request uri is different from the local uri.
  3467. * This is usually if an absolute URI, including server
  3468. * name has been provided. */
  3469. mg_snprintf(conn,
  3470. &truncated,
  3471. buf,
  3472. buflen,
  3473. "%s://%s",
  3474. proto,
  3475. ri->request_uri);
  3476. if (truncated) {
  3477. return -1;
  3478. }
  3479. return 0;
  3480. } else {
  3481. /* The common case is a relative URI, so we have to
  3482. * construct an absolute URI from server name and port */
  3483. #if defined(USE_IPV6)
  3484. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3485. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3486. : htons(conn->client.lsa.sin.sin_port);
  3487. #else
  3488. int port = htons(conn->client.lsa.sin.sin_port);
  3489. #endif
  3490. int def_port = ri->is_ssl ? 443 : 80;
  3491. int auth_domain_check_enabled =
  3492. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3493. && (!mg_strcasecmp(
  3494. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3495. const char *server_domain =
  3496. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3497. char portstr[16];
  3498. char server_ip[48];
  3499. if (port != def_port) {
  3500. sprintf(portstr, ":%u", (unsigned)port);
  3501. } else {
  3502. portstr[0] = 0;
  3503. }
  3504. if (!auth_domain_check_enabled || !server_domain) {
  3505. sockaddr_to_string(server_ip,
  3506. sizeof(server_ip),
  3507. &conn->client.lsa);
  3508. server_domain = server_ip;
  3509. }
  3510. mg_snprintf(conn,
  3511. &truncated,
  3512. buf,
  3513. buflen,
  3514. #if defined(USE_IPV6)
  3515. "%s://%s%s%s%s%s",
  3516. proto,
  3517. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3518. server_domain,
  3519. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3520. #else
  3521. "%s://%s%s%s",
  3522. proto,
  3523. server_domain,
  3524. #endif
  3525. portstr,
  3526. ri->local_uri);
  3527. if (truncated) {
  3528. return -1;
  3529. }
  3530. return 0;
  3531. }
  3532. }
  3533. }
  3534. /* Skip the characters until one of the delimiters characters found.
  3535. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3536. * Advance pointer to buffer to the next word. Return found 0-terminated
  3537. * word.
  3538. * Delimiters can be quoted with quotechar. */
  3539. static char *
  3540. skip_quoted(char **buf,
  3541. const char *delimiters,
  3542. const char *whitespace,
  3543. char quotechar)
  3544. {
  3545. char *p, *begin_word, *end_word, *end_whitespace;
  3546. begin_word = *buf;
  3547. end_word = begin_word + strcspn(begin_word, delimiters);
  3548. /* Check for quotechar */
  3549. if (end_word > begin_word) {
  3550. p = end_word - 1;
  3551. while (*p == quotechar) {
  3552. /* While the delimiter is quoted, look for the next delimiter.
  3553. */
  3554. /* This happens, e.g., in calls from parse_auth_header,
  3555. * if the user name contains a " character. */
  3556. /* If there is anything beyond end_word, copy it. */
  3557. if (*end_word != '\0') {
  3558. size_t end_off = strcspn(end_word + 1, delimiters);
  3559. memmove(p, end_word, end_off + 1);
  3560. p += end_off; /* p must correspond to end_word - 1 */
  3561. end_word += end_off + 1;
  3562. } else {
  3563. *p = '\0';
  3564. break;
  3565. }
  3566. }
  3567. for (p++; p < end_word; p++) {
  3568. *p = '\0';
  3569. }
  3570. }
  3571. if (*end_word == '\0') {
  3572. *buf = end_word;
  3573. } else {
  3574. #if defined(GCC_DIAGNOSTIC)
  3575. /* Disable spurious conversion warning for GCC */
  3576. #pragma GCC diagnostic push
  3577. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3578. #endif /* defined(GCC_DIAGNOSTIC) */
  3579. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3580. #if defined(GCC_DIAGNOSTIC)
  3581. #pragma GCC diagnostic pop
  3582. #endif /* defined(GCC_DIAGNOSTIC) */
  3583. for (p = end_word; p < end_whitespace; p++) {
  3584. *p = '\0';
  3585. }
  3586. *buf = end_whitespace;
  3587. }
  3588. return begin_word;
  3589. }
  3590. /* Return HTTP header value, or NULL if not found. */
  3591. static const char *
  3592. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3593. {
  3594. int i;
  3595. for (i = 0; i < num_hdr; i++) {
  3596. if (!mg_strcasecmp(name, hdr[i].name)) {
  3597. return hdr[i].value;
  3598. }
  3599. }
  3600. return NULL;
  3601. }
  3602. #if defined(USE_WEBSOCKET)
  3603. /* Retrieve requested HTTP header multiple values, and return the number of
  3604. * found occurrences */
  3605. static int
  3606. get_req_headers(const struct mg_request_info *ri,
  3607. const char *name,
  3608. const char **output,
  3609. int output_max_size)
  3610. {
  3611. int i;
  3612. int cnt = 0;
  3613. if (ri) {
  3614. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3615. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3616. output[cnt++] = ri->http_headers[i].value;
  3617. }
  3618. }
  3619. }
  3620. return cnt;
  3621. }
  3622. #endif
  3623. const char *
  3624. mg_get_header(const struct mg_connection *conn, const char *name)
  3625. {
  3626. if (!conn) {
  3627. return NULL;
  3628. }
  3629. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3630. return get_header(conn->request_info.http_headers,
  3631. conn->request_info.num_headers,
  3632. name);
  3633. }
  3634. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3635. return get_header(conn->response_info.http_headers,
  3636. conn->response_info.num_headers,
  3637. name);
  3638. }
  3639. return NULL;
  3640. }
  3641. static const char *
  3642. get_http_version(const struct mg_connection *conn)
  3643. {
  3644. if (!conn) {
  3645. return NULL;
  3646. }
  3647. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3648. return conn->request_info.http_version;
  3649. }
  3650. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3651. return conn->response_info.http_version;
  3652. }
  3653. return NULL;
  3654. }
  3655. /* A helper function for traversing a comma separated list of values.
  3656. * It returns a list pointer shifted to the next value, or NULL if the end
  3657. * of the list found.
  3658. * Value is stored in val vector. If value has form "x=y", then eq_val
  3659. * vector is initialized to point to the "y" part, and val vector length
  3660. * is adjusted to point only to "x". */
  3661. static const char *
  3662. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3663. {
  3664. int end;
  3665. reparse:
  3666. if (val == NULL || list == NULL || *list == '\0') {
  3667. /* End of the list */
  3668. return NULL;
  3669. }
  3670. /* Skip over leading LWS */
  3671. while (*list == ' ' || *list == '\t')
  3672. list++;
  3673. val->ptr = list;
  3674. if ((list = strchr(val->ptr, ',')) != NULL) {
  3675. /* Comma found. Store length and shift the list ptr */
  3676. val->len = ((size_t)(list - val->ptr));
  3677. list++;
  3678. } else {
  3679. /* This value is the last one */
  3680. list = val->ptr + strlen(val->ptr);
  3681. val->len = ((size_t)(list - val->ptr));
  3682. }
  3683. /* Adjust length for trailing LWS */
  3684. end = (int)val->len - 1;
  3685. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3686. end--;
  3687. val->len = (size_t)(end) + (size_t)(1);
  3688. if (val->len == 0) {
  3689. /* Ignore any empty entries. */
  3690. goto reparse;
  3691. }
  3692. if (eq_val != NULL) {
  3693. /* Value has form "x=y", adjust pointers and lengths
  3694. * so that val points to "x", and eq_val points to "y". */
  3695. eq_val->len = 0;
  3696. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3697. if (eq_val->ptr != NULL) {
  3698. eq_val->ptr++; /* Skip over '=' character */
  3699. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3700. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3701. }
  3702. }
  3703. return list;
  3704. }
  3705. /* A helper function for checking if a comma separated list of values
  3706. * contains
  3707. * the given option (case insensitvely).
  3708. * 'header' can be NULL, in which case false is returned. */
  3709. static int
  3710. header_has_option(const char *header, const char *option)
  3711. {
  3712. struct vec opt_vec;
  3713. struct vec eq_vec;
  3714. DEBUG_ASSERT(option != NULL);
  3715. DEBUG_ASSERT(option[0] != '\0');
  3716. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3717. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3718. return 1;
  3719. }
  3720. return 0;
  3721. }
  3722. /* Perform case-insensitive match of string against pattern */
  3723. static ptrdiff_t
  3724. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3725. {
  3726. const char *or_str;
  3727. ptrdiff_t i, j, len, res;
  3728. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3729. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3730. return (res > 0) ? res
  3731. : match_prefix(or_str + 1,
  3732. (size_t)((pattern + pattern_len)
  3733. - (or_str + 1)),
  3734. str);
  3735. }
  3736. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3737. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3738. continue;
  3739. } else if (pattern[i] == '$') {
  3740. return (str[j] == '\0') ? j : -1;
  3741. } else if (pattern[i] == '*') {
  3742. i++;
  3743. if (pattern[i] == '*') {
  3744. i++;
  3745. len = (ptrdiff_t)strlen(str + j);
  3746. } else {
  3747. len = (ptrdiff_t)strcspn(str + j, "/");
  3748. }
  3749. if (i == (ptrdiff_t)pattern_len) {
  3750. return j + len;
  3751. }
  3752. do {
  3753. res = match_prefix(pattern + i,
  3754. (pattern_len - (size_t)i),
  3755. str + j + len);
  3756. } while (res == -1 && len-- > 0);
  3757. return (res == -1) ? -1 : j + res + len;
  3758. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3759. return -1;
  3760. }
  3761. }
  3762. return (ptrdiff_t)j;
  3763. }
  3764. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3765. * This function must tolerate situations when connection info is not
  3766. * set up, for example if request parsing failed. */
  3767. static int
  3768. should_keep_alive(const struct mg_connection *conn)
  3769. {
  3770. const char *http_version;
  3771. const char *header;
  3772. /* First satisfy needs of the server */
  3773. if ((conn == NULL) || conn->must_close) {
  3774. /* Close, if civetweb framework needs to close */
  3775. return 0;
  3776. }
  3777. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3778. /* Close, if keep alive is not enabled */
  3779. return 0;
  3780. }
  3781. /* Check explicit wish of the client */
  3782. header = mg_get_header(conn, "Connection");
  3783. if (header) {
  3784. /* If there is a connection header from the client, obey */
  3785. if (header_has_option(header, "keep-alive")) {
  3786. return 1;
  3787. }
  3788. return 0;
  3789. }
  3790. /* Use default of the standard */
  3791. http_version = get_http_version(conn);
  3792. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3793. /* HTTP 1.1 default is keep alive */
  3794. return 1;
  3795. }
  3796. /* HTTP 1.0 (and earlier) default is to close the connection */
  3797. return 0;
  3798. }
  3799. static int
  3800. should_decode_url(const struct mg_connection *conn)
  3801. {
  3802. if (!conn || !conn->dom_ctx) {
  3803. return 0;
  3804. }
  3805. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3806. }
  3807. static const char *
  3808. suggest_connection_header(const struct mg_connection *conn)
  3809. {
  3810. return should_keep_alive(conn) ? "keep-alive" : "close";
  3811. }
  3812. static int
  3813. send_no_cache_header(struct mg_connection *conn)
  3814. {
  3815. /* Send all current and obsolete cache opt-out directives. */
  3816. return mg_printf(conn,
  3817. "Cache-Control: no-cache, no-store, "
  3818. "must-revalidate, private, max-age=0\r\n"
  3819. "Pragma: no-cache\r\n"
  3820. "Expires: 0\r\n");
  3821. }
  3822. static int
  3823. send_static_cache_header(struct mg_connection *conn)
  3824. {
  3825. #if !defined(NO_CACHING)
  3826. int max_age;
  3827. const char *cache_control =
  3828. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3829. if (cache_control != NULL) {
  3830. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3831. }
  3832. /* Read the server config to check how long a file may be cached.
  3833. * The configuration is in seconds. */
  3834. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3835. if (max_age <= 0) {
  3836. /* 0 means "do not cache". All values <0 are reserved
  3837. * and may be used differently in the future. */
  3838. /* If a file should not be cached, do not only send
  3839. * max-age=0, but also pragmas and Expires headers. */
  3840. return send_no_cache_header(conn);
  3841. }
  3842. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3843. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3844. /* See also https://www.mnot.net/cache_docs/ */
  3845. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3846. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3847. * leap
  3848. * year to 31622400 seconds. For the moment, we just send whatever has
  3849. * been configured, still the behavior for >1 year should be considered
  3850. * as undefined. */
  3851. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3852. #else /* NO_CACHING */
  3853. return send_no_cache_header(conn);
  3854. #endif /* !NO_CACHING */
  3855. }
  3856. static int
  3857. send_additional_header(struct mg_connection *conn)
  3858. {
  3859. int i = 0;
  3860. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3861. #if !defined(NO_SSL)
  3862. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3863. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3864. if (max_age >= 0) {
  3865. i += mg_printf(conn,
  3866. "Strict-Transport-Security: max-age=%u\r\n",
  3867. (unsigned)max_age);
  3868. }
  3869. }
  3870. #endif
  3871. if (header && header[0]) {
  3872. i += mg_printf(conn, "%s\r\n", header);
  3873. }
  3874. return i;
  3875. }
  3876. #if !defined(NO_FILESYSTEMS)
  3877. static void handle_file_based_request(struct mg_connection *conn,
  3878. const char *path,
  3879. struct mg_file *filep);
  3880. #endif /* NO_FILESYSTEMS */
  3881. const char *
  3882. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3883. {
  3884. /* See IANA HTTP status code assignment:
  3885. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3886. */
  3887. switch (response_code) {
  3888. /* RFC2616 Section 10.1 - Informational 1xx */
  3889. case 100:
  3890. return "Continue"; /* RFC2616 Section 10.1.1 */
  3891. case 101:
  3892. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3893. case 102:
  3894. return "Processing"; /* RFC2518 Section 10.1 */
  3895. /* RFC2616 Section 10.2 - Successful 2xx */
  3896. case 200:
  3897. return "OK"; /* RFC2616 Section 10.2.1 */
  3898. case 201:
  3899. return "Created"; /* RFC2616 Section 10.2.2 */
  3900. case 202:
  3901. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3902. case 203:
  3903. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3904. case 204:
  3905. return "No Content"; /* RFC2616 Section 10.2.5 */
  3906. case 205:
  3907. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3908. case 206:
  3909. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3910. case 207:
  3911. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3912. */
  3913. case 208:
  3914. return "Already Reported"; /* RFC5842 Section 7.1 */
  3915. case 226:
  3916. return "IM used"; /* RFC3229 Section 10.4.1 */
  3917. /* RFC2616 Section 10.3 - Redirection 3xx */
  3918. case 300:
  3919. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3920. case 301:
  3921. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3922. case 302:
  3923. return "Found"; /* RFC2616 Section 10.3.3 */
  3924. case 303:
  3925. return "See Other"; /* RFC2616 Section 10.3.4 */
  3926. case 304:
  3927. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3928. case 305:
  3929. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3930. case 307:
  3931. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3932. case 308:
  3933. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3934. /* RFC2616 Section 10.4 - Client Error 4xx */
  3935. case 400:
  3936. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3937. case 401:
  3938. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3939. case 402:
  3940. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3941. case 403:
  3942. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3943. case 404:
  3944. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3945. case 405:
  3946. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3947. case 406:
  3948. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3949. case 407:
  3950. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3951. case 408:
  3952. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3953. case 409:
  3954. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3955. case 410:
  3956. return "Gone"; /* RFC2616 Section 10.4.11 */
  3957. case 411:
  3958. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3959. case 412:
  3960. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3961. case 413:
  3962. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3963. case 414:
  3964. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3965. case 415:
  3966. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3967. case 416:
  3968. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3969. */
  3970. case 417:
  3971. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3972. case 421:
  3973. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3974. case 422:
  3975. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3976. * Section 11.2 */
  3977. case 423:
  3978. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3979. case 424:
  3980. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3981. * Section 11.4 */
  3982. case 426:
  3983. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3984. case 428:
  3985. return "Precondition Required"; /* RFC 6585, Section 3 */
  3986. case 429:
  3987. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3988. case 431:
  3989. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3990. case 451:
  3991. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3992. * Section 3 */
  3993. /* RFC2616 Section 10.5 - Server Error 5xx */
  3994. case 500:
  3995. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3996. case 501:
  3997. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3998. case 502:
  3999. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4000. case 503:
  4001. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4002. case 504:
  4003. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4004. case 505:
  4005. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4006. case 506:
  4007. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4008. case 507:
  4009. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4010. * Section 11.5 */
  4011. case 508:
  4012. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4013. case 510:
  4014. return "Not Extended"; /* RFC 2774, Section 7 */
  4015. case 511:
  4016. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4017. /* Other status codes, not shown in the IANA HTTP status code
  4018. * assignment.
  4019. * E.g., "de facto" standards due to common use, ... */
  4020. case 418:
  4021. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4022. case 419:
  4023. return "Authentication Timeout"; /* common use */
  4024. case 420:
  4025. return "Enhance Your Calm"; /* common use */
  4026. case 440:
  4027. return "Login Timeout"; /* common use */
  4028. case 509:
  4029. return "Bandwidth Limit Exceeded"; /* common use */
  4030. default:
  4031. /* This error code is unknown. This should not happen. */
  4032. if (conn) {
  4033. mg_cry_internal(conn,
  4034. "Unknown HTTP response code: %u",
  4035. response_code);
  4036. }
  4037. /* Return at least a category according to RFC 2616 Section 10. */
  4038. if (response_code >= 100 && response_code < 200) {
  4039. /* Unknown informational status code */
  4040. return "Information";
  4041. }
  4042. if (response_code >= 200 && response_code < 300) {
  4043. /* Unknown success code */
  4044. return "Success";
  4045. }
  4046. if (response_code >= 300 && response_code < 400) {
  4047. /* Unknown redirection code */
  4048. return "Redirection";
  4049. }
  4050. if (response_code >= 400 && response_code < 500) {
  4051. /* Unknown request error code */
  4052. return "Client Error";
  4053. }
  4054. if (response_code >= 500 && response_code < 600) {
  4055. /* Unknown server error code */
  4056. return "Server Error";
  4057. }
  4058. /* Response code not even within reasonable range */
  4059. return "";
  4060. }
  4061. }
  4062. static int
  4063. mg_send_http_error_impl(struct mg_connection *conn,
  4064. int status,
  4065. const char *fmt,
  4066. va_list args)
  4067. {
  4068. char errmsg_buf[MG_BUF_LEN];
  4069. va_list ap;
  4070. int has_body;
  4071. char date[64];
  4072. time_t curtime = time(NULL);
  4073. #if !defined(NO_FILESYSTEMS)
  4074. char path_buf[PATH_MAX];
  4075. int len, i, page_handler_found, scope, truncated;
  4076. const char *error_handler = NULL;
  4077. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4078. const char *error_page_file_ext, *tstr;
  4079. #endif /* NO_FILESYSTEMS */
  4080. int handled_by_callback = 0;
  4081. const char *status_text = mg_get_response_code_text(conn, status);
  4082. if ((conn == NULL) || (fmt == NULL)) {
  4083. return -2;
  4084. }
  4085. /* Set status (for log) */
  4086. conn->status_code = status;
  4087. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4088. has_body = ((status > 199) && (status != 204) && (status != 304));
  4089. /* Prepare message in buf, if required */
  4090. if (has_body
  4091. || (!conn->in_error_handler
  4092. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4093. /* Store error message in errmsg_buf */
  4094. va_copy(ap, args);
  4095. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4096. va_end(ap);
  4097. /* In a debug build, print all html errors */
  4098. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4099. }
  4100. /* If there is a http_error callback, call it.
  4101. * But don't do it recursively, if callback calls mg_send_http_error again.
  4102. */
  4103. if (!conn->in_error_handler
  4104. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4105. /* Mark in_error_handler to avoid recursion and call user callback. */
  4106. conn->in_error_handler = 1;
  4107. handled_by_callback =
  4108. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4109. == 0);
  4110. conn->in_error_handler = 0;
  4111. }
  4112. if (!handled_by_callback) {
  4113. /* Check for recursion */
  4114. if (conn->in_error_handler) {
  4115. DEBUG_TRACE(
  4116. "Recursion when handling error %u - fall back to default",
  4117. status);
  4118. #if !defined(NO_FILESYSTEMS)
  4119. } else {
  4120. /* Send user defined error pages, if defined */
  4121. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4122. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4123. page_handler_found = 0;
  4124. if (error_handler != NULL) {
  4125. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4126. switch (scope) {
  4127. case 1: /* Handler for specific error, e.g. 404 error */
  4128. mg_snprintf(conn,
  4129. &truncated,
  4130. path_buf,
  4131. sizeof(path_buf) - 32,
  4132. "%serror%03u.",
  4133. error_handler,
  4134. status);
  4135. break;
  4136. case 2: /* Handler for error group, e.g., 5xx error
  4137. * handler
  4138. * for all server errors (500-599) */
  4139. mg_snprintf(conn,
  4140. &truncated,
  4141. path_buf,
  4142. sizeof(path_buf) - 32,
  4143. "%serror%01uxx.",
  4144. error_handler,
  4145. status / 100);
  4146. break;
  4147. default: /* Handler for all errors */
  4148. mg_snprintf(conn,
  4149. &truncated,
  4150. path_buf,
  4151. sizeof(path_buf) - 32,
  4152. "%serror.",
  4153. error_handler);
  4154. break;
  4155. }
  4156. /* String truncation in buf may only occur if
  4157. * error_handler is too long. This string is
  4158. * from the config, not from a client. */
  4159. (void)truncated;
  4160. /* The following code is redundant, but it should avoid
  4161. * false positives in static source code analyzers and
  4162. * vulnerability scanners.
  4163. */
  4164. path_buf[sizeof(path_buf) - 32] = 0;
  4165. len = (int)strlen(path_buf);
  4166. if (len > (int)sizeof(path_buf) - 32) {
  4167. len = (int)sizeof(path_buf) - 32;
  4168. }
  4169. /* Start with the file extenstion from the configuration. */
  4170. tstr = strchr(error_page_file_ext, '.');
  4171. while (tstr) {
  4172. for (i = 1;
  4173. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4174. i++) {
  4175. /* buffer overrun is not possible here, since
  4176. * (i < 32) && (len < sizeof(path_buf) - 32)
  4177. * ==> (i + len) < sizeof(path_buf) */
  4178. path_buf[len + i - 1] = tstr[i];
  4179. }
  4180. /* buffer overrun is not possible here, since
  4181. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4182. * ==> (i + len) <= sizeof(path_buf) */
  4183. path_buf[len + i - 1] = 0;
  4184. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4185. DEBUG_TRACE("Check error page %s - found",
  4186. path_buf);
  4187. page_handler_found = 1;
  4188. break;
  4189. }
  4190. DEBUG_TRACE("Check error page %s - not found",
  4191. path_buf);
  4192. /* Continue with the next file extenstion from the
  4193. * configuration (if there is a next one). */
  4194. tstr = strchr(tstr + i, '.');
  4195. }
  4196. }
  4197. }
  4198. if (page_handler_found) {
  4199. conn->in_error_handler = 1;
  4200. handle_file_based_request(conn, path_buf, &error_page_file);
  4201. conn->in_error_handler = 0;
  4202. return 0;
  4203. }
  4204. #endif /* NO_FILESYSTEMS */
  4205. }
  4206. /* No custom error page. Send default error page. */
  4207. gmt_time_string(date, sizeof(date), &curtime);
  4208. conn->must_close = 1;
  4209. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4210. send_no_cache_header(conn);
  4211. send_additional_header(conn);
  4212. if (has_body) {
  4213. mg_printf(conn,
  4214. "%s",
  4215. "Content-Type: text/plain; charset=utf-8\r\n");
  4216. }
  4217. mg_printf(conn,
  4218. "Date: %s\r\n"
  4219. "Connection: close\r\n\r\n",
  4220. date);
  4221. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4222. if (has_body) {
  4223. /* For other errors, send a generic error message. */
  4224. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4225. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4226. } else {
  4227. /* No body allowed. Close the connection. */
  4228. DEBUG_TRACE("Error %i", status);
  4229. }
  4230. }
  4231. return 0;
  4232. }
  4233. int
  4234. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4235. {
  4236. va_list ap;
  4237. int ret;
  4238. va_start(ap, fmt);
  4239. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4240. va_end(ap);
  4241. return ret;
  4242. }
  4243. int
  4244. mg_send_http_ok(struct mg_connection *conn,
  4245. const char *mime_type,
  4246. long long content_length)
  4247. {
  4248. char date[64];
  4249. time_t curtime = time(NULL);
  4250. if ((mime_type == NULL) || (*mime_type == 0)) {
  4251. /* No content type defined: default to text/html */
  4252. mime_type = "text/html";
  4253. }
  4254. gmt_time_string(date, sizeof(date), &curtime);
  4255. mg_printf(conn,
  4256. "HTTP/1.1 200 OK\r\n"
  4257. "Content-Type: %s\r\n"
  4258. "Date: %s\r\n"
  4259. "Connection: %s\r\n",
  4260. mime_type,
  4261. date,
  4262. suggest_connection_header(conn));
  4263. send_no_cache_header(conn);
  4264. send_additional_header(conn);
  4265. if (content_length < 0) {
  4266. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4267. } else {
  4268. mg_printf(conn,
  4269. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4270. (uint64_t)content_length);
  4271. }
  4272. return 0;
  4273. }
  4274. int
  4275. mg_send_http_redirect(struct mg_connection *conn,
  4276. const char *target_url,
  4277. int redirect_code)
  4278. {
  4279. /* Send a 30x redirect response.
  4280. *
  4281. * Redirect types (status codes):
  4282. *
  4283. * Status | Perm/Temp | Method | Version
  4284. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4285. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4286. * 303 | temporary | always use GET | HTTP/1.1
  4287. * 307 | temporary | always keep method | HTTP/1.1
  4288. * 308 | permanent | always keep method | HTTP/1.1
  4289. */
  4290. const char *redirect_text;
  4291. int ret;
  4292. size_t content_len = 0;
  4293. char reply[MG_BUF_LEN];
  4294. /* In case redirect_code=0, use 307. */
  4295. if (redirect_code == 0) {
  4296. redirect_code = 307;
  4297. }
  4298. /* In case redirect_code is none of the above, return error. */
  4299. if ((redirect_code != 301) && (redirect_code != 302)
  4300. && (redirect_code != 303) && (redirect_code != 307)
  4301. && (redirect_code != 308)) {
  4302. /* Parameter error */
  4303. return -2;
  4304. }
  4305. /* Get proper text for response code */
  4306. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4307. /* If target_url is not defined, redirect to "/". */
  4308. if ((target_url == NULL) || (*target_url == 0)) {
  4309. target_url = "/";
  4310. }
  4311. #if defined(MG_SEND_REDIRECT_BODY)
  4312. /* TODO: condition name? */
  4313. /* Prepare a response body with a hyperlink.
  4314. *
  4315. * According to RFC2616 (and RFC1945 before):
  4316. * Unless the request method was HEAD, the entity of the
  4317. * response SHOULD contain a short hypertext note with a hyperlink to
  4318. * the new URI(s).
  4319. *
  4320. * However, this response body is not useful in M2M communication.
  4321. * Probably the original reason in the RFC was, clients not supporting
  4322. * a 30x HTTP redirect could still show the HTML page and let the user
  4323. * press the link. Since current browsers support 30x HTTP, the additional
  4324. * HTML body does not seem to make sense anymore.
  4325. *
  4326. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4327. * but it only notes:
  4328. * The server's response payload usually contains a short
  4329. * hypertext note with a hyperlink to the new URI(s).
  4330. *
  4331. * Deactivated by default. If you need the 30x body, set the define.
  4332. */
  4333. mg_snprintf(
  4334. conn,
  4335. NULL /* ignore truncation */,
  4336. reply,
  4337. sizeof(reply),
  4338. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4339. redirect_text,
  4340. target_url,
  4341. target_url);
  4342. content_len = strlen(reply);
  4343. #else
  4344. reply[0] = 0;
  4345. #endif
  4346. /* Do not send any additional header. For all other options,
  4347. * including caching, there are suitable defaults. */
  4348. ret = mg_printf(conn,
  4349. "HTTP/1.1 %i %s\r\n"
  4350. "Location: %s\r\n"
  4351. "Content-Length: %u\r\n"
  4352. "Connection: %s\r\n\r\n",
  4353. redirect_code,
  4354. redirect_text,
  4355. target_url,
  4356. (unsigned int)content_len,
  4357. suggest_connection_header(conn));
  4358. /* Send response body */
  4359. if (ret > 0) {
  4360. /* ... unless it is a HEAD request */
  4361. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4362. ret = mg_write(conn, reply, content_len);
  4363. }
  4364. }
  4365. return (ret > 0) ? ret : -1;
  4366. }
  4367. #if defined(_WIN32)
  4368. /* Create substitutes for POSIX functions in Win32. */
  4369. #if defined(GCC_DIAGNOSTIC)
  4370. /* Show no warning in case system functions are not used. */
  4371. #pragma GCC diagnostic push
  4372. #pragma GCC diagnostic ignored "-Wunused-function"
  4373. #endif
  4374. static int
  4375. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4376. {
  4377. (void)unused;
  4378. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4379. InitializeCriticalSection(&mutex->sec);
  4380. return 0;
  4381. }
  4382. static int
  4383. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4384. {
  4385. DeleteCriticalSection(&mutex->sec);
  4386. return 0;
  4387. }
  4388. static int
  4389. pthread_mutex_lock(pthread_mutex_t *mutex)
  4390. {
  4391. EnterCriticalSection(&mutex->sec);
  4392. return 0;
  4393. }
  4394. static int
  4395. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4396. {
  4397. LeaveCriticalSection(&mutex->sec);
  4398. return 0;
  4399. }
  4400. FUNCTION_MAY_BE_UNUSED
  4401. static int
  4402. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4403. {
  4404. (void)unused;
  4405. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4406. cv->waiting_thread = NULL;
  4407. return 0;
  4408. }
  4409. FUNCTION_MAY_BE_UNUSED
  4410. static int
  4411. pthread_cond_timedwait(pthread_cond_t *cv,
  4412. pthread_mutex_t *mutex,
  4413. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4414. {
  4415. struct mg_workerTLS **ptls,
  4416. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4417. int ok;
  4418. int64_t nsnow, nswaitabs, nswaitrel;
  4419. DWORD mswaitrel;
  4420. pthread_mutex_lock(&cv->threadIdSec);
  4421. /* Add this thread to cv's waiting list */
  4422. ptls = &cv->waiting_thread;
  4423. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4424. ;
  4425. tls->next_waiting_thread = NULL;
  4426. *ptls = tls;
  4427. pthread_mutex_unlock(&cv->threadIdSec);
  4428. if (abstime) {
  4429. nsnow = mg_get_current_time_ns();
  4430. nswaitabs =
  4431. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4432. nswaitrel = nswaitabs - nsnow;
  4433. if (nswaitrel < 0) {
  4434. nswaitrel = 0;
  4435. }
  4436. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4437. } else {
  4438. mswaitrel = (DWORD)INFINITE;
  4439. }
  4440. pthread_mutex_unlock(mutex);
  4441. ok = (WAIT_OBJECT_0
  4442. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4443. if (!ok) {
  4444. ok = 1;
  4445. pthread_mutex_lock(&cv->threadIdSec);
  4446. ptls = &cv->waiting_thread;
  4447. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4448. if (*ptls == tls) {
  4449. *ptls = tls->next_waiting_thread;
  4450. ok = 0;
  4451. break;
  4452. }
  4453. }
  4454. pthread_mutex_unlock(&cv->threadIdSec);
  4455. if (ok) {
  4456. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4457. (DWORD)INFINITE);
  4458. }
  4459. }
  4460. /* This thread has been removed from cv's waiting list */
  4461. pthread_mutex_lock(mutex);
  4462. return ok ? 0 : -1;
  4463. }
  4464. FUNCTION_MAY_BE_UNUSED
  4465. static int
  4466. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4467. {
  4468. return pthread_cond_timedwait(cv, mutex, NULL);
  4469. }
  4470. FUNCTION_MAY_BE_UNUSED
  4471. static int
  4472. pthread_cond_signal(pthread_cond_t *cv)
  4473. {
  4474. HANDLE wkup = NULL;
  4475. BOOL ok = FALSE;
  4476. pthread_mutex_lock(&cv->threadIdSec);
  4477. if (cv->waiting_thread) {
  4478. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4479. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4480. ok = SetEvent(wkup);
  4481. DEBUG_ASSERT(ok);
  4482. }
  4483. pthread_mutex_unlock(&cv->threadIdSec);
  4484. return ok ? 0 : 1;
  4485. }
  4486. FUNCTION_MAY_BE_UNUSED
  4487. static int
  4488. pthread_cond_broadcast(pthread_cond_t *cv)
  4489. {
  4490. pthread_mutex_lock(&cv->threadIdSec);
  4491. while (cv->waiting_thread) {
  4492. pthread_cond_signal(cv);
  4493. }
  4494. pthread_mutex_unlock(&cv->threadIdSec);
  4495. return 0;
  4496. }
  4497. FUNCTION_MAY_BE_UNUSED
  4498. static int
  4499. pthread_cond_destroy(pthread_cond_t *cv)
  4500. {
  4501. pthread_mutex_lock(&cv->threadIdSec);
  4502. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4503. pthread_mutex_unlock(&cv->threadIdSec);
  4504. pthread_mutex_destroy(&cv->threadIdSec);
  4505. return 0;
  4506. }
  4507. #if defined(ALTERNATIVE_QUEUE)
  4508. FUNCTION_MAY_BE_UNUSED
  4509. static void *
  4510. event_create(void)
  4511. {
  4512. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4513. }
  4514. FUNCTION_MAY_BE_UNUSED
  4515. static int
  4516. event_wait(void *eventhdl)
  4517. {
  4518. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4519. return (res == WAIT_OBJECT_0);
  4520. }
  4521. FUNCTION_MAY_BE_UNUSED
  4522. static int
  4523. event_signal(void *eventhdl)
  4524. {
  4525. return (int)SetEvent((HANDLE)eventhdl);
  4526. }
  4527. FUNCTION_MAY_BE_UNUSED
  4528. static void
  4529. event_destroy(void *eventhdl)
  4530. {
  4531. CloseHandle((HANDLE)eventhdl);
  4532. }
  4533. #endif
  4534. #if defined(GCC_DIAGNOSTIC)
  4535. /* Enable unused function warning again */
  4536. #pragma GCC diagnostic pop
  4537. #endif
  4538. /* For Windows, change all slashes to backslashes in path names. */
  4539. static void
  4540. change_slashes_to_backslashes(char *path)
  4541. {
  4542. int i;
  4543. for (i = 0; path[i] != '\0'; i++) {
  4544. if (path[i] == '/') {
  4545. path[i] = '\\';
  4546. }
  4547. /* remove double backslash (check i > 0 to preserve UNC paths,
  4548. * like \\server\file.txt) */
  4549. if ((i > 0) && (path[i] == '\\')) {
  4550. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4551. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4552. }
  4553. }
  4554. }
  4555. }
  4556. static int
  4557. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4558. {
  4559. int diff;
  4560. do {
  4561. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4562. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4563. s1++;
  4564. s2++;
  4565. } while ((diff == 0) && (s1[-1] != L'\0'));
  4566. return diff;
  4567. }
  4568. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4569. * wbuf and wbuf_len is a target buffer and its length. */
  4570. static void
  4571. path_to_unicode(const struct mg_connection *conn,
  4572. const char *path,
  4573. wchar_t *wbuf,
  4574. size_t wbuf_len)
  4575. {
  4576. char buf[PATH_MAX], buf2[PATH_MAX];
  4577. wchar_t wbuf2[W_PATH_MAX + 1];
  4578. DWORD long_len, err;
  4579. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4580. mg_strlcpy(buf, path, sizeof(buf));
  4581. change_slashes_to_backslashes(buf);
  4582. /* Convert to Unicode and back. If doubly-converted string does not
  4583. * match the original, something is fishy, reject. */
  4584. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4585. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4586. WideCharToMultiByte(
  4587. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4588. if (strcmp(buf, buf2) != 0) {
  4589. wbuf[0] = L'\0';
  4590. }
  4591. /* Windows file systems are not case sensitive, but you can still use
  4592. * uppercase and lowercase letters (on all modern file systems).
  4593. * The server can check if the URI uses the same upper/lowercase
  4594. * letters an the file system, effectively making Windows servers
  4595. * case sensitive (like Linux servers are). It is still not possible
  4596. * to use two files with the same name in different cases on Windows
  4597. * (like /a and /A) - this would be possible in Linux.
  4598. * As a default, Windows is not case sensitive, but the case sensitive
  4599. * file name check can be activated by an additional configuration. */
  4600. if (conn) {
  4601. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4602. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4603. "yes")) {
  4604. /* Use case sensitive compare function */
  4605. fcompare = wcscmp;
  4606. }
  4607. }
  4608. (void)conn; /* conn is currently unused */
  4609. #if !defined(_WIN32_WCE)
  4610. /* Only accept a full file path, not a Windows short (8.3) path. */
  4611. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4612. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4613. if (long_len == 0) {
  4614. err = GetLastError();
  4615. if (err == ERROR_FILE_NOT_FOUND) {
  4616. /* File does not exist. This is not always a problem here. */
  4617. return;
  4618. }
  4619. }
  4620. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4621. /* Short name is used. */
  4622. wbuf[0] = L'\0';
  4623. }
  4624. #else
  4625. (void)long_len;
  4626. (void)wbuf2;
  4627. (void)err;
  4628. if (strchr(path, '~')) {
  4629. wbuf[0] = L'\0';
  4630. }
  4631. #endif
  4632. }
  4633. #if !defined(NO_FILESYSTEMS)
  4634. static int
  4635. mg_stat(const struct mg_connection *conn,
  4636. const char *path,
  4637. struct mg_file_stat *filep)
  4638. {
  4639. wchar_t wbuf[W_PATH_MAX];
  4640. WIN32_FILE_ATTRIBUTE_DATA info;
  4641. time_t creation_time;
  4642. size_t len;
  4643. if (!filep) {
  4644. return 0;
  4645. }
  4646. memset(filep, 0, sizeof(*filep));
  4647. if (conn && is_file_in_memory(conn, path)) {
  4648. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4649. * memset */
  4650. /* Quick fix (for 1.9.x): */
  4651. /* mg_stat must fill all fields, also for files in memory */
  4652. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4653. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4654. filep->size = tmp_file.stat.size;
  4655. filep->location = 2;
  4656. /* TODO: for 1.10: restructure how files in memory are handled */
  4657. /* The "file in memory" feature is a candidate for deletion.
  4658. * Please join the discussion at
  4659. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4660. */
  4661. filep->last_modified = time(NULL); /* TODO */
  4662. /* last_modified = now ... assumes the file may change during
  4663. * runtime,
  4664. * so every mg_fopen call may return different data */
  4665. /* last_modified = conn->phys_ctx.start_time;
  4666. * May be used it the data does not change during runtime. This
  4667. * allows
  4668. * browser caching. Since we do not know, we have to assume the file
  4669. * in memory may change. */
  4670. return 1;
  4671. }
  4672. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4673. /* Windows happily opens files with some garbage at the end of file name.
  4674. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4675. * "a.cgi", despite one would expect an error back. */
  4676. len = strlen(path);
  4677. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4678. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4679. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4680. filep->last_modified =
  4681. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4682. info.ftLastWriteTime.dwHighDateTime);
  4683. /* On Windows, the file creation time can be higher than the
  4684. * modification time, e.g. when a file is copied.
  4685. * Since the Last-Modified timestamp is used for caching
  4686. * it should be based on the most recent timestamp. */
  4687. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4688. info.ftCreationTime.dwHighDateTime);
  4689. if (creation_time > filep->last_modified) {
  4690. filep->last_modified = creation_time;
  4691. }
  4692. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4693. return 1;
  4694. }
  4695. return 0;
  4696. }
  4697. #endif
  4698. static int
  4699. mg_remove(const struct mg_connection *conn, const char *path)
  4700. {
  4701. wchar_t wbuf[W_PATH_MAX];
  4702. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4703. return DeleteFileW(wbuf) ? 0 : -1;
  4704. }
  4705. static int
  4706. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4707. {
  4708. wchar_t wbuf[W_PATH_MAX];
  4709. (void)mode;
  4710. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4711. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4712. }
  4713. /* Create substitutes for POSIX functions in Win32. */
  4714. #if defined(GCC_DIAGNOSTIC)
  4715. /* Show no warning in case system functions are not used. */
  4716. #pragma GCC diagnostic push
  4717. #pragma GCC diagnostic ignored "-Wunused-function"
  4718. #endif
  4719. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4720. FUNCTION_MAY_BE_UNUSED
  4721. static DIR *
  4722. mg_opendir(const struct mg_connection *conn, const char *name)
  4723. {
  4724. DIR *dir = NULL;
  4725. wchar_t wpath[W_PATH_MAX];
  4726. DWORD attrs;
  4727. if (name == NULL) {
  4728. SetLastError(ERROR_BAD_ARGUMENTS);
  4729. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4730. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4731. } else {
  4732. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4733. attrs = GetFileAttributesW(wpath);
  4734. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4735. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4736. (void)wcscat(wpath, L"\\*");
  4737. dir->handle = FindFirstFileW(wpath, &dir->info);
  4738. dir->result.d_name[0] = '\0';
  4739. } else {
  4740. mg_free(dir);
  4741. dir = NULL;
  4742. }
  4743. }
  4744. return dir;
  4745. }
  4746. FUNCTION_MAY_BE_UNUSED
  4747. static int
  4748. mg_closedir(DIR *dir)
  4749. {
  4750. int result = 0;
  4751. if (dir != NULL) {
  4752. if (dir->handle != INVALID_HANDLE_VALUE)
  4753. result = FindClose(dir->handle) ? 0 : -1;
  4754. mg_free(dir);
  4755. } else {
  4756. result = -1;
  4757. SetLastError(ERROR_BAD_ARGUMENTS);
  4758. }
  4759. return result;
  4760. }
  4761. FUNCTION_MAY_BE_UNUSED
  4762. static struct dirent *
  4763. mg_readdir(DIR *dir)
  4764. {
  4765. struct dirent *result = 0;
  4766. if (dir) {
  4767. if (dir->handle != INVALID_HANDLE_VALUE) {
  4768. result = &dir->result;
  4769. (void)WideCharToMultiByte(CP_UTF8,
  4770. 0,
  4771. dir->info.cFileName,
  4772. -1,
  4773. result->d_name,
  4774. sizeof(result->d_name),
  4775. NULL,
  4776. NULL);
  4777. if (!FindNextFileW(dir->handle, &dir->info)) {
  4778. (void)FindClose(dir->handle);
  4779. dir->handle = INVALID_HANDLE_VALUE;
  4780. }
  4781. } else {
  4782. SetLastError(ERROR_FILE_NOT_FOUND);
  4783. }
  4784. } else {
  4785. SetLastError(ERROR_BAD_ARGUMENTS);
  4786. }
  4787. return result;
  4788. }
  4789. #if !defined(HAVE_POLL)
  4790. #undef POLLIN
  4791. #undef POLLPRI
  4792. #undef POLLOUT
  4793. #define POLLIN (1) /* Data ready - read will not block. */
  4794. #define POLLPRI (2) /* Priority data ready. */
  4795. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4796. FUNCTION_MAY_BE_UNUSED
  4797. static int
  4798. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4799. {
  4800. struct timeval tv;
  4801. fd_set rset;
  4802. fd_set wset;
  4803. unsigned int i;
  4804. int result;
  4805. SOCKET maxfd = 0;
  4806. memset(&tv, 0, sizeof(tv));
  4807. tv.tv_sec = milliseconds / 1000;
  4808. tv.tv_usec = (milliseconds % 1000) * 1000;
  4809. FD_ZERO(&rset);
  4810. FD_ZERO(&wset);
  4811. for (i = 0; i < n; i++) {
  4812. if (pfd[i].events & POLLIN) {
  4813. FD_SET(pfd[i].fd, &rset);
  4814. }
  4815. if (pfd[i].events & POLLOUT) {
  4816. FD_SET(pfd[i].fd, &wset);
  4817. }
  4818. pfd[i].revents = 0;
  4819. if (pfd[i].fd > maxfd) {
  4820. maxfd = pfd[i].fd;
  4821. }
  4822. }
  4823. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4824. for (i = 0; i < n; i++) {
  4825. if (FD_ISSET(pfd[i].fd, &rset)) {
  4826. pfd[i].revents |= POLLIN;
  4827. }
  4828. if (FD_ISSET(pfd[i].fd, &wset)) {
  4829. pfd[i].revents |= POLLOUT;
  4830. }
  4831. }
  4832. }
  4833. /* We should subtract the time used in select from remaining
  4834. * "milliseconds", in particular if called from mg_poll with a
  4835. * timeout quantum.
  4836. * Unfortunately, the remaining time is not stored in "tv" in all
  4837. * implementations, so the result in "tv" must be considered undefined.
  4838. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4839. return result;
  4840. }
  4841. #endif /* HAVE_POLL */
  4842. #if defined(GCC_DIAGNOSTIC)
  4843. /* Enable unused function warning again */
  4844. #pragma GCC diagnostic pop
  4845. #endif
  4846. static void
  4847. set_close_on_exec(SOCKET sock,
  4848. const struct mg_connection *conn /* may be null */,
  4849. struct mg_context *ctx /* may be null */)
  4850. {
  4851. (void)conn; /* Unused. */
  4852. (void)ctx;
  4853. #if defined(_WIN32_WCE)
  4854. (void)sock;
  4855. #else
  4856. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4857. #endif
  4858. }
  4859. int
  4860. mg_start_thread(mg_thread_func_t f, void *p)
  4861. {
  4862. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4863. /* Compile-time option to control stack size, e.g.
  4864. * -DUSE_STACK_SIZE=16384
  4865. */
  4866. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4867. == ((uintptr_t)(-1L)))
  4868. ? -1
  4869. : 0);
  4870. #else
  4871. return (
  4872. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4873. ? -1
  4874. : 0);
  4875. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4876. }
  4877. /* Start a thread storing the thread context. */
  4878. static int
  4879. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4880. void *p,
  4881. pthread_t *threadidptr)
  4882. {
  4883. uintptr_t uip;
  4884. HANDLE threadhandle;
  4885. int result = -1;
  4886. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4887. threadhandle = (HANDLE)uip;
  4888. if ((uip != 0) && (threadidptr != NULL)) {
  4889. *threadidptr = threadhandle;
  4890. result = 0;
  4891. }
  4892. return result;
  4893. }
  4894. /* Wait for a thread to finish. */
  4895. static int
  4896. mg_join_thread(pthread_t threadid)
  4897. {
  4898. int result;
  4899. DWORD dwevent;
  4900. result = -1;
  4901. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4902. if (dwevent == WAIT_FAILED) {
  4903. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4904. } else {
  4905. if (dwevent == WAIT_OBJECT_0) {
  4906. CloseHandle(threadid);
  4907. result = 0;
  4908. }
  4909. }
  4910. return result;
  4911. }
  4912. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4913. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4914. /* Create substitutes for POSIX functions in Win32. */
  4915. #if defined(GCC_DIAGNOSTIC)
  4916. /* Show no warning in case system functions are not used. */
  4917. #pragma GCC diagnostic push
  4918. #pragma GCC diagnostic ignored "-Wunused-function"
  4919. #endif
  4920. FUNCTION_MAY_BE_UNUSED
  4921. static HANDLE
  4922. dlopen(const char *dll_name, int flags)
  4923. {
  4924. wchar_t wbuf[W_PATH_MAX];
  4925. (void)flags;
  4926. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4927. return LoadLibraryW(wbuf);
  4928. }
  4929. FUNCTION_MAY_BE_UNUSED
  4930. static int
  4931. dlclose(void *handle)
  4932. {
  4933. int result;
  4934. if (FreeLibrary((HMODULE)handle) != 0) {
  4935. result = 0;
  4936. } else {
  4937. result = -1;
  4938. }
  4939. return result;
  4940. }
  4941. #if defined(GCC_DIAGNOSTIC)
  4942. /* Enable unused function warning again */
  4943. #pragma GCC diagnostic pop
  4944. #endif
  4945. #endif
  4946. #if !defined(NO_CGI)
  4947. #define SIGKILL (0)
  4948. static int
  4949. kill(pid_t pid, int sig_num)
  4950. {
  4951. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4952. (void)CloseHandle((HANDLE)pid);
  4953. return 0;
  4954. }
  4955. #if !defined(WNOHANG)
  4956. #define WNOHANG (1)
  4957. #endif
  4958. static pid_t
  4959. waitpid(pid_t pid, int *status, int flags)
  4960. {
  4961. DWORD timeout = INFINITE;
  4962. DWORD waitres;
  4963. (void)status; /* Currently not used by any client here */
  4964. if ((flags | WNOHANG) == WNOHANG) {
  4965. timeout = 0;
  4966. }
  4967. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4968. if (waitres == WAIT_OBJECT_0) {
  4969. return pid;
  4970. }
  4971. if (waitres == WAIT_TIMEOUT) {
  4972. return 0;
  4973. }
  4974. return (pid_t)-1;
  4975. }
  4976. static void
  4977. trim_trailing_whitespaces(char *s)
  4978. {
  4979. char *e = s + strlen(s);
  4980. while ((e > s) && isspace((unsigned char)e[-1])) {
  4981. *(--e) = '\0';
  4982. }
  4983. }
  4984. static pid_t
  4985. spawn_process(struct mg_connection *conn,
  4986. const char *prog,
  4987. char *envblk,
  4988. char *envp[],
  4989. int fdin[2],
  4990. int fdout[2],
  4991. int fderr[2],
  4992. const char *dir)
  4993. {
  4994. HANDLE me;
  4995. char *p, *interp;
  4996. char *interp_arg = 0;
  4997. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  4998. buf[PATH_MAX];
  4999. int truncated;
  5000. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5001. STARTUPINFOA si;
  5002. PROCESS_INFORMATION pi = {0};
  5003. (void)envp;
  5004. memset(&si, 0, sizeof(si));
  5005. si.cb = sizeof(si);
  5006. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5007. si.wShowWindow = SW_HIDE;
  5008. me = GetCurrentProcess();
  5009. DuplicateHandle(me,
  5010. (HANDLE)_get_osfhandle(fdin[0]),
  5011. me,
  5012. &si.hStdInput,
  5013. 0,
  5014. TRUE,
  5015. DUPLICATE_SAME_ACCESS);
  5016. DuplicateHandle(me,
  5017. (HANDLE)_get_osfhandle(fdout[1]),
  5018. me,
  5019. &si.hStdOutput,
  5020. 0,
  5021. TRUE,
  5022. DUPLICATE_SAME_ACCESS);
  5023. DuplicateHandle(me,
  5024. (HANDLE)_get_osfhandle(fderr[1]),
  5025. me,
  5026. &si.hStdError,
  5027. 0,
  5028. TRUE,
  5029. DUPLICATE_SAME_ACCESS);
  5030. /* Mark handles that should not be inherited. See
  5031. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5032. */
  5033. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5034. HANDLE_FLAG_INHERIT,
  5035. 0);
  5036. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5037. HANDLE_FLAG_INHERIT,
  5038. 0);
  5039. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5040. HANDLE_FLAG_INHERIT,
  5041. 0);
  5042. /* First check, if there is a CGI interpreter configured for all CGI
  5043. * scripts. */
  5044. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5045. if (interp != NULL) {
  5046. /* If there is a configured interpreter, check for additional arguments
  5047. */
  5048. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5049. } else {
  5050. /* Otherwise, the interpreter must be stated in the first line of the
  5051. * CGI script file, after a #! (shebang) mark. */
  5052. buf[0] = buf[1] = '\0';
  5053. /* Get the full script path */
  5054. mg_snprintf(
  5055. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5056. if (truncated) {
  5057. pi.hProcess = (pid_t)-1;
  5058. goto spawn_cleanup;
  5059. }
  5060. /* Open the script file, to read the first line */
  5061. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5062. #if defined(MG_USE_OPEN_FILE)
  5063. p = (char *)file.access.membuf;
  5064. #else
  5065. p = (char *)NULL;
  5066. #endif
  5067. /* Read the first line of the script into the buffer */
  5068. mg_fgets(buf, sizeof(buf), &file, &p);
  5069. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5070. buf[sizeof(buf) - 1] = '\0';
  5071. }
  5072. if ((buf[0] == '#') && (buf[1] == '!')) {
  5073. trim_trailing_whitespaces(buf + 2);
  5074. } else {
  5075. buf[2] = '\0';
  5076. }
  5077. interp = buf + 2;
  5078. }
  5079. if (interp[0] != '\0') {
  5080. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5081. interp = full_interp;
  5082. }
  5083. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5084. if (interp[0] != '\0') {
  5085. /* This is an interpreted script file. We must call the interpreter. */
  5086. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5087. mg_snprintf(conn,
  5088. &truncated,
  5089. cmdline,
  5090. sizeof(cmdline),
  5091. "\"%s\" %s \"%s\\%s\"",
  5092. interp,
  5093. interp_arg,
  5094. full_dir,
  5095. prog);
  5096. } else {
  5097. mg_snprintf(conn,
  5098. &truncated,
  5099. cmdline,
  5100. sizeof(cmdline),
  5101. "\"%s\" \"%s\\%s\"",
  5102. interp,
  5103. full_dir,
  5104. prog);
  5105. }
  5106. } else {
  5107. /* This is (probably) a compiled program. We call it directly. */
  5108. mg_snprintf(conn,
  5109. &truncated,
  5110. cmdline,
  5111. sizeof(cmdline),
  5112. "\"%s\\%s\"",
  5113. full_dir,
  5114. prog);
  5115. }
  5116. if (truncated) {
  5117. pi.hProcess = (pid_t)-1;
  5118. goto spawn_cleanup;
  5119. }
  5120. DEBUG_TRACE("Running [%s]", cmdline);
  5121. if (CreateProcessA(NULL,
  5122. cmdline,
  5123. NULL,
  5124. NULL,
  5125. TRUE,
  5126. CREATE_NEW_PROCESS_GROUP,
  5127. envblk,
  5128. NULL,
  5129. &si,
  5130. &pi)
  5131. == 0) {
  5132. mg_cry_internal(
  5133. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5134. pi.hProcess = (pid_t)-1;
  5135. /* goto spawn_cleanup; */
  5136. }
  5137. spawn_cleanup:
  5138. (void)CloseHandle(si.hStdOutput);
  5139. (void)CloseHandle(si.hStdError);
  5140. (void)CloseHandle(si.hStdInput);
  5141. if (pi.hThread != NULL) {
  5142. (void)CloseHandle(pi.hThread);
  5143. }
  5144. return (pid_t)pi.hProcess;
  5145. }
  5146. #endif /* !NO_CGI */
  5147. static int
  5148. set_blocking_mode(SOCKET sock)
  5149. {
  5150. unsigned long non_blocking = 0;
  5151. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5152. }
  5153. static int
  5154. set_non_blocking_mode(SOCKET sock)
  5155. {
  5156. unsigned long non_blocking = 1;
  5157. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5158. }
  5159. #else
  5160. #if !defined(NO_FILESYSTEMS)
  5161. static int
  5162. mg_stat(const struct mg_connection *conn,
  5163. const char *path,
  5164. struct mg_file_stat *filep)
  5165. {
  5166. struct stat st;
  5167. if (!filep) {
  5168. return 0;
  5169. }
  5170. memset(filep, 0, sizeof(*filep));
  5171. if (conn && is_file_in_memory(conn, path)) {
  5172. /* Quick fix (for 1.9.x): */
  5173. /* mg_stat must fill all fields, also for files in memory */
  5174. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5175. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5176. filep->size = tmp_file.stat.size;
  5177. filep->last_modified = time(NULL);
  5178. filep->location = 2;
  5179. /* TODO: remove legacy "files in memory" feature */
  5180. return 1;
  5181. }
  5182. if (0 == stat(path, &st)) {
  5183. filep->size = (uint64_t)(st.st_size);
  5184. filep->last_modified = st.st_mtime;
  5185. filep->is_directory = S_ISDIR(st.st_mode);
  5186. return 1;
  5187. }
  5188. return 0;
  5189. }
  5190. #endif /* NO_FILESYSTEMS */
  5191. static void
  5192. set_close_on_exec(int fd,
  5193. const struct mg_connection *conn /* may be null */,
  5194. struct mg_context *ctx /* may be null */)
  5195. {
  5196. #if defined(__ZEPHYR__)
  5197. (void)fd;
  5198. (void)conn;
  5199. (void)ctx;
  5200. #else
  5201. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5202. if (conn || ctx) {
  5203. struct mg_connection fc;
  5204. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5205. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5206. __func__,
  5207. strerror(ERRNO));
  5208. }
  5209. }
  5210. #endif
  5211. }
  5212. int
  5213. mg_start_thread(mg_thread_func_t func, void *param)
  5214. {
  5215. pthread_t thread_id;
  5216. pthread_attr_t attr;
  5217. int result;
  5218. (void)pthread_attr_init(&attr);
  5219. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5220. #if defined(__ZEPHYR__)
  5221. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5222. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5223. /* Compile-time option to control stack size,
  5224. * e.g. -DUSE_STACK_SIZE=16384 */
  5225. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5226. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5227. result = pthread_create(&thread_id, &attr, func, param);
  5228. pthread_attr_destroy(&attr);
  5229. return result;
  5230. }
  5231. /* Start a thread storing the thread context. */
  5232. static int
  5233. mg_start_thread_with_id(mg_thread_func_t func,
  5234. void *param,
  5235. pthread_t *threadidptr)
  5236. {
  5237. pthread_t thread_id;
  5238. pthread_attr_t attr;
  5239. int result;
  5240. (void)pthread_attr_init(&attr);
  5241. #if defined(__ZEPHYR__)
  5242. pthread_attr_setstack(&attr,
  5243. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5244. ZEPHYR_STACK_SIZE);
  5245. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5246. /* Compile-time option to control stack size,
  5247. * e.g. -DUSE_STACK_SIZE=16384 */
  5248. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5249. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5250. result = pthread_create(&thread_id, &attr, func, param);
  5251. pthread_attr_destroy(&attr);
  5252. if ((result == 0) && (threadidptr != NULL)) {
  5253. *threadidptr = thread_id;
  5254. }
  5255. return result;
  5256. }
  5257. /* Wait for a thread to finish. */
  5258. static int
  5259. mg_join_thread(pthread_t threadid)
  5260. {
  5261. int result;
  5262. result = pthread_join(threadid, NULL);
  5263. return result;
  5264. }
  5265. #if !defined(NO_CGI)
  5266. static pid_t
  5267. spawn_process(struct mg_connection *conn,
  5268. const char *prog,
  5269. char *envblk,
  5270. char *envp[],
  5271. int fdin[2],
  5272. int fdout[2],
  5273. int fderr[2],
  5274. const char *dir)
  5275. {
  5276. pid_t pid;
  5277. const char *interp;
  5278. (void)envblk;
  5279. if ((pid = fork()) == -1) {
  5280. /* Parent */
  5281. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5282. } else if (pid != 0) {
  5283. /* Make sure children close parent-side descriptors.
  5284. * The caller will close the child-side immediately. */
  5285. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5286. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5287. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5288. } else {
  5289. /* Child */
  5290. if (chdir(dir) != 0) {
  5291. mg_cry_internal(
  5292. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5293. } else if (dup2(fdin[0], 0) == -1) {
  5294. mg_cry_internal(conn,
  5295. "%s: dup2(%d, 0): %s",
  5296. __func__,
  5297. fdin[0],
  5298. strerror(ERRNO));
  5299. } else if (dup2(fdout[1], 1) == -1) {
  5300. mg_cry_internal(conn,
  5301. "%s: dup2(%d, 1): %s",
  5302. __func__,
  5303. fdout[1],
  5304. strerror(ERRNO));
  5305. } else if (dup2(fderr[1], 2) == -1) {
  5306. mg_cry_internal(conn,
  5307. "%s: dup2(%d, 2): %s",
  5308. __func__,
  5309. fderr[1],
  5310. strerror(ERRNO));
  5311. } else {
  5312. struct sigaction sa;
  5313. /* Keep stderr and stdout in two different pipes.
  5314. * Stdout will be sent back to the client,
  5315. * stderr should go into a server error log. */
  5316. (void)close(fdin[0]);
  5317. (void)close(fdout[1]);
  5318. (void)close(fderr[1]);
  5319. /* Close write end fdin and read end fdout and fderr */
  5320. (void)close(fdin[1]);
  5321. (void)close(fdout[0]);
  5322. (void)close(fderr[0]);
  5323. /* After exec, all signal handlers are restored to their default
  5324. * values, with one exception of SIGCHLD. According to
  5325. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5326. * will leave unchanged after exec if it was set to be ignored.
  5327. * Restore it to default action. */
  5328. memset(&sa, 0, sizeof(sa));
  5329. sa.sa_handler = SIG_DFL;
  5330. sigaction(SIGCHLD, &sa, NULL);
  5331. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5332. if (interp == NULL) {
  5333. /* no interpreter configured, call the programm directly */
  5334. (void)execle(prog, prog, NULL, envp);
  5335. mg_cry_internal(conn,
  5336. "%s: execle(%s): %s",
  5337. __func__,
  5338. prog,
  5339. strerror(ERRNO));
  5340. } else {
  5341. /* call the configured interpreter */
  5342. const char *interp_args =
  5343. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5344. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5345. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5346. } else {
  5347. (void)execle(interp, interp, prog, NULL, envp);
  5348. }
  5349. mg_cry_internal(conn,
  5350. "%s: execle(%s %s): %s",
  5351. __func__,
  5352. interp,
  5353. prog,
  5354. strerror(ERRNO));
  5355. }
  5356. }
  5357. exit(EXIT_FAILURE);
  5358. }
  5359. return pid;
  5360. }
  5361. #endif /* !NO_CGI */
  5362. static int
  5363. set_non_blocking_mode(SOCKET sock)
  5364. {
  5365. int flags = fcntl(sock, F_GETFL, 0);
  5366. if (flags < 0) {
  5367. return -1;
  5368. }
  5369. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5370. return -1;
  5371. }
  5372. return 0;
  5373. }
  5374. static int
  5375. set_blocking_mode(SOCKET sock)
  5376. {
  5377. int flags = fcntl(sock, F_GETFL, 0);
  5378. if (flags < 0) {
  5379. return -1;
  5380. }
  5381. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5382. return -1;
  5383. }
  5384. return 0;
  5385. }
  5386. #endif /* _WIN32 / else */
  5387. /* End of initial operating system specific define block. */
  5388. /* Get a random number (independent of C rand function) */
  5389. static uint64_t
  5390. get_random(void)
  5391. {
  5392. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5393. static uint64_t lcg = 0; /* Linear congruential generator */
  5394. uint64_t now = mg_get_current_time_ns();
  5395. if (lfsr == 0) {
  5396. /* lfsr will be only 0 if has not been initialized,
  5397. * so this code is called only once. */
  5398. lfsr = mg_get_current_time_ns();
  5399. lcg = mg_get_current_time_ns();
  5400. } else {
  5401. /* Get the next step of both random number generators. */
  5402. lfsr = (lfsr >> 1)
  5403. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5404. << 63);
  5405. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5406. }
  5407. /* Combining two pseudo-random number generators and a high resolution
  5408. * part
  5409. * of the current server time will make it hard (impossible?) to guess
  5410. * the
  5411. * next number. */
  5412. return (lfsr ^ lcg ^ now);
  5413. }
  5414. static int
  5415. mg_poll(struct mg_pollfd *pfd,
  5416. unsigned int n,
  5417. int milliseconds,
  5418. stop_flag_t *stop_flag)
  5419. {
  5420. /* Call poll, but only for a maximum time of a few seconds.
  5421. * This will allow to stop the server after some seconds, instead
  5422. * of having to wait for a long socket timeout. */
  5423. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5424. do {
  5425. int result;
  5426. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5427. /* Shut down signal */
  5428. return -2;
  5429. }
  5430. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5431. ms_now = milliseconds;
  5432. }
  5433. result = poll(pfd, n, ms_now);
  5434. if (result != 0) {
  5435. /* Poll returned either success (1) or error (-1).
  5436. * Forward both to the caller. */
  5437. return result;
  5438. }
  5439. /* Poll returned timeout (0). */
  5440. if (milliseconds > 0) {
  5441. milliseconds -= ms_now;
  5442. }
  5443. } while (milliseconds != 0);
  5444. /* timeout: return 0 */
  5445. return 0;
  5446. }
  5447. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5448. * descriptor.
  5449. * Return value:
  5450. * >=0 .. number of bytes successfully written
  5451. * -1 .. timeout
  5452. * -2 .. error
  5453. */
  5454. static int
  5455. push_inner(struct mg_context *ctx,
  5456. FILE *fp,
  5457. SOCKET sock,
  5458. SSL *ssl,
  5459. const char *buf,
  5460. int len,
  5461. double timeout)
  5462. {
  5463. uint64_t start = 0, now = 0, timeout_ns = 0;
  5464. int n, err;
  5465. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5466. #if defined(_WIN32)
  5467. typedef int len_t;
  5468. #else
  5469. typedef size_t len_t;
  5470. #endif
  5471. if (timeout > 0) {
  5472. now = mg_get_current_time_ns();
  5473. start = now;
  5474. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5475. }
  5476. if (ctx == NULL) {
  5477. return -2;
  5478. }
  5479. #if defined(NO_SSL)
  5480. if (ssl) {
  5481. return -2;
  5482. }
  5483. #endif
  5484. /* Try to read until it succeeds, fails, times out, or the server
  5485. * shuts down. */
  5486. for (;;) {
  5487. #if !defined(NO_SSL)
  5488. if (ssl != NULL) {
  5489. ERR_clear_error();
  5490. n = SSL_write(ssl, buf, len);
  5491. if (n <= 0) {
  5492. err = SSL_get_error(ssl, n);
  5493. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5494. err = ERRNO;
  5495. } else if ((err == SSL_ERROR_WANT_READ)
  5496. || (err == SSL_ERROR_WANT_WRITE)) {
  5497. n = 0;
  5498. } else {
  5499. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5500. ERR_clear_error();
  5501. return -2;
  5502. }
  5503. ERR_clear_error();
  5504. } else {
  5505. err = 0;
  5506. }
  5507. } else
  5508. #endif
  5509. if (fp != NULL) {
  5510. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5511. if (ferror(fp)) {
  5512. n = -1;
  5513. err = ERRNO;
  5514. } else {
  5515. err = 0;
  5516. }
  5517. } else {
  5518. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5519. err = (n < 0) ? ERRNO : 0;
  5520. #if defined(_WIN32)
  5521. if (err == WSAEWOULDBLOCK) {
  5522. err = 0;
  5523. n = 0;
  5524. }
  5525. #else
  5526. if (err == EWOULDBLOCK) {
  5527. err = 0;
  5528. n = 0;
  5529. }
  5530. #endif
  5531. if (n < 0) {
  5532. /* shutdown of the socket at client side */
  5533. return -2;
  5534. }
  5535. }
  5536. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5537. return -2;
  5538. }
  5539. if ((n > 0) || ((n == 0) && (len == 0))) {
  5540. /* some data has been read, or no data was requested */
  5541. return n;
  5542. }
  5543. if (n < 0) {
  5544. /* socket error - check errno */
  5545. DEBUG_TRACE("send() failed, error %d", err);
  5546. /* TODO (mid): error handling depending on the error code.
  5547. * These codes are different between Windows and Linux.
  5548. * Currently there is no problem with failing send calls,
  5549. * if there is a reproducible situation, it should be
  5550. * investigated in detail.
  5551. */
  5552. return -2;
  5553. }
  5554. /* Only in case n=0 (timeout), repeat calling the write function */
  5555. /* If send failed, wait before retry */
  5556. if (fp != NULL) {
  5557. /* For files, just wait a fixed time.
  5558. * Maybe it helps, maybe not. */
  5559. mg_sleep(5);
  5560. } else {
  5561. /* For sockets, wait for the socket using poll */
  5562. struct mg_pollfd pfd[1];
  5563. int pollres;
  5564. pfd[0].fd = sock;
  5565. pfd[0].events = POLLOUT;
  5566. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5567. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5568. return -2;
  5569. }
  5570. if (pollres > 0) {
  5571. continue;
  5572. }
  5573. }
  5574. if (timeout > 0) {
  5575. now = mg_get_current_time_ns();
  5576. if ((now - start) > timeout_ns) {
  5577. /* Timeout */
  5578. break;
  5579. }
  5580. }
  5581. }
  5582. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5583. used */
  5584. return -1;
  5585. }
  5586. static int
  5587. push_all(struct mg_context *ctx,
  5588. FILE *fp,
  5589. SOCKET sock,
  5590. SSL *ssl,
  5591. const char *buf,
  5592. int len)
  5593. {
  5594. double timeout = -1.0;
  5595. int n, nwritten = 0;
  5596. if (ctx == NULL) {
  5597. return -1;
  5598. }
  5599. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5600. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5601. }
  5602. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5603. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5604. if (n < 0) {
  5605. if (nwritten == 0) {
  5606. nwritten = -1; /* Propagate the error */
  5607. }
  5608. break;
  5609. } else if (n == 0) {
  5610. break; /* No more data to write */
  5611. } else {
  5612. nwritten += n;
  5613. len -= n;
  5614. }
  5615. }
  5616. return nwritten;
  5617. }
  5618. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5619. * Return value:
  5620. * >=0 .. number of bytes successfully read
  5621. * -1 .. timeout
  5622. * -2 .. error
  5623. */
  5624. static int
  5625. pull_inner(FILE *fp,
  5626. struct mg_connection *conn,
  5627. char *buf,
  5628. int len,
  5629. double timeout)
  5630. {
  5631. int nread, err = 0;
  5632. #if defined(_WIN32)
  5633. typedef int len_t;
  5634. #else
  5635. typedef size_t len_t;
  5636. #endif
  5637. /* We need an additional wait loop around this, because in some cases
  5638. * with TLSwe may get data from the socket but not from SSL_read.
  5639. * In this case we need to repeat at least once.
  5640. */
  5641. if (fp != NULL) {
  5642. #if !defined(_WIN32_WCE)
  5643. /* Use read() instead of fread(), because if we're reading from the
  5644. * CGI pipe, fread() may block until IO buffer is filled up. We
  5645. * cannot afford to block and must pass all read bytes immediately
  5646. * to the client. */
  5647. nread = (int)read(fileno(fp), buf, (size_t)len);
  5648. #else
  5649. /* WinCE does not support CGI pipes */
  5650. nread = (int)fread(buf, 1, (size_t)len, fp);
  5651. #endif
  5652. err = (nread < 0) ? ERRNO : 0;
  5653. if ((nread == 0) && (len > 0)) {
  5654. /* Should get data, but got EOL */
  5655. return -2;
  5656. }
  5657. #if !defined(NO_SSL)
  5658. } else if (conn->ssl != NULL) {
  5659. int ssl_pending;
  5660. struct mg_pollfd pfd[1];
  5661. int pollres;
  5662. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5663. /* We already know there is no more data buffered in conn->buf
  5664. * but there is more available in the SSL layer. So don't poll
  5665. * conn->client.sock yet. */
  5666. if (ssl_pending > len) {
  5667. ssl_pending = len;
  5668. }
  5669. pollres = 1;
  5670. } else {
  5671. pfd[0].fd = conn->client.sock;
  5672. pfd[0].events = POLLIN;
  5673. pollres = mg_poll(pfd,
  5674. 1,
  5675. (int)(timeout * 1000.0),
  5676. &(conn->phys_ctx->stop_flag));
  5677. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5678. return -2;
  5679. }
  5680. }
  5681. if (pollres > 0) {
  5682. ERR_clear_error();
  5683. nread =
  5684. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5685. if (nread <= 0) {
  5686. err = SSL_get_error(conn->ssl, nread);
  5687. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5688. err = ERRNO;
  5689. } else if ((err == SSL_ERROR_WANT_READ)
  5690. || (err == SSL_ERROR_WANT_WRITE)) {
  5691. nread = 0;
  5692. } else {
  5693. /* All errors should return -2 */
  5694. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5695. ERR_clear_error();
  5696. return -2;
  5697. }
  5698. ERR_clear_error();
  5699. } else {
  5700. err = 0;
  5701. }
  5702. } else if (pollres < 0) {
  5703. /* Error */
  5704. return -2;
  5705. } else {
  5706. /* pollres = 0 means timeout */
  5707. nread = 0;
  5708. }
  5709. #endif
  5710. } else {
  5711. struct mg_pollfd pfd[1];
  5712. int pollres;
  5713. pfd[0].fd = conn->client.sock;
  5714. pfd[0].events = POLLIN;
  5715. pollres = mg_poll(pfd,
  5716. 1,
  5717. (int)(timeout * 1000.0),
  5718. &(conn->phys_ctx->stop_flag));
  5719. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5720. return -2;
  5721. }
  5722. if (pollres > 0) {
  5723. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5724. err = (nread < 0) ? ERRNO : 0;
  5725. if (nread <= 0) {
  5726. /* shutdown of the socket at client side */
  5727. return -2;
  5728. }
  5729. } else if (pollres < 0) {
  5730. /* error callint poll */
  5731. return -2;
  5732. } else {
  5733. /* pollres = 0 means timeout */
  5734. nread = 0;
  5735. }
  5736. }
  5737. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5738. return -2;
  5739. }
  5740. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5741. /* some data has been read, or no data was requested */
  5742. return nread;
  5743. }
  5744. if (nread < 0) {
  5745. /* socket error - check errno */
  5746. #if defined(_WIN32)
  5747. if (err == WSAEWOULDBLOCK) {
  5748. /* TODO (low): check if this is still required */
  5749. /* standard case if called from close_socket_gracefully */
  5750. return -2;
  5751. } else if (err == WSAETIMEDOUT) {
  5752. /* TODO (low): check if this is still required */
  5753. /* timeout is handled by the while loop */
  5754. return 0;
  5755. } else if (err == WSAECONNABORTED) {
  5756. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5757. return -2;
  5758. } else {
  5759. DEBUG_TRACE("recv() failed, error %d", err);
  5760. return -2;
  5761. }
  5762. #else
  5763. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5764. * if the timeout is reached and if the socket was set to non-
  5765. * blocking in close_socket_gracefully, so we can not distinguish
  5766. * here. We have to wait for the timeout in both cases for now.
  5767. */
  5768. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5769. /* TODO (low): check if this is still required */
  5770. /* EAGAIN/EWOULDBLOCK:
  5771. * standard case if called from close_socket_gracefully
  5772. * => should return -1 */
  5773. /* or timeout occurred
  5774. * => the code must stay in the while loop */
  5775. /* EINTR can be generated on a socket with a timeout set even
  5776. * when SA_RESTART is effective for all relevant signals
  5777. * (see signal(7)).
  5778. * => stay in the while loop */
  5779. } else {
  5780. DEBUG_TRACE("recv() failed, error %d", err);
  5781. return -2;
  5782. }
  5783. #endif
  5784. }
  5785. /* Timeout occurred, but no data available. */
  5786. return -1;
  5787. }
  5788. static int
  5789. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5790. {
  5791. int n, nread = 0;
  5792. double timeout = -1.0;
  5793. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5794. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5795. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5796. }
  5797. if (timeout >= 0.0) {
  5798. start_time = mg_get_current_time_ns();
  5799. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5800. }
  5801. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5802. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5803. if (n == -2) {
  5804. if (nread == 0) {
  5805. nread = -1; /* Propagate the error */
  5806. }
  5807. break;
  5808. } else if (n == -1) {
  5809. /* timeout */
  5810. if (timeout >= 0.0) {
  5811. now = mg_get_current_time_ns();
  5812. if ((now - start_time) <= timeout_ns) {
  5813. continue;
  5814. }
  5815. }
  5816. break;
  5817. } else if (n == 0) {
  5818. break; /* No more data to read */
  5819. } else {
  5820. nread += n;
  5821. len -= n;
  5822. }
  5823. }
  5824. return nread;
  5825. }
  5826. static void
  5827. discard_unread_request_data(struct mg_connection *conn)
  5828. {
  5829. char buf[MG_BUF_LEN];
  5830. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5831. ;
  5832. }
  5833. static int
  5834. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5835. {
  5836. int64_t content_len, n, buffered_len, nread;
  5837. int64_t len64 =
  5838. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5839. * int, we may not read more
  5840. * bytes */
  5841. const char *body;
  5842. if (conn == NULL) {
  5843. return 0;
  5844. }
  5845. /* If Content-Length is not set for a response with body data,
  5846. * we do not know in advance how much data should be read. */
  5847. content_len = conn->content_len;
  5848. if (content_len < 0) {
  5849. /* The body data is completed when the connection is closed. */
  5850. content_len = INT64_MAX;
  5851. }
  5852. nread = 0;
  5853. if (conn->consumed_content < content_len) {
  5854. /* Adjust number of bytes to read. */
  5855. int64_t left_to_read = content_len - conn->consumed_content;
  5856. if (left_to_read < len64) {
  5857. /* Do not read more than the total content length of the
  5858. * request.
  5859. */
  5860. len64 = left_to_read;
  5861. }
  5862. /* Return buffered data */
  5863. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5864. - conn->consumed_content;
  5865. if (buffered_len > 0) {
  5866. if (len64 < buffered_len) {
  5867. buffered_len = len64;
  5868. }
  5869. body = conn->buf + conn->request_len + conn->consumed_content;
  5870. memcpy(buf, body, (size_t)buffered_len);
  5871. len64 -= buffered_len;
  5872. conn->consumed_content += buffered_len;
  5873. nread += buffered_len;
  5874. buf = (char *)buf + buffered_len;
  5875. }
  5876. /* We have returned all buffered data. Read new data from the remote
  5877. * socket.
  5878. */
  5879. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5880. conn->consumed_content += n;
  5881. nread += n;
  5882. } else {
  5883. nread = ((nread > 0) ? nread : n);
  5884. }
  5885. }
  5886. return (int)nread;
  5887. }
  5888. int
  5889. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5890. {
  5891. if (len > INT_MAX) {
  5892. len = INT_MAX;
  5893. }
  5894. if (conn == NULL) {
  5895. return 0;
  5896. }
  5897. if (conn->is_chunked) {
  5898. size_t all_read = 0;
  5899. while (len > 0) {
  5900. if (conn->is_chunked >= 3) {
  5901. /* No more data left to read */
  5902. return 0;
  5903. }
  5904. if (conn->is_chunked != 1) {
  5905. /* Has error */
  5906. return -1;
  5907. }
  5908. if (conn->consumed_content != conn->content_len) {
  5909. /* copy from the current chunk */
  5910. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5911. if (read_ret < 1) {
  5912. /* read error */
  5913. conn->is_chunked = 2;
  5914. return -1;
  5915. }
  5916. all_read += (size_t)read_ret;
  5917. len -= (size_t)read_ret;
  5918. if (conn->consumed_content == conn->content_len) {
  5919. /* Add data bytes in the current chunk have been read,
  5920. * so we are expecting \r\n now. */
  5921. char x[2];
  5922. conn->content_len += 2;
  5923. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5924. || (x[1] != '\n')) {
  5925. /* Protocol violation */
  5926. conn->is_chunked = 2;
  5927. return -1;
  5928. }
  5929. }
  5930. } else {
  5931. /* fetch a new chunk */
  5932. size_t i;
  5933. char lenbuf[64];
  5934. char *end = NULL;
  5935. unsigned long chunkSize = 0;
  5936. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5937. conn->content_len++;
  5938. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5939. lenbuf[i] = 0;
  5940. }
  5941. if ((i > 0) && (lenbuf[i] == '\r')
  5942. && (lenbuf[i - 1] != '\r')) {
  5943. continue;
  5944. }
  5945. if ((i > 1) && (lenbuf[i] == '\n')
  5946. && (lenbuf[i - 1] == '\r')) {
  5947. lenbuf[i + 1] = 0;
  5948. chunkSize = strtoul(lenbuf, &end, 16);
  5949. if (chunkSize == 0) {
  5950. /* regular end of content */
  5951. conn->is_chunked = 3;
  5952. }
  5953. break;
  5954. }
  5955. if (!isxdigit((unsigned char)lenbuf[i])) {
  5956. /* illegal character for chunk length */
  5957. conn->is_chunked = 2;
  5958. return -1;
  5959. }
  5960. }
  5961. if ((end == NULL) || (*end != '\r')) {
  5962. /* chunksize not set correctly */
  5963. conn->is_chunked = 2;
  5964. return -1;
  5965. }
  5966. if (chunkSize == 0) {
  5967. /* try discarding trailer for keep-alive */
  5968. conn->content_len += 2;
  5969. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5970. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5971. conn->is_chunked = 4;
  5972. }
  5973. break;
  5974. }
  5975. /* append a new chunk */
  5976. conn->content_len += (int64_t)chunkSize;
  5977. }
  5978. }
  5979. return (int)all_read;
  5980. }
  5981. return mg_read_inner(conn, buf, len);
  5982. }
  5983. int
  5984. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5985. {
  5986. time_t now;
  5987. int n, total, allowed;
  5988. if (conn == NULL) {
  5989. return 0;
  5990. }
  5991. if (len > INT_MAX) {
  5992. return -1;
  5993. }
  5994. if (conn->throttle > 0) {
  5995. if ((now = time(NULL)) != conn->last_throttle_time) {
  5996. conn->last_throttle_time = now;
  5997. conn->last_throttle_bytes = 0;
  5998. }
  5999. allowed = conn->throttle - conn->last_throttle_bytes;
  6000. if (allowed > (int)len) {
  6001. allowed = (int)len;
  6002. }
  6003. if ((total = push_all(conn->phys_ctx,
  6004. NULL,
  6005. conn->client.sock,
  6006. conn->ssl,
  6007. (const char *)buf,
  6008. allowed))
  6009. == allowed) {
  6010. buf = (const char *)buf + total;
  6011. conn->last_throttle_bytes += total;
  6012. while ((total < (int)len)
  6013. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6014. allowed = (conn->throttle > ((int)len - total))
  6015. ? (int)len - total
  6016. : conn->throttle;
  6017. if ((n = push_all(conn->phys_ctx,
  6018. NULL,
  6019. conn->client.sock,
  6020. conn->ssl,
  6021. (const char *)buf,
  6022. allowed))
  6023. != allowed) {
  6024. break;
  6025. }
  6026. sleep(1);
  6027. conn->last_throttle_bytes = allowed;
  6028. conn->last_throttle_time = time(NULL);
  6029. buf = (const char *)buf + n;
  6030. total += n;
  6031. }
  6032. }
  6033. } else {
  6034. total = push_all(conn->phys_ctx,
  6035. NULL,
  6036. conn->client.sock,
  6037. conn->ssl,
  6038. (const char *)buf,
  6039. (int)len);
  6040. }
  6041. if (total > 0) {
  6042. conn->num_bytes_sent += total;
  6043. }
  6044. return total;
  6045. }
  6046. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6047. int
  6048. mg_send_chunk(struct mg_connection *conn,
  6049. const char *chunk,
  6050. unsigned int chunk_len)
  6051. {
  6052. char lenbuf[16];
  6053. size_t lenbuf_len;
  6054. int ret;
  6055. int t;
  6056. /* First store the length information in a text buffer. */
  6057. sprintf(lenbuf, "%x\r\n", chunk_len);
  6058. lenbuf_len = strlen(lenbuf);
  6059. /* Then send length information, chunk and terminating \r\n. */
  6060. ret = mg_write(conn, lenbuf, lenbuf_len);
  6061. if (ret != (int)lenbuf_len) {
  6062. return -1;
  6063. }
  6064. t = ret;
  6065. ret = mg_write(conn, chunk, chunk_len);
  6066. if (ret != (int)chunk_len) {
  6067. return -1;
  6068. }
  6069. t += ret;
  6070. ret = mg_write(conn, "\r\n", 2);
  6071. if (ret != 2) {
  6072. return -1;
  6073. }
  6074. t += ret;
  6075. return t;
  6076. }
  6077. #if defined(GCC_DIAGNOSTIC)
  6078. /* This block forwards format strings to printf implementations,
  6079. * so we need to disable the format-nonliteral warning. */
  6080. #pragma GCC diagnostic push
  6081. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6082. #endif
  6083. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6084. static int
  6085. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6086. {
  6087. va_list ap_copy;
  6088. size_t size = MG_BUF_LEN / 4;
  6089. int len = -1;
  6090. *buf = NULL;
  6091. while (len < 0) {
  6092. if (*buf) {
  6093. mg_free(*buf);
  6094. }
  6095. size *= 4;
  6096. *buf = (char *)mg_malloc(size);
  6097. if (!*buf) {
  6098. break;
  6099. }
  6100. va_copy(ap_copy, ap);
  6101. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6102. va_end(ap_copy);
  6103. (*buf)[size - 1] = 0;
  6104. }
  6105. return len;
  6106. }
  6107. /* Print message to buffer. If buffer is large enough to hold the message,
  6108. * return buffer. If buffer is to small, allocate large enough buffer on
  6109. * heap,
  6110. * and return allocated buffer. */
  6111. static int
  6112. alloc_vprintf(char **out_buf,
  6113. char *prealloc_buf,
  6114. size_t prealloc_size,
  6115. const char *fmt,
  6116. va_list ap)
  6117. {
  6118. va_list ap_copy;
  6119. int len;
  6120. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6121. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6122. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6123. * Therefore, we make two passes: on first pass, get required message
  6124. * length.
  6125. * On second pass, actually print the message. */
  6126. va_copy(ap_copy, ap);
  6127. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6128. va_end(ap_copy);
  6129. if (len < 0) {
  6130. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6131. * Switch to alternative code path that uses incremental
  6132. * allocations.
  6133. */
  6134. va_copy(ap_copy, ap);
  6135. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6136. va_end(ap_copy);
  6137. } else if ((size_t)(len) >= prealloc_size) {
  6138. /* The pre-allocated buffer not large enough. */
  6139. /* Allocate a new buffer. */
  6140. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6141. if (!*out_buf) {
  6142. /* Allocation failed. Return -1 as "out of memory" error. */
  6143. return -1;
  6144. }
  6145. /* Buffer allocation successful. Store the string there. */
  6146. va_copy(ap_copy, ap);
  6147. IGNORE_UNUSED_RESULT(
  6148. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6149. va_end(ap_copy);
  6150. } else {
  6151. /* The pre-allocated buffer is large enough.
  6152. * Use it to store the string and return the address. */
  6153. va_copy(ap_copy, ap);
  6154. IGNORE_UNUSED_RESULT(
  6155. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6156. va_end(ap_copy);
  6157. *out_buf = prealloc_buf;
  6158. }
  6159. return len;
  6160. }
  6161. #if defined(GCC_DIAGNOSTIC)
  6162. /* Enable format-nonliteral warning again. */
  6163. #pragma GCC diagnostic pop
  6164. #endif
  6165. static int
  6166. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6167. {
  6168. char mem[MG_BUF_LEN];
  6169. char *buf = NULL;
  6170. int len;
  6171. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6172. len = mg_write(conn, buf, (size_t)len);
  6173. }
  6174. if (buf != mem) {
  6175. mg_free(buf);
  6176. }
  6177. return len;
  6178. }
  6179. int
  6180. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6181. {
  6182. va_list ap;
  6183. int result;
  6184. va_start(ap, fmt);
  6185. result = mg_vprintf(conn, fmt, ap);
  6186. va_end(ap);
  6187. return result;
  6188. }
  6189. int
  6190. mg_url_decode(const char *src,
  6191. int src_len,
  6192. char *dst,
  6193. int dst_len,
  6194. int is_form_url_encoded)
  6195. {
  6196. int i, j, a, b;
  6197. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6198. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6199. if ((i < src_len - 2) && (src[i] == '%')
  6200. && isxdigit((unsigned char)src[i + 1])
  6201. && isxdigit((unsigned char)src[i + 2])) {
  6202. a = tolower((unsigned char)src[i + 1]);
  6203. b = tolower((unsigned char)src[i + 2]);
  6204. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6205. i += 2;
  6206. } else if (is_form_url_encoded && (src[i] == '+')) {
  6207. dst[j] = ' ';
  6208. } else {
  6209. dst[j] = src[i];
  6210. }
  6211. }
  6212. dst[j] = '\0'; /* Null-terminate the destination */
  6213. return (i >= src_len) ? j : -1;
  6214. }
  6215. /* form url decoding of an entire string */
  6216. static void
  6217. url_decode_in_place(char *buf)
  6218. {
  6219. int len = (int)strlen(buf);
  6220. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6221. }
  6222. int
  6223. mg_get_var(const char *data,
  6224. size_t data_len,
  6225. const char *name,
  6226. char *dst,
  6227. size_t dst_len)
  6228. {
  6229. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6230. }
  6231. int
  6232. mg_get_var2(const char *data,
  6233. size_t data_len,
  6234. const char *name,
  6235. char *dst,
  6236. size_t dst_len,
  6237. size_t occurrence)
  6238. {
  6239. const char *p, *e, *s;
  6240. size_t name_len;
  6241. int len;
  6242. if ((dst == NULL) || (dst_len == 0)) {
  6243. len = -2;
  6244. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6245. len = -1;
  6246. dst[0] = '\0';
  6247. } else {
  6248. name_len = strlen(name);
  6249. e = data + data_len;
  6250. len = -1;
  6251. dst[0] = '\0';
  6252. /* data is "var1=val1&var2=val2...". Find variable first */
  6253. for (p = data; p + name_len < e; p++) {
  6254. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6255. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6256. /* Point p to variable value */
  6257. p += name_len + 1;
  6258. /* Point s to the end of the value */
  6259. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6260. if (s == NULL) {
  6261. s = e;
  6262. }
  6263. DEBUG_ASSERT(s >= p);
  6264. if (s < p) {
  6265. return -3;
  6266. }
  6267. /* Decode variable into destination buffer */
  6268. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6269. /* Redirect error code from -1 to -2 (destination buffer too
  6270. * small). */
  6271. if (len == -1) {
  6272. len = -2;
  6273. }
  6274. break;
  6275. }
  6276. }
  6277. }
  6278. return len;
  6279. }
  6280. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6281. int
  6282. mg_split_form_urlencoded(char *data,
  6283. struct mg_header *form_fields,
  6284. unsigned num_form_fields)
  6285. {
  6286. char *b;
  6287. int i;
  6288. int num = 0;
  6289. if (data == NULL) {
  6290. /* parameter error */
  6291. return -1;
  6292. }
  6293. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6294. /* determine the number of expected fields */
  6295. if (data[0] == 0) {
  6296. return 0;
  6297. }
  6298. /* count number of & to return the number of key-value-pairs */
  6299. num = 1;
  6300. while (*data) {
  6301. if (*data == '&') {
  6302. num++;
  6303. }
  6304. data++;
  6305. }
  6306. return num;
  6307. }
  6308. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6309. /* parameter error */
  6310. return -1;
  6311. }
  6312. for (i = 0; i < (int)num_form_fields; i++) {
  6313. /* extract key-value pairs from input data */
  6314. while ((*data == ' ') || (*data == '\t')) {
  6315. /* skip initial spaces */
  6316. data++;
  6317. }
  6318. if (*data == 0) {
  6319. /* end of string reached */
  6320. break;
  6321. }
  6322. form_fields[num].name = data;
  6323. /* find & or = */
  6324. b = data;
  6325. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6326. b++;
  6327. }
  6328. if (*b == 0) {
  6329. /* last key without value */
  6330. form_fields[num].value = NULL;
  6331. } else if (*b == '&') {
  6332. /* mid key without value */
  6333. form_fields[num].value = NULL;
  6334. } else {
  6335. /* terminate string */
  6336. *b = 0;
  6337. /* value starts after '=' */
  6338. data = b + 1;
  6339. form_fields[num].value = data;
  6340. }
  6341. /* new field is stored */
  6342. num++;
  6343. /* find a next key */
  6344. b = strchr(data, '&');
  6345. if (b == 0) {
  6346. /* no more data */
  6347. break;
  6348. } else {
  6349. /* terminate value of last field at '&' */
  6350. *b = 0;
  6351. /* next key-value-pairs starts after '&' */
  6352. data = b + 1;
  6353. }
  6354. }
  6355. /* Decode all values */
  6356. for (i = 0; i < num; i++) {
  6357. if (form_fields[i].name) {
  6358. url_decode_in_place((char *)form_fields[i].name);
  6359. }
  6360. if (form_fields[i].value) {
  6361. url_decode_in_place((char *)form_fields[i].value);
  6362. }
  6363. }
  6364. /* return number of fields found */
  6365. return num;
  6366. }
  6367. /* HCP24: some changes to compare hole var_name */
  6368. int
  6369. mg_get_cookie(const char *cookie_header,
  6370. const char *var_name,
  6371. char *dst,
  6372. size_t dst_size)
  6373. {
  6374. const char *s, *p, *end;
  6375. int name_len, len = -1;
  6376. if ((dst == NULL) || (dst_size == 0)) {
  6377. return -2;
  6378. }
  6379. dst[0] = '\0';
  6380. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6381. return -1;
  6382. }
  6383. name_len = (int)strlen(var_name);
  6384. end = s + strlen(s);
  6385. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6386. if (s[name_len] == '=') {
  6387. /* HCP24: now check is it a substring or a full cookie name */
  6388. if ((s == cookie_header) || (s[-1] == ' ')) {
  6389. s += name_len + 1;
  6390. if ((p = strchr(s, ' ')) == NULL) {
  6391. p = end;
  6392. }
  6393. if (p[-1] == ';') {
  6394. p--;
  6395. }
  6396. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6397. s++;
  6398. p--;
  6399. }
  6400. if ((size_t)(p - s) < dst_size) {
  6401. len = (int)(p - s);
  6402. mg_strlcpy(dst, s, (size_t)len + 1);
  6403. } else {
  6404. len = -3;
  6405. }
  6406. break;
  6407. }
  6408. }
  6409. }
  6410. return len;
  6411. }
  6412. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6413. static void
  6414. base64_encode(const unsigned char *src, int src_len, char *dst)
  6415. {
  6416. static const char *b64 =
  6417. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6418. int i, j, a, b, c;
  6419. for (i = j = 0; i < src_len; i += 3) {
  6420. a = src[i];
  6421. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6422. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6423. dst[j++] = b64[a >> 2];
  6424. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6425. if (i + 1 < src_len) {
  6426. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6427. }
  6428. if (i + 2 < src_len) {
  6429. dst[j++] = b64[c & 63];
  6430. }
  6431. }
  6432. while (j % 4 != 0) {
  6433. dst[j++] = '=';
  6434. }
  6435. dst[j++] = '\0';
  6436. }
  6437. #endif
  6438. #if defined(USE_LUA)
  6439. static unsigned char
  6440. b64reverse(char letter)
  6441. {
  6442. if ((letter >= 'A') && (letter <= 'Z')) {
  6443. return letter - 'A';
  6444. }
  6445. if ((letter >= 'a') && (letter <= 'z')) {
  6446. return letter - 'a' + 26;
  6447. }
  6448. if ((letter >= '0') && (letter <= '9')) {
  6449. return letter - '0' + 52;
  6450. }
  6451. if (letter == '+') {
  6452. return 62;
  6453. }
  6454. if (letter == '/') {
  6455. return 63;
  6456. }
  6457. if (letter == '=') {
  6458. return 255; /* normal end */
  6459. }
  6460. return 254; /* error */
  6461. }
  6462. static int
  6463. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6464. {
  6465. int i;
  6466. unsigned char a, b, c, d;
  6467. *dst_len = 0;
  6468. for (i = 0; i < src_len; i += 4) {
  6469. a = b64reverse(src[i]);
  6470. if (a >= 254) {
  6471. return i;
  6472. }
  6473. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6474. if (b >= 254) {
  6475. return i + 1;
  6476. }
  6477. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6478. if (c == 254) {
  6479. return i + 2;
  6480. }
  6481. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6482. if (d == 254) {
  6483. return i + 3;
  6484. }
  6485. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6486. if (c != 255) {
  6487. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6488. if (d != 255) {
  6489. dst[(*dst_len)++] = (c << 6) + d;
  6490. }
  6491. }
  6492. }
  6493. return -1;
  6494. }
  6495. #endif
  6496. static int
  6497. is_put_or_delete_method(const struct mg_connection *conn)
  6498. {
  6499. if (conn) {
  6500. const char *s = conn->request_info.request_method;
  6501. return (s != NULL)
  6502. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6503. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6504. }
  6505. return 0;
  6506. }
  6507. #if !defined(NO_FILES)
  6508. static int
  6509. extention_matches_script(
  6510. struct mg_connection *conn, /* in: request (must be valid) */
  6511. const char *filename /* in: filename (must be valid) */
  6512. )
  6513. {
  6514. #if !defined(NO_CGI)
  6515. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6516. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6517. filename)
  6518. > 0) {
  6519. return 1;
  6520. }
  6521. #endif
  6522. #if defined(USE_LUA)
  6523. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6524. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6525. filename)
  6526. > 0) {
  6527. return 1;
  6528. }
  6529. #endif
  6530. #if defined(USE_DUKTAPE)
  6531. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6532. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6533. filename)
  6534. > 0) {
  6535. return 1;
  6536. }
  6537. #endif
  6538. /* filename and conn could be unused, if all preocessor conditions
  6539. * are false (no script language supported). */
  6540. (void)filename;
  6541. (void)conn;
  6542. return 0;
  6543. }
  6544. /* For given directory path, substitute it to valid index file.
  6545. * Return 1 if index file has been found, 0 if not found.
  6546. * If the file is found, it's stats is returned in stp. */
  6547. static int
  6548. substitute_index_file(struct mg_connection *conn,
  6549. char *path,
  6550. size_t path_len,
  6551. struct mg_file_stat *filestat)
  6552. {
  6553. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6554. struct vec filename_vec;
  6555. size_t n = strlen(path);
  6556. int found = 0;
  6557. /* The 'path' given to us points to the directory. Remove all trailing
  6558. * directory separator characters from the end of the path, and
  6559. * then append single directory separator character. */
  6560. while ((n > 0) && (path[n - 1] == '/')) {
  6561. n--;
  6562. }
  6563. path[n] = '/';
  6564. /* Traverse index files list. For each entry, append it to the given
  6565. * path and see if the file exists. If it exists, break the loop */
  6566. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6567. /* Ignore too long entries that may overflow path buffer */
  6568. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6569. continue;
  6570. }
  6571. /* Prepare full path to the index file */
  6572. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6573. /* Does it exist? */
  6574. if (mg_stat(conn, path, filestat)) {
  6575. /* Yes it does, break the loop */
  6576. found = 1;
  6577. break;
  6578. }
  6579. }
  6580. /* If no index file exists, restore directory path */
  6581. if (!found) {
  6582. path[n] = '\0';
  6583. }
  6584. return found;
  6585. }
  6586. #endif
  6587. static void
  6588. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6589. char *filename, /* out: filename */
  6590. size_t filename_buf_len, /* in: size of filename buffer */
  6591. struct mg_file_stat *filestat, /* out: file status structure */
  6592. int *is_found, /* out: file found (directly) */
  6593. int *is_script_resource, /* out: handled by a script? */
  6594. int *is_websocket_request, /* out: websocket connetion? */
  6595. int *is_put_or_delete_request /* out: put/delete a file? */
  6596. )
  6597. {
  6598. char const *accept_encoding;
  6599. #if !defined(NO_FILES)
  6600. const char *uri = conn->request_info.local_uri;
  6601. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6602. const char *rewrite;
  6603. struct vec a, b;
  6604. ptrdiff_t match_len;
  6605. char gz_path[PATH_MAX];
  6606. int truncated;
  6607. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6608. char *tmp_str;
  6609. size_t tmp_str_len, sep_pos;
  6610. int allow_substitute_script_subresources;
  6611. #endif
  6612. #else
  6613. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6614. #endif
  6615. /* Step 1: Set all initially unknown outputs to zero */
  6616. memset(filestat, 0, sizeof(*filestat));
  6617. *filename = 0;
  6618. *is_found = 0;
  6619. *is_script_resource = 0;
  6620. /* Step 2: Check if the request attempts to modify the file system */
  6621. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6622. /* Step 3: Check if it is a websocket request, and modify the document
  6623. * root if required */
  6624. #if defined(USE_WEBSOCKET)
  6625. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6626. #if !defined(NO_FILES)
  6627. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6628. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6629. }
  6630. #endif /* !NO_FILES */
  6631. #else /* USE_WEBSOCKET */
  6632. *is_websocket_request = 0;
  6633. #endif /* USE_WEBSOCKET */
  6634. /* Step 4: Check if gzip encoded response is allowed */
  6635. conn->accept_gzip = 0;
  6636. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6637. if (strstr(accept_encoding, "gzip") != NULL) {
  6638. conn->accept_gzip = 1;
  6639. }
  6640. }
  6641. #if !defined(NO_FILES)
  6642. /* Step 5: If there is no root directory, don't look for files. */
  6643. /* Note that root == NULL is a regular use case here. This occurs,
  6644. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6645. * config is not required. */
  6646. if (root == NULL) {
  6647. /* all file related outputs have already been set to 0, just return
  6648. */
  6649. return;
  6650. }
  6651. /* Step 6: Determine the local file path from the root path and the
  6652. * request uri. */
  6653. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6654. * part of the path one byte on the right. */
  6655. mg_snprintf(
  6656. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6657. if (truncated) {
  6658. goto interpret_cleanup;
  6659. }
  6660. /* Step 7: URI rewriting */
  6661. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6662. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6663. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6664. mg_snprintf(conn,
  6665. &truncated,
  6666. filename,
  6667. filename_buf_len - 1,
  6668. "%.*s%s",
  6669. (int)b.len,
  6670. b.ptr,
  6671. uri + match_len);
  6672. break;
  6673. }
  6674. }
  6675. if (truncated) {
  6676. goto interpret_cleanup;
  6677. }
  6678. /* Step 8: Check if the file exists at the server */
  6679. /* Local file path and name, corresponding to requested URI
  6680. * is now stored in "filename" variable. */
  6681. if (mg_stat(conn, filename, filestat)) {
  6682. int uri_len = (int)strlen(uri);
  6683. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6684. /* 8.1: File exists. */
  6685. *is_found = 1;
  6686. /* 8.2: Check if it is a script type. */
  6687. if (extention_matches_script(conn, filename)) {
  6688. /* The request addresses a CGI resource, Lua script or
  6689. * server-side javascript.
  6690. * The URI corresponds to the script itself (like
  6691. * /path/script.cgi), and there is no additional resource
  6692. * path (like /path/script.cgi/something).
  6693. * Requests that modify (replace or delete) a resource, like
  6694. * PUT and DELETE requests, should replace/delete the script
  6695. * file.
  6696. * Requests that read or write from/to a resource, like GET and
  6697. * POST requests, should call the script and return the
  6698. * generated response. */
  6699. *is_script_resource = (!*is_put_or_delete_request);
  6700. }
  6701. /* 8.3: If the request target is a directory, there could be
  6702. * a substitute file (index.html, index.cgi, ...). */
  6703. if (filestat->is_directory && is_uri_end_slash) {
  6704. /* Use a local copy here, since substitute_index_file will
  6705. * change the content of the file status */
  6706. struct mg_file_stat tmp_filestat;
  6707. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6708. if (substitute_index_file(
  6709. conn, filename, filename_buf_len, &tmp_filestat)) {
  6710. /* Substitute file found. Copy stat to the output, then
  6711. * check if the file is a script file */
  6712. *filestat = tmp_filestat;
  6713. if (extention_matches_script(conn, filename)) {
  6714. /* Substitute file is a script file */
  6715. *is_script_resource = 1;
  6716. } else {
  6717. /* Substitute file is a regular file */
  6718. *is_script_resource = 0;
  6719. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6720. }
  6721. }
  6722. /* If there is no substitute file, the server could return
  6723. * a directory listing in a later step */
  6724. }
  6725. return;
  6726. }
  6727. /* Step 9: Check for zipped files: */
  6728. /* If we can't find the actual file, look for the file
  6729. * with the same name but a .gz extension. If we find it,
  6730. * use that and set the gzipped flag in the file struct
  6731. * to indicate that the response need to have the content-
  6732. * encoding: gzip header.
  6733. * We can only do this if the browser declares support. */
  6734. if (conn->accept_gzip) {
  6735. mg_snprintf(
  6736. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6737. if (truncated) {
  6738. goto interpret_cleanup;
  6739. }
  6740. if (mg_stat(conn, gz_path, filestat)) {
  6741. if (filestat) {
  6742. filestat->is_gzipped = 1;
  6743. *is_found = 1;
  6744. }
  6745. /* Currently gz files can not be scripts. */
  6746. return;
  6747. }
  6748. }
  6749. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6750. /* Step 10: Script resources may handle sub-resources */
  6751. /* Support PATH_INFO for CGI scripts. */
  6752. tmp_str_len = strlen(filename);
  6753. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6754. if (!tmp_str) {
  6755. /* Out of memory */
  6756. goto interpret_cleanup;
  6757. }
  6758. memcpy(tmp_str, filename, tmp_str_len + 1);
  6759. /* Check config, if index scripts may have sub-resources */
  6760. allow_substitute_script_subresources =
  6761. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6762. "yes");
  6763. sep_pos = tmp_str_len;
  6764. while (sep_pos > 0) {
  6765. sep_pos--;
  6766. if (tmp_str[sep_pos] == '/') {
  6767. int is_script = 0, does_exist = 0;
  6768. tmp_str[sep_pos] = 0;
  6769. if (tmp_str[0]) {
  6770. is_script = extention_matches_script(conn, tmp_str);
  6771. does_exist = mg_stat(conn, tmp_str, filestat);
  6772. }
  6773. if (does_exist && is_script) {
  6774. filename[sep_pos] = 0;
  6775. memmove(filename + sep_pos + 2,
  6776. filename + sep_pos + 1,
  6777. strlen(filename + sep_pos + 1) + 1);
  6778. conn->path_info = filename + sep_pos + 1;
  6779. filename[sep_pos + 1] = '/';
  6780. *is_script_resource = 1;
  6781. *is_found = 1;
  6782. break;
  6783. }
  6784. if (allow_substitute_script_subresources) {
  6785. if (substitute_index_file(
  6786. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6787. /* some intermediate directory has an index file */
  6788. if (extention_matches_script(conn, tmp_str)) {
  6789. DEBUG_TRACE("Substitute script %s serving path %s",
  6790. tmp_str,
  6791. filename);
  6792. /* this index file is a script */
  6793. mg_snprintf(conn,
  6794. &truncated,
  6795. filename,
  6796. filename_buf_len,
  6797. "%s//%s",
  6798. tmp_str,
  6799. filename + sep_pos + 1);
  6800. if (truncated) {
  6801. mg_free(tmp_str);
  6802. goto interpret_cleanup;
  6803. }
  6804. sep_pos = strlen(tmp_str);
  6805. filename[sep_pos] = 0;
  6806. conn->path_info = filename + sep_pos + 1;
  6807. *is_script_resource = 1;
  6808. *is_found = 1;
  6809. break;
  6810. } else {
  6811. DEBUG_TRACE("Substitute file %s serving path %s",
  6812. tmp_str,
  6813. filename);
  6814. /* non-script files will not have sub-resources */
  6815. filename[sep_pos] = 0;
  6816. conn->path_info = 0;
  6817. *is_script_resource = 0;
  6818. *is_found = 0;
  6819. break;
  6820. }
  6821. }
  6822. }
  6823. tmp_str[sep_pos] = '/';
  6824. }
  6825. }
  6826. mg_free(tmp_str);
  6827. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6828. #endif /* !defined(NO_FILES) */
  6829. return;
  6830. #if !defined(NO_FILES)
  6831. /* Reset all outputs */
  6832. interpret_cleanup:
  6833. memset(filestat, 0, sizeof(*filestat));
  6834. *filename = 0;
  6835. *is_found = 0;
  6836. *is_script_resource = 0;
  6837. *is_websocket_request = 0;
  6838. *is_put_or_delete_request = 0;
  6839. #endif /* !defined(NO_FILES) */
  6840. }
  6841. /* Check whether full request is buffered. Return:
  6842. * -1 if request or response is malformed
  6843. * 0 if request or response is not yet fully buffered
  6844. * >0 actual request length, including last \r\n\r\n */
  6845. static int
  6846. get_http_header_len(const char *buf, int buflen)
  6847. {
  6848. int i;
  6849. for (i = 0; i < buflen; i++) {
  6850. /* Do an unsigned comparison in some conditions below */
  6851. const unsigned char c = (unsigned char)buf[i];
  6852. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6853. && !isprint(c)) {
  6854. /* abort scan as soon as one malformed character is found */
  6855. return -1;
  6856. }
  6857. if (i < buflen - 1) {
  6858. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6859. /* Two newline, no carriage return - not standard compliant,
  6860. * but it should be accepted */
  6861. return i + 2;
  6862. }
  6863. }
  6864. if (i < buflen - 3) {
  6865. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6866. && (buf[i + 3] == '\n')) {
  6867. /* Two \r\n - standard compliant */
  6868. return i + 4;
  6869. }
  6870. }
  6871. }
  6872. return 0;
  6873. }
  6874. #if !defined(NO_CACHING)
  6875. /* Convert month to the month number. Return -1 on error, or month number */
  6876. static int
  6877. get_month_index(const char *s)
  6878. {
  6879. size_t i;
  6880. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6881. if (!strcmp(s, month_names[i])) {
  6882. return (int)i;
  6883. }
  6884. }
  6885. return -1;
  6886. }
  6887. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6888. static time_t
  6889. parse_date_string(const char *datetime)
  6890. {
  6891. char month_str[32] = {0};
  6892. int second, minute, hour, day, month, year;
  6893. time_t result = (time_t)0;
  6894. struct tm tm;
  6895. if ((sscanf(datetime,
  6896. "%d/%3s/%d %d:%d:%d",
  6897. &day,
  6898. month_str,
  6899. &year,
  6900. &hour,
  6901. &minute,
  6902. &second)
  6903. == 6)
  6904. || (sscanf(datetime,
  6905. "%d %3s %d %d:%d:%d",
  6906. &day,
  6907. month_str,
  6908. &year,
  6909. &hour,
  6910. &minute,
  6911. &second)
  6912. == 6)
  6913. || (sscanf(datetime,
  6914. "%*3s, %d %3s %d %d:%d:%d",
  6915. &day,
  6916. month_str,
  6917. &year,
  6918. &hour,
  6919. &minute,
  6920. &second)
  6921. == 6)
  6922. || (sscanf(datetime,
  6923. "%d-%3s-%d %d:%d:%d",
  6924. &day,
  6925. month_str,
  6926. &year,
  6927. &hour,
  6928. &minute,
  6929. &second)
  6930. == 6)) {
  6931. month = get_month_index(month_str);
  6932. if ((month >= 0) && (year >= 1970)) {
  6933. memset(&tm, 0, sizeof(tm));
  6934. tm.tm_year = year - 1900;
  6935. tm.tm_mon = month;
  6936. tm.tm_mday = day;
  6937. tm.tm_hour = hour;
  6938. tm.tm_min = minute;
  6939. tm.tm_sec = second;
  6940. result = timegm(&tm);
  6941. }
  6942. }
  6943. return result;
  6944. }
  6945. #endif /* !NO_CACHING */
  6946. /* Pre-process URIs according to RFC + protect against directory disclosure
  6947. * attacks by removing '..', excessive '/' and '\' characters */
  6948. static void
  6949. remove_dot_segments(char *inout)
  6950. {
  6951. /* Windows backend protection
  6952. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6953. * in URI by slash */
  6954. char *out_end = inout;
  6955. char *in = inout;
  6956. if (!in) {
  6957. /* Param error. */
  6958. return;
  6959. }
  6960. while (*in) {
  6961. if (*in == '\\') {
  6962. *in = '/';
  6963. }
  6964. in++;
  6965. }
  6966. /* Algorithm "remove_dot_segments" from
  6967. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6968. /* Step 1:
  6969. * The input buffer is initialized.
  6970. * The output buffer is initialized to the empty string.
  6971. */
  6972. in = inout;
  6973. /* Step 2:
  6974. * While the input buffer is not empty, loop as follows:
  6975. */
  6976. /* Less than out_end of the inout buffer is used as output, so keep
  6977. * condition: out_end <= in */
  6978. while (*in) {
  6979. /* Step 2a:
  6980. * If the input buffer begins with a prefix of "../" or "./",
  6981. * then remove that prefix from the input buffer;
  6982. */
  6983. if (!strncmp(in, "../", 3)) {
  6984. in += 3;
  6985. } else if (!strncmp(in, "./", 2)) {
  6986. in += 2;
  6987. }
  6988. /* otherwise */
  6989. /* Step 2b:
  6990. * if the input buffer begins with a prefix of "/./" or "/.",
  6991. * where "." is a complete path segment, then replace that
  6992. * prefix with "/" in the input buffer;
  6993. */
  6994. else if (!strncmp(in, "/./", 3)) {
  6995. in += 2;
  6996. } else if (!strcmp(in, "/.")) {
  6997. in[1] = 0;
  6998. }
  6999. /* otherwise */
  7000. /* Step 2c:
  7001. * if the input buffer begins with a prefix of "/../" or "/..",
  7002. * where ".." is a complete path segment, then replace that
  7003. * prefix with "/" in the input buffer and remove the last
  7004. * segment and its preceding "/" (if any) from the output
  7005. * buffer;
  7006. */
  7007. else if (!strncmp(in, "/../", 4)) {
  7008. in += 3;
  7009. if (inout != out_end) {
  7010. /* remove last segment */
  7011. do {
  7012. out_end--;
  7013. } while ((inout != out_end) && (*out_end != '/'));
  7014. }
  7015. } else if (!strcmp(in, "/..")) {
  7016. in[1] = 0;
  7017. if (inout != out_end) {
  7018. /* remove last segment */
  7019. do {
  7020. out_end--;
  7021. } while ((inout != out_end) && (*out_end != '/'));
  7022. }
  7023. }
  7024. /* otherwise */
  7025. /* Step 2d:
  7026. * if the input buffer consists only of "." or "..", then remove
  7027. * that from the input buffer;
  7028. */
  7029. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7030. *in = 0;
  7031. }
  7032. /* otherwise */
  7033. /* Step 2e:
  7034. * move the first path segment in the input buffer to the end of
  7035. * the output buffer, including the initial "/" character (if
  7036. * any) and any subsequent characters up to, but not including,
  7037. * the next "/" character or the end of the input buffer.
  7038. */
  7039. else {
  7040. do {
  7041. *out_end = *in;
  7042. out_end++;
  7043. in++;
  7044. } while ((*in != 0) && (*in != '/'));
  7045. }
  7046. }
  7047. /* Step 3:
  7048. * Finally, the output buffer is returned as the result of
  7049. * remove_dot_segments.
  7050. */
  7051. /* Terminate output */
  7052. *out_end = 0;
  7053. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7054. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7055. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7056. * or "//" anymore.
  7057. */
  7058. out_end = in = inout;
  7059. while (*in) {
  7060. if (*in == '.') {
  7061. /* remove . at the end or preceding of / */
  7062. char *in_ahead = in;
  7063. do {
  7064. in_ahead++;
  7065. } while (*in_ahead == '.');
  7066. if (*in_ahead == '/') {
  7067. in = in_ahead;
  7068. if ((out_end != inout) && (out_end[-1] == '/')) {
  7069. /* remove generated // */
  7070. out_end--;
  7071. }
  7072. } else if (*in_ahead == 0) {
  7073. in = in_ahead;
  7074. } else {
  7075. do {
  7076. *out_end++ = '.';
  7077. in++;
  7078. } while (in != in_ahead);
  7079. }
  7080. } else if (*in == '/') {
  7081. /* replace // by / */
  7082. *out_end++ = '/';
  7083. do {
  7084. in++;
  7085. } while (*in == '/');
  7086. } else {
  7087. *out_end++ = *in;
  7088. in++;
  7089. }
  7090. }
  7091. *out_end = 0;
  7092. }
  7093. static const struct {
  7094. const char *extension;
  7095. size_t ext_len;
  7096. const char *mime_type;
  7097. } builtin_mime_types[] = {
  7098. /* IANA registered MIME types
  7099. * (http://www.iana.org/assignments/media-types)
  7100. * application types */
  7101. {".doc", 4, "application/msword"},
  7102. {".eps", 4, "application/postscript"},
  7103. {".exe", 4, "application/octet-stream"},
  7104. {".js", 3, "application/javascript"},
  7105. {".json", 5, "application/json"},
  7106. {".pdf", 4, "application/pdf"},
  7107. {".ps", 3, "application/postscript"},
  7108. {".rtf", 4, "application/rtf"},
  7109. {".xhtml", 6, "application/xhtml+xml"},
  7110. {".xsl", 4, "application/xml"},
  7111. {".xslt", 5, "application/xml"},
  7112. /* fonts */
  7113. {".ttf", 4, "application/font-sfnt"},
  7114. {".cff", 4, "application/font-sfnt"},
  7115. {".otf", 4, "application/font-sfnt"},
  7116. {".aat", 4, "application/font-sfnt"},
  7117. {".sil", 4, "application/font-sfnt"},
  7118. {".pfr", 4, "application/font-tdpfr"},
  7119. {".woff", 5, "application/font-woff"},
  7120. /* audio */
  7121. {".mp3", 4, "audio/mpeg"},
  7122. {".oga", 4, "audio/ogg"},
  7123. {".ogg", 4, "audio/ogg"},
  7124. /* image */
  7125. {".gif", 4, "image/gif"},
  7126. {".ief", 4, "image/ief"},
  7127. {".jpeg", 5, "image/jpeg"},
  7128. {".jpg", 4, "image/jpeg"},
  7129. {".jpm", 4, "image/jpm"},
  7130. {".jpx", 4, "image/jpx"},
  7131. {".png", 4, "image/png"},
  7132. {".svg", 4, "image/svg+xml"},
  7133. {".tif", 4, "image/tiff"},
  7134. {".tiff", 5, "image/tiff"},
  7135. /* model */
  7136. {".wrl", 4, "model/vrml"},
  7137. /* text */
  7138. {".css", 4, "text/css"},
  7139. {".csv", 4, "text/csv"},
  7140. {".htm", 4, "text/html"},
  7141. {".html", 5, "text/html"},
  7142. {".sgm", 4, "text/sgml"},
  7143. {".shtm", 5, "text/html"},
  7144. {".shtml", 6, "text/html"},
  7145. {".txt", 4, "text/plain"},
  7146. {".xml", 4, "text/xml"},
  7147. /* video */
  7148. {".mov", 4, "video/quicktime"},
  7149. {".mp4", 4, "video/mp4"},
  7150. {".mpeg", 5, "video/mpeg"},
  7151. {".mpg", 4, "video/mpeg"},
  7152. {".ogv", 4, "video/ogg"},
  7153. {".qt", 3, "video/quicktime"},
  7154. /* not registered types
  7155. * (http://reference.sitepoint.com/html/mime-types-full,
  7156. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7157. {".arj", 4, "application/x-arj-compressed"},
  7158. {".gz", 3, "application/x-gunzip"},
  7159. {".rar", 4, "application/x-arj-compressed"},
  7160. {".swf", 4, "application/x-shockwave-flash"},
  7161. {".tar", 4, "application/x-tar"},
  7162. {".tgz", 4, "application/x-tar-gz"},
  7163. {".torrent", 8, "application/x-bittorrent"},
  7164. {".ppt", 4, "application/x-mspowerpoint"},
  7165. {".xls", 4, "application/x-msexcel"},
  7166. {".zip", 4, "application/x-zip-compressed"},
  7167. {".aac",
  7168. 4,
  7169. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7170. {".aif", 4, "audio/x-aif"},
  7171. {".m3u", 4, "audio/x-mpegurl"},
  7172. {".mid", 4, "audio/x-midi"},
  7173. {".ra", 3, "audio/x-pn-realaudio"},
  7174. {".ram", 4, "audio/x-pn-realaudio"},
  7175. {".wav", 4, "audio/x-wav"},
  7176. {".bmp", 4, "image/bmp"},
  7177. {".ico", 4, "image/x-icon"},
  7178. {".pct", 4, "image/x-pct"},
  7179. {".pict", 5, "image/pict"},
  7180. {".rgb", 4, "image/x-rgb"},
  7181. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7182. {".asf", 4, "video/x-ms-asf"},
  7183. {".avi", 4, "video/x-msvideo"},
  7184. {".m4v", 4, "video/x-m4v"},
  7185. {NULL, 0, NULL}};
  7186. const char *
  7187. mg_get_builtin_mime_type(const char *path)
  7188. {
  7189. const char *ext;
  7190. size_t i, path_len;
  7191. path_len = strlen(path);
  7192. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7193. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7194. if ((path_len > builtin_mime_types[i].ext_len)
  7195. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7196. return builtin_mime_types[i].mime_type;
  7197. }
  7198. }
  7199. return "text/plain";
  7200. }
  7201. /* Look at the "path" extension and figure what mime type it has.
  7202. * Store mime type in the vector. */
  7203. static void
  7204. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7205. {
  7206. struct vec ext_vec, mime_vec;
  7207. const char *list, *ext;
  7208. size_t path_len;
  7209. path_len = strlen(path);
  7210. if ((conn == NULL) || (vec == NULL)) {
  7211. if (vec != NULL) {
  7212. memset(vec, '\0', sizeof(struct vec));
  7213. }
  7214. return;
  7215. }
  7216. /* Scan user-defined mime types first, in case user wants to
  7217. * override default mime types. */
  7218. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7219. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7220. /* ext now points to the path suffix */
  7221. ext = path + path_len - ext_vec.len;
  7222. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7223. *vec = mime_vec;
  7224. return;
  7225. }
  7226. }
  7227. vec->ptr = mg_get_builtin_mime_type(path);
  7228. vec->len = strlen(vec->ptr);
  7229. }
  7230. /* Stringify binary data. Output buffer must be twice as big as input,
  7231. * because each byte takes 2 bytes in string representation */
  7232. static void
  7233. bin2str(char *to, const unsigned char *p, size_t len)
  7234. {
  7235. static const char *hex = "0123456789abcdef";
  7236. for (; len--; p++) {
  7237. *to++ = hex[p[0] >> 4];
  7238. *to++ = hex[p[0] & 0x0f];
  7239. }
  7240. *to = '\0';
  7241. }
  7242. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7243. */
  7244. char *
  7245. mg_md5(char buf[33], ...)
  7246. {
  7247. md5_byte_t hash[16];
  7248. const char *p;
  7249. va_list ap;
  7250. md5_state_t ctx;
  7251. md5_init(&ctx);
  7252. va_start(ap, buf);
  7253. while ((p = va_arg(ap, const char *)) != NULL) {
  7254. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7255. }
  7256. va_end(ap);
  7257. md5_finish(&ctx, hash);
  7258. bin2str(buf, hash, sizeof(hash));
  7259. return buf;
  7260. }
  7261. /* Check the user's password, return 1 if OK */
  7262. static int
  7263. check_password(const char *method,
  7264. const char *ha1,
  7265. const char *uri,
  7266. const char *nonce,
  7267. const char *nc,
  7268. const char *cnonce,
  7269. const char *qop,
  7270. const char *response)
  7271. {
  7272. char ha2[32 + 1], expected_response[32 + 1];
  7273. /* Some of the parameters may be NULL */
  7274. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7275. || (qop == NULL) || (response == NULL)) {
  7276. return 0;
  7277. }
  7278. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7279. if (strlen(response) != 32) {
  7280. return 0;
  7281. }
  7282. mg_md5(ha2, method, ":", uri, NULL);
  7283. mg_md5(expected_response,
  7284. ha1,
  7285. ":",
  7286. nonce,
  7287. ":",
  7288. nc,
  7289. ":",
  7290. cnonce,
  7291. ":",
  7292. qop,
  7293. ":",
  7294. ha2,
  7295. NULL);
  7296. return mg_strcasecmp(response, expected_response) == 0;
  7297. }
  7298. #if !defined(NO_FILESYSTEMS)
  7299. /* Use the global passwords file, if specified by auth_gpass option,
  7300. * or search for .htpasswd in the requested directory. */
  7301. static void
  7302. open_auth_file(struct mg_connection *conn,
  7303. const char *path,
  7304. struct mg_file *filep)
  7305. {
  7306. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7307. char name[PATH_MAX];
  7308. const char *p, *e,
  7309. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7310. int truncated;
  7311. if (gpass != NULL) {
  7312. /* Use global passwords file */
  7313. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7314. #if defined(DEBUG)
  7315. /* Use mg_cry_internal here, since gpass has been
  7316. * configured. */
  7317. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7318. #endif
  7319. }
  7320. /* Important: using local struct mg_file to test path for
  7321. * is_directory flag. If filep is used, mg_stat() makes it
  7322. * appear as if auth file was opened.
  7323. * TODO(mid): Check if this is still required after rewriting
  7324. * mg_stat */
  7325. } else if (mg_stat(conn, path, &filep->stat)
  7326. && filep->stat.is_directory) {
  7327. mg_snprintf(conn,
  7328. &truncated,
  7329. name,
  7330. sizeof(name),
  7331. "%s/%s",
  7332. path,
  7333. PASSWORDS_FILE_NAME);
  7334. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7335. #if defined(DEBUG)
  7336. /* Don't use mg_cry_internal here, but only a trace, since
  7337. * this is a typical case. It will occur for every directory
  7338. * without a password file. */
  7339. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7340. #endif
  7341. }
  7342. } else {
  7343. /* Try to find .htpasswd in requested directory. */
  7344. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7345. if (e[0] == '/') {
  7346. break;
  7347. }
  7348. }
  7349. mg_snprintf(conn,
  7350. &truncated,
  7351. name,
  7352. sizeof(name),
  7353. "%.*s/%s",
  7354. (int)(e - p),
  7355. p,
  7356. PASSWORDS_FILE_NAME);
  7357. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7358. #if defined(DEBUG)
  7359. /* Don't use mg_cry_internal here, but only a trace, since
  7360. * this is a typical case. It will occur for every directory
  7361. * without a password file. */
  7362. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7363. #endif
  7364. }
  7365. }
  7366. }
  7367. }
  7368. #endif /* NO_FILESYSTEMS */
  7369. /* Parsed Authorization header */
  7370. struct ah {
  7371. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7372. };
  7373. /* Return 1 on success. Always initializes the ah structure. */
  7374. static int
  7375. parse_auth_header(struct mg_connection *conn,
  7376. char *buf,
  7377. size_t buf_size,
  7378. struct ah *ah)
  7379. {
  7380. char *name, *value, *s;
  7381. const char *auth_header;
  7382. uint64_t nonce;
  7383. if (!ah || !conn) {
  7384. return 0;
  7385. }
  7386. (void)memset(ah, 0, sizeof(*ah));
  7387. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7388. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7389. return 0;
  7390. }
  7391. /* Make modifiable copy of the auth header */
  7392. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7393. s = buf;
  7394. /* Parse authorization header */
  7395. for (;;) {
  7396. /* Gobble initial spaces */
  7397. while (isspace((unsigned char)*s)) {
  7398. s++;
  7399. }
  7400. name = skip_quoted(&s, "=", " ", 0);
  7401. /* Value is either quote-delimited, or ends at first comma or space.
  7402. */
  7403. if (s[0] == '\"') {
  7404. s++;
  7405. value = skip_quoted(&s, "\"", " ", '\\');
  7406. if (s[0] == ',') {
  7407. s++;
  7408. }
  7409. } else {
  7410. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7411. * uses spaces */
  7412. }
  7413. if (*name == '\0') {
  7414. break;
  7415. }
  7416. if (!strcmp(name, "username")) {
  7417. ah->user = value;
  7418. } else if (!strcmp(name, "cnonce")) {
  7419. ah->cnonce = value;
  7420. } else if (!strcmp(name, "response")) {
  7421. ah->response = value;
  7422. } else if (!strcmp(name, "uri")) {
  7423. ah->uri = value;
  7424. } else if (!strcmp(name, "qop")) {
  7425. ah->qop = value;
  7426. } else if (!strcmp(name, "nc")) {
  7427. ah->nc = value;
  7428. } else if (!strcmp(name, "nonce")) {
  7429. ah->nonce = value;
  7430. }
  7431. }
  7432. #if !defined(NO_NONCE_CHECK)
  7433. /* Read the nonce from the response. */
  7434. if (ah->nonce == NULL) {
  7435. return 0;
  7436. }
  7437. s = NULL;
  7438. nonce = strtoull(ah->nonce, &s, 10);
  7439. if ((s == NULL) || (*s != 0)) {
  7440. return 0;
  7441. }
  7442. /* Convert the nonce from the client to a number. */
  7443. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7444. /* The converted number corresponds to the time the nounce has been
  7445. * created. This should not be earlier than the server start. */
  7446. /* Server side nonce check is valuable in all situations but one:
  7447. * if the server restarts frequently, but the client should not see
  7448. * that, so the server should accept nonces from previous starts. */
  7449. /* However, the reasonable default is to not accept a nonce from a
  7450. * previous start, so if anyone changed the access rights between
  7451. * two restarts, a new login is required. */
  7452. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7453. /* nonce is from a previous start of the server and no longer valid
  7454. * (replay attack?) */
  7455. return 0;
  7456. }
  7457. /* Check if the nonce is too high, so it has not (yet) been used by the
  7458. * server. */
  7459. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7460. + conn->dom_ctx->nonce_count)) {
  7461. return 0;
  7462. }
  7463. #else
  7464. (void)nonce;
  7465. #endif
  7466. /* CGI needs it as REMOTE_USER */
  7467. if (ah->user != NULL) {
  7468. conn->request_info.remote_user =
  7469. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7470. } else {
  7471. return 0;
  7472. }
  7473. return 1;
  7474. }
  7475. static const char *
  7476. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7477. {
  7478. #if defined(MG_USE_OPEN_FILE)
  7479. const char *eof;
  7480. size_t len;
  7481. const char *memend;
  7482. #else
  7483. (void)p; /* parameter is unused */
  7484. #endif
  7485. if (!filep) {
  7486. return NULL;
  7487. }
  7488. #if defined(MG_USE_OPEN_FILE)
  7489. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7490. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7491. /* Search for \n from p till the end of stream */
  7492. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7493. if (eof != NULL) {
  7494. eof += 1; /* Include \n */
  7495. } else {
  7496. eof = memend; /* Copy remaining data */
  7497. }
  7498. len =
  7499. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7500. memcpy(buf, *p, len);
  7501. buf[len] = '\0';
  7502. *p += len;
  7503. return len ? eof : NULL;
  7504. } else /* filep->access.fp block below */
  7505. #endif
  7506. if (filep->access.fp != NULL) {
  7507. return fgets(buf, (int)size, filep->access.fp);
  7508. } else {
  7509. return NULL;
  7510. }
  7511. }
  7512. /* Define the initial recursion depth for procesesing htpasswd files that
  7513. * include other htpasswd
  7514. * (or even the same) files. It is not difficult to provide a file or files
  7515. * s.t. they force civetweb
  7516. * to infinitely recurse and then crash.
  7517. */
  7518. #define INITIAL_DEPTH 9
  7519. #if INITIAL_DEPTH <= 0
  7520. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7521. #endif
  7522. #if !defined(NO_FILESYSTEMS)
  7523. struct read_auth_file_struct {
  7524. struct mg_connection *conn;
  7525. struct ah ah;
  7526. const char *domain;
  7527. char buf[256 + 256 + 40];
  7528. const char *f_user;
  7529. const char *f_domain;
  7530. const char *f_ha1;
  7531. };
  7532. static int
  7533. read_auth_file(struct mg_file *filep,
  7534. struct read_auth_file_struct *workdata,
  7535. int depth)
  7536. {
  7537. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7538. int is_authorized = 0;
  7539. struct mg_file fp;
  7540. size_t l;
  7541. if (!filep || !workdata || (0 == depth)) {
  7542. return 0;
  7543. }
  7544. /* Loop over passwords file */
  7545. #if defined(MG_USE_OPEN_FILE)
  7546. p = (char *)filep->access.membuf;
  7547. #endif
  7548. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7549. l = strlen(workdata->buf);
  7550. while (l > 0) {
  7551. if (isspace((unsigned char)workdata->buf[l - 1])
  7552. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7553. l--;
  7554. workdata->buf[l] = 0;
  7555. } else
  7556. break;
  7557. }
  7558. if (l < 1) {
  7559. continue;
  7560. }
  7561. workdata->f_user = workdata->buf;
  7562. if (workdata->f_user[0] == ':') {
  7563. /* user names may not contain a ':' and may not be empty,
  7564. * so lines starting with ':' may be used for a special purpose
  7565. */
  7566. if (workdata->f_user[1] == '#') {
  7567. /* :# is a comment */
  7568. continue;
  7569. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7570. if (mg_fopen(workdata->conn,
  7571. workdata->f_user + 9,
  7572. MG_FOPEN_MODE_READ,
  7573. &fp)) {
  7574. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7575. (void)mg_fclose(
  7576. &fp.access); /* ignore error on read only file */
  7577. /* No need to continue processing files once we have a
  7578. * match, since nothing will reset it back
  7579. * to 0.
  7580. */
  7581. if (is_authorized) {
  7582. return is_authorized;
  7583. }
  7584. } else {
  7585. mg_cry_internal(workdata->conn,
  7586. "%s: cannot open authorization file: %s",
  7587. __func__,
  7588. workdata->buf);
  7589. }
  7590. continue;
  7591. }
  7592. /* everything is invalid for the moment (might change in the
  7593. * future) */
  7594. mg_cry_internal(workdata->conn,
  7595. "%s: syntax error in authorization file: %s",
  7596. __func__,
  7597. workdata->buf);
  7598. continue;
  7599. }
  7600. workdata->f_domain = strchr(workdata->f_user, ':');
  7601. if (workdata->f_domain == NULL) {
  7602. mg_cry_internal(workdata->conn,
  7603. "%s: syntax error in authorization file: %s",
  7604. __func__,
  7605. workdata->buf);
  7606. continue;
  7607. }
  7608. *(char *)(workdata->f_domain) = 0;
  7609. (workdata->f_domain)++;
  7610. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7611. if (workdata->f_ha1 == NULL) {
  7612. mg_cry_internal(workdata->conn,
  7613. "%s: syntax error in authorization file: %s",
  7614. __func__,
  7615. workdata->buf);
  7616. continue;
  7617. }
  7618. *(char *)(workdata->f_ha1) = 0;
  7619. (workdata->f_ha1)++;
  7620. if (!strcmp(workdata->ah.user, workdata->f_user)
  7621. && !strcmp(workdata->domain, workdata->f_domain)) {
  7622. return check_password(workdata->conn->request_info.request_method,
  7623. workdata->f_ha1,
  7624. workdata->ah.uri,
  7625. workdata->ah.nonce,
  7626. workdata->ah.nc,
  7627. workdata->ah.cnonce,
  7628. workdata->ah.qop,
  7629. workdata->ah.response);
  7630. }
  7631. }
  7632. return is_authorized;
  7633. }
  7634. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7635. static int
  7636. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7637. {
  7638. struct read_auth_file_struct workdata;
  7639. char buf[MG_BUF_LEN];
  7640. if (!conn || !conn->dom_ctx) {
  7641. return 0;
  7642. }
  7643. memset(&workdata, 0, sizeof(workdata));
  7644. workdata.conn = conn;
  7645. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7646. return 0;
  7647. }
  7648. if (realm) {
  7649. workdata.domain = realm;
  7650. } else {
  7651. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7652. }
  7653. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7654. }
  7655. /* Public function to check http digest authentication header */
  7656. int
  7657. mg_check_digest_access_authentication(struct mg_connection *conn,
  7658. const char *realm,
  7659. const char *filename)
  7660. {
  7661. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7662. int auth;
  7663. if (!conn || !filename) {
  7664. return -1;
  7665. }
  7666. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7667. return -2;
  7668. }
  7669. auth = authorize(conn, &file, realm);
  7670. mg_fclose(&file.access);
  7671. return auth;
  7672. }
  7673. #endif /* NO_FILESYSTEMS */
  7674. /* Return 1 if request is authorised, 0 otherwise. */
  7675. static int
  7676. check_authorization(struct mg_connection *conn, const char *path)
  7677. {
  7678. #if !defined(NO_FILESYSTEMS)
  7679. char fname[PATH_MAX];
  7680. struct vec uri_vec, filename_vec;
  7681. const char *list;
  7682. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7683. int authorized = 1, truncated;
  7684. if (!conn || !conn->dom_ctx) {
  7685. return 0;
  7686. }
  7687. list = conn->dom_ctx->config[PROTECT_URI];
  7688. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7689. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7690. mg_snprintf(conn,
  7691. &truncated,
  7692. fname,
  7693. sizeof(fname),
  7694. "%.*s",
  7695. (int)filename_vec.len,
  7696. filename_vec.ptr);
  7697. if (truncated
  7698. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7699. mg_cry_internal(conn,
  7700. "%s: cannot open %s: %s",
  7701. __func__,
  7702. fname,
  7703. strerror(errno));
  7704. }
  7705. break;
  7706. }
  7707. }
  7708. if (!is_file_opened(&file.access)) {
  7709. open_auth_file(conn, path, &file);
  7710. }
  7711. if (is_file_opened(&file.access)) {
  7712. authorized = authorize(conn, &file, NULL);
  7713. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7714. }
  7715. return authorized;
  7716. #else
  7717. (void)conn;
  7718. (void)path;
  7719. return 1;
  7720. #endif /* NO_FILESYSTEMS */
  7721. }
  7722. /* Internal function. Assumes conn is valid */
  7723. static void
  7724. send_authorization_request(struct mg_connection *conn, const char *realm)
  7725. {
  7726. char date[64];
  7727. time_t curtime = time(NULL);
  7728. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7729. if (!realm) {
  7730. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7731. }
  7732. mg_lock_context(conn->phys_ctx);
  7733. nonce += conn->dom_ctx->nonce_count;
  7734. ++conn->dom_ctx->nonce_count;
  7735. mg_unlock_context(conn->phys_ctx);
  7736. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7737. conn->status_code = 401;
  7738. conn->must_close = 1;
  7739. gmt_time_string(date, sizeof(date), &curtime);
  7740. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7741. send_no_cache_header(conn);
  7742. send_additional_header(conn);
  7743. mg_printf(conn,
  7744. "Date: %s\r\n"
  7745. "Connection: %s\r\n"
  7746. "Content-Length: 0\r\n"
  7747. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7748. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7749. date,
  7750. suggest_connection_header(conn),
  7751. realm,
  7752. nonce);
  7753. }
  7754. /* Interface function. Parameters are provided by the user, so do
  7755. * at least some basic checks.
  7756. */
  7757. int
  7758. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7759. const char *realm)
  7760. {
  7761. if (conn && conn->dom_ctx) {
  7762. send_authorization_request(conn, realm);
  7763. return 0;
  7764. }
  7765. return -1;
  7766. }
  7767. #if !defined(NO_FILES)
  7768. static int
  7769. is_authorized_for_put(struct mg_connection *conn)
  7770. {
  7771. if (conn) {
  7772. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7773. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7774. int ret = 0;
  7775. if (passfile != NULL
  7776. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7777. ret = authorize(conn, &file, NULL);
  7778. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7779. }
  7780. return ret;
  7781. }
  7782. return 0;
  7783. }
  7784. #endif
  7785. int
  7786. mg_modify_passwords_file(const char *fname,
  7787. const char *domain,
  7788. const char *user,
  7789. const char *pass)
  7790. {
  7791. int found, i;
  7792. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7793. FILE *fp, *fp2;
  7794. found = 0;
  7795. fp = fp2 = NULL;
  7796. /* Regard empty password as no password - remove user record. */
  7797. if ((pass != NULL) && (pass[0] == '\0')) {
  7798. pass = NULL;
  7799. }
  7800. /* Other arguments must not be empty */
  7801. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7802. return 0;
  7803. }
  7804. /* Using the given file format, user name and domain must not contain
  7805. * ':'
  7806. */
  7807. if (strchr(user, ':') != NULL) {
  7808. return 0;
  7809. }
  7810. if (strchr(domain, ':') != NULL) {
  7811. return 0;
  7812. }
  7813. /* Do not allow control characters like newline in user name and domain.
  7814. * Do not allow excessively long names either. */
  7815. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7816. if (iscntrl((unsigned char)user[i])) {
  7817. return 0;
  7818. }
  7819. }
  7820. if (user[i]) {
  7821. return 0;
  7822. }
  7823. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7824. if (iscntrl((unsigned char)domain[i])) {
  7825. return 0;
  7826. }
  7827. }
  7828. if (domain[i]) {
  7829. return 0;
  7830. }
  7831. /* The maximum length of the path to the password file is limited */
  7832. if ((strlen(fname) + 4) >= PATH_MAX) {
  7833. return 0;
  7834. }
  7835. /* Create a temporary file name. Length has been checked before. */
  7836. strcpy(tmp, fname);
  7837. strcat(tmp, ".tmp");
  7838. /* Create the file if does not exist */
  7839. /* Use of fopen here is OK, since fname is only ASCII */
  7840. if ((fp = fopen(fname, "a+")) != NULL) {
  7841. (void)fclose(fp);
  7842. }
  7843. /* Open the given file and temporary file */
  7844. if ((fp = fopen(fname, "r")) == NULL) {
  7845. return 0;
  7846. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7847. fclose(fp);
  7848. return 0;
  7849. }
  7850. /* Copy the stuff to temporary file */
  7851. while (fgets(line, sizeof(line), fp) != NULL) {
  7852. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7853. continue;
  7854. }
  7855. u[255] = 0;
  7856. d[255] = 0;
  7857. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7858. found++;
  7859. if (pass != NULL) {
  7860. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7861. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7862. }
  7863. } else {
  7864. fprintf(fp2, "%s", line);
  7865. }
  7866. }
  7867. /* If new user, just add it */
  7868. if (!found && (pass != NULL)) {
  7869. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7870. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7871. }
  7872. /* Close files */
  7873. fclose(fp);
  7874. fclose(fp2);
  7875. /* Put the temp file in place of real file */
  7876. IGNORE_UNUSED_RESULT(remove(fname));
  7877. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7878. return 1;
  7879. }
  7880. static int
  7881. is_valid_port(unsigned long port)
  7882. {
  7883. return (port <= 0xffff);
  7884. }
  7885. static int
  7886. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7887. {
  7888. struct addrinfo hints, *res, *ressave;
  7889. int func_ret = 0;
  7890. int gai_ret;
  7891. memset(&hints, 0, sizeof(struct addrinfo));
  7892. hints.ai_family = af;
  7893. if (!resolve_src) {
  7894. hints.ai_flags = AI_NUMERICHOST;
  7895. }
  7896. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7897. if (gai_ret != 0) {
  7898. /* gai_strerror could be used to convert gai_ret to a string */
  7899. /* POSIX return values: see
  7900. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7901. */
  7902. /* Windows return values: see
  7903. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7904. */
  7905. return 0;
  7906. }
  7907. ressave = res;
  7908. while (res) {
  7909. if ((dstlen >= (size_t)res->ai_addrlen)
  7910. && (res->ai_addr->sa_family == af)) {
  7911. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7912. func_ret = 1;
  7913. }
  7914. res = res->ai_next;
  7915. }
  7916. freeaddrinfo(ressave);
  7917. return func_ret;
  7918. }
  7919. static int
  7920. connect_socket(struct mg_context *ctx /* may be NULL */,
  7921. const char *host,
  7922. int port,
  7923. int use_ssl,
  7924. char *ebuf,
  7925. size_t ebuf_len,
  7926. SOCKET *sock /* output: socket, must not be NULL */,
  7927. union usa *sa /* output: socket address, must not be NULL */
  7928. )
  7929. {
  7930. int ip_ver = 0;
  7931. int conn_ret = -1;
  7932. int sockerr = 0;
  7933. *sock = INVALID_SOCKET;
  7934. memset(sa, 0, sizeof(*sa));
  7935. if (ebuf_len > 0) {
  7936. *ebuf = 0;
  7937. }
  7938. if (host == NULL) {
  7939. mg_snprintf(NULL,
  7940. NULL, /* No truncation check for ebuf */
  7941. ebuf,
  7942. ebuf_len,
  7943. "%s",
  7944. "NULL host");
  7945. return 0;
  7946. }
  7947. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7948. mg_snprintf(NULL,
  7949. NULL, /* No truncation check for ebuf */
  7950. ebuf,
  7951. ebuf_len,
  7952. "%s",
  7953. "invalid port");
  7954. return 0;
  7955. }
  7956. #if !defined(NO_SSL)
  7957. #if !defined(NO_SSL_DL)
  7958. #if defined(OPENSSL_API_1_1)
  7959. if (use_ssl && (TLS_client_method == NULL)) {
  7960. mg_snprintf(NULL,
  7961. NULL, /* No truncation check for ebuf */
  7962. ebuf,
  7963. ebuf_len,
  7964. "%s",
  7965. "SSL is not initialized");
  7966. return 0;
  7967. }
  7968. #else
  7969. if (use_ssl && (SSLv23_client_method == NULL)) {
  7970. mg_snprintf(NULL,
  7971. NULL, /* No truncation check for ebuf */
  7972. ebuf,
  7973. ebuf_len,
  7974. "%s",
  7975. "SSL is not initialized");
  7976. return 0;
  7977. }
  7978. #endif /* OPENSSL_API_1_1 */
  7979. #else
  7980. (void)use_ssl;
  7981. #endif /* NO_SSL_DL */
  7982. #else
  7983. (void)use_ssl;
  7984. #endif /* !defined(NO_SSL) */
  7985. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7986. sa->sin.sin_port = htons((uint16_t)port);
  7987. ip_ver = 4;
  7988. #if defined(USE_IPV6)
  7989. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7990. sa->sin6.sin6_port = htons((uint16_t)port);
  7991. ip_ver = 6;
  7992. } else if (host[0] == '[') {
  7993. /* While getaddrinfo on Windows will work with [::1],
  7994. * getaddrinfo on Linux only works with ::1 (without []). */
  7995. size_t l = strlen(host + 1);
  7996. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7997. if (h) {
  7998. h[l - 1] = 0;
  7999. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8000. sa->sin6.sin6_port = htons((uint16_t)port);
  8001. ip_ver = 6;
  8002. }
  8003. mg_free(h);
  8004. }
  8005. #endif
  8006. }
  8007. if (ip_ver == 0) {
  8008. mg_snprintf(NULL,
  8009. NULL, /* No truncation check for ebuf */
  8010. ebuf,
  8011. ebuf_len,
  8012. "%s",
  8013. "host not found");
  8014. return 0;
  8015. }
  8016. if (ip_ver == 4) {
  8017. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8018. }
  8019. #if defined(USE_IPV6)
  8020. else if (ip_ver == 6) {
  8021. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8022. }
  8023. #endif
  8024. if (*sock == INVALID_SOCKET) {
  8025. mg_snprintf(NULL,
  8026. NULL, /* No truncation check for ebuf */
  8027. ebuf,
  8028. ebuf_len,
  8029. "socket(): %s",
  8030. strerror(ERRNO));
  8031. return 0;
  8032. }
  8033. if (0 != set_non_blocking_mode(*sock)) {
  8034. mg_snprintf(NULL,
  8035. NULL, /* No truncation check for ebuf */
  8036. ebuf,
  8037. ebuf_len,
  8038. "Cannot set socket to non-blocking: %s",
  8039. strerror(ERRNO));
  8040. closesocket(*sock);
  8041. *sock = INVALID_SOCKET;
  8042. return 0;
  8043. }
  8044. set_close_on_exec(*sock, NULL, ctx);
  8045. if (ip_ver == 4) {
  8046. /* connected with IPv4 */
  8047. conn_ret = connect(*sock,
  8048. (struct sockaddr *)((void *)&sa->sin),
  8049. sizeof(sa->sin));
  8050. }
  8051. #if defined(USE_IPV6)
  8052. else if (ip_ver == 6) {
  8053. /* connected with IPv6 */
  8054. conn_ret = connect(*sock,
  8055. (struct sockaddr *)((void *)&sa->sin6),
  8056. sizeof(sa->sin6));
  8057. }
  8058. #endif
  8059. if (conn_ret != 0) {
  8060. sockerr = ERRNO;
  8061. }
  8062. #if defined(_WIN32)
  8063. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8064. #else
  8065. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8066. #endif
  8067. /* Data for getsockopt */
  8068. void *psockerr = &sockerr;
  8069. int ret;
  8070. #if defined(_WIN32)
  8071. int len = (int)sizeof(sockerr);
  8072. #else
  8073. socklen_t len = (socklen_t)sizeof(sockerr);
  8074. #endif
  8075. /* Data for poll */
  8076. struct mg_pollfd pfd[1];
  8077. int pollres;
  8078. int ms_wait = 10000; /* 10 second timeout */
  8079. stop_flag_t nonstop;
  8080. STOP_FLAG_ASSIGN(&nonstop, 0);
  8081. /* For a non-blocking socket, the connect sequence is:
  8082. * 1) call connect (will not block)
  8083. * 2) wait until the socket is ready for writing (select or poll)
  8084. * 3) check connection state with getsockopt
  8085. */
  8086. pfd[0].fd = *sock;
  8087. pfd[0].events = POLLOUT;
  8088. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8089. if (pollres != 1) {
  8090. /* Not connected */
  8091. mg_snprintf(NULL,
  8092. NULL, /* No truncation check for ebuf */
  8093. ebuf,
  8094. ebuf_len,
  8095. "connect(%s:%d): timeout",
  8096. host,
  8097. port);
  8098. closesocket(*sock);
  8099. *sock = INVALID_SOCKET;
  8100. return 0;
  8101. }
  8102. #if defined(_WIN32)
  8103. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8104. #else
  8105. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8106. #endif
  8107. if ((ret == 0) && (sockerr == 0)) {
  8108. conn_ret = 0;
  8109. }
  8110. }
  8111. if (conn_ret != 0) {
  8112. /* Not connected */
  8113. mg_snprintf(NULL,
  8114. NULL, /* No truncation check for ebuf */
  8115. ebuf,
  8116. ebuf_len,
  8117. "connect(%s:%d): error %s",
  8118. host,
  8119. port,
  8120. strerror(sockerr));
  8121. closesocket(*sock);
  8122. *sock = INVALID_SOCKET;
  8123. return 0;
  8124. }
  8125. return 1;
  8126. }
  8127. int
  8128. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8129. {
  8130. static const char *dont_escape = "._-$,;~()";
  8131. static const char *hex = "0123456789abcdef";
  8132. char *pos = dst;
  8133. const char *end = dst + dst_len - 1;
  8134. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8135. if (isalnum((unsigned char)*src)
  8136. || (strchr(dont_escape, *src) != NULL)) {
  8137. *pos = *src;
  8138. } else if (pos + 2 < end) {
  8139. pos[0] = '%';
  8140. pos[1] = hex[(unsigned char)*src >> 4];
  8141. pos[2] = hex[(unsigned char)*src & 0xf];
  8142. pos += 2;
  8143. } else {
  8144. break;
  8145. }
  8146. }
  8147. *pos = '\0';
  8148. return (*src == '\0') ? (int)(pos - dst) : -1;
  8149. }
  8150. /* Return 0 on success, non-zero if an error occurs. */
  8151. static int
  8152. print_dir_entry(struct de *de)
  8153. {
  8154. size_t namesize, escsize, i;
  8155. char *href, *esc, *p;
  8156. char size[64], mod[64];
  8157. #if defined(REENTRANT_TIME)
  8158. struct tm _tm;
  8159. struct tm *tm = &_tm;
  8160. #else
  8161. struct tm *tm;
  8162. #endif
  8163. /* Estimate worst case size for encoding and escaping */
  8164. namesize = strlen(de->file_name) + 1;
  8165. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8166. href = (char *)mg_malloc(namesize * 3 + escsize);
  8167. if (href == NULL) {
  8168. return -1;
  8169. }
  8170. mg_url_encode(de->file_name, href, namesize * 3);
  8171. esc = NULL;
  8172. if (escsize > 0) {
  8173. /* HTML escaping needed */
  8174. esc = href + namesize * 3;
  8175. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8176. mg_strlcpy(p, de->file_name + i, 2);
  8177. if (*p == '&') {
  8178. strcpy(p, "&amp;");
  8179. } else if (*p == '<') {
  8180. strcpy(p, "&lt;");
  8181. } else if (*p == '>') {
  8182. strcpy(p, "&gt;");
  8183. }
  8184. }
  8185. }
  8186. if (de->file.is_directory) {
  8187. mg_snprintf(de->conn,
  8188. NULL, /* Buffer is big enough */
  8189. size,
  8190. sizeof(size),
  8191. "%s",
  8192. "[DIRECTORY]");
  8193. } else {
  8194. /* We use (signed) cast below because MSVC 6 compiler cannot
  8195. * convert unsigned __int64 to double. Sigh. */
  8196. if (de->file.size < 1024) {
  8197. mg_snprintf(de->conn,
  8198. NULL, /* Buffer is big enough */
  8199. size,
  8200. sizeof(size),
  8201. "%d",
  8202. (int)de->file.size);
  8203. } else if (de->file.size < 0x100000) {
  8204. mg_snprintf(de->conn,
  8205. NULL, /* Buffer is big enough */
  8206. size,
  8207. sizeof(size),
  8208. "%.1fk",
  8209. (double)de->file.size / 1024.0);
  8210. } else if (de->file.size < 0x40000000) {
  8211. mg_snprintf(de->conn,
  8212. NULL, /* Buffer is big enough */
  8213. size,
  8214. sizeof(size),
  8215. "%.1fM",
  8216. (double)de->file.size / 1048576);
  8217. } else {
  8218. mg_snprintf(de->conn,
  8219. NULL, /* Buffer is big enough */
  8220. size,
  8221. sizeof(size),
  8222. "%.1fG",
  8223. (double)de->file.size / 1073741824);
  8224. }
  8225. }
  8226. /* Note: mg_snprintf will not cause a buffer overflow above.
  8227. * So, string truncation checks are not required here. */
  8228. #if defined(REENTRANT_TIME)
  8229. localtime_r(&de->file.last_modified, tm);
  8230. #else
  8231. tm = localtime(&de->file.last_modified);
  8232. #endif
  8233. if (tm != NULL) {
  8234. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8235. } else {
  8236. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8237. mod[sizeof(mod) - 1] = '\0';
  8238. }
  8239. mg_printf(de->conn,
  8240. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8241. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8242. href,
  8243. de->file.is_directory ? "/" : "",
  8244. esc ? esc : de->file_name,
  8245. de->file.is_directory ? "/" : "",
  8246. mod,
  8247. size);
  8248. mg_free(href);
  8249. return 0;
  8250. }
  8251. /* This function is called from send_directory() and used for
  8252. * sorting directory entries by size, or name, or modification time.
  8253. * On windows, __cdecl specification is needed in case if project is built
  8254. * with __stdcall convention. qsort always requires __cdels callback. */
  8255. static int WINCDECL
  8256. compare_dir_entries(const void *p1, const void *p2)
  8257. {
  8258. if (p1 && p2) {
  8259. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8260. const char *query_string = a->conn->request_info.query_string;
  8261. int cmp_result = 0;
  8262. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8263. query_string = "n";
  8264. }
  8265. if (a->file.is_directory && !b->file.is_directory) {
  8266. return -1; /* Always put directories on top */
  8267. } else if (!a->file.is_directory && b->file.is_directory) {
  8268. return 1; /* Always put directories on top */
  8269. } else if (*query_string == 'n') {
  8270. cmp_result = strcmp(a->file_name, b->file_name);
  8271. } else if (*query_string == 's') {
  8272. cmp_result = (a->file.size == b->file.size)
  8273. ? 0
  8274. : ((a->file.size > b->file.size) ? 1 : -1);
  8275. } else if (*query_string == 'd') {
  8276. cmp_result =
  8277. (a->file.last_modified == b->file.last_modified)
  8278. ? 0
  8279. : ((a->file.last_modified > b->file.last_modified) ? 1
  8280. : -1);
  8281. }
  8282. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8283. }
  8284. return 0;
  8285. }
  8286. static int
  8287. must_hide_file(struct mg_connection *conn, const char *path)
  8288. {
  8289. if (conn && conn->dom_ctx) {
  8290. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8291. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8292. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8293. || ((pattern != NULL)
  8294. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8295. }
  8296. return 0;
  8297. }
  8298. #if !defined(NO_FILESYSTEMS)
  8299. static int
  8300. scan_directory(struct mg_connection *conn,
  8301. const char *dir,
  8302. void *data,
  8303. int (*cb)(struct de *, void *))
  8304. {
  8305. char path[PATH_MAX];
  8306. struct dirent *dp;
  8307. DIR *dirp;
  8308. struct de de;
  8309. int truncated;
  8310. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8311. return 0;
  8312. } else {
  8313. de.conn = conn;
  8314. while ((dp = mg_readdir(dirp)) != NULL) {
  8315. /* Do not show current dir and hidden files */
  8316. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8317. || must_hide_file(conn, dp->d_name)) {
  8318. continue;
  8319. }
  8320. mg_snprintf(
  8321. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8322. /* If we don't memset stat structure to zero, mtime will have
  8323. * garbage and strftime() will segfault later on in
  8324. * print_dir_entry(). memset is required only if mg_stat()
  8325. * fails. For more details, see
  8326. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8327. memset(&de.file, 0, sizeof(de.file));
  8328. if (truncated) {
  8329. /* If the path is not complete, skip processing. */
  8330. continue;
  8331. }
  8332. if (!mg_stat(conn, path, &de.file)) {
  8333. mg_cry_internal(conn,
  8334. "%s: mg_stat(%s) failed: %s",
  8335. __func__,
  8336. path,
  8337. strerror(ERRNO));
  8338. }
  8339. de.file_name = dp->d_name;
  8340. cb(&de, data);
  8341. }
  8342. (void)mg_closedir(dirp);
  8343. }
  8344. return 1;
  8345. }
  8346. #endif /* NO_FILESYSTEMS */
  8347. #if !defined(NO_FILES)
  8348. static int
  8349. remove_directory(struct mg_connection *conn, const char *dir)
  8350. {
  8351. char path[PATH_MAX];
  8352. struct dirent *dp;
  8353. DIR *dirp;
  8354. struct de de;
  8355. int truncated;
  8356. int ok = 1;
  8357. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8358. return 0;
  8359. } else {
  8360. de.conn = conn;
  8361. while ((dp = mg_readdir(dirp)) != NULL) {
  8362. /* Do not show current dir (but show hidden files as they will
  8363. * also be removed) */
  8364. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8365. continue;
  8366. }
  8367. mg_snprintf(
  8368. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8369. /* If we don't memset stat structure to zero, mtime will have
  8370. * garbage and strftime() will segfault later on in
  8371. * print_dir_entry(). memset is required only if mg_stat()
  8372. * fails. For more details, see
  8373. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8374. memset(&de.file, 0, sizeof(de.file));
  8375. if (truncated) {
  8376. /* Do not delete anything shorter */
  8377. ok = 0;
  8378. continue;
  8379. }
  8380. if (!mg_stat(conn, path, &de.file)) {
  8381. mg_cry_internal(conn,
  8382. "%s: mg_stat(%s) failed: %s",
  8383. __func__,
  8384. path,
  8385. strerror(ERRNO));
  8386. ok = 0;
  8387. }
  8388. if (de.file.is_directory) {
  8389. if (remove_directory(conn, path) == 0) {
  8390. ok = 0;
  8391. }
  8392. } else {
  8393. /* This will fail file is the file is in memory */
  8394. if (mg_remove(conn, path) == 0) {
  8395. ok = 0;
  8396. }
  8397. }
  8398. }
  8399. (void)mg_closedir(dirp);
  8400. IGNORE_UNUSED_RESULT(rmdir(dir));
  8401. }
  8402. return ok;
  8403. }
  8404. #endif
  8405. struct dir_scan_data {
  8406. struct de *entries;
  8407. unsigned int num_entries;
  8408. unsigned int arr_size;
  8409. };
  8410. /* Behaves like realloc(), but frees original pointer on failure */
  8411. static void *
  8412. realloc2(void *ptr, size_t size)
  8413. {
  8414. void *new_ptr = mg_realloc(ptr, size);
  8415. if ((new_ptr == NULL) && (size > 0)) {
  8416. mg_free(ptr);
  8417. }
  8418. return new_ptr;
  8419. }
  8420. #if !defined(NO_FILESYSTEMS)
  8421. static int
  8422. dir_scan_callback(struct de *de, void *data)
  8423. {
  8424. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8425. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8426. dsd->arr_size *= 2;
  8427. dsd->entries =
  8428. (struct de *)realloc2(dsd->entries,
  8429. dsd->arr_size * sizeof(dsd->entries[0]));
  8430. }
  8431. if (dsd->entries == NULL) {
  8432. /* TODO(lsm, low): propagate an error to the caller */
  8433. dsd->num_entries = 0;
  8434. } else {
  8435. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8436. dsd->entries[dsd->num_entries].file = de->file;
  8437. dsd->entries[dsd->num_entries].conn = de->conn;
  8438. dsd->num_entries++;
  8439. }
  8440. return 0;
  8441. }
  8442. static void
  8443. handle_directory_request(struct mg_connection *conn, const char *dir)
  8444. {
  8445. unsigned int i;
  8446. int sort_direction;
  8447. struct dir_scan_data data = {NULL, 0, 128};
  8448. char date[64], *esc, *p;
  8449. const char *title;
  8450. time_t curtime = time(NULL);
  8451. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8452. mg_send_http_error(conn,
  8453. 500,
  8454. "Error: Cannot open directory\nopendir(%s): %s",
  8455. dir,
  8456. strerror(ERRNO));
  8457. return;
  8458. }
  8459. gmt_time_string(date, sizeof(date), &curtime);
  8460. if (!conn) {
  8461. return;
  8462. }
  8463. esc = NULL;
  8464. title = conn->request_info.local_uri;
  8465. if (title[strcspn(title, "&<>")]) {
  8466. /* HTML escaping needed */
  8467. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8468. if (esc) {
  8469. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8470. mg_strlcpy(p, title + i, 2);
  8471. if (*p == '&') {
  8472. strcpy(p, "&amp;");
  8473. } else if (*p == '<') {
  8474. strcpy(p, "&lt;");
  8475. } else if (*p == '>') {
  8476. strcpy(p, "&gt;");
  8477. }
  8478. }
  8479. } else {
  8480. title = "";
  8481. }
  8482. }
  8483. sort_direction = ((conn->request_info.query_string != NULL)
  8484. && (conn->request_info.query_string[0] != '\0')
  8485. && (conn->request_info.query_string[1] == 'd'))
  8486. ? 'a'
  8487. : 'd';
  8488. conn->must_close = 1;
  8489. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8490. send_static_cache_header(conn);
  8491. send_additional_header(conn);
  8492. mg_printf(conn,
  8493. "Date: %s\r\n"
  8494. "Connection: close\r\n"
  8495. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8496. date);
  8497. mg_printf(conn,
  8498. "<html><head><title>Index of %s</title>"
  8499. "<style>th {text-align: left;}</style></head>"
  8500. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8501. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8502. "<th><a href=\"?d%c\">Modified</a></th>"
  8503. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8504. "<tr><td colspan=\"3\"><hr></td></tr>",
  8505. esc ? esc : title,
  8506. esc ? esc : title,
  8507. sort_direction,
  8508. sort_direction,
  8509. sort_direction);
  8510. mg_free(esc);
  8511. /* Print first entry - link to a parent directory */
  8512. mg_printf(conn,
  8513. "<tr><td><a href=\"%s\">%s</a></td>"
  8514. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8515. "..",
  8516. "Parent directory",
  8517. "-",
  8518. "-");
  8519. /* Sort and print directory entries */
  8520. if (data.entries != NULL) {
  8521. qsort(data.entries,
  8522. (size_t)data.num_entries,
  8523. sizeof(data.entries[0]),
  8524. compare_dir_entries);
  8525. for (i = 0; i < data.num_entries; i++) {
  8526. print_dir_entry(&data.entries[i]);
  8527. mg_free(data.entries[i].file_name);
  8528. }
  8529. mg_free(data.entries);
  8530. }
  8531. mg_printf(conn, "%s", "</table></pre></body></html>");
  8532. conn->status_code = 200;
  8533. }
  8534. #endif /* NO_FILESYSTEMS */
  8535. /* Send len bytes from the opened file to the client. */
  8536. static void
  8537. send_file_data(struct mg_connection *conn,
  8538. struct mg_file *filep,
  8539. int64_t offset,
  8540. int64_t len)
  8541. {
  8542. char buf[MG_BUF_LEN];
  8543. int to_read, num_read, num_written;
  8544. int64_t size;
  8545. if (!filep || !conn) {
  8546. return;
  8547. }
  8548. /* Sanity check the offset */
  8549. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8550. : (int64_t)(filep->stat.size);
  8551. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8552. #if defined(MG_USE_OPEN_FILE)
  8553. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8554. /* file stored in memory */
  8555. if (len > size - offset) {
  8556. len = size - offset;
  8557. }
  8558. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8559. } else /* else block below */
  8560. #endif
  8561. if (len > 0 && filep->access.fp != NULL) {
  8562. /* file stored on disk */
  8563. #if defined(__linux__)
  8564. /* sendfile is only available for Linux */
  8565. if ((conn->ssl == 0) && (conn->throttle == 0)
  8566. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8567. "yes"))) {
  8568. off_t sf_offs = (off_t)offset;
  8569. ssize_t sf_sent;
  8570. int sf_file = fileno(filep->access.fp);
  8571. int loop_cnt = 0;
  8572. do {
  8573. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8574. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8575. size_t sf_tosend =
  8576. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8577. sf_sent =
  8578. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8579. if (sf_sent > 0) {
  8580. len -= sf_sent;
  8581. offset += sf_sent;
  8582. } else if (loop_cnt == 0) {
  8583. /* This file can not be sent using sendfile.
  8584. * This might be the case for pseudo-files in the
  8585. * /sys/ and /proc/ file system.
  8586. * Use the regular user mode copy code instead. */
  8587. break;
  8588. } else if (sf_sent == 0) {
  8589. /* No error, but 0 bytes sent. May be EOF? */
  8590. return;
  8591. }
  8592. loop_cnt++;
  8593. } while ((len > 0) && (sf_sent >= 0));
  8594. if (sf_sent > 0) {
  8595. return; /* OK */
  8596. }
  8597. /* sf_sent<0 means error, thus fall back to the classic way */
  8598. /* This is always the case, if sf_file is not a "normal" file,
  8599. * e.g., for sending data from the output of a CGI process. */
  8600. offset = (int64_t)sf_offs;
  8601. }
  8602. #endif
  8603. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8604. mg_cry_internal(conn,
  8605. "%s: fseeko() failed: %s",
  8606. __func__,
  8607. strerror(ERRNO));
  8608. mg_send_http_error(
  8609. conn,
  8610. 500,
  8611. "%s",
  8612. "Error: Unable to access file at requested position.");
  8613. } else {
  8614. while (len > 0) {
  8615. /* Calculate how much to read from the file in the buffer */
  8616. to_read = sizeof(buf);
  8617. if ((int64_t)to_read > len) {
  8618. to_read = (int)len;
  8619. }
  8620. /* Read from file, exit the loop on error */
  8621. if ((num_read =
  8622. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8623. <= 0) {
  8624. break;
  8625. }
  8626. /* Send read bytes to the client, exit the loop on error */
  8627. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8628. != num_read) {
  8629. break;
  8630. }
  8631. /* Both read and were successful, adjust counters */
  8632. len -= num_written;
  8633. }
  8634. }
  8635. }
  8636. }
  8637. static int
  8638. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8639. {
  8640. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8641. }
  8642. static void
  8643. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8644. {
  8645. if ((filestat != NULL) && (buf != NULL)) {
  8646. mg_snprintf(NULL,
  8647. NULL, /* All calls to construct_etag use 64 byte buffer */
  8648. buf,
  8649. buf_len,
  8650. "\"%lx.%" INT64_FMT "\"",
  8651. (unsigned long)filestat->last_modified,
  8652. filestat->size);
  8653. }
  8654. }
  8655. static void
  8656. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8657. {
  8658. if (filep != NULL && filep->fp != NULL) {
  8659. #if defined(_WIN32)
  8660. (void)conn; /* Unused. */
  8661. #else
  8662. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8663. mg_cry_internal(conn,
  8664. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8665. __func__,
  8666. strerror(ERRNO));
  8667. }
  8668. #endif
  8669. }
  8670. }
  8671. #if defined(USE_ZLIB)
  8672. #include "mod_zlib.inl"
  8673. #endif
  8674. #if !defined(NO_FILESYSTEMS)
  8675. static void
  8676. handle_static_file_request(struct mg_connection *conn,
  8677. const char *path,
  8678. struct mg_file *filep,
  8679. const char *mime_type,
  8680. const char *additional_headers)
  8681. {
  8682. char date[64], lm[64], etag[64];
  8683. char range[128]; /* large enough, so there will be no overflow */
  8684. const char *msg = "OK";
  8685. const char *range_hdr;
  8686. time_t curtime = time(NULL);
  8687. int64_t cl, r1, r2;
  8688. struct vec mime_vec;
  8689. int n, truncated;
  8690. char gz_path[PATH_MAX];
  8691. const char *encoding = "";
  8692. const char *origin_hdr;
  8693. const char *cors_orig_cfg;
  8694. const char *cors1, *cors2, *cors3;
  8695. int is_head_request;
  8696. #if defined(USE_ZLIB)
  8697. /* Compression is allowed, unless there is a reason not to use
  8698. * compression. If the file is already compressed, too small or a
  8699. * "range" request was made, on the fly compression is not possible. */
  8700. int allow_on_the_fly_compression = 1;
  8701. #endif
  8702. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8703. return;
  8704. }
  8705. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8706. if (mime_type == NULL) {
  8707. get_mime_type(conn, path, &mime_vec);
  8708. } else {
  8709. mime_vec.ptr = mime_type;
  8710. mime_vec.len = strlen(mime_type);
  8711. }
  8712. if (filep->stat.size > INT64_MAX) {
  8713. mg_send_http_error(conn,
  8714. 500,
  8715. "Error: File size is too large to send\n%" INT64_FMT,
  8716. filep->stat.size);
  8717. return;
  8718. }
  8719. cl = (int64_t)filep->stat.size;
  8720. conn->status_code = 200;
  8721. range[0] = '\0';
  8722. #if defined(USE_ZLIB)
  8723. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8724. * it's important to rewrite the filename after resolving
  8725. * the mime type from it, to preserve the actual file's type */
  8726. if (!conn->accept_gzip) {
  8727. allow_on_the_fly_compression = 0;
  8728. }
  8729. #endif
  8730. /* Check if there is a range header */
  8731. range_hdr = mg_get_header(conn, "Range");
  8732. /* For gzipped files, add *.gz */
  8733. if (filep->stat.is_gzipped) {
  8734. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8735. if (truncated) {
  8736. mg_send_http_error(conn,
  8737. 500,
  8738. "Error: Path of zipped file too long (%s)",
  8739. path);
  8740. return;
  8741. }
  8742. path = gz_path;
  8743. encoding = "Content-Encoding: gzip\r\n";
  8744. #if defined(USE_ZLIB)
  8745. /* File is already compressed. No "on the fly" compression. */
  8746. allow_on_the_fly_compression = 0;
  8747. #endif
  8748. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8749. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8750. struct mg_file_stat file_stat;
  8751. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8752. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8753. && !file_stat.is_directory) {
  8754. file_stat.is_gzipped = 1;
  8755. filep->stat = file_stat;
  8756. cl = (int64_t)filep->stat.size;
  8757. path = gz_path;
  8758. encoding = "Content-Encoding: gzip\r\n";
  8759. #if defined(USE_ZLIB)
  8760. /* File is already compressed. No "on the fly" compression. */
  8761. allow_on_the_fly_compression = 0;
  8762. #endif
  8763. }
  8764. }
  8765. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8766. mg_send_http_error(conn,
  8767. 500,
  8768. "Error: Cannot open file\nfopen(%s): %s",
  8769. path,
  8770. strerror(ERRNO));
  8771. return;
  8772. }
  8773. fclose_on_exec(&filep->access, conn);
  8774. /* If "Range" request was made: parse header, send only selected part
  8775. * of the file. */
  8776. r1 = r2 = 0;
  8777. if ((range_hdr != NULL)
  8778. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8779. && (r2 >= 0)) {
  8780. /* actually, range requests don't play well with a pre-gzipped
  8781. * file (since the range is specified in the uncompressed space) */
  8782. if (filep->stat.is_gzipped) {
  8783. mg_send_http_error(
  8784. conn,
  8785. 416, /* 416 = Range Not Satisfiable */
  8786. "%s",
  8787. "Error: Range requests in gzipped files are not supported");
  8788. (void)mg_fclose(
  8789. &filep->access); /* ignore error on read only file */
  8790. return;
  8791. }
  8792. conn->status_code = 206;
  8793. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8794. mg_snprintf(conn,
  8795. NULL, /* range buffer is big enough */
  8796. range,
  8797. sizeof(range),
  8798. "Content-Range: bytes "
  8799. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8800. r1,
  8801. r1 + cl - 1,
  8802. filep->stat.size);
  8803. msg = "Partial Content";
  8804. #if defined(USE_ZLIB)
  8805. /* Do not compress ranges. */
  8806. allow_on_the_fly_compression = 0;
  8807. #endif
  8808. }
  8809. /* Do not compress small files. Small files do not benefit from file
  8810. * compression, but there is still some overhead. */
  8811. #if defined(USE_ZLIB)
  8812. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8813. /* File is below the size limit. */
  8814. allow_on_the_fly_compression = 0;
  8815. }
  8816. #endif
  8817. /* Standard CORS header */
  8818. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8819. origin_hdr = mg_get_header(conn, "Origin");
  8820. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8821. /* Cross-origin resource sharing (CORS), see
  8822. * http://www.html5rocks.com/en/tutorials/cors/,
  8823. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8824. * -
  8825. * preflight is not supported for files. */
  8826. cors1 = "Access-Control-Allow-Origin: ";
  8827. cors2 = cors_orig_cfg;
  8828. cors3 = "\r\n";
  8829. } else {
  8830. cors1 = cors2 = cors3 = "";
  8831. }
  8832. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8833. * according to
  8834. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8835. gmt_time_string(date, sizeof(date), &curtime);
  8836. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8837. construct_etag(etag, sizeof(etag), &filep->stat);
  8838. /* Send header */
  8839. (void)mg_printf(conn,
  8840. "HTTP/1.1 %d %s\r\n"
  8841. "%s%s%s" /* CORS */
  8842. "Date: %s\r\n"
  8843. "Last-Modified: %s\r\n"
  8844. "Etag: %s\r\n"
  8845. "Content-Type: %.*s\r\n"
  8846. "Connection: %s\r\n",
  8847. conn->status_code,
  8848. msg,
  8849. cors1,
  8850. cors2,
  8851. cors3,
  8852. date,
  8853. lm,
  8854. etag,
  8855. (int)mime_vec.len,
  8856. mime_vec.ptr,
  8857. suggest_connection_header(conn));
  8858. send_static_cache_header(conn);
  8859. send_additional_header(conn);
  8860. #if defined(USE_ZLIB)
  8861. /* On the fly compression allowed */
  8862. if (allow_on_the_fly_compression) {
  8863. /* For on the fly compression, we don't know the content size in
  8864. * advance, so we have to use chunked encoding */
  8865. (void)mg_printf(conn,
  8866. "Content-Encoding: gzip\r\n"
  8867. "Transfer-Encoding: chunked\r\n");
  8868. } else
  8869. #endif
  8870. {
  8871. /* Without on-the-fly compression, we know the content-length
  8872. * and we can use ranges (with on-the-fly compression we cannot).
  8873. * So we send these response headers only in this case. */
  8874. (void)mg_printf(conn,
  8875. "Content-Length: %" INT64_FMT "\r\n"
  8876. "Accept-Ranges: bytes\r\n"
  8877. "%s" /* range */
  8878. "%s" /* encoding */,
  8879. cl,
  8880. range,
  8881. encoding);
  8882. }
  8883. /* The previous code must not add any header starting with X- to make
  8884. * sure no one of the additional_headers is included twice */
  8885. if (additional_headers != NULL) {
  8886. (void)mg_printf(conn,
  8887. "%.*s\r\n\r\n",
  8888. (int)strlen(additional_headers),
  8889. additional_headers);
  8890. } else {
  8891. (void)mg_printf(conn, "\r\n");
  8892. }
  8893. if (!is_head_request) {
  8894. #if defined(USE_ZLIB)
  8895. if (allow_on_the_fly_compression) {
  8896. /* Compress and send */
  8897. send_compressed_data(conn, filep);
  8898. } else
  8899. #endif
  8900. {
  8901. /* Send file directly */
  8902. send_file_data(conn, filep, r1, cl);
  8903. }
  8904. }
  8905. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8906. }
  8907. int
  8908. mg_send_file_body(struct mg_connection *conn, const char *path)
  8909. {
  8910. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8911. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8912. return -1;
  8913. }
  8914. fclose_on_exec(&file.access, conn);
  8915. send_file_data(conn, &file, 0, INT64_MAX);
  8916. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8917. return 0; /* >= 0 for OK */
  8918. }
  8919. #endif /* NO_FILESYSTEMS */
  8920. #if !defined(NO_CACHING)
  8921. /* Return True if we should reply 304 Not Modified. */
  8922. static int
  8923. is_not_modified(const struct mg_connection *conn,
  8924. const struct mg_file_stat *filestat)
  8925. {
  8926. char etag[64];
  8927. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8928. const char *inm = mg_get_header(conn, "If-None-Match");
  8929. construct_etag(etag, sizeof(etag), filestat);
  8930. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8931. || ((ims != NULL)
  8932. && (filestat->last_modified <= parse_date_string(ims)));
  8933. }
  8934. static void
  8935. handle_not_modified_static_file_request(struct mg_connection *conn,
  8936. struct mg_file *filep)
  8937. {
  8938. char date[64], lm[64], etag[64];
  8939. time_t curtime = time(NULL);
  8940. if ((conn == NULL) || (filep == NULL)) {
  8941. return;
  8942. }
  8943. conn->status_code = 304;
  8944. gmt_time_string(date, sizeof(date), &curtime);
  8945. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8946. construct_etag(etag, sizeof(etag), &filep->stat);
  8947. (void)mg_printf(conn,
  8948. "HTTP/1.1 %d %s\r\n"
  8949. "Date: %s\r\n",
  8950. conn->status_code,
  8951. mg_get_response_code_text(conn, conn->status_code),
  8952. date);
  8953. send_static_cache_header(conn);
  8954. send_additional_header(conn);
  8955. (void)mg_printf(conn,
  8956. "Last-Modified: %s\r\n"
  8957. "Etag: %s\r\n"
  8958. "Connection: %s\r\n"
  8959. "\r\n",
  8960. lm,
  8961. etag,
  8962. suggest_connection_header(conn));
  8963. }
  8964. #endif
  8965. #if !defined(NO_FILESYSTEMS)
  8966. void
  8967. mg_send_file(struct mg_connection *conn, const char *path)
  8968. {
  8969. mg_send_mime_file2(conn, path, NULL, NULL);
  8970. }
  8971. void
  8972. mg_send_mime_file(struct mg_connection *conn,
  8973. const char *path,
  8974. const char *mime_type)
  8975. {
  8976. mg_send_mime_file2(conn, path, mime_type, NULL);
  8977. }
  8978. void
  8979. mg_send_mime_file2(struct mg_connection *conn,
  8980. const char *path,
  8981. const char *mime_type,
  8982. const char *additional_headers)
  8983. {
  8984. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8985. if (!conn) {
  8986. /* No conn */
  8987. return;
  8988. }
  8989. if (mg_stat(conn, path, &file.stat)) {
  8990. #if !defined(NO_CACHING)
  8991. if (is_not_modified(conn, &file.stat)) {
  8992. /* Send 304 "Not Modified" - this must not send any body data */
  8993. handle_not_modified_static_file_request(conn, &file);
  8994. } else
  8995. #endif /* NO_CACHING */
  8996. if (file.stat.is_directory) {
  8997. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8998. "yes")) {
  8999. handle_directory_request(conn, path);
  9000. } else {
  9001. mg_send_http_error(conn,
  9002. 403,
  9003. "%s",
  9004. "Error: Directory listing denied");
  9005. }
  9006. } else {
  9007. handle_static_file_request(
  9008. conn, path, &file, mime_type, additional_headers);
  9009. }
  9010. } else {
  9011. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9012. }
  9013. }
  9014. /* For a given PUT path, create all intermediate subdirectories.
  9015. * Return 0 if the path itself is a directory.
  9016. * Return 1 if the path leads to a file.
  9017. * Return -1 for if the path is too long.
  9018. * Return -2 if path can not be created.
  9019. */
  9020. static int
  9021. put_dir(struct mg_connection *conn, const char *path)
  9022. {
  9023. char buf[PATH_MAX];
  9024. const char *s, *p;
  9025. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9026. size_t len;
  9027. int res = 1;
  9028. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9029. len = (size_t)(p - path);
  9030. if (len >= sizeof(buf)) {
  9031. /* path too long */
  9032. res = -1;
  9033. break;
  9034. }
  9035. memcpy(buf, path, len);
  9036. buf[len] = '\0';
  9037. /* Try to create intermediate directory */
  9038. DEBUG_TRACE("mkdir(%s)", buf);
  9039. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9040. /* path does not exixt and can not be created */
  9041. res = -2;
  9042. break;
  9043. }
  9044. /* Is path itself a directory? */
  9045. if (p[1] == '\0') {
  9046. res = 0;
  9047. }
  9048. }
  9049. return res;
  9050. }
  9051. static void
  9052. remove_bad_file(const struct mg_connection *conn, const char *path)
  9053. {
  9054. int r = mg_remove(conn, path);
  9055. if (r != 0) {
  9056. mg_cry_internal(conn,
  9057. "%s: Cannot remove invalid file %s",
  9058. __func__,
  9059. path);
  9060. }
  9061. }
  9062. long long
  9063. mg_store_body(struct mg_connection *conn, const char *path)
  9064. {
  9065. char buf[MG_BUF_LEN];
  9066. long long len = 0;
  9067. int ret, n;
  9068. struct mg_file fi;
  9069. if (conn->consumed_content != 0) {
  9070. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9071. return -11;
  9072. }
  9073. ret = put_dir(conn, path);
  9074. if (ret < 0) {
  9075. /* -1 for path too long,
  9076. * -2 for path can not be created. */
  9077. return ret;
  9078. }
  9079. if (ret != 1) {
  9080. /* Return 0 means, path itself is a directory. */
  9081. return 0;
  9082. }
  9083. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9084. return -12;
  9085. }
  9086. ret = mg_read(conn, buf, sizeof(buf));
  9087. while (ret > 0) {
  9088. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9089. if (n != ret) {
  9090. (void)mg_fclose(
  9091. &fi.access); /* File is bad and will be removed anyway. */
  9092. remove_bad_file(conn, path);
  9093. return -13;
  9094. }
  9095. len += ret;
  9096. ret = mg_read(conn, buf, sizeof(buf));
  9097. }
  9098. /* File is open for writing. If fclose fails, there was probably an
  9099. * error flushing the buffer to disk, so the file on disk might be
  9100. * broken. Delete it and return an error to the caller. */
  9101. if (mg_fclose(&fi.access) != 0) {
  9102. remove_bad_file(conn, path);
  9103. return -14;
  9104. }
  9105. return len;
  9106. }
  9107. #endif /* NO_FILESYSTEMS */
  9108. /* Parse a buffer:
  9109. * Forward the string pointer till the end of a word, then
  9110. * terminate it and forward till the begin of the next word.
  9111. */
  9112. static int
  9113. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9114. {
  9115. /* Forward until a space is found - use isgraph here */
  9116. /* See http://www.cplusplus.com/reference/cctype/ */
  9117. while (isgraph((unsigned char)**ppw)) {
  9118. (*ppw)++;
  9119. }
  9120. /* Check end of word */
  9121. if (eol) {
  9122. /* must be a end of line */
  9123. if ((**ppw != '\r') && (**ppw != '\n')) {
  9124. return -1;
  9125. }
  9126. } else {
  9127. /* must be a end of a word, but not a line */
  9128. if (**ppw != ' ') {
  9129. return -1;
  9130. }
  9131. }
  9132. /* Terminate and forward to the next word */
  9133. do {
  9134. **ppw = 0;
  9135. (*ppw)++;
  9136. } while (isspace((unsigned char)**ppw));
  9137. /* Check after term */
  9138. if (!eol) {
  9139. /* if it's not the end of line, there must be a next word */
  9140. if (!isgraph((unsigned char)**ppw)) {
  9141. return -1;
  9142. }
  9143. }
  9144. /* ok */
  9145. return 1;
  9146. }
  9147. /* Parse HTTP headers from the given buffer, advance buf pointer
  9148. * to the point where parsing stopped.
  9149. * All parameters must be valid pointers (not NULL).
  9150. * Return <0 on error. */
  9151. static int
  9152. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9153. {
  9154. int i;
  9155. int num_headers = 0;
  9156. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9157. char *dp = *buf;
  9158. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9159. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9160. dp++;
  9161. }
  9162. if (dp == *buf) {
  9163. /* End of headers reached. */
  9164. break;
  9165. }
  9166. if (*dp != ':') {
  9167. /* This is not a valid field. */
  9168. return -1;
  9169. }
  9170. /* End of header key (*dp == ':') */
  9171. /* Truncate here and set the key name */
  9172. *dp = 0;
  9173. hdr[i].name = *buf;
  9174. /* Skip all spaces */
  9175. do {
  9176. dp++;
  9177. } while ((*dp == ' ') || (*dp == '\t'));
  9178. /* The rest of the line is the value */
  9179. hdr[i].value = dp;
  9180. /* Find end of line */
  9181. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9182. dp++;
  9183. };
  9184. /* eliminate \r */
  9185. if (*dp == '\r') {
  9186. *dp = 0;
  9187. dp++;
  9188. if (*dp != '\n') {
  9189. /* This is not a valid line. */
  9190. return -1;
  9191. }
  9192. }
  9193. /* here *dp is either 0 or '\n' */
  9194. /* in any case, we have a new header */
  9195. num_headers = i + 1;
  9196. if (*dp) {
  9197. *dp = 0;
  9198. dp++;
  9199. *buf = dp;
  9200. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9201. /* This is the end of the header */
  9202. break;
  9203. }
  9204. } else {
  9205. *buf = dp;
  9206. break;
  9207. }
  9208. }
  9209. return num_headers;
  9210. }
  9211. struct mg_http_method_info {
  9212. const char *name;
  9213. int request_has_body;
  9214. int response_has_body;
  9215. int is_safe;
  9216. int is_idempotent;
  9217. int is_cacheable;
  9218. };
  9219. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9220. static const struct mg_http_method_info http_methods[] = {
  9221. /* HTTP (RFC 2616) */
  9222. {"GET", 0, 1, 1, 1, 1},
  9223. {"POST", 1, 1, 0, 0, 0},
  9224. {"PUT", 1, 0, 0, 1, 0},
  9225. {"DELETE", 0, 0, 0, 1, 0},
  9226. {"HEAD", 0, 0, 1, 1, 1},
  9227. {"OPTIONS", 0, 0, 1, 1, 0},
  9228. {"CONNECT", 1, 1, 0, 0, 0},
  9229. /* TRACE method (RFC 2616) is not supported for security reasons */
  9230. /* PATCH method (RFC 5789) */
  9231. {"PATCH", 1, 0, 0, 0, 0},
  9232. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9233. /* WEBDAV (RFC 2518) */
  9234. {"PROPFIND", 0, 1, 1, 1, 0},
  9235. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9236. * Some PROPFIND results MAY be cached, with care,
  9237. * as there is no cache validation mechanism for
  9238. * most properties. This method is both safe and
  9239. * idempotent (see Section 9.1 of [RFC2616]). */
  9240. {"MKCOL", 0, 0, 0, 1, 0},
  9241. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9242. * When MKCOL is invoked without a request body,
  9243. * the newly created collection SHOULD have no
  9244. * members. A MKCOL request message may contain
  9245. * a message body. The precise behavior of a MKCOL
  9246. * request when the body is present is undefined,
  9247. * ... ==> We do not support MKCOL with body data.
  9248. * This method is idempotent, but not safe (see
  9249. * Section 9.1 of [RFC2616]). Responses to this
  9250. * method MUST NOT be cached. */
  9251. /* Unsupported WEBDAV Methods: */
  9252. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9253. /* + 11 methods from RFC 3253 */
  9254. /* ORDERPATCH (RFC 3648) */
  9255. /* ACL (RFC 3744) */
  9256. /* SEARCH (RFC 5323) */
  9257. /* + MicroSoft extensions
  9258. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9259. /* REPORT method (RFC 3253) */
  9260. {"REPORT", 1, 1, 1, 1, 1},
  9261. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9262. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9263. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9264. * to be useful for REST in case a "GET request with body" is
  9265. * required. */
  9266. {NULL, 0, 0, 0, 0, 0}
  9267. /* end of list */
  9268. };
  9269. static const struct mg_http_method_info *
  9270. get_http_method_info(const char *method)
  9271. {
  9272. /* Check if the method is known to the server. The list of all known
  9273. * HTTP methods can be found here at
  9274. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9275. */
  9276. const struct mg_http_method_info *m = http_methods;
  9277. while (m->name) {
  9278. if (!strcmp(m->name, method)) {
  9279. return m;
  9280. }
  9281. m++;
  9282. }
  9283. return NULL;
  9284. }
  9285. static int
  9286. is_valid_http_method(const char *method)
  9287. {
  9288. return (get_http_method_info(method) != NULL);
  9289. }
  9290. /* Parse HTTP request, fill in mg_request_info structure.
  9291. * This function modifies the buffer by NUL-terminating
  9292. * HTTP request components, header names and header values.
  9293. * Parameters:
  9294. * buf (in/out): pointer to the HTTP header to parse and split
  9295. * len (in): length of HTTP header buffer
  9296. * re (out): parsed header as mg_request_info
  9297. * buf and ri must be valid pointers (not NULL), len>0.
  9298. * Returns <0 on error. */
  9299. static int
  9300. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9301. {
  9302. int request_length;
  9303. int init_skip = 0;
  9304. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9305. * remote_port */
  9306. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9307. NULL;
  9308. ri->num_headers = 0;
  9309. /* RFC says that all initial whitespaces should be ingored */
  9310. /* This included all leading \r and \n (isspace) */
  9311. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9312. while ((len > 0) && isspace((unsigned char)*buf)) {
  9313. buf++;
  9314. len--;
  9315. init_skip++;
  9316. }
  9317. if (len == 0) {
  9318. /* Incomplete request */
  9319. return 0;
  9320. }
  9321. /* Control characters are not allowed, including zero */
  9322. if (iscntrl((unsigned char)*buf)) {
  9323. return -1;
  9324. }
  9325. /* Find end of HTTP header */
  9326. request_length = get_http_header_len(buf, len);
  9327. if (request_length <= 0) {
  9328. return request_length;
  9329. }
  9330. buf[request_length - 1] = '\0';
  9331. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9332. return -1;
  9333. }
  9334. /* The first word has to be the HTTP method */
  9335. ri->request_method = buf;
  9336. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9337. return -1;
  9338. }
  9339. /* Check for a valid http method */
  9340. if (!is_valid_http_method(ri->request_method)) {
  9341. return -1;
  9342. }
  9343. /* The second word is the URI */
  9344. ri->request_uri = buf;
  9345. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9346. return -1;
  9347. }
  9348. /* Next would be the HTTP version */
  9349. ri->http_version = buf;
  9350. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9351. return -1;
  9352. }
  9353. /* Check for a valid HTTP version key */
  9354. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9355. /* Invalid request */
  9356. return -1;
  9357. }
  9358. ri->http_version += 5;
  9359. /* Parse all HTTP headers */
  9360. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9361. if (ri->num_headers < 0) {
  9362. /* Error while parsing headers */
  9363. return -1;
  9364. }
  9365. return request_length + init_skip;
  9366. }
  9367. static int
  9368. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9369. {
  9370. int response_length;
  9371. int init_skip = 0;
  9372. char *tmp, *tmp2;
  9373. long l;
  9374. /* Initialize elements. */
  9375. ri->http_version = ri->status_text = NULL;
  9376. ri->num_headers = ri->status_code = 0;
  9377. /* RFC says that all initial whitespaces should be ingored */
  9378. /* This included all leading \r and \n (isspace) */
  9379. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9380. while ((len > 0) && isspace((unsigned char)*buf)) {
  9381. buf++;
  9382. len--;
  9383. init_skip++;
  9384. }
  9385. if (len == 0) {
  9386. /* Incomplete request */
  9387. return 0;
  9388. }
  9389. /* Control characters are not allowed, including zero */
  9390. if (iscntrl((unsigned char)*buf)) {
  9391. return -1;
  9392. }
  9393. /* Find end of HTTP header */
  9394. response_length = get_http_header_len(buf, len);
  9395. if (response_length <= 0) {
  9396. return response_length;
  9397. }
  9398. buf[response_length - 1] = '\0';
  9399. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9400. return -1;
  9401. }
  9402. /* The first word is the HTTP version */
  9403. /* Check for a valid HTTP version key */
  9404. if (strncmp(buf, "HTTP/", 5) != 0) {
  9405. /* Invalid request */
  9406. return -1;
  9407. }
  9408. buf += 5;
  9409. if (!isgraph((unsigned char)buf[0])) {
  9410. /* Invalid request */
  9411. return -1;
  9412. }
  9413. ri->http_version = buf;
  9414. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9415. return -1;
  9416. }
  9417. /* The second word is the status as a number */
  9418. tmp = buf;
  9419. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9420. return -1;
  9421. }
  9422. l = strtol(tmp, &tmp2, 10);
  9423. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9424. /* Everything else but a 3 digit code is invalid */
  9425. return -1;
  9426. }
  9427. ri->status_code = (int)l;
  9428. /* The rest of the line is the status text */
  9429. ri->status_text = buf;
  9430. /* Find end of status text */
  9431. /* isgraph or isspace = isprint */
  9432. while (isprint((unsigned char)*buf)) {
  9433. buf++;
  9434. }
  9435. if ((*buf != '\r') && (*buf != '\n')) {
  9436. return -1;
  9437. }
  9438. /* Terminate string and forward buf to next line */
  9439. do {
  9440. *buf = 0;
  9441. buf++;
  9442. } while (isspace((unsigned char)*buf));
  9443. /* Parse all HTTP headers */
  9444. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9445. if (ri->num_headers < 0) {
  9446. /* Error while parsing headers */
  9447. return -1;
  9448. }
  9449. return response_length + init_skip;
  9450. }
  9451. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9452. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9453. * buffer (which marks the end of HTTP request). Buffer buf may already
  9454. * have some data. The length of the data is stored in nread.
  9455. * Upon every read operation, increase nread by the number of bytes read. */
  9456. static int
  9457. read_message(FILE *fp,
  9458. struct mg_connection *conn,
  9459. char *buf,
  9460. int bufsiz,
  9461. int *nread)
  9462. {
  9463. int request_len, n = 0;
  9464. struct timespec last_action_time;
  9465. double request_timeout;
  9466. if (!conn) {
  9467. return 0;
  9468. }
  9469. memset(&last_action_time, 0, sizeof(last_action_time));
  9470. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9471. /* value of request_timeout is in seconds, config in milliseconds */
  9472. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9473. } else {
  9474. request_timeout = -1.0;
  9475. }
  9476. if (conn->handled_requests > 0) {
  9477. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9478. request_timeout =
  9479. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9480. }
  9481. }
  9482. request_len = get_http_header_len(buf, *nread);
  9483. while (request_len == 0) {
  9484. /* Full request not yet received */
  9485. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9486. /* Server is to be stopped. */
  9487. return -1;
  9488. }
  9489. if (*nread >= bufsiz) {
  9490. /* Request too long */
  9491. return -2;
  9492. }
  9493. n = pull_inner(
  9494. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9495. if (n == -2) {
  9496. /* Receive error */
  9497. return -1;
  9498. }
  9499. /* update clock after every read request */
  9500. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9501. if (n > 0) {
  9502. *nread += n;
  9503. request_len = get_http_header_len(buf, *nread);
  9504. }
  9505. if ((request_len == 0) && (request_timeout >= 0)) {
  9506. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9507. > request_timeout) {
  9508. /* Timeout */
  9509. return -1;
  9510. }
  9511. }
  9512. }
  9513. return request_len;
  9514. }
  9515. #if !defined(NO_CGI) || !defined(NO_FILES)
  9516. static int
  9517. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9518. {
  9519. const char *expect;
  9520. char buf[MG_BUF_LEN];
  9521. int success = 0;
  9522. if (!conn) {
  9523. return 0;
  9524. }
  9525. expect = mg_get_header(conn, "Expect");
  9526. DEBUG_ASSERT(fp != NULL);
  9527. if (!fp) {
  9528. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9529. return 0;
  9530. }
  9531. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9532. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9533. */
  9534. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9535. } else {
  9536. if (expect != NULL) {
  9537. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9538. conn->status_code = 100;
  9539. } else {
  9540. conn->status_code = 200;
  9541. }
  9542. DEBUG_ASSERT(conn->consumed_content == 0);
  9543. if (conn->consumed_content != 0) {
  9544. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9545. return 0;
  9546. }
  9547. for (;;) {
  9548. int nread = mg_read(conn, buf, sizeof(buf));
  9549. if (nread <= 0) {
  9550. success = (nread == 0);
  9551. break;
  9552. }
  9553. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9554. break;
  9555. }
  9556. }
  9557. /* Each error code path in this function must send an error */
  9558. if (!success) {
  9559. /* NOTE: Maybe some data has already been sent. */
  9560. /* TODO (low): If some data has been sent, a correct error
  9561. * reply can no longer be sent, so just close the connection */
  9562. mg_send_http_error(conn, 500, "%s", "");
  9563. }
  9564. }
  9565. return success;
  9566. }
  9567. #endif
  9568. #if defined(USE_TIMERS)
  9569. #define TIMER_API static
  9570. #include "timer.inl"
  9571. #endif /* USE_TIMERS */
  9572. #if !defined(NO_CGI)
  9573. /* This structure helps to create an environment for the spawned CGI
  9574. * program.
  9575. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9576. * last element must be NULL.
  9577. * However, on Windows there is a requirement that all these
  9578. * VARIABLE=VALUE\0
  9579. * strings must reside in a contiguous buffer. The end of the buffer is
  9580. * marked by two '\0' characters.
  9581. * We satisfy both worlds: we create an envp array (which is vars), all
  9582. * entries are actually pointers inside buf. */
  9583. struct cgi_environment {
  9584. struct mg_connection *conn;
  9585. /* Data block */
  9586. char *buf; /* Environment buffer */
  9587. size_t buflen; /* Space available in buf */
  9588. size_t bufused; /* Space taken in buf */
  9589. /* Index block */
  9590. char **var; /* char **envp */
  9591. size_t varlen; /* Number of variables available in var */
  9592. size_t varused; /* Number of variables stored in var */
  9593. };
  9594. static void addenv(struct cgi_environment *env,
  9595. PRINTF_FORMAT_STRING(const char *fmt),
  9596. ...) PRINTF_ARGS(2, 3);
  9597. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9598. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9599. static void
  9600. addenv(struct cgi_environment *env, const char *fmt, ...)
  9601. {
  9602. size_t i, n, space;
  9603. int truncated = 0;
  9604. char *added;
  9605. va_list ap;
  9606. if ((env->varlen - env->varused) < 2) {
  9607. mg_cry_internal(env->conn,
  9608. "%s: Cannot register CGI variable [%s]",
  9609. __func__,
  9610. fmt);
  9611. return;
  9612. }
  9613. /* Calculate how much space is left in the buffer */
  9614. space = (env->buflen - env->bufused);
  9615. do {
  9616. /* Space for "\0\0" is always needed. */
  9617. if (space <= 2) {
  9618. /* Allocate new buffer */
  9619. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9620. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9621. if (!added) {
  9622. /* Out of memory */
  9623. mg_cry_internal(
  9624. env->conn,
  9625. "%s: Cannot allocate memory for CGI variable [%s]",
  9626. __func__,
  9627. fmt);
  9628. return;
  9629. }
  9630. /* Retarget pointers */
  9631. env->buf = added;
  9632. env->buflen = n;
  9633. for (i = 0, n = 0; i < env->varused; i++) {
  9634. env->var[i] = added + n;
  9635. n += strlen(added + n) + 1;
  9636. }
  9637. space = (env->buflen - env->bufused);
  9638. }
  9639. /* Make a pointer to the free space int the buffer */
  9640. added = env->buf + env->bufused;
  9641. /* Copy VARIABLE=VALUE\0 string into the free space */
  9642. va_start(ap, fmt);
  9643. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9644. va_end(ap);
  9645. /* Do not add truncated strings to the environment */
  9646. if (truncated) {
  9647. /* Reallocate the buffer */
  9648. space = 0;
  9649. }
  9650. } while (truncated);
  9651. /* Calculate number of bytes added to the environment */
  9652. n = strlen(added) + 1;
  9653. env->bufused += n;
  9654. /* Append a pointer to the added string into the envp array */
  9655. env->var[env->varused] = added;
  9656. env->varused++;
  9657. }
  9658. /* Return 0 on success, non-zero if an error occurs. */
  9659. static int
  9660. prepare_cgi_environment(struct mg_connection *conn,
  9661. const char *prog,
  9662. struct cgi_environment *env)
  9663. {
  9664. const char *s;
  9665. struct vec var_vec;
  9666. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9667. int i, truncated, uri_len;
  9668. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9669. return -1;
  9670. }
  9671. env->conn = conn;
  9672. env->buflen = CGI_ENVIRONMENT_SIZE;
  9673. env->bufused = 0;
  9674. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9675. if (env->buf == NULL) {
  9676. mg_cry_internal(conn,
  9677. "%s: Not enough memory for environmental buffer",
  9678. __func__);
  9679. return -1;
  9680. }
  9681. env->varlen = MAX_CGI_ENVIR_VARS;
  9682. env->varused = 0;
  9683. env->var =
  9684. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9685. if (env->var == NULL) {
  9686. mg_cry_internal(conn,
  9687. "%s: Not enough memory for environmental variables",
  9688. __func__);
  9689. mg_free(env->buf);
  9690. return -1;
  9691. }
  9692. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9693. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9694. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9695. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9696. /* Prepare the environment block */
  9697. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9698. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9699. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9700. #if defined(USE_IPV6)
  9701. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9702. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9703. } else
  9704. #endif
  9705. {
  9706. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9707. }
  9708. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9709. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9710. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9711. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9712. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9713. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9714. /* SCRIPT_NAME */
  9715. uri_len = (int)strlen(conn->request_info.local_uri);
  9716. if (conn->path_info == NULL) {
  9717. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9718. /* URI: /path_to_script/script.cgi */
  9719. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9720. } else {
  9721. /* URI: /path_to_script/ ... using index.cgi */
  9722. const char *index_file = strrchr(prog, '/');
  9723. if (index_file) {
  9724. addenv(env,
  9725. "SCRIPT_NAME=%s%s",
  9726. conn->request_info.local_uri,
  9727. index_file + 1);
  9728. }
  9729. }
  9730. } else {
  9731. /* URI: /path_to_script/script.cgi/path_info */
  9732. addenv(env,
  9733. "SCRIPT_NAME=%.*s",
  9734. uri_len - (int)strlen(conn->path_info),
  9735. conn->request_info.local_uri);
  9736. }
  9737. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9738. if (conn->path_info == NULL) {
  9739. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9740. } else {
  9741. addenv(env,
  9742. "PATH_TRANSLATED=%s%s",
  9743. conn->dom_ctx->config[DOCUMENT_ROOT],
  9744. conn->path_info);
  9745. }
  9746. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9747. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9748. addenv(env, "CONTENT_TYPE=%s", s);
  9749. }
  9750. if (conn->request_info.query_string != NULL) {
  9751. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9752. }
  9753. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9754. addenv(env, "CONTENT_LENGTH=%s", s);
  9755. }
  9756. if ((s = getenv("PATH")) != NULL) {
  9757. addenv(env, "PATH=%s", s);
  9758. }
  9759. if (conn->path_info != NULL) {
  9760. addenv(env, "PATH_INFO=%s", conn->path_info);
  9761. }
  9762. if (conn->status_code > 0) {
  9763. /* CGI error handler should show the status code */
  9764. addenv(env, "STATUS=%d", conn->status_code);
  9765. }
  9766. #if defined(_WIN32)
  9767. if ((s = getenv("COMSPEC")) != NULL) {
  9768. addenv(env, "COMSPEC=%s", s);
  9769. }
  9770. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9771. addenv(env, "SYSTEMROOT=%s", s);
  9772. }
  9773. if ((s = getenv("SystemDrive")) != NULL) {
  9774. addenv(env, "SystemDrive=%s", s);
  9775. }
  9776. if ((s = getenv("ProgramFiles")) != NULL) {
  9777. addenv(env, "ProgramFiles=%s", s);
  9778. }
  9779. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9780. addenv(env, "ProgramFiles(x86)=%s", s);
  9781. }
  9782. #else
  9783. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9784. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9785. }
  9786. #endif /* _WIN32 */
  9787. if ((s = getenv("PERLLIB")) != NULL) {
  9788. addenv(env, "PERLLIB=%s", s);
  9789. }
  9790. if (conn->request_info.remote_user != NULL) {
  9791. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9792. addenv(env, "%s", "AUTH_TYPE=Digest");
  9793. }
  9794. /* Add all headers as HTTP_* variables */
  9795. for (i = 0; i < conn->request_info.num_headers; i++) {
  9796. (void)mg_snprintf(conn,
  9797. &truncated,
  9798. http_var_name,
  9799. sizeof(http_var_name),
  9800. "HTTP_%s",
  9801. conn->request_info.http_headers[i].name);
  9802. if (truncated) {
  9803. mg_cry_internal(conn,
  9804. "%s: HTTP header variable too long [%s]",
  9805. __func__,
  9806. conn->request_info.http_headers[i].name);
  9807. continue;
  9808. }
  9809. /* Convert variable name into uppercase, and change - to _ */
  9810. for (p = http_var_name; *p != '\0'; p++) {
  9811. if (*p == '-') {
  9812. *p = '_';
  9813. }
  9814. *p = (char)toupper((unsigned char)*p);
  9815. }
  9816. addenv(env,
  9817. "%s=%s",
  9818. http_var_name,
  9819. conn->request_info.http_headers[i].value);
  9820. }
  9821. /* Add user-specified variables */
  9822. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9823. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9824. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9825. }
  9826. env->var[env->varused] = NULL;
  9827. env->buf[env->bufused] = '\0';
  9828. return 0;
  9829. }
  9830. /* Data for CGI process control: PID and number of references */
  9831. struct process_control_data {
  9832. pid_t pid;
  9833. int references;
  9834. };
  9835. static int
  9836. abort_process(void *data)
  9837. {
  9838. /* Waitpid checks for child status and won't work for a pid that does
  9839. * not identify a child of the current process. Thus, if the pid is
  9840. * reused, we will not affect a different process. */
  9841. struct process_control_data *proc = (struct process_control_data *)data;
  9842. int status = 0;
  9843. int refs;
  9844. pid_t ret_pid;
  9845. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9846. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9847. /* Stop child process */
  9848. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9849. kill(proc->pid, SIGABRT);
  9850. /* Wait until process is terminated (don't leave zombies) */
  9851. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9852. ;
  9853. } else {
  9854. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9855. }
  9856. /* Dec reference counter */
  9857. refs = mg_atomic_dec(&proc->references);
  9858. if (refs == 0) {
  9859. /* no more references - free data */
  9860. mg_free(data);
  9861. }
  9862. return 0;
  9863. }
  9864. /* Local (static) function assumes all arguments are valid. */
  9865. static void
  9866. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9867. {
  9868. char *buf;
  9869. size_t buflen;
  9870. int headers_len, data_len, i, truncated;
  9871. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9872. const char *status, *status_text, *connection_state;
  9873. char *pbuf, dir[PATH_MAX], *p;
  9874. struct mg_request_info ri;
  9875. struct cgi_environment blk;
  9876. FILE *in = NULL, *out = NULL, *err = NULL;
  9877. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9878. pid_t pid = (pid_t)-1;
  9879. struct process_control_data *proc = NULL;
  9880. #if defined(USE_TIMERS)
  9881. double cgi_timeout = -1.0;
  9882. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9883. /* Get timeout in seconds */
  9884. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9885. }
  9886. #endif
  9887. buf = NULL;
  9888. buflen = conn->phys_ctx->max_request_size;
  9889. i = prepare_cgi_environment(conn, prog, &blk);
  9890. if (i != 0) {
  9891. blk.buf = NULL;
  9892. blk.var = NULL;
  9893. goto done;
  9894. }
  9895. /* CGI must be executed in its own directory. 'dir' must point to the
  9896. * directory containing executable program, 'p' must point to the
  9897. * executable program name relative to 'dir'. */
  9898. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9899. if (truncated) {
  9900. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9901. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9902. goto done;
  9903. }
  9904. if ((p = strrchr(dir, '/')) != NULL) {
  9905. *p++ = '\0';
  9906. } else {
  9907. dir[0] = '.';
  9908. dir[1] = '\0';
  9909. p = (char *)prog;
  9910. }
  9911. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9912. status = strerror(ERRNO);
  9913. mg_cry_internal(
  9914. conn,
  9915. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9916. prog,
  9917. status);
  9918. mg_send_http_error(conn,
  9919. 500,
  9920. "Error: Cannot create CGI pipe: %s",
  9921. status);
  9922. goto done;
  9923. }
  9924. proc = (struct process_control_data *)
  9925. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9926. if (proc == NULL) {
  9927. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9928. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9929. goto done;
  9930. }
  9931. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9932. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9933. if (pid == (pid_t)-1) {
  9934. status = strerror(ERRNO);
  9935. mg_cry_internal(
  9936. conn,
  9937. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9938. prog,
  9939. status);
  9940. mg_send_http_error(conn,
  9941. 500,
  9942. "Error: Cannot spawn CGI process [%s]: %s",
  9943. prog,
  9944. status);
  9945. mg_free(proc);
  9946. proc = NULL;
  9947. goto done;
  9948. }
  9949. /* Store data in shared process_control_data */
  9950. proc->pid = pid;
  9951. proc->references = 1;
  9952. #if defined(USE_TIMERS)
  9953. if (cgi_timeout > 0.0) {
  9954. proc->references = 2;
  9955. // Start a timer for CGI
  9956. timer_add(conn->phys_ctx,
  9957. cgi_timeout /* in seconds */,
  9958. 0.0,
  9959. 1,
  9960. abort_process,
  9961. (void *)proc);
  9962. }
  9963. #endif
  9964. /* Parent closes only one side of the pipes.
  9965. * If we don't mark them as closed, close() attempt before
  9966. * return from this function throws an exception on Windows.
  9967. * Windows does not like when closed descriptor is closed again. */
  9968. (void)close(fdin[0]);
  9969. (void)close(fdout[1]);
  9970. (void)close(fderr[1]);
  9971. fdin[0] = fdout[1] = fderr[1] = -1;
  9972. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9973. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9974. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9975. status = strerror(ERRNO);
  9976. mg_cry_internal(conn,
  9977. "Error: CGI program \"%s\": Can not open fd: %s",
  9978. prog,
  9979. status);
  9980. mg_send_http_error(conn,
  9981. 500,
  9982. "Error: CGI can not open fd\nfdopen: %s",
  9983. status);
  9984. goto done;
  9985. }
  9986. setbuf(in, NULL);
  9987. setbuf(out, NULL);
  9988. setbuf(err, NULL);
  9989. fout.access.fp = out;
  9990. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9991. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9992. conn->content_len);
  9993. /* This is a POST/PUT request, or another request with body data. */
  9994. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9995. /* Error sending the body data */
  9996. mg_cry_internal(
  9997. conn,
  9998. "Error: CGI program \"%s\": Forward body data failed",
  9999. prog);
  10000. goto done;
  10001. }
  10002. }
  10003. /* Close so child gets an EOF. */
  10004. fclose(in);
  10005. in = NULL;
  10006. fdin[1] = -1;
  10007. /* Now read CGI reply into a buffer. We need to set correct
  10008. * status code, thus we need to see all HTTP headers first.
  10009. * Do not send anything back to client, until we buffer in all
  10010. * HTTP headers. */
  10011. data_len = 0;
  10012. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10013. if (buf == NULL) {
  10014. mg_send_http_error(conn,
  10015. 500,
  10016. "Error: Not enough memory for CGI buffer (%u bytes)",
  10017. (unsigned int)buflen);
  10018. mg_cry_internal(
  10019. conn,
  10020. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10021. "bytes)",
  10022. prog,
  10023. (unsigned int)buflen);
  10024. goto done;
  10025. }
  10026. DEBUG_TRACE("CGI: %s", "wait for response");
  10027. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10028. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10029. if (headers_len <= 0) {
  10030. /* Could not parse the CGI response. Check if some error message on
  10031. * stderr. */
  10032. i = pull_all(err, conn, buf, (int)buflen);
  10033. if (i > 0) {
  10034. /* CGI program explicitly sent an error */
  10035. /* Write the error message to the internal log */
  10036. mg_cry_internal(conn,
  10037. "Error: CGI program \"%s\" sent error "
  10038. "message: [%.*s]",
  10039. prog,
  10040. i,
  10041. buf);
  10042. /* Don't send the error message back to the client */
  10043. mg_send_http_error(conn,
  10044. 500,
  10045. "Error: CGI program \"%s\" failed.",
  10046. prog);
  10047. } else {
  10048. /* CGI program did not explicitly send an error, but a broken
  10049. * respon header */
  10050. mg_cry_internal(conn,
  10051. "Error: CGI program sent malformed or too big "
  10052. "(>%u bytes) HTTP headers: [%.*s]",
  10053. (unsigned)buflen,
  10054. data_len,
  10055. buf);
  10056. mg_send_http_error(conn,
  10057. 500,
  10058. "Error: CGI program sent malformed or too big "
  10059. "(>%u bytes) HTTP headers: [%.*s]",
  10060. (unsigned)buflen,
  10061. data_len,
  10062. buf);
  10063. }
  10064. /* in both cases, abort processing CGI */
  10065. goto done;
  10066. }
  10067. pbuf = buf;
  10068. buf[headers_len - 1] = '\0';
  10069. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10070. /* Make up and send the status line */
  10071. status_text = "OK";
  10072. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10073. != NULL) {
  10074. conn->status_code = atoi(status);
  10075. status_text = status;
  10076. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10077. status_text++;
  10078. }
  10079. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10080. != NULL) {
  10081. conn->status_code = 307;
  10082. } else {
  10083. conn->status_code = 200;
  10084. }
  10085. connection_state =
  10086. get_header(ri.http_headers, ri.num_headers, "Connection");
  10087. if (!header_has_option(connection_state, "keep-alive")) {
  10088. conn->must_close = 1;
  10089. }
  10090. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10091. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10092. /* Send headers */
  10093. for (i = 0; i < ri.num_headers; i++) {
  10094. DEBUG_TRACE("CGI header: %s: %s",
  10095. ri.http_headers[i].name,
  10096. ri.http_headers[i].value);
  10097. mg_printf(conn,
  10098. "%s: %s\r\n",
  10099. ri.http_headers[i].name,
  10100. ri.http_headers[i].value);
  10101. }
  10102. mg_write(conn, "\r\n", 2);
  10103. /* Send chunk of data that may have been read after the headers */
  10104. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10105. /* Read the rest of CGI output and send to the client */
  10106. DEBUG_TRACE("CGI: %s", "forward all data");
  10107. send_file_data(conn, &fout, 0, INT64_MAX);
  10108. DEBUG_TRACE("CGI: %s", "all data sent");
  10109. done:
  10110. mg_free(blk.var);
  10111. mg_free(blk.buf);
  10112. if (pid != (pid_t)-1) {
  10113. abort_process((void *)proc);
  10114. }
  10115. if (fdin[0] != -1) {
  10116. close(fdin[0]);
  10117. }
  10118. if (fdout[1] != -1) {
  10119. close(fdout[1]);
  10120. }
  10121. if (fderr[1] != -1) {
  10122. close(fderr[1]);
  10123. }
  10124. if (in != NULL) {
  10125. fclose(in);
  10126. } else if (fdin[1] != -1) {
  10127. close(fdin[1]);
  10128. }
  10129. if (out != NULL) {
  10130. fclose(out);
  10131. } else if (fdout[0] != -1) {
  10132. close(fdout[0]);
  10133. }
  10134. if (err != NULL) {
  10135. fclose(err);
  10136. } else if (fderr[0] != -1) {
  10137. close(fderr[0]);
  10138. }
  10139. mg_free(buf);
  10140. }
  10141. #endif /* !NO_CGI */
  10142. #if !defined(NO_FILES)
  10143. static void
  10144. mkcol(struct mg_connection *conn, const char *path)
  10145. {
  10146. int rc, body_len;
  10147. struct de de;
  10148. char date[64];
  10149. time_t curtime = time(NULL);
  10150. if (conn == NULL) {
  10151. return;
  10152. }
  10153. /* TODO (mid): Check the mg_send_http_error situations in this function
  10154. */
  10155. memset(&de.file, 0, sizeof(de.file));
  10156. if (!mg_stat(conn, path, &de.file)) {
  10157. mg_cry_internal(conn,
  10158. "%s: mg_stat(%s) failed: %s",
  10159. __func__,
  10160. path,
  10161. strerror(ERRNO));
  10162. }
  10163. if (de.file.last_modified) {
  10164. /* TODO (mid): This check does not seem to make any sense ! */
  10165. /* TODO (mid): Add a webdav unit test first, before changing
  10166. * anything here. */
  10167. mg_send_http_error(
  10168. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10169. return;
  10170. }
  10171. body_len = conn->data_len - conn->request_len;
  10172. if (body_len > 0) {
  10173. mg_send_http_error(
  10174. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10175. return;
  10176. }
  10177. rc = mg_mkdir(conn, path, 0755);
  10178. if (rc == 0) {
  10179. conn->status_code = 201;
  10180. gmt_time_string(date, sizeof(date), &curtime);
  10181. mg_printf(conn,
  10182. "HTTP/1.1 %d Created\r\n"
  10183. "Date: %s\r\n",
  10184. conn->status_code,
  10185. date);
  10186. send_static_cache_header(conn);
  10187. send_additional_header(conn);
  10188. mg_printf(conn,
  10189. "Content-Length: 0\r\n"
  10190. "Connection: %s\r\n\r\n",
  10191. suggest_connection_header(conn));
  10192. } else {
  10193. if (errno == EEXIST) {
  10194. mg_send_http_error(
  10195. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10196. } else if (errno == EACCES) {
  10197. mg_send_http_error(
  10198. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10199. } else if (errno == ENOENT) {
  10200. mg_send_http_error(
  10201. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10202. } else {
  10203. mg_send_http_error(
  10204. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10205. }
  10206. }
  10207. }
  10208. static void
  10209. put_file(struct mg_connection *conn, const char *path)
  10210. {
  10211. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10212. const char *range;
  10213. int64_t r1, r2;
  10214. int rc;
  10215. char date[64];
  10216. time_t curtime = time(NULL);
  10217. if (conn == NULL) {
  10218. return;
  10219. }
  10220. if (mg_stat(conn, path, &file.stat)) {
  10221. /* File already exists */
  10222. conn->status_code = 200;
  10223. if (file.stat.is_directory) {
  10224. /* This is an already existing directory,
  10225. * so there is nothing to do for the server. */
  10226. rc = 0;
  10227. } else {
  10228. /* File exists and is not a directory. */
  10229. /* Can it be replaced? */
  10230. #if defined(MG_USE_OPEN_FILE)
  10231. if (file.access.membuf != NULL) {
  10232. /* This is an "in-memory" file, that can not be replaced */
  10233. mg_send_http_error(conn,
  10234. 405,
  10235. "Error: Put not possible\nReplacing %s "
  10236. "is not supported",
  10237. path);
  10238. return;
  10239. }
  10240. #endif
  10241. /* Check if the server may write this file */
  10242. if (access(path, W_OK) == 0) {
  10243. /* Access granted */
  10244. rc = 1;
  10245. } else {
  10246. mg_send_http_error(
  10247. conn,
  10248. 403,
  10249. "Error: Put not possible\nReplacing %s is not allowed",
  10250. path);
  10251. return;
  10252. }
  10253. }
  10254. } else {
  10255. /* File should be created */
  10256. conn->status_code = 201;
  10257. rc = put_dir(conn, path);
  10258. }
  10259. if (rc == 0) {
  10260. /* put_dir returns 0 if path is a directory */
  10261. gmt_time_string(date, sizeof(date), &curtime);
  10262. mg_printf(conn,
  10263. "HTTP/1.1 %d %s\r\n",
  10264. conn->status_code,
  10265. mg_get_response_code_text(NULL, conn->status_code));
  10266. send_no_cache_header(conn);
  10267. send_additional_header(conn);
  10268. mg_printf(conn,
  10269. "Date: %s\r\n"
  10270. "Content-Length: 0\r\n"
  10271. "Connection: %s\r\n\r\n",
  10272. date,
  10273. suggest_connection_header(conn));
  10274. /* Request to create a directory has been fulfilled successfully.
  10275. * No need to put a file. */
  10276. return;
  10277. }
  10278. if (rc == -1) {
  10279. /* put_dir returns -1 if the path is too long */
  10280. mg_send_http_error(conn,
  10281. 414,
  10282. "Error: Path too long\nput_dir(%s): %s",
  10283. path,
  10284. strerror(ERRNO));
  10285. return;
  10286. }
  10287. if (rc == -2) {
  10288. /* put_dir returns -2 if the directory can not be created */
  10289. mg_send_http_error(conn,
  10290. 500,
  10291. "Error: Can not create directory\nput_dir(%s): %s",
  10292. path,
  10293. strerror(ERRNO));
  10294. return;
  10295. }
  10296. /* A file should be created or overwritten. */
  10297. /* Currently CivetWeb does not nead read+write access. */
  10298. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10299. || file.access.fp == NULL) {
  10300. (void)mg_fclose(&file.access);
  10301. mg_send_http_error(conn,
  10302. 500,
  10303. "Error: Can not create file\nfopen(%s): %s",
  10304. path,
  10305. strerror(ERRNO));
  10306. return;
  10307. }
  10308. fclose_on_exec(&file.access, conn);
  10309. range = mg_get_header(conn, "Content-Range");
  10310. r1 = r2 = 0;
  10311. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10312. conn->status_code = 206; /* Partial content */
  10313. fseeko(file.access.fp, r1, SEEK_SET);
  10314. }
  10315. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10316. /* forward_body_data failed.
  10317. * The error code has already been sent to the client,
  10318. * and conn->status_code is already set. */
  10319. (void)mg_fclose(&file.access);
  10320. return;
  10321. }
  10322. if (mg_fclose(&file.access) != 0) {
  10323. /* fclose failed. This might have different reasons, but a likely
  10324. * one is "no space on disk", http 507. */
  10325. conn->status_code = 507;
  10326. }
  10327. gmt_time_string(date, sizeof(date), &curtime);
  10328. mg_printf(conn,
  10329. "HTTP/1.1 %d %s\r\n",
  10330. conn->status_code,
  10331. mg_get_response_code_text(NULL, conn->status_code));
  10332. send_no_cache_header(conn);
  10333. send_additional_header(conn);
  10334. mg_printf(conn,
  10335. "Date: %s\r\n"
  10336. "Content-Length: 0\r\n"
  10337. "Connection: %s\r\n\r\n",
  10338. date,
  10339. suggest_connection_header(conn));
  10340. }
  10341. static void
  10342. delete_file(struct mg_connection *conn, const char *path)
  10343. {
  10344. struct de de;
  10345. memset(&de.file, 0, sizeof(de.file));
  10346. if (!mg_stat(conn, path, &de.file)) {
  10347. /* mg_stat returns 0 if the file does not exist */
  10348. mg_send_http_error(conn,
  10349. 404,
  10350. "Error: Cannot delete file\nFile %s not found",
  10351. path);
  10352. return;
  10353. }
  10354. #if 0 /* Ignore if a file in memory is inside a folder */
  10355. if (de.access.membuf != NULL) {
  10356. /* the file is cached in memory */
  10357. mg_send_http_error(
  10358. conn,
  10359. 405,
  10360. "Error: Delete not possible\nDeleting %s is not supported",
  10361. path);
  10362. return;
  10363. }
  10364. #endif
  10365. if (de.file.is_directory) {
  10366. if (remove_directory(conn, path)) {
  10367. /* Delete is successful: Return 204 without content. */
  10368. mg_send_http_error(conn, 204, "%s", "");
  10369. } else {
  10370. /* Delete is not successful: Return 500 (Server error). */
  10371. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10372. }
  10373. return;
  10374. }
  10375. /* This is an existing file (not a directory).
  10376. * Check if write permission is granted. */
  10377. if (access(path, W_OK) != 0) {
  10378. /* File is read only */
  10379. mg_send_http_error(
  10380. conn,
  10381. 403,
  10382. "Error: Delete not possible\nDeleting %s is not allowed",
  10383. path);
  10384. return;
  10385. }
  10386. /* Try to delete it. */
  10387. if (mg_remove(conn, path) == 0) {
  10388. /* Delete was successful: Return 204 without content. */
  10389. mg_send_http_error(conn, 204, "%s", "");
  10390. } else {
  10391. /* Delete not successful (file locked). */
  10392. mg_send_http_error(conn,
  10393. 423,
  10394. "Error: Cannot delete file\nremove(%s): %s",
  10395. path,
  10396. strerror(ERRNO));
  10397. }
  10398. }
  10399. #endif /* !NO_FILES */
  10400. #if !defined(NO_FILESYSTEMS)
  10401. static void
  10402. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10403. static void
  10404. do_ssi_include(struct mg_connection *conn,
  10405. const char *ssi,
  10406. char *tag,
  10407. int include_level)
  10408. {
  10409. char file_name[MG_BUF_LEN], path[512], *p;
  10410. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10411. size_t len;
  10412. int truncated = 0;
  10413. if (conn == NULL) {
  10414. return;
  10415. }
  10416. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10417. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10418. * always < MG_BUF_LEN. */
  10419. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10420. /* File name is relative to the webserver root */
  10421. file_name[511] = 0;
  10422. (void)mg_snprintf(conn,
  10423. &truncated,
  10424. path,
  10425. sizeof(path),
  10426. "%s/%s",
  10427. conn->dom_ctx->config[DOCUMENT_ROOT],
  10428. file_name);
  10429. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10430. /* File name is relative to the webserver working directory
  10431. * or it is absolute system path */
  10432. file_name[511] = 0;
  10433. (void)
  10434. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10435. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10436. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10437. /* File name is relative to the currect document */
  10438. file_name[511] = 0;
  10439. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10440. if (!truncated) {
  10441. if ((p = strrchr(path, '/')) != NULL) {
  10442. p[1] = '\0';
  10443. }
  10444. len = strlen(path);
  10445. (void)mg_snprintf(conn,
  10446. &truncated,
  10447. path + len,
  10448. sizeof(path) - len,
  10449. "%s",
  10450. file_name);
  10451. }
  10452. } else {
  10453. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10454. return;
  10455. }
  10456. if (truncated) {
  10457. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10458. return;
  10459. }
  10460. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10461. mg_cry_internal(conn,
  10462. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10463. tag,
  10464. path,
  10465. strerror(ERRNO));
  10466. } else {
  10467. fclose_on_exec(&file.access, conn);
  10468. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10469. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10470. path)
  10471. > 0) {
  10472. send_ssi_file(conn, path, &file, include_level + 1);
  10473. } else {
  10474. send_file_data(conn, &file, 0, INT64_MAX);
  10475. }
  10476. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10477. }
  10478. }
  10479. #if !defined(NO_POPEN)
  10480. static void
  10481. do_ssi_exec(struct mg_connection *conn, char *tag)
  10482. {
  10483. char cmd[1024] = "";
  10484. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10485. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10486. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10487. } else {
  10488. cmd[1023] = 0;
  10489. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10490. mg_cry_internal(conn,
  10491. "Cannot SSI #exec: [%s]: %s",
  10492. cmd,
  10493. strerror(ERRNO));
  10494. } else {
  10495. send_file_data(conn, &file, 0, INT64_MAX);
  10496. pclose(file.access.fp);
  10497. }
  10498. }
  10499. }
  10500. #endif /* !NO_POPEN */
  10501. static int
  10502. mg_fgetc(struct mg_file *filep, int offset)
  10503. {
  10504. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10505. if (filep == NULL) {
  10506. return EOF;
  10507. }
  10508. #if defined(MG_USE_OPEN_FILE)
  10509. if ((filep->access.membuf != NULL) && (offset >= 0)
  10510. && (((unsigned int)(offset)) < filep->stat.size)) {
  10511. return ((const unsigned char *)filep->access.membuf)[offset];
  10512. } else /* else block below */
  10513. #endif
  10514. if (filep->access.fp != NULL) {
  10515. return fgetc(filep->access.fp);
  10516. } else {
  10517. return EOF;
  10518. }
  10519. }
  10520. static void
  10521. send_ssi_file(struct mg_connection *conn,
  10522. const char *path,
  10523. struct mg_file *filep,
  10524. int include_level)
  10525. {
  10526. char buf[MG_BUF_LEN];
  10527. int ch, offset, len, in_tag, in_ssi_tag;
  10528. if (include_level > 10) {
  10529. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10530. return;
  10531. }
  10532. in_tag = in_ssi_tag = len = offset = 0;
  10533. /* Read file, byte by byte, and look for SSI include tags */
  10534. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10535. if (in_tag) {
  10536. /* We are in a tag, either SSI tag or html tag */
  10537. if (ch == '>') {
  10538. /* Tag is closing */
  10539. buf[len++] = '>';
  10540. if (in_ssi_tag) {
  10541. /* Handle SSI tag */
  10542. buf[len] = 0;
  10543. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10544. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10545. #if !defined(NO_POPEN)
  10546. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10547. do_ssi_exec(conn, buf + 9);
  10548. #endif /* !NO_POPEN */
  10549. } else {
  10550. mg_cry_internal(conn,
  10551. "%s: unknown SSI "
  10552. "command: \"%s\"",
  10553. path,
  10554. buf);
  10555. }
  10556. len = 0;
  10557. in_ssi_tag = in_tag = 0;
  10558. } else {
  10559. /* Not an SSI tag */
  10560. /* Flush buffer */
  10561. (void)mg_write(conn, buf, (size_t)len);
  10562. len = 0;
  10563. in_tag = 0;
  10564. }
  10565. } else {
  10566. /* Tag is still open */
  10567. buf[len++] = (char)(ch & 0xff);
  10568. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10569. /* All SSI tags start with <!--# */
  10570. in_ssi_tag = 1;
  10571. }
  10572. if ((len + 2) > (int)sizeof(buf)) {
  10573. /* Tag to long for buffer */
  10574. mg_cry_internal(conn, "%s: tag is too large", path);
  10575. return;
  10576. }
  10577. }
  10578. } else {
  10579. /* We are not in a tag yet. */
  10580. if (ch == '<') {
  10581. /* Tag is opening */
  10582. in_tag = 1;
  10583. if (len > 0) {
  10584. /* Flush current buffer.
  10585. * Buffer is filled with "len" bytes. */
  10586. (void)mg_write(conn, buf, (size_t)len);
  10587. }
  10588. /* Store the < */
  10589. len = 1;
  10590. buf[0] = '<';
  10591. } else {
  10592. /* No Tag */
  10593. /* Add data to buffer */
  10594. buf[len++] = (char)(ch & 0xff);
  10595. /* Flush if buffer is full */
  10596. if (len == (int)sizeof(buf)) {
  10597. mg_write(conn, buf, (size_t)len);
  10598. len = 0;
  10599. }
  10600. }
  10601. }
  10602. }
  10603. /* Send the rest of buffered data */
  10604. if (len > 0) {
  10605. mg_write(conn, buf, (size_t)len);
  10606. }
  10607. }
  10608. static void
  10609. handle_ssi_file_request(struct mg_connection *conn,
  10610. const char *path,
  10611. struct mg_file *filep)
  10612. {
  10613. char date[64];
  10614. time_t curtime = time(NULL);
  10615. const char *cors_orig_cfg;
  10616. const char *cors1, *cors2, *cors3;
  10617. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10618. return;
  10619. }
  10620. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10621. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10622. /* Cross-origin resource sharing (CORS). */
  10623. cors1 = "Access-Control-Allow-Origin: ";
  10624. cors2 = cors_orig_cfg;
  10625. cors3 = "\r\n";
  10626. } else {
  10627. cors1 = cors2 = cors3 = "";
  10628. }
  10629. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10630. /* File exists (precondition for calling this function),
  10631. * but can not be opened by the server. */
  10632. mg_send_http_error(conn,
  10633. 500,
  10634. "Error: Cannot read file\nfopen(%s): %s",
  10635. path,
  10636. strerror(ERRNO));
  10637. } else {
  10638. conn->must_close = 1;
  10639. gmt_time_string(date, sizeof(date), &curtime);
  10640. fclose_on_exec(&filep->access, conn);
  10641. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10642. send_no_cache_header(conn);
  10643. send_additional_header(conn);
  10644. mg_printf(conn,
  10645. "%s%s%s"
  10646. "Date: %s\r\n"
  10647. "Content-Type: text/html\r\n"
  10648. "Connection: %s\r\n\r\n",
  10649. cors1,
  10650. cors2,
  10651. cors3,
  10652. date,
  10653. suggest_connection_header(conn));
  10654. send_ssi_file(conn, path, filep, 0);
  10655. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10656. }
  10657. }
  10658. #endif /* NO_FILESYSTEMS */
  10659. #if !defined(NO_FILES)
  10660. static void
  10661. send_options(struct mg_connection *conn)
  10662. {
  10663. char date[64];
  10664. time_t curtime = time(NULL);
  10665. if (!conn) {
  10666. return;
  10667. }
  10668. conn->status_code = 200;
  10669. conn->must_close = 1;
  10670. gmt_time_string(date, sizeof(date), &curtime);
  10671. /* We do not set a "Cache-Control" header here, but leave the default.
  10672. * Since browsers do not send an OPTIONS request, we can not test the
  10673. * effect anyway. */
  10674. mg_printf(conn,
  10675. "HTTP/1.1 200 OK\r\n"
  10676. "Date: %s\r\n"
  10677. "Connection: %s\r\n"
  10678. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10679. "PROPFIND, MKCOL\r\n"
  10680. "DAV: 1\r\n",
  10681. date,
  10682. suggest_connection_header(conn));
  10683. send_additional_header(conn);
  10684. mg_printf(conn, "\r\n");
  10685. }
  10686. /* Writes PROPFIND properties for a collection element */
  10687. static int
  10688. print_props(struct mg_connection *conn,
  10689. const char *uri,
  10690. const char *name,
  10691. struct mg_file_stat *filep)
  10692. {
  10693. size_t href_size, i, j;
  10694. int len;
  10695. char *href, mtime[64];
  10696. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10697. return 0;
  10698. }
  10699. /* Estimate worst case size for encoding */
  10700. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10701. href = (char *)mg_malloc(href_size);
  10702. if (href == NULL) {
  10703. return 0;
  10704. }
  10705. len = mg_url_encode(uri, href, href_size);
  10706. if (len >= 0) {
  10707. /* Append an extra string */
  10708. mg_url_encode(name, href + len, href_size - (size_t)len);
  10709. }
  10710. /* Directory separator should be preserved. */
  10711. for (i = j = 0; href[i]; j++) {
  10712. if (!strncmp(href + i, "%2f", 3)) {
  10713. href[j] = '/';
  10714. i += 3;
  10715. } else {
  10716. href[j] = href[i++];
  10717. }
  10718. }
  10719. href[j] = '\0';
  10720. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10721. mg_printf(conn,
  10722. "<d:response>"
  10723. "<d:href>%s</d:href>"
  10724. "<d:propstat>"
  10725. "<d:prop>"
  10726. "<d:resourcetype>%s</d:resourcetype>"
  10727. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10728. "<d:getlastmodified>%s</d:getlastmodified>"
  10729. "</d:prop>"
  10730. "<d:status>HTTP/1.1 200 OK</d:status>"
  10731. "</d:propstat>"
  10732. "</d:response>\n",
  10733. href,
  10734. filep->is_directory ? "<d:collection/>" : "",
  10735. filep->size,
  10736. mtime);
  10737. mg_free(href);
  10738. return 1;
  10739. }
  10740. static int
  10741. print_dav_dir_entry(struct de *de, void *data)
  10742. {
  10743. struct mg_connection *conn = (struct mg_connection *)data;
  10744. if (!de || !conn
  10745. || !print_props(
  10746. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10747. return -1;
  10748. }
  10749. return 0;
  10750. }
  10751. static void
  10752. handle_propfind(struct mg_connection *conn,
  10753. const char *path,
  10754. struct mg_file_stat *filep)
  10755. {
  10756. const char *depth = mg_get_header(conn, "Depth");
  10757. char date[64];
  10758. time_t curtime = time(NULL);
  10759. gmt_time_string(date, sizeof(date), &curtime);
  10760. if (!conn || !path || !filep || !conn->dom_ctx) {
  10761. return;
  10762. }
  10763. conn->must_close = 1;
  10764. conn->status_code = 207;
  10765. mg_printf(conn,
  10766. "HTTP/1.1 207 Multi-Status\r\n"
  10767. "Date: %s\r\n",
  10768. date);
  10769. send_static_cache_header(conn);
  10770. send_additional_header(conn);
  10771. mg_printf(conn,
  10772. "Connection: %s\r\n"
  10773. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10774. suggest_connection_header(conn));
  10775. mg_printf(conn,
  10776. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10777. "<d:multistatus xmlns:d='DAV:'>\n");
  10778. /* Print properties for the requested resource itself */
  10779. print_props(conn, conn->request_info.local_uri, "", filep);
  10780. /* If it is a directory, print directory entries too if Depth is not 0
  10781. */
  10782. if (filep->is_directory
  10783. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10784. "yes")
  10785. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10786. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10787. }
  10788. mg_printf(conn, "%s\n", "</d:multistatus>");
  10789. }
  10790. #endif
  10791. void
  10792. mg_lock_connection(struct mg_connection *conn)
  10793. {
  10794. if (conn) {
  10795. (void)pthread_mutex_lock(&conn->mutex);
  10796. }
  10797. }
  10798. void
  10799. mg_unlock_connection(struct mg_connection *conn)
  10800. {
  10801. if (conn) {
  10802. (void)pthread_mutex_unlock(&conn->mutex);
  10803. }
  10804. }
  10805. void
  10806. mg_lock_context(struct mg_context *ctx)
  10807. {
  10808. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10809. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10810. }
  10811. }
  10812. void
  10813. mg_unlock_context(struct mg_context *ctx)
  10814. {
  10815. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10816. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10817. }
  10818. }
  10819. #if defined(USE_LUA)
  10820. #include "mod_lua.inl"
  10821. #endif /* USE_LUA */
  10822. #if defined(USE_DUKTAPE)
  10823. #include "mod_duktape.inl"
  10824. #endif /* USE_DUKTAPE */
  10825. #if defined(USE_WEBSOCKET)
  10826. #if !defined(NO_SSL_DL)
  10827. #define SHA_API static
  10828. #include "sha1.inl"
  10829. #endif
  10830. static int
  10831. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10832. {
  10833. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10834. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10835. SHA_CTX sha_ctx;
  10836. int truncated;
  10837. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10838. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10839. if (truncated) {
  10840. conn->must_close = 1;
  10841. return 0;
  10842. }
  10843. DEBUG_TRACE("%s", "Send websocket handshake");
  10844. SHA1_Init(&sha_ctx);
  10845. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10846. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10847. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10848. mg_printf(conn,
  10849. "HTTP/1.1 101 Switching Protocols\r\n"
  10850. "Upgrade: websocket\r\n"
  10851. "Connection: Upgrade\r\n"
  10852. "Sec-WebSocket-Accept: %s\r\n",
  10853. b64_sha);
  10854. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10855. mg_printf(conn,
  10856. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10857. conn->request_info.acceptedWebSocketSubprotocol);
  10858. } else {
  10859. mg_printf(conn, "%s", "\r\n");
  10860. }
  10861. return 1;
  10862. }
  10863. #if !defined(MG_MAX_UNANSWERED_PING)
  10864. /* Configuration of the maximum number of websocket PINGs that might
  10865. * stay unanswered before the connection is considered broken.
  10866. * Note: The name of this define may still change (until it is
  10867. * defined as a compile parameter in a documentation).
  10868. */
  10869. #define MG_MAX_UNANSWERED_PING (5)
  10870. #endif
  10871. static void
  10872. read_websocket(struct mg_connection *conn,
  10873. mg_websocket_data_handler ws_data_handler,
  10874. void *callback_data)
  10875. {
  10876. /* Pointer to the beginning of the portion of the incoming websocket
  10877. * message queue.
  10878. * The original websocket upgrade request is never removed, so the queue
  10879. * begins after it. */
  10880. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10881. int n, error, exit_by_callback;
  10882. int ret;
  10883. /* body_len is the length of the entire queue in bytes
  10884. * len is the length of the current message
  10885. * data_len is the length of the current message's data payload
  10886. * header_len is the length of the current message's header */
  10887. size_t i, len, mask_len = 0, header_len, body_len;
  10888. uint64_t data_len = 0;
  10889. /* "The masking key is a 32-bit value chosen at random by the client."
  10890. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10891. */
  10892. unsigned char mask[4];
  10893. /* data points to the place where the message is stored when passed to
  10894. * the websocket_data callback. This is either mem on the stack, or a
  10895. * dynamically allocated buffer if it is too large. */
  10896. unsigned char mem[4096];
  10897. unsigned char mop; /* mask flag and opcode */
  10898. /* Variables used for connection monitoring */
  10899. double timeout = -1.0;
  10900. int enable_ping_pong = 0;
  10901. int ping_count = 0;
  10902. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10903. enable_ping_pong =
  10904. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10905. "yes");
  10906. }
  10907. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10908. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10909. }
  10910. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10911. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10912. }
  10913. /* Enter data processing loop */
  10914. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10915. conn->request_info.remote_addr,
  10916. conn->request_info.remote_port);
  10917. conn->in_websocket_handling = 1;
  10918. mg_set_thread_name("wsock");
  10919. /* Loop continuously, reading messages from the socket, invoking the
  10920. * callback, and waiting repeatedly until an error occurs. */
  10921. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10922. && (!conn->must_close)) {
  10923. header_len = 0;
  10924. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10925. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10926. len = buf[1] & 127;
  10927. mask_len = (buf[1] & 128) ? 4 : 0;
  10928. if ((len < 126) && (body_len >= mask_len)) {
  10929. /* inline 7-bit length field */
  10930. data_len = len;
  10931. header_len = 2 + mask_len;
  10932. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10933. /* 16-bit length field */
  10934. header_len = 4 + mask_len;
  10935. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10936. } else if (body_len >= (10 + mask_len)) {
  10937. /* 64-bit length field */
  10938. uint32_t l1, l2;
  10939. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10940. memcpy(&l2, &buf[6], 4);
  10941. header_len = 10 + mask_len;
  10942. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10943. if (data_len > (uint64_t)0x7FFF0000ul) {
  10944. /* no can do */
  10945. mg_cry_internal(
  10946. conn,
  10947. "%s",
  10948. "websocket out of memory; closing connection");
  10949. break;
  10950. }
  10951. }
  10952. }
  10953. if ((header_len > 0) && (body_len >= header_len)) {
  10954. /* Allocate space to hold websocket payload */
  10955. unsigned char *data = mem;
  10956. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10957. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10958. conn->phys_ctx);
  10959. if (data == NULL) {
  10960. /* Allocation failed, exit the loop and then close the
  10961. * connection */
  10962. mg_cry_internal(
  10963. conn,
  10964. "%s",
  10965. "websocket out of memory; closing connection");
  10966. break;
  10967. }
  10968. }
  10969. /* Copy the mask before we shift the queue and destroy it */
  10970. if (mask_len > 0) {
  10971. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10972. } else {
  10973. memset(mask, 0, sizeof(mask));
  10974. }
  10975. /* Read frame payload from the first message in the queue into
  10976. * data and advance the queue by moving the memory in place. */
  10977. DEBUG_ASSERT(body_len >= header_len);
  10978. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10979. mop = buf[0]; /* current mask and opcode */
  10980. /* Overflow case */
  10981. len = body_len - header_len;
  10982. memcpy(data, buf + header_len, len);
  10983. error = 0;
  10984. while ((uint64_t)len < data_len) {
  10985. n = pull_inner(NULL,
  10986. conn,
  10987. (char *)(data + len),
  10988. (int)(data_len - len),
  10989. timeout);
  10990. if (n <= -2) {
  10991. error = 1;
  10992. break;
  10993. } else if (n > 0) {
  10994. len += (size_t)n;
  10995. } else {
  10996. /* Timeout: should retry */
  10997. /* TODO: retry condition */
  10998. }
  10999. }
  11000. if (error) {
  11001. mg_cry_internal(
  11002. conn,
  11003. "%s",
  11004. "Websocket pull failed; closing connection");
  11005. if (data != mem) {
  11006. mg_free(data);
  11007. }
  11008. break;
  11009. }
  11010. conn->data_len = conn->request_len;
  11011. } else {
  11012. mop = buf[0]; /* current mask and opcode, overwritten by
  11013. * memmove() */
  11014. /* Length of the message being read at the front of the
  11015. * queue. Cast to 31 bit is OK, since we limited
  11016. * data_len before. */
  11017. len = (size_t)data_len + header_len;
  11018. /* Copy the data payload into the data pointer for the
  11019. * callback. Cast to 31 bit is OK, since we
  11020. * limited data_len */
  11021. memcpy(data, buf + header_len, (size_t)data_len);
  11022. /* Move the queue forward len bytes */
  11023. memmove(buf, buf + len, body_len - len);
  11024. /* Mark the queue as advanced */
  11025. conn->data_len -= (int)len;
  11026. }
  11027. /* Apply mask if necessary */
  11028. if (mask_len > 0) {
  11029. for (i = 0; i < (size_t)data_len; i++) {
  11030. data[i] ^= mask[i & 3];
  11031. }
  11032. }
  11033. exit_by_callback = 0;
  11034. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11035. /* filter PONG messages */
  11036. DEBUG_TRACE("PONG from %s:%u",
  11037. conn->request_info.remote_addr,
  11038. conn->request_info.remote_port);
  11039. /* No unanwered PINGs left */
  11040. ping_count = 0;
  11041. } else if (enable_ping_pong
  11042. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11043. /* reply PING messages */
  11044. DEBUG_TRACE("Reply PING from %s:%u",
  11045. conn->request_info.remote_addr,
  11046. conn->request_info.remote_port);
  11047. ret = mg_websocket_write(conn,
  11048. MG_WEBSOCKET_OPCODE_PONG,
  11049. (char *)data,
  11050. (size_t)data_len);
  11051. if (ret <= 0) {
  11052. /* Error: send failed */
  11053. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11054. break;
  11055. }
  11056. } else {
  11057. /* Exit the loop if callback signals to exit (server side),
  11058. * or "connection close" opcode received (client side). */
  11059. if ((ws_data_handler != NULL)
  11060. && !ws_data_handler(conn,
  11061. mop,
  11062. (char *)data,
  11063. (size_t)data_len,
  11064. callback_data)) {
  11065. exit_by_callback = 1;
  11066. }
  11067. }
  11068. /* It a buffer has been allocated, free it again */
  11069. if (data != mem) {
  11070. mg_free(data);
  11071. }
  11072. if (exit_by_callback) {
  11073. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11074. conn->request_info.remote_addr,
  11075. conn->request_info.remote_port);
  11076. break;
  11077. }
  11078. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11079. /* Opcode == 8, connection close */
  11080. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11081. conn->request_info.remote_addr,
  11082. conn->request_info.remote_port);
  11083. break;
  11084. }
  11085. /* Not breaking the loop, process next websocket frame. */
  11086. } else {
  11087. /* Read from the socket into the next available location in the
  11088. * message queue. */
  11089. n = pull_inner(NULL,
  11090. conn,
  11091. conn->buf + conn->data_len,
  11092. conn->buf_size - conn->data_len,
  11093. timeout);
  11094. if (n <= -2) {
  11095. /* Error, no bytes read */
  11096. DEBUG_TRACE("PULL from %s:%u failed",
  11097. conn->request_info.remote_addr,
  11098. conn->request_info.remote_port);
  11099. break;
  11100. }
  11101. if (n > 0) {
  11102. conn->data_len += n;
  11103. /* Reset open PING count */
  11104. ping_count = 0;
  11105. } else {
  11106. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11107. && (!conn->must_close)) {
  11108. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11109. /* Stop sending PING */
  11110. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11111. "- closing connection",
  11112. ping_count,
  11113. conn->request_info.remote_addr,
  11114. conn->request_info.remote_port);
  11115. break;
  11116. }
  11117. if (enable_ping_pong) {
  11118. /* Send Websocket PING message */
  11119. DEBUG_TRACE("PING to %s:%u",
  11120. conn->request_info.remote_addr,
  11121. conn->request_info.remote_port);
  11122. ret = mg_websocket_write(conn,
  11123. MG_WEBSOCKET_OPCODE_PING,
  11124. NULL,
  11125. 0);
  11126. if (ret <= 0) {
  11127. /* Error: send failed */
  11128. DEBUG_TRACE("Send PING failed (%i)", ret);
  11129. break;
  11130. }
  11131. ping_count++;
  11132. }
  11133. }
  11134. /* Timeout: should retry */
  11135. /* TODO: get timeout def */
  11136. }
  11137. }
  11138. }
  11139. /* Leave data processing loop */
  11140. mg_set_thread_name("worker");
  11141. conn->in_websocket_handling = 0;
  11142. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11143. conn->request_info.remote_addr,
  11144. conn->request_info.remote_port);
  11145. }
  11146. static int
  11147. mg_websocket_write_exec(struct mg_connection *conn,
  11148. int opcode,
  11149. const char *data,
  11150. size_t dataLen,
  11151. uint32_t masking_key)
  11152. {
  11153. unsigned char header[14];
  11154. size_t headerLen;
  11155. int retval;
  11156. #if defined(GCC_DIAGNOSTIC)
  11157. /* Disable spurious conversion warning for GCC */
  11158. #pragma GCC diagnostic push
  11159. #pragma GCC diagnostic ignored "-Wconversion"
  11160. #endif
  11161. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11162. #if defined(GCC_DIAGNOSTIC)
  11163. #pragma GCC diagnostic pop
  11164. #endif
  11165. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11166. if (dataLen < 126) {
  11167. /* inline 7-bit length field */
  11168. header[1] = (unsigned char)dataLen;
  11169. headerLen = 2;
  11170. } else if (dataLen <= 0xFFFF) {
  11171. /* 16-bit length field */
  11172. uint16_t len = htons((uint16_t)dataLen);
  11173. header[1] = 126;
  11174. memcpy(header + 2, &len, 2);
  11175. headerLen = 4;
  11176. } else {
  11177. /* 64-bit length field */
  11178. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11179. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11180. header[1] = 127;
  11181. memcpy(header + 2, &len1, 4);
  11182. memcpy(header + 6, &len2, 4);
  11183. headerLen = 10;
  11184. }
  11185. if (masking_key) {
  11186. /* add mask */
  11187. header[1] |= 0x80;
  11188. memcpy(header + headerLen, &masking_key, 4);
  11189. headerLen += 4;
  11190. }
  11191. /* Note that POSIX/Winsock's send() is threadsafe
  11192. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11193. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11194. * push(), although that is only a problem if the packet is large or
  11195. * outgoing buffer is full). */
  11196. /* TODO: Check if this lock should be moved to user land.
  11197. * Currently the server sets this lock for websockets, but
  11198. * not for any other connection. It must be set for every
  11199. * conn read/written by more than one thread, no matter if
  11200. * it is a websocket or regular connection. */
  11201. (void)mg_lock_connection(conn);
  11202. retval = mg_write(conn, header, headerLen);
  11203. if (retval != (int)headerLen) {
  11204. /* Did not send complete header */
  11205. retval = -1;
  11206. } else {
  11207. if (dataLen > 0) {
  11208. retval = mg_write(conn, data, dataLen);
  11209. }
  11210. /* if dataLen == 0, the header length (2) is returned */
  11211. }
  11212. /* TODO: Remove this unlock as well, when lock is removed. */
  11213. mg_unlock_connection(conn);
  11214. return retval;
  11215. }
  11216. int
  11217. mg_websocket_write(struct mg_connection *conn,
  11218. int opcode,
  11219. const char *data,
  11220. size_t dataLen)
  11221. {
  11222. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11223. }
  11224. static void
  11225. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11226. {
  11227. size_t i = 0;
  11228. i = 0;
  11229. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11230. /* Convert in 32 bit words, if data is 4 byte aligned */
  11231. while (i < (in_len - 3)) {
  11232. *(uint32_t *)(void *)(out + i) =
  11233. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11234. i += 4;
  11235. }
  11236. }
  11237. if (i != in_len) {
  11238. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11239. while (i < in_len) {
  11240. *(uint8_t *)(void *)(out + i) =
  11241. *(uint8_t *)(void *)(in + i)
  11242. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11243. i++;
  11244. }
  11245. }
  11246. }
  11247. int
  11248. mg_websocket_client_write(struct mg_connection *conn,
  11249. int opcode,
  11250. const char *data,
  11251. size_t dataLen)
  11252. {
  11253. int retval = -1;
  11254. char *masked_data =
  11255. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11256. uint32_t masking_key = 0;
  11257. if (masked_data == NULL) {
  11258. /* Return -1 in an error case */
  11259. mg_cry_internal(conn,
  11260. "%s",
  11261. "Cannot allocate buffer for masked websocket response: "
  11262. "Out of memory");
  11263. return -1;
  11264. }
  11265. do {
  11266. /* Get a masking key - but not 0 */
  11267. masking_key = (uint32_t)get_random();
  11268. } while (masking_key == 0);
  11269. mask_data(data, dataLen, masking_key, masked_data);
  11270. retval = mg_websocket_write_exec(
  11271. conn, opcode, masked_data, dataLen, masking_key);
  11272. mg_free(masked_data);
  11273. return retval;
  11274. }
  11275. static void
  11276. handle_websocket_request(struct mg_connection *conn,
  11277. const char *path,
  11278. int is_callback_resource,
  11279. struct mg_websocket_subprotocols *subprotocols,
  11280. mg_websocket_connect_handler ws_connect_handler,
  11281. mg_websocket_ready_handler ws_ready_handler,
  11282. mg_websocket_data_handler ws_data_handler,
  11283. mg_websocket_close_handler ws_close_handler,
  11284. void *cbData)
  11285. {
  11286. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11287. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11288. ptrdiff_t lua_websock = 0;
  11289. #if !defined(USE_LUA)
  11290. (void)path;
  11291. #endif
  11292. /* Step 1: Check websocket protocol version. */
  11293. /* Step 1.1: Check Sec-WebSocket-Key. */
  11294. if (!websock_key) {
  11295. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11296. * requires a Sec-WebSocket-Key header.
  11297. */
  11298. /* It could be the hixie draft version
  11299. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11300. */
  11301. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11302. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11303. char key3[8];
  11304. if ((key1 != NULL) && (key2 != NULL)) {
  11305. /* This version uses 8 byte body data in a GET request */
  11306. conn->content_len = 8;
  11307. if (8 == mg_read(conn, key3, 8)) {
  11308. /* This is the hixie version */
  11309. mg_send_http_error(conn,
  11310. 426,
  11311. "%s",
  11312. "Protocol upgrade to RFC 6455 required");
  11313. return;
  11314. }
  11315. }
  11316. /* This is an unknown version */
  11317. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11318. return;
  11319. }
  11320. /* Step 1.2: Check websocket protocol version. */
  11321. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11322. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11323. /* Reject wrong versions */
  11324. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11325. return;
  11326. }
  11327. /* Step 1.3: Could check for "Host", but we do not really nead this
  11328. * value for anything, so just ignore it. */
  11329. /* Step 2: If a callback is responsible, call it. */
  11330. if (is_callback_resource) {
  11331. /* Step 2.1 check and select subprotocol */
  11332. const char *protocols[64]; // max 64 headers
  11333. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11334. "Sec-WebSocket-Protocol",
  11335. protocols,
  11336. 64);
  11337. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11338. int cnt = 0;
  11339. int idx;
  11340. unsigned long len;
  11341. const char *sep, *curSubProtocol,
  11342. *acceptedWebSocketSubprotocol = NULL;
  11343. /* look for matching subprotocol */
  11344. do {
  11345. const char *protocol = protocols[cnt];
  11346. do {
  11347. sep = strchr(protocol, ',');
  11348. curSubProtocol = protocol;
  11349. len = sep ? (unsigned long)(sep - protocol)
  11350. : (unsigned long)strlen(protocol);
  11351. while (sep && isspace((unsigned char)*++sep))
  11352. ; // ignore leading whitespaces
  11353. protocol = sep;
  11354. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11355. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11356. && (strncmp(curSubProtocol,
  11357. subprotocols->subprotocols[idx],
  11358. len)
  11359. == 0)) {
  11360. acceptedWebSocketSubprotocol =
  11361. subprotocols->subprotocols[idx];
  11362. break;
  11363. }
  11364. }
  11365. } while (sep && !acceptedWebSocketSubprotocol);
  11366. } while (++cnt < nbSubprotocolHeader
  11367. && !acceptedWebSocketSubprotocol);
  11368. conn->request_info.acceptedWebSocketSubprotocol =
  11369. acceptedWebSocketSubprotocol;
  11370. } else if (nbSubprotocolHeader > 0) {
  11371. /* keep legacy behavior */
  11372. const char *protocol = protocols[0];
  11373. /* The protocol is a comma separated list of names. */
  11374. /* The server must only return one value from this list. */
  11375. /* First check if it is a list or just a single value. */
  11376. const char *sep = strrchr(protocol, ',');
  11377. if (sep == NULL) {
  11378. /* Just a single protocol -> accept it. */
  11379. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11380. } else {
  11381. /* Multiple protocols -> accept the last one. */
  11382. /* This is just a quick fix if the client offers multiple
  11383. * protocols. The handler should have a list of accepted
  11384. * protocols on his own
  11385. * and use it to select one protocol among those the client
  11386. * has
  11387. * offered.
  11388. */
  11389. while (isspace((unsigned char)*++sep)) {
  11390. ; /* ignore leading whitespaces */
  11391. }
  11392. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11393. }
  11394. }
  11395. if ((ws_connect_handler != NULL)
  11396. && (ws_connect_handler(conn, cbData) != 0)) {
  11397. /* C callback has returned non-zero, do not proceed with
  11398. * handshake.
  11399. */
  11400. /* Note that C callbacks are no longer called when Lua is
  11401. * responsible, so C can no longer filter callbacks for Lua. */
  11402. return;
  11403. }
  11404. }
  11405. #if defined(USE_LUA)
  11406. /* Step 3: No callback. Check if Lua is responsible. */
  11407. else {
  11408. /* Step 3.1: Check if Lua is responsible. */
  11409. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11410. lua_websock = match_prefix(
  11411. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11412. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11413. path);
  11414. }
  11415. if (lua_websock) {
  11416. /* Step 3.2: Lua is responsible: call it. */
  11417. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11418. if (!conn->lua_websocket_state) {
  11419. /* Lua rejected the new client */
  11420. return;
  11421. }
  11422. }
  11423. }
  11424. #endif
  11425. /* Step 4: Check if there is a responsible websocket handler. */
  11426. if (!is_callback_resource && !lua_websock) {
  11427. /* There is no callback, and Lua is not responsible either. */
  11428. /* Reply with a 404 Not Found. We are still at a standard
  11429. * HTTP request here, before the websocket handshake, so
  11430. * we can still send standard HTTP error replies. */
  11431. mg_send_http_error(conn, 404, "%s", "Not found");
  11432. return;
  11433. }
  11434. /* Step 5: The websocket connection has been accepted */
  11435. if (!send_websocket_handshake(conn, websock_key)) {
  11436. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11437. return;
  11438. }
  11439. /* Step 6: Call the ready handler */
  11440. if (is_callback_resource) {
  11441. if (ws_ready_handler != NULL) {
  11442. ws_ready_handler(conn, cbData);
  11443. }
  11444. #if defined(USE_LUA)
  11445. } else if (lua_websock) {
  11446. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11447. /* the ready handler returned false */
  11448. return;
  11449. }
  11450. #endif
  11451. }
  11452. /* Step 7: Enter the read loop */
  11453. if (is_callback_resource) {
  11454. read_websocket(conn, ws_data_handler, cbData);
  11455. #if defined(USE_LUA)
  11456. } else if (lua_websock) {
  11457. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11458. #endif
  11459. }
  11460. /* Step 8: Call the close handler */
  11461. if (ws_close_handler) {
  11462. ws_close_handler(conn, cbData);
  11463. }
  11464. }
  11465. #endif /* !USE_WEBSOCKET */
  11466. /* Is upgrade request:
  11467. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11468. * 1 = upgrade to websocket
  11469. * 2 = upgrade to HTTP/2
  11470. * -1 = upgrade to unknown protocol
  11471. */
  11472. static int
  11473. should_switch_to_protocol(const struct mg_connection *conn)
  11474. {
  11475. const char *upgrade, *connection;
  11476. /* A websocket protocoll has the following HTTP headers:
  11477. *
  11478. * Connection: Upgrade
  11479. * Upgrade: Websocket
  11480. */
  11481. connection = mg_get_header(conn, "Connection");
  11482. if (connection == NULL) {
  11483. return PROTOCOL_TYPE_HTTP1;
  11484. }
  11485. if (!mg_strcasestr(connection, "upgrade")) {
  11486. return PROTOCOL_TYPE_HTTP1;
  11487. }
  11488. upgrade = mg_get_header(conn, "Upgrade");
  11489. if (upgrade == NULL) {
  11490. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11491. return -1;
  11492. }
  11493. /* Upgrade to ... */
  11494. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11495. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11496. * "Sec-WebSocket-Version" are also required.
  11497. * Don't check them here, since even an unsupported websocket protocol
  11498. * request still IS a websocket request (in contrast to a standard HTTP
  11499. * request). It will fail later in handle_websocket_request.
  11500. */
  11501. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11502. }
  11503. if (0 != mg_strcasestr(upgrade, "h2")) {
  11504. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11505. }
  11506. /* Upgrade to another protocol */
  11507. return -1;
  11508. }
  11509. static int
  11510. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11511. {
  11512. int n;
  11513. unsigned int a, b, c, d, slash;
  11514. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11515. slash = 32;
  11516. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11517. n = 0;
  11518. }
  11519. }
  11520. if ((n > 0) && ((size_t)n == vec->len)) {
  11521. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11522. /* IPv4 format */
  11523. if (sa->sa.sa_family == AF_INET) {
  11524. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11525. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11526. | ((uint32_t)c << 8) | (uint32_t)d;
  11527. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11528. return (ip & mask) == net;
  11529. }
  11530. return 0;
  11531. }
  11532. }
  11533. #if defined(USE_IPV6)
  11534. else {
  11535. char ad[50];
  11536. const char *p;
  11537. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11538. slash = 128;
  11539. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11540. n = 0;
  11541. }
  11542. }
  11543. if ((n <= 0) && no_strict) {
  11544. /* no square brackets? */
  11545. p = strchr(vec->ptr, '/');
  11546. if (p && (p < (vec->ptr + vec->len))) {
  11547. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11548. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11549. n += (int)(p - vec->ptr);
  11550. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11551. } else {
  11552. n = 0;
  11553. }
  11554. } else if (vec->len < sizeof(ad)) {
  11555. n = (int)vec->len;
  11556. slash = 128;
  11557. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11558. }
  11559. }
  11560. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11561. p = ad;
  11562. c = 0;
  11563. /* zone indexes are unsupported, at least two colons are needed */
  11564. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11565. if (*(p++) == ':') {
  11566. c++;
  11567. }
  11568. }
  11569. if ((*p == '\0') && (c >= 2)) {
  11570. struct sockaddr_in6 sin6;
  11571. unsigned int i;
  11572. /* for strict validation, an actual IPv6 argument is needed */
  11573. if (sa->sa.sa_family != AF_INET6) {
  11574. return 0;
  11575. }
  11576. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11577. /* IPv6 format */
  11578. for (i = 0; i < 16; i++) {
  11579. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11580. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11581. uint8_t mask = 0;
  11582. if (8 * i + 8 < slash) {
  11583. mask = 0xFFu;
  11584. } else if (8 * i < slash) {
  11585. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11586. }
  11587. if ((ip & mask) != net) {
  11588. return 0;
  11589. }
  11590. }
  11591. return 1;
  11592. }
  11593. }
  11594. }
  11595. }
  11596. #else
  11597. (void)no_strict;
  11598. #endif
  11599. /* malformed */
  11600. return -1;
  11601. }
  11602. static int
  11603. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11604. {
  11605. int throttle = 0;
  11606. struct vec vec, val;
  11607. char mult;
  11608. double v;
  11609. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11610. mult = ',';
  11611. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11612. || (v < 0)
  11613. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11614. && (mult != ','))) {
  11615. continue;
  11616. }
  11617. v *= (lowercase(&mult) == 'k')
  11618. ? 1024
  11619. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11620. if (vec.len == 1 && vec.ptr[0] == '*') {
  11621. throttle = (int)v;
  11622. } else {
  11623. int matched = parse_match_net(&vec, rsa, 0);
  11624. if (matched >= 0) {
  11625. /* a valid IP subnet */
  11626. if (matched) {
  11627. throttle = (int)v;
  11628. }
  11629. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11630. throttle = (int)v;
  11631. }
  11632. }
  11633. }
  11634. return throttle;
  11635. }
  11636. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11637. #include "handle_form.inl"
  11638. #if defined(MG_LEGACY_INTERFACE)
  11639. /* Implement the deprecated mg_upload function by calling the new
  11640. * mg_handle_form_request function. While mg_upload could only handle
  11641. * HTML forms sent as POST request in multipart/form-data format
  11642. * containing only file input elements, mg_handle_form_request can
  11643. * handle all form input elements and all standard request methods. */
  11644. struct mg_upload_user_data {
  11645. struct mg_connection *conn;
  11646. const char *destination_dir;
  11647. int num_uploaded_files;
  11648. };
  11649. /* Helper function for deprecated mg_upload. */
  11650. static int
  11651. mg_upload_field_found(const char *key,
  11652. const char *filename,
  11653. char *path,
  11654. size_t pathlen,
  11655. void *user_data)
  11656. {
  11657. int truncated = 0;
  11658. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11659. (void)key;
  11660. if (!filename) {
  11661. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11662. return FORM_FIELD_STORAGE_ABORT;
  11663. }
  11664. mg_snprintf(fud->conn,
  11665. &truncated,
  11666. path,
  11667. pathlen - 1,
  11668. "%s/%s",
  11669. fud->destination_dir,
  11670. filename);
  11671. if (truncated) {
  11672. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11673. return FORM_FIELD_STORAGE_ABORT;
  11674. }
  11675. return FORM_FIELD_STORAGE_STORE;
  11676. }
  11677. /* Helper function for deprecated mg_upload. */
  11678. static int
  11679. mg_upload_field_get(const char *key,
  11680. const char *value,
  11681. size_t value_size,
  11682. void *user_data)
  11683. {
  11684. /* Function should never be called */
  11685. (void)key;
  11686. (void)value;
  11687. (void)value_size;
  11688. (void)user_data;
  11689. return 0;
  11690. }
  11691. /* Helper function for deprecated mg_upload. */
  11692. static int
  11693. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11694. {
  11695. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11696. (void)file_size;
  11697. fud->num_uploaded_files++;
  11698. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11699. return 0;
  11700. }
  11701. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11702. int
  11703. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11704. {
  11705. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11706. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11707. mg_upload_field_get,
  11708. mg_upload_field_stored,
  11709. 0};
  11710. int ret;
  11711. fdh.user_data = (void *)&fud;
  11712. ret = mg_handle_form_request(conn, &fdh);
  11713. if (ret < 0) {
  11714. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11715. }
  11716. return fud.num_uploaded_files;
  11717. }
  11718. #endif
  11719. static int
  11720. get_first_ssl_listener_index(const struct mg_context *ctx)
  11721. {
  11722. unsigned int i;
  11723. int idx = -1;
  11724. if (ctx) {
  11725. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11726. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11727. }
  11728. }
  11729. return idx;
  11730. }
  11731. /* Return host (without port) */
  11732. static void
  11733. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11734. {
  11735. const char *host_header =
  11736. get_header(ri->http_headers, ri->num_headers, "Host");
  11737. host->ptr = NULL;
  11738. host->len = 0;
  11739. if (host_header != NULL) {
  11740. char *pos;
  11741. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11742. * is found. */
  11743. if (*host_header == '[') {
  11744. pos = strchr(host_header, ']');
  11745. if (!pos) {
  11746. /* Malformed hostname starts with '[', but no ']' found */
  11747. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11748. return;
  11749. }
  11750. /* terminate after ']' */
  11751. host->ptr = host_header;
  11752. host->len = (size_t)(pos + 1 - host_header);
  11753. } else {
  11754. /* Otherwise, a ':' separates hostname and port number */
  11755. pos = strchr(host_header, ':');
  11756. if (pos != NULL) {
  11757. host->len = (size_t)(pos - host_header);
  11758. } else {
  11759. host->len = strlen(host_header);
  11760. }
  11761. host->ptr = host_header;
  11762. }
  11763. }
  11764. }
  11765. static int
  11766. switch_domain_context(struct mg_connection *conn)
  11767. {
  11768. struct vec host;
  11769. get_host_from_request_info(&host, &conn->request_info);
  11770. if (host.ptr) {
  11771. if (conn->ssl) {
  11772. /* This is a HTTPS connection, maybe we have a hostname
  11773. * from SNI (set in ssl_servername_callback). */
  11774. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11775. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11776. /* We are not using the default domain */
  11777. if ((strlen(sslhost) != host.len)
  11778. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11779. /* Mismatch between SNI domain and HTTP domain */
  11780. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11781. sslhost,
  11782. (int)host.len,
  11783. host.ptr);
  11784. return 0;
  11785. }
  11786. }
  11787. } else {
  11788. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11789. while (dom) {
  11790. if ((strlen(dom->config[AUTHENTICATION_DOMAIN]) == host.len)
  11791. && !mg_strncasecmp(host.ptr,
  11792. dom->config[AUTHENTICATION_DOMAIN],
  11793. host.len)) {
  11794. /* Found matching domain */
  11795. DEBUG_TRACE("HTTP domain %s found",
  11796. dom->config[AUTHENTICATION_DOMAIN]);
  11797. /* TODO: Check if this is a HTTP or HTTPS domain */
  11798. conn->dom_ctx = dom;
  11799. break;
  11800. }
  11801. mg_lock_context(conn->phys_ctx);
  11802. dom = dom->next;
  11803. mg_unlock_context(conn->phys_ctx);
  11804. }
  11805. }
  11806. } else {
  11807. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11808. return 1;
  11809. }
  11810. DEBUG_TRACE("HTTP%s Host: %.*s",
  11811. conn->ssl ? "S" : "",
  11812. (int)host.len,
  11813. host.ptr);
  11814. return 1;
  11815. }
  11816. static void
  11817. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11818. {
  11819. struct vec host;
  11820. char target_url[MG_BUF_LEN];
  11821. int truncated = 0;
  11822. conn->must_close = 1;
  11823. /* Send host, port, uri and (if it exists) ?query_string */
  11824. get_host_from_request_info(&host, &conn->request_info);
  11825. if (host.ptr) {
  11826. /* Use "308 Permanent Redirect" */
  11827. int redirect_code = 308;
  11828. /* Create target URL */
  11829. mg_snprintf(
  11830. conn,
  11831. &truncated,
  11832. target_url,
  11833. sizeof(target_url),
  11834. "https://%.*s:%d%s%s%s",
  11835. (int)host.len,
  11836. host.ptr,
  11837. #if defined(USE_IPV6)
  11838. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11839. == AF_INET6)
  11840. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11841. .lsa.sin6.sin6_port)
  11842. :
  11843. #endif
  11844. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11845. .lsa.sin.sin_port),
  11846. conn->request_info.local_uri,
  11847. (conn->request_info.query_string == NULL) ? "" : "?",
  11848. (conn->request_info.query_string == NULL)
  11849. ? ""
  11850. : conn->request_info.query_string);
  11851. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11852. * is used as buffer size) */
  11853. if (truncated) {
  11854. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11855. return;
  11856. }
  11857. /* Use redirect helper function */
  11858. mg_send_http_redirect(conn, target_url, redirect_code);
  11859. } else {
  11860. mg_send_http_error(conn, 400, "%s", "Bad Request");
  11861. }
  11862. }
  11863. static void
  11864. mg_set_handler_type(struct mg_context *phys_ctx,
  11865. struct mg_domain_context *dom_ctx,
  11866. const char *uri,
  11867. int handler_type,
  11868. int is_delete_request,
  11869. mg_request_handler handler,
  11870. struct mg_websocket_subprotocols *subprotocols,
  11871. mg_websocket_connect_handler connect_handler,
  11872. mg_websocket_ready_handler ready_handler,
  11873. mg_websocket_data_handler data_handler,
  11874. mg_websocket_close_handler close_handler,
  11875. mg_authorization_handler auth_handler,
  11876. void *cbdata)
  11877. {
  11878. struct mg_handler_info *tmp_rh, **lastref;
  11879. size_t urilen = strlen(uri);
  11880. if (handler_type == WEBSOCKET_HANDLER) {
  11881. DEBUG_ASSERT(handler == NULL);
  11882. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11883. || ready_handler != NULL || data_handler != NULL
  11884. || close_handler != NULL);
  11885. DEBUG_ASSERT(auth_handler == NULL);
  11886. if (handler != NULL) {
  11887. return;
  11888. }
  11889. if (!is_delete_request && (connect_handler == NULL)
  11890. && (ready_handler == NULL) && (data_handler == NULL)
  11891. && (close_handler == NULL)) {
  11892. return;
  11893. }
  11894. if (auth_handler != NULL) {
  11895. return;
  11896. }
  11897. } else if (handler_type == REQUEST_HANDLER) {
  11898. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11899. && data_handler == NULL && close_handler == NULL);
  11900. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11901. DEBUG_ASSERT(auth_handler == NULL);
  11902. if ((connect_handler != NULL) || (ready_handler != NULL)
  11903. || (data_handler != NULL) || (close_handler != NULL)) {
  11904. return;
  11905. }
  11906. if (!is_delete_request && (handler == NULL)) {
  11907. return;
  11908. }
  11909. if (auth_handler != NULL) {
  11910. return;
  11911. }
  11912. } else { /* AUTH_HANDLER */
  11913. DEBUG_ASSERT(handler == NULL);
  11914. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11915. && data_handler == NULL && close_handler == NULL);
  11916. DEBUG_ASSERT(auth_handler != NULL);
  11917. if (handler != NULL) {
  11918. return;
  11919. }
  11920. if ((connect_handler != NULL) || (ready_handler != NULL)
  11921. || (data_handler != NULL) || (close_handler != NULL)) {
  11922. return;
  11923. }
  11924. if (!is_delete_request && (auth_handler == NULL)) {
  11925. return;
  11926. }
  11927. }
  11928. if (!phys_ctx || !dom_ctx) {
  11929. return;
  11930. }
  11931. mg_lock_context(phys_ctx);
  11932. /* first try to find an existing handler */
  11933. do {
  11934. lastref = &(dom_ctx->handlers);
  11935. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11936. tmp_rh = tmp_rh->next) {
  11937. if (tmp_rh->handler_type == handler_type
  11938. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11939. if (!is_delete_request) {
  11940. /* update existing handler */
  11941. if (handler_type == REQUEST_HANDLER) {
  11942. /* Wait for end of use before updating */
  11943. if (tmp_rh->refcount) {
  11944. mg_unlock_context(phys_ctx);
  11945. mg_sleep(1);
  11946. mg_lock_context(phys_ctx);
  11947. /* tmp_rh might have been freed, search again. */
  11948. break;
  11949. }
  11950. /* Ok, the handler is no more use -> Update it */
  11951. tmp_rh->handler = handler;
  11952. } else if (handler_type == WEBSOCKET_HANDLER) {
  11953. tmp_rh->subprotocols = subprotocols;
  11954. tmp_rh->connect_handler = connect_handler;
  11955. tmp_rh->ready_handler = ready_handler;
  11956. tmp_rh->data_handler = data_handler;
  11957. tmp_rh->close_handler = close_handler;
  11958. } else { /* AUTH_HANDLER */
  11959. tmp_rh->auth_handler = auth_handler;
  11960. }
  11961. tmp_rh->cbdata = cbdata;
  11962. } else {
  11963. /* remove existing handler */
  11964. if (handler_type == REQUEST_HANDLER) {
  11965. /* Wait for end of use before removing */
  11966. if (tmp_rh->refcount) {
  11967. tmp_rh->removing = 1;
  11968. mg_unlock_context(phys_ctx);
  11969. mg_sleep(1);
  11970. mg_lock_context(phys_ctx);
  11971. /* tmp_rh might have been freed, search again. */
  11972. break;
  11973. }
  11974. /* Ok, the handler is no more used */
  11975. }
  11976. *lastref = tmp_rh->next;
  11977. mg_free(tmp_rh->uri);
  11978. mg_free(tmp_rh);
  11979. }
  11980. mg_unlock_context(phys_ctx);
  11981. return;
  11982. }
  11983. lastref = &(tmp_rh->next);
  11984. }
  11985. } while (tmp_rh != NULL);
  11986. if (is_delete_request) {
  11987. /* no handler to set, this was a remove request to a non-existing
  11988. * handler */
  11989. mg_unlock_context(phys_ctx);
  11990. return;
  11991. }
  11992. tmp_rh =
  11993. (struct mg_handler_info *)mg_calloc_ctx(1,
  11994. sizeof(struct mg_handler_info),
  11995. phys_ctx);
  11996. if (tmp_rh == NULL) {
  11997. mg_unlock_context(phys_ctx);
  11998. mg_cry_ctx_internal(phys_ctx,
  11999. "%s",
  12000. "Cannot create new request handler struct, OOM");
  12001. return;
  12002. }
  12003. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12004. if (!tmp_rh->uri) {
  12005. mg_unlock_context(phys_ctx);
  12006. mg_free(tmp_rh);
  12007. mg_cry_ctx_internal(phys_ctx,
  12008. "%s",
  12009. "Cannot create new request handler struct, OOM");
  12010. return;
  12011. }
  12012. tmp_rh->uri_len = urilen;
  12013. if (handler_type == REQUEST_HANDLER) {
  12014. tmp_rh->refcount = 0;
  12015. tmp_rh->removing = 0;
  12016. tmp_rh->handler = handler;
  12017. } else if (handler_type == WEBSOCKET_HANDLER) {
  12018. tmp_rh->subprotocols = subprotocols;
  12019. tmp_rh->connect_handler = connect_handler;
  12020. tmp_rh->ready_handler = ready_handler;
  12021. tmp_rh->data_handler = data_handler;
  12022. tmp_rh->close_handler = close_handler;
  12023. } else { /* AUTH_HANDLER */
  12024. tmp_rh->auth_handler = auth_handler;
  12025. }
  12026. tmp_rh->cbdata = cbdata;
  12027. tmp_rh->handler_type = handler_type;
  12028. tmp_rh->next = NULL;
  12029. *lastref = tmp_rh;
  12030. mg_unlock_context(phys_ctx);
  12031. }
  12032. void
  12033. mg_set_request_handler(struct mg_context *ctx,
  12034. const char *uri,
  12035. mg_request_handler handler,
  12036. void *cbdata)
  12037. {
  12038. mg_set_handler_type(ctx,
  12039. &(ctx->dd),
  12040. uri,
  12041. REQUEST_HANDLER,
  12042. handler == NULL,
  12043. handler,
  12044. NULL,
  12045. NULL,
  12046. NULL,
  12047. NULL,
  12048. NULL,
  12049. NULL,
  12050. cbdata);
  12051. }
  12052. void
  12053. mg_set_websocket_handler(struct mg_context *ctx,
  12054. const char *uri,
  12055. mg_websocket_connect_handler connect_handler,
  12056. mg_websocket_ready_handler ready_handler,
  12057. mg_websocket_data_handler data_handler,
  12058. mg_websocket_close_handler close_handler,
  12059. void *cbdata)
  12060. {
  12061. mg_set_websocket_handler_with_subprotocols(ctx,
  12062. uri,
  12063. NULL,
  12064. connect_handler,
  12065. ready_handler,
  12066. data_handler,
  12067. close_handler,
  12068. cbdata);
  12069. }
  12070. void
  12071. mg_set_websocket_handler_with_subprotocols(
  12072. struct mg_context *ctx,
  12073. const char *uri,
  12074. struct mg_websocket_subprotocols *subprotocols,
  12075. mg_websocket_connect_handler connect_handler,
  12076. mg_websocket_ready_handler ready_handler,
  12077. mg_websocket_data_handler data_handler,
  12078. mg_websocket_close_handler close_handler,
  12079. void *cbdata)
  12080. {
  12081. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12082. && (data_handler == NULL)
  12083. && (close_handler == NULL);
  12084. mg_set_handler_type(ctx,
  12085. &(ctx->dd),
  12086. uri,
  12087. WEBSOCKET_HANDLER,
  12088. is_delete_request,
  12089. NULL,
  12090. subprotocols,
  12091. connect_handler,
  12092. ready_handler,
  12093. data_handler,
  12094. close_handler,
  12095. NULL,
  12096. cbdata);
  12097. }
  12098. void
  12099. mg_set_auth_handler(struct mg_context *ctx,
  12100. const char *uri,
  12101. mg_authorization_handler handler,
  12102. void *cbdata)
  12103. {
  12104. mg_set_handler_type(ctx,
  12105. &(ctx->dd),
  12106. uri,
  12107. AUTH_HANDLER,
  12108. handler == NULL,
  12109. NULL,
  12110. NULL,
  12111. NULL,
  12112. NULL,
  12113. NULL,
  12114. NULL,
  12115. handler,
  12116. cbdata);
  12117. }
  12118. static int
  12119. get_request_handler(struct mg_connection *conn,
  12120. int handler_type,
  12121. mg_request_handler *handler,
  12122. struct mg_websocket_subprotocols **subprotocols,
  12123. mg_websocket_connect_handler *connect_handler,
  12124. mg_websocket_ready_handler *ready_handler,
  12125. mg_websocket_data_handler *data_handler,
  12126. mg_websocket_close_handler *close_handler,
  12127. mg_authorization_handler *auth_handler,
  12128. void **cbdata,
  12129. struct mg_handler_info **handler_info)
  12130. {
  12131. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12132. if (request_info) {
  12133. const char *uri = request_info->local_uri;
  12134. size_t urilen = strlen(uri);
  12135. struct mg_handler_info *tmp_rh;
  12136. int step, matched;
  12137. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12138. return 0;
  12139. }
  12140. mg_lock_context(conn->phys_ctx);
  12141. for (step = 0; step < 3; step++) {
  12142. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12143. tmp_rh = tmp_rh->next) {
  12144. if (tmp_rh->handler_type != handler_type) {
  12145. continue;
  12146. }
  12147. if (step == 0) {
  12148. /* first try for an exact match */
  12149. matched = (tmp_rh->uri_len == urilen)
  12150. && (strcmp(tmp_rh->uri, uri) == 0);
  12151. } else if (step == 1) {
  12152. /* next try for a partial match, we will accept
  12153. uri/something */
  12154. matched =
  12155. (tmp_rh->uri_len < urilen)
  12156. && (uri[tmp_rh->uri_len] == '/')
  12157. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12158. } else {
  12159. /* finally try for pattern match */
  12160. matched =
  12161. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12162. }
  12163. if (matched) {
  12164. if (handler_type == WEBSOCKET_HANDLER) {
  12165. *subprotocols = tmp_rh->subprotocols;
  12166. *connect_handler = tmp_rh->connect_handler;
  12167. *ready_handler = tmp_rh->ready_handler;
  12168. *data_handler = tmp_rh->data_handler;
  12169. *close_handler = tmp_rh->close_handler;
  12170. } else if (handler_type == REQUEST_HANDLER) {
  12171. if (tmp_rh->removing) {
  12172. /* Treat as none found */
  12173. step = 2;
  12174. break;
  12175. }
  12176. *handler = tmp_rh->handler;
  12177. /* Acquire handler and give it back */
  12178. tmp_rh->refcount++;
  12179. *handler_info = tmp_rh;
  12180. } else { /* AUTH_HANDLER */
  12181. *auth_handler = tmp_rh->auth_handler;
  12182. }
  12183. *cbdata = tmp_rh->cbdata;
  12184. mg_unlock_context(conn->phys_ctx);
  12185. return 1;
  12186. }
  12187. }
  12188. }
  12189. mg_unlock_context(conn->phys_ctx);
  12190. }
  12191. return 0; /* none found */
  12192. }
  12193. /* Check if the script file is in a path, allowed for script files.
  12194. * This can be used if uploading files is possible not only for the server
  12195. * admin, and the upload mechanism does not check the file extension.
  12196. */
  12197. static int
  12198. is_in_script_path(const struct mg_connection *conn, const char *path)
  12199. {
  12200. /* TODO (Feature): Add config value for allowed script path.
  12201. * Default: All allowed. */
  12202. (void)conn;
  12203. (void)path;
  12204. return 1;
  12205. }
  12206. #if defined(USE_WEBSOCKET) \
  12207. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12208. static int
  12209. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12210. void *cbdata)
  12211. {
  12212. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12213. if (pcallbacks->websocket_connect) {
  12214. return pcallbacks->websocket_connect(conn);
  12215. }
  12216. /* No handler set - assume "OK" */
  12217. return 0;
  12218. }
  12219. static void
  12220. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12221. {
  12222. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12223. if (pcallbacks->websocket_ready) {
  12224. pcallbacks->websocket_ready(conn);
  12225. }
  12226. }
  12227. static int
  12228. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12229. int bits,
  12230. char *data,
  12231. size_t len,
  12232. void *cbdata)
  12233. {
  12234. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12235. if (pcallbacks->websocket_data) {
  12236. return pcallbacks->websocket_data(conn, bits, data, len);
  12237. }
  12238. /* No handler set - assume "OK" */
  12239. return 1;
  12240. }
  12241. static void
  12242. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12243. void *cbdata)
  12244. {
  12245. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12246. if (pcallbacks->connection_close) {
  12247. pcallbacks->connection_close(conn);
  12248. }
  12249. }
  12250. #endif
  12251. /* This is the heart of the Civetweb's logic.
  12252. * This function is called when the request is read, parsed and validated,
  12253. * and Civetweb must decide what action to take: serve a file, or
  12254. * a directory, or call embedded function, etcetera. */
  12255. static void
  12256. handle_request(struct mg_connection *conn)
  12257. {
  12258. struct mg_request_info *ri = &conn->request_info;
  12259. char path[PATH_MAX];
  12260. int uri_len, ssl_index;
  12261. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12262. is_put_or_delete_request = 0, is_callback_resource = 0;
  12263. int i;
  12264. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12265. mg_request_handler callback_handler = NULL;
  12266. struct mg_handler_info *handler_info = NULL;
  12267. struct mg_websocket_subprotocols *subprotocols;
  12268. mg_websocket_connect_handler ws_connect_handler = NULL;
  12269. mg_websocket_ready_handler ws_ready_handler = NULL;
  12270. mg_websocket_data_handler ws_data_handler = NULL;
  12271. mg_websocket_close_handler ws_close_handler = NULL;
  12272. void *callback_data = NULL;
  12273. mg_authorization_handler auth_handler = NULL;
  12274. void *auth_callback_data = NULL;
  12275. int handler_type;
  12276. time_t curtime = time(NULL);
  12277. char date[64];
  12278. path[0] = 0;
  12279. /* 1. get the request url */
  12280. /* 1.1. split into url and query string */
  12281. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12282. != NULL) {
  12283. *((char *)conn->request_info.query_string++) = '\0';
  12284. }
  12285. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12286. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12287. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12288. if (ssl_index >= 0) {
  12289. redirect_to_https_port(conn, ssl_index);
  12290. } else {
  12291. /* A http to https forward port has been specified,
  12292. * but no https port to forward to. */
  12293. mg_send_http_error(conn,
  12294. 503,
  12295. "%s",
  12296. "Error: SSL forward not configured properly");
  12297. mg_cry_internal(conn,
  12298. "%s",
  12299. "Can not redirect to SSL, no SSL port available");
  12300. }
  12301. return;
  12302. }
  12303. uri_len = (int)strlen(ri->local_uri);
  12304. /* 1.3. decode url (if config says so) */
  12305. if (should_decode_url(conn)) {
  12306. mg_url_decode(
  12307. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12308. }
  12309. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12310. * not possible */
  12311. remove_dot_segments((char *)ri->local_uri);
  12312. /* step 1. completed, the url is known now */
  12313. uri_len = (int)strlen(ri->local_uri);
  12314. DEBUG_TRACE("URL: %s", ri->local_uri);
  12315. /* 2. if this ip has limited speed, set it for this connection */
  12316. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12317. &conn->client.rsa,
  12318. ri->local_uri);
  12319. /* 3. call a "handle everything" callback, if registered */
  12320. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12321. /* Note that since V1.7 the "begin_request" function is called
  12322. * before an authorization check. If an authorization check is
  12323. * required, use a request_handler instead. */
  12324. i = conn->phys_ctx->callbacks.begin_request(conn);
  12325. if (i > 0) {
  12326. /* callback already processed the request. Store the
  12327. return value as a status code for the access log. */
  12328. conn->status_code = i;
  12329. if (!conn->must_close) {
  12330. discard_unread_request_data(conn);
  12331. }
  12332. return;
  12333. } else if (i == 0) {
  12334. /* civetweb should process the request */
  12335. } else {
  12336. /* unspecified - may change with the next version */
  12337. return;
  12338. }
  12339. }
  12340. /* request not yet handled by a handler or redirect, so the request
  12341. * is processed here */
  12342. /* 4. Check for CORS preflight requests and handle them (if configured).
  12343. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12344. */
  12345. if (!strcmp(ri->request_method, "OPTIONS")) {
  12346. /* Send a response to CORS preflights only if
  12347. * access_control_allow_methods is not NULL and not an empty string.
  12348. * In this case, scripts can still handle CORS. */
  12349. const char *cors_meth_cfg =
  12350. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12351. const char *cors_orig_cfg =
  12352. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12353. const char *cors_origin =
  12354. get_header(ri->http_headers, ri->num_headers, "Origin");
  12355. const char *cors_acrm = get_header(ri->http_headers,
  12356. ri->num_headers,
  12357. "Access-Control-Request-Method");
  12358. /* Todo: check if cors_origin is in cors_orig_cfg.
  12359. * Or, let the client check this. */
  12360. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12361. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12362. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12363. /* This is a valid CORS preflight, and the server is configured
  12364. * to
  12365. * handle it automatically. */
  12366. const char *cors_acrh =
  12367. get_header(ri->http_headers,
  12368. ri->num_headers,
  12369. "Access-Control-Request-Headers");
  12370. gmt_time_string(date, sizeof(date), &curtime);
  12371. mg_printf(conn,
  12372. "HTTP/1.1 200 OK\r\n"
  12373. "Date: %s\r\n"
  12374. "Access-Control-Allow-Origin: %s\r\n"
  12375. "Access-Control-Allow-Methods: %s\r\n"
  12376. "Content-Length: 0\r\n"
  12377. "Connection: %s\r\n",
  12378. date,
  12379. cors_orig_cfg,
  12380. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12381. suggest_connection_header(conn));
  12382. if (cors_acrh != NULL) {
  12383. /* CORS request is asking for additional headers */
  12384. const char *cors_hdr_cfg =
  12385. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12386. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12387. /* Allow only if access_control_allow_headers is
  12388. * not NULL and not an empty string. If this
  12389. * configuration is set to *, allow everything.
  12390. * Otherwise this configuration must be a list
  12391. * of allowed HTTP header names. */
  12392. mg_printf(conn,
  12393. "Access-Control-Allow-Headers: %s\r\n",
  12394. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12395. : cors_hdr_cfg));
  12396. }
  12397. }
  12398. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12399. mg_printf(conn, "\r\n");
  12400. return;
  12401. }
  12402. }
  12403. /* 5. interpret the url to find out how the request must be handled
  12404. */
  12405. /* 5.1. first test, if the request targets the regular http(s)://
  12406. * protocol namespace or the websocket ws(s):// protocol namespace.
  12407. */
  12408. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12409. #if defined(USE_WEBSOCKET)
  12410. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12411. #else
  12412. handler_type = REQUEST_HANDLER;
  12413. #endif /* defined(USE_WEBSOCKET) */
  12414. /* 5.2. check if the request will be handled by a callback */
  12415. if (get_request_handler(conn,
  12416. handler_type,
  12417. &callback_handler,
  12418. &subprotocols,
  12419. &ws_connect_handler,
  12420. &ws_ready_handler,
  12421. &ws_data_handler,
  12422. &ws_close_handler,
  12423. NULL,
  12424. &callback_data,
  12425. &handler_info)) {
  12426. /* 5.2.1. A callback will handle this request. All requests
  12427. * handled
  12428. * by a callback have to be considered as requests to a script
  12429. * resource. */
  12430. is_callback_resource = 1;
  12431. is_script_resource = 1;
  12432. is_put_or_delete_request = is_put_or_delete_method(conn);
  12433. } else {
  12434. no_callback_resource:
  12435. /* 5.2.2. No callback is responsible for this request. The URI
  12436. * addresses a file based resource (static content or Lua/cgi
  12437. * scripts in the file system). */
  12438. is_callback_resource = 0;
  12439. interpret_uri(conn,
  12440. path,
  12441. sizeof(path),
  12442. &file.stat,
  12443. &is_found,
  12444. &is_script_resource,
  12445. &is_websocket_request,
  12446. &is_put_or_delete_request);
  12447. }
  12448. /* 6. authorization check */
  12449. /* 6.1. a custom authorization handler is installed */
  12450. if (get_request_handler(conn,
  12451. AUTH_HANDLER,
  12452. NULL,
  12453. NULL,
  12454. NULL,
  12455. NULL,
  12456. NULL,
  12457. NULL,
  12458. &auth_handler,
  12459. &auth_callback_data,
  12460. NULL)) {
  12461. if (!auth_handler(conn, auth_callback_data)) {
  12462. return;
  12463. }
  12464. } else if (is_put_or_delete_request && !is_script_resource
  12465. && !is_callback_resource) {
  12466. /* 6.2. this request is a PUT/DELETE to a real file */
  12467. /* 6.2.1. thus, the server must have real files */
  12468. #if defined(NO_FILES)
  12469. if (1) {
  12470. #else
  12471. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12472. #endif
  12473. /* This server does not have any real files, thus the
  12474. * PUT/DELETE methods are not valid. */
  12475. mg_send_http_error(conn,
  12476. 405,
  12477. "%s method not allowed",
  12478. conn->request_info.request_method);
  12479. return;
  12480. }
  12481. #if !defined(NO_FILES)
  12482. /* 6.2.2. Check if put authorization for static files is
  12483. * available.
  12484. */
  12485. if (!is_authorized_for_put(conn)) {
  12486. send_authorization_request(conn, NULL);
  12487. return;
  12488. }
  12489. #endif
  12490. } else {
  12491. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12492. * or it is a PUT or DELETE request to a resource that does not
  12493. * correspond to a file. Check authorization. */
  12494. if (!check_authorization(conn, path)) {
  12495. send_authorization_request(conn, NULL);
  12496. return;
  12497. }
  12498. }
  12499. /* request is authorized or does not need authorization */
  12500. /* 7. check if there are request handlers for this uri */
  12501. if (is_callback_resource) {
  12502. if (!is_websocket_request) {
  12503. i = callback_handler(conn, callback_data);
  12504. /* Callback handler will not be used anymore. Release it */
  12505. mg_lock_context(conn->phys_ctx);
  12506. handler_info->refcount--;
  12507. mg_unlock_context(conn->phys_ctx);
  12508. if (i > 0) {
  12509. /* Do nothing, callback has served the request. Store
  12510. * then return value as status code for the log and discard
  12511. * all data from the client not used by the callback. */
  12512. conn->status_code = i;
  12513. if (!conn->must_close) {
  12514. discard_unread_request_data(conn);
  12515. }
  12516. } else {
  12517. /* The handler did NOT handle the request. */
  12518. /* Some proper reactions would be:
  12519. * a) close the connections without sending anything
  12520. * b) send a 404 not found
  12521. * c) try if there is a file matching the URI
  12522. * It would be possible to do a, b or c in the callback
  12523. * implementation, and return 1 - we cannot do anything
  12524. * here, that is not possible in the callback.
  12525. *
  12526. * TODO: What would be the best reaction here?
  12527. * (Note: The reaction may change, if there is a better
  12528. *idea.)
  12529. */
  12530. /* For the moment, use option c: We look for a proper file,
  12531. * but since a file request is not always a script resource,
  12532. * the authorization check might be different. */
  12533. interpret_uri(conn,
  12534. path,
  12535. sizeof(path),
  12536. &file.stat,
  12537. &is_found,
  12538. &is_script_resource,
  12539. &is_websocket_request,
  12540. &is_put_or_delete_request);
  12541. callback_handler = NULL;
  12542. /* Here we are at a dead end:
  12543. * According to URI matching, a callback should be
  12544. * responsible for handling the request,
  12545. * we called it, but the callback declared itself
  12546. * not responsible.
  12547. * We use a goto here, to get out of this dead end,
  12548. * and continue with the default handling.
  12549. * A goto here is simpler and better to understand
  12550. * than some curious loop. */
  12551. goto no_callback_resource;
  12552. }
  12553. } else {
  12554. #if defined(USE_WEBSOCKET)
  12555. handle_websocket_request(conn,
  12556. path,
  12557. is_callback_resource,
  12558. subprotocols,
  12559. ws_connect_handler,
  12560. ws_ready_handler,
  12561. ws_data_handler,
  12562. ws_close_handler,
  12563. callback_data);
  12564. #endif
  12565. }
  12566. return;
  12567. }
  12568. /* 8. handle websocket requests */
  12569. #if defined(USE_WEBSOCKET)
  12570. if (is_websocket_request) {
  12571. if (is_script_resource) {
  12572. if (is_in_script_path(conn, path)) {
  12573. /* Websocket Lua script */
  12574. handle_websocket_request(conn,
  12575. path,
  12576. 0 /* Lua Script */,
  12577. NULL,
  12578. NULL,
  12579. NULL,
  12580. NULL,
  12581. NULL,
  12582. conn->phys_ctx->user_data);
  12583. } else {
  12584. /* Script was in an illegal path */
  12585. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12586. }
  12587. } else {
  12588. #if defined(MG_LEGACY_INTERFACE)
  12589. handle_websocket_request(
  12590. conn,
  12591. path,
  12592. !is_script_resource /* could be deprecated global callback
  12593. */
  12594. ,
  12595. NULL,
  12596. deprecated_websocket_connect_wrapper,
  12597. deprecated_websocket_ready_wrapper,
  12598. deprecated_websocket_data_wrapper,
  12599. NULL,
  12600. conn->phys_ctx->callbacks);
  12601. #else
  12602. mg_send_http_error(conn, 404, "%s", "Not found");
  12603. #endif
  12604. }
  12605. return;
  12606. } else
  12607. #endif
  12608. #if defined(NO_FILES)
  12609. /* 9a. In case the server uses only callbacks, this uri is
  12610. * unknown.
  12611. * Then, all request handling ends here. */
  12612. mg_send_http_error(conn, 404, "%s", "Not Found");
  12613. #else
  12614. /* 9b. This request is either for a static file or resource handled
  12615. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12616. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12617. mg_send_http_error(conn, 404, "%s", "Not Found");
  12618. return;
  12619. }
  12620. /* 10. Request is handled by a script */
  12621. if (is_script_resource) {
  12622. handle_file_based_request(conn, path, &file);
  12623. return;
  12624. }
  12625. /* 11. Handle put/delete/mkcol requests */
  12626. if (is_put_or_delete_request) {
  12627. /* 11.1. PUT method */
  12628. if (!strcmp(ri->request_method, "PUT")) {
  12629. put_file(conn, path);
  12630. return;
  12631. }
  12632. /* 11.2. DELETE method */
  12633. if (!strcmp(ri->request_method, "DELETE")) {
  12634. delete_file(conn, path);
  12635. return;
  12636. }
  12637. /* 11.3. MKCOL method */
  12638. if (!strcmp(ri->request_method, "MKCOL")) {
  12639. mkcol(conn, path);
  12640. return;
  12641. }
  12642. /* 11.4. PATCH method
  12643. * This method is not supported for static resources,
  12644. * only for scripts (Lua, CGI) and callbacks. */
  12645. mg_send_http_error(conn,
  12646. 405,
  12647. "%s method not allowed",
  12648. conn->request_info.request_method);
  12649. return;
  12650. }
  12651. /* 11. File does not exist, or it was configured that it should be
  12652. * hidden */
  12653. if (!is_found || (must_hide_file(conn, path))) {
  12654. mg_send_http_error(conn, 404, "%s", "Not found");
  12655. return;
  12656. }
  12657. /* 12. Directory uris should end with a slash */
  12658. if (file.stat.is_directory && (uri_len > 0)
  12659. && (ri->local_uri[uri_len - 1] != '/')) {
  12660. gmt_time_string(date, sizeof(date), &curtime);
  12661. mg_printf(conn,
  12662. "HTTP/1.1 301 Moved Permanently\r\n"
  12663. "Location: %s/\r\n"
  12664. "Date: %s\r\n"
  12665. /* "Cache-Control: private\r\n" (= default) */
  12666. "Content-Length: 0\r\n"
  12667. "Connection: %s\r\n",
  12668. ri->request_uri,
  12669. date,
  12670. suggest_connection_header(conn));
  12671. send_additional_header(conn);
  12672. mg_printf(conn, "\r\n");
  12673. return;
  12674. }
  12675. /* 13. Handle other methods than GET/HEAD */
  12676. /* 13.1. Handle PROPFIND */
  12677. if (!strcmp(ri->request_method, "PROPFIND")) {
  12678. handle_propfind(conn, path, &file.stat);
  12679. return;
  12680. }
  12681. /* 13.2. Handle OPTIONS for files */
  12682. if (!strcmp(ri->request_method, "OPTIONS")) {
  12683. /* This standard handler is only used for real files.
  12684. * Scripts should support the OPTIONS method themselves, to allow a
  12685. * maximum flexibility.
  12686. * Lua and CGI scripts may fully support CORS this way (including
  12687. * preflights). */
  12688. send_options(conn);
  12689. return;
  12690. }
  12691. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12692. if ((0 != strcmp(ri->request_method, "GET"))
  12693. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12694. mg_send_http_error(conn,
  12695. 405,
  12696. "%s method not allowed",
  12697. conn->request_info.request_method);
  12698. return;
  12699. }
  12700. /* 14. directories */
  12701. if (file.stat.is_directory) {
  12702. /* Substitute files have already been handled above. */
  12703. /* Here we can either generate and send a directory listing,
  12704. * or send an "access denied" error. */
  12705. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12706. "yes")) {
  12707. handle_directory_request(conn, path);
  12708. } else {
  12709. mg_send_http_error(conn,
  12710. 403,
  12711. "%s",
  12712. "Error: Directory listing denied");
  12713. }
  12714. return;
  12715. }
  12716. /* 15. read a normal file with GET or HEAD */
  12717. handle_file_based_request(conn, path, &file);
  12718. #endif /* !defined(NO_FILES) */
  12719. }
  12720. /* Include HTTP/2 modules */
  12721. #ifdef USE_HTTP2
  12722. #if defined(NO_SSL)
  12723. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  12724. #endif
  12725. #include "mod_http2.inl"
  12726. #endif
  12727. #if !defined(NO_FILESYSTEMS)
  12728. static void
  12729. handle_file_based_request(struct mg_connection *conn,
  12730. const char *path,
  12731. struct mg_file *file)
  12732. {
  12733. if (!conn || !conn->dom_ctx) {
  12734. return;
  12735. }
  12736. if (0) {
  12737. #if defined(USE_LUA)
  12738. } else if (match_prefix(
  12739. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12740. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12741. path)
  12742. > 0) {
  12743. if (is_in_script_path(conn, path)) {
  12744. /* Lua server page: an SSI like page containing mostly plain
  12745. * html
  12746. * code
  12747. * plus some tags with server generated contents. */
  12748. handle_lsp_request(conn, path, file, NULL);
  12749. } else {
  12750. /* Script was in an illegal path */
  12751. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12752. }
  12753. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12754. strlen(
  12755. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12756. path)
  12757. > 0) {
  12758. if (is_in_script_path(conn, path)) {
  12759. /* Lua in-server module script: a CGI like script used to
  12760. * generate
  12761. * the
  12762. * entire reply. */
  12763. mg_exec_lua_script(conn, path, NULL);
  12764. } else {
  12765. /* Script was in an illegal path */
  12766. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12767. }
  12768. #endif
  12769. #if defined(USE_DUKTAPE)
  12770. } else if (match_prefix(
  12771. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12772. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12773. path)
  12774. > 0) {
  12775. if (is_in_script_path(conn, path)) {
  12776. /* Call duktape to generate the page */
  12777. mg_exec_duktape_script(conn, path);
  12778. } else {
  12779. /* Script was in an illegal path */
  12780. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12781. }
  12782. #endif
  12783. #if !defined(NO_CGI)
  12784. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12785. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12786. path)
  12787. > 0) {
  12788. if (is_in_script_path(conn, path)) {
  12789. /* CGI scripts may support all HTTP methods */
  12790. handle_cgi_request(conn, path);
  12791. } else {
  12792. /* Script was in an illegal path */
  12793. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12794. }
  12795. #endif /* !NO_CGI */
  12796. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12797. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12798. path)
  12799. > 0) {
  12800. if (is_in_script_path(conn, path)) {
  12801. handle_ssi_file_request(conn, path, file);
  12802. } else {
  12803. /* Script was in an illegal path */
  12804. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12805. }
  12806. #if !defined(NO_CACHING)
  12807. } else if ((!conn->in_error_handler)
  12808. && is_not_modified(conn, &file->stat)) {
  12809. /* Send 304 "Not Modified" - this must not send any body data */
  12810. handle_not_modified_static_file_request(conn, file);
  12811. #endif /* !NO_CACHING */
  12812. } else {
  12813. handle_static_file_request(conn, path, file, NULL, NULL);
  12814. }
  12815. }
  12816. #endif /* NO_FILESYSTEMS */
  12817. static void
  12818. close_all_listening_sockets(struct mg_context *ctx)
  12819. {
  12820. unsigned int i;
  12821. if (!ctx) {
  12822. return;
  12823. }
  12824. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12825. closesocket(ctx->listening_sockets[i].sock);
  12826. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12827. }
  12828. mg_free(ctx->listening_sockets);
  12829. ctx->listening_sockets = NULL;
  12830. mg_free(ctx->listening_socket_fds);
  12831. ctx->listening_socket_fds = NULL;
  12832. }
  12833. /* Valid listening port specification is: [ip_address:]port[s]
  12834. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12835. * Examples for IPv6: [::]:80, [::1]:80,
  12836. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12837. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12838. * In order to bind to both, IPv4 and IPv6, you can either add
  12839. * both ports using 8080,[::]:8080, or the short form +8080.
  12840. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12841. * one only accepting IPv4 the other only IPv6. +8080 creates
  12842. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12843. * environment, they might work differently, or might not work
  12844. * at all - it must be tested what options work best in the
  12845. * relevant network environment.
  12846. */
  12847. static int
  12848. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12849. {
  12850. unsigned int a, b, c, d;
  12851. unsigned port;
  12852. unsigned long portUL;
  12853. int ch, len;
  12854. const char *cb;
  12855. char *endptr;
  12856. #if defined(USE_IPV6)
  12857. char buf[100] = {0};
  12858. #endif
  12859. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12860. * Also, all-zeroes in the socket address means binding to all addresses
  12861. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12862. memset(so, 0, sizeof(*so));
  12863. so->lsa.sin.sin_family = AF_INET;
  12864. *ip_version = 0;
  12865. /* Initialize len as invalid. */
  12866. port = 0;
  12867. len = 0;
  12868. /* Test for different ways to format this string */
  12869. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12870. == 5) {
  12871. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12872. so->lsa.sin.sin_addr.s_addr =
  12873. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12874. so->lsa.sin.sin_port = htons((uint16_t)port);
  12875. *ip_version = 4;
  12876. #if defined(USE_IPV6)
  12877. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12878. && ((size_t)len <= vec->len)
  12879. && mg_inet_pton(
  12880. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12881. /* IPv6 address, examples: see above */
  12882. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12883. */
  12884. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12885. *ip_version = 6;
  12886. #endif
  12887. } else if ((vec->ptr[0] == '+')
  12888. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12889. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12890. /* Add 1 to len for the + character we skipped before */
  12891. len++;
  12892. #if defined(USE_IPV6)
  12893. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12894. so->lsa.sin6.sin6_family = AF_INET6;
  12895. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12896. *ip_version = 4 + 6;
  12897. #else
  12898. /* Bind to IPv4 only, since IPv6 is not built in. */
  12899. so->lsa.sin.sin_port = htons((uint16_t)port);
  12900. *ip_version = 4;
  12901. #endif
  12902. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12903. && (vec->ptr != endptr)) {
  12904. len = (int)(endptr - vec->ptr);
  12905. port = (uint16_t)portUL;
  12906. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12907. so->lsa.sin.sin_port = htons((uint16_t)port);
  12908. *ip_version = 4;
  12909. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12910. /* String could be a hostname. This check algotithm
  12911. * will only work for RFC 952 compliant hostnames,
  12912. * starting with a letter, containing only letters,
  12913. * digits and hyphen ('-'). Newer specs may allow
  12914. * more, but this is not guaranteed here, since it
  12915. * may interfere with rules for port option lists. */
  12916. /* According to RFC 1035, hostnames are restricted to 255 characters
  12917. * in total (63 between two dots). */
  12918. char hostname[256];
  12919. size_t hostnlen = (size_t)(cb - vec->ptr);
  12920. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12921. /* This would be invalid in any case */
  12922. *ip_version = 0;
  12923. return 0;
  12924. }
  12925. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12926. if (mg_inet_pton(
  12927. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12928. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12929. *ip_version = 4;
  12930. so->lsa.sin.sin_port = htons((uint16_t)port);
  12931. len += (int)(hostnlen + 1);
  12932. } else {
  12933. len = 0;
  12934. }
  12935. #if defined(USE_IPV6)
  12936. } else if (mg_inet_pton(AF_INET6,
  12937. hostname,
  12938. &so->lsa.sin6,
  12939. sizeof(so->lsa.sin6),
  12940. 1)) {
  12941. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12942. *ip_version = 6;
  12943. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12944. len += (int)(hostnlen + 1);
  12945. } else {
  12946. len = 0;
  12947. }
  12948. #endif
  12949. } else {
  12950. len = 0;
  12951. }
  12952. } else {
  12953. /* Parsing failure. */
  12954. len = 0;
  12955. }
  12956. /* sscanf and the option splitting code ensure the following condition
  12957. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12958. if ((len > 0) && is_valid_port(port)
  12959. && (((size_t)len == vec->len) || ((size_t)(len + 1) == vec->len))) {
  12960. /* Next character after the port number */
  12961. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12962. so->is_ssl = (ch == 's');
  12963. so->ssl_redir = (ch == 'r');
  12964. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12965. return 1;
  12966. }
  12967. }
  12968. /* Reset ip_version to 0 if there is an error */
  12969. *ip_version = 0;
  12970. return 0;
  12971. }
  12972. /* Is there any SSL port in use? */
  12973. static int
  12974. is_ssl_port_used(const char *ports)
  12975. {
  12976. if (ports) {
  12977. /* There are several different allowed syntax variants:
  12978. * - "80" for a single port using every network interface
  12979. * - "localhost:80" for a single port using only localhost
  12980. * - "80,localhost:8080" for two ports, one bound to localhost
  12981. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12982. * to IPv4 localhost, one to IPv6 localhost
  12983. * - "+80" use port 80 for IPv4 and IPv6
  12984. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12985. * for both: IPv4 and IPv4
  12986. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12987. * additionally port 8080 bound to localhost connections
  12988. *
  12989. * If we just look for 's' anywhere in the string, "localhost:80"
  12990. * will be detected as SSL (false positive).
  12991. * Looking for 's' after a digit may cause false positives in
  12992. * "my24service:8080".
  12993. * Looking from 's' backward if there are only ':' and numbers
  12994. * before will not work for "24service:8080" (non SSL, port 8080)
  12995. * or "24s" (SSL, port 24).
  12996. *
  12997. * Remark: Initially hostnames were not allowed to start with a
  12998. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12999. * Section 2.1).
  13000. *
  13001. * To get this correct, the entire string must be parsed as a whole,
  13002. * reading it as a list element for element and parsing with an
  13003. * algorithm equivalent to parse_port_string.
  13004. *
  13005. * In fact, we use local interface names here, not arbitrary
  13006. * hostnames, so in most cases the only name will be "localhost".
  13007. *
  13008. * So, for now, we use this simple algorithm, that may still return
  13009. * a false positive in bizarre cases.
  13010. */
  13011. int i;
  13012. int portslen = (int)strlen(ports);
  13013. char prevIsNumber = 0;
  13014. for (i = 0; i < portslen; i++) {
  13015. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13016. return 1;
  13017. }
  13018. if (ports[i] >= '0' && ports[i] <= '9') {
  13019. prevIsNumber = 1;
  13020. } else {
  13021. prevIsNumber = 0;
  13022. }
  13023. }
  13024. }
  13025. return 0;
  13026. }
  13027. static int
  13028. set_ports_option(struct mg_context *phys_ctx)
  13029. {
  13030. const char *list;
  13031. int on = 1;
  13032. #if defined(USE_IPV6)
  13033. int off = 0;
  13034. #endif
  13035. struct vec vec;
  13036. struct socket so, *ptr;
  13037. struct mg_pollfd *pfd;
  13038. union usa usa;
  13039. socklen_t len;
  13040. int ip_version;
  13041. int portsTotal = 0;
  13042. int portsOk = 0;
  13043. const char *opt_txt;
  13044. long opt_listen_backlog;
  13045. if (!phys_ctx) {
  13046. return 0;
  13047. }
  13048. memset(&so, 0, sizeof(so));
  13049. memset(&usa, 0, sizeof(usa));
  13050. len = sizeof(usa);
  13051. list = phys_ctx->dd.config[LISTENING_PORTS];
  13052. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13053. portsTotal++;
  13054. if (!parse_port_string(&vec, &so, &ip_version)) {
  13055. mg_cry_ctx_internal(
  13056. phys_ctx,
  13057. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13058. (int)vec.len,
  13059. vec.ptr,
  13060. portsTotal,
  13061. "[IP_ADDRESS:]PORT[s|r]");
  13062. continue;
  13063. }
  13064. #if !defined(NO_SSL)
  13065. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13066. mg_cry_ctx_internal(phys_ctx,
  13067. "Cannot add SSL socket (entry %i)",
  13068. portsTotal);
  13069. continue;
  13070. }
  13071. #endif
  13072. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  13073. == INVALID_SOCKET) {
  13074. mg_cry_ctx_internal(phys_ctx,
  13075. "cannot create socket (entry %i)",
  13076. portsTotal);
  13077. continue;
  13078. }
  13079. #if defined(_WIN32)
  13080. /* Windows SO_REUSEADDR lets many procs binds to a
  13081. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13082. * if someone already has the socket -- DTL */
  13083. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13084. * Windows might need a few seconds before
  13085. * the same port can be used again in the
  13086. * same process, so a short Sleep may be
  13087. * required between mg_stop and mg_start.
  13088. */
  13089. if (setsockopt(so.sock,
  13090. SOL_SOCKET,
  13091. SO_EXCLUSIVEADDRUSE,
  13092. (SOCK_OPT_TYPE)&on,
  13093. sizeof(on))
  13094. != 0) {
  13095. /* Set reuse option, but don't abort on errors. */
  13096. mg_cry_ctx_internal(
  13097. phys_ctx,
  13098. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13099. portsTotal);
  13100. }
  13101. #else
  13102. if (setsockopt(so.sock,
  13103. SOL_SOCKET,
  13104. SO_REUSEADDR,
  13105. (SOCK_OPT_TYPE)&on,
  13106. sizeof(on))
  13107. != 0) {
  13108. /* Set reuse option, but don't abort on errors. */
  13109. mg_cry_ctx_internal(
  13110. phys_ctx,
  13111. "cannot set socket option SO_REUSEADDR (entry %i)",
  13112. portsTotal);
  13113. }
  13114. #endif
  13115. if (ip_version > 4) {
  13116. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13117. #if defined(USE_IPV6)
  13118. if (ip_version > 6) {
  13119. if (so.lsa.sa.sa_family == AF_INET6
  13120. && setsockopt(so.sock,
  13121. IPPROTO_IPV6,
  13122. IPV6_V6ONLY,
  13123. (void *)&off,
  13124. sizeof(off))
  13125. != 0) {
  13126. /* Set IPv6 only option, but don't abort on errors. */
  13127. mg_cry_ctx_internal(phys_ctx,
  13128. "cannot set socket option "
  13129. "IPV6_V6ONLY=off (entry %i)",
  13130. portsTotal);
  13131. }
  13132. } else {
  13133. if (so.lsa.sa.sa_family == AF_INET6
  13134. && setsockopt(so.sock,
  13135. IPPROTO_IPV6,
  13136. IPV6_V6ONLY,
  13137. (void *)&on,
  13138. sizeof(on))
  13139. != 0) {
  13140. /* Set IPv6 only option, but don't abort on errors. */
  13141. mg_cry_ctx_internal(phys_ctx,
  13142. "cannot set socket option "
  13143. "IPV6_V6ONLY=on (entry %i)",
  13144. portsTotal);
  13145. }
  13146. }
  13147. #else
  13148. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13149. closesocket(so.sock);
  13150. so.sock = INVALID_SOCKET;
  13151. continue;
  13152. #endif
  13153. }
  13154. if (so.lsa.sa.sa_family == AF_INET) {
  13155. len = sizeof(so.lsa.sin);
  13156. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13157. mg_cry_ctx_internal(phys_ctx,
  13158. "cannot bind to %.*s: %d (%s)",
  13159. (int)vec.len,
  13160. vec.ptr,
  13161. (int)ERRNO,
  13162. strerror(errno));
  13163. closesocket(so.sock);
  13164. so.sock = INVALID_SOCKET;
  13165. continue;
  13166. }
  13167. }
  13168. #if defined(USE_IPV6)
  13169. else if (so.lsa.sa.sa_family == AF_INET6) {
  13170. len = sizeof(so.lsa.sin6);
  13171. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13172. mg_cry_ctx_internal(phys_ctx,
  13173. "cannot bind to IPv6 %.*s: %d (%s)",
  13174. (int)vec.len,
  13175. vec.ptr,
  13176. (int)ERRNO,
  13177. strerror(errno));
  13178. closesocket(so.sock);
  13179. so.sock = INVALID_SOCKET;
  13180. continue;
  13181. }
  13182. }
  13183. #endif
  13184. else {
  13185. mg_cry_ctx_internal(
  13186. phys_ctx,
  13187. "cannot bind: address family not supported (entry %i)",
  13188. portsTotal);
  13189. closesocket(so.sock);
  13190. so.sock = INVALID_SOCKET;
  13191. continue;
  13192. }
  13193. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13194. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13195. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13196. mg_cry_ctx_internal(phys_ctx,
  13197. "%s value \"%s\" is invalid",
  13198. config_options[LISTEN_BACKLOG_SIZE].name,
  13199. opt_txt);
  13200. closesocket(so.sock);
  13201. so.sock = INVALID_SOCKET;
  13202. continue;
  13203. }
  13204. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13205. mg_cry_ctx_internal(phys_ctx,
  13206. "cannot listen to %.*s: %d (%s)",
  13207. (int)vec.len,
  13208. vec.ptr,
  13209. (int)ERRNO,
  13210. strerror(errno));
  13211. closesocket(so.sock);
  13212. so.sock = INVALID_SOCKET;
  13213. continue;
  13214. }
  13215. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13216. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13217. int err = (int)ERRNO;
  13218. mg_cry_ctx_internal(phys_ctx,
  13219. "call to getsockname failed %.*s: %d (%s)",
  13220. (int)vec.len,
  13221. vec.ptr,
  13222. err,
  13223. strerror(errno));
  13224. closesocket(so.sock);
  13225. so.sock = INVALID_SOCKET;
  13226. continue;
  13227. }
  13228. /* Update lsa port in case of random free ports */
  13229. #if defined(USE_IPV6)
  13230. if (so.lsa.sa.sa_family == AF_INET6) {
  13231. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13232. } else
  13233. #endif
  13234. {
  13235. so.lsa.sin.sin_port = usa.sin.sin_port;
  13236. }
  13237. if ((ptr = (struct socket *)
  13238. mg_realloc_ctx(phys_ctx->listening_sockets,
  13239. (phys_ctx->num_listening_sockets + 1)
  13240. * sizeof(phys_ctx->listening_sockets[0]),
  13241. phys_ctx))
  13242. == NULL) {
  13243. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13244. closesocket(so.sock);
  13245. so.sock = INVALID_SOCKET;
  13246. continue;
  13247. }
  13248. if ((pfd = (struct mg_pollfd *)
  13249. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13250. (phys_ctx->num_listening_sockets + 1)
  13251. * sizeof(phys_ctx->listening_socket_fds[0]),
  13252. phys_ctx))
  13253. == NULL) {
  13254. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13255. closesocket(so.sock);
  13256. so.sock = INVALID_SOCKET;
  13257. mg_free(ptr);
  13258. continue;
  13259. }
  13260. set_close_on_exec(so.sock, NULL, phys_ctx);
  13261. phys_ctx->listening_sockets = ptr;
  13262. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13263. phys_ctx->listening_socket_fds = pfd;
  13264. phys_ctx->num_listening_sockets++;
  13265. portsOk++;
  13266. }
  13267. if (portsOk != portsTotal) {
  13268. close_all_listening_sockets(phys_ctx);
  13269. portsOk = 0;
  13270. }
  13271. return portsOk;
  13272. }
  13273. static const char *
  13274. header_val(const struct mg_connection *conn, const char *header)
  13275. {
  13276. const char *header_value;
  13277. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13278. return "-";
  13279. } else {
  13280. return header_value;
  13281. }
  13282. }
  13283. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13284. static void log_access(const struct mg_connection *conn);
  13285. #include "external_log_access.inl"
  13286. #elif !defined(NO_FILESYSTEMS)
  13287. static void
  13288. log_access(const struct mg_connection *conn)
  13289. {
  13290. const struct mg_request_info *ri;
  13291. struct mg_file fi;
  13292. char date[64], src_addr[IP_ADDR_STR_LEN];
  13293. struct tm *tm;
  13294. const char *referer;
  13295. const char *user_agent;
  13296. char buf[4096];
  13297. if (!conn || !conn->dom_ctx) {
  13298. return;
  13299. }
  13300. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13301. if (mg_fopen(conn,
  13302. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13303. MG_FOPEN_MODE_APPEND,
  13304. &fi)
  13305. == 0) {
  13306. fi.access.fp = NULL;
  13307. }
  13308. } else {
  13309. fi.access.fp = NULL;
  13310. }
  13311. /* Log is written to a file and/or a callback. If both are not set,
  13312. * executing the rest of the function is pointless. */
  13313. if ((fi.access.fp == NULL)
  13314. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13315. return;
  13316. }
  13317. tm = localtime(&conn->conn_birth_time);
  13318. if (tm != NULL) {
  13319. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13320. } else {
  13321. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13322. date[sizeof(date) - 1] = '\0';
  13323. }
  13324. ri = &conn->request_info;
  13325. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13326. referer = header_val(conn, "Referer");
  13327. user_agent = header_val(conn, "User-Agent");
  13328. mg_snprintf(conn,
  13329. NULL, /* Ignore truncation in access log */
  13330. buf,
  13331. sizeof(buf),
  13332. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13333. src_addr,
  13334. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13335. date,
  13336. ri->request_method ? ri->request_method : "-",
  13337. ri->request_uri ? ri->request_uri : "-",
  13338. ri->query_string ? "?" : "",
  13339. ri->query_string ? ri->query_string : "",
  13340. ri->http_version,
  13341. conn->status_code,
  13342. conn->num_bytes_sent,
  13343. referer,
  13344. user_agent);
  13345. if (conn->phys_ctx->callbacks.log_access) {
  13346. conn->phys_ctx->callbacks.log_access(conn, buf);
  13347. }
  13348. if (fi.access.fp) {
  13349. int ok = 1;
  13350. flockfile(fi.access.fp);
  13351. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13352. ok = 0;
  13353. }
  13354. if (fflush(fi.access.fp) != 0) {
  13355. ok = 0;
  13356. }
  13357. funlockfile(fi.access.fp);
  13358. if (mg_fclose(&fi.access) != 0) {
  13359. ok = 0;
  13360. }
  13361. if (!ok) {
  13362. mg_cry_internal(conn,
  13363. "Error writing log file %s",
  13364. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13365. }
  13366. }
  13367. }
  13368. #else
  13369. #error Must either enable filesystems or provide a custom log_access implementation
  13370. #endif /* Externally provided function */
  13371. /* Verify given socket address against the ACL.
  13372. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13373. */
  13374. static int
  13375. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13376. {
  13377. int allowed, flag, matched;
  13378. struct vec vec;
  13379. if (phys_ctx) {
  13380. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13381. /* If any ACL is set, deny by default */
  13382. allowed = (list == NULL) ? '+' : '-';
  13383. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13384. flag = vec.ptr[0];
  13385. matched = -1;
  13386. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13387. vec.ptr++;
  13388. vec.len--;
  13389. matched = parse_match_net(&vec, sa, 1);
  13390. }
  13391. if (matched < 0) {
  13392. mg_cry_ctx_internal(phys_ctx,
  13393. "%s: subnet must be [+|-]IP-addr[/x]",
  13394. __func__);
  13395. return -1;
  13396. }
  13397. if (matched) {
  13398. allowed = flag;
  13399. }
  13400. }
  13401. return allowed == '+';
  13402. }
  13403. return -1;
  13404. }
  13405. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13406. static int
  13407. set_uid_option(struct mg_context *phys_ctx)
  13408. {
  13409. int success = 0;
  13410. if (phys_ctx) {
  13411. /* We are currently running as curr_uid. */
  13412. const uid_t curr_uid = getuid();
  13413. /* If set, we want to run as run_as_user. */
  13414. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13415. const struct passwd *to_pw = NULL;
  13416. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13417. /* run_as_user does not exist on the system. We can't proceed
  13418. * further. */
  13419. mg_cry_ctx_internal(phys_ctx,
  13420. "%s: unknown user [%s]",
  13421. __func__,
  13422. run_as_user);
  13423. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13424. /* There was either no request to change user, or we're already
  13425. * running as run_as_user. Nothing else to do.
  13426. */
  13427. success = 1;
  13428. } else {
  13429. /* Valid change request. */
  13430. if (setgid(to_pw->pw_gid) == -1) {
  13431. mg_cry_ctx_internal(phys_ctx,
  13432. "%s: setgid(%s): %s",
  13433. __func__,
  13434. run_as_user,
  13435. strerror(errno));
  13436. } else if (setgroups(0, NULL) == -1) {
  13437. mg_cry_ctx_internal(phys_ctx,
  13438. "%s: setgroups(): %s",
  13439. __func__,
  13440. strerror(errno));
  13441. } else if (setuid(to_pw->pw_uid) == -1) {
  13442. mg_cry_ctx_internal(phys_ctx,
  13443. "%s: setuid(%s): %s",
  13444. __func__,
  13445. run_as_user,
  13446. strerror(errno));
  13447. } else {
  13448. success = 1;
  13449. }
  13450. }
  13451. }
  13452. return success;
  13453. }
  13454. #endif /* !_WIN32 */
  13455. static void
  13456. tls_dtor(void *key)
  13457. {
  13458. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13459. /* key == pthread_getspecific(sTlsKey); */
  13460. if (tls) {
  13461. if (tls->is_master == 2) {
  13462. tls->is_master = -3; /* Mark memory as dead */
  13463. mg_free(tls);
  13464. }
  13465. }
  13466. pthread_setspecific(sTlsKey, NULL);
  13467. }
  13468. #if !defined(NO_SSL)
  13469. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13470. struct mg_domain_context *dom_ctx,
  13471. const char *pem,
  13472. const char *chain);
  13473. static const char *ssl_error(void);
  13474. static int
  13475. refresh_trust(struct mg_connection *conn)
  13476. {
  13477. struct stat cert_buf;
  13478. int64_t t = 0;
  13479. const char *pem;
  13480. const char *chain;
  13481. int should_verify_peer;
  13482. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13483. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13484. * refresh_trust still can not work. */
  13485. return 0;
  13486. }
  13487. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13488. if (chain == NULL) {
  13489. /* pem is not NULL here */
  13490. chain = pem;
  13491. }
  13492. if (*chain == 0) {
  13493. chain = NULL;
  13494. }
  13495. if (stat(pem, &cert_buf) != -1) {
  13496. t = (int64_t)cert_buf.st_mtime;
  13497. }
  13498. mg_lock_context(conn->phys_ctx);
  13499. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13500. conn->dom_ctx->ssl_cert_last_mtime = t;
  13501. should_verify_peer = 0;
  13502. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13503. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13504. == 0) {
  13505. should_verify_peer = 1;
  13506. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13507. "optional")
  13508. == 0) {
  13509. should_verify_peer = 1;
  13510. }
  13511. }
  13512. if (should_verify_peer) {
  13513. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13514. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13515. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13516. ca_file,
  13517. ca_path)
  13518. != 1) {
  13519. mg_unlock_context(conn->phys_ctx);
  13520. mg_cry_ctx_internal(
  13521. conn->phys_ctx,
  13522. "SSL_CTX_load_verify_locations error: %s "
  13523. "ssl_verify_peer requires setting "
  13524. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13525. "present in "
  13526. "the .conf file?",
  13527. ssl_error());
  13528. return 0;
  13529. }
  13530. }
  13531. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13532. mg_unlock_context(conn->phys_ctx);
  13533. return 0;
  13534. }
  13535. }
  13536. mg_unlock_context(conn->phys_ctx);
  13537. return 1;
  13538. }
  13539. #if defined(OPENSSL_API_1_1)
  13540. #else
  13541. static pthread_mutex_t *ssl_mutexes;
  13542. #endif /* OPENSSL_API_1_1 */
  13543. static int
  13544. sslize(struct mg_connection *conn,
  13545. int (*func)(SSL *),
  13546. const struct mg_client_options *client_options)
  13547. {
  13548. int ret, err;
  13549. int short_trust;
  13550. unsigned timeout = 1024;
  13551. unsigned i;
  13552. if (!conn) {
  13553. return 0;
  13554. }
  13555. short_trust =
  13556. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13557. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13558. if (short_trust) {
  13559. int trust_ret = refresh_trust(conn);
  13560. if (!trust_ret) {
  13561. return trust_ret;
  13562. }
  13563. }
  13564. mg_lock_context(conn->phys_ctx);
  13565. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13566. mg_unlock_context(conn->phys_ctx);
  13567. if (conn->ssl == NULL) {
  13568. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13569. OPENSSL_REMOVE_THREAD_STATE();
  13570. return 0;
  13571. }
  13572. SSL_set_app_data(conn->ssl, (char *)conn);
  13573. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13574. if (ret != 1) {
  13575. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13576. SSL_free(conn->ssl);
  13577. conn->ssl = NULL;
  13578. OPENSSL_REMOVE_THREAD_STATE();
  13579. return 0;
  13580. }
  13581. if (client_options) {
  13582. if (client_options->host_name) {
  13583. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13584. }
  13585. }
  13586. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13587. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13588. /* NOTE: The loop below acts as a back-off, so we can end
  13589. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13590. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13591. if (to >= 0) {
  13592. timeout = (unsigned)to;
  13593. }
  13594. }
  13595. /* SSL functions may fail and require to be called again:
  13596. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13597. * Here "func" could be SSL_connect or SSL_accept. */
  13598. for (i = 0; i <= timeout; i += 50) {
  13599. ERR_clear_error();
  13600. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13601. ret = func(conn->ssl);
  13602. if (ret != 1) {
  13603. err = SSL_get_error(conn->ssl, ret);
  13604. if ((err == SSL_ERROR_WANT_CONNECT)
  13605. || (err == SSL_ERROR_WANT_ACCEPT)
  13606. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13607. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13608. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13609. /* Don't wait if the server is going to be stopped. */
  13610. break;
  13611. }
  13612. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13613. /* Simply retry the function call. */
  13614. mg_sleep(50);
  13615. } else {
  13616. /* Need to retry the function call "later".
  13617. * See https://linux.die.net/man/3/ssl_get_error
  13618. * This is typical for non-blocking sockets. */
  13619. struct mg_pollfd pfd;
  13620. int pollres;
  13621. pfd.fd = conn->client.sock;
  13622. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13623. || (err == SSL_ERROR_WANT_WRITE))
  13624. ? POLLOUT
  13625. : POLLIN;
  13626. pollres =
  13627. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13628. if (pollres < 0) {
  13629. /* Break if error occured (-1)
  13630. * or server shutdown (-2) */
  13631. break;
  13632. }
  13633. }
  13634. } else if (err == SSL_ERROR_SYSCALL) {
  13635. /* This is an IO error. Look at errno. */
  13636. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13637. break;
  13638. } else {
  13639. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13640. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13641. break;
  13642. }
  13643. } else {
  13644. /* success */
  13645. break;
  13646. }
  13647. }
  13648. ERR_clear_error();
  13649. if (ret != 1) {
  13650. SSL_free(conn->ssl);
  13651. conn->ssl = NULL;
  13652. OPENSSL_REMOVE_THREAD_STATE();
  13653. return 0;
  13654. }
  13655. return 1;
  13656. }
  13657. /* Return OpenSSL error message (from CRYPTO lib) */
  13658. static const char *
  13659. ssl_error(void)
  13660. {
  13661. unsigned long err;
  13662. err = ERR_get_error();
  13663. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13664. }
  13665. static int
  13666. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13667. {
  13668. int i;
  13669. const char hexdigit[] = "0123456789abcdef";
  13670. if ((memlen <= 0) || (buflen <= 0)) {
  13671. return 0;
  13672. }
  13673. if (buflen < (3 * memlen)) {
  13674. return 0;
  13675. }
  13676. for (i = 0; i < memlen; i++) {
  13677. if (i > 0) {
  13678. buf[3 * i - 1] = ' ';
  13679. }
  13680. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13681. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13682. }
  13683. buf[3 * memlen - 1] = 0;
  13684. return 1;
  13685. }
  13686. static int
  13687. ssl_get_client_cert_info(const struct mg_connection *conn,
  13688. struct mg_client_cert *client_cert)
  13689. {
  13690. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13691. if (cert) {
  13692. char str_buf[1024];
  13693. unsigned char buf[256];
  13694. char *str_serial = NULL;
  13695. unsigned int ulen;
  13696. int ilen;
  13697. unsigned char *tmp_buf;
  13698. unsigned char *tmp_p;
  13699. /* Handle to algorithm used for fingerprint */
  13700. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13701. /* Get Subject and issuer */
  13702. X509_NAME *subj = X509_get_subject_name(cert);
  13703. X509_NAME *iss = X509_get_issuer_name(cert);
  13704. /* Get serial number */
  13705. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13706. /* Translate serial number to a hex string */
  13707. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13708. if (serial_bn) {
  13709. str_serial = BN_bn2hex(serial_bn);
  13710. BN_free(serial_bn);
  13711. }
  13712. client_cert->serial =
  13713. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13714. /* Translate subject and issuer to a string */
  13715. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13716. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13717. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13718. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13719. /* Calculate SHA1 fingerprint and store as a hex string */
  13720. ulen = 0;
  13721. /* ASN1_digest is deprecated. Do the calculation manually,
  13722. * using EVP_Digest. */
  13723. ilen = i2d_X509(cert, NULL);
  13724. tmp_buf = (ilen > 0)
  13725. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13726. conn->phys_ctx)
  13727. : NULL;
  13728. if (tmp_buf) {
  13729. tmp_p = tmp_buf;
  13730. (void)i2d_X509(cert, &tmp_p);
  13731. if (!EVP_Digest(
  13732. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13733. ulen = 0;
  13734. }
  13735. mg_free(tmp_buf);
  13736. }
  13737. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13738. *str_buf = 0;
  13739. }
  13740. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13741. client_cert->peer_cert = (void *)cert;
  13742. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13743. * see https://linux.die.net/man/3/bn_bn2hex */
  13744. OPENSSL_free(str_serial);
  13745. return 1;
  13746. }
  13747. return 0;
  13748. }
  13749. #if defined(OPENSSL_API_1_1)
  13750. #else
  13751. static void
  13752. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13753. {
  13754. (void)line;
  13755. (void)file;
  13756. if (mode & 1) {
  13757. /* 1 is CRYPTO_LOCK */
  13758. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13759. } else {
  13760. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13761. }
  13762. }
  13763. #endif /* OPENSSL_API_1_1 */
  13764. #if !defined(NO_SSL_DL)
  13765. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13766. static void *
  13767. load_tls_dll(char *ebuf,
  13768. size_t ebuf_len,
  13769. const char *dll_name,
  13770. struct ssl_func *sw)
  13771. {
  13772. union {
  13773. void *p;
  13774. void (*fp)(void);
  13775. } u;
  13776. void *dll_handle;
  13777. struct ssl_func *fp;
  13778. int ok;
  13779. int truncated = 0;
  13780. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13781. mg_snprintf(NULL,
  13782. NULL, /* No truncation check for ebuf */
  13783. ebuf,
  13784. ebuf_len,
  13785. "%s: cannot load %s",
  13786. __func__,
  13787. dll_name);
  13788. return NULL;
  13789. }
  13790. ok = 1;
  13791. for (fp = sw; fp->name != NULL; fp++) {
  13792. enum ssl_func_category req = fp->required;
  13793. #if defined(_WIN32)
  13794. /* GetProcAddress() returns pointer to function */
  13795. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13796. #else
  13797. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13798. * pointers to function pointers. We need to use a union to make a
  13799. * cast. */
  13800. u.p = dlsym(dll_handle, fp->name);
  13801. #endif /* _WIN32 */
  13802. /* Set pointer (might be NULL) */
  13803. fp->ptr = u.fp;
  13804. if (u.fp == NULL) {
  13805. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13806. tls_feature_missing[req]++;
  13807. if (req == TLS_Mandatory) {
  13808. /* Mandatory function is missing */
  13809. if (ok) {
  13810. /* This is the first missing function.
  13811. * Create a new error message. */
  13812. mg_snprintf(NULL,
  13813. &truncated,
  13814. ebuf,
  13815. ebuf_len,
  13816. "%s: %s: cannot find %s",
  13817. __func__,
  13818. dll_name,
  13819. fp->name);
  13820. ok = 0;
  13821. } else {
  13822. /* This is yet anothermissing function.
  13823. * Append existing error message. */
  13824. size_t cur_len = strlen(ebuf);
  13825. if (!truncated) {
  13826. mg_snprintf(NULL,
  13827. &truncated,
  13828. ebuf + cur_len,
  13829. ebuf_len - cur_len - 3,
  13830. ", %s",
  13831. fp->name);
  13832. if (truncated) {
  13833. /* If truncated, add "..." */
  13834. strcat(ebuf, "...");
  13835. }
  13836. }
  13837. }
  13838. }
  13839. }
  13840. }
  13841. if (!ok) {
  13842. (void)dlclose(dll_handle);
  13843. return NULL;
  13844. }
  13845. return dll_handle;
  13846. }
  13847. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13848. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13849. #endif /* NO_SSL_DL */
  13850. #if defined(SSL_ALREADY_INITIALIZED)
  13851. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13852. #else
  13853. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13854. #endif
  13855. static int
  13856. initialize_ssl(char *ebuf, size_t ebuf_len)
  13857. {
  13858. #if defined(OPENSSL_API_1_1)
  13859. if (ebuf_len > 0) {
  13860. ebuf[0] = 0;
  13861. }
  13862. #if !defined(NO_SSL_DL)
  13863. if (!cryptolib_dll_handle) {
  13864. cryptolib_dll_handle =
  13865. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13866. if (!cryptolib_dll_handle) {
  13867. mg_snprintf(NULL,
  13868. NULL, /* No truncation check for ebuf */
  13869. ebuf,
  13870. ebuf_len,
  13871. "%s: error loading library %s",
  13872. __func__,
  13873. CRYPTO_LIB);
  13874. DEBUG_TRACE("%s", ebuf);
  13875. return 0;
  13876. }
  13877. }
  13878. #endif /* NO_SSL_DL */
  13879. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13880. return 1;
  13881. }
  13882. #else /* not OPENSSL_API_1_1 */
  13883. int i, num_locks;
  13884. size_t size;
  13885. if (ebuf_len > 0) {
  13886. ebuf[0] = 0;
  13887. }
  13888. #if !defined(NO_SSL_DL)
  13889. if (!cryptolib_dll_handle) {
  13890. cryptolib_dll_handle =
  13891. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13892. if (!cryptolib_dll_handle) {
  13893. mg_snprintf(NULL,
  13894. NULL, /* No truncation check for ebuf */
  13895. ebuf,
  13896. ebuf_len,
  13897. "%s: error loading library %s",
  13898. __func__,
  13899. CRYPTO_LIB);
  13900. DEBUG_TRACE("%s", ebuf);
  13901. return 0;
  13902. }
  13903. }
  13904. #endif /* NO_SSL_DL */
  13905. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13906. return 1;
  13907. }
  13908. /* Initialize locking callbacks, needed for thread safety.
  13909. * http://www.openssl.org/support/faq.html#PROG1
  13910. */
  13911. num_locks = CRYPTO_num_locks();
  13912. if (num_locks < 0) {
  13913. num_locks = 0;
  13914. }
  13915. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13916. /* allocate mutex array, if required */
  13917. if (num_locks == 0) {
  13918. /* No mutex array required */
  13919. ssl_mutexes = NULL;
  13920. } else {
  13921. /* Mutex array required - allocate it */
  13922. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13923. /* Check OOM */
  13924. if (ssl_mutexes == NULL) {
  13925. mg_snprintf(NULL,
  13926. NULL, /* No truncation check for ebuf */
  13927. ebuf,
  13928. ebuf_len,
  13929. "%s: cannot allocate mutexes: %s",
  13930. __func__,
  13931. ssl_error());
  13932. DEBUG_TRACE("%s", ebuf);
  13933. return 0;
  13934. }
  13935. /* initialize mutex array */
  13936. for (i = 0; i < num_locks; i++) {
  13937. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13938. mg_snprintf(NULL,
  13939. NULL, /* No truncation check for ebuf */
  13940. ebuf,
  13941. ebuf_len,
  13942. "%s: error initializing mutex %i of %i",
  13943. __func__,
  13944. i,
  13945. num_locks);
  13946. DEBUG_TRACE("%s", ebuf);
  13947. mg_free(ssl_mutexes);
  13948. return 0;
  13949. }
  13950. }
  13951. }
  13952. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13953. CRYPTO_set_id_callback(&mg_current_thread_id);
  13954. #endif /* OPENSSL_API_1_1 */
  13955. #if !defined(NO_SSL_DL)
  13956. if (!ssllib_dll_handle) {
  13957. ssllib_dll_handle = load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13958. if (!ssllib_dll_handle) {
  13959. #if !defined(OPENSSL_API_1_1)
  13960. mg_free(ssl_mutexes);
  13961. #endif
  13962. DEBUG_TRACE("%s", ebuf);
  13963. return 0;
  13964. }
  13965. }
  13966. #endif /* NO_SSL_DL */
  13967. #if defined(OPENSSL_API_1_1)
  13968. /* Initialize SSL library */
  13969. OPENSSL_init_ssl(0, NULL);
  13970. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13971. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13972. NULL);
  13973. #else
  13974. /* Initialize SSL library */
  13975. SSL_library_init();
  13976. SSL_load_error_strings();
  13977. #endif
  13978. return 1;
  13979. }
  13980. static int
  13981. ssl_use_pem_file(struct mg_context *phys_ctx,
  13982. struct mg_domain_context *dom_ctx,
  13983. const char *pem,
  13984. const char *chain)
  13985. {
  13986. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13987. mg_cry_ctx_internal(phys_ctx,
  13988. "%s: cannot open certificate file %s: %s",
  13989. __func__,
  13990. pem,
  13991. ssl_error());
  13992. return 0;
  13993. }
  13994. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13995. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13996. mg_cry_ctx_internal(phys_ctx,
  13997. "%s: cannot open private key file %s: %s",
  13998. __func__,
  13999. pem,
  14000. ssl_error());
  14001. return 0;
  14002. }
  14003. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14004. mg_cry_ctx_internal(phys_ctx,
  14005. "%s: certificate and private key do not match: %s",
  14006. __func__,
  14007. pem);
  14008. return 0;
  14009. }
  14010. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14011. * chain files that contain private keys and certificates in
  14012. * SSL_CTX_use_certificate_chain_file.
  14013. * The CivetWeb-Server used pem-Files that contained both information.
  14014. * In order to make wolfSSL work, it is split in two files.
  14015. * One file that contains key and certificate used by the server and
  14016. * an optional chain file for the ssl stack.
  14017. */
  14018. if (chain) {
  14019. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14020. mg_cry_ctx_internal(phys_ctx,
  14021. "%s: cannot use certificate chain file %s: %s",
  14022. __func__,
  14023. chain,
  14024. ssl_error());
  14025. return 0;
  14026. }
  14027. }
  14028. return 1;
  14029. }
  14030. #if defined(OPENSSL_API_1_1)
  14031. static unsigned long
  14032. ssl_get_protocol(int version_id)
  14033. {
  14034. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14035. if (version_id > 0)
  14036. ret |= SSL_OP_NO_SSLv2;
  14037. if (version_id > 1)
  14038. ret |= SSL_OP_NO_SSLv3;
  14039. if (version_id > 2)
  14040. ret |= SSL_OP_NO_TLSv1;
  14041. if (version_id > 3)
  14042. ret |= SSL_OP_NO_TLSv1_1;
  14043. if (version_id > 4)
  14044. ret |= SSL_OP_NO_TLSv1_2;
  14045. #if defined(SSL_OP_NO_TLSv1_3)
  14046. if (version_id > 5)
  14047. ret |= SSL_OP_NO_TLSv1_3;
  14048. #endif
  14049. return ret;
  14050. }
  14051. #else
  14052. static long
  14053. ssl_get_protocol(int version_id)
  14054. {
  14055. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14056. if (version_id > 0)
  14057. ret |= SSL_OP_NO_SSLv2;
  14058. if (version_id > 1)
  14059. ret |= SSL_OP_NO_SSLv3;
  14060. if (version_id > 2)
  14061. ret |= SSL_OP_NO_TLSv1;
  14062. if (version_id > 3)
  14063. ret |= SSL_OP_NO_TLSv1_1;
  14064. if (version_id > 4)
  14065. ret |= SSL_OP_NO_TLSv1_2;
  14066. #if defined(SSL_OP_NO_TLSv1_3)
  14067. if (version_id > 5)
  14068. ret |= SSL_OP_NO_TLSv1_3;
  14069. #endif
  14070. return (long)ret;
  14071. }
  14072. #endif /* OPENSSL_API_1_1 */
  14073. /* SSL callback documentation:
  14074. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14075. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14076. * https://linux.die.net/man/3/ssl_set_info_callback */
  14077. /* Note: There is no "const" for the first argument in the documentation
  14078. * examples, however some (maybe most, but not all) headers of OpenSSL
  14079. * versions / OpenSSL compatibility layers have it. Having a different
  14080. * definition will cause a warning in C and an error in C++. Use "const SSL
  14081. * *", while automatical conversion from "SSL *" works for all compilers,
  14082. * but not other way around */
  14083. static void
  14084. ssl_info_callback(const SSL *ssl, int what, int ret)
  14085. {
  14086. (void)ret;
  14087. if (what & SSL_CB_HANDSHAKE_START) {
  14088. SSL_get_app_data(ssl);
  14089. }
  14090. if (what & SSL_CB_HANDSHAKE_DONE) {
  14091. /* TODO: check for openSSL 1.1 */
  14092. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14093. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14094. }
  14095. }
  14096. static int
  14097. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14098. {
  14099. #if defined(GCC_DIAGNOSTIC)
  14100. #pragma GCC diagnostic push
  14101. #pragma GCC diagnostic ignored "-Wcast-align"
  14102. #endif /* defined(GCC_DIAGNOSTIC) */
  14103. /* We used an aligned pointer in SSL_set_app_data */
  14104. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14105. #if defined(GCC_DIAGNOSTIC)
  14106. #pragma GCC diagnostic pop
  14107. #endif /* defined(GCC_DIAGNOSTIC) */
  14108. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14109. (void)ad;
  14110. (void)arg;
  14111. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14112. DEBUG_ASSERT(0);
  14113. return SSL_TLSEXT_ERR_NOACK;
  14114. }
  14115. conn->dom_ctx = &(conn->phys_ctx->dd);
  14116. /* Old clients (Win XP) will not support SNI. Then, there
  14117. * is no server name available in the request - we can
  14118. * only work with the default certificate.
  14119. * Multiple HTTPS hosts on one IP+port are only possible
  14120. * with a certificate containing all alternative names.
  14121. */
  14122. if ((servername == NULL) || (*servername == 0)) {
  14123. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14124. mg_lock_context(conn->phys_ctx);
  14125. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14126. mg_unlock_context(conn->phys_ctx);
  14127. return SSL_TLSEXT_ERR_NOACK;
  14128. }
  14129. DEBUG_TRACE("TLS connection to host %s", servername);
  14130. while (conn->dom_ctx) {
  14131. if (!mg_strcasecmp(servername,
  14132. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14133. /* Found matching domain */
  14134. DEBUG_TRACE("TLS domain %s found",
  14135. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14136. break;
  14137. }
  14138. mg_lock_context(conn->phys_ctx);
  14139. conn->dom_ctx = conn->dom_ctx->next;
  14140. mg_unlock_context(conn->phys_ctx);
  14141. }
  14142. if (conn->dom_ctx == NULL) {
  14143. /* Default domain */
  14144. DEBUG_TRACE("TLS default domain %s used",
  14145. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14146. conn->dom_ctx = &(conn->phys_ctx->dd);
  14147. }
  14148. mg_lock_context(conn->phys_ctx);
  14149. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14150. mg_unlock_context(conn->phys_ctx);
  14151. return SSL_TLSEXT_ERR_OK;
  14152. }
  14153. #if defined(USE_HTTP2)
  14154. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14155. static const char *alpn_proto_order[] = {alpn_proto_list,
  14156. alpn_proto_list + 3,
  14157. alpn_proto_list + 3 + 8,
  14158. NULL};
  14159. #else
  14160. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14161. static const char *alpn_proto_order[] = {alpn_proto_list,
  14162. alpn_proto_list + 8,
  14163. NULL};
  14164. #endif
  14165. static int
  14166. alpn_select_cb(SSL *ssl,
  14167. const unsigned char **out,
  14168. unsigned char *outlen,
  14169. const unsigned char *in,
  14170. unsigned int inlen,
  14171. void *arg)
  14172. {
  14173. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14174. unsigned int i, j;
  14175. struct mg_workerTLS *tls =
  14176. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14177. (void)ssl;
  14178. (void)dom_ctx;
  14179. if (tls == NULL) {
  14180. /* Need to store protocol in Thread Local Storage */
  14181. /* If there is no Thread Local Storage, don't use ALPN */
  14182. return SSL_TLSEXT_ERR_NOACK;
  14183. }
  14184. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14185. /* check all accepted protocols in this order */
  14186. const char *alpn_proto = alpn_proto_order[j];
  14187. /* search input for matching protocol */
  14188. for (i = 0; i < inlen; i++) {
  14189. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14190. *out = in + i + 1;
  14191. *outlen = in[i];
  14192. tls->alpn_proto = alpn_proto;
  14193. return SSL_TLSEXT_ERR_OK;
  14194. }
  14195. }
  14196. }
  14197. /* Nothing found */
  14198. return SSL_TLSEXT_ERR_NOACK;
  14199. }
  14200. static int
  14201. next_protos_advertised_cb(SSL *ssl,
  14202. const unsigned char **data,
  14203. unsigned int *len,
  14204. void *arg)
  14205. {
  14206. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14207. *data = (const unsigned char *)alpn_proto_list;
  14208. *len = (unsigned int)strlen((const char *)data);
  14209. (void)ssl;
  14210. (void)dom_ctx;
  14211. return SSL_TLSEXT_ERR_OK;
  14212. }
  14213. static int
  14214. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14215. {
  14216. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14217. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14218. (const unsigned char *)alpn_proto_list,
  14219. alpn_len);
  14220. if (ret != 0) {
  14221. mg_cry_ctx_internal(phys_ctx,
  14222. "SSL_CTX_set_alpn_protos error: %s",
  14223. ssl_error());
  14224. }
  14225. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14226. alpn_select_cb,
  14227. (void *)dom_ctx);
  14228. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14229. next_protos_advertised_cb,
  14230. (void *)dom_ctx);
  14231. return ret;
  14232. }
  14233. /* Setup SSL CTX as required by CivetWeb */
  14234. static int
  14235. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14236. struct mg_domain_context *dom_ctx,
  14237. const char *pem,
  14238. const char *chain)
  14239. {
  14240. int callback_ret;
  14241. int should_verify_peer;
  14242. int peer_certificate_optional;
  14243. const char *ca_path;
  14244. const char *ca_file;
  14245. int use_default_verify_paths;
  14246. int verify_depth;
  14247. struct timespec now_mt;
  14248. md5_byte_t ssl_context_id[16];
  14249. md5_state_t md5state;
  14250. int protocol_ver;
  14251. #if defined(OPENSSL_API_1_1)
  14252. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14253. mg_cry_ctx_internal(phys_ctx,
  14254. "SSL_CTX_new (server) error: %s",
  14255. ssl_error());
  14256. return 0;
  14257. }
  14258. #else
  14259. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14260. mg_cry_ctx_internal(phys_ctx,
  14261. "SSL_CTX_new (server) error: %s",
  14262. ssl_error());
  14263. return 0;
  14264. }
  14265. #endif /* OPENSSL_API_1_1 */
  14266. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14267. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14268. | SSL_OP_NO_TLSv1_1);
  14269. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14270. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14271. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14272. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14273. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14274. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14275. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14276. #if defined(SSL_OP_NO_RENEGOTIATION)
  14277. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14278. #endif
  14279. #if !defined(NO_SSL_DL)
  14280. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14281. #endif /* NO_SSL_DL */
  14282. /* In SSL documentation examples callback defined without const
  14283. * specifier 'void (*)(SSL *, int, int)' See:
  14284. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14285. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14286. * But in the source code const SSL is used:
  14287. * 'void (*)(const SSL *, int, int)' See:
  14288. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14289. * Problem about wrong documentation described, but not resolved:
  14290. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14291. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14292. * But when compiled with modern C++ compiler, correct const should be
  14293. * provided
  14294. */
  14295. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14296. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14297. ssl_servername_callback);
  14298. /* If a callback has been specified, call it. */
  14299. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14300. ? 0
  14301. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14302. phys_ctx->user_data));
  14303. /* If callback returns 0, civetweb sets up the SSL certificate.
  14304. * If it returns 1, civetweb assumes the calback already did this.
  14305. * If it returns -1, initializing ssl fails. */
  14306. if (callback_ret < 0) {
  14307. mg_cry_ctx_internal(phys_ctx,
  14308. "SSL callback returned error: %i",
  14309. callback_ret);
  14310. return 0;
  14311. }
  14312. if (callback_ret > 0) {
  14313. /* Callback did everything. */
  14314. return 1;
  14315. }
  14316. /* If a domain callback has been specified, call it. */
  14317. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14318. ? 0
  14319. : (phys_ctx->callbacks.init_ssl_domain(
  14320. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14321. dom_ctx->ssl_ctx,
  14322. phys_ctx->user_data));
  14323. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14324. * If it returns 1, civetweb assumes the calback already did this.
  14325. * If it returns -1, initializing ssl fails. */
  14326. if (callback_ret < 0) {
  14327. mg_cry_ctx_internal(phys_ctx,
  14328. "Domain SSL callback returned error: %i",
  14329. callback_ret);
  14330. return 0;
  14331. }
  14332. if (callback_ret > 0) {
  14333. /* Domain callback did everything. */
  14334. return 1;
  14335. }
  14336. /* Use some combination of start time, domain and port as a SSL
  14337. * context ID. This should be unique on the current machine. */
  14338. md5_init(&md5state);
  14339. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14340. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14341. md5_append(&md5state,
  14342. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14343. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14344. md5_append(&md5state,
  14345. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14346. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14347. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14348. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14349. md5_finish(&md5state, ssl_context_id);
  14350. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14351. (unsigned char *)ssl_context_id,
  14352. sizeof(ssl_context_id));
  14353. if (pem != NULL) {
  14354. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14355. return 0;
  14356. }
  14357. }
  14358. /* Should we support client certificates? */
  14359. /* Default is "no". */
  14360. should_verify_peer = 0;
  14361. peer_certificate_optional = 0;
  14362. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14363. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14364. /* Yes, they are mandatory */
  14365. should_verify_peer = 1;
  14366. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14367. "optional")
  14368. == 0) {
  14369. /* Yes, they are optional */
  14370. should_verify_peer = 1;
  14371. peer_certificate_optional = 1;
  14372. }
  14373. }
  14374. use_default_verify_paths =
  14375. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14376. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14377. == 0);
  14378. if (should_verify_peer) {
  14379. ca_path = dom_ctx->config[SSL_CA_PATH];
  14380. ca_file = dom_ctx->config[SSL_CA_FILE];
  14381. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14382. != 1) {
  14383. mg_cry_ctx_internal(phys_ctx,
  14384. "SSL_CTX_load_verify_locations error: %s "
  14385. "ssl_verify_peer requires setting "
  14386. "either ssl_ca_path or ssl_ca_file. "
  14387. "Is any of them present in the "
  14388. ".conf file?",
  14389. ssl_error());
  14390. return 0;
  14391. }
  14392. if (peer_certificate_optional) {
  14393. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14394. } else {
  14395. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14396. SSL_VERIFY_PEER
  14397. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14398. NULL);
  14399. }
  14400. if (use_default_verify_paths
  14401. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14402. mg_cry_ctx_internal(phys_ctx,
  14403. "SSL_CTX_set_default_verify_paths error: %s",
  14404. ssl_error());
  14405. return 0;
  14406. }
  14407. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14408. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14409. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14410. }
  14411. }
  14412. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14413. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14414. dom_ctx->config[SSL_CIPHER_LIST])
  14415. != 1) {
  14416. mg_cry_ctx_internal(phys_ctx,
  14417. "SSL_CTX_set_cipher_list error: %s",
  14418. ssl_error());
  14419. }
  14420. }
  14421. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14422. #if !defined(NO_SSL_DL)
  14423. if (!tls_feature_missing[TLS_ALPN])
  14424. #endif
  14425. {
  14426. init_alpn(phys_ctx, dom_ctx);
  14427. }
  14428. return 1;
  14429. }
  14430. /* Check if SSL is required.
  14431. * If so, dynamically load SSL library
  14432. * and set up ctx->ssl_ctx pointer. */
  14433. static int
  14434. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14435. {
  14436. void *ssl_ctx = 0;
  14437. int callback_ret;
  14438. const char *pem;
  14439. const char *chain;
  14440. char ebuf[128];
  14441. if (!phys_ctx) {
  14442. return 0;
  14443. }
  14444. if (!dom_ctx) {
  14445. dom_ctx = &(phys_ctx->dd);
  14446. }
  14447. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14448. /* No SSL port is set. No need to setup SSL. */
  14449. return 1;
  14450. }
  14451. /* Check for external SSL_CTX */
  14452. callback_ret =
  14453. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14454. ? 0
  14455. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14456. phys_ctx->user_data));
  14457. if (callback_ret < 0) {
  14458. mg_cry_ctx_internal(phys_ctx,
  14459. "external_ssl_ctx callback returned error: %i",
  14460. callback_ret);
  14461. return 0;
  14462. } else if (callback_ret > 0) {
  14463. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14464. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14465. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14466. return 0;
  14467. }
  14468. return 1;
  14469. }
  14470. /* Check for external domain SSL_CTX */
  14471. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14472. ? 0
  14473. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14474. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14475. &ssl_ctx,
  14476. phys_ctx->user_data));
  14477. if (callback_ret < 0) {
  14478. mg_cry_ctx_internal(
  14479. phys_ctx,
  14480. "external_ssl_ctx_domain callback returned error: %i",
  14481. callback_ret);
  14482. return 0;
  14483. } else if (callback_ret > 0) {
  14484. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14485. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14486. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14487. return 0;
  14488. }
  14489. return 1;
  14490. }
  14491. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14492. * 0, CivetWeb should continue initializing SSL */
  14493. /* If PEM file is not specified and the init_ssl callbacks
  14494. * are not specified, setup will fail. */
  14495. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14496. && (phys_ctx->callbacks.init_ssl == NULL)
  14497. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14498. /* No certificate and no init_ssl callbacks:
  14499. * Essential data to set up TLS is missing.
  14500. */
  14501. mg_cry_ctx_internal(phys_ctx,
  14502. "Initializing SSL failed: -%s is not set",
  14503. config_options[SSL_CERTIFICATE].name);
  14504. return 0;
  14505. }
  14506. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14507. if (chain == NULL) {
  14508. chain = pem;
  14509. }
  14510. if ((chain != NULL) && (*chain == 0)) {
  14511. chain = NULL;
  14512. }
  14513. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14514. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14515. return 0;
  14516. }
  14517. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14518. }
  14519. static void
  14520. uninitialize_ssl(void)
  14521. {
  14522. #if defined(OPENSSL_API_1_1)
  14523. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14524. /* Shutdown according to
  14525. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14526. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14527. */
  14528. CONF_modules_unload(1);
  14529. #else
  14530. int i;
  14531. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14532. /* Shutdown according to
  14533. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14534. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14535. */
  14536. CRYPTO_set_locking_callback(NULL);
  14537. CRYPTO_set_id_callback(NULL);
  14538. ENGINE_cleanup();
  14539. CONF_modules_unload(1);
  14540. ERR_free_strings();
  14541. EVP_cleanup();
  14542. CRYPTO_cleanup_all_ex_data();
  14543. OPENSSL_REMOVE_THREAD_STATE();
  14544. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14545. pthread_mutex_destroy(&ssl_mutexes[i]);
  14546. }
  14547. mg_free(ssl_mutexes);
  14548. ssl_mutexes = NULL;
  14549. #endif /* OPENSSL_API_1_1 */
  14550. }
  14551. }
  14552. #endif /* !NO_SSL */
  14553. #if !defined(NO_FILESYSTEMS)
  14554. static int
  14555. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14556. {
  14557. if (phys_ctx) {
  14558. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14559. const char *path;
  14560. struct mg_connection fc;
  14561. if (!dom_ctx) {
  14562. dom_ctx = &(phys_ctx->dd);
  14563. }
  14564. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14565. if ((path != NULL)
  14566. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14567. mg_cry_ctx_internal(phys_ctx,
  14568. "Cannot open %s: %s",
  14569. path,
  14570. strerror(ERRNO));
  14571. return 0;
  14572. }
  14573. return 1;
  14574. }
  14575. return 0;
  14576. }
  14577. #endif /* NO_FILESYSTEMS */
  14578. static int
  14579. set_acl_option(struct mg_context *phys_ctx)
  14580. {
  14581. union usa sa;
  14582. memset(&sa, 0, sizeof(sa));
  14583. #if defined(USE_IPV6)
  14584. sa.sin6.sin6_family = AF_INET6;
  14585. #else
  14586. sa.sin.sin_family = AF_INET;
  14587. #endif
  14588. return check_acl(phys_ctx, &sa) != -1;
  14589. }
  14590. static void
  14591. reset_per_request_attributes(struct mg_connection *conn)
  14592. {
  14593. if (!conn) {
  14594. return;
  14595. }
  14596. conn->connection_type =
  14597. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14598. conn->num_bytes_sent = conn->consumed_content = 0;
  14599. conn->path_info = NULL;
  14600. conn->status_code = -1;
  14601. conn->content_len = -1;
  14602. conn->is_chunked = 0;
  14603. conn->must_close = 0;
  14604. conn->request_len = 0;
  14605. conn->throttle = 0;
  14606. conn->accept_gzip = 0;
  14607. conn->response_info.content_length = conn->request_info.content_length = -1;
  14608. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14609. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14610. conn->response_info.status_text = NULL;
  14611. conn->response_info.status_code = 0;
  14612. conn->request_info.remote_user = NULL;
  14613. conn->request_info.request_method = NULL;
  14614. conn->request_info.request_uri = NULL;
  14615. conn->request_info.local_uri = NULL;
  14616. #if defined(MG_LEGACY_INTERFACE)
  14617. /* Legacy before split into local_uri and request_uri */
  14618. conn->request_info.uri = NULL;
  14619. #endif
  14620. }
  14621. static int
  14622. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14623. {
  14624. if (setsockopt(sock,
  14625. IPPROTO_TCP,
  14626. TCP_NODELAY,
  14627. (SOCK_OPT_TYPE)&nodelay_on,
  14628. sizeof(nodelay_on))
  14629. != 0) {
  14630. /* Error */
  14631. return 1;
  14632. }
  14633. /* OK */
  14634. return 0;
  14635. }
  14636. #if !defined(__ZEPHYR__)
  14637. static void
  14638. close_socket_gracefully(struct mg_connection *conn)
  14639. {
  14640. #if defined(_WIN32)
  14641. char buf[MG_BUF_LEN];
  14642. int n;
  14643. #endif
  14644. struct linger linger;
  14645. int error_code = 0;
  14646. int linger_timeout = -2;
  14647. socklen_t opt_len = sizeof(error_code);
  14648. if (!conn) {
  14649. return;
  14650. }
  14651. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14652. * "Note that enabling a nonzero timeout on a nonblocking socket
  14653. * is not recommended.", so set it to blocking now */
  14654. set_blocking_mode(conn->client.sock);
  14655. /* Send FIN to the client */
  14656. shutdown(conn->client.sock, SHUTDOWN_WR);
  14657. #if defined(_WIN32)
  14658. /* Read and discard pending incoming data. If we do not do that and
  14659. * close
  14660. * the socket, the data in the send buffer may be discarded. This
  14661. * behaviour is seen on Windows, when client keeps sending data
  14662. * when server decides to close the connection; then when client
  14663. * does recv() it gets no data back. */
  14664. do {
  14665. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14666. } while (n > 0);
  14667. #endif
  14668. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14669. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14670. }
  14671. /* Set linger option according to configuration */
  14672. if (linger_timeout >= 0) {
  14673. /* Set linger option to avoid socket hanging out after close. This
  14674. * prevent ephemeral port exhaust problem under high QPS. */
  14675. linger.l_onoff = 1;
  14676. #if defined(_MSC_VER)
  14677. #pragma warning(push)
  14678. #pragma warning(disable : 4244)
  14679. #endif
  14680. #if defined(GCC_DIAGNOSTIC)
  14681. #pragma GCC diagnostic push
  14682. #pragma GCC diagnostic ignored "-Wconversion"
  14683. #endif
  14684. /* Data type of linger structure elements may differ,
  14685. * so we don't know what cast we need here.
  14686. * Disable type conversion warnings. */
  14687. linger.l_linger = (linger_timeout + 999) / 1000;
  14688. #if defined(GCC_DIAGNOSTIC)
  14689. #pragma GCC diagnostic pop
  14690. #endif
  14691. #if defined(_MSC_VER)
  14692. #pragma warning(pop)
  14693. #endif
  14694. } else {
  14695. linger.l_onoff = 0;
  14696. linger.l_linger = 0;
  14697. }
  14698. if (linger_timeout < -1) {
  14699. /* Default: don't configure any linger */
  14700. } else if (getsockopt(conn->client.sock,
  14701. SOL_SOCKET,
  14702. SO_ERROR,
  14703. #if defined(_WIN32) /* WinSock uses different data type here */
  14704. (char *)&error_code,
  14705. #else
  14706. &error_code,
  14707. #endif
  14708. &opt_len)
  14709. != 0) {
  14710. /* Cannot determine if socket is already closed. This should
  14711. * not occur and never did in a test. Log an error message
  14712. * and continue. */
  14713. mg_cry_internal(conn,
  14714. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14715. __func__,
  14716. strerror(ERRNO));
  14717. #if defined(_WIN32)
  14718. } else if (error_code == WSAECONNRESET) {
  14719. #else
  14720. } else if (error_code == ECONNRESET) {
  14721. #endif
  14722. /* Socket already closed by client/peer, close socket without linger
  14723. */
  14724. } else {
  14725. /* Set linger timeout */
  14726. if (setsockopt(conn->client.sock,
  14727. SOL_SOCKET,
  14728. SO_LINGER,
  14729. (char *)&linger,
  14730. sizeof(linger))
  14731. != 0) {
  14732. mg_cry_internal(
  14733. conn,
  14734. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14735. __func__,
  14736. linger.l_onoff,
  14737. linger.l_linger,
  14738. strerror(ERRNO));
  14739. }
  14740. }
  14741. /* Now we know that our FIN is ACK-ed, safe to close */
  14742. closesocket(conn->client.sock);
  14743. conn->client.sock = INVALID_SOCKET;
  14744. }
  14745. #endif
  14746. static void
  14747. close_connection(struct mg_connection *conn)
  14748. {
  14749. #if defined(USE_SERVER_STATS)
  14750. conn->conn_state = 6; /* to close */
  14751. #endif
  14752. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14753. if (conn->lua_websocket_state) {
  14754. lua_websocket_close(conn, conn->lua_websocket_state);
  14755. conn->lua_websocket_state = NULL;
  14756. }
  14757. #endif
  14758. mg_lock_connection(conn);
  14759. /* Set close flag, so keep-alive loops will stop */
  14760. conn->must_close = 1;
  14761. /* call the connection_close callback if assigned */
  14762. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14763. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14764. conn->phys_ctx->callbacks.connection_close(conn);
  14765. }
  14766. }
  14767. /* Reset user data, after close callback is called.
  14768. * Do not reuse it. If the user needs a destructor,
  14769. * it must be done in the connection_close callback. */
  14770. mg_set_user_connection_data(conn, NULL);
  14771. #if defined(USE_SERVER_STATS)
  14772. conn->conn_state = 7; /* closing */
  14773. #endif
  14774. #if !defined(NO_SSL)
  14775. if (conn->ssl != NULL) {
  14776. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14777. */
  14778. SSL_shutdown(conn->ssl);
  14779. SSL_free(conn->ssl);
  14780. OPENSSL_REMOVE_THREAD_STATE();
  14781. conn->ssl = NULL;
  14782. }
  14783. #endif
  14784. if (conn->client.sock != INVALID_SOCKET) {
  14785. #if defined(__ZEPHYR__)
  14786. closesocket(conn->client.sock);
  14787. #else
  14788. close_socket_gracefully(conn);
  14789. #endif
  14790. conn->client.sock = INVALID_SOCKET;
  14791. }
  14792. mg_unlock_connection(conn);
  14793. #if defined(USE_SERVER_STATS)
  14794. conn->conn_state = 8; /* closed */
  14795. #endif
  14796. }
  14797. void
  14798. mg_close_connection(struct mg_connection *conn)
  14799. {
  14800. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14801. return;
  14802. }
  14803. #if defined(USE_WEBSOCKET)
  14804. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14805. if (conn->in_websocket_handling) {
  14806. /* Set close flag, so the server thread can exit. */
  14807. conn->must_close = 1;
  14808. return;
  14809. }
  14810. }
  14811. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14812. unsigned int i;
  14813. /* client context: loops must end */
  14814. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14815. conn->must_close = 1;
  14816. /* We need to get the client thread out of the select/recv call
  14817. * here. */
  14818. /* Since we use a sleep quantum of some seconds to check for recv
  14819. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14820. /* join worker thread */
  14821. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14822. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14823. }
  14824. }
  14825. #endif /* defined(USE_WEBSOCKET) */
  14826. close_connection(conn);
  14827. #if !defined(NO_SSL)
  14828. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14829. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14830. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14831. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14832. }
  14833. #endif
  14834. #if defined(USE_WEBSOCKET)
  14835. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14836. mg_free(conn->phys_ctx->worker_threadids);
  14837. (void)pthread_mutex_destroy(&conn->mutex);
  14838. mg_free(conn);
  14839. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14840. (void)pthread_mutex_destroy(&conn->mutex);
  14841. mg_free(conn);
  14842. }
  14843. #else
  14844. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14845. (void)pthread_mutex_destroy(&conn->mutex);
  14846. mg_free(conn);
  14847. }
  14848. #endif /* defined(USE_WEBSOCKET) */
  14849. }
  14850. static struct mg_connection *
  14851. mg_connect_client_impl(const struct mg_client_options *client_options,
  14852. int use_ssl,
  14853. char *ebuf,
  14854. size_t ebuf_len)
  14855. {
  14856. struct mg_connection *conn = NULL;
  14857. SOCKET sock;
  14858. union usa sa;
  14859. struct sockaddr *psa;
  14860. socklen_t len;
  14861. unsigned max_req_size =
  14862. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14863. /* Size of structures, aligned to 8 bytes */
  14864. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14865. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14866. conn =
  14867. (struct mg_connection *)mg_calloc(1,
  14868. conn_size + ctx_size + max_req_size);
  14869. if (conn == NULL) {
  14870. mg_snprintf(NULL,
  14871. NULL, /* No truncation check for ebuf */
  14872. ebuf,
  14873. ebuf_len,
  14874. "calloc(): %s",
  14875. strerror(ERRNO));
  14876. return NULL;
  14877. }
  14878. #if defined(GCC_DIAGNOSTIC)
  14879. #pragma GCC diagnostic push
  14880. #pragma GCC diagnostic ignored "-Wcast-align"
  14881. #endif /* defined(GCC_DIAGNOSTIC) */
  14882. /* conn_size is aligned to 8 bytes */
  14883. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14884. #if defined(GCC_DIAGNOSTIC)
  14885. #pragma GCC diagnostic pop
  14886. #endif /* defined(GCC_DIAGNOSTIC) */
  14887. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14888. conn->buf_size = (int)max_req_size;
  14889. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14890. conn->dom_ctx = &(conn->phys_ctx->dd);
  14891. if (!connect_socket(conn->phys_ctx,
  14892. client_options->host,
  14893. client_options->port,
  14894. use_ssl,
  14895. ebuf,
  14896. ebuf_len,
  14897. &sock,
  14898. &sa)) {
  14899. /* ebuf is set by connect_socket,
  14900. * free all memory and return NULL; */
  14901. mg_free(conn);
  14902. return NULL;
  14903. }
  14904. #if !defined(NO_SSL)
  14905. #if defined(OPENSSL_API_1_1)
  14906. if (use_ssl
  14907. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14908. == NULL) {
  14909. mg_snprintf(NULL,
  14910. NULL, /* No truncation check for ebuf */
  14911. ebuf,
  14912. ebuf_len,
  14913. "SSL_CTX_new error: %s",
  14914. ssl_error());
  14915. closesocket(sock);
  14916. mg_free(conn);
  14917. return NULL;
  14918. }
  14919. #else
  14920. if (use_ssl
  14921. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14922. == NULL) {
  14923. mg_snprintf(NULL,
  14924. NULL, /* No truncation check for ebuf */
  14925. ebuf,
  14926. ebuf_len,
  14927. "SSL_CTX_new error: %s",
  14928. ssl_error());
  14929. closesocket(sock);
  14930. mg_free(conn);
  14931. return NULL;
  14932. }
  14933. #endif /* OPENSSL_API_1_1 */
  14934. #endif /* NO_SSL */
  14935. #if defined(USE_IPV6)
  14936. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14937. : sizeof(conn->client.rsa.sin6);
  14938. psa = (sa.sa.sa_family == AF_INET)
  14939. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14940. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14941. #else
  14942. len = sizeof(conn->client.rsa.sin);
  14943. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14944. #endif
  14945. conn->client.sock = sock;
  14946. conn->client.lsa = sa;
  14947. if (getsockname(sock, psa, &len) != 0) {
  14948. mg_cry_internal(conn,
  14949. "%s: getsockname() failed: %s",
  14950. __func__,
  14951. strerror(ERRNO));
  14952. }
  14953. conn->client.is_ssl = use_ssl ? 1 : 0;
  14954. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14955. mg_snprintf(NULL,
  14956. NULL, /* No truncation check for ebuf */
  14957. ebuf,
  14958. ebuf_len,
  14959. "Can not create mutex");
  14960. #if !defined(NO_SSL)
  14961. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14962. #endif
  14963. closesocket(sock);
  14964. mg_free(conn);
  14965. return NULL;
  14966. }
  14967. #if !defined(NO_SSL)
  14968. if (use_ssl) {
  14969. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14970. * SSL_CTX_set_verify call is needed to switch off server
  14971. * certificate checking, which is off by default in OpenSSL and
  14972. * on in yaSSL. */
  14973. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14974. * SSL_VERIFY_PEER, verify_ssl_server); */
  14975. if (client_options->client_cert) {
  14976. if (!ssl_use_pem_file(conn->phys_ctx,
  14977. conn->dom_ctx,
  14978. client_options->client_cert,
  14979. NULL)) {
  14980. mg_snprintf(NULL,
  14981. NULL, /* No truncation check for ebuf */
  14982. ebuf,
  14983. ebuf_len,
  14984. "Can not use SSL client certificate");
  14985. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14986. closesocket(sock);
  14987. mg_free(conn);
  14988. return NULL;
  14989. }
  14990. }
  14991. if (client_options->server_cert) {
  14992. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14993. client_options->server_cert,
  14994. NULL)
  14995. != 1) {
  14996. mg_cry_internal(conn,
  14997. "SSL_CTX_load_verify_locations error: %s ",
  14998. ssl_error());
  14999. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15000. closesocket(sock);
  15001. mg_free(conn);
  15002. return NULL;
  15003. }
  15004. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15005. } else {
  15006. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15007. }
  15008. if (!sslize(conn, SSL_connect, client_options)) {
  15009. mg_snprintf(NULL,
  15010. NULL, /* No truncation check for ebuf */
  15011. ebuf,
  15012. ebuf_len,
  15013. "SSL connection error");
  15014. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15015. closesocket(sock);
  15016. mg_free(conn);
  15017. return NULL;
  15018. }
  15019. }
  15020. #endif
  15021. return conn;
  15022. }
  15023. CIVETWEB_API struct mg_connection *
  15024. mg_connect_client_secure(const struct mg_client_options *client_options,
  15025. char *error_buffer,
  15026. size_t error_buffer_size)
  15027. {
  15028. return mg_connect_client_impl(client_options,
  15029. 1,
  15030. error_buffer,
  15031. error_buffer_size);
  15032. }
  15033. struct mg_connection *
  15034. mg_connect_client(const char *host,
  15035. int port,
  15036. int use_ssl,
  15037. char *error_buffer,
  15038. size_t error_buffer_size)
  15039. {
  15040. struct mg_client_options opts;
  15041. memset(&opts, 0, sizeof(opts));
  15042. opts.host = host;
  15043. opts.port = port;
  15044. return mg_connect_client_impl(&opts,
  15045. use_ssl,
  15046. error_buffer,
  15047. error_buffer_size);
  15048. }
  15049. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15050. struct mg_connection *
  15051. mg_connect_client2(const char *host,
  15052. const char *protocol,
  15053. int port,
  15054. const char *path,
  15055. struct mg_init_data *init,
  15056. struct mg_error_data *error)
  15057. {
  15058. int is_ssl, is_ws;
  15059. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15060. if (error != NULL) {
  15061. error->code = 0;
  15062. if (error->text_buffer_size > 0) {
  15063. *error->text = 0;
  15064. }
  15065. }
  15066. if ((host == NULL) || (protocol == NULL)) {
  15067. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15068. mg_snprintf(NULL,
  15069. NULL, /* No truncation check for error buffers */
  15070. error->text,
  15071. error->text_buffer_size,
  15072. "%s",
  15073. "Invalid parameters");
  15074. }
  15075. return NULL;
  15076. }
  15077. /* check all known protocolls */
  15078. if (!mg_strcasecmp(protocol, "http")) {
  15079. is_ssl = 0;
  15080. is_ws = 0;
  15081. } else if (!mg_strcasecmp(protocol, "https")) {
  15082. is_ssl = 1;
  15083. is_ws = 0;
  15084. #if defined(USE_WEBSOCKET)
  15085. } else if (!mg_strcasecmp(protocol, "ws")) {
  15086. is_ssl = 0;
  15087. is_ws = 1;
  15088. } else if (!mg_strcasecmp(protocol, "wss")) {
  15089. is_ssl = 1;
  15090. is_ws = 1;
  15091. #endif
  15092. } else {
  15093. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15094. mg_snprintf(NULL,
  15095. NULL, /* No truncation check for error buffers */
  15096. error->text,
  15097. error->text_buffer_size,
  15098. "Protocol %s not supported",
  15099. protocol);
  15100. }
  15101. return NULL;
  15102. }
  15103. /* TODO: The current implementation here just calls the old
  15104. * implementations, without using any new options. This is just a first
  15105. * step to test the new interfaces. */
  15106. #if defined(USE_WEBSOCKET)
  15107. if (is_ws) {
  15108. /* TODO: implement all options */
  15109. return mg_connect_websocket_client(
  15110. host,
  15111. port,
  15112. is_ssl,
  15113. ((error != NULL) ? error->text : NULL),
  15114. ((error != NULL) ? error->text_buffer_size : 0),
  15115. (path ? path : ""),
  15116. NULL /* TODO: origin */,
  15117. deprecated_websocket_data_wrapper,
  15118. deprecated_websocket_close_wrapper,
  15119. (void *)init->callbacks);
  15120. }
  15121. #endif
  15122. /* TODO: all additional options */
  15123. struct mg_client_options opts;
  15124. memset(&opts, 0, sizeof(opts));
  15125. opts.host = host;
  15126. opts.port = port;
  15127. return mg_connect_client_impl(&opts,
  15128. is_ssl,
  15129. ((error != NULL) ? error->text : NULL),
  15130. ((error != NULL) ? error->text_buffer_size
  15131. : 0));
  15132. }
  15133. #endif
  15134. static const struct {
  15135. const char *proto;
  15136. size_t proto_len;
  15137. unsigned default_port;
  15138. } abs_uri_protocols[] = {{"http://", 7, 80},
  15139. {"https://", 8, 443},
  15140. {"ws://", 5, 80},
  15141. {"wss://", 6, 443},
  15142. {NULL, 0, 0}};
  15143. /* Check if the uri is valid.
  15144. * return 0 for invalid uri,
  15145. * return 1 for *,
  15146. * return 2 for relative uri,
  15147. * return 3 for absolute uri without port,
  15148. * return 4 for absolute uri with port */
  15149. static int
  15150. get_uri_type(const char *uri)
  15151. {
  15152. int i;
  15153. const char *hostend, *portbegin;
  15154. char *portend;
  15155. unsigned long port;
  15156. /* According to the HTTP standard
  15157. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15158. * URI can be an asterisk (*) or should start with slash (relative uri),
  15159. * or it should start with the protocol (absolute uri). */
  15160. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15161. /* asterisk */
  15162. return 1;
  15163. }
  15164. /* Valid URIs according to RFC 3986
  15165. * (https://www.ietf.org/rfc/rfc3986.txt)
  15166. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15167. * and unreserved characters A-Z a-z 0-9 and -._~
  15168. * and % encoded symbols.
  15169. */
  15170. for (i = 0; uri[i] != 0; i++) {
  15171. if (uri[i] < 33) {
  15172. /* control characters and spaces are invalid */
  15173. return 0;
  15174. }
  15175. if (uri[i] > 126) {
  15176. /* non-ascii characters must be % encoded */
  15177. return 0;
  15178. } else {
  15179. switch (uri[i]) {
  15180. case '"': /* 34 */
  15181. case '<': /* 60 */
  15182. case '>': /* 62 */
  15183. case '\\': /* 92 */
  15184. case '^': /* 94 */
  15185. case '`': /* 96 */
  15186. case '{': /* 123 */
  15187. case '|': /* 124 */
  15188. case '}': /* 125 */
  15189. return 0;
  15190. default:
  15191. /* character is ok */
  15192. break;
  15193. }
  15194. }
  15195. }
  15196. /* A relative uri starts with a / character */
  15197. if (uri[0] == '/') {
  15198. /* relative uri */
  15199. return 2;
  15200. }
  15201. /* It could be an absolute uri: */
  15202. /* This function only checks if the uri is valid, not if it is
  15203. * addressing the current server. So civetweb can also be used
  15204. * as a proxy server. */
  15205. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15206. if (mg_strncasecmp(uri,
  15207. abs_uri_protocols[i].proto,
  15208. abs_uri_protocols[i].proto_len)
  15209. == 0) {
  15210. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15211. if (!hostend) {
  15212. return 0;
  15213. }
  15214. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15215. if (!portbegin) {
  15216. return 3;
  15217. }
  15218. port = strtoul(portbegin + 1, &portend, 10);
  15219. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15220. return 0;
  15221. }
  15222. return 4;
  15223. }
  15224. }
  15225. return 0;
  15226. }
  15227. /* Return NULL or the relative uri at the current server */
  15228. static const char *
  15229. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15230. {
  15231. const char *server_domain;
  15232. size_t server_domain_len;
  15233. size_t request_domain_len = 0;
  15234. unsigned long port = 0;
  15235. int i, auth_domain_check_enabled;
  15236. const char *hostbegin = NULL;
  15237. const char *hostend = NULL;
  15238. const char *portbegin;
  15239. char *portend;
  15240. auth_domain_check_enabled =
  15241. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15242. /* DNS is case insensitive, so use case insensitive string compare here
  15243. */
  15244. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15245. if (mg_strncasecmp(uri,
  15246. abs_uri_protocols[i].proto,
  15247. abs_uri_protocols[i].proto_len)
  15248. == 0) {
  15249. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15250. hostend = strchr(hostbegin, '/');
  15251. if (!hostend) {
  15252. return 0;
  15253. }
  15254. portbegin = strchr(hostbegin, ':');
  15255. if ((!portbegin) || (portbegin > hostend)) {
  15256. port = abs_uri_protocols[i].default_port;
  15257. request_domain_len = (size_t)(hostend - hostbegin);
  15258. } else {
  15259. port = strtoul(portbegin + 1, &portend, 10);
  15260. if ((portend != hostend) || (port <= 0)
  15261. || !is_valid_port(port)) {
  15262. return 0;
  15263. }
  15264. request_domain_len = (size_t)(portbegin - hostbegin);
  15265. }
  15266. /* protocol found, port set */
  15267. break;
  15268. }
  15269. }
  15270. if (!port) {
  15271. /* port remains 0 if the protocol is not found */
  15272. return 0;
  15273. }
  15274. /* Check if the request is directed to a different server. */
  15275. /* First check if the port is the same (IPv4 and IPv6). */
  15276. #if defined(USE_IPV6)
  15277. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  15278. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  15279. /* Request is directed to a different port */
  15280. return 0;
  15281. }
  15282. } else
  15283. #endif
  15284. {
  15285. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  15286. /* Request is directed to a different port */
  15287. return 0;
  15288. }
  15289. }
  15290. /* Finally check if the server corresponds to the authentication
  15291. * domain of the server (the server domain).
  15292. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15293. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15294. * but do not allow substrings (like
  15295. * http://notmydomain.com/path/file.ext
  15296. * or http://mydomain.com.fake/path/file.ext).
  15297. */
  15298. if (auth_domain_check_enabled) {
  15299. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15300. server_domain_len = strlen(server_domain);
  15301. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15302. return 0;
  15303. }
  15304. if ((request_domain_len == server_domain_len)
  15305. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15306. /* Request is directed to this server - full name match. */
  15307. } else {
  15308. if (request_domain_len < (server_domain_len + 2)) {
  15309. /* Request is directed to another server: The server name
  15310. * is longer than the request name.
  15311. * Drop this case here to avoid overflows in the
  15312. * following checks. */
  15313. return 0;
  15314. }
  15315. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15316. /* Request is directed to another server: It could be a
  15317. * substring
  15318. * like notmyserver.com */
  15319. return 0;
  15320. }
  15321. if (0
  15322. != memcmp(server_domain,
  15323. hostbegin + request_domain_len - server_domain_len,
  15324. server_domain_len)) {
  15325. /* Request is directed to another server:
  15326. * The server name is different. */
  15327. return 0;
  15328. }
  15329. }
  15330. }
  15331. return hostend;
  15332. }
  15333. static int
  15334. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15335. {
  15336. if (ebuf_len > 0) {
  15337. ebuf[0] = '\0';
  15338. }
  15339. *err = 0;
  15340. reset_per_request_attributes(conn);
  15341. if (!conn) {
  15342. mg_snprintf(conn,
  15343. NULL, /* No truncation check for ebuf */
  15344. ebuf,
  15345. ebuf_len,
  15346. "%s",
  15347. "Internal error");
  15348. *err = 500;
  15349. return 0;
  15350. }
  15351. /* Set the time the request was received. This value should be used for
  15352. * timeouts. */
  15353. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15354. conn->request_len =
  15355. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15356. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15357. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15358. mg_snprintf(conn,
  15359. NULL, /* No truncation check for ebuf */
  15360. ebuf,
  15361. ebuf_len,
  15362. "%s",
  15363. "Invalid message size");
  15364. *err = 500;
  15365. return 0;
  15366. }
  15367. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15368. mg_snprintf(conn,
  15369. NULL, /* No truncation check for ebuf */
  15370. ebuf,
  15371. ebuf_len,
  15372. "%s",
  15373. "Message too large");
  15374. *err = 413;
  15375. return 0;
  15376. }
  15377. if (conn->request_len <= 0) {
  15378. if (conn->data_len > 0) {
  15379. mg_snprintf(conn,
  15380. NULL, /* No truncation check for ebuf */
  15381. ebuf,
  15382. ebuf_len,
  15383. "%s",
  15384. "Malformed message");
  15385. *err = 400;
  15386. } else {
  15387. /* Server did not recv anything -> just close the connection */
  15388. conn->must_close = 1;
  15389. mg_snprintf(conn,
  15390. NULL, /* No truncation check for ebuf */
  15391. ebuf,
  15392. ebuf_len,
  15393. "%s",
  15394. "No data received");
  15395. *err = 0;
  15396. }
  15397. return 0;
  15398. }
  15399. return 1;
  15400. }
  15401. static int
  15402. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15403. {
  15404. const char *cl;
  15405. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15406. return 0;
  15407. }
  15408. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15409. <= 0) {
  15410. mg_snprintf(conn,
  15411. NULL, /* No truncation check for ebuf */
  15412. ebuf,
  15413. ebuf_len,
  15414. "%s",
  15415. "Bad request");
  15416. *err = 400;
  15417. return 0;
  15418. }
  15419. /* Message is a valid request */
  15420. if (!switch_domain_context(conn)) {
  15421. mg_snprintf(conn,
  15422. NULL, /* No truncation check for ebuf */
  15423. ebuf,
  15424. ebuf_len,
  15425. "%s",
  15426. "Bad request: Host mismatch");
  15427. *err = 400;
  15428. return 0;
  15429. }
  15430. if (((cl = get_header(conn->request_info.http_headers,
  15431. conn->request_info.num_headers,
  15432. "Transfer-Encoding"))
  15433. != NULL)
  15434. && mg_strcasecmp(cl, "identity")) {
  15435. if (mg_strcasecmp(cl, "chunked")) {
  15436. mg_snprintf(conn,
  15437. NULL, /* No truncation check for ebuf */
  15438. ebuf,
  15439. ebuf_len,
  15440. "%s",
  15441. "Bad request");
  15442. *err = 400;
  15443. return 0;
  15444. }
  15445. conn->is_chunked = 1;
  15446. conn->content_len = 0; /* not yet read */
  15447. } else if ((cl = get_header(conn->request_info.http_headers,
  15448. conn->request_info.num_headers,
  15449. "Content-Length"))
  15450. != NULL) {
  15451. /* Request has content length set */
  15452. char *endptr = NULL;
  15453. conn->content_len = strtoll(cl, &endptr, 10);
  15454. if ((endptr == cl) || (conn->content_len < 0)) {
  15455. mg_snprintf(conn,
  15456. NULL, /* No truncation check for ebuf */
  15457. ebuf,
  15458. ebuf_len,
  15459. "%s",
  15460. "Bad request");
  15461. *err = 411;
  15462. return 0;
  15463. }
  15464. /* Publish the content length back to the request info. */
  15465. conn->request_info.content_length = conn->content_len;
  15466. } else {
  15467. /* There is no exception, see RFC7230. */
  15468. conn->content_len = 0;
  15469. }
  15470. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15471. return 1;
  15472. }
  15473. /* conn is assumed to be valid in this internal function */
  15474. static int
  15475. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15476. {
  15477. const char *cl;
  15478. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15479. return 0;
  15480. }
  15481. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15482. <= 0) {
  15483. mg_snprintf(conn,
  15484. NULL, /* No truncation check for ebuf */
  15485. ebuf,
  15486. ebuf_len,
  15487. "%s",
  15488. "Bad response");
  15489. *err = 400;
  15490. return 0;
  15491. }
  15492. /* Message is a valid response */
  15493. if (((cl = get_header(conn->response_info.http_headers,
  15494. conn->response_info.num_headers,
  15495. "Transfer-Encoding"))
  15496. != NULL)
  15497. && mg_strcasecmp(cl, "identity")) {
  15498. if (mg_strcasecmp(cl, "chunked")) {
  15499. mg_snprintf(conn,
  15500. NULL, /* No truncation check for ebuf */
  15501. ebuf,
  15502. ebuf_len,
  15503. "%s",
  15504. "Bad request");
  15505. *err = 400;
  15506. return 0;
  15507. }
  15508. conn->is_chunked = 1;
  15509. conn->content_len = 0; /* not yet read */
  15510. } else if ((cl = get_header(conn->response_info.http_headers,
  15511. conn->response_info.num_headers,
  15512. "Content-Length"))
  15513. != NULL) {
  15514. char *endptr = NULL;
  15515. conn->content_len = strtoll(cl, &endptr, 10);
  15516. if ((endptr == cl) || (conn->content_len < 0)) {
  15517. mg_snprintf(conn,
  15518. NULL, /* No truncation check for ebuf */
  15519. ebuf,
  15520. ebuf_len,
  15521. "%s",
  15522. "Bad request");
  15523. *err = 411;
  15524. return 0;
  15525. }
  15526. /* Publish the content length back to the response info. */
  15527. conn->response_info.content_length = conn->content_len;
  15528. /* TODO: check if it is still used in response_info */
  15529. conn->request_info.content_length = conn->content_len;
  15530. /* TODO: we should also consider HEAD method */
  15531. if (conn->response_info.status_code == 304) {
  15532. conn->content_len = 0;
  15533. }
  15534. } else {
  15535. /* TODO: we should also consider HEAD method */
  15536. if (((conn->response_info.status_code >= 100)
  15537. && (conn->response_info.status_code <= 199))
  15538. || (conn->response_info.status_code == 204)
  15539. || (conn->response_info.status_code == 304)) {
  15540. conn->content_len = 0;
  15541. } else {
  15542. conn->content_len = -1; /* unknown content length */
  15543. }
  15544. }
  15545. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15546. return 1;
  15547. }
  15548. int
  15549. mg_get_response(struct mg_connection *conn,
  15550. char *ebuf,
  15551. size_t ebuf_len,
  15552. int timeout)
  15553. {
  15554. int err, ret;
  15555. char txt[32]; /* will not overflow */
  15556. char *save_timeout;
  15557. char *new_timeout;
  15558. if (ebuf_len > 0) {
  15559. ebuf[0] = '\0';
  15560. }
  15561. if (!conn) {
  15562. mg_snprintf(conn,
  15563. NULL, /* No truncation check for ebuf */
  15564. ebuf,
  15565. ebuf_len,
  15566. "%s",
  15567. "Parameter error");
  15568. return -1;
  15569. }
  15570. /* Reset the previous responses */
  15571. conn->data_len = 0;
  15572. /* Implementation of API function for HTTP clients */
  15573. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15574. if (timeout >= 0) {
  15575. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15576. new_timeout = txt;
  15577. } else {
  15578. new_timeout = NULL;
  15579. }
  15580. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15581. ret = get_response(conn, ebuf, ebuf_len, &err);
  15582. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15583. #if defined(MG_LEGACY_INTERFACE)
  15584. /* TODO: 1) uri is deprecated;
  15585. * 2) here, ri.uri is the http response code */
  15586. conn->request_info.uri = conn->request_info.request_uri;
  15587. #endif
  15588. conn->request_info.local_uri = conn->request_info.request_uri;
  15589. /* TODO (mid): Define proper return values - maybe return length?
  15590. * For the first test use <0 for error and >0 for OK */
  15591. return (ret == 0) ? -1 : +1;
  15592. }
  15593. struct mg_connection *
  15594. mg_download(const char *host,
  15595. int port,
  15596. int use_ssl,
  15597. char *ebuf,
  15598. size_t ebuf_len,
  15599. const char *fmt,
  15600. ...)
  15601. {
  15602. struct mg_connection *conn;
  15603. va_list ap;
  15604. int i;
  15605. int reqerr;
  15606. if (ebuf_len > 0) {
  15607. ebuf[0] = '\0';
  15608. }
  15609. va_start(ap, fmt);
  15610. /* open a connection */
  15611. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15612. if (conn != NULL) {
  15613. i = mg_vprintf(conn, fmt, ap);
  15614. if (i <= 0) {
  15615. mg_snprintf(conn,
  15616. NULL, /* No truncation check for ebuf */
  15617. ebuf,
  15618. ebuf_len,
  15619. "%s",
  15620. "Error sending request");
  15621. } else {
  15622. /* make sure the buffer is clear */
  15623. conn->data_len = 0;
  15624. get_response(conn, ebuf, ebuf_len, &reqerr);
  15625. #if defined(MG_LEGACY_INTERFACE)
  15626. /* TODO: 1) uri is deprecated;
  15627. * 2) here, ri.uri is the http response code */
  15628. conn->request_info.uri = conn->request_info.request_uri;
  15629. #endif
  15630. conn->request_info.local_uri = conn->request_info.request_uri;
  15631. }
  15632. }
  15633. /* if an error occurred, close the connection */
  15634. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15635. mg_close_connection(conn);
  15636. conn = NULL;
  15637. }
  15638. va_end(ap);
  15639. return conn;
  15640. }
  15641. struct websocket_client_thread_data {
  15642. struct mg_connection *conn;
  15643. mg_websocket_data_handler data_handler;
  15644. mg_websocket_close_handler close_handler;
  15645. void *callback_data;
  15646. };
  15647. #if defined(USE_WEBSOCKET)
  15648. #if defined(_WIN32)
  15649. static unsigned __stdcall websocket_client_thread(void *data)
  15650. #else
  15651. static void *
  15652. websocket_client_thread(void *data)
  15653. #endif
  15654. {
  15655. struct websocket_client_thread_data *cdata =
  15656. (struct websocket_client_thread_data *)data;
  15657. void *user_thread_ptr = NULL;
  15658. #if !defined(_WIN32)
  15659. struct sigaction sa;
  15660. /* Ignore SIGPIPE */
  15661. memset(&sa, 0, sizeof(sa));
  15662. sa.sa_handler = SIG_IGN;
  15663. sigaction(SIGPIPE, &sa, NULL);
  15664. #endif
  15665. mg_set_thread_name("ws-clnt");
  15666. if (cdata->conn->phys_ctx) {
  15667. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15668. /* 3 indicates a websocket client thread */
  15669. /* TODO: check if conn->phys_ctx can be set */
  15670. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15671. cdata->conn->phys_ctx, 3);
  15672. }
  15673. }
  15674. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15675. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15676. if (cdata->close_handler != NULL) {
  15677. cdata->close_handler(cdata->conn, cdata->callback_data);
  15678. }
  15679. /* The websocket_client context has only this thread. If it runs out,
  15680. set the stop_flag to 2 (= "stopped"). */
  15681. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15682. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15683. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15684. 3,
  15685. user_thread_ptr);
  15686. }
  15687. mg_free((void *)cdata);
  15688. #if defined(_WIN32)
  15689. return 0;
  15690. #else
  15691. return NULL;
  15692. #endif
  15693. }
  15694. #endif
  15695. static struct mg_connection *
  15696. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15697. int use_ssl,
  15698. char *error_buffer,
  15699. size_t error_buffer_size,
  15700. const char *path,
  15701. const char *origin,
  15702. mg_websocket_data_handler data_func,
  15703. mg_websocket_close_handler close_func,
  15704. void *user_data)
  15705. {
  15706. struct mg_connection *conn = NULL;
  15707. #if defined(USE_WEBSOCKET)
  15708. struct websocket_client_thread_data *thread_data;
  15709. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15710. const char *handshake_req;
  15711. int port = client_options->port;
  15712. const char *host = client_options->host;
  15713. int i;
  15714. if (origin != NULL) {
  15715. handshake_req = "GET %s HTTP/1.1\r\n"
  15716. "Host: %s\r\n"
  15717. "Upgrade: websocket\r\n"
  15718. "Connection: Upgrade\r\n"
  15719. "Sec-WebSocket-Key: %s\r\n"
  15720. "Sec-WebSocket-Version: 13\r\n"
  15721. "Origin: %s\r\n"
  15722. "\r\n";
  15723. } else {
  15724. handshake_req = "GET %s HTTP/1.1\r\n"
  15725. "Host: %s\r\n"
  15726. "Upgrade: websocket\r\n"
  15727. "Connection: Upgrade\r\n"
  15728. "Sec-WebSocket-Key: %s\r\n"
  15729. "Sec-WebSocket-Version: 13\r\n"
  15730. "\r\n";
  15731. }
  15732. #if defined(__clang__)
  15733. #pragma clang diagnostic push
  15734. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15735. #endif
  15736. /* Establish the client connection and request upgrade */
  15737. conn =
  15738. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15739. if (conn == NULL) {
  15740. /* error_buffer already filled */
  15741. return NULL;
  15742. }
  15743. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15744. if (i <= 0) {
  15745. mg_snprintf(conn,
  15746. NULL, /* No truncation check for ebuf */
  15747. error_buffer,
  15748. error_buffer_size,
  15749. "%s",
  15750. "Error sending request");
  15751. mg_close_connection(conn);
  15752. return NULL;
  15753. }
  15754. conn->data_len = 0;
  15755. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15756. mg_close_connection(conn);
  15757. return NULL;
  15758. }
  15759. conn->request_info.local_uri = conn->request_info.request_uri;
  15760. #if defined(__clang__)
  15761. #pragma clang diagnostic pop
  15762. #endif
  15763. /* Connection object will be null if something goes wrong */
  15764. if (conn == NULL) {
  15765. if (!*error_buffer) {
  15766. /* There should be already an error message */
  15767. mg_snprintf(conn,
  15768. NULL, /* No truncation check for ebuf */
  15769. error_buffer,
  15770. error_buffer_size,
  15771. "Unexpected error");
  15772. }
  15773. return NULL;
  15774. }
  15775. if (conn->response_info.status_code != 101) {
  15776. /* We sent an "upgrade" request. For a correct websocket
  15777. * protocol handshake, we expect a "101 Continue" response.
  15778. * Otherwise it is a protocol violation. Maybe the HTTP
  15779. * Server does not know websockets. */
  15780. if (!*error_buffer) {
  15781. /* set an error, if not yet set */
  15782. mg_snprintf(conn,
  15783. NULL, /* No truncation check for ebuf */
  15784. error_buffer,
  15785. error_buffer_size,
  15786. "Unexpected server reply");
  15787. }
  15788. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15789. mg_close_connection(conn);
  15790. return NULL;
  15791. }
  15792. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15793. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15794. if (!thread_data) {
  15795. DEBUG_TRACE("%s\r\n", "Out of memory");
  15796. mg_close_connection(conn);
  15797. return NULL;
  15798. }
  15799. thread_data->conn = conn;
  15800. thread_data->data_handler = data_func;
  15801. thread_data->close_handler = close_func;
  15802. thread_data->callback_data = user_data;
  15803. conn->phys_ctx->worker_threadids =
  15804. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15805. if (!conn->phys_ctx->worker_threadids) {
  15806. DEBUG_TRACE("%s\r\n", "Out of memory");
  15807. mg_free(thread_data);
  15808. mg_close_connection(conn);
  15809. return NULL;
  15810. }
  15811. /* Now upgrade to ws/wss client context */
  15812. conn->phys_ctx->user_data = user_data;
  15813. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15814. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15815. /* Start a thread to read the websocket client connection
  15816. * This thread will automatically stop when mg_disconnect is
  15817. * called on the client connection */
  15818. if (mg_start_thread_with_id(websocket_client_thread,
  15819. thread_data,
  15820. conn->phys_ctx->worker_threadids)
  15821. != 0) {
  15822. conn->phys_ctx->cfg_worker_threads = 0;
  15823. mg_free(thread_data);
  15824. mg_close_connection(conn);
  15825. conn = NULL;
  15826. DEBUG_TRACE("%s",
  15827. "Websocket client connect thread could not be started\r\n");
  15828. }
  15829. #else
  15830. /* Appease "unused parameter" warnings */
  15831. (void)client_options;
  15832. (void)use_ssl;
  15833. (void)error_buffer;
  15834. (void)error_buffer_size;
  15835. (void)path;
  15836. (void)origin;
  15837. (void)user_data;
  15838. (void)data_func;
  15839. (void)close_func;
  15840. #endif
  15841. return conn;
  15842. }
  15843. struct mg_connection *
  15844. mg_connect_websocket_client(const char *host,
  15845. int port,
  15846. int use_ssl,
  15847. char *error_buffer,
  15848. size_t error_buffer_size,
  15849. const char *path,
  15850. const char *origin,
  15851. mg_websocket_data_handler data_func,
  15852. mg_websocket_close_handler close_func,
  15853. void *user_data)
  15854. {
  15855. struct mg_client_options client_options;
  15856. memset(&client_options, 0, sizeof(client_options));
  15857. client_options.host = host;
  15858. client_options.port = port;
  15859. return mg_connect_websocket_client_impl(&client_options,
  15860. use_ssl,
  15861. error_buffer,
  15862. error_buffer_size,
  15863. path,
  15864. origin,
  15865. data_func,
  15866. close_func,
  15867. user_data);
  15868. }
  15869. struct mg_connection *
  15870. mg_connect_websocket_client_secure(
  15871. const struct mg_client_options *client_options,
  15872. char *error_buffer,
  15873. size_t error_buffer_size,
  15874. const char *path,
  15875. const char *origin,
  15876. mg_websocket_data_handler data_func,
  15877. mg_websocket_close_handler close_func,
  15878. void *user_data)
  15879. {
  15880. if (!client_options) {
  15881. return NULL;
  15882. }
  15883. return mg_connect_websocket_client_impl(client_options,
  15884. 1,
  15885. error_buffer,
  15886. error_buffer_size,
  15887. path,
  15888. origin,
  15889. data_func,
  15890. close_func,
  15891. user_data);
  15892. }
  15893. /* Prepare connection data structure */
  15894. static void
  15895. init_connection(struct mg_connection *conn)
  15896. {
  15897. /* Is keep alive allowed by the server */
  15898. int keep_alive_enabled =
  15899. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15900. if (!keep_alive_enabled) {
  15901. conn->must_close = 1;
  15902. }
  15903. /* Important: on new connection, reset the receiving buffer. Credit
  15904. * goes to crule42. */
  15905. conn->data_len = 0;
  15906. conn->handled_requests = 0;
  15907. mg_set_user_connection_data(conn, NULL);
  15908. #if defined(USE_SERVER_STATS)
  15909. conn->conn_state = 2; /* init */
  15910. #endif
  15911. /* call the init_connection callback if assigned */
  15912. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15913. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15914. void *conn_data = NULL;
  15915. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15916. mg_set_user_connection_data(conn, conn_data);
  15917. }
  15918. }
  15919. }
  15920. /* Process a connection - may handle multiple requests
  15921. * using the same connection.
  15922. * Must be called with a valid connection (conn and
  15923. * conn->phys_ctx must be valid).
  15924. */
  15925. static void
  15926. process_new_connection(struct mg_connection *conn)
  15927. {
  15928. struct mg_request_info *ri = &conn->request_info;
  15929. int keep_alive, discard_len;
  15930. char ebuf[100];
  15931. const char *hostend;
  15932. int reqerr, uri_type;
  15933. #if defined(USE_SERVER_STATS)
  15934. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15935. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15936. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15937. /* could use atomic compare exchange, but this
  15938. * seems overkill for statistics data */
  15939. conn->phys_ctx->max_active_connections = mcon;
  15940. }
  15941. #endif
  15942. init_connection(conn);
  15943. DEBUG_TRACE("Start processing connection from %s",
  15944. conn->request_info.remote_addr);
  15945. /* Loop over multiple requests sent using the same connection
  15946. * (while "keep alive"). */
  15947. do {
  15948. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15949. conn->handled_requests + 1);
  15950. #if defined(USE_SERVER_STATS)
  15951. conn->conn_state = 3; /* ready */
  15952. #endif
  15953. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15954. /* The request sent by the client could not be understood by
  15955. * the server, or it was incomplete or a timeout. Send an
  15956. * error message and close the connection. */
  15957. if (reqerr > 0) {
  15958. DEBUG_ASSERT(ebuf[0] != '\0');
  15959. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15960. }
  15961. } else if (strcmp(ri->http_version, "1.0")
  15962. && strcmp(ri->http_version, "1.1")) {
  15963. /* HTTP/2 is not allowed here */
  15964. mg_snprintf(conn,
  15965. NULL, /* No truncation check for ebuf */
  15966. ebuf,
  15967. sizeof(ebuf),
  15968. "Bad HTTP version: [%s]",
  15969. ri->http_version);
  15970. mg_send_http_error(conn, 505, "%s", ebuf);
  15971. }
  15972. if (ebuf[0] == '\0') {
  15973. uri_type = get_uri_type(conn->request_info.request_uri);
  15974. switch (uri_type) {
  15975. case 1:
  15976. /* Asterisk */
  15977. conn->request_info.local_uri = 0;
  15978. /* TODO: Deal with '*'. */
  15979. break;
  15980. case 2:
  15981. /* relative uri */
  15982. conn->request_info.local_uri = conn->request_info.request_uri;
  15983. break;
  15984. case 3:
  15985. case 4:
  15986. /* absolute uri (with/without port) */
  15987. hostend = get_rel_url_at_current_server(
  15988. conn->request_info.request_uri, conn);
  15989. if (hostend) {
  15990. conn->request_info.local_uri = hostend;
  15991. } else {
  15992. conn->request_info.local_uri = NULL;
  15993. }
  15994. break;
  15995. default:
  15996. mg_snprintf(conn,
  15997. NULL, /* No truncation check for ebuf */
  15998. ebuf,
  15999. sizeof(ebuf),
  16000. "Invalid URI");
  16001. mg_send_http_error(conn, 400, "%s", ebuf);
  16002. conn->request_info.local_uri = NULL;
  16003. break;
  16004. }
  16005. #if defined(MG_LEGACY_INTERFACE)
  16006. /* Legacy before split into local_uri and request_uri */
  16007. conn->request_info.uri = conn->request_info.local_uri;
  16008. #endif
  16009. }
  16010. if (ebuf[0] != '\0') {
  16011. conn->protocol_type = -1;
  16012. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  16013. /* HTTP/1 allows protocol upgrade */
  16014. conn->protocol_type = should_switch_to_protocol(conn);
  16015. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16016. /* This will occur, if a HTTP/1.1 request should be upgraded
  16017. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16018. * Since most (all?) major browsers only support HTTP/2 using
  16019. * ALPN, this is hard to test and very low priority.
  16020. * Deactivate it (at least for now).
  16021. */
  16022. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16023. }
  16024. }
  16025. DEBUG_TRACE("http: %s, error: %s",
  16026. (ri->http_version ? ri->http_version : "none"),
  16027. (ebuf[0] ? ebuf : "none"));
  16028. if (ebuf[0] == '\0') {
  16029. if (conn->request_info.local_uri) {
  16030. /* handle request to local server */
  16031. #if defined(USE_SERVER_STATS)
  16032. conn->conn_state = 4; /* processing */
  16033. #endif
  16034. handle_request(conn);
  16035. #if defined(USE_SERVER_STATS)
  16036. conn->conn_state = 5; /* processed */
  16037. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  16038. conn->consumed_content);
  16039. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  16040. conn->num_bytes_sent);
  16041. #endif
  16042. DEBUG_TRACE("%s", "handle_request done");
  16043. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16044. conn->phys_ctx->callbacks.end_request(conn,
  16045. conn->status_code);
  16046. DEBUG_TRACE("%s", "end_request callback done");
  16047. }
  16048. log_access(conn);
  16049. } else {
  16050. /* TODO: handle non-local request (PROXY) */
  16051. conn->must_close = 1;
  16052. }
  16053. } else {
  16054. conn->must_close = 1;
  16055. }
  16056. if (ri->remote_user != NULL) {
  16057. mg_free((void *)ri->remote_user);
  16058. /* Important! When having connections with and without auth
  16059. * would cause double free and then crash */
  16060. ri->remote_user = NULL;
  16061. }
  16062. /* NOTE(lsm): order is important here. should_keep_alive() call
  16063. * is using parsed request, which will be invalid after
  16064. * memmove's below.
  16065. * Therefore, memorize should_keep_alive() result now for later
  16066. * use in loop exit condition. */
  16067. /* Enable it only if this request is completely discardable. */
  16068. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16069. && should_keep_alive(conn) && (conn->content_len >= 0)
  16070. && (conn->request_len > 0)
  16071. && ((conn->is_chunked == 4)
  16072. || (!conn->is_chunked
  16073. && ((conn->consumed_content == conn->content_len)
  16074. || ((conn->request_len + conn->content_len)
  16075. <= conn->data_len))))
  16076. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16077. if (keep_alive) {
  16078. /* Discard all buffered data for this request */
  16079. discard_len =
  16080. ((conn->request_len + conn->content_len) < conn->data_len)
  16081. ? (int)(conn->request_len + conn->content_len)
  16082. : conn->data_len;
  16083. conn->data_len -= discard_len;
  16084. if (conn->data_len > 0) {
  16085. DEBUG_TRACE("discard_len = %d", discard_len);
  16086. memmove(conn->buf,
  16087. conn->buf + discard_len,
  16088. (size_t)conn->data_len);
  16089. }
  16090. }
  16091. DEBUG_ASSERT(conn->data_len >= 0);
  16092. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16093. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16094. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16095. (long int)conn->data_len,
  16096. (long int)conn->buf_size);
  16097. break;
  16098. }
  16099. conn->handled_requests++;
  16100. } while (keep_alive);
  16101. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16102. conn->request_info.remote_addr,
  16103. difftime(time(NULL), conn->conn_birth_time));
  16104. close_connection(conn);
  16105. #if defined(USE_SERVER_STATS)
  16106. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16107. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16108. #endif
  16109. }
  16110. #if defined(ALTERNATIVE_QUEUE)
  16111. static void
  16112. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16113. {
  16114. unsigned int i;
  16115. while (!ctx->stop_flag) {
  16116. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16117. /* find a free worker slot and signal it */
  16118. if (ctx->client_socks[i].in_use == 2) {
  16119. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16120. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16121. ctx->client_socks[i] = *sp;
  16122. ctx->client_socks[i].in_use = 1;
  16123. /* socket has been moved to the consumer */
  16124. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16125. (void)event_signal(ctx->client_wait_events[i]);
  16126. return;
  16127. }
  16128. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16129. }
  16130. }
  16131. /* queue is full */
  16132. mg_sleep(1);
  16133. }
  16134. /* must consume */
  16135. set_blocking_mode(sp->sock);
  16136. closesocket(sp->sock);
  16137. }
  16138. static int
  16139. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16140. {
  16141. DEBUG_TRACE("%s", "going idle");
  16142. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16143. ctx->client_socks[thread_index].in_use = 2;
  16144. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16145. event_wait(ctx->client_wait_events[thread_index]);
  16146. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16147. *sp = ctx->client_socks[thread_index];
  16148. if (ctx->stop_flag) {
  16149. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16150. if (sp->in_use == 1) {
  16151. /* must consume */
  16152. set_blocking_mode(sp->sock);
  16153. closesocket(sp->sock);
  16154. }
  16155. return 0;
  16156. }
  16157. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16158. if (sp->in_use == 1) {
  16159. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16160. return 1;
  16161. }
  16162. /* must not reach here */
  16163. DEBUG_ASSERT(0);
  16164. return 0;
  16165. }
  16166. #else /* ALTERNATIVE_QUEUE */
  16167. /* Worker threads take accepted socket from the queue */
  16168. static int
  16169. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16170. {
  16171. (void)thread_index;
  16172. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16173. DEBUG_TRACE("%s", "going idle");
  16174. /* If the queue is empty, wait. We're idle at this point. */
  16175. while ((ctx->sq_head == ctx->sq_tail)
  16176. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16177. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16178. }
  16179. /* If we're stopping, sq_head may be equal to sq_tail. */
  16180. if (ctx->sq_head > ctx->sq_tail) {
  16181. /* Copy socket from the queue and increment tail */
  16182. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16183. ctx->sq_tail++;
  16184. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16185. /* Wrap pointers if needed */
  16186. while (ctx->sq_tail > ctx->sq_size) {
  16187. ctx->sq_tail -= ctx->sq_size;
  16188. ctx->sq_head -= ctx->sq_size;
  16189. }
  16190. }
  16191. (void)pthread_cond_signal(&ctx->sq_empty);
  16192. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16193. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16194. }
  16195. /* Master thread adds accepted socket to a queue */
  16196. static void
  16197. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16198. {
  16199. int queue_filled;
  16200. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16201. queue_filled = ctx->sq_head - ctx->sq_tail;
  16202. /* If the queue is full, wait */
  16203. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16204. && (queue_filled >= ctx->sq_size)) {
  16205. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16206. #if defined(USE_SERVER_STATS)
  16207. if (queue_filled > ctx->sq_max_fill) {
  16208. ctx->sq_max_fill = queue_filled;
  16209. }
  16210. #endif
  16211. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16212. ctx->sq_blocked = 0; /* Not blocked now */
  16213. queue_filled = ctx->sq_head - ctx->sq_tail;
  16214. }
  16215. if (queue_filled < ctx->sq_size) {
  16216. /* Copy socket to the queue and increment head */
  16217. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16218. ctx->sq_head++;
  16219. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16220. }
  16221. queue_filled = ctx->sq_head - ctx->sq_tail;
  16222. #if defined(USE_SERVER_STATS)
  16223. if (queue_filled > ctx->sq_max_fill) {
  16224. ctx->sq_max_fill = queue_filled;
  16225. }
  16226. #endif
  16227. (void)pthread_cond_signal(&ctx->sq_full);
  16228. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16229. }
  16230. #endif /* ALTERNATIVE_QUEUE */
  16231. static void
  16232. worker_thread_run(struct mg_connection *conn)
  16233. {
  16234. struct mg_context *ctx = conn->phys_ctx;
  16235. int thread_index;
  16236. struct mg_workerTLS tls;
  16237. #if defined(MG_LEGACY_INTERFACE)
  16238. uint32_t addr;
  16239. #endif
  16240. mg_set_thread_name("worker");
  16241. tls.is_master = 0;
  16242. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16243. #if defined(_WIN32)
  16244. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16245. #endif
  16246. /* Initialize thread local storage before calling any callback */
  16247. pthread_setspecific(sTlsKey, &tls);
  16248. /* Check if there is a user callback */
  16249. if (ctx->callbacks.init_thread) {
  16250. /* call init_thread for a worker thread (type 1), and store the
  16251. * return value */
  16252. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16253. } else {
  16254. /* No callback: set user pointer to NULL */
  16255. tls.user_ptr = NULL;
  16256. }
  16257. /* Connection structure has been pre-allocated */
  16258. thread_index = (int)(conn - ctx->worker_connections);
  16259. if ((thread_index < 0)
  16260. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16261. mg_cry_ctx_internal(ctx,
  16262. "Internal error: Invalid worker index %i",
  16263. thread_index);
  16264. return;
  16265. }
  16266. /* Request buffers are not pre-allocated. They are private to the
  16267. * request and do not contain any state information that might be
  16268. * of interest to anyone observing a server status. */
  16269. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16270. if (conn->buf == NULL) {
  16271. mg_cry_ctx_internal(
  16272. ctx,
  16273. "Out of memory: Cannot allocate buffer for worker %i",
  16274. thread_index);
  16275. return;
  16276. }
  16277. conn->buf_size = (int)ctx->max_request_size;
  16278. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16279. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16280. conn->request_info.user_data = ctx->user_data;
  16281. /* Allocate a mutex for this connection to allow communication both
  16282. * within the request handler and from elsewhere in the application
  16283. */
  16284. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16285. mg_free(conn->buf);
  16286. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16287. return;
  16288. }
  16289. #if defined(USE_SERVER_STATS)
  16290. conn->conn_state = 1; /* not consumed */
  16291. #endif
  16292. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16293. * signal sq_empty condvar to wake up the master waiting in
  16294. * produce_socket() */
  16295. while (consume_socket(ctx, &conn->client, thread_index)) {
  16296. /* New connections must start with new protocol negotiation */
  16297. tls.alpn_proto = NULL;
  16298. #if defined(USE_SERVER_STATS)
  16299. conn->conn_close_time = 0;
  16300. #endif
  16301. conn->conn_birth_time = time(NULL);
  16302. /* Fill in IP, port info early so even if SSL setup below fails,
  16303. * error handler would have the corresponding info.
  16304. * Thanks to Johannes Winkelmann for the patch.
  16305. */
  16306. #if defined(USE_IPV6)
  16307. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  16308. conn->request_info.remote_port =
  16309. ntohs(conn->client.rsa.sin6.sin6_port);
  16310. } else
  16311. #endif
  16312. {
  16313. conn->request_info.remote_port =
  16314. ntohs(conn->client.rsa.sin.sin_port);
  16315. }
  16316. sockaddr_to_string(conn->request_info.remote_addr,
  16317. sizeof(conn->request_info.remote_addr),
  16318. &conn->client.rsa);
  16319. DEBUG_TRACE("Start processing connection from %s",
  16320. conn->request_info.remote_addr);
  16321. conn->request_info.is_ssl = conn->client.is_ssl;
  16322. if (conn->client.is_ssl) {
  16323. #if !defined(NO_SSL)
  16324. /* HTTPS connection */
  16325. if (sslize(conn, SSL_accept, NULL)) {
  16326. /* conn->dom_ctx is set in get_request */
  16327. /* Get SSL client certificate information (if set) */
  16328. struct mg_client_cert client_cert;
  16329. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16330. conn->request_info.client_cert = &client_cert;
  16331. }
  16332. /* process HTTPS connection */
  16333. #if defined(USE_HTTP2)
  16334. if ((tls.alpn_proto != NULL)
  16335. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16336. /* process HTTPS/2 connection */
  16337. init_connection(conn);
  16338. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16339. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16340. conn->content_len = -1;
  16341. conn->is_chunked = 0;
  16342. process_new_http2_connection(conn);
  16343. } else
  16344. #endif
  16345. {
  16346. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16347. process_new_connection(conn);
  16348. }
  16349. /* Free client certificate info */
  16350. if (conn->request_info.client_cert) {
  16351. mg_free((void *)(conn->request_info.client_cert->subject));
  16352. mg_free((void *)(conn->request_info.client_cert->issuer));
  16353. mg_free((void *)(conn->request_info.client_cert->serial));
  16354. mg_free((void *)(conn->request_info.client_cert->finger));
  16355. /* Free certificate memory */
  16356. X509_free(
  16357. (X509 *)conn->request_info.client_cert->peer_cert);
  16358. conn->request_info.client_cert->peer_cert = 0;
  16359. conn->request_info.client_cert->subject = 0;
  16360. conn->request_info.client_cert->issuer = 0;
  16361. conn->request_info.client_cert->serial = 0;
  16362. conn->request_info.client_cert->finger = 0;
  16363. conn->request_info.client_cert = 0;
  16364. }
  16365. } else {
  16366. /* make sure the connection is cleaned up on SSL failure */
  16367. close_connection(conn);
  16368. }
  16369. #endif
  16370. } else {
  16371. /* process HTTP connection */
  16372. process_new_connection(conn);
  16373. }
  16374. DEBUG_TRACE("%s", "Connection closed");
  16375. #if defined(USE_SERVER_STATS)
  16376. conn->conn_close_time = time(NULL);
  16377. #endif
  16378. }
  16379. /* Call exit thread user callback */
  16380. if (ctx->callbacks.exit_thread) {
  16381. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16382. }
  16383. /* delete thread local storage objects */
  16384. pthread_setspecific(sTlsKey, NULL);
  16385. #if defined(_WIN32)
  16386. CloseHandle(tls.pthread_cond_helper_mutex);
  16387. #endif
  16388. pthread_mutex_destroy(&conn->mutex);
  16389. /* Free the request buffer. */
  16390. conn->buf_size = 0;
  16391. mg_free(conn->buf);
  16392. conn->buf = NULL;
  16393. #if defined(USE_SERVER_STATS)
  16394. conn->conn_state = 9; /* done */
  16395. #endif
  16396. DEBUG_TRACE("%s", "exiting");
  16397. }
  16398. /* Threads have different return types on Windows and Unix. */
  16399. #if defined(_WIN32)
  16400. static unsigned __stdcall worker_thread(void *thread_func_param)
  16401. {
  16402. worker_thread_run((struct mg_connection *)thread_func_param);
  16403. return 0;
  16404. }
  16405. #else
  16406. static void *
  16407. worker_thread(void *thread_func_param)
  16408. {
  16409. #if !defined(__ZEPHYR__)
  16410. struct sigaction sa;
  16411. /* Ignore SIGPIPE */
  16412. memset(&sa, 0, sizeof(sa));
  16413. sa.sa_handler = SIG_IGN;
  16414. sigaction(SIGPIPE, &sa, NULL);
  16415. #endif
  16416. worker_thread_run((struct mg_connection *)thread_func_param);
  16417. return NULL;
  16418. }
  16419. #endif /* _WIN32 */
  16420. /* This is an internal function, thus all arguments are expected to be
  16421. * valid - a NULL check is not required. */
  16422. static void
  16423. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16424. {
  16425. struct socket so;
  16426. char src_addr[IP_ADDR_STR_LEN];
  16427. socklen_t len = sizeof(so.rsa);
  16428. #if !defined(__ZEPHYR__)
  16429. int on = 1;
  16430. #endif
  16431. memset(&so, 0, sizeof(so));
  16432. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16433. == INVALID_SOCKET) {
  16434. } else if (check_acl(ctx, &so.rsa) != 1) {
  16435. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16436. mg_cry_ctx_internal(ctx,
  16437. "%s: %s is not allowed to connect",
  16438. __func__,
  16439. src_addr);
  16440. closesocket(so.sock);
  16441. } else {
  16442. /* Put so socket structure into the queue */
  16443. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16444. set_close_on_exec(so.sock, NULL, ctx);
  16445. so.is_ssl = listener->is_ssl;
  16446. so.ssl_redir = listener->ssl_redir;
  16447. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16448. mg_cry_ctx_internal(ctx,
  16449. "%s: getsockname() failed: %s",
  16450. __func__,
  16451. strerror(ERRNO));
  16452. }
  16453. #if !defined(__ZEPHYR__)
  16454. /* Set TCP keep-alive. This is needed because if HTTP-level
  16455. * keep-alive
  16456. * is enabled, and client resets the connection, server won't get
  16457. * TCP FIN or RST and will keep the connection open forever. With
  16458. * TCP keep-alive, next keep-alive handshake will figure out that
  16459. * the client is down and will close the server end.
  16460. * Thanks to Igor Klopov who suggested the patch. */
  16461. if (setsockopt(so.sock,
  16462. SOL_SOCKET,
  16463. SO_KEEPALIVE,
  16464. (SOCK_OPT_TYPE)&on,
  16465. sizeof(on))
  16466. != 0) {
  16467. mg_cry_ctx_internal(
  16468. ctx,
  16469. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16470. __func__,
  16471. strerror(ERRNO));
  16472. }
  16473. #endif
  16474. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16475. * to effectively fill up the underlying IP packet payload and
  16476. * reduce the overhead of sending lots of small buffers. However
  16477. * this hurts the server's throughput (ie. operations per second)
  16478. * when HTTP 1.1 persistent connections are used and the responses
  16479. * are relatively small (eg. less than 1400 bytes).
  16480. */
  16481. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16482. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16483. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16484. mg_cry_ctx_internal(
  16485. ctx,
  16486. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16487. __func__,
  16488. strerror(ERRNO));
  16489. }
  16490. }
  16491. /* The "non blocking" property should already be
  16492. * inherited from the parent socket. Set it for
  16493. * non-compliant socket implementations. */
  16494. set_non_blocking_mode(so.sock);
  16495. so.in_use = 0;
  16496. produce_socket(ctx, &so);
  16497. }
  16498. }
  16499. static void
  16500. master_thread_run(struct mg_context *ctx)
  16501. {
  16502. struct mg_workerTLS tls;
  16503. struct mg_pollfd *pfd;
  16504. unsigned int i;
  16505. unsigned int workerthreadcount;
  16506. if (!ctx) {
  16507. return;
  16508. }
  16509. mg_set_thread_name("master");
  16510. /* Increase priority of the master thread */
  16511. #if defined(_WIN32)
  16512. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16513. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16514. int min_prio = sched_get_priority_min(SCHED_RR);
  16515. int max_prio = sched_get_priority_max(SCHED_RR);
  16516. if ((min_prio >= 0) && (max_prio >= 0)
  16517. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16518. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16519. struct sched_param sched_param = {0};
  16520. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16521. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16522. }
  16523. #endif
  16524. /* Initialize thread local storage */
  16525. #if defined(_WIN32)
  16526. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16527. #endif
  16528. tls.is_master = 1;
  16529. pthread_setspecific(sTlsKey, &tls);
  16530. if (ctx->callbacks.init_thread) {
  16531. /* Callback for the master thread (type 0) */
  16532. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16533. } else {
  16534. tls.user_ptr = NULL;
  16535. }
  16536. /* Server starts *now* */
  16537. ctx->start_time = time(NULL);
  16538. /* Start the server */
  16539. pfd = ctx->listening_socket_fds;
  16540. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16541. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16542. pfd[i].fd = ctx->listening_sockets[i].sock;
  16543. pfd[i].events = POLLIN;
  16544. }
  16545. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16546. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16547. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16548. * successful poll, and POLLIN is defined as
  16549. * (POLLRDNORM | POLLRDBAND)
  16550. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16551. * pfd[i].revents == POLLIN. */
  16552. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16553. && (pfd[i].revents & POLLIN)) {
  16554. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16555. }
  16556. }
  16557. }
  16558. }
  16559. /* Here stop_flag is 1 - Initiate shutdown. */
  16560. DEBUG_TRACE("%s", "stopping workers");
  16561. /* Stop signal received: somebody called mg_stop. Quit. */
  16562. close_all_listening_sockets(ctx);
  16563. /* Wakeup workers that are waiting for connections to handle. */
  16564. #if defined(ALTERNATIVE_QUEUE)
  16565. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16566. event_signal(ctx->client_wait_events[i]);
  16567. }
  16568. #else
  16569. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16570. pthread_cond_broadcast(&ctx->sq_full);
  16571. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16572. #endif
  16573. /* Join all worker threads to avoid leaking threads. */
  16574. workerthreadcount = ctx->cfg_worker_threads;
  16575. for (i = 0; i < workerthreadcount; i++) {
  16576. if (ctx->worker_threadids[i] != 0) {
  16577. mg_join_thread(ctx->worker_threadids[i]);
  16578. }
  16579. }
  16580. #if defined(USE_LUA)
  16581. /* Free Lua state of lua background task */
  16582. if (ctx->lua_background_state) {
  16583. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16584. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16585. if (lua_istable(lstate, -1)) {
  16586. reg_boolean(lstate, "shutdown", 1);
  16587. lua_pop(lstate, 1);
  16588. mg_sleep(2);
  16589. }
  16590. lua_close(lstate);
  16591. ctx->lua_background_state = 0;
  16592. }
  16593. #endif
  16594. DEBUG_TRACE("%s", "exiting");
  16595. /* call exit thread callback */
  16596. if (ctx->callbacks.exit_thread) {
  16597. /* Callback for the master thread (type 0) */
  16598. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16599. }
  16600. #if defined(_WIN32)
  16601. CloseHandle(tls.pthread_cond_helper_mutex);
  16602. #endif
  16603. pthread_setspecific(sTlsKey, NULL);
  16604. /* Signal mg_stop() that we're done.
  16605. * WARNING: This must be the very last thing this
  16606. * thread does, as ctx becomes invalid after this line. */
  16607. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16608. }
  16609. /* Threads have different return types on Windows and Unix. */
  16610. #if defined(_WIN32)
  16611. static unsigned __stdcall master_thread(void *thread_func_param)
  16612. {
  16613. master_thread_run((struct mg_context *)thread_func_param);
  16614. return 0;
  16615. }
  16616. #else
  16617. static void *
  16618. master_thread(void *thread_func_param)
  16619. {
  16620. #if !defined(__ZEPHYR__)
  16621. struct sigaction sa;
  16622. /* Ignore SIGPIPE */
  16623. memset(&sa, 0, sizeof(sa));
  16624. sa.sa_handler = SIG_IGN;
  16625. sigaction(SIGPIPE, &sa, NULL);
  16626. #endif
  16627. master_thread_run((struct mg_context *)thread_func_param);
  16628. return NULL;
  16629. }
  16630. #endif /* _WIN32 */
  16631. static void
  16632. free_context(struct mg_context *ctx)
  16633. {
  16634. int i;
  16635. struct mg_handler_info *tmp_rh;
  16636. if (ctx == NULL) {
  16637. return;
  16638. }
  16639. if (ctx->callbacks.exit_context) {
  16640. ctx->callbacks.exit_context(ctx);
  16641. }
  16642. /* All threads exited, no sync is needed. Destroy thread mutex and
  16643. * condvars
  16644. */
  16645. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16646. #if defined(ALTERNATIVE_QUEUE)
  16647. mg_free(ctx->client_socks);
  16648. if (ctx->client_wait_events != NULL) {
  16649. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16650. event_destroy(ctx->client_wait_events[i]);
  16651. }
  16652. mg_free(ctx->client_wait_events);
  16653. }
  16654. #else
  16655. (void)pthread_cond_destroy(&ctx->sq_empty);
  16656. (void)pthread_cond_destroy(&ctx->sq_full);
  16657. mg_free(ctx->squeue);
  16658. #endif
  16659. /* Destroy other context global data structures mutex */
  16660. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16661. #if defined(USE_TIMERS)
  16662. timers_exit(ctx);
  16663. #endif
  16664. /* Deallocate config parameters */
  16665. for (i = 0; i < NUM_OPTIONS; i++) {
  16666. if (ctx->dd.config[i] != NULL) {
  16667. #if defined(_MSC_VER)
  16668. #pragma warning(suppress : 6001)
  16669. #endif
  16670. mg_free(ctx->dd.config[i]);
  16671. }
  16672. }
  16673. /* Deallocate request handlers */
  16674. while (ctx->dd.handlers) {
  16675. tmp_rh = ctx->dd.handlers;
  16676. ctx->dd.handlers = tmp_rh->next;
  16677. mg_free(tmp_rh->uri);
  16678. mg_free(tmp_rh);
  16679. }
  16680. #if !defined(NO_SSL)
  16681. /* Deallocate SSL context */
  16682. if (ctx->dd.ssl_ctx != NULL) {
  16683. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16684. int callback_ret =
  16685. (ctx->callbacks.external_ssl_ctx == NULL)
  16686. ? 0
  16687. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16688. if (callback_ret == 0) {
  16689. SSL_CTX_free(ctx->dd.ssl_ctx);
  16690. }
  16691. /* else: ignore error and ommit SSL_CTX_free in case
  16692. * callback_ret is 1 */
  16693. }
  16694. #endif /* !NO_SSL */
  16695. /* Deallocate worker thread ID array */
  16696. mg_free(ctx->worker_threadids);
  16697. /* Deallocate worker thread ID array */
  16698. mg_free(ctx->worker_connections);
  16699. /* deallocate system name string */
  16700. mg_free(ctx->systemName);
  16701. /* Deallocate context itself */
  16702. mg_free(ctx);
  16703. }
  16704. void
  16705. mg_stop(struct mg_context *ctx)
  16706. {
  16707. pthread_t mt;
  16708. if (!ctx) {
  16709. return;
  16710. }
  16711. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16712. * two threads is not allowed. */
  16713. mt = ctx->masterthreadid;
  16714. if (mt == 0) {
  16715. return;
  16716. }
  16717. ctx->masterthreadid = 0;
  16718. /* Set stop flag, so all threads know they have to exit. */
  16719. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16720. /* Wait until everything has stopped. */
  16721. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16722. (void)mg_sleep(10);
  16723. }
  16724. mg_join_thread(mt);
  16725. free_context(ctx);
  16726. }
  16727. static void
  16728. get_system_name(char **sysName)
  16729. {
  16730. #if defined(_WIN32)
  16731. #if defined(_WIN32_WCE)
  16732. *sysName = mg_strdup("WinCE");
  16733. #else
  16734. char name[128];
  16735. DWORD dwVersion = 0;
  16736. DWORD dwMajorVersion = 0;
  16737. DWORD dwMinorVersion = 0;
  16738. DWORD dwBuild = 0;
  16739. BOOL wowRet, isWoW = FALSE;
  16740. #if defined(_MSC_VER)
  16741. #pragma warning(push)
  16742. /* GetVersion was declared deprecated */
  16743. #pragma warning(disable : 4996)
  16744. #endif
  16745. dwVersion = GetVersion();
  16746. #if defined(_MSC_VER)
  16747. #pragma warning(pop)
  16748. #endif
  16749. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16750. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16751. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16752. (void)dwBuild;
  16753. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16754. sprintf(name,
  16755. "Windows %u.%u%s",
  16756. (unsigned)dwMajorVersion,
  16757. (unsigned)dwMinorVersion,
  16758. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16759. *sysName = mg_strdup(name);
  16760. #endif
  16761. #elif defined(__ZEPHYR__)
  16762. *sysName = mg_strdup("Zephyr OS");
  16763. #else
  16764. struct utsname name;
  16765. memset(&name, 0, sizeof(name));
  16766. uname(&name);
  16767. *sysName = mg_strdup(name.sysname);
  16768. #endif
  16769. }
  16770. static void
  16771. legacy_init(const char **options)
  16772. {
  16773. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16774. if (options) {
  16775. const char **run_options = options;
  16776. const char *optname = config_options[LISTENING_PORTS].name;
  16777. /* Try to find the "listening_ports" option */
  16778. while (*run_options) {
  16779. if (!strcmp(*run_options, optname)) {
  16780. ports_option = run_options[1];
  16781. }
  16782. run_options += 2;
  16783. }
  16784. }
  16785. if (is_ssl_port_used(ports_option)) {
  16786. /* Initialize with SSL support */
  16787. mg_init_library(MG_FEATURES_TLS);
  16788. } else {
  16789. /* Initialize without SSL support */
  16790. mg_init_library(MG_FEATURES_DEFAULT);
  16791. }
  16792. }
  16793. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16794. static
  16795. #endif
  16796. struct mg_context *
  16797. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16798. {
  16799. struct mg_context *ctx;
  16800. const char *name, *value, *default_value;
  16801. int idx, ok, workerthreadcount;
  16802. unsigned int i;
  16803. int itmp;
  16804. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16805. const char **options =
  16806. ((init != NULL) ? (init->configuration_options) : (NULL));
  16807. struct mg_workerTLS tls;
  16808. if (error != NULL) {
  16809. error->code = 0;
  16810. if (error->text_buffer_size > 0) {
  16811. *error->text = 0;
  16812. }
  16813. }
  16814. if (mg_init_library_called == 0) {
  16815. /* Legacy INIT, if mg_start is called without mg_init_library.
  16816. * Note: This will cause a memory leak when unloading the library.
  16817. */
  16818. legacy_init(options);
  16819. }
  16820. if (mg_init_library_called == 0) {
  16821. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16822. mg_snprintf(NULL,
  16823. NULL, /* No truncation check for error buffers */
  16824. error->text,
  16825. error->text_buffer_size,
  16826. "%s",
  16827. "Library uninitialized");
  16828. }
  16829. return NULL;
  16830. }
  16831. /* Allocate context and initialize reasonable general case defaults. */
  16832. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16833. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16834. mg_snprintf(NULL,
  16835. NULL, /* No truncation check for error buffers */
  16836. error->text,
  16837. error->text_buffer_size,
  16838. "%s",
  16839. "Out of memory");
  16840. }
  16841. return NULL;
  16842. }
  16843. /* Random number generator will initialize at the first call */
  16844. ctx->dd.auth_nonce_mask =
  16845. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16846. /* Save started thread index to reuse in other external API calls
  16847. * For the sake of thread synchronization all non-civetweb threads
  16848. * can be considered as single external thread */
  16849. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16850. tls.is_master = -1; /* Thread calling mg_start */
  16851. tls.thread_idx = ctx->starter_thread_idx;
  16852. #if defined(_WIN32)
  16853. tls.pthread_cond_helper_mutex = NULL;
  16854. #endif
  16855. pthread_setspecific(sTlsKey, &tls);
  16856. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16857. #if !defined(ALTERNATIVE_QUEUE)
  16858. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16859. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16860. ctx->sq_blocked = 0;
  16861. #endif
  16862. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16863. if (!ok) {
  16864. const char *err_msg =
  16865. "Cannot initialize thread synchronization objects";
  16866. /* Fatal error - abort start. However, this situation should never
  16867. * occur in practice. */
  16868. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16869. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16870. mg_snprintf(NULL,
  16871. NULL, /* No truncation check for error buffers */
  16872. error->text,
  16873. error->text_buffer_size,
  16874. "%s",
  16875. err_msg);
  16876. }
  16877. mg_free(ctx);
  16878. pthread_setspecific(sTlsKey, NULL);
  16879. return NULL;
  16880. }
  16881. if ((init != NULL) && (init->callbacks != NULL)) {
  16882. /* Set all callbacks except exit_context. */
  16883. ctx->callbacks = *init->callbacks;
  16884. exit_callback = init->callbacks->exit_context;
  16885. /* The exit callback is activated once the context is successfully
  16886. * created. It should not be called, if an incomplete context object
  16887. * is deleted during a failed initialization. */
  16888. ctx->callbacks.exit_context = 0;
  16889. }
  16890. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16891. ctx->dd.handlers = NULL;
  16892. ctx->dd.next = NULL;
  16893. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16894. ctx->dd.shared_lua_websockets = NULL;
  16895. #endif
  16896. /* Store options */
  16897. while (options && (name = *options++) != NULL) {
  16898. if ((idx = get_option_index(name)) == -1) {
  16899. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16900. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16901. mg_snprintf(NULL,
  16902. NULL, /* No truncation check for error buffers */
  16903. error->text,
  16904. error->text_buffer_size,
  16905. "Invalid configuration option: %s",
  16906. name);
  16907. }
  16908. free_context(ctx);
  16909. pthread_setspecific(sTlsKey, NULL);
  16910. return NULL;
  16911. } else if ((value = *options++) == NULL) {
  16912. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16913. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16914. mg_snprintf(NULL,
  16915. NULL, /* No truncation check for error buffers */
  16916. error->text,
  16917. error->text_buffer_size,
  16918. "Invalid configuration option value: %s",
  16919. name);
  16920. }
  16921. free_context(ctx);
  16922. pthread_setspecific(sTlsKey, NULL);
  16923. return NULL;
  16924. }
  16925. if (ctx->dd.config[idx] != NULL) {
  16926. /* A duplicate configuration option is not an error - the last
  16927. * option value will be used. */
  16928. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16929. mg_free(ctx->dd.config[idx]);
  16930. }
  16931. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16932. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16933. }
  16934. /* Set default value if needed */
  16935. for (i = 0; config_options[i].name != NULL; i++) {
  16936. default_value = config_options[i].default_value;
  16937. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16938. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16939. }
  16940. }
  16941. /* Request size option */
  16942. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16943. if (itmp < 1024) {
  16944. mg_cry_ctx_internal(ctx,
  16945. "%s too small",
  16946. config_options[MAX_REQUEST_SIZE].name);
  16947. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16948. mg_snprintf(NULL,
  16949. NULL, /* No truncation check for error buffers */
  16950. error->text,
  16951. error->text_buffer_size,
  16952. "Invalid configuration option value: %s",
  16953. config_options[MAX_REQUEST_SIZE].name);
  16954. }
  16955. free_context(ctx);
  16956. pthread_setspecific(sTlsKey, NULL);
  16957. return NULL;
  16958. }
  16959. ctx->max_request_size = (unsigned)itmp;
  16960. /* Queue length */
  16961. #if !defined(ALTERNATIVE_QUEUE)
  16962. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16963. if (itmp < 1) {
  16964. mg_cry_ctx_internal(ctx,
  16965. "%s too small",
  16966. config_options[CONNECTION_QUEUE_SIZE].name);
  16967. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16968. mg_snprintf(NULL,
  16969. NULL, /* No truncation check for error buffers */
  16970. error->text,
  16971. error->text_buffer_size,
  16972. "Invalid configuration option value: %s",
  16973. config_options[CONNECTION_QUEUE_SIZE].name);
  16974. }
  16975. free_context(ctx);
  16976. pthread_setspecific(sTlsKey, NULL);
  16977. return NULL;
  16978. }
  16979. ctx->squeue =
  16980. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16981. if (ctx->squeue == NULL) {
  16982. mg_cry_ctx_internal(ctx,
  16983. "Out of memory: Cannot allocate %s",
  16984. config_options[CONNECTION_QUEUE_SIZE].name);
  16985. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16986. mg_snprintf(NULL,
  16987. NULL, /* No truncation check for error buffers */
  16988. error->text,
  16989. error->text_buffer_size,
  16990. "Out of memory: Cannot allocate %s",
  16991. config_options[CONNECTION_QUEUE_SIZE].name);
  16992. }
  16993. free_context(ctx);
  16994. pthread_setspecific(sTlsKey, NULL);
  16995. return NULL;
  16996. }
  16997. ctx->sq_size = itmp;
  16998. #endif
  16999. /* Worker thread count option */
  17000. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17001. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17002. if (workerthreadcount <= 0) {
  17003. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17004. } else {
  17005. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17006. }
  17007. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17008. mg_snprintf(NULL,
  17009. NULL, /* No truncation check for error buffers */
  17010. error->text,
  17011. error->text_buffer_size,
  17012. "Invalid configuration option value: %s",
  17013. config_options[NUM_THREADS].name);
  17014. }
  17015. free_context(ctx);
  17016. pthread_setspecific(sTlsKey, NULL);
  17017. return NULL;
  17018. }
  17019. /* Document root */
  17020. #if defined(NO_FILES)
  17021. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17022. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17023. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17024. mg_snprintf(NULL,
  17025. NULL, /* No truncation check for error buffers */
  17026. error->text,
  17027. error->text_buffer_size,
  17028. "Invalid configuration option value: %s",
  17029. config_options[DOCUMENT_ROOT].name);
  17030. }
  17031. free_context(ctx);
  17032. pthread_setspecific(sTlsKey, NULL);
  17033. return NULL;
  17034. }
  17035. #endif
  17036. get_system_name(&ctx->systemName);
  17037. #if defined(USE_LUA)
  17038. /* If a Lua background script has been configured, start it. */
  17039. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17040. char ebuf[256];
  17041. struct vec opt_vec;
  17042. struct vec eq_vec;
  17043. const char *sparams;
  17044. lua_State *state = mg_prepare_lua_context_script(
  17045. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17046. if (!state) {
  17047. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  17048. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17049. mg_snprintf(NULL,
  17050. NULL, /* No truncation check for error buffers */
  17051. error->text,
  17052. error->text_buffer_size,
  17053. "Error in script %s: %s",
  17054. config_options[DOCUMENT_ROOT].name,
  17055. ebuf);
  17056. }
  17057. free_context(ctx);
  17058. pthread_setspecific(sTlsKey, NULL);
  17059. return NULL;
  17060. }
  17061. ctx->lua_background_state = (void *)state;
  17062. lua_newtable(state);
  17063. reg_boolean(state, "shutdown", 0);
  17064. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17065. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17066. reg_llstring(
  17067. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17068. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17069. break;
  17070. }
  17071. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17072. } else {
  17073. ctx->lua_background_state = 0;
  17074. }
  17075. #endif
  17076. /* Step by step initialization of ctx - depending on build options */
  17077. #if !defined(NO_FILESYSTEMS)
  17078. if (!set_gpass_option(ctx, NULL)) {
  17079. const char *err_msg = "Invalid global password file";
  17080. /* Fatal error - abort start. */
  17081. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17082. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17083. mg_snprintf(NULL,
  17084. NULL, /* No truncation check for error buffers */
  17085. error->text,
  17086. error->text_buffer_size,
  17087. "%s",
  17088. err_msg);
  17089. }
  17090. free_context(ctx);
  17091. pthread_setspecific(sTlsKey, NULL);
  17092. return NULL;
  17093. }
  17094. #endif
  17095. #if !defined(NO_SSL)
  17096. if (!init_ssl_ctx(ctx, NULL)) {
  17097. const char *err_msg = "Error initializing SSL context";
  17098. /* Fatal error - abort start. */
  17099. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17100. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17101. mg_snprintf(NULL,
  17102. NULL, /* No truncation check for error buffers */
  17103. error->text,
  17104. error->text_buffer_size,
  17105. "%s",
  17106. err_msg);
  17107. }
  17108. free_context(ctx);
  17109. pthread_setspecific(sTlsKey, NULL);
  17110. return NULL;
  17111. }
  17112. #endif
  17113. if (!set_ports_option(ctx)) {
  17114. const char *err_msg = "Failed to setup server ports";
  17115. /* Fatal error - abort start. */
  17116. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17117. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17118. mg_snprintf(NULL,
  17119. NULL, /* No truncation check for error buffers */
  17120. error->text,
  17121. error->text_buffer_size,
  17122. "%s",
  17123. err_msg);
  17124. }
  17125. free_context(ctx);
  17126. pthread_setspecific(sTlsKey, NULL);
  17127. return NULL;
  17128. }
  17129. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17130. if (!set_uid_option(ctx)) {
  17131. const char *err_msg = "Failed to run as configured user";
  17132. /* Fatal error - abort start. */
  17133. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17134. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17135. mg_snprintf(NULL,
  17136. NULL, /* No truncation check for error buffers */
  17137. error->text,
  17138. error->text_buffer_size,
  17139. "%s",
  17140. err_msg);
  17141. }
  17142. free_context(ctx);
  17143. pthread_setspecific(sTlsKey, NULL);
  17144. return NULL;
  17145. }
  17146. #endif
  17147. if (!set_acl_option(ctx)) {
  17148. const char *err_msg = "Failed to setup access control list";
  17149. /* Fatal error - abort start. */
  17150. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17151. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17152. mg_snprintf(NULL,
  17153. NULL, /* No truncation check for error buffers */
  17154. error->text,
  17155. error->text_buffer_size,
  17156. "%s",
  17157. err_msg);
  17158. }
  17159. free_context(ctx);
  17160. pthread_setspecific(sTlsKey, NULL);
  17161. return NULL;
  17162. }
  17163. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17164. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17165. sizeof(pthread_t),
  17166. ctx);
  17167. if (ctx->worker_threadids == NULL) {
  17168. const char *err_msg = "Not enough memory for worker thread ID array";
  17169. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17170. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17171. mg_snprintf(NULL,
  17172. NULL, /* No truncation check for error buffers */
  17173. error->text,
  17174. error->text_buffer_size,
  17175. "%s",
  17176. err_msg);
  17177. }
  17178. free_context(ctx);
  17179. pthread_setspecific(sTlsKey, NULL);
  17180. return NULL;
  17181. }
  17182. ctx->worker_connections =
  17183. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17184. sizeof(struct mg_connection),
  17185. ctx);
  17186. if (ctx->worker_connections == NULL) {
  17187. const char *err_msg =
  17188. "Not enough memory for worker thread connection array";
  17189. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17190. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17191. mg_snprintf(NULL,
  17192. NULL, /* No truncation check for error buffers */
  17193. error->text,
  17194. error->text_buffer_size,
  17195. "%s",
  17196. err_msg);
  17197. }
  17198. free_context(ctx);
  17199. pthread_setspecific(sTlsKey, NULL);
  17200. return NULL;
  17201. }
  17202. #if defined(ALTERNATIVE_QUEUE)
  17203. ctx->client_wait_events =
  17204. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17205. sizeof(ctx->client_wait_events[0]),
  17206. ctx);
  17207. if (ctx->client_wait_events == NULL) {
  17208. const char *err_msg = "Not enough memory for worker event array";
  17209. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17210. mg_free(ctx->worker_threadids);
  17211. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17212. mg_snprintf(NULL,
  17213. NULL, /* No truncation check for error buffers */
  17214. error->text,
  17215. error->text_buffer_size,
  17216. "%s",
  17217. err_msg);
  17218. }
  17219. free_context(ctx);
  17220. pthread_setspecific(sTlsKey, NULL);
  17221. return NULL;
  17222. }
  17223. ctx->client_socks =
  17224. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17225. sizeof(ctx->client_socks[0]),
  17226. ctx);
  17227. if (ctx->client_socks == NULL) {
  17228. const char *err_msg = "Not enough memory for worker socket array";
  17229. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17230. mg_free(ctx->client_wait_events);
  17231. mg_free(ctx->worker_threadids);
  17232. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17233. mg_snprintf(NULL,
  17234. NULL, /* No truncation check for error buffers */
  17235. error->text,
  17236. error->text_buffer_size,
  17237. "%s",
  17238. err_msg);
  17239. }
  17240. free_context(ctx);
  17241. pthread_setspecific(sTlsKey, NULL);
  17242. return NULL;
  17243. }
  17244. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17245. ctx->client_wait_events[i] = event_create();
  17246. if (ctx->client_wait_events[i] == 0) {
  17247. const char *err_msg = "Error creating worker event %i";
  17248. mg_cry_ctx_internal(ctx, err_msg, i);
  17249. while (i > 0) {
  17250. i--;
  17251. event_destroy(ctx->client_wait_events[i]);
  17252. }
  17253. mg_free(ctx->client_socks);
  17254. mg_free(ctx->client_wait_events);
  17255. mg_free(ctx->worker_threadids);
  17256. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17257. mg_snprintf(NULL,
  17258. NULL, /* No truncation check for error buffers */
  17259. error->text,
  17260. error->text_buffer_size,
  17261. err_msg,
  17262. i);
  17263. }
  17264. free_context(ctx);
  17265. pthread_setspecific(sTlsKey, NULL);
  17266. return NULL;
  17267. }
  17268. }
  17269. #endif
  17270. #if defined(USE_TIMERS)
  17271. if (timers_init(ctx) != 0) {
  17272. const char *err_msg = "Error creating timers";
  17273. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17274. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17275. mg_snprintf(NULL,
  17276. NULL, /* No truncation check for error buffers */
  17277. error->text,
  17278. error->text_buffer_size,
  17279. "%s",
  17280. err_msg);
  17281. }
  17282. free_context(ctx);
  17283. pthread_setspecific(sTlsKey, NULL);
  17284. return NULL;
  17285. }
  17286. #endif
  17287. /* Context has been created - init user libraries */
  17288. if (ctx->callbacks.init_context) {
  17289. ctx->callbacks.init_context(ctx);
  17290. }
  17291. /* From now, the context is successfully created.
  17292. * When it is destroyed, the exit callback should be called. */
  17293. ctx->callbacks.exit_context = exit_callback;
  17294. ctx->context_type = CONTEXT_SERVER; /* server context */
  17295. /* Start worker threads */
  17296. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17297. /* worker_thread sets up the other fields */
  17298. ctx->worker_connections[i].phys_ctx = ctx;
  17299. if (mg_start_thread_with_id(worker_thread,
  17300. &ctx->worker_connections[i],
  17301. &ctx->worker_threadids[i])
  17302. != 0) {
  17303. long error_no = (long)ERRNO;
  17304. /* thread was not created */
  17305. if (i > 0) {
  17306. /* If the second, third, ... thread cannot be created, set a
  17307. * warning, but keep running. */
  17308. mg_cry_ctx_internal(ctx,
  17309. "Cannot start worker thread %i: error %ld",
  17310. i + 1,
  17311. error_no);
  17312. /* If the server initialization should stop here, all
  17313. * threads that have already been created must be stopped
  17314. * first, before any free_context(ctx) call.
  17315. */
  17316. } else {
  17317. /* If the first worker thread cannot be created, stop
  17318. * initialization and free the entire server context. */
  17319. mg_cry_ctx_internal(ctx,
  17320. "Cannot create threads: error %ld",
  17321. error_no);
  17322. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17323. mg_snprintf(
  17324. NULL,
  17325. NULL, /* No truncation check for error buffers */
  17326. error->text,
  17327. error->text_buffer_size,
  17328. "Cannot create first worker thread: error %ld",
  17329. error_no);
  17330. }
  17331. free_context(ctx);
  17332. pthread_setspecific(sTlsKey, NULL);
  17333. return NULL;
  17334. }
  17335. break;
  17336. }
  17337. }
  17338. /* Start master (listening) thread */
  17339. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17340. pthread_setspecific(sTlsKey, NULL);
  17341. return ctx;
  17342. }
  17343. struct mg_context *
  17344. mg_start(const struct mg_callbacks *callbacks,
  17345. void *user_data,
  17346. const char **options)
  17347. {
  17348. struct mg_init_data init = {0};
  17349. init.callbacks = callbacks;
  17350. init.user_data = user_data;
  17351. init.configuration_options = options;
  17352. return mg_start2(&init, NULL);
  17353. }
  17354. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17355. /* Add an additional domain to an already running web server. */
  17356. int
  17357. mg_start_domain2(struct mg_context *ctx,
  17358. const char **options,
  17359. struct mg_error_data *error)
  17360. {
  17361. const char *name;
  17362. const char *value;
  17363. const char *default_value;
  17364. struct mg_domain_context *new_dom;
  17365. struct mg_domain_context *dom;
  17366. int idx, i;
  17367. if (error != NULL) {
  17368. error->code = 0;
  17369. if (error->text_buffer_size > 0) {
  17370. *error->text = 0;
  17371. }
  17372. }
  17373. if ((ctx == NULL) || (options == NULL)) {
  17374. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17375. mg_snprintf(NULL,
  17376. NULL, /* No truncation check for error buffers */
  17377. error->text,
  17378. error->text_buffer_size,
  17379. "%s",
  17380. "Invalid parameters");
  17381. }
  17382. return -1;
  17383. }
  17384. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17385. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17386. mg_snprintf(NULL,
  17387. NULL, /* No truncation check for error buffers */
  17388. error->text,
  17389. error->text_buffer_size,
  17390. "%s",
  17391. "Server already stopped");
  17392. }
  17393. return -1;
  17394. }
  17395. new_dom = (struct mg_domain_context *)
  17396. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17397. if (!new_dom) {
  17398. /* Out of memory */
  17399. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17400. mg_snprintf(NULL,
  17401. NULL, /* No truncation check for error buffers */
  17402. error->text,
  17403. error->text_buffer_size,
  17404. "%s",
  17405. "Out or memory");
  17406. }
  17407. return -6;
  17408. }
  17409. /* Store options - TODO: unite duplicate code */
  17410. while (options && (name = *options++) != NULL) {
  17411. if ((idx = get_option_index(name)) == -1) {
  17412. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17413. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17414. mg_snprintf(NULL,
  17415. NULL, /* No truncation check for error buffers */
  17416. error->text,
  17417. error->text_buffer_size,
  17418. "Invalid option: %s",
  17419. name);
  17420. }
  17421. mg_free(new_dom);
  17422. return -2;
  17423. } else if ((value = *options++) == NULL) {
  17424. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17425. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17426. mg_snprintf(NULL,
  17427. NULL, /* No truncation check for error buffers */
  17428. error->text,
  17429. error->text_buffer_size,
  17430. "Invalid option value: %s",
  17431. name);
  17432. }
  17433. mg_free(new_dom);
  17434. return -2;
  17435. }
  17436. if (new_dom->config[idx] != NULL) {
  17437. /* Duplicate option: Later values overwrite earlier ones. */
  17438. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17439. mg_free(new_dom->config[idx]);
  17440. }
  17441. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17442. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17443. }
  17444. /* Authentication domain is mandatory */
  17445. /* TODO: Maybe use a new option hostname? */
  17446. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17447. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17448. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17449. mg_snprintf(NULL,
  17450. NULL, /* No truncation check for error buffers */
  17451. error->text,
  17452. error->text_buffer_size,
  17453. "Mandatory option %s missing",
  17454. config_options[AUTHENTICATION_DOMAIN].name);
  17455. }
  17456. mg_free(new_dom);
  17457. return -4;
  17458. }
  17459. /* Set default value if needed. Take the config value from
  17460. * ctx as a default value. */
  17461. for (i = 0; config_options[i].name != NULL; i++) {
  17462. default_value = ctx->dd.config[i];
  17463. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17464. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17465. }
  17466. }
  17467. new_dom->handlers = NULL;
  17468. new_dom->next = NULL;
  17469. new_dom->nonce_count = 0;
  17470. new_dom->auth_nonce_mask =
  17471. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17472. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17473. new_dom->shared_lua_websockets = NULL;
  17474. #endif
  17475. #if !defined(NO_SSL)
  17476. if (!init_ssl_ctx(ctx, new_dom)) {
  17477. /* Init SSL failed */
  17478. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17479. mg_snprintf(NULL,
  17480. NULL, /* No truncation check for error buffers */
  17481. error->text,
  17482. error->text_buffer_size,
  17483. "%s",
  17484. "Initializing SSL context failed");
  17485. }
  17486. mg_free(new_dom);
  17487. return -3;
  17488. }
  17489. #endif
  17490. /* Add element to linked list. */
  17491. mg_lock_context(ctx);
  17492. idx = 0;
  17493. dom = &(ctx->dd);
  17494. for (;;) {
  17495. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17496. dom->config[AUTHENTICATION_DOMAIN])) {
  17497. /* Domain collision */
  17498. mg_cry_ctx_internal(ctx,
  17499. "domain %s already in use",
  17500. new_dom->config[AUTHENTICATION_DOMAIN]);
  17501. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17502. mg_snprintf(NULL,
  17503. NULL, /* No truncation check for error buffers */
  17504. error->text,
  17505. error->text_buffer_size,
  17506. "Domain %s specified by %s is already in use",
  17507. new_dom->config[AUTHENTICATION_DOMAIN],
  17508. config_options[AUTHENTICATION_DOMAIN].name);
  17509. }
  17510. mg_free(new_dom);
  17511. mg_unlock_context(ctx);
  17512. return -5;
  17513. }
  17514. /* Count number of domains */
  17515. idx++;
  17516. if (dom->next == NULL) {
  17517. dom->next = new_dom;
  17518. break;
  17519. }
  17520. dom = dom->next;
  17521. }
  17522. mg_unlock_context(ctx);
  17523. /* Return domain number */
  17524. return idx;
  17525. }
  17526. int
  17527. mg_start_domain(struct mg_context *ctx, const char **options)
  17528. {
  17529. return mg_start_domain2(ctx, options, NULL);
  17530. }
  17531. #endif
  17532. /* Feature check API function */
  17533. unsigned
  17534. mg_check_feature(unsigned feature)
  17535. {
  17536. static const unsigned feature_set = 0
  17537. /* Set bits for available features according to API documentation.
  17538. * This bit mask is created at compile time, according to the active
  17539. * preprocessor defines. It is a single const value at runtime. */
  17540. #if !defined(NO_FILES)
  17541. | MG_FEATURES_FILES
  17542. #endif
  17543. #if !defined(NO_SSL)
  17544. | MG_FEATURES_SSL
  17545. #endif
  17546. #if !defined(NO_CGI)
  17547. | MG_FEATURES_CGI
  17548. #endif
  17549. #if defined(USE_IPV6)
  17550. | MG_FEATURES_IPV6
  17551. #endif
  17552. #if defined(USE_WEBSOCKET)
  17553. | MG_FEATURES_WEBSOCKET
  17554. #endif
  17555. #if defined(USE_LUA)
  17556. | MG_FEATURES_LUA
  17557. #endif
  17558. #if defined(USE_DUKTAPE)
  17559. | MG_FEATURES_SSJS
  17560. #endif
  17561. #if !defined(NO_CACHING)
  17562. | MG_FEATURES_CACHE
  17563. #endif
  17564. #if defined(USE_SERVER_STATS)
  17565. | MG_FEATURES_STATS
  17566. #endif
  17567. #if defined(USE_ZLIB)
  17568. | MG_FEATURES_COMPRESSION
  17569. #endif
  17570. /* Set some extra bits not defined in the API documentation.
  17571. * These bits may change without further notice. */
  17572. #if defined(MG_LEGACY_INTERFACE)
  17573. | 0x00008000u
  17574. #endif
  17575. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17576. | 0x00004000u
  17577. #endif
  17578. #if defined(MEMORY_DEBUGGING)
  17579. | 0x00001000u
  17580. #endif
  17581. #if defined(USE_TIMERS)
  17582. | 0x00020000u
  17583. #endif
  17584. #if !defined(NO_NONCE_CHECK)
  17585. | 0x00040000u
  17586. #endif
  17587. #if !defined(NO_POPEN)
  17588. | 0x00080000u
  17589. #endif
  17590. ;
  17591. return (feature & feature_set);
  17592. }
  17593. static size_t
  17594. mg_str_append(char **dst, char *end, const char *src)
  17595. {
  17596. size_t len = strlen(src);
  17597. if (*dst != end) {
  17598. /* Append src if enough space, or close dst. */
  17599. if ((size_t)(end - *dst) > len) {
  17600. strcpy(*dst, src);
  17601. *dst += len;
  17602. } else {
  17603. *dst = end;
  17604. }
  17605. }
  17606. return len;
  17607. }
  17608. /* Get system information. It can be printed or stored by the caller.
  17609. * Return the size of available information. */
  17610. int
  17611. mg_get_system_info(char *buffer, int buflen)
  17612. {
  17613. char *end, *append_eoobj = NULL, block[256];
  17614. size_t system_info_length = 0;
  17615. #if defined(_WIN32)
  17616. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17617. #else
  17618. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17619. #endif
  17620. if ((buffer == NULL) || (buflen < 1)) {
  17621. buflen = 0;
  17622. end = buffer;
  17623. } else {
  17624. *buffer = 0;
  17625. end = buffer + buflen;
  17626. }
  17627. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17628. /* has enough space to append eoobj */
  17629. append_eoobj = buffer;
  17630. if (end) {
  17631. end -= sizeof(eoobj) - 1;
  17632. }
  17633. }
  17634. system_info_length += mg_str_append(&buffer, end, "{");
  17635. /* Server version */
  17636. {
  17637. const char *version = mg_version();
  17638. mg_snprintf(NULL,
  17639. NULL,
  17640. block,
  17641. sizeof(block),
  17642. "%s\"version\" : \"%s\"",
  17643. eol,
  17644. version);
  17645. system_info_length += mg_str_append(&buffer, end, block);
  17646. }
  17647. /* System info */
  17648. {
  17649. #if defined(_WIN32)
  17650. DWORD dwVersion = 0;
  17651. DWORD dwMajorVersion = 0;
  17652. DWORD dwMinorVersion = 0;
  17653. SYSTEM_INFO si;
  17654. GetSystemInfo(&si);
  17655. #if defined(_MSC_VER)
  17656. #pragma warning(push)
  17657. /* GetVersion was declared deprecated */
  17658. #pragma warning(disable : 4996)
  17659. #endif
  17660. dwVersion = GetVersion();
  17661. #if defined(_MSC_VER)
  17662. #pragma warning(pop)
  17663. #endif
  17664. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17665. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17666. mg_snprintf(NULL,
  17667. NULL,
  17668. block,
  17669. sizeof(block),
  17670. ",%s\"os\" : \"Windows %u.%u\"",
  17671. eol,
  17672. (unsigned)dwMajorVersion,
  17673. (unsigned)dwMinorVersion);
  17674. system_info_length += mg_str_append(&buffer, end, block);
  17675. mg_snprintf(NULL,
  17676. NULL,
  17677. block,
  17678. sizeof(block),
  17679. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17680. eol,
  17681. (unsigned)si.wProcessorArchitecture,
  17682. (unsigned)si.dwNumberOfProcessors,
  17683. (unsigned)si.dwActiveProcessorMask);
  17684. system_info_length += mg_str_append(&buffer, end, block);
  17685. #elif defined(__ZEPHYR__)
  17686. mg_snprintf(NULL,
  17687. NULL,
  17688. block,
  17689. sizeof(block),
  17690. ",%s\"os\" : \"%s %s\"",
  17691. eol,
  17692. "Zephyr OS",
  17693. ZEPHYR_VERSION);
  17694. system_info_length += mg_str_append(&buffer, end, block);
  17695. #else
  17696. struct utsname name;
  17697. memset(&name, 0, sizeof(name));
  17698. uname(&name);
  17699. mg_snprintf(NULL,
  17700. NULL,
  17701. block,
  17702. sizeof(block),
  17703. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17704. eol,
  17705. name.sysname,
  17706. name.version,
  17707. name.release,
  17708. name.machine);
  17709. system_info_length += mg_str_append(&buffer, end, block);
  17710. #endif
  17711. }
  17712. /* Features */
  17713. {
  17714. mg_snprintf(NULL,
  17715. NULL,
  17716. block,
  17717. sizeof(block),
  17718. ",%s\"features\" : %lu"
  17719. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17720. eol,
  17721. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17722. eol,
  17723. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17724. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17725. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17726. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17727. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17728. : "",
  17729. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17730. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17731. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17732. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17733. system_info_length += mg_str_append(&buffer, end, block);
  17734. #if defined(USE_LUA)
  17735. mg_snprintf(NULL,
  17736. NULL,
  17737. block,
  17738. sizeof(block),
  17739. ",%s\"lua_version\" : \"%u (%s)\"",
  17740. eol,
  17741. (unsigned)LUA_VERSION_NUM,
  17742. LUA_RELEASE);
  17743. system_info_length += mg_str_append(&buffer, end, block);
  17744. #endif
  17745. #if defined(USE_DUKTAPE)
  17746. mg_snprintf(NULL,
  17747. NULL,
  17748. block,
  17749. sizeof(block),
  17750. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17751. eol,
  17752. (unsigned)DUK_VERSION / 10000,
  17753. ((unsigned)DUK_VERSION / 100) % 100,
  17754. (unsigned)DUK_VERSION % 100);
  17755. system_info_length += mg_str_append(&buffer, end, block);
  17756. #endif
  17757. }
  17758. /* Build date */
  17759. {
  17760. #if defined(GCC_DIAGNOSTIC)
  17761. #if GCC_VERSION >= 40900
  17762. #pragma GCC diagnostic push
  17763. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17764. #pragma GCC diagnostic ignored "-Wdate-time"
  17765. #endif
  17766. #endif
  17767. mg_snprintf(NULL,
  17768. NULL,
  17769. block,
  17770. sizeof(block),
  17771. ",%s\"build\" : \"%s\"",
  17772. eol,
  17773. __DATE__);
  17774. #if defined(GCC_DIAGNOSTIC)
  17775. #if GCC_VERSION >= 40900
  17776. #pragma GCC diagnostic pop
  17777. #endif
  17778. #endif
  17779. system_info_length += mg_str_append(&buffer, end, block);
  17780. }
  17781. /* Compiler information */
  17782. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17783. {
  17784. #if defined(_MSC_VER)
  17785. mg_snprintf(NULL,
  17786. NULL,
  17787. block,
  17788. sizeof(block),
  17789. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17790. eol,
  17791. (unsigned)_MSC_VER,
  17792. (unsigned)_MSC_FULL_VER);
  17793. system_info_length += mg_str_append(&buffer, end, block);
  17794. #elif defined(__MINGW64__)
  17795. mg_snprintf(NULL,
  17796. NULL,
  17797. block,
  17798. sizeof(block),
  17799. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17800. eol,
  17801. (unsigned)__MINGW64_VERSION_MAJOR,
  17802. (unsigned)__MINGW64_VERSION_MINOR);
  17803. system_info_length += mg_str_append(&buffer, end, block);
  17804. mg_snprintf(NULL,
  17805. NULL,
  17806. block,
  17807. sizeof(block),
  17808. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17809. eol,
  17810. (unsigned)__MINGW32_MAJOR_VERSION,
  17811. (unsigned)__MINGW32_MINOR_VERSION);
  17812. system_info_length += mg_str_append(&buffer, end, block);
  17813. #elif defined(__MINGW32__)
  17814. mg_snprintf(NULL,
  17815. NULL,
  17816. block,
  17817. sizeof(block),
  17818. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17819. eol,
  17820. (unsigned)__MINGW32_MAJOR_VERSION,
  17821. (unsigned)__MINGW32_MINOR_VERSION);
  17822. system_info_length += mg_str_append(&buffer, end, block);
  17823. #elif defined(__clang__)
  17824. mg_snprintf(NULL,
  17825. NULL,
  17826. block,
  17827. sizeof(block),
  17828. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17829. eol,
  17830. __clang_major__,
  17831. __clang_minor__,
  17832. __clang_patchlevel__,
  17833. __clang_version__);
  17834. system_info_length += mg_str_append(&buffer, end, block);
  17835. #elif defined(__GNUC__)
  17836. mg_snprintf(NULL,
  17837. NULL,
  17838. block,
  17839. sizeof(block),
  17840. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17841. eol,
  17842. (unsigned)__GNUC__,
  17843. (unsigned)__GNUC_MINOR__,
  17844. (unsigned)__GNUC_PATCHLEVEL__);
  17845. system_info_length += mg_str_append(&buffer, end, block);
  17846. #elif defined(__INTEL_COMPILER)
  17847. mg_snprintf(NULL,
  17848. NULL,
  17849. block,
  17850. sizeof(block),
  17851. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17852. eol,
  17853. (unsigned)__INTEL_COMPILER);
  17854. system_info_length += mg_str_append(&buffer, end, block);
  17855. #elif defined(__BORLANDC__)
  17856. mg_snprintf(NULL,
  17857. NULL,
  17858. block,
  17859. sizeof(block),
  17860. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17861. eol,
  17862. (unsigned)__BORLANDC__);
  17863. system_info_length += mg_str_append(&buffer, end, block);
  17864. #elif defined(__SUNPRO_C)
  17865. mg_snprintf(NULL,
  17866. NULL,
  17867. block,
  17868. sizeof(block),
  17869. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17870. eol,
  17871. (unsigned)__SUNPRO_C);
  17872. system_info_length += mg_str_append(&buffer, end, block);
  17873. #else
  17874. mg_snprintf(NULL,
  17875. NULL,
  17876. block,
  17877. sizeof(block),
  17878. ",%s\"compiler\" : \"other\"",
  17879. eol);
  17880. system_info_length += mg_str_append(&buffer, end, block);
  17881. #endif
  17882. }
  17883. /* Determine 32/64 bit data mode.
  17884. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17885. {
  17886. mg_snprintf(NULL,
  17887. NULL,
  17888. block,
  17889. sizeof(block),
  17890. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17891. "char:%u/%u, "
  17892. "ptr:%u, size:%u, time:%u\"",
  17893. eol,
  17894. (unsigned)sizeof(short),
  17895. (unsigned)sizeof(int),
  17896. (unsigned)sizeof(long),
  17897. (unsigned)sizeof(long long),
  17898. (unsigned)sizeof(float),
  17899. (unsigned)sizeof(double),
  17900. (unsigned)sizeof(long double),
  17901. (unsigned)sizeof(char),
  17902. (unsigned)sizeof(wchar_t),
  17903. (unsigned)sizeof(void *),
  17904. (unsigned)sizeof(size_t),
  17905. (unsigned)sizeof(time_t));
  17906. system_info_length += mg_str_append(&buffer, end, block);
  17907. }
  17908. /* Terminate string */
  17909. if (append_eoobj) {
  17910. strcat(append_eoobj, eoobj);
  17911. }
  17912. system_info_length += sizeof(eoobj) - 1;
  17913. return (int)system_info_length;
  17914. }
  17915. /* Get context information. It can be printed or stored by the caller.
  17916. * Return the size of available information. */
  17917. int
  17918. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17919. {
  17920. #if defined(USE_SERVER_STATS)
  17921. char *end, *append_eoobj = NULL, block[256];
  17922. size_t context_info_length = 0;
  17923. #if defined(_WIN32)
  17924. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17925. #else
  17926. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17927. #endif
  17928. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17929. if ((buffer == NULL) || (buflen < 1)) {
  17930. buflen = 0;
  17931. end = buffer;
  17932. } else {
  17933. *buffer = 0;
  17934. end = buffer + buflen;
  17935. }
  17936. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17937. /* has enough space to append eoobj */
  17938. append_eoobj = buffer;
  17939. end -= sizeof(eoobj) - 1;
  17940. }
  17941. context_info_length += mg_str_append(&buffer, end, "{");
  17942. if (ms) { /* <-- should be always true */
  17943. /* Memory information */
  17944. mg_snprintf(NULL,
  17945. NULL,
  17946. block,
  17947. sizeof(block),
  17948. "%s\"memory\" : {%s"
  17949. "\"blocks\" : %i,%s"
  17950. "\"used\" : %" INT64_FMT ",%s"
  17951. "\"maxUsed\" : %" INT64_FMT "%s"
  17952. "}",
  17953. eol,
  17954. eol,
  17955. ms->blockCount,
  17956. eol,
  17957. ms->totalMemUsed,
  17958. eol,
  17959. ms->maxMemUsed,
  17960. eol);
  17961. context_info_length += mg_str_append(&buffer, end, block);
  17962. }
  17963. if (ctx) {
  17964. /* Declare all variables at begin of the block, to comply
  17965. * with old C standards. */
  17966. char start_time_str[64] = {0};
  17967. char now_str[64] = {0};
  17968. time_t start_time = ctx->start_time;
  17969. time_t now = time(NULL);
  17970. /* Connections information */
  17971. mg_snprintf(NULL,
  17972. NULL,
  17973. block,
  17974. sizeof(block),
  17975. ",%s\"connections\" : {%s"
  17976. "\"active\" : %i,%s"
  17977. "\"maxActive\" : %i,%s"
  17978. "\"total\" : %" INT64_FMT "%s"
  17979. "}",
  17980. eol,
  17981. eol,
  17982. ctx->active_connections,
  17983. eol,
  17984. ctx->max_active_connections,
  17985. eol,
  17986. ctx->total_connections,
  17987. eol);
  17988. context_info_length += mg_str_append(&buffer, end, block);
  17989. /* Queue information */
  17990. #if !defined(ALTERNATIVE_QUEUE)
  17991. mg_snprintf(NULL,
  17992. NULL,
  17993. block,
  17994. sizeof(block),
  17995. ",%s\"queue\" : {%s"
  17996. "\"length\" : %i,%s"
  17997. "\"filled\" : %i,%s"
  17998. "\"maxFilled\" : %i,%s"
  17999. "\"full\" : %s%s"
  18000. "}",
  18001. eol,
  18002. eol,
  18003. ctx->sq_size,
  18004. eol,
  18005. ctx->sq_head - ctx->sq_tail,
  18006. eol,
  18007. ctx->sq_max_fill,
  18008. eol,
  18009. (ctx->sq_blocked ? "true" : "false"),
  18010. eol);
  18011. context_info_length += mg_str_append(&buffer, end, block);
  18012. #endif
  18013. /* Requests information */
  18014. mg_snprintf(NULL,
  18015. NULL,
  18016. block,
  18017. sizeof(block),
  18018. ",%s\"requests\" : {%s"
  18019. "\"total\" : %" INT64_FMT "%s"
  18020. "}",
  18021. eol,
  18022. eol,
  18023. ctx->total_requests,
  18024. eol);
  18025. context_info_length += mg_str_append(&buffer, end, block);
  18026. /* Data information */
  18027. mg_snprintf(NULL,
  18028. NULL,
  18029. block,
  18030. sizeof(block),
  18031. ",%s\"data\" : {%s"
  18032. "\"read\" : %" INT64_FMT ",%s"
  18033. "\"written\" : %" INT64_FMT "%s"
  18034. "}",
  18035. eol,
  18036. eol,
  18037. ctx->total_data_read,
  18038. eol,
  18039. ctx->total_data_written,
  18040. eol);
  18041. context_info_length += mg_str_append(&buffer, end, block);
  18042. /* Execution time information */
  18043. gmt_time_string(start_time_str,
  18044. sizeof(start_time_str) - 1,
  18045. &start_time);
  18046. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18047. mg_snprintf(NULL,
  18048. NULL,
  18049. block,
  18050. sizeof(block),
  18051. ",%s\"time\" : {%s"
  18052. "\"uptime\" : %.0f,%s"
  18053. "\"start\" : \"%s\",%s"
  18054. "\"now\" : \"%s\"%s"
  18055. "}",
  18056. eol,
  18057. eol,
  18058. difftime(now, start_time),
  18059. eol,
  18060. start_time_str,
  18061. eol,
  18062. now_str,
  18063. eol);
  18064. context_info_length += mg_str_append(&buffer, end, block);
  18065. }
  18066. /* Terminate string */
  18067. if (append_eoobj) {
  18068. strcat(append_eoobj, eoobj);
  18069. }
  18070. context_info_length += sizeof(eoobj) - 1;
  18071. return (int)context_info_length;
  18072. #else
  18073. (void)ctx;
  18074. if ((buffer != NULL) && (buflen > 0)) {
  18075. *buffer = 0;
  18076. }
  18077. return 0;
  18078. #endif
  18079. }
  18080. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18081. /* Get connection information. It can be printed or stored by the caller.
  18082. * Return the size of available information. */
  18083. int
  18084. mg_get_connection_info(const struct mg_context *ctx,
  18085. int idx,
  18086. char *buffer,
  18087. int buflen)
  18088. {
  18089. const struct mg_connection *conn;
  18090. const struct mg_request_info *ri;
  18091. char *end, *append_eoobj = NULL, block[256];
  18092. size_t connection_info_length = 0;
  18093. int state = 0;
  18094. const char *state_str = "unknown";
  18095. #if defined(_WIN32)
  18096. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18097. #else
  18098. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18099. #endif
  18100. if ((buffer == NULL) || (buflen < 1)) {
  18101. buflen = 0;
  18102. end = buffer;
  18103. } else {
  18104. *buffer = 0;
  18105. end = buffer + buflen;
  18106. }
  18107. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18108. /* has enough space to append eoobj */
  18109. append_eoobj = buffer;
  18110. end -= sizeof(eoobj) - 1;
  18111. }
  18112. if ((ctx == NULL) || (idx < 0)) {
  18113. /* Parameter error */
  18114. return 0;
  18115. }
  18116. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18117. /* Out of range */
  18118. return 0;
  18119. }
  18120. /* Take connection [idx]. This connection is not locked in
  18121. * any way, so some other thread might use it. */
  18122. conn = (ctx->worker_connections) + idx;
  18123. /* Initialize output string */
  18124. connection_info_length += mg_str_append(&buffer, end, "{");
  18125. /* Init variables */
  18126. ri = &(conn->request_info);
  18127. #if defined(USE_SERVER_STATS)
  18128. state = conn->conn_state;
  18129. /* State as string */
  18130. switch (state) {
  18131. case 0:
  18132. state_str = "undefined";
  18133. break;
  18134. case 1:
  18135. state_str = "not used";
  18136. break;
  18137. case 2:
  18138. state_str = "init";
  18139. break;
  18140. case 3:
  18141. state_str = "ready";
  18142. break;
  18143. case 4:
  18144. state_str = "processing";
  18145. break;
  18146. case 5:
  18147. state_str = "processed";
  18148. break;
  18149. case 6:
  18150. state_str = "to close";
  18151. break;
  18152. case 7:
  18153. state_str = "closing";
  18154. break;
  18155. case 8:
  18156. state_str = "closed";
  18157. break;
  18158. case 9:
  18159. state_str = "done";
  18160. break;
  18161. }
  18162. #endif
  18163. /* Connection info */
  18164. if ((state >= 3) && (state < 9)) {
  18165. mg_snprintf(NULL,
  18166. NULL,
  18167. block,
  18168. sizeof(block),
  18169. "%s\"connection\" : {%s"
  18170. "\"remote\" : {%s"
  18171. "\"protocol\" : \"%s\",%s"
  18172. "\"addr\" : \"%s\",%s"
  18173. "\"port\" : %u%s"
  18174. "},%s"
  18175. "\"handled_requests\" : %u%s"
  18176. "}",
  18177. eol,
  18178. eol,
  18179. eol,
  18180. get_proto_name(conn),
  18181. eol,
  18182. ri->remote_addr,
  18183. eol,
  18184. ri->remote_port,
  18185. eol,
  18186. eol,
  18187. conn->handled_requests,
  18188. eol);
  18189. connection_info_length += mg_str_append(&buffer, end, block);
  18190. }
  18191. /* Request info */
  18192. if ((state >= 4) && (state < 6)) {
  18193. mg_snprintf(NULL,
  18194. NULL,
  18195. block,
  18196. sizeof(block),
  18197. "%s%s\"request_info\" : {%s"
  18198. "\"method\" : \"%s\",%s"
  18199. "\"uri\" : \"%s\",%s"
  18200. "\"query\" : %s%s%s%s"
  18201. "}",
  18202. (connection_info_length > 1 ? "," : ""),
  18203. eol,
  18204. eol,
  18205. ri->request_method,
  18206. eol,
  18207. ri->request_uri,
  18208. eol,
  18209. ri->query_string ? "\"" : "",
  18210. ri->query_string ? ri->query_string : "null",
  18211. ri->query_string ? "\"" : "",
  18212. eol);
  18213. connection_info_length += mg_str_append(&buffer, end, block);
  18214. }
  18215. /* Execution time information */
  18216. if ((state >= 2) && (state < 9)) {
  18217. char start_time_str[64] = {0};
  18218. char close_time_str[64] = {0};
  18219. time_t start_time = conn->conn_birth_time;
  18220. time_t close_time = 0;
  18221. double time_diff;
  18222. gmt_time_string(start_time_str,
  18223. sizeof(start_time_str) - 1,
  18224. &start_time);
  18225. #if defined(USE_SERVER_STATS)
  18226. close_time = conn->conn_close_time;
  18227. #endif
  18228. if (close_time != 0) {
  18229. time_diff = difftime(close_time, start_time);
  18230. gmt_time_string(close_time_str,
  18231. sizeof(close_time_str) - 1,
  18232. &close_time);
  18233. } else {
  18234. time_t now = time(NULL);
  18235. time_diff = difftime(now, start_time);
  18236. close_time_str[0] = 0; /* or use "now" ? */
  18237. }
  18238. mg_snprintf(NULL,
  18239. NULL,
  18240. block,
  18241. sizeof(block),
  18242. "%s%s\"time\" : {%s"
  18243. "\"uptime\" : %.0f,%s"
  18244. "\"start\" : \"%s\",%s"
  18245. "\"closed\" : \"%s\"%s"
  18246. "}",
  18247. (connection_info_length > 1 ? "," : ""),
  18248. eol,
  18249. eol,
  18250. time_diff,
  18251. eol,
  18252. start_time_str,
  18253. eol,
  18254. close_time_str,
  18255. eol);
  18256. connection_info_length += mg_str_append(&buffer, end, block);
  18257. }
  18258. /* Remote user name */
  18259. if ((ri->remote_user) && (state < 9)) {
  18260. mg_snprintf(NULL,
  18261. NULL,
  18262. block,
  18263. sizeof(block),
  18264. "%s%s\"user\" : {%s"
  18265. "\"name\" : \"%s\",%s"
  18266. "}",
  18267. (connection_info_length > 1 ? "," : ""),
  18268. eol,
  18269. eol,
  18270. ri->remote_user,
  18271. eol);
  18272. connection_info_length += mg_str_append(&buffer, end, block);
  18273. }
  18274. /* Data block */
  18275. if (state >= 3) {
  18276. mg_snprintf(NULL,
  18277. NULL,
  18278. block,
  18279. sizeof(block),
  18280. "%s%s\"data\" : {%s"
  18281. "\"read\" : %" INT64_FMT ",%s"
  18282. "\"written\" : %" INT64_FMT "%s"
  18283. "}",
  18284. (connection_info_length > 1 ? "," : ""),
  18285. eol,
  18286. eol,
  18287. conn->consumed_content,
  18288. eol,
  18289. conn->num_bytes_sent,
  18290. eol);
  18291. connection_info_length += mg_str_append(&buffer, end, block);
  18292. }
  18293. /* State */
  18294. mg_snprintf(NULL,
  18295. NULL,
  18296. block,
  18297. sizeof(block),
  18298. "%s%s\"state\" : \"%s\"",
  18299. (connection_info_length > 1 ? "," : ""),
  18300. eol,
  18301. state_str);
  18302. connection_info_length += mg_str_append(&buffer, end, block);
  18303. /* Terminate string */
  18304. if (append_eoobj) {
  18305. strcat(append_eoobj, eoobj);
  18306. }
  18307. connection_info_length += sizeof(eoobj) - 1;
  18308. return (int)connection_info_length;
  18309. }
  18310. #endif
  18311. /* Initialize this library. This function does not need to be thread safe.
  18312. */
  18313. unsigned
  18314. mg_init_library(unsigned features)
  18315. {
  18316. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18317. unsigned features_inited = features_to_init;
  18318. if (mg_init_library_called <= 0) {
  18319. /* Not initialized yet */
  18320. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18321. return 0;
  18322. }
  18323. }
  18324. mg_global_lock();
  18325. if (mg_init_library_called <= 0) {
  18326. #if defined(_WIN32)
  18327. int file_mutex_init = 1;
  18328. int wsa = 1;
  18329. #else
  18330. int mutexattr_init = 1;
  18331. #endif
  18332. int failed = 1;
  18333. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18334. if (key_create == 0) {
  18335. #if defined(_WIN32)
  18336. file_mutex_init =
  18337. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18338. if (file_mutex_init == 0) {
  18339. /* Start WinSock */
  18340. WSADATA data;
  18341. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18342. }
  18343. #else
  18344. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18345. if (mutexattr_init == 0) {
  18346. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18347. PTHREAD_MUTEX_RECURSIVE);
  18348. }
  18349. #endif
  18350. }
  18351. if (failed) {
  18352. #if defined(_WIN32)
  18353. if (wsa == 0) {
  18354. (void)WSACleanup();
  18355. }
  18356. if (file_mutex_init == 0) {
  18357. (void)pthread_mutex_destroy(&global_log_file_lock);
  18358. }
  18359. #else
  18360. if (mutexattr_init == 0) {
  18361. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18362. }
  18363. #endif
  18364. if (key_create == 0) {
  18365. (void)pthread_key_delete(sTlsKey);
  18366. }
  18367. mg_global_unlock();
  18368. (void)pthread_mutex_destroy(&global_lock_mutex);
  18369. return 0;
  18370. }
  18371. #if defined(USE_LUA)
  18372. lua_init_optional_libraries();
  18373. #endif
  18374. }
  18375. mg_global_unlock();
  18376. #if !defined(NO_SSL)
  18377. if (features_to_init & MG_FEATURES_SSL) {
  18378. if (!mg_ssl_initialized) {
  18379. char ebuf[128];
  18380. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18381. mg_ssl_initialized = 1;
  18382. } else {
  18383. (void)ebuf;
  18384. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18385. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18386. }
  18387. } else {
  18388. /* ssl already initialized */
  18389. }
  18390. }
  18391. #endif
  18392. mg_global_lock();
  18393. if (mg_init_library_called <= 0) {
  18394. mg_init_library_called = 1;
  18395. } else {
  18396. mg_init_library_called++;
  18397. }
  18398. mg_global_unlock();
  18399. return features_inited;
  18400. }
  18401. /* Un-initialize this library. */
  18402. unsigned
  18403. mg_exit_library(void)
  18404. {
  18405. if (mg_init_library_called <= 0) {
  18406. return 0;
  18407. }
  18408. mg_global_lock();
  18409. mg_init_library_called--;
  18410. if (mg_init_library_called == 0) {
  18411. #if !defined(NO_SSL)
  18412. if (mg_ssl_initialized) {
  18413. uninitialize_ssl();
  18414. mg_ssl_initialized = 0;
  18415. }
  18416. #endif
  18417. #if defined(_WIN32)
  18418. (void)WSACleanup();
  18419. (void)pthread_mutex_destroy(&global_log_file_lock);
  18420. #else
  18421. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18422. #endif
  18423. (void)pthread_key_delete(sTlsKey);
  18424. #if defined(USE_LUA)
  18425. lua_exit_optional_libraries();
  18426. #endif
  18427. mg_global_unlock();
  18428. (void)pthread_mutex_destroy(&global_lock_mutex);
  18429. return 1;
  18430. }
  18431. mg_global_unlock();
  18432. return 1;
  18433. }
  18434. /* End of civetweb.c */