civetweb.c 568 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170
  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. #if defined(USE_IPV6)
  2028. #define USA_IN_PORT_UNSAFE(s) \
  2029. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  2030. #else
  2031. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  2032. #endif
  2033. /* Describes a string (chunk of memory). */
  2034. struct vec {
  2035. const char *ptr;
  2036. size_t len;
  2037. };
  2038. struct mg_file_stat {
  2039. /* File properties filled by mg_stat: */
  2040. uint64_t size;
  2041. time_t last_modified;
  2042. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2043. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2044. * case we need a "Content-Eencoding: gzip" header */
  2045. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2046. };
  2047. struct mg_file_in_memory {
  2048. char *p;
  2049. uint32_t pos;
  2050. char mode;
  2051. };
  2052. struct mg_file_access {
  2053. /* File properties filled by mg_fopen: */
  2054. FILE *fp;
  2055. #if defined(MG_USE_OPEN_FILE)
  2056. /* TODO (low): Remove obsolete "file in memory" implementation.
  2057. * In an "early 2017" discussion at Google groups
  2058. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2059. * we decided to get rid of this feature (after some fade-out
  2060. * phase). */
  2061. const char *membuf;
  2062. #endif
  2063. };
  2064. struct mg_file {
  2065. struct mg_file_stat stat;
  2066. struct mg_file_access access;
  2067. };
  2068. #if defined(MG_USE_OPEN_FILE)
  2069. #define STRUCT_FILE_INITIALIZER \
  2070. { \
  2071. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2072. { \
  2073. (FILE *)NULL, (const char *)NULL \
  2074. } \
  2075. }
  2076. #else
  2077. #define STRUCT_FILE_INITIALIZER \
  2078. { \
  2079. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2080. { \
  2081. (FILE *)NULL \
  2082. } \
  2083. }
  2084. #endif
  2085. /* Describes listening socket, or socket which was accept()-ed by the master
  2086. * thread and queued for future handling by the worker thread. */
  2087. struct socket {
  2088. SOCKET sock; /* Listening socket */
  2089. union usa lsa; /* Local socket address */
  2090. union usa rsa; /* Remote socket address */
  2091. unsigned char is_ssl; /* Is port SSL-ed */
  2092. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2093. * port */
  2094. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2095. };
  2096. /* Enum const for all options must be in sync with
  2097. * static struct mg_option config_options[]
  2098. * This is tested in the unit test (test/private.c)
  2099. * "Private Config Options"
  2100. */
  2101. enum {
  2102. /* Once for each server */
  2103. LISTENING_PORTS,
  2104. NUM_THREADS,
  2105. RUN_AS_USER,
  2106. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2107. * socket option typedef TCP_NODELAY. */
  2108. MAX_REQUEST_SIZE,
  2109. LINGER_TIMEOUT,
  2110. CONNECTION_QUEUE_SIZE,
  2111. LISTEN_BACKLOG_SIZE,
  2112. #if defined(__linux__)
  2113. ALLOW_SENDFILE_CALL,
  2114. #endif
  2115. #if defined(_WIN32)
  2116. CASE_SENSITIVE_FILES,
  2117. #endif
  2118. THROTTLE,
  2119. ACCESS_LOG_FILE,
  2120. ERROR_LOG_FILE,
  2121. ENABLE_KEEP_ALIVE,
  2122. REQUEST_TIMEOUT,
  2123. KEEP_ALIVE_TIMEOUT,
  2124. #if defined(USE_WEBSOCKET)
  2125. WEBSOCKET_TIMEOUT,
  2126. ENABLE_WEBSOCKET_PING_PONG,
  2127. #endif
  2128. DECODE_URL,
  2129. #if defined(USE_LUA)
  2130. LUA_BACKGROUND_SCRIPT,
  2131. LUA_BACKGROUND_SCRIPT_PARAMS,
  2132. #endif
  2133. #if defined(USE_TIMERS)
  2134. CGI_TIMEOUT,
  2135. #endif
  2136. /* Once for each domain */
  2137. DOCUMENT_ROOT,
  2138. CGI_EXTENSIONS,
  2139. CGI_ENVIRONMENT,
  2140. PUT_DELETE_PASSWORDS_FILE,
  2141. CGI_INTERPRETER,
  2142. CGI_INTERPRETER_ARGS,
  2143. PROTECT_URI,
  2144. AUTHENTICATION_DOMAIN,
  2145. ENABLE_AUTH_DOMAIN_CHECK,
  2146. SSI_EXTENSIONS,
  2147. ENABLE_DIRECTORY_LISTING,
  2148. GLOBAL_PASSWORDS_FILE,
  2149. INDEX_FILES,
  2150. ACCESS_CONTROL_LIST,
  2151. EXTRA_MIME_TYPES,
  2152. SSL_CERTIFICATE,
  2153. SSL_CERTIFICATE_CHAIN,
  2154. URL_REWRITE_PATTERN,
  2155. HIDE_FILES,
  2156. SSL_DO_VERIFY_PEER,
  2157. SSL_CA_PATH,
  2158. SSL_CA_FILE,
  2159. SSL_VERIFY_DEPTH,
  2160. SSL_DEFAULT_VERIFY_PATHS,
  2161. SSL_CIPHER_LIST,
  2162. SSL_PROTOCOL_VERSION,
  2163. SSL_SHORT_TRUST,
  2164. #if defined(USE_LUA)
  2165. LUA_PRELOAD_FILE,
  2166. LUA_SCRIPT_EXTENSIONS,
  2167. LUA_SERVER_PAGE_EXTENSIONS,
  2168. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2169. LUA_DEBUG_PARAMS,
  2170. #endif
  2171. #endif
  2172. #if defined(USE_DUKTAPE)
  2173. DUKTAPE_SCRIPT_EXTENSIONS,
  2174. #endif
  2175. #if defined(USE_WEBSOCKET)
  2176. WEBSOCKET_ROOT,
  2177. #endif
  2178. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2179. LUA_WEBSOCKET_EXTENSIONS,
  2180. #endif
  2181. ACCESS_CONTROL_ALLOW_ORIGIN,
  2182. ACCESS_CONTROL_ALLOW_METHODS,
  2183. ACCESS_CONTROL_ALLOW_HEADERS,
  2184. ERROR_PAGES,
  2185. #if !defined(NO_CACHING)
  2186. STATIC_FILE_MAX_AGE,
  2187. STATIC_FILE_CACHE_CONTROL,
  2188. #endif
  2189. #if !defined(NO_SSL)
  2190. STRICT_HTTPS_MAX_AGE,
  2191. #endif
  2192. ADDITIONAL_HEADER,
  2193. ALLOW_INDEX_SCRIPT_SUB_RES,
  2194. #if defined(DAEMONIZE)
  2195. ENABLE_DAEMONIZE,
  2196. #endif
  2197. NUM_OPTIONS
  2198. };
  2199. /* Config option name, config types, default value.
  2200. * Must be in the same order as the enum const above.
  2201. */
  2202. static const struct mg_option config_options[] = {
  2203. /* Once for each server */
  2204. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2205. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2206. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2207. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2208. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2209. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2210. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2211. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2212. #if defined(__linux__)
  2213. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2214. #endif
  2215. #if defined(_WIN32)
  2216. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2217. #endif
  2218. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2219. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2220. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2221. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2222. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2223. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2224. #if defined(USE_WEBSOCKET)
  2225. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2226. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2227. #endif
  2228. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2229. #if defined(USE_LUA)
  2230. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2231. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2232. #endif
  2233. #if defined(USE_TIMERS)
  2234. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2235. #endif
  2236. /* Once for each domain */
  2237. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2238. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2239. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2240. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2241. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2242. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2243. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2244. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2245. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2246. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2247. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2248. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2249. {"index_files",
  2250. MG_CONFIG_TYPE_STRING_LIST,
  2251. #if defined(USE_LUA)
  2252. "index.xhtml,index.html,index.htm,"
  2253. "index.lp,index.lsp,index.lua,index.cgi,"
  2254. "index.shtml,index.php"},
  2255. #else
  2256. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2257. #endif
  2258. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2259. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2260. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2261. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2262. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2263. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2264. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2265. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2266. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2267. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2268. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2269. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2270. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2271. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2272. #if defined(USE_LUA)
  2273. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2274. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2275. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2276. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2277. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2278. #endif
  2279. #endif
  2280. #if defined(USE_DUKTAPE)
  2281. /* The support for duktape is still in alpha version state.
  2282. * The name of this config option might change. */
  2283. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2284. #endif
  2285. #if defined(USE_WEBSOCKET)
  2286. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2287. #endif
  2288. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2289. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2290. #endif
  2291. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2292. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2293. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2294. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2295. #if !defined(NO_CACHING)
  2296. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2297. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2298. #endif
  2299. #if !defined(NO_SSL)
  2300. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2301. #endif
  2302. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2303. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2304. #if defined(DAEMONIZE)
  2305. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2306. #endif
  2307. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2308. /* Check if the config_options and the corresponding enum have compatible
  2309. * sizes. */
  2310. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2311. == (NUM_OPTIONS + 1),
  2312. "config_options and enum not sync");
  2313. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2314. struct mg_handler_info {
  2315. /* Name/Pattern of the URI. */
  2316. char *uri;
  2317. size_t uri_len;
  2318. /* handler type */
  2319. int handler_type;
  2320. /* Handler for http/https or authorization requests. */
  2321. mg_request_handler handler;
  2322. unsigned int refcount;
  2323. int removing;
  2324. /* Handler for ws/wss (websocket) requests. */
  2325. mg_websocket_connect_handler connect_handler;
  2326. mg_websocket_ready_handler ready_handler;
  2327. mg_websocket_data_handler data_handler;
  2328. mg_websocket_close_handler close_handler;
  2329. /* accepted subprotocols for ws/wss requests. */
  2330. struct mg_websocket_subprotocols *subprotocols;
  2331. /* Handler for authorization requests */
  2332. mg_authorization_handler auth_handler;
  2333. /* User supplied argument for the handler function. */
  2334. void *cbdata;
  2335. /* next handler in a linked list */
  2336. struct mg_handler_info *next;
  2337. };
  2338. enum {
  2339. CONTEXT_INVALID,
  2340. CONTEXT_SERVER,
  2341. CONTEXT_HTTP_CLIENT,
  2342. CONTEXT_WS_CLIENT
  2343. };
  2344. struct mg_domain_context {
  2345. SSL_CTX *ssl_ctx; /* SSL context */
  2346. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2347. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2348. int64_t ssl_cert_last_mtime;
  2349. /* Server nonce */
  2350. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2351. unsigned long nonce_count; /* Used nonces, used for authentication */
  2352. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2353. /* linked list of shared lua websockets */
  2354. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2355. #endif
  2356. /* Linked list of domains */
  2357. struct mg_domain_context *next;
  2358. };
  2359. /* Stop flag can be "volatile" or require a lock */
  2360. typedef int volatile stop_flag_t;
  2361. #ifdef STOP_FLAG_NEEDS_LOCK
  2362. static int
  2363. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2364. {
  2365. int r;
  2366. mg_global_lock();
  2367. r = ((*f) == 0);
  2368. mg_global_unlock();
  2369. return r;
  2370. }
  2371. static int
  2372. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2373. {
  2374. int r;
  2375. mg_global_lock();
  2376. r = ((*f) == 2);
  2377. mg_global_unlock();
  2378. return r;
  2379. }
  2380. static void
  2381. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2382. {
  2383. mg_global_lock();
  2384. (*f) = v;
  2385. mg_global_unlock();
  2386. }
  2387. #else /* STOP_FLAG_NEEDS_LOCK */
  2388. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2389. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2390. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2391. #endif /* STOP_FLAG_NEEDS_LOCK */
  2392. struct mg_context {
  2393. /* Part 1 - Physical context:
  2394. * This holds threads, ports, timeouts, ...
  2395. * set for the entire server, independent from the
  2396. * addressed hostname.
  2397. */
  2398. /* Connection related */
  2399. int context_type; /* See CONTEXT_* above */
  2400. struct socket *listening_sockets;
  2401. struct mg_pollfd *listening_socket_fds;
  2402. unsigned int num_listening_sockets;
  2403. struct mg_connection *worker_connections; /* The connection struct, pre-
  2404. * allocated for each worker */
  2405. #if defined(USE_SERVER_STATS)
  2406. int active_connections;
  2407. int max_active_connections;
  2408. int64_t total_connections;
  2409. int64_t total_requests;
  2410. int64_t total_data_read;
  2411. int64_t total_data_written;
  2412. #endif
  2413. /* Thread related */
  2414. stop_flag_t stop_flag; /* Should we stop event loop */
  2415. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2416. pthread_t masterthreadid; /* The master thread ID */
  2417. unsigned int
  2418. cfg_worker_threads; /* The number of configured worker threads. */
  2419. pthread_t *worker_threadids; /* The worker thread IDs */
  2420. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2421. /* Connection to thread dispatching */
  2422. #if defined(ALTERNATIVE_QUEUE)
  2423. struct socket *client_socks;
  2424. void **client_wait_events;
  2425. #else
  2426. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2427. worker thread */
  2428. volatile int sq_head; /* Head of the socket queue */
  2429. volatile int sq_tail; /* Tail of the socket queue */
  2430. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2431. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2432. volatile int sq_blocked; /* Status information: sq is full */
  2433. int sq_size; /* No of elements in socket queue */
  2434. #if defined(USE_SERVER_STATS)
  2435. int sq_max_fill;
  2436. #endif /* USE_SERVER_STATS */
  2437. #endif /* ALTERNATIVE_QUEUE */
  2438. /* Memory related */
  2439. unsigned int max_request_size; /* The max request size */
  2440. #if defined(USE_SERVER_STATS)
  2441. struct mg_memory_stat ctx_memory;
  2442. #endif
  2443. /* Operating system related */
  2444. char *systemName; /* What operating system is running */
  2445. time_t start_time; /* Server start time, used for authentication
  2446. * and for diagnstics. */
  2447. #if defined(USE_TIMERS)
  2448. struct ttimers *timers;
  2449. #endif
  2450. /* Lua specific: Background operations and shared websockets */
  2451. #if defined(USE_LUA)
  2452. void *lua_background_state;
  2453. #endif
  2454. /* Server nonce */
  2455. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2456. * ssl_cert_last_mtime, nonce_count, and
  2457. * next (linked list) */
  2458. /* Server callbacks */
  2459. struct mg_callbacks callbacks; /* User-defined callback function */
  2460. void *user_data; /* User-defined data */
  2461. /* Part 2 - Logical domain:
  2462. * This holds hostname, TLS certificate, document root, ...
  2463. * set for a domain hosted at the server.
  2464. * There may be multiple domains hosted at one physical server.
  2465. * The default domain "dd" is the first element of a list of
  2466. * domains.
  2467. */
  2468. struct mg_domain_context dd; /* default domain */
  2469. };
  2470. #if defined(USE_SERVER_STATS)
  2471. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2472. static struct mg_memory_stat *
  2473. get_memory_stat(struct mg_context *ctx)
  2474. {
  2475. if (ctx) {
  2476. return &(ctx->ctx_memory);
  2477. }
  2478. return &mg_common_memory;
  2479. }
  2480. #endif
  2481. enum {
  2482. CONNECTION_TYPE_INVALID,
  2483. CONNECTION_TYPE_REQUEST,
  2484. CONNECTION_TYPE_RESPONSE
  2485. };
  2486. enum {
  2487. PROTOCOL_TYPE_HTTP1 = 0,
  2488. PROTOCOL_TYPE_WEBSOCKET = 1,
  2489. PROTOCOL_TYPE_HTTP2 = 2
  2490. };
  2491. struct mg_connection {
  2492. int connection_type; /* see CONNECTION_TYPE_* above */
  2493. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2494. struct mg_request_info request_info;
  2495. struct mg_response_info response_info;
  2496. struct mg_context *phys_ctx;
  2497. struct mg_domain_context *dom_ctx;
  2498. #if defined(USE_SERVER_STATS)
  2499. int conn_state; /* 0 = undef, numerical value may change in different
  2500. * versions. For the current definition, see
  2501. * mg_get_connection_info_impl */
  2502. #endif
  2503. SSL *ssl; /* SSL descriptor */
  2504. struct socket client; /* Connected client */
  2505. time_t conn_birth_time; /* Time (wall clock) when connection was
  2506. * established */
  2507. #if defined(USE_SERVER_STATS)
  2508. time_t conn_close_time; /* Time (wall clock) when connection was
  2509. * closed (or 0 if still open) */
  2510. #endif
  2511. struct timespec req_time; /* Time (since system start) when the request
  2512. * was received */
  2513. int64_t num_bytes_sent; /* Total bytes sent to client */
  2514. int64_t content_len; /* How many bytes of content can be read
  2515. * !is_chunked: Content-Length header value
  2516. * or -1 (until connection closed,
  2517. * not allowed for a request)
  2518. * is_chunked: >= 0, appended gradually
  2519. */
  2520. int64_t consumed_content; /* How many bytes of content have been read */
  2521. int is_chunked; /* Transfer-Encoding is chunked:
  2522. * 0 = not chunked,
  2523. * 1 = chunked, not yet, or some data read,
  2524. * 2 = chunked, has error,
  2525. * 3 = chunked, all data read except trailer,
  2526. * 4 = chunked, all data read
  2527. */
  2528. char *buf; /* Buffer for received data */
  2529. char *path_info; /* PATH_INFO part of the URL */
  2530. int must_close; /* 1 if connection must be closed */
  2531. int accept_gzip; /* 1 if gzip encoding is accepted */
  2532. int in_error_handler; /* 1 if in handler for user defined error
  2533. * pages */
  2534. #if defined(USE_WEBSOCKET)
  2535. int in_websocket_handling; /* 1 if in read_websocket */
  2536. #endif
  2537. int handled_requests; /* Number of requests handled by this connection
  2538. */
  2539. int buf_size; /* Buffer size */
  2540. int request_len; /* Size of the request + headers in a buffer */
  2541. int data_len; /* Total size of data in a buffer */
  2542. int status_code; /* HTTP reply status code, e.g. 200 */
  2543. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2544. * throttle */
  2545. time_t last_throttle_time; /* Last time throttled data was sent */
  2546. int last_throttle_bytes; /* Bytes sent this second */
  2547. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2548. * atomic transmissions for websockets */
  2549. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2550. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2551. #endif
  2552. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2553. * for quick access */
  2554. };
  2555. /* Directory entry */
  2556. struct de {
  2557. struct mg_connection *conn;
  2558. char *file_name;
  2559. struct mg_file_stat file;
  2560. };
  2561. #define mg_cry_internal(conn, fmt, ...) \
  2562. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2563. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2564. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2565. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2566. struct mg_context *ctx,
  2567. const char *func,
  2568. unsigned line,
  2569. const char *fmt,
  2570. ...) PRINTF_ARGS(5, 6);
  2571. #if !defined(NO_THREAD_NAME)
  2572. #if defined(_WIN32) && defined(_MSC_VER)
  2573. /* Set the thread name for debugging purposes in Visual Studio
  2574. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2575. */
  2576. #pragma pack(push, 8)
  2577. typedef struct tagTHREADNAME_INFO {
  2578. DWORD dwType; /* Must be 0x1000. */
  2579. LPCSTR szName; /* Pointer to name (in user addr space). */
  2580. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2581. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2582. } THREADNAME_INFO;
  2583. #pragma pack(pop)
  2584. #elif defined(__linux__)
  2585. #include <sys/prctl.h>
  2586. #include <sys/sendfile.h>
  2587. #if defined(ALTERNATIVE_QUEUE)
  2588. #include <sys/eventfd.h>
  2589. #endif /* ALTERNATIVE_QUEUE */
  2590. #if defined(ALTERNATIVE_QUEUE)
  2591. static void *
  2592. event_create(void)
  2593. {
  2594. int evhdl = eventfd(0, EFD_CLOEXEC);
  2595. int *ret;
  2596. if (evhdl == -1) {
  2597. /* Linux uses -1 on error, Windows NULL. */
  2598. /* However, Linux does not return 0 on success either. */
  2599. return 0;
  2600. }
  2601. ret = (int *)mg_malloc(sizeof(int));
  2602. if (ret) {
  2603. *ret = evhdl;
  2604. } else {
  2605. (void)close(evhdl);
  2606. }
  2607. return (void *)ret;
  2608. }
  2609. static int
  2610. event_wait(void *eventhdl)
  2611. {
  2612. uint64_t u;
  2613. int evhdl, s;
  2614. if (!eventhdl) {
  2615. /* error */
  2616. return 0;
  2617. }
  2618. evhdl = *(int *)eventhdl;
  2619. s = (int)read(evhdl, &u, sizeof(u));
  2620. if (s != sizeof(u)) {
  2621. /* error */
  2622. return 0;
  2623. }
  2624. (void)u; /* the value is not required */
  2625. return 1;
  2626. }
  2627. static int
  2628. event_signal(void *eventhdl)
  2629. {
  2630. uint64_t u = 1;
  2631. int evhdl, s;
  2632. if (!eventhdl) {
  2633. /* error */
  2634. return 0;
  2635. }
  2636. evhdl = *(int *)eventhdl;
  2637. s = (int)write(evhdl, &u, sizeof(u));
  2638. if (s != sizeof(u)) {
  2639. /* error */
  2640. return 0;
  2641. }
  2642. return 1;
  2643. }
  2644. static void
  2645. event_destroy(void *eventhdl)
  2646. {
  2647. int evhdl;
  2648. if (!eventhdl) {
  2649. /* error */
  2650. return;
  2651. }
  2652. evhdl = *(int *)eventhdl;
  2653. close(evhdl);
  2654. mg_free(eventhdl);
  2655. }
  2656. #endif
  2657. #endif
  2658. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2659. struct posix_event {
  2660. pthread_mutex_t mutex;
  2661. pthread_cond_t cond;
  2662. int signaled;
  2663. };
  2664. static void *
  2665. event_create(void)
  2666. {
  2667. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2668. if (ret == 0) {
  2669. /* out of memory */
  2670. return 0;
  2671. }
  2672. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2673. /* pthread mutex not available */
  2674. mg_free(ret);
  2675. return 0;
  2676. }
  2677. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2678. /* pthread cond not available */
  2679. pthread_mutex_destroy(&(ret->mutex));
  2680. mg_free(ret);
  2681. return 0;
  2682. }
  2683. ret->signaled = 0;
  2684. return (void *)ret;
  2685. }
  2686. static int
  2687. event_wait(void *eventhdl)
  2688. {
  2689. struct posix_event *ev = (struct posix_event *)eventhdl;
  2690. pthread_mutex_lock(&(ev->mutex));
  2691. while (!ev->signaled) {
  2692. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2693. }
  2694. ev->signaled = 0;
  2695. pthread_mutex_unlock(&(ev->mutex));
  2696. return 1;
  2697. }
  2698. static int
  2699. event_signal(void *eventhdl)
  2700. {
  2701. struct posix_event *ev = (struct posix_event *)eventhdl;
  2702. pthread_mutex_lock(&(ev->mutex));
  2703. pthread_cond_signal(&(ev->cond));
  2704. ev->signaled = 1;
  2705. pthread_mutex_unlock(&(ev->mutex));
  2706. return 1;
  2707. }
  2708. static void
  2709. event_destroy(void *eventhdl)
  2710. {
  2711. struct posix_event *ev = (struct posix_event *)eventhdl;
  2712. pthread_cond_destroy(&(ev->cond));
  2713. pthread_mutex_destroy(&(ev->mutex));
  2714. mg_free(ev);
  2715. }
  2716. #endif
  2717. static void
  2718. mg_set_thread_name(const char *name)
  2719. {
  2720. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2721. mg_snprintf(
  2722. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2723. #if defined(_WIN32)
  2724. #if defined(_MSC_VER)
  2725. /* Windows and Visual Studio Compiler */
  2726. __try {
  2727. THREADNAME_INFO info;
  2728. info.dwType = 0x1000;
  2729. info.szName = threadName;
  2730. info.dwThreadID = ~0U;
  2731. info.dwFlags = 0;
  2732. RaiseException(0x406D1388,
  2733. 0,
  2734. sizeof(info) / sizeof(ULONG_PTR),
  2735. (ULONG_PTR *)&info);
  2736. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2737. }
  2738. #elif defined(__MINGW32__)
  2739. /* No option known to set thread name for MinGW known */
  2740. #endif
  2741. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2742. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2743. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2744. #if defined(__MACH__)
  2745. /* OS X only current thread name can be changed */
  2746. (void)pthread_setname_np(threadName);
  2747. #else
  2748. (void)pthread_setname_np(pthread_self(), threadName);
  2749. #endif
  2750. #elif defined(__linux__)
  2751. /* On Linux we can use the prctl function.
  2752. * When building for Linux Standard Base (LSB) use
  2753. * NO_THREAD_NAME. However, thread names are a big
  2754. * help for debugging, so the stadard is to set them.
  2755. */
  2756. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2757. #endif
  2758. }
  2759. #else /* !defined(NO_THREAD_NAME) */
  2760. void
  2761. mg_set_thread_name(const char *threadName)
  2762. {
  2763. }
  2764. #endif
  2765. #if defined(MG_LEGACY_INTERFACE)
  2766. const char **
  2767. mg_get_valid_option_names(void)
  2768. {
  2769. /* This function is deprecated. Use mg_get_valid_options instead. */
  2770. static const char
  2771. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2772. int i;
  2773. for (i = 0; config_options[i].name != NULL; i++) {
  2774. data[i * 2] = config_options[i].name;
  2775. data[i * 2 + 1] = config_options[i].default_value;
  2776. }
  2777. return data;
  2778. }
  2779. #endif
  2780. const struct mg_option *
  2781. mg_get_valid_options(void)
  2782. {
  2783. return config_options;
  2784. }
  2785. /* Do not open file (used in is_file_in_memory) */
  2786. #define MG_FOPEN_MODE_NONE (0)
  2787. /* Open file for read only access */
  2788. #define MG_FOPEN_MODE_READ (1)
  2789. /* Open file for writing, create and overwrite */
  2790. #define MG_FOPEN_MODE_WRITE (2)
  2791. /* Open file for writing, create and append */
  2792. #define MG_FOPEN_MODE_APPEND (4)
  2793. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2794. * output filep and return 1, otherwise return 0 and don't modify anything.
  2795. */
  2796. static int
  2797. open_file_in_memory(const struct mg_connection *conn,
  2798. const char *path,
  2799. struct mg_file *filep,
  2800. int mode)
  2801. {
  2802. #if defined(MG_USE_OPEN_FILE)
  2803. size_t size = 0;
  2804. const char *buf = NULL;
  2805. if (!conn) {
  2806. return 0;
  2807. }
  2808. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2809. return 0;
  2810. }
  2811. if (conn->phys_ctx->callbacks.open_file) {
  2812. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2813. if (buf != NULL) {
  2814. if (filep == NULL) {
  2815. /* This is a file in memory, but we cannot store the
  2816. * properties
  2817. * now.
  2818. * Called from "is_file_in_memory" function. */
  2819. return 1;
  2820. }
  2821. /* NOTE: override filep->size only on success. Otherwise, it
  2822. * might
  2823. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2824. filep->access.membuf = buf;
  2825. filep->access.fp = NULL;
  2826. /* Size was set by the callback */
  2827. filep->stat.size = size;
  2828. /* Assume the data may change during runtime by setting
  2829. * last_modified = now */
  2830. filep->stat.last_modified = time(NULL);
  2831. filep->stat.is_directory = 0;
  2832. filep->stat.is_gzipped = 0;
  2833. }
  2834. }
  2835. return (buf != NULL);
  2836. #else
  2837. (void)conn;
  2838. (void)path;
  2839. (void)filep;
  2840. (void)mode;
  2841. return 0;
  2842. #endif
  2843. }
  2844. static int
  2845. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2846. {
  2847. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2848. }
  2849. static int
  2850. is_file_opened(const struct mg_file_access *fileacc)
  2851. {
  2852. if (!fileacc) {
  2853. return 0;
  2854. }
  2855. #if defined(MG_USE_OPEN_FILE)
  2856. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2857. #else
  2858. return (fileacc->fp != NULL);
  2859. #endif
  2860. }
  2861. #if !defined(NO_FILESYSTEMS)
  2862. static int mg_stat(const struct mg_connection *conn,
  2863. const char *path,
  2864. struct mg_file_stat *filep);
  2865. /* mg_fopen will open a file either in memory or on the disk.
  2866. * The input parameter path is a string in UTF-8 encoding.
  2867. * The input parameter mode is MG_FOPEN_MODE_*
  2868. * On success, either fp or membuf will be set in the output
  2869. * struct file. All status members will also be set.
  2870. * The function returns 1 on success, 0 on error. */
  2871. static int
  2872. mg_fopen(const struct mg_connection *conn,
  2873. const char *path,
  2874. int mode,
  2875. struct mg_file *filep)
  2876. {
  2877. int found;
  2878. if (!filep) {
  2879. return 0;
  2880. }
  2881. filep->access.fp = NULL;
  2882. #if defined(MG_USE_OPEN_FILE)
  2883. filep->access.membuf = NULL;
  2884. #endif
  2885. if (!is_file_in_memory(conn, path)) {
  2886. /* filep is initialized in mg_stat: all fields with memset to,
  2887. * some fields like size and modification date with values */
  2888. found = mg_stat(conn, path, &(filep->stat));
  2889. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2890. /* file does not exist and will not be created */
  2891. return 0;
  2892. }
  2893. #if defined(_WIN32)
  2894. {
  2895. wchar_t wbuf[W_PATH_MAX];
  2896. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2897. switch (mode) {
  2898. case MG_FOPEN_MODE_READ:
  2899. filep->access.fp = _wfopen(wbuf, L"rb");
  2900. break;
  2901. case MG_FOPEN_MODE_WRITE:
  2902. filep->access.fp = _wfopen(wbuf, L"wb");
  2903. break;
  2904. case MG_FOPEN_MODE_APPEND:
  2905. filep->access.fp = _wfopen(wbuf, L"ab");
  2906. break;
  2907. }
  2908. }
  2909. #else
  2910. /* Linux et al already use unicode. No need to convert. */
  2911. switch (mode) {
  2912. case MG_FOPEN_MODE_READ:
  2913. filep->access.fp = fopen(path, "r");
  2914. break;
  2915. case MG_FOPEN_MODE_WRITE:
  2916. filep->access.fp = fopen(path, "w");
  2917. break;
  2918. case MG_FOPEN_MODE_APPEND:
  2919. filep->access.fp = fopen(path, "a");
  2920. break;
  2921. }
  2922. #endif
  2923. if (!found) {
  2924. /* File did not exist before fopen was called.
  2925. * Maybe it has been created now. Get stat info
  2926. * like creation time now. */
  2927. found = mg_stat(conn, path, &(filep->stat));
  2928. (void)found;
  2929. }
  2930. /* file is on disk */
  2931. return (filep->access.fp != NULL);
  2932. } else {
  2933. #if defined(MG_USE_OPEN_FILE)
  2934. /* is_file_in_memory returned true */
  2935. if (open_file_in_memory(conn, path, filep, mode)) {
  2936. /* file is in memory */
  2937. return (filep->access.membuf != NULL);
  2938. }
  2939. #endif
  2940. }
  2941. /* Open failed */
  2942. return 0;
  2943. }
  2944. /* return 0 on success, just like fclose */
  2945. static int
  2946. mg_fclose(struct mg_file_access *fileacc)
  2947. {
  2948. int ret = -1;
  2949. if (fileacc != NULL) {
  2950. if (fileacc->fp != NULL) {
  2951. ret = fclose(fileacc->fp);
  2952. #if defined(MG_USE_OPEN_FILE)
  2953. } else if (fileacc->membuf != NULL) {
  2954. ret = 0;
  2955. #endif
  2956. }
  2957. /* reset all members of fileacc */
  2958. memset(fileacc, 0, sizeof(*fileacc));
  2959. }
  2960. return ret;
  2961. }
  2962. #endif /* NO_FILESYSTEMS */
  2963. static void
  2964. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2965. {
  2966. for (; *src != '\0' && n > 1; n--) {
  2967. *dst++ = *src++;
  2968. }
  2969. *dst = '\0';
  2970. }
  2971. static int
  2972. lowercase(const char *s)
  2973. {
  2974. return tolower((unsigned char)*s);
  2975. }
  2976. int
  2977. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2978. {
  2979. int diff = 0;
  2980. if (len > 0) {
  2981. do {
  2982. diff = lowercase(s1++) - lowercase(s2++);
  2983. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2984. }
  2985. return diff;
  2986. }
  2987. int
  2988. mg_strcasecmp(const char *s1, const char *s2)
  2989. {
  2990. int diff;
  2991. do {
  2992. diff = lowercase(s1++) - lowercase(s2++);
  2993. } while (diff == 0 && s1[-1] != '\0');
  2994. return diff;
  2995. }
  2996. static char *
  2997. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2998. {
  2999. char *p;
  3000. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3001. * defined */
  3002. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3003. mg_strlcpy(p, ptr, len + 1);
  3004. }
  3005. return p;
  3006. }
  3007. static char *
  3008. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3009. {
  3010. return mg_strndup_ctx(str, strlen(str), ctx);
  3011. }
  3012. static char *
  3013. mg_strdup(const char *str)
  3014. {
  3015. return mg_strndup_ctx(str, strlen(str), NULL);
  3016. }
  3017. static const char *
  3018. mg_strcasestr(const char *big_str, const char *small_str)
  3019. {
  3020. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3021. if (big_len >= small_len) {
  3022. for (i = 0; i <= (big_len - small_len); i++) {
  3023. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3024. return big_str + i;
  3025. }
  3026. }
  3027. }
  3028. return NULL;
  3029. }
  3030. /* Return null terminated string of given maximum length.
  3031. * Report errors if length is exceeded. */
  3032. static void
  3033. mg_vsnprintf(const struct mg_connection *conn,
  3034. int *truncated,
  3035. char *buf,
  3036. size_t buflen,
  3037. const char *fmt,
  3038. va_list ap)
  3039. {
  3040. int n, ok;
  3041. if (buflen == 0) {
  3042. if (truncated) {
  3043. *truncated = 1;
  3044. }
  3045. return;
  3046. }
  3047. #if defined(__clang__)
  3048. #pragma clang diagnostic push
  3049. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3050. /* Using fmt as a non-literal is intended here, since it is mostly called
  3051. * indirectly by mg_snprintf */
  3052. #endif
  3053. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3054. ok = (n >= 0) && ((size_t)n < buflen);
  3055. #if defined(__clang__)
  3056. #pragma clang diagnostic pop
  3057. #endif
  3058. if (ok) {
  3059. if (truncated) {
  3060. *truncated = 0;
  3061. }
  3062. } else {
  3063. if (truncated) {
  3064. *truncated = 1;
  3065. }
  3066. mg_cry_internal(conn,
  3067. "truncating vsnprintf buffer: [%.*s]",
  3068. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3069. buf);
  3070. n = (int)buflen - 1;
  3071. }
  3072. buf[n] = '\0';
  3073. }
  3074. static void
  3075. mg_snprintf(const struct mg_connection *conn,
  3076. int *truncated,
  3077. char *buf,
  3078. size_t buflen,
  3079. const char *fmt,
  3080. ...)
  3081. {
  3082. va_list ap;
  3083. va_start(ap, fmt);
  3084. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3085. va_end(ap);
  3086. }
  3087. static int
  3088. get_option_index(const char *name)
  3089. {
  3090. int i;
  3091. for (i = 0; config_options[i].name != NULL; i++) {
  3092. if (strcmp(config_options[i].name, name) == 0) {
  3093. return i;
  3094. }
  3095. }
  3096. return -1;
  3097. }
  3098. const char *
  3099. mg_get_option(const struct mg_context *ctx, const char *name)
  3100. {
  3101. int i;
  3102. if ((i = get_option_index(name)) == -1) {
  3103. return NULL;
  3104. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3105. return "";
  3106. } else {
  3107. return ctx->dd.config[i];
  3108. }
  3109. }
  3110. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3111. struct mg_context *
  3112. mg_get_context(const struct mg_connection *conn)
  3113. {
  3114. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3115. }
  3116. void *
  3117. mg_get_user_data(const struct mg_context *ctx)
  3118. {
  3119. return (ctx == NULL) ? NULL : ctx->user_data;
  3120. }
  3121. void *
  3122. mg_get_user_context_data(const struct mg_connection *conn)
  3123. {
  3124. return mg_get_user_data(mg_get_context(conn));
  3125. }
  3126. void *
  3127. mg_get_thread_pointer(const struct mg_connection *conn)
  3128. {
  3129. /* both methods should return the same pointer */
  3130. if (conn) {
  3131. /* quick access, in case conn is known */
  3132. return conn->tls_user_ptr;
  3133. } else {
  3134. /* otherwise get pointer from thread local storage (TLS) */
  3135. struct mg_workerTLS *tls =
  3136. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3137. return tls->user_ptr;
  3138. }
  3139. }
  3140. void
  3141. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3142. {
  3143. if (conn != NULL) {
  3144. conn->request_info.conn_data = data;
  3145. }
  3146. }
  3147. void *
  3148. mg_get_user_connection_data(const struct mg_connection *conn)
  3149. {
  3150. if (conn != NULL) {
  3151. return conn->request_info.conn_data;
  3152. }
  3153. return NULL;
  3154. }
  3155. #if defined(MG_LEGACY_INTERFACE)
  3156. /* Deprecated: Use mg_get_server_ports instead. */
  3157. size_t
  3158. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3159. {
  3160. size_t i;
  3161. if (!ctx) {
  3162. return 0;
  3163. }
  3164. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3165. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3166. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  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. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3190. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3191. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3192. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3193. /* IPv4 */
  3194. ports[cnt].protocol = 1;
  3195. cnt++;
  3196. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3197. /* IPv6 */
  3198. ports[cnt].protocol = 3;
  3199. cnt++;
  3200. }
  3201. }
  3202. return cnt;
  3203. }
  3204. static void
  3205. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3206. {
  3207. buf[0] = '\0';
  3208. if (!usa) {
  3209. return;
  3210. }
  3211. if (usa->sa.sa_family == AF_INET) {
  3212. getnameinfo(&usa->sa,
  3213. sizeof(usa->sin),
  3214. buf,
  3215. (unsigned)len,
  3216. NULL,
  3217. 0,
  3218. NI_NUMERICHOST);
  3219. }
  3220. #if defined(USE_IPV6)
  3221. else if (usa->sa.sa_family == AF_INET6) {
  3222. getnameinfo(&usa->sa,
  3223. sizeof(usa->sin6),
  3224. buf,
  3225. (unsigned)len,
  3226. NULL,
  3227. 0,
  3228. NI_NUMERICHOST);
  3229. }
  3230. #endif
  3231. }
  3232. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3233. * included in all responses other than 100, 101, 5xx. */
  3234. static void
  3235. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3236. {
  3237. #if !defined(REENTRANT_TIME)
  3238. struct tm *tm;
  3239. tm = ((t != NULL) ? gmtime(t) : NULL);
  3240. if (tm != NULL) {
  3241. #else
  3242. struct tm _tm;
  3243. struct tm *tm = &_tm;
  3244. if (t != NULL) {
  3245. gmtime_r(t, tm);
  3246. #endif
  3247. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3248. } else {
  3249. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3250. buf[buf_len - 1] = '\0';
  3251. }
  3252. }
  3253. /* difftime for struct timespec. Return value is in seconds. */
  3254. static double
  3255. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3256. {
  3257. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3258. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3259. }
  3260. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3261. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3262. const char *func,
  3263. unsigned line,
  3264. const char *fmt,
  3265. va_list ap);
  3266. #include "external_mg_cry_internal_impl.inl"
  3267. #elif !defined(NO_FILESYSTEMS)
  3268. /* Print error message to the opened error log stream. */
  3269. static void
  3270. mg_cry_internal_impl(const struct mg_connection *conn,
  3271. const char *func,
  3272. unsigned line,
  3273. const char *fmt,
  3274. va_list ap)
  3275. {
  3276. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3277. struct mg_file fi;
  3278. time_t timestamp;
  3279. /* Unused, in the RELEASE build */
  3280. (void)func;
  3281. (void)line;
  3282. #if defined(GCC_DIAGNOSTIC)
  3283. #pragma GCC diagnostic push
  3284. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3285. #endif
  3286. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3287. #if defined(GCC_DIAGNOSTIC)
  3288. #pragma GCC diagnostic pop
  3289. #endif
  3290. buf[sizeof(buf) - 1] = 0;
  3291. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3292. if (!conn) {
  3293. puts(buf);
  3294. return;
  3295. }
  3296. /* Do not lock when getting the callback value, here and below.
  3297. * I suppose this is fine, since function cannot disappear in the
  3298. * same way string option can. */
  3299. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3300. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3301. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3302. if (mg_fopen(conn,
  3303. conn->dom_ctx->config[ERROR_LOG_FILE],
  3304. MG_FOPEN_MODE_APPEND,
  3305. &fi)
  3306. == 0) {
  3307. fi.access.fp = NULL;
  3308. }
  3309. } else {
  3310. fi.access.fp = NULL;
  3311. }
  3312. if (fi.access.fp != NULL) {
  3313. flockfile(fi.access.fp);
  3314. timestamp = time(NULL);
  3315. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3316. fprintf(fi.access.fp,
  3317. "[%010lu] [error] [client %s] ",
  3318. (unsigned long)timestamp,
  3319. src_addr);
  3320. if (conn->request_info.request_method != NULL) {
  3321. fprintf(fi.access.fp,
  3322. "%s %s: ",
  3323. conn->request_info.request_method,
  3324. conn->request_info.request_uri
  3325. ? conn->request_info.request_uri
  3326. : "");
  3327. }
  3328. fprintf(fi.access.fp, "%s", buf);
  3329. fputc('\n', fi.access.fp);
  3330. fflush(fi.access.fp);
  3331. funlockfile(fi.access.fp);
  3332. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3333. * mg_cry here anyway ;-) */
  3334. }
  3335. }
  3336. }
  3337. #else
  3338. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3339. #endif /* Externally provided function */
  3340. /* Construct fake connection structure. Used for logging, if connection
  3341. * is not applicable at the moment of logging. */
  3342. static struct mg_connection *
  3343. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3344. {
  3345. static const struct mg_connection conn_zero = {0};
  3346. *fc = conn_zero;
  3347. fc->phys_ctx = ctx;
  3348. fc->dom_ctx = &(ctx->dd);
  3349. return fc;
  3350. }
  3351. static void
  3352. mg_cry_internal_wrap(const struct mg_connection *conn,
  3353. struct mg_context *ctx,
  3354. const char *func,
  3355. unsigned line,
  3356. const char *fmt,
  3357. ...)
  3358. {
  3359. va_list ap;
  3360. va_start(ap, fmt);
  3361. if (!conn && ctx) {
  3362. struct mg_connection fc;
  3363. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3364. } else {
  3365. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3366. }
  3367. va_end(ap);
  3368. }
  3369. void
  3370. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3371. {
  3372. va_list ap;
  3373. va_start(ap, fmt);
  3374. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3375. va_end(ap);
  3376. }
  3377. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3378. const char *
  3379. mg_version(void)
  3380. {
  3381. return CIVETWEB_VERSION;
  3382. }
  3383. const struct mg_request_info *
  3384. mg_get_request_info(const struct mg_connection *conn)
  3385. {
  3386. if (!conn) {
  3387. return NULL;
  3388. }
  3389. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3390. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3391. char txt[16];
  3392. struct mg_workerTLS *tls =
  3393. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3394. sprintf(txt, "%03i", conn->response_info.status_code);
  3395. if (strlen(txt) == 3) {
  3396. memcpy(tls->txtbuf, txt, 4);
  3397. } else {
  3398. strcpy(tls->txtbuf, "ERR");
  3399. }
  3400. ((struct mg_connection *)conn)->request_info.local_uri =
  3401. ((struct mg_connection *)conn)->request_info.request_uri =
  3402. tls->txtbuf; /* use thread safe buffer */
  3403. ((struct mg_connection *)conn)->request_info.num_headers =
  3404. conn->response_info.num_headers;
  3405. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3406. conn->response_info.http_headers,
  3407. sizeof(conn->response_info.http_headers));
  3408. } else
  3409. #endif
  3410. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3411. return NULL;
  3412. }
  3413. return &conn->request_info;
  3414. }
  3415. const struct mg_response_info *
  3416. mg_get_response_info(const struct mg_connection *conn)
  3417. {
  3418. if (!conn) {
  3419. return NULL;
  3420. }
  3421. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3422. return NULL;
  3423. }
  3424. return &conn->response_info;
  3425. }
  3426. static const char *
  3427. get_proto_name(const struct mg_connection *conn)
  3428. {
  3429. #if defined(__clang__)
  3430. #pragma clang diagnostic push
  3431. #pragma clang diagnostic ignored "-Wunreachable-code"
  3432. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3433. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3434. * unreachable, but splitting into four different #ifdef clauses here is more
  3435. * complicated.
  3436. */
  3437. #endif
  3438. const struct mg_request_info *ri = &conn->request_info;
  3439. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3440. ? (ri->is_ssl ? "wss" : "ws")
  3441. : (ri->is_ssl ? "https" : "http"));
  3442. return proto;
  3443. #if defined(__clang__)
  3444. #pragma clang diagnostic pop
  3445. #endif
  3446. }
  3447. int
  3448. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3449. {
  3450. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3451. return -1;
  3452. } else {
  3453. int truncated = 0;
  3454. const struct mg_request_info *ri = &conn->request_info;
  3455. const char *proto = get_proto_name(conn);
  3456. if (ri->local_uri == NULL) {
  3457. return -1;
  3458. }
  3459. if ((ri->request_uri != NULL)
  3460. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3461. /* The request uri is different from the local uri.
  3462. * This is usually if an absolute URI, including server
  3463. * name has been provided. */
  3464. mg_snprintf(conn,
  3465. &truncated,
  3466. buf,
  3467. buflen,
  3468. "%s://%s",
  3469. proto,
  3470. ri->request_uri);
  3471. if (truncated) {
  3472. return -1;
  3473. }
  3474. return 0;
  3475. } else {
  3476. /* The common case is a relative URI, so we have to
  3477. * construct an absolute URI from server name and port */
  3478. #if defined(USE_IPV6)
  3479. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3480. #endif
  3481. int port = htons(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  3482. int def_port = ri->is_ssl ? 443 : 80;
  3483. int auth_domain_check_enabled =
  3484. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3485. && (!mg_strcasecmp(
  3486. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3487. const char *server_domain =
  3488. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3489. char portstr[16];
  3490. char server_ip[48];
  3491. if (port != def_port) {
  3492. sprintf(portstr, ":%u", (unsigned)port);
  3493. } else {
  3494. portstr[0] = 0;
  3495. }
  3496. if (!auth_domain_check_enabled || !server_domain) {
  3497. sockaddr_to_string(server_ip,
  3498. sizeof(server_ip),
  3499. &conn->client.lsa);
  3500. server_domain = server_ip;
  3501. }
  3502. mg_snprintf(conn,
  3503. &truncated,
  3504. buf,
  3505. buflen,
  3506. #if defined(USE_IPV6)
  3507. "%s://%s%s%s%s%s",
  3508. proto,
  3509. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3510. server_domain,
  3511. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3512. #else
  3513. "%s://%s%s%s",
  3514. proto,
  3515. server_domain,
  3516. #endif
  3517. portstr,
  3518. ri->local_uri);
  3519. if (truncated) {
  3520. return -1;
  3521. }
  3522. return 0;
  3523. }
  3524. }
  3525. }
  3526. /* Skip the characters until one of the delimiters characters found.
  3527. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3528. * Advance pointer to buffer to the next word. Return found 0-terminated
  3529. * word.
  3530. * Delimiters can be quoted with quotechar. */
  3531. static char *
  3532. skip_quoted(char **buf,
  3533. const char *delimiters,
  3534. const char *whitespace,
  3535. char quotechar)
  3536. {
  3537. char *p, *begin_word, *end_word, *end_whitespace;
  3538. begin_word = *buf;
  3539. end_word = begin_word + strcspn(begin_word, delimiters);
  3540. /* Check for quotechar */
  3541. if (end_word > begin_word) {
  3542. p = end_word - 1;
  3543. while (*p == quotechar) {
  3544. /* While the delimiter is quoted, look for the next delimiter.
  3545. */
  3546. /* This happens, e.g., in calls from parse_auth_header,
  3547. * if the user name contains a " character. */
  3548. /* If there is anything beyond end_word, copy it. */
  3549. if (*end_word != '\0') {
  3550. size_t end_off = strcspn(end_word + 1, delimiters);
  3551. memmove(p, end_word, end_off + 1);
  3552. p += end_off; /* p must correspond to end_word - 1 */
  3553. end_word += end_off + 1;
  3554. } else {
  3555. *p = '\0';
  3556. break;
  3557. }
  3558. }
  3559. for (p++; p < end_word; p++) {
  3560. *p = '\0';
  3561. }
  3562. }
  3563. if (*end_word == '\0') {
  3564. *buf = end_word;
  3565. } else {
  3566. #if defined(GCC_DIAGNOSTIC)
  3567. /* Disable spurious conversion warning for GCC */
  3568. #pragma GCC diagnostic push
  3569. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3570. #endif /* defined(GCC_DIAGNOSTIC) */
  3571. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3572. #if defined(GCC_DIAGNOSTIC)
  3573. #pragma GCC diagnostic pop
  3574. #endif /* defined(GCC_DIAGNOSTIC) */
  3575. for (p = end_word; p < end_whitespace; p++) {
  3576. *p = '\0';
  3577. }
  3578. *buf = end_whitespace;
  3579. }
  3580. return begin_word;
  3581. }
  3582. /* Return HTTP header value, or NULL if not found. */
  3583. static const char *
  3584. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3585. {
  3586. int i;
  3587. for (i = 0; i < num_hdr; i++) {
  3588. if (!mg_strcasecmp(name, hdr[i].name)) {
  3589. return hdr[i].value;
  3590. }
  3591. }
  3592. return NULL;
  3593. }
  3594. #if defined(USE_WEBSOCKET)
  3595. /* Retrieve requested HTTP header multiple values, and return the number of
  3596. * found occurrences */
  3597. static int
  3598. get_req_headers(const struct mg_request_info *ri,
  3599. const char *name,
  3600. const char **output,
  3601. int output_max_size)
  3602. {
  3603. int i;
  3604. int cnt = 0;
  3605. if (ri) {
  3606. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3607. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3608. output[cnt++] = ri->http_headers[i].value;
  3609. }
  3610. }
  3611. }
  3612. return cnt;
  3613. }
  3614. #endif
  3615. const char *
  3616. mg_get_header(const struct mg_connection *conn, const char *name)
  3617. {
  3618. if (!conn) {
  3619. return NULL;
  3620. }
  3621. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3622. return get_header(conn->request_info.http_headers,
  3623. conn->request_info.num_headers,
  3624. name);
  3625. }
  3626. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3627. return get_header(conn->response_info.http_headers,
  3628. conn->response_info.num_headers,
  3629. name);
  3630. }
  3631. return NULL;
  3632. }
  3633. static const char *
  3634. get_http_version(const struct mg_connection *conn)
  3635. {
  3636. if (!conn) {
  3637. return NULL;
  3638. }
  3639. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3640. return conn->request_info.http_version;
  3641. }
  3642. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3643. return conn->response_info.http_version;
  3644. }
  3645. return NULL;
  3646. }
  3647. /* A helper function for traversing a comma separated list of values.
  3648. * It returns a list pointer shifted to the next value, or NULL if the end
  3649. * of the list found.
  3650. * Value is stored in val vector. If value has form "x=y", then eq_val
  3651. * vector is initialized to point to the "y" part, and val vector length
  3652. * is adjusted to point only to "x". */
  3653. static const char *
  3654. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3655. {
  3656. int end;
  3657. reparse:
  3658. if (val == NULL || list == NULL || *list == '\0') {
  3659. /* End of the list */
  3660. return NULL;
  3661. }
  3662. /* Skip over leading LWS */
  3663. while (*list == ' ' || *list == '\t')
  3664. list++;
  3665. val->ptr = list;
  3666. if ((list = strchr(val->ptr, ',')) != NULL) {
  3667. /* Comma found. Store length and shift the list ptr */
  3668. val->len = ((size_t)(list - val->ptr));
  3669. list++;
  3670. } else {
  3671. /* This value is the last one */
  3672. list = val->ptr + strlen(val->ptr);
  3673. val->len = ((size_t)(list - val->ptr));
  3674. }
  3675. /* Adjust length for trailing LWS */
  3676. end = (int)val->len - 1;
  3677. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3678. end--;
  3679. val->len = (size_t)(end) + (size_t)(1);
  3680. if (val->len == 0) {
  3681. /* Ignore any empty entries. */
  3682. goto reparse;
  3683. }
  3684. if (eq_val != NULL) {
  3685. /* Value has form "x=y", adjust pointers and lengths
  3686. * so that val points to "x", and eq_val points to "y". */
  3687. eq_val->len = 0;
  3688. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3689. if (eq_val->ptr != NULL) {
  3690. eq_val->ptr++; /* Skip over '=' character */
  3691. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3692. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3693. }
  3694. }
  3695. return list;
  3696. }
  3697. /* A helper function for checking if a comma separated list of values
  3698. * contains
  3699. * the given option (case insensitvely).
  3700. * 'header' can be NULL, in which case false is returned. */
  3701. static int
  3702. header_has_option(const char *header, const char *option)
  3703. {
  3704. struct vec opt_vec;
  3705. struct vec eq_vec;
  3706. DEBUG_ASSERT(option != NULL);
  3707. DEBUG_ASSERT(option[0] != '\0');
  3708. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3709. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3710. return 1;
  3711. }
  3712. return 0;
  3713. }
  3714. /* Perform case-insensitive match of string against pattern */
  3715. static ptrdiff_t
  3716. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3717. {
  3718. const char *or_str;
  3719. ptrdiff_t i, j, len, res;
  3720. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3721. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3722. return (res > 0) ? res
  3723. : match_prefix(or_str + 1,
  3724. (size_t)((pattern + pattern_len)
  3725. - (or_str + 1)),
  3726. str);
  3727. }
  3728. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3729. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3730. continue;
  3731. } else if (pattern[i] == '$') {
  3732. return (str[j] == '\0') ? j : -1;
  3733. } else if (pattern[i] == '*') {
  3734. i++;
  3735. if (pattern[i] == '*') {
  3736. i++;
  3737. len = (ptrdiff_t)strlen(str + j);
  3738. } else {
  3739. len = (ptrdiff_t)strcspn(str + j, "/");
  3740. }
  3741. if (i == (ptrdiff_t)pattern_len) {
  3742. return j + len;
  3743. }
  3744. do {
  3745. res = match_prefix(pattern + i,
  3746. (pattern_len - (size_t)i),
  3747. str + j + len);
  3748. } while (res == -1 && len-- > 0);
  3749. return (res == -1) ? -1 : j + res + len;
  3750. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3751. return -1;
  3752. }
  3753. }
  3754. return (ptrdiff_t)j;
  3755. }
  3756. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3757. * This function must tolerate situations when connection info is not
  3758. * set up, for example if request parsing failed. */
  3759. static int
  3760. should_keep_alive(const struct mg_connection *conn)
  3761. {
  3762. const char *http_version;
  3763. const char *header;
  3764. /* First satisfy needs of the server */
  3765. if ((conn == NULL) || conn->must_close) {
  3766. /* Close, if civetweb framework needs to close */
  3767. return 0;
  3768. }
  3769. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3770. /* Close, if keep alive is not enabled */
  3771. return 0;
  3772. }
  3773. /* Check explicit wish of the client */
  3774. header = mg_get_header(conn, "Connection");
  3775. if (header) {
  3776. /* If there is a connection header from the client, obey */
  3777. if (header_has_option(header, "keep-alive")) {
  3778. return 1;
  3779. }
  3780. return 0;
  3781. }
  3782. /* Use default of the standard */
  3783. http_version = get_http_version(conn);
  3784. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3785. /* HTTP 1.1 default is keep alive */
  3786. return 1;
  3787. }
  3788. /* HTTP 1.0 (and earlier) default is to close the connection */
  3789. return 0;
  3790. }
  3791. static int
  3792. should_decode_url(const struct mg_connection *conn)
  3793. {
  3794. if (!conn || !conn->dom_ctx) {
  3795. return 0;
  3796. }
  3797. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3798. }
  3799. static const char *
  3800. suggest_connection_header(const struct mg_connection *conn)
  3801. {
  3802. return should_keep_alive(conn) ? "keep-alive" : "close";
  3803. }
  3804. static int
  3805. send_no_cache_header(struct mg_connection *conn)
  3806. {
  3807. /* Send all current and obsolete cache opt-out directives. */
  3808. return mg_printf(conn,
  3809. "Cache-Control: no-cache, no-store, "
  3810. "must-revalidate, private, max-age=0\r\n"
  3811. "Pragma: no-cache\r\n"
  3812. "Expires: 0\r\n");
  3813. }
  3814. static int
  3815. send_static_cache_header(struct mg_connection *conn)
  3816. {
  3817. #if !defined(NO_CACHING)
  3818. int max_age;
  3819. const char *cache_control =
  3820. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3821. if (cache_control != NULL) {
  3822. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3823. }
  3824. /* Read the server config to check how long a file may be cached.
  3825. * The configuration is in seconds. */
  3826. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3827. if (max_age <= 0) {
  3828. /* 0 means "do not cache". All values <0 are reserved
  3829. * and may be used differently in the future. */
  3830. /* If a file should not be cached, do not only send
  3831. * max-age=0, but also pragmas and Expires headers. */
  3832. return send_no_cache_header(conn);
  3833. }
  3834. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3835. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3836. /* See also https://www.mnot.net/cache_docs/ */
  3837. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3838. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3839. * leap
  3840. * year to 31622400 seconds. For the moment, we just send whatever has
  3841. * been configured, still the behavior for >1 year should be considered
  3842. * as undefined. */
  3843. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3844. #else /* NO_CACHING */
  3845. return send_no_cache_header(conn);
  3846. #endif /* !NO_CACHING */
  3847. }
  3848. static int
  3849. send_additional_header(struct mg_connection *conn)
  3850. {
  3851. int i = 0;
  3852. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3853. #if !defined(NO_SSL)
  3854. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3855. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3856. if (max_age >= 0) {
  3857. i += mg_printf(conn,
  3858. "Strict-Transport-Security: max-age=%u\r\n",
  3859. (unsigned)max_age);
  3860. }
  3861. }
  3862. #endif
  3863. if (header && header[0]) {
  3864. i += mg_printf(conn, "%s\r\n", header);
  3865. }
  3866. return i;
  3867. }
  3868. #if !defined(NO_FILESYSTEMS)
  3869. static void handle_file_based_request(struct mg_connection *conn,
  3870. const char *path,
  3871. struct mg_file *filep);
  3872. #endif /* NO_FILESYSTEMS */
  3873. const char *
  3874. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3875. {
  3876. /* See IANA HTTP status code assignment:
  3877. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3878. */
  3879. switch (response_code) {
  3880. /* RFC2616 Section 10.1 - Informational 1xx */
  3881. case 100:
  3882. return "Continue"; /* RFC2616 Section 10.1.1 */
  3883. case 101:
  3884. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3885. case 102:
  3886. return "Processing"; /* RFC2518 Section 10.1 */
  3887. /* RFC2616 Section 10.2 - Successful 2xx */
  3888. case 200:
  3889. return "OK"; /* RFC2616 Section 10.2.1 */
  3890. case 201:
  3891. return "Created"; /* RFC2616 Section 10.2.2 */
  3892. case 202:
  3893. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3894. case 203:
  3895. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3896. case 204:
  3897. return "No Content"; /* RFC2616 Section 10.2.5 */
  3898. case 205:
  3899. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3900. case 206:
  3901. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3902. case 207:
  3903. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3904. */
  3905. case 208:
  3906. return "Already Reported"; /* RFC5842 Section 7.1 */
  3907. case 226:
  3908. return "IM used"; /* RFC3229 Section 10.4.1 */
  3909. /* RFC2616 Section 10.3 - Redirection 3xx */
  3910. case 300:
  3911. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3912. case 301:
  3913. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3914. case 302:
  3915. return "Found"; /* RFC2616 Section 10.3.3 */
  3916. case 303:
  3917. return "See Other"; /* RFC2616 Section 10.3.4 */
  3918. case 304:
  3919. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3920. case 305:
  3921. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3922. case 307:
  3923. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3924. case 308:
  3925. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3926. /* RFC2616 Section 10.4 - Client Error 4xx */
  3927. case 400:
  3928. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3929. case 401:
  3930. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3931. case 402:
  3932. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3933. case 403:
  3934. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3935. case 404:
  3936. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3937. case 405:
  3938. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3939. case 406:
  3940. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3941. case 407:
  3942. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3943. case 408:
  3944. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3945. case 409:
  3946. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3947. case 410:
  3948. return "Gone"; /* RFC2616 Section 10.4.11 */
  3949. case 411:
  3950. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3951. case 412:
  3952. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3953. case 413:
  3954. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3955. case 414:
  3956. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3957. case 415:
  3958. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3959. case 416:
  3960. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3961. */
  3962. case 417:
  3963. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3964. case 421:
  3965. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3966. case 422:
  3967. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3968. * Section 11.2 */
  3969. case 423:
  3970. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3971. case 424:
  3972. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3973. * Section 11.4 */
  3974. case 426:
  3975. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3976. case 428:
  3977. return "Precondition Required"; /* RFC 6585, Section 3 */
  3978. case 429:
  3979. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3980. case 431:
  3981. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3982. case 451:
  3983. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3984. * Section 3 */
  3985. /* RFC2616 Section 10.5 - Server Error 5xx */
  3986. case 500:
  3987. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3988. case 501:
  3989. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3990. case 502:
  3991. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3992. case 503:
  3993. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3994. case 504:
  3995. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3996. case 505:
  3997. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3998. case 506:
  3999. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4000. case 507:
  4001. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4002. * Section 11.5 */
  4003. case 508:
  4004. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4005. case 510:
  4006. return "Not Extended"; /* RFC 2774, Section 7 */
  4007. case 511:
  4008. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4009. /* Other status codes, not shown in the IANA HTTP status code
  4010. * assignment.
  4011. * E.g., "de facto" standards due to common use, ... */
  4012. case 418:
  4013. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4014. case 419:
  4015. return "Authentication Timeout"; /* common use */
  4016. case 420:
  4017. return "Enhance Your Calm"; /* common use */
  4018. case 440:
  4019. return "Login Timeout"; /* common use */
  4020. case 509:
  4021. return "Bandwidth Limit Exceeded"; /* common use */
  4022. default:
  4023. /* This error code is unknown. This should not happen. */
  4024. if (conn) {
  4025. mg_cry_internal(conn,
  4026. "Unknown HTTP response code: %u",
  4027. response_code);
  4028. }
  4029. /* Return at least a category according to RFC 2616 Section 10. */
  4030. if (response_code >= 100 && response_code < 200) {
  4031. /* Unknown informational status code */
  4032. return "Information";
  4033. }
  4034. if (response_code >= 200 && response_code < 300) {
  4035. /* Unknown success code */
  4036. return "Success";
  4037. }
  4038. if (response_code >= 300 && response_code < 400) {
  4039. /* Unknown redirection code */
  4040. return "Redirection";
  4041. }
  4042. if (response_code >= 400 && response_code < 500) {
  4043. /* Unknown request error code */
  4044. return "Client Error";
  4045. }
  4046. if (response_code >= 500 && response_code < 600) {
  4047. /* Unknown server error code */
  4048. return "Server Error";
  4049. }
  4050. /* Response code not even within reasonable range */
  4051. return "";
  4052. }
  4053. }
  4054. static int
  4055. mg_send_http_error_impl(struct mg_connection *conn,
  4056. int status,
  4057. const char *fmt,
  4058. va_list args)
  4059. {
  4060. char errmsg_buf[MG_BUF_LEN];
  4061. va_list ap;
  4062. int has_body;
  4063. char date[64];
  4064. time_t curtime = time(NULL);
  4065. #if !defined(NO_FILESYSTEMS)
  4066. char path_buf[PATH_MAX];
  4067. int len, i, page_handler_found, scope, truncated;
  4068. const char *error_handler = NULL;
  4069. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4070. const char *error_page_file_ext, *tstr;
  4071. #endif /* NO_FILESYSTEMS */
  4072. int handled_by_callback = 0;
  4073. const char *status_text = mg_get_response_code_text(conn, status);
  4074. if ((conn == NULL) || (fmt == NULL)) {
  4075. return -2;
  4076. }
  4077. /* Set status (for log) */
  4078. conn->status_code = status;
  4079. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4080. has_body = ((status > 199) && (status != 204) && (status != 304));
  4081. /* Prepare message in buf, if required */
  4082. if (has_body
  4083. || (!conn->in_error_handler
  4084. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4085. /* Store error message in errmsg_buf */
  4086. va_copy(ap, args);
  4087. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4088. va_end(ap);
  4089. /* In a debug build, print all html errors */
  4090. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4091. }
  4092. /* If there is a http_error callback, call it.
  4093. * But don't do it recursively, if callback calls mg_send_http_error again.
  4094. */
  4095. if (!conn->in_error_handler
  4096. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4097. /* Mark in_error_handler to avoid recursion and call user callback. */
  4098. conn->in_error_handler = 1;
  4099. handled_by_callback =
  4100. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4101. == 0);
  4102. conn->in_error_handler = 0;
  4103. }
  4104. if (!handled_by_callback) {
  4105. /* Check for recursion */
  4106. if (conn->in_error_handler) {
  4107. DEBUG_TRACE(
  4108. "Recursion when handling error %u - fall back to default",
  4109. status);
  4110. #if !defined(NO_FILESYSTEMS)
  4111. } else {
  4112. /* Send user defined error pages, if defined */
  4113. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4114. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4115. page_handler_found = 0;
  4116. if (error_handler != NULL) {
  4117. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4118. switch (scope) {
  4119. case 1: /* Handler for specific error, e.g. 404 error */
  4120. mg_snprintf(conn,
  4121. &truncated,
  4122. path_buf,
  4123. sizeof(path_buf) - 32,
  4124. "%serror%03u.",
  4125. error_handler,
  4126. status);
  4127. break;
  4128. case 2: /* Handler for error group, e.g., 5xx error
  4129. * handler
  4130. * for all server errors (500-599) */
  4131. mg_snprintf(conn,
  4132. &truncated,
  4133. path_buf,
  4134. sizeof(path_buf) - 32,
  4135. "%serror%01uxx.",
  4136. error_handler,
  4137. status / 100);
  4138. break;
  4139. default: /* Handler for all errors */
  4140. mg_snprintf(conn,
  4141. &truncated,
  4142. path_buf,
  4143. sizeof(path_buf) - 32,
  4144. "%serror.",
  4145. error_handler);
  4146. break;
  4147. }
  4148. /* String truncation in buf may only occur if
  4149. * error_handler is too long. This string is
  4150. * from the config, not from a client. */
  4151. (void)truncated;
  4152. /* The following code is redundant, but it should avoid
  4153. * false positives in static source code analyzers and
  4154. * vulnerability scanners.
  4155. */
  4156. path_buf[sizeof(path_buf) - 32] = 0;
  4157. len = (int)strlen(path_buf);
  4158. if (len > (int)sizeof(path_buf) - 32) {
  4159. len = (int)sizeof(path_buf) - 32;
  4160. }
  4161. /* Start with the file extenstion from the configuration. */
  4162. tstr = strchr(error_page_file_ext, '.');
  4163. while (tstr) {
  4164. for (i = 1;
  4165. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4166. i++) {
  4167. /* buffer overrun is not possible here, since
  4168. * (i < 32) && (len < sizeof(path_buf) - 32)
  4169. * ==> (i + len) < sizeof(path_buf) */
  4170. path_buf[len + i - 1] = tstr[i];
  4171. }
  4172. /* buffer overrun is not possible here, since
  4173. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4174. * ==> (i + len) <= sizeof(path_buf) */
  4175. path_buf[len + i - 1] = 0;
  4176. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4177. DEBUG_TRACE("Check error page %s - found",
  4178. path_buf);
  4179. page_handler_found = 1;
  4180. break;
  4181. }
  4182. DEBUG_TRACE("Check error page %s - not found",
  4183. path_buf);
  4184. /* Continue with the next file extenstion from the
  4185. * configuration (if there is a next one). */
  4186. tstr = strchr(tstr + i, '.');
  4187. }
  4188. }
  4189. }
  4190. if (page_handler_found) {
  4191. conn->in_error_handler = 1;
  4192. handle_file_based_request(conn, path_buf, &error_page_file);
  4193. conn->in_error_handler = 0;
  4194. return 0;
  4195. }
  4196. #endif /* NO_FILESYSTEMS */
  4197. }
  4198. /* No custom error page. Send default error page. */
  4199. gmt_time_string(date, sizeof(date), &curtime);
  4200. conn->must_close = 1;
  4201. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4202. send_no_cache_header(conn);
  4203. send_additional_header(conn);
  4204. if (has_body) {
  4205. mg_printf(conn,
  4206. "%s",
  4207. "Content-Type: text/plain; charset=utf-8\r\n");
  4208. }
  4209. mg_printf(conn,
  4210. "Date: %s\r\n"
  4211. "Connection: close\r\n\r\n",
  4212. date);
  4213. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4214. if (has_body) {
  4215. /* For other errors, send a generic error message. */
  4216. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4217. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4218. } else {
  4219. /* No body allowed. Close the connection. */
  4220. DEBUG_TRACE("Error %i", status);
  4221. }
  4222. }
  4223. return 0;
  4224. }
  4225. int
  4226. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4227. {
  4228. va_list ap;
  4229. int ret;
  4230. va_start(ap, fmt);
  4231. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4232. va_end(ap);
  4233. return ret;
  4234. }
  4235. int
  4236. mg_send_http_ok(struct mg_connection *conn,
  4237. const char *mime_type,
  4238. long long content_length)
  4239. {
  4240. char date[64];
  4241. time_t curtime = time(NULL);
  4242. if ((mime_type == NULL) || (*mime_type == 0)) {
  4243. /* No content type defined: default to text/html */
  4244. mime_type = "text/html";
  4245. }
  4246. gmt_time_string(date, sizeof(date), &curtime);
  4247. mg_printf(conn,
  4248. "HTTP/1.1 200 OK\r\n"
  4249. "Content-Type: %s\r\n"
  4250. "Date: %s\r\n"
  4251. "Connection: %s\r\n",
  4252. mime_type,
  4253. date,
  4254. suggest_connection_header(conn));
  4255. send_no_cache_header(conn);
  4256. send_additional_header(conn);
  4257. if (content_length < 0) {
  4258. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4259. } else {
  4260. mg_printf(conn,
  4261. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4262. (uint64_t)content_length);
  4263. }
  4264. return 0;
  4265. }
  4266. int
  4267. mg_send_http_redirect(struct mg_connection *conn,
  4268. const char *target_url,
  4269. int redirect_code)
  4270. {
  4271. /* Send a 30x redirect response.
  4272. *
  4273. * Redirect types (status codes):
  4274. *
  4275. * Status | Perm/Temp | Method | Version
  4276. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4277. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4278. * 303 | temporary | always use GET | HTTP/1.1
  4279. * 307 | temporary | always keep method | HTTP/1.1
  4280. * 308 | permanent | always keep method | HTTP/1.1
  4281. */
  4282. const char *redirect_text;
  4283. int ret;
  4284. size_t content_len = 0;
  4285. char reply[MG_BUF_LEN];
  4286. /* In case redirect_code=0, use 307. */
  4287. if (redirect_code == 0) {
  4288. redirect_code = 307;
  4289. }
  4290. /* In case redirect_code is none of the above, return error. */
  4291. if ((redirect_code != 301) && (redirect_code != 302)
  4292. && (redirect_code != 303) && (redirect_code != 307)
  4293. && (redirect_code != 308)) {
  4294. /* Parameter error */
  4295. return -2;
  4296. }
  4297. /* Get proper text for response code */
  4298. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4299. /* If target_url is not defined, redirect to "/". */
  4300. if ((target_url == NULL) || (*target_url == 0)) {
  4301. target_url = "/";
  4302. }
  4303. #if defined(MG_SEND_REDIRECT_BODY)
  4304. /* TODO: condition name? */
  4305. /* Prepare a response body with a hyperlink.
  4306. *
  4307. * According to RFC2616 (and RFC1945 before):
  4308. * Unless the request method was HEAD, the entity of the
  4309. * response SHOULD contain a short hypertext note with a hyperlink to
  4310. * the new URI(s).
  4311. *
  4312. * However, this response body is not useful in M2M communication.
  4313. * Probably the original reason in the RFC was, clients not supporting
  4314. * a 30x HTTP redirect could still show the HTML page and let the user
  4315. * press the link. Since current browsers support 30x HTTP, the additional
  4316. * HTML body does not seem to make sense anymore.
  4317. *
  4318. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4319. * but it only notes:
  4320. * The server's response payload usually contains a short
  4321. * hypertext note with a hyperlink to the new URI(s).
  4322. *
  4323. * Deactivated by default. If you need the 30x body, set the define.
  4324. */
  4325. mg_snprintf(
  4326. conn,
  4327. NULL /* ignore truncation */,
  4328. reply,
  4329. sizeof(reply),
  4330. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4331. redirect_text,
  4332. target_url,
  4333. target_url);
  4334. content_len = strlen(reply);
  4335. #else
  4336. reply[0] = 0;
  4337. #endif
  4338. /* Do not send any additional header. For all other options,
  4339. * including caching, there are suitable defaults. */
  4340. ret = mg_printf(conn,
  4341. "HTTP/1.1 %i %s\r\n"
  4342. "Location: %s\r\n"
  4343. "Content-Length: %u\r\n"
  4344. "Connection: %s\r\n\r\n",
  4345. redirect_code,
  4346. redirect_text,
  4347. target_url,
  4348. (unsigned int)content_len,
  4349. suggest_connection_header(conn));
  4350. /* Send response body */
  4351. if (ret > 0) {
  4352. /* ... unless it is a HEAD request */
  4353. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4354. ret = mg_write(conn, reply, content_len);
  4355. }
  4356. }
  4357. return (ret > 0) ? ret : -1;
  4358. }
  4359. #if defined(_WIN32)
  4360. /* Create substitutes for POSIX functions in Win32. */
  4361. #if defined(GCC_DIAGNOSTIC)
  4362. /* Show no warning in case system functions are not used. */
  4363. #pragma GCC diagnostic push
  4364. #pragma GCC diagnostic ignored "-Wunused-function"
  4365. #endif
  4366. static int
  4367. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4368. {
  4369. (void)unused;
  4370. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4371. InitializeCriticalSection(&mutex->sec);
  4372. return 0;
  4373. }
  4374. static int
  4375. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4376. {
  4377. DeleteCriticalSection(&mutex->sec);
  4378. return 0;
  4379. }
  4380. static int
  4381. pthread_mutex_lock(pthread_mutex_t *mutex)
  4382. {
  4383. EnterCriticalSection(&mutex->sec);
  4384. return 0;
  4385. }
  4386. static int
  4387. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4388. {
  4389. LeaveCriticalSection(&mutex->sec);
  4390. return 0;
  4391. }
  4392. FUNCTION_MAY_BE_UNUSED
  4393. static int
  4394. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4395. {
  4396. (void)unused;
  4397. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4398. cv->waiting_thread = NULL;
  4399. return 0;
  4400. }
  4401. FUNCTION_MAY_BE_UNUSED
  4402. static int
  4403. pthread_cond_timedwait(pthread_cond_t *cv,
  4404. pthread_mutex_t *mutex,
  4405. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4406. {
  4407. struct mg_workerTLS **ptls,
  4408. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4409. int ok;
  4410. int64_t nsnow, nswaitabs, nswaitrel;
  4411. DWORD mswaitrel;
  4412. pthread_mutex_lock(&cv->threadIdSec);
  4413. /* Add this thread to cv's waiting list */
  4414. ptls = &cv->waiting_thread;
  4415. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4416. ;
  4417. tls->next_waiting_thread = NULL;
  4418. *ptls = tls;
  4419. pthread_mutex_unlock(&cv->threadIdSec);
  4420. if (abstime) {
  4421. nsnow = mg_get_current_time_ns();
  4422. nswaitabs =
  4423. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4424. nswaitrel = nswaitabs - nsnow;
  4425. if (nswaitrel < 0) {
  4426. nswaitrel = 0;
  4427. }
  4428. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4429. } else {
  4430. mswaitrel = (DWORD)INFINITE;
  4431. }
  4432. pthread_mutex_unlock(mutex);
  4433. ok = (WAIT_OBJECT_0
  4434. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4435. if (!ok) {
  4436. ok = 1;
  4437. pthread_mutex_lock(&cv->threadIdSec);
  4438. ptls = &cv->waiting_thread;
  4439. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4440. if (*ptls == tls) {
  4441. *ptls = tls->next_waiting_thread;
  4442. ok = 0;
  4443. break;
  4444. }
  4445. }
  4446. pthread_mutex_unlock(&cv->threadIdSec);
  4447. if (ok) {
  4448. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4449. (DWORD)INFINITE);
  4450. }
  4451. }
  4452. /* This thread has been removed from cv's waiting list */
  4453. pthread_mutex_lock(mutex);
  4454. return ok ? 0 : -1;
  4455. }
  4456. FUNCTION_MAY_BE_UNUSED
  4457. static int
  4458. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4459. {
  4460. return pthread_cond_timedwait(cv, mutex, NULL);
  4461. }
  4462. FUNCTION_MAY_BE_UNUSED
  4463. static int
  4464. pthread_cond_signal(pthread_cond_t *cv)
  4465. {
  4466. HANDLE wkup = NULL;
  4467. BOOL ok = FALSE;
  4468. pthread_mutex_lock(&cv->threadIdSec);
  4469. if (cv->waiting_thread) {
  4470. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4471. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4472. ok = SetEvent(wkup);
  4473. DEBUG_ASSERT(ok);
  4474. }
  4475. pthread_mutex_unlock(&cv->threadIdSec);
  4476. return ok ? 0 : 1;
  4477. }
  4478. FUNCTION_MAY_BE_UNUSED
  4479. static int
  4480. pthread_cond_broadcast(pthread_cond_t *cv)
  4481. {
  4482. pthread_mutex_lock(&cv->threadIdSec);
  4483. while (cv->waiting_thread) {
  4484. pthread_cond_signal(cv);
  4485. }
  4486. pthread_mutex_unlock(&cv->threadIdSec);
  4487. return 0;
  4488. }
  4489. FUNCTION_MAY_BE_UNUSED
  4490. static int
  4491. pthread_cond_destroy(pthread_cond_t *cv)
  4492. {
  4493. pthread_mutex_lock(&cv->threadIdSec);
  4494. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4495. pthread_mutex_unlock(&cv->threadIdSec);
  4496. pthread_mutex_destroy(&cv->threadIdSec);
  4497. return 0;
  4498. }
  4499. #if defined(ALTERNATIVE_QUEUE)
  4500. FUNCTION_MAY_BE_UNUSED
  4501. static void *
  4502. event_create(void)
  4503. {
  4504. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4505. }
  4506. FUNCTION_MAY_BE_UNUSED
  4507. static int
  4508. event_wait(void *eventhdl)
  4509. {
  4510. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4511. return (res == WAIT_OBJECT_0);
  4512. }
  4513. FUNCTION_MAY_BE_UNUSED
  4514. static int
  4515. event_signal(void *eventhdl)
  4516. {
  4517. return (int)SetEvent((HANDLE)eventhdl);
  4518. }
  4519. FUNCTION_MAY_BE_UNUSED
  4520. static void
  4521. event_destroy(void *eventhdl)
  4522. {
  4523. CloseHandle((HANDLE)eventhdl);
  4524. }
  4525. #endif
  4526. #if defined(GCC_DIAGNOSTIC)
  4527. /* Enable unused function warning again */
  4528. #pragma GCC diagnostic pop
  4529. #endif
  4530. /* For Windows, change all slashes to backslashes in path names. */
  4531. static void
  4532. change_slashes_to_backslashes(char *path)
  4533. {
  4534. int i;
  4535. for (i = 0; path[i] != '\0'; i++) {
  4536. if (path[i] == '/') {
  4537. path[i] = '\\';
  4538. }
  4539. /* remove double backslash (check i > 0 to preserve UNC paths,
  4540. * like \\server\file.txt) */
  4541. if ((i > 0) && (path[i] == '\\')) {
  4542. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4543. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4544. }
  4545. }
  4546. }
  4547. }
  4548. static int
  4549. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4550. {
  4551. int diff;
  4552. do {
  4553. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4554. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4555. s1++;
  4556. s2++;
  4557. } while ((diff == 0) && (s1[-1] != L'\0'));
  4558. return diff;
  4559. }
  4560. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4561. * wbuf and wbuf_len is a target buffer and its length. */
  4562. static void
  4563. path_to_unicode(const struct mg_connection *conn,
  4564. const char *path,
  4565. wchar_t *wbuf,
  4566. size_t wbuf_len)
  4567. {
  4568. char buf[PATH_MAX], buf2[PATH_MAX];
  4569. wchar_t wbuf2[W_PATH_MAX + 1];
  4570. DWORD long_len, err;
  4571. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4572. mg_strlcpy(buf, path, sizeof(buf));
  4573. change_slashes_to_backslashes(buf);
  4574. /* Convert to Unicode and back. If doubly-converted string does not
  4575. * match the original, something is fishy, reject. */
  4576. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4577. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4578. WideCharToMultiByte(
  4579. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4580. if (strcmp(buf, buf2) != 0) {
  4581. wbuf[0] = L'\0';
  4582. }
  4583. /* Windows file systems are not case sensitive, but you can still use
  4584. * uppercase and lowercase letters (on all modern file systems).
  4585. * The server can check if the URI uses the same upper/lowercase
  4586. * letters an the file system, effectively making Windows servers
  4587. * case sensitive (like Linux servers are). It is still not possible
  4588. * to use two files with the same name in different cases on Windows
  4589. * (like /a and /A) - this would be possible in Linux.
  4590. * As a default, Windows is not case sensitive, but the case sensitive
  4591. * file name check can be activated by an additional configuration. */
  4592. if (conn) {
  4593. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4594. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4595. "yes")) {
  4596. /* Use case sensitive compare function */
  4597. fcompare = wcscmp;
  4598. }
  4599. }
  4600. (void)conn; /* conn is currently unused */
  4601. #if !defined(_WIN32_WCE)
  4602. /* Only accept a full file path, not a Windows short (8.3) path. */
  4603. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4604. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4605. if (long_len == 0) {
  4606. err = GetLastError();
  4607. if (err == ERROR_FILE_NOT_FOUND) {
  4608. /* File does not exist. This is not always a problem here. */
  4609. return;
  4610. }
  4611. }
  4612. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4613. /* Short name is used. */
  4614. wbuf[0] = L'\0';
  4615. }
  4616. #else
  4617. (void)long_len;
  4618. (void)wbuf2;
  4619. (void)err;
  4620. if (strchr(path, '~')) {
  4621. wbuf[0] = L'\0';
  4622. }
  4623. #endif
  4624. }
  4625. #if !defined(NO_FILESYSTEMS)
  4626. static int
  4627. mg_stat(const struct mg_connection *conn,
  4628. const char *path,
  4629. struct mg_file_stat *filep)
  4630. {
  4631. wchar_t wbuf[W_PATH_MAX];
  4632. WIN32_FILE_ATTRIBUTE_DATA info;
  4633. time_t creation_time;
  4634. size_t len;
  4635. if (!filep) {
  4636. return 0;
  4637. }
  4638. memset(filep, 0, sizeof(*filep));
  4639. if (conn && is_file_in_memory(conn, path)) {
  4640. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4641. * memset */
  4642. /* Quick fix (for 1.9.x): */
  4643. /* mg_stat must fill all fields, also for files in memory */
  4644. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4645. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4646. filep->size = tmp_file.stat.size;
  4647. filep->location = 2;
  4648. /* TODO: for 1.10: restructure how files in memory are handled */
  4649. /* The "file in memory" feature is a candidate for deletion.
  4650. * Please join the discussion at
  4651. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4652. */
  4653. filep->last_modified = time(NULL); /* TODO */
  4654. /* last_modified = now ... assumes the file may change during
  4655. * runtime,
  4656. * so every mg_fopen call may return different data */
  4657. /* last_modified = conn->phys_ctx.start_time;
  4658. * May be used it the data does not change during runtime. This
  4659. * allows
  4660. * browser caching. Since we do not know, we have to assume the file
  4661. * in memory may change. */
  4662. return 1;
  4663. }
  4664. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4665. /* Windows happily opens files with some garbage at the end of file name.
  4666. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4667. * "a.cgi", despite one would expect an error back. */
  4668. len = strlen(path);
  4669. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4670. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4671. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4672. filep->last_modified =
  4673. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4674. info.ftLastWriteTime.dwHighDateTime);
  4675. /* On Windows, the file creation time can be higher than the
  4676. * modification time, e.g. when a file is copied.
  4677. * Since the Last-Modified timestamp is used for caching
  4678. * it should be based on the most recent timestamp. */
  4679. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4680. info.ftCreationTime.dwHighDateTime);
  4681. if (creation_time > filep->last_modified) {
  4682. filep->last_modified = creation_time;
  4683. }
  4684. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4685. return 1;
  4686. }
  4687. return 0;
  4688. }
  4689. #endif
  4690. static int
  4691. mg_remove(const struct mg_connection *conn, const char *path)
  4692. {
  4693. wchar_t wbuf[W_PATH_MAX];
  4694. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4695. return DeleteFileW(wbuf) ? 0 : -1;
  4696. }
  4697. static int
  4698. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4699. {
  4700. wchar_t wbuf[W_PATH_MAX];
  4701. (void)mode;
  4702. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4703. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4704. }
  4705. /* Create substitutes for POSIX functions in Win32. */
  4706. #if defined(GCC_DIAGNOSTIC)
  4707. /* Show no warning in case system functions are not used. */
  4708. #pragma GCC diagnostic push
  4709. #pragma GCC diagnostic ignored "-Wunused-function"
  4710. #endif
  4711. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4712. FUNCTION_MAY_BE_UNUSED
  4713. static DIR *
  4714. mg_opendir(const struct mg_connection *conn, const char *name)
  4715. {
  4716. DIR *dir = NULL;
  4717. wchar_t wpath[W_PATH_MAX];
  4718. DWORD attrs;
  4719. if (name == NULL) {
  4720. SetLastError(ERROR_BAD_ARGUMENTS);
  4721. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4722. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4723. } else {
  4724. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4725. attrs = GetFileAttributesW(wpath);
  4726. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4727. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4728. (void)wcscat(wpath, L"\\*");
  4729. dir->handle = FindFirstFileW(wpath, &dir->info);
  4730. dir->result.d_name[0] = '\0';
  4731. } else {
  4732. mg_free(dir);
  4733. dir = NULL;
  4734. }
  4735. }
  4736. return dir;
  4737. }
  4738. FUNCTION_MAY_BE_UNUSED
  4739. static int
  4740. mg_closedir(DIR *dir)
  4741. {
  4742. int result = 0;
  4743. if (dir != NULL) {
  4744. if (dir->handle != INVALID_HANDLE_VALUE)
  4745. result = FindClose(dir->handle) ? 0 : -1;
  4746. mg_free(dir);
  4747. } else {
  4748. result = -1;
  4749. SetLastError(ERROR_BAD_ARGUMENTS);
  4750. }
  4751. return result;
  4752. }
  4753. FUNCTION_MAY_BE_UNUSED
  4754. static struct dirent *
  4755. mg_readdir(DIR *dir)
  4756. {
  4757. struct dirent *result = 0;
  4758. if (dir) {
  4759. if (dir->handle != INVALID_HANDLE_VALUE) {
  4760. result = &dir->result;
  4761. (void)WideCharToMultiByte(CP_UTF8,
  4762. 0,
  4763. dir->info.cFileName,
  4764. -1,
  4765. result->d_name,
  4766. sizeof(result->d_name),
  4767. NULL,
  4768. NULL);
  4769. if (!FindNextFileW(dir->handle, &dir->info)) {
  4770. (void)FindClose(dir->handle);
  4771. dir->handle = INVALID_HANDLE_VALUE;
  4772. }
  4773. } else {
  4774. SetLastError(ERROR_FILE_NOT_FOUND);
  4775. }
  4776. } else {
  4777. SetLastError(ERROR_BAD_ARGUMENTS);
  4778. }
  4779. return result;
  4780. }
  4781. #if !defined(HAVE_POLL)
  4782. #undef POLLIN
  4783. #undef POLLPRI
  4784. #undef POLLOUT
  4785. #define POLLIN (1) /* Data ready - read will not block. */
  4786. #define POLLPRI (2) /* Priority data ready. */
  4787. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4788. FUNCTION_MAY_BE_UNUSED
  4789. static int
  4790. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4791. {
  4792. struct timeval tv;
  4793. fd_set rset;
  4794. fd_set wset;
  4795. unsigned int i;
  4796. int result;
  4797. SOCKET maxfd = 0;
  4798. memset(&tv, 0, sizeof(tv));
  4799. tv.tv_sec = milliseconds / 1000;
  4800. tv.tv_usec = (milliseconds % 1000) * 1000;
  4801. FD_ZERO(&rset);
  4802. FD_ZERO(&wset);
  4803. for (i = 0; i < n; i++) {
  4804. if (pfd[i].events & POLLIN) {
  4805. FD_SET(pfd[i].fd, &rset);
  4806. }
  4807. if (pfd[i].events & POLLOUT) {
  4808. FD_SET(pfd[i].fd, &wset);
  4809. }
  4810. pfd[i].revents = 0;
  4811. if (pfd[i].fd > maxfd) {
  4812. maxfd = pfd[i].fd;
  4813. }
  4814. }
  4815. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4816. for (i = 0; i < n; i++) {
  4817. if (FD_ISSET(pfd[i].fd, &rset)) {
  4818. pfd[i].revents |= POLLIN;
  4819. }
  4820. if (FD_ISSET(pfd[i].fd, &wset)) {
  4821. pfd[i].revents |= POLLOUT;
  4822. }
  4823. }
  4824. }
  4825. /* We should subtract the time used in select from remaining
  4826. * "milliseconds", in particular if called from mg_poll with a
  4827. * timeout quantum.
  4828. * Unfortunately, the remaining time is not stored in "tv" in all
  4829. * implementations, so the result in "tv" must be considered undefined.
  4830. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4831. return result;
  4832. }
  4833. #endif /* HAVE_POLL */
  4834. #if defined(GCC_DIAGNOSTIC)
  4835. /* Enable unused function warning again */
  4836. #pragma GCC diagnostic pop
  4837. #endif
  4838. static void
  4839. set_close_on_exec(SOCKET sock,
  4840. const struct mg_connection *conn /* may be null */,
  4841. struct mg_context *ctx /* may be null */)
  4842. {
  4843. (void)conn; /* Unused. */
  4844. (void)ctx;
  4845. #if defined(_WIN32_WCE)
  4846. (void)sock;
  4847. #else
  4848. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4849. #endif
  4850. }
  4851. int
  4852. mg_start_thread(mg_thread_func_t f, void *p)
  4853. {
  4854. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4855. /* Compile-time option to control stack size, e.g.
  4856. * -DUSE_STACK_SIZE=16384
  4857. */
  4858. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4859. == ((uintptr_t)(-1L)))
  4860. ? -1
  4861. : 0);
  4862. #else
  4863. return (
  4864. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4865. ? -1
  4866. : 0);
  4867. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4868. }
  4869. /* Start a thread storing the thread context. */
  4870. static int
  4871. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4872. void *p,
  4873. pthread_t *threadidptr)
  4874. {
  4875. uintptr_t uip;
  4876. HANDLE threadhandle;
  4877. int result = -1;
  4878. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4879. threadhandle = (HANDLE)uip;
  4880. if ((uip != 0) && (threadidptr != NULL)) {
  4881. *threadidptr = threadhandle;
  4882. result = 0;
  4883. }
  4884. return result;
  4885. }
  4886. /* Wait for a thread to finish. */
  4887. static int
  4888. mg_join_thread(pthread_t threadid)
  4889. {
  4890. int result;
  4891. DWORD dwevent;
  4892. result = -1;
  4893. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4894. if (dwevent == WAIT_FAILED) {
  4895. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4896. } else {
  4897. if (dwevent == WAIT_OBJECT_0) {
  4898. CloseHandle(threadid);
  4899. result = 0;
  4900. }
  4901. }
  4902. return result;
  4903. }
  4904. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4905. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4906. /* Create substitutes for POSIX functions in Win32. */
  4907. #if defined(GCC_DIAGNOSTIC)
  4908. /* Show no warning in case system functions are not used. */
  4909. #pragma GCC diagnostic push
  4910. #pragma GCC diagnostic ignored "-Wunused-function"
  4911. #endif
  4912. FUNCTION_MAY_BE_UNUSED
  4913. static HANDLE
  4914. dlopen(const char *dll_name, int flags)
  4915. {
  4916. wchar_t wbuf[W_PATH_MAX];
  4917. (void)flags;
  4918. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4919. return LoadLibraryW(wbuf);
  4920. }
  4921. FUNCTION_MAY_BE_UNUSED
  4922. static int
  4923. dlclose(void *handle)
  4924. {
  4925. int result;
  4926. if (FreeLibrary((HMODULE)handle) != 0) {
  4927. result = 0;
  4928. } else {
  4929. result = -1;
  4930. }
  4931. return result;
  4932. }
  4933. #if defined(GCC_DIAGNOSTIC)
  4934. /* Enable unused function warning again */
  4935. #pragma GCC diagnostic pop
  4936. #endif
  4937. #endif
  4938. #if !defined(NO_CGI)
  4939. #define SIGKILL (0)
  4940. static int
  4941. kill(pid_t pid, int sig_num)
  4942. {
  4943. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4944. (void)CloseHandle((HANDLE)pid);
  4945. return 0;
  4946. }
  4947. #if !defined(WNOHANG)
  4948. #define WNOHANG (1)
  4949. #endif
  4950. static pid_t
  4951. waitpid(pid_t pid, int *status, int flags)
  4952. {
  4953. DWORD timeout = INFINITE;
  4954. DWORD waitres;
  4955. (void)status; /* Currently not used by any client here */
  4956. if ((flags | WNOHANG) == WNOHANG) {
  4957. timeout = 0;
  4958. }
  4959. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4960. if (waitres == WAIT_OBJECT_0) {
  4961. return pid;
  4962. }
  4963. if (waitres == WAIT_TIMEOUT) {
  4964. return 0;
  4965. }
  4966. return (pid_t)-1;
  4967. }
  4968. static void
  4969. trim_trailing_whitespaces(char *s)
  4970. {
  4971. char *e = s + strlen(s);
  4972. while ((e > s) && isspace((unsigned char)e[-1])) {
  4973. *(--e) = '\0';
  4974. }
  4975. }
  4976. static pid_t
  4977. spawn_process(struct mg_connection *conn,
  4978. const char *prog,
  4979. char *envblk,
  4980. char *envp[],
  4981. int fdin[2],
  4982. int fdout[2],
  4983. int fderr[2],
  4984. const char *dir)
  4985. {
  4986. HANDLE me;
  4987. char *p, *interp;
  4988. char *interp_arg = 0;
  4989. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  4990. buf[PATH_MAX];
  4991. int truncated;
  4992. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4993. STARTUPINFOA si;
  4994. PROCESS_INFORMATION pi = {0};
  4995. (void)envp;
  4996. memset(&si, 0, sizeof(si));
  4997. si.cb = sizeof(si);
  4998. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4999. si.wShowWindow = SW_HIDE;
  5000. me = GetCurrentProcess();
  5001. DuplicateHandle(me,
  5002. (HANDLE)_get_osfhandle(fdin[0]),
  5003. me,
  5004. &si.hStdInput,
  5005. 0,
  5006. TRUE,
  5007. DUPLICATE_SAME_ACCESS);
  5008. DuplicateHandle(me,
  5009. (HANDLE)_get_osfhandle(fdout[1]),
  5010. me,
  5011. &si.hStdOutput,
  5012. 0,
  5013. TRUE,
  5014. DUPLICATE_SAME_ACCESS);
  5015. DuplicateHandle(me,
  5016. (HANDLE)_get_osfhandle(fderr[1]),
  5017. me,
  5018. &si.hStdError,
  5019. 0,
  5020. TRUE,
  5021. DUPLICATE_SAME_ACCESS);
  5022. /* Mark handles that should not be inherited. See
  5023. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5024. */
  5025. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5026. HANDLE_FLAG_INHERIT,
  5027. 0);
  5028. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5029. HANDLE_FLAG_INHERIT,
  5030. 0);
  5031. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5032. HANDLE_FLAG_INHERIT,
  5033. 0);
  5034. /* First check, if there is a CGI interpreter configured for all CGI
  5035. * scripts. */
  5036. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5037. if (interp != NULL) {
  5038. /* If there is a configured interpreter, check for additional arguments
  5039. */
  5040. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5041. } else {
  5042. /* Otherwise, the interpreter must be stated in the first line of the
  5043. * CGI script file, after a #! (shebang) mark. */
  5044. buf[0] = buf[1] = '\0';
  5045. /* Get the full script path */
  5046. mg_snprintf(
  5047. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5048. if (truncated) {
  5049. pi.hProcess = (pid_t)-1;
  5050. goto spawn_cleanup;
  5051. }
  5052. /* Open the script file, to read the first line */
  5053. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5054. #if defined(MG_USE_OPEN_FILE)
  5055. p = (char *)file.access.membuf;
  5056. #else
  5057. p = (char *)NULL;
  5058. #endif
  5059. /* Read the first line of the script into the buffer */
  5060. mg_fgets(buf, sizeof(buf), &file, &p);
  5061. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5062. buf[sizeof(buf) - 1] = '\0';
  5063. }
  5064. if ((buf[0] == '#') && (buf[1] == '!')) {
  5065. trim_trailing_whitespaces(buf + 2);
  5066. } else {
  5067. buf[2] = '\0';
  5068. }
  5069. interp = buf + 2;
  5070. }
  5071. if (interp[0] != '\0') {
  5072. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5073. interp = full_interp;
  5074. }
  5075. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5076. if (interp[0] != '\0') {
  5077. /* This is an interpreted script file. We must call the interpreter. */
  5078. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5079. mg_snprintf(conn,
  5080. &truncated,
  5081. cmdline,
  5082. sizeof(cmdline),
  5083. "\"%s\" %s \"%s\\%s\"",
  5084. interp,
  5085. interp_arg,
  5086. full_dir,
  5087. prog);
  5088. } else {
  5089. mg_snprintf(conn,
  5090. &truncated,
  5091. cmdline,
  5092. sizeof(cmdline),
  5093. "\"%s\" \"%s\\%s\"",
  5094. interp,
  5095. full_dir,
  5096. prog);
  5097. }
  5098. } else {
  5099. /* This is (probably) a compiled program. We call it directly. */
  5100. mg_snprintf(conn,
  5101. &truncated,
  5102. cmdline,
  5103. sizeof(cmdline),
  5104. "\"%s\\%s\"",
  5105. full_dir,
  5106. prog);
  5107. }
  5108. if (truncated) {
  5109. pi.hProcess = (pid_t)-1;
  5110. goto spawn_cleanup;
  5111. }
  5112. DEBUG_TRACE("Running [%s]", cmdline);
  5113. if (CreateProcessA(NULL,
  5114. cmdline,
  5115. NULL,
  5116. NULL,
  5117. TRUE,
  5118. CREATE_NEW_PROCESS_GROUP,
  5119. envblk,
  5120. NULL,
  5121. &si,
  5122. &pi)
  5123. == 0) {
  5124. mg_cry_internal(
  5125. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5126. pi.hProcess = (pid_t)-1;
  5127. /* goto spawn_cleanup; */
  5128. }
  5129. spawn_cleanup:
  5130. (void)CloseHandle(si.hStdOutput);
  5131. (void)CloseHandle(si.hStdError);
  5132. (void)CloseHandle(si.hStdInput);
  5133. if (pi.hThread != NULL) {
  5134. (void)CloseHandle(pi.hThread);
  5135. }
  5136. return (pid_t)pi.hProcess;
  5137. }
  5138. #endif /* !NO_CGI */
  5139. static int
  5140. set_blocking_mode(SOCKET sock)
  5141. {
  5142. unsigned long non_blocking = 0;
  5143. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5144. }
  5145. static int
  5146. set_non_blocking_mode(SOCKET sock)
  5147. {
  5148. unsigned long non_blocking = 1;
  5149. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5150. }
  5151. #else
  5152. #if !defined(NO_FILESYSTEMS)
  5153. static int
  5154. mg_stat(const struct mg_connection *conn,
  5155. const char *path,
  5156. struct mg_file_stat *filep)
  5157. {
  5158. struct stat st;
  5159. if (!filep) {
  5160. return 0;
  5161. }
  5162. memset(filep, 0, sizeof(*filep));
  5163. if (conn && is_file_in_memory(conn, path)) {
  5164. /* Quick fix (for 1.9.x): */
  5165. /* mg_stat must fill all fields, also for files in memory */
  5166. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5167. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5168. filep->size = tmp_file.stat.size;
  5169. filep->last_modified = time(NULL);
  5170. filep->location = 2;
  5171. /* TODO: remove legacy "files in memory" feature */
  5172. return 1;
  5173. }
  5174. if (0 == stat(path, &st)) {
  5175. filep->size = (uint64_t)(st.st_size);
  5176. filep->last_modified = st.st_mtime;
  5177. filep->is_directory = S_ISDIR(st.st_mode);
  5178. return 1;
  5179. }
  5180. return 0;
  5181. }
  5182. #endif /* NO_FILESYSTEMS */
  5183. static void
  5184. set_close_on_exec(int fd,
  5185. const struct mg_connection *conn /* may be null */,
  5186. struct mg_context *ctx /* may be null */)
  5187. {
  5188. #if defined(__ZEPHYR__)
  5189. (void)fd;
  5190. (void)conn;
  5191. (void)ctx;
  5192. #else
  5193. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5194. if (conn || ctx) {
  5195. struct mg_connection fc;
  5196. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5197. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5198. __func__,
  5199. strerror(ERRNO));
  5200. }
  5201. }
  5202. #endif
  5203. }
  5204. int
  5205. mg_start_thread(mg_thread_func_t func, void *param)
  5206. {
  5207. pthread_t thread_id;
  5208. pthread_attr_t attr;
  5209. int result;
  5210. (void)pthread_attr_init(&attr);
  5211. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5212. #if defined(__ZEPHYR__)
  5213. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5214. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5215. /* Compile-time option to control stack size,
  5216. * e.g. -DUSE_STACK_SIZE=16384 */
  5217. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5218. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5219. result = pthread_create(&thread_id, &attr, func, param);
  5220. pthread_attr_destroy(&attr);
  5221. return result;
  5222. }
  5223. /* Start a thread storing the thread context. */
  5224. static int
  5225. mg_start_thread_with_id(mg_thread_func_t func,
  5226. void *param,
  5227. pthread_t *threadidptr)
  5228. {
  5229. pthread_t thread_id;
  5230. pthread_attr_t attr;
  5231. int result;
  5232. (void)pthread_attr_init(&attr);
  5233. #if defined(__ZEPHYR__)
  5234. pthread_attr_setstack(&attr,
  5235. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5236. ZEPHYR_STACK_SIZE);
  5237. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5238. /* Compile-time option to control stack size,
  5239. * e.g. -DUSE_STACK_SIZE=16384 */
  5240. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5241. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5242. result = pthread_create(&thread_id, &attr, func, param);
  5243. pthread_attr_destroy(&attr);
  5244. if ((result == 0) && (threadidptr != NULL)) {
  5245. *threadidptr = thread_id;
  5246. }
  5247. return result;
  5248. }
  5249. /* Wait for a thread to finish. */
  5250. static int
  5251. mg_join_thread(pthread_t threadid)
  5252. {
  5253. int result;
  5254. result = pthread_join(threadid, NULL);
  5255. return result;
  5256. }
  5257. #if !defined(NO_CGI)
  5258. static pid_t
  5259. spawn_process(struct mg_connection *conn,
  5260. const char *prog,
  5261. char *envblk,
  5262. char *envp[],
  5263. int fdin[2],
  5264. int fdout[2],
  5265. int fderr[2],
  5266. const char *dir)
  5267. {
  5268. pid_t pid;
  5269. const char *interp;
  5270. (void)envblk;
  5271. if ((pid = fork()) == -1) {
  5272. /* Parent */
  5273. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5274. } else if (pid != 0) {
  5275. /* Make sure children close parent-side descriptors.
  5276. * The caller will close the child-side immediately. */
  5277. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5278. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5279. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5280. } else {
  5281. /* Child */
  5282. if (chdir(dir) != 0) {
  5283. mg_cry_internal(
  5284. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5285. } else if (dup2(fdin[0], 0) == -1) {
  5286. mg_cry_internal(conn,
  5287. "%s: dup2(%d, 0): %s",
  5288. __func__,
  5289. fdin[0],
  5290. strerror(ERRNO));
  5291. } else if (dup2(fdout[1], 1) == -1) {
  5292. mg_cry_internal(conn,
  5293. "%s: dup2(%d, 1): %s",
  5294. __func__,
  5295. fdout[1],
  5296. strerror(ERRNO));
  5297. } else if (dup2(fderr[1], 2) == -1) {
  5298. mg_cry_internal(conn,
  5299. "%s: dup2(%d, 2): %s",
  5300. __func__,
  5301. fderr[1],
  5302. strerror(ERRNO));
  5303. } else {
  5304. struct sigaction sa;
  5305. /* Keep stderr and stdout in two different pipes.
  5306. * Stdout will be sent back to the client,
  5307. * stderr should go into a server error log. */
  5308. (void)close(fdin[0]);
  5309. (void)close(fdout[1]);
  5310. (void)close(fderr[1]);
  5311. /* Close write end fdin and read end fdout and fderr */
  5312. (void)close(fdin[1]);
  5313. (void)close(fdout[0]);
  5314. (void)close(fderr[0]);
  5315. /* After exec, all signal handlers are restored to their default
  5316. * values, with one exception of SIGCHLD. According to
  5317. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5318. * will leave unchanged after exec if it was set to be ignored.
  5319. * Restore it to default action. */
  5320. memset(&sa, 0, sizeof(sa));
  5321. sa.sa_handler = SIG_DFL;
  5322. sigaction(SIGCHLD, &sa, NULL);
  5323. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5324. if (interp == NULL) {
  5325. /* no interpreter configured, call the programm directly */
  5326. (void)execle(prog, prog, NULL, envp);
  5327. mg_cry_internal(conn,
  5328. "%s: execle(%s): %s",
  5329. __func__,
  5330. prog,
  5331. strerror(ERRNO));
  5332. } else {
  5333. /* call the configured interpreter */
  5334. const char *interp_args =
  5335. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5336. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5337. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5338. } else {
  5339. (void)execle(interp, interp, prog, NULL, envp);
  5340. }
  5341. mg_cry_internal(conn,
  5342. "%s: execle(%s %s): %s",
  5343. __func__,
  5344. interp,
  5345. prog,
  5346. strerror(ERRNO));
  5347. }
  5348. }
  5349. exit(EXIT_FAILURE);
  5350. }
  5351. return pid;
  5352. }
  5353. #endif /* !NO_CGI */
  5354. static int
  5355. set_non_blocking_mode(SOCKET sock)
  5356. {
  5357. int flags = fcntl(sock, F_GETFL, 0);
  5358. if (flags < 0) {
  5359. return -1;
  5360. }
  5361. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5362. return -1;
  5363. }
  5364. return 0;
  5365. }
  5366. static int
  5367. set_blocking_mode(SOCKET sock)
  5368. {
  5369. int flags = fcntl(sock, F_GETFL, 0);
  5370. if (flags < 0) {
  5371. return -1;
  5372. }
  5373. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5374. return -1;
  5375. }
  5376. return 0;
  5377. }
  5378. #endif /* _WIN32 / else */
  5379. /* End of initial operating system specific define block. */
  5380. /* Get a random number (independent of C rand function) */
  5381. static uint64_t
  5382. get_random(void)
  5383. {
  5384. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5385. static uint64_t lcg = 0; /* Linear congruential generator */
  5386. uint64_t now = mg_get_current_time_ns();
  5387. if (lfsr == 0) {
  5388. /* lfsr will be only 0 if has not been initialized,
  5389. * so this code is called only once. */
  5390. lfsr = mg_get_current_time_ns();
  5391. lcg = mg_get_current_time_ns();
  5392. } else {
  5393. /* Get the next step of both random number generators. */
  5394. lfsr = (lfsr >> 1)
  5395. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5396. << 63);
  5397. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5398. }
  5399. /* Combining two pseudo-random number generators and a high resolution
  5400. * part
  5401. * of the current server time will make it hard (impossible?) to guess
  5402. * the
  5403. * next number. */
  5404. return (lfsr ^ lcg ^ now);
  5405. }
  5406. static int
  5407. mg_poll(struct mg_pollfd *pfd,
  5408. unsigned int n,
  5409. int milliseconds,
  5410. stop_flag_t *stop_flag)
  5411. {
  5412. /* Call poll, but only for a maximum time of a few seconds.
  5413. * This will allow to stop the server after some seconds, instead
  5414. * of having to wait for a long socket timeout. */
  5415. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5416. do {
  5417. int result;
  5418. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5419. /* Shut down signal */
  5420. return -2;
  5421. }
  5422. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5423. ms_now = milliseconds;
  5424. }
  5425. result = poll(pfd, n, ms_now);
  5426. if (result != 0) {
  5427. /* Poll returned either success (1) or error (-1).
  5428. * Forward both to the caller. */
  5429. return result;
  5430. }
  5431. /* Poll returned timeout (0). */
  5432. if (milliseconds > 0) {
  5433. milliseconds -= ms_now;
  5434. }
  5435. } while (milliseconds != 0);
  5436. /* timeout: return 0 */
  5437. return 0;
  5438. }
  5439. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5440. * descriptor.
  5441. * Return value:
  5442. * >=0 .. number of bytes successfully written
  5443. * -1 .. timeout
  5444. * -2 .. error
  5445. */
  5446. static int
  5447. push_inner(struct mg_context *ctx,
  5448. FILE *fp,
  5449. SOCKET sock,
  5450. SSL *ssl,
  5451. const char *buf,
  5452. int len,
  5453. double timeout)
  5454. {
  5455. uint64_t start = 0, now = 0, timeout_ns = 0;
  5456. int n, err;
  5457. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5458. #if defined(_WIN32)
  5459. typedef int len_t;
  5460. #else
  5461. typedef size_t len_t;
  5462. #endif
  5463. if (timeout > 0) {
  5464. now = mg_get_current_time_ns();
  5465. start = now;
  5466. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5467. }
  5468. if (ctx == NULL) {
  5469. return -2;
  5470. }
  5471. #if defined(NO_SSL)
  5472. if (ssl) {
  5473. return -2;
  5474. }
  5475. #endif
  5476. /* Try to read until it succeeds, fails, times out, or the server
  5477. * shuts down. */
  5478. for (;;) {
  5479. #if !defined(NO_SSL)
  5480. if (ssl != NULL) {
  5481. ERR_clear_error();
  5482. n = SSL_write(ssl, buf, len);
  5483. if (n <= 0) {
  5484. err = SSL_get_error(ssl, n);
  5485. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5486. err = ERRNO;
  5487. } else if ((err == SSL_ERROR_WANT_READ)
  5488. || (err == SSL_ERROR_WANT_WRITE)) {
  5489. n = 0;
  5490. } else {
  5491. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5492. ERR_clear_error();
  5493. return -2;
  5494. }
  5495. ERR_clear_error();
  5496. } else {
  5497. err = 0;
  5498. }
  5499. } else
  5500. #endif
  5501. if (fp != NULL) {
  5502. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5503. if (ferror(fp)) {
  5504. n = -1;
  5505. err = ERRNO;
  5506. } else {
  5507. err = 0;
  5508. }
  5509. } else {
  5510. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5511. err = (n < 0) ? ERRNO : 0;
  5512. #if defined(_WIN32)
  5513. if (err == WSAEWOULDBLOCK) {
  5514. err = 0;
  5515. n = 0;
  5516. }
  5517. #else
  5518. if (err == EWOULDBLOCK) {
  5519. err = 0;
  5520. n = 0;
  5521. }
  5522. #endif
  5523. if (n < 0) {
  5524. /* shutdown of the socket at client side */
  5525. return -2;
  5526. }
  5527. }
  5528. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5529. return -2;
  5530. }
  5531. if ((n > 0) || ((n == 0) && (len == 0))) {
  5532. /* some data has been read, or no data was requested */
  5533. return n;
  5534. }
  5535. if (n < 0) {
  5536. /* socket error - check errno */
  5537. DEBUG_TRACE("send() failed, error %d", err);
  5538. /* TODO (mid): error handling depending on the error code.
  5539. * These codes are different between Windows and Linux.
  5540. * Currently there is no problem with failing send calls,
  5541. * if there is a reproducible situation, it should be
  5542. * investigated in detail.
  5543. */
  5544. return -2;
  5545. }
  5546. /* Only in case n=0 (timeout), repeat calling the write function */
  5547. /* If send failed, wait before retry */
  5548. if (fp != NULL) {
  5549. /* For files, just wait a fixed time.
  5550. * Maybe it helps, maybe not. */
  5551. mg_sleep(5);
  5552. } else {
  5553. /* For sockets, wait for the socket using poll */
  5554. struct mg_pollfd pfd[1];
  5555. int pollres;
  5556. pfd[0].fd = sock;
  5557. pfd[0].events = POLLOUT;
  5558. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5559. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5560. return -2;
  5561. }
  5562. if (pollres > 0) {
  5563. continue;
  5564. }
  5565. }
  5566. if (timeout > 0) {
  5567. now = mg_get_current_time_ns();
  5568. if ((now - start) > timeout_ns) {
  5569. /* Timeout */
  5570. break;
  5571. }
  5572. }
  5573. }
  5574. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5575. used */
  5576. return -1;
  5577. }
  5578. static int
  5579. push_all(struct mg_context *ctx,
  5580. FILE *fp,
  5581. SOCKET sock,
  5582. SSL *ssl,
  5583. const char *buf,
  5584. int len)
  5585. {
  5586. double timeout = -1.0;
  5587. int n, nwritten = 0;
  5588. if (ctx == NULL) {
  5589. return -1;
  5590. }
  5591. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5592. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5593. }
  5594. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5595. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5596. if (n < 0) {
  5597. if (nwritten == 0) {
  5598. nwritten = -1; /* Propagate the error */
  5599. }
  5600. break;
  5601. } else if (n == 0) {
  5602. break; /* No more data to write */
  5603. } else {
  5604. nwritten += n;
  5605. len -= n;
  5606. }
  5607. }
  5608. return nwritten;
  5609. }
  5610. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5611. * Return value:
  5612. * >=0 .. number of bytes successfully read
  5613. * -1 .. timeout
  5614. * -2 .. error
  5615. */
  5616. static int
  5617. pull_inner(FILE *fp,
  5618. struct mg_connection *conn,
  5619. char *buf,
  5620. int len,
  5621. double timeout)
  5622. {
  5623. int nread, err = 0;
  5624. #if defined(_WIN32)
  5625. typedef int len_t;
  5626. #else
  5627. typedef size_t len_t;
  5628. #endif
  5629. /* We need an additional wait loop around this, because in some cases
  5630. * with TLSwe may get data from the socket but not from SSL_read.
  5631. * In this case we need to repeat at least once.
  5632. */
  5633. if (fp != NULL) {
  5634. #if !defined(_WIN32_WCE)
  5635. /* Use read() instead of fread(), because if we're reading from the
  5636. * CGI pipe, fread() may block until IO buffer is filled up. We
  5637. * cannot afford to block and must pass all read bytes immediately
  5638. * to the client. */
  5639. nread = (int)read(fileno(fp), buf, (size_t)len);
  5640. #else
  5641. /* WinCE does not support CGI pipes */
  5642. nread = (int)fread(buf, 1, (size_t)len, fp);
  5643. #endif
  5644. err = (nread < 0) ? ERRNO : 0;
  5645. if ((nread == 0) && (len > 0)) {
  5646. /* Should get data, but got EOL */
  5647. return -2;
  5648. }
  5649. #if !defined(NO_SSL)
  5650. } else if (conn->ssl != NULL) {
  5651. int ssl_pending;
  5652. struct mg_pollfd pfd[1];
  5653. int pollres;
  5654. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5655. /* We already know there is no more data buffered in conn->buf
  5656. * but there is more available in the SSL layer. So don't poll
  5657. * conn->client.sock yet. */
  5658. if (ssl_pending > len) {
  5659. ssl_pending = len;
  5660. }
  5661. pollres = 1;
  5662. } else {
  5663. pfd[0].fd = conn->client.sock;
  5664. pfd[0].events = POLLIN;
  5665. pollres = mg_poll(pfd,
  5666. 1,
  5667. (int)(timeout * 1000.0),
  5668. &(conn->phys_ctx->stop_flag));
  5669. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5670. return -2;
  5671. }
  5672. }
  5673. if (pollres > 0) {
  5674. ERR_clear_error();
  5675. nread =
  5676. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5677. if (nread <= 0) {
  5678. err = SSL_get_error(conn->ssl, nread);
  5679. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5680. err = ERRNO;
  5681. } else if ((err == SSL_ERROR_WANT_READ)
  5682. || (err == SSL_ERROR_WANT_WRITE)) {
  5683. nread = 0;
  5684. } else {
  5685. /* All errors should return -2 */
  5686. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5687. ERR_clear_error();
  5688. return -2;
  5689. }
  5690. ERR_clear_error();
  5691. } else {
  5692. err = 0;
  5693. }
  5694. } else if (pollres < 0) {
  5695. /* Error */
  5696. return -2;
  5697. } else {
  5698. /* pollres = 0 means timeout */
  5699. nread = 0;
  5700. }
  5701. #endif
  5702. } else {
  5703. struct mg_pollfd pfd[1];
  5704. int pollres;
  5705. pfd[0].fd = conn->client.sock;
  5706. pfd[0].events = POLLIN;
  5707. pollres = mg_poll(pfd,
  5708. 1,
  5709. (int)(timeout * 1000.0),
  5710. &(conn->phys_ctx->stop_flag));
  5711. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5712. return -2;
  5713. }
  5714. if (pollres > 0) {
  5715. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5716. err = (nread < 0) ? ERRNO : 0;
  5717. if (nread <= 0) {
  5718. /* shutdown of the socket at client side */
  5719. return -2;
  5720. }
  5721. } else if (pollres < 0) {
  5722. /* error callint poll */
  5723. return -2;
  5724. } else {
  5725. /* pollres = 0 means timeout */
  5726. nread = 0;
  5727. }
  5728. }
  5729. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5730. return -2;
  5731. }
  5732. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5733. /* some data has been read, or no data was requested */
  5734. return nread;
  5735. }
  5736. if (nread < 0) {
  5737. /* socket error - check errno */
  5738. #if defined(_WIN32)
  5739. if (err == WSAEWOULDBLOCK) {
  5740. /* TODO (low): check if this is still required */
  5741. /* standard case if called from close_socket_gracefully */
  5742. return -2;
  5743. } else if (err == WSAETIMEDOUT) {
  5744. /* TODO (low): check if this is still required */
  5745. /* timeout is handled by the while loop */
  5746. return 0;
  5747. } else if (err == WSAECONNABORTED) {
  5748. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5749. return -2;
  5750. } else {
  5751. DEBUG_TRACE("recv() failed, error %d", err);
  5752. return -2;
  5753. }
  5754. #else
  5755. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5756. * if the timeout is reached and if the socket was set to non-
  5757. * blocking in close_socket_gracefully, so we can not distinguish
  5758. * here. We have to wait for the timeout in both cases for now.
  5759. */
  5760. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5761. /* TODO (low): check if this is still required */
  5762. /* EAGAIN/EWOULDBLOCK:
  5763. * standard case if called from close_socket_gracefully
  5764. * => should return -1 */
  5765. /* or timeout occurred
  5766. * => the code must stay in the while loop */
  5767. /* EINTR can be generated on a socket with a timeout set even
  5768. * when SA_RESTART is effective for all relevant signals
  5769. * (see signal(7)).
  5770. * => stay in the while loop */
  5771. } else {
  5772. DEBUG_TRACE("recv() failed, error %d", err);
  5773. return -2;
  5774. }
  5775. #endif
  5776. }
  5777. /* Timeout occurred, but no data available. */
  5778. return -1;
  5779. }
  5780. static int
  5781. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5782. {
  5783. int n, nread = 0;
  5784. double timeout = -1.0;
  5785. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5786. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5787. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5788. }
  5789. if (timeout >= 0.0) {
  5790. start_time = mg_get_current_time_ns();
  5791. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5792. }
  5793. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5794. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5795. if (n == -2) {
  5796. if (nread == 0) {
  5797. nread = -1; /* Propagate the error */
  5798. }
  5799. break;
  5800. } else if (n == -1) {
  5801. /* timeout */
  5802. if (timeout >= 0.0) {
  5803. now = mg_get_current_time_ns();
  5804. if ((now - start_time) <= timeout_ns) {
  5805. continue;
  5806. }
  5807. }
  5808. break;
  5809. } else if (n == 0) {
  5810. break; /* No more data to read */
  5811. } else {
  5812. nread += n;
  5813. len -= n;
  5814. }
  5815. }
  5816. return nread;
  5817. }
  5818. static void
  5819. discard_unread_request_data(struct mg_connection *conn)
  5820. {
  5821. char buf[MG_BUF_LEN];
  5822. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5823. ;
  5824. }
  5825. static int
  5826. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5827. {
  5828. int64_t content_len, n, buffered_len, nread;
  5829. int64_t len64 =
  5830. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5831. * int, we may not read more
  5832. * bytes */
  5833. const char *body;
  5834. if (conn == NULL) {
  5835. return 0;
  5836. }
  5837. /* If Content-Length is not set for a response with body data,
  5838. * we do not know in advance how much data should be read. */
  5839. content_len = conn->content_len;
  5840. if (content_len < 0) {
  5841. /* The body data is completed when the connection is closed. */
  5842. content_len = INT64_MAX;
  5843. }
  5844. nread = 0;
  5845. if (conn->consumed_content < content_len) {
  5846. /* Adjust number of bytes to read. */
  5847. int64_t left_to_read = content_len - conn->consumed_content;
  5848. if (left_to_read < len64) {
  5849. /* Do not read more than the total content length of the
  5850. * request.
  5851. */
  5852. len64 = left_to_read;
  5853. }
  5854. /* Return buffered data */
  5855. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5856. - conn->consumed_content;
  5857. if (buffered_len > 0) {
  5858. if (len64 < buffered_len) {
  5859. buffered_len = len64;
  5860. }
  5861. body = conn->buf + conn->request_len + conn->consumed_content;
  5862. memcpy(buf, body, (size_t)buffered_len);
  5863. len64 -= buffered_len;
  5864. conn->consumed_content += buffered_len;
  5865. nread += buffered_len;
  5866. buf = (char *)buf + buffered_len;
  5867. }
  5868. /* We have returned all buffered data. Read new data from the remote
  5869. * socket.
  5870. */
  5871. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5872. conn->consumed_content += n;
  5873. nread += n;
  5874. } else {
  5875. nread = ((nread > 0) ? nread : n);
  5876. }
  5877. }
  5878. return (int)nread;
  5879. }
  5880. int
  5881. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5882. {
  5883. if (len > INT_MAX) {
  5884. len = INT_MAX;
  5885. }
  5886. if (conn == NULL) {
  5887. return 0;
  5888. }
  5889. if (conn->is_chunked) {
  5890. size_t all_read = 0;
  5891. while (len > 0) {
  5892. if (conn->is_chunked >= 3) {
  5893. /* No more data left to read */
  5894. return 0;
  5895. }
  5896. if (conn->is_chunked != 1) {
  5897. /* Has error */
  5898. return -1;
  5899. }
  5900. if (conn->consumed_content != conn->content_len) {
  5901. /* copy from the current chunk */
  5902. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5903. if (read_ret < 1) {
  5904. /* read error */
  5905. conn->is_chunked = 2;
  5906. return -1;
  5907. }
  5908. all_read += (size_t)read_ret;
  5909. len -= (size_t)read_ret;
  5910. if (conn->consumed_content == conn->content_len) {
  5911. /* Add data bytes in the current chunk have been read,
  5912. * so we are expecting \r\n now. */
  5913. char x[2];
  5914. conn->content_len += 2;
  5915. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5916. || (x[1] != '\n')) {
  5917. /* Protocol violation */
  5918. conn->is_chunked = 2;
  5919. return -1;
  5920. }
  5921. }
  5922. } else {
  5923. /* fetch a new chunk */
  5924. size_t i;
  5925. char lenbuf[64];
  5926. char *end = NULL;
  5927. unsigned long chunkSize = 0;
  5928. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5929. conn->content_len++;
  5930. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5931. lenbuf[i] = 0;
  5932. }
  5933. if ((i > 0) && (lenbuf[i] == '\r')
  5934. && (lenbuf[i - 1] != '\r')) {
  5935. continue;
  5936. }
  5937. if ((i > 1) && (lenbuf[i] == '\n')
  5938. && (lenbuf[i - 1] == '\r')) {
  5939. lenbuf[i + 1] = 0;
  5940. chunkSize = strtoul(lenbuf, &end, 16);
  5941. if (chunkSize == 0) {
  5942. /* regular end of content */
  5943. conn->is_chunked = 3;
  5944. }
  5945. break;
  5946. }
  5947. if (!isxdigit((unsigned char)lenbuf[i])) {
  5948. /* illegal character for chunk length */
  5949. conn->is_chunked = 2;
  5950. return -1;
  5951. }
  5952. }
  5953. if ((end == NULL) || (*end != '\r')) {
  5954. /* chunksize not set correctly */
  5955. conn->is_chunked = 2;
  5956. return -1;
  5957. }
  5958. if (chunkSize == 0) {
  5959. /* try discarding trailer for keep-alive */
  5960. conn->content_len += 2;
  5961. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5962. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5963. conn->is_chunked = 4;
  5964. }
  5965. break;
  5966. }
  5967. /* append a new chunk */
  5968. conn->content_len += (int64_t)chunkSize;
  5969. }
  5970. }
  5971. return (int)all_read;
  5972. }
  5973. return mg_read_inner(conn, buf, len);
  5974. }
  5975. int
  5976. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5977. {
  5978. time_t now;
  5979. int n, total, allowed;
  5980. if (conn == NULL) {
  5981. return 0;
  5982. }
  5983. if (len > INT_MAX) {
  5984. return -1;
  5985. }
  5986. if (conn->throttle > 0) {
  5987. if ((now = time(NULL)) != conn->last_throttle_time) {
  5988. conn->last_throttle_time = now;
  5989. conn->last_throttle_bytes = 0;
  5990. }
  5991. allowed = conn->throttle - conn->last_throttle_bytes;
  5992. if (allowed > (int)len) {
  5993. allowed = (int)len;
  5994. }
  5995. if ((total = push_all(conn->phys_ctx,
  5996. NULL,
  5997. conn->client.sock,
  5998. conn->ssl,
  5999. (const char *)buf,
  6000. allowed))
  6001. == allowed) {
  6002. buf = (const char *)buf + total;
  6003. conn->last_throttle_bytes += total;
  6004. while ((total < (int)len)
  6005. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6006. allowed = (conn->throttle > ((int)len - total))
  6007. ? (int)len - total
  6008. : conn->throttle;
  6009. if ((n = push_all(conn->phys_ctx,
  6010. NULL,
  6011. conn->client.sock,
  6012. conn->ssl,
  6013. (const char *)buf,
  6014. allowed))
  6015. != allowed) {
  6016. break;
  6017. }
  6018. sleep(1);
  6019. conn->last_throttle_bytes = allowed;
  6020. conn->last_throttle_time = time(NULL);
  6021. buf = (const char *)buf + n;
  6022. total += n;
  6023. }
  6024. }
  6025. } else {
  6026. total = push_all(conn->phys_ctx,
  6027. NULL,
  6028. conn->client.sock,
  6029. conn->ssl,
  6030. (const char *)buf,
  6031. (int)len);
  6032. }
  6033. if (total > 0) {
  6034. conn->num_bytes_sent += total;
  6035. }
  6036. return total;
  6037. }
  6038. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6039. int
  6040. mg_send_chunk(struct mg_connection *conn,
  6041. const char *chunk,
  6042. unsigned int chunk_len)
  6043. {
  6044. char lenbuf[16];
  6045. size_t lenbuf_len;
  6046. int ret;
  6047. int t;
  6048. /* First store the length information in a text buffer. */
  6049. sprintf(lenbuf, "%x\r\n", chunk_len);
  6050. lenbuf_len = strlen(lenbuf);
  6051. /* Then send length information, chunk and terminating \r\n. */
  6052. ret = mg_write(conn, lenbuf, lenbuf_len);
  6053. if (ret != (int)lenbuf_len) {
  6054. return -1;
  6055. }
  6056. t = ret;
  6057. ret = mg_write(conn, chunk, chunk_len);
  6058. if (ret != (int)chunk_len) {
  6059. return -1;
  6060. }
  6061. t += ret;
  6062. ret = mg_write(conn, "\r\n", 2);
  6063. if (ret != 2) {
  6064. return -1;
  6065. }
  6066. t += ret;
  6067. return t;
  6068. }
  6069. #if defined(GCC_DIAGNOSTIC)
  6070. /* This block forwards format strings to printf implementations,
  6071. * so we need to disable the format-nonliteral warning. */
  6072. #pragma GCC diagnostic push
  6073. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6074. #endif
  6075. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6076. static int
  6077. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6078. {
  6079. va_list ap_copy;
  6080. size_t size = MG_BUF_LEN / 4;
  6081. int len = -1;
  6082. *buf = NULL;
  6083. while (len < 0) {
  6084. if (*buf) {
  6085. mg_free(*buf);
  6086. }
  6087. size *= 4;
  6088. *buf = (char *)mg_malloc(size);
  6089. if (!*buf) {
  6090. break;
  6091. }
  6092. va_copy(ap_copy, ap);
  6093. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6094. va_end(ap_copy);
  6095. (*buf)[size - 1] = 0;
  6096. }
  6097. return len;
  6098. }
  6099. /* Print message to buffer. If buffer is large enough to hold the message,
  6100. * return buffer. If buffer is to small, allocate large enough buffer on
  6101. * heap,
  6102. * and return allocated buffer. */
  6103. static int
  6104. alloc_vprintf(char **out_buf,
  6105. char *prealloc_buf,
  6106. size_t prealloc_size,
  6107. const char *fmt,
  6108. va_list ap)
  6109. {
  6110. va_list ap_copy;
  6111. int len;
  6112. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6113. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6114. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6115. * Therefore, we make two passes: on first pass, get required message
  6116. * length.
  6117. * On second pass, actually print the message. */
  6118. va_copy(ap_copy, ap);
  6119. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6120. va_end(ap_copy);
  6121. if (len < 0) {
  6122. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6123. * Switch to alternative code path that uses incremental
  6124. * allocations.
  6125. */
  6126. va_copy(ap_copy, ap);
  6127. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6128. va_end(ap_copy);
  6129. } else if ((size_t)(len) >= prealloc_size) {
  6130. /* The pre-allocated buffer not large enough. */
  6131. /* Allocate a new buffer. */
  6132. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6133. if (!*out_buf) {
  6134. /* Allocation failed. Return -1 as "out of memory" error. */
  6135. return -1;
  6136. }
  6137. /* Buffer allocation successful. Store the string there. */
  6138. va_copy(ap_copy, ap);
  6139. IGNORE_UNUSED_RESULT(
  6140. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6141. va_end(ap_copy);
  6142. } else {
  6143. /* The pre-allocated buffer is large enough.
  6144. * Use it to store the string and return the address. */
  6145. va_copy(ap_copy, ap);
  6146. IGNORE_UNUSED_RESULT(
  6147. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6148. va_end(ap_copy);
  6149. *out_buf = prealloc_buf;
  6150. }
  6151. return len;
  6152. }
  6153. #if defined(GCC_DIAGNOSTIC)
  6154. /* Enable format-nonliteral warning again. */
  6155. #pragma GCC diagnostic pop
  6156. #endif
  6157. static int
  6158. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6159. {
  6160. char mem[MG_BUF_LEN];
  6161. char *buf = NULL;
  6162. int len;
  6163. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6164. len = mg_write(conn, buf, (size_t)len);
  6165. }
  6166. if (buf != mem) {
  6167. mg_free(buf);
  6168. }
  6169. return len;
  6170. }
  6171. int
  6172. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6173. {
  6174. va_list ap;
  6175. int result;
  6176. va_start(ap, fmt);
  6177. result = mg_vprintf(conn, fmt, ap);
  6178. va_end(ap);
  6179. return result;
  6180. }
  6181. int
  6182. mg_url_decode(const char *src,
  6183. int src_len,
  6184. char *dst,
  6185. int dst_len,
  6186. int is_form_url_encoded)
  6187. {
  6188. int i, j, a, b;
  6189. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6190. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6191. if ((i < src_len - 2) && (src[i] == '%')
  6192. && isxdigit((unsigned char)src[i + 1])
  6193. && isxdigit((unsigned char)src[i + 2])) {
  6194. a = tolower((unsigned char)src[i + 1]);
  6195. b = tolower((unsigned char)src[i + 2]);
  6196. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6197. i += 2;
  6198. } else if (is_form_url_encoded && (src[i] == '+')) {
  6199. dst[j] = ' ';
  6200. } else {
  6201. dst[j] = src[i];
  6202. }
  6203. }
  6204. dst[j] = '\0'; /* Null-terminate the destination */
  6205. return (i >= src_len) ? j : -1;
  6206. }
  6207. /* form url decoding of an entire string */
  6208. static void
  6209. url_decode_in_place(char *buf)
  6210. {
  6211. int len = (int)strlen(buf);
  6212. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6213. }
  6214. int
  6215. mg_get_var(const char *data,
  6216. size_t data_len,
  6217. const char *name,
  6218. char *dst,
  6219. size_t dst_len)
  6220. {
  6221. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6222. }
  6223. int
  6224. mg_get_var2(const char *data,
  6225. size_t data_len,
  6226. const char *name,
  6227. char *dst,
  6228. size_t dst_len,
  6229. size_t occurrence)
  6230. {
  6231. const char *p, *e, *s;
  6232. size_t name_len;
  6233. int len;
  6234. if ((dst == NULL) || (dst_len == 0)) {
  6235. len = -2;
  6236. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6237. len = -1;
  6238. dst[0] = '\0';
  6239. } else {
  6240. name_len = strlen(name);
  6241. e = data + data_len;
  6242. len = -1;
  6243. dst[0] = '\0';
  6244. /* data is "var1=val1&var2=val2...". Find variable first */
  6245. for (p = data; p + name_len < e; p++) {
  6246. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6247. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6248. /* Point p to variable value */
  6249. p += name_len + 1;
  6250. /* Point s to the end of the value */
  6251. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6252. if (s == NULL) {
  6253. s = e;
  6254. }
  6255. DEBUG_ASSERT(s >= p);
  6256. if (s < p) {
  6257. return -3;
  6258. }
  6259. /* Decode variable into destination buffer */
  6260. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6261. /* Redirect error code from -1 to -2 (destination buffer too
  6262. * small). */
  6263. if (len == -1) {
  6264. len = -2;
  6265. }
  6266. break;
  6267. }
  6268. }
  6269. }
  6270. return len;
  6271. }
  6272. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6273. int
  6274. mg_split_form_urlencoded(char *data,
  6275. struct mg_header *form_fields,
  6276. unsigned num_form_fields)
  6277. {
  6278. char *b;
  6279. int i;
  6280. int num = 0;
  6281. if (data == NULL) {
  6282. /* parameter error */
  6283. return -1;
  6284. }
  6285. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6286. /* determine the number of expected fields */
  6287. if (data[0] == 0) {
  6288. return 0;
  6289. }
  6290. /* count number of & to return the number of key-value-pairs */
  6291. num = 1;
  6292. while (*data) {
  6293. if (*data == '&') {
  6294. num++;
  6295. }
  6296. data++;
  6297. }
  6298. return num;
  6299. }
  6300. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6301. /* parameter error */
  6302. return -1;
  6303. }
  6304. for (i = 0; i < (int)num_form_fields; i++) {
  6305. /* extract key-value pairs from input data */
  6306. while ((*data == ' ') || (*data == '\t')) {
  6307. /* skip initial spaces */
  6308. data++;
  6309. }
  6310. if (*data == 0) {
  6311. /* end of string reached */
  6312. break;
  6313. }
  6314. form_fields[num].name = data;
  6315. /* find & or = */
  6316. b = data;
  6317. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6318. b++;
  6319. }
  6320. if (*b == 0) {
  6321. /* last key without value */
  6322. form_fields[num].value = NULL;
  6323. } else if (*b == '&') {
  6324. /* mid key without value */
  6325. form_fields[num].value = NULL;
  6326. } else {
  6327. /* terminate string */
  6328. *b = 0;
  6329. /* value starts after '=' */
  6330. data = b + 1;
  6331. form_fields[num].value = data;
  6332. }
  6333. /* new field is stored */
  6334. num++;
  6335. /* find a next key */
  6336. b = strchr(data, '&');
  6337. if (b == 0) {
  6338. /* no more data */
  6339. break;
  6340. } else {
  6341. /* terminate value of last field at '&' */
  6342. *b = 0;
  6343. /* next key-value-pairs starts after '&' */
  6344. data = b + 1;
  6345. }
  6346. }
  6347. /* Decode all values */
  6348. for (i = 0; i < num; i++) {
  6349. if (form_fields[i].name) {
  6350. url_decode_in_place((char *)form_fields[i].name);
  6351. }
  6352. if (form_fields[i].value) {
  6353. url_decode_in_place((char *)form_fields[i].value);
  6354. }
  6355. }
  6356. /* return number of fields found */
  6357. return num;
  6358. }
  6359. /* HCP24: some changes to compare hole var_name */
  6360. int
  6361. mg_get_cookie(const char *cookie_header,
  6362. const char *var_name,
  6363. char *dst,
  6364. size_t dst_size)
  6365. {
  6366. const char *s, *p, *end;
  6367. int name_len, len = -1;
  6368. if ((dst == NULL) || (dst_size == 0)) {
  6369. return -2;
  6370. }
  6371. dst[0] = '\0';
  6372. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6373. return -1;
  6374. }
  6375. name_len = (int)strlen(var_name);
  6376. end = s + strlen(s);
  6377. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6378. if (s[name_len] == '=') {
  6379. /* HCP24: now check is it a substring or a full cookie name */
  6380. if ((s == cookie_header) || (s[-1] == ' ')) {
  6381. s += name_len + 1;
  6382. if ((p = strchr(s, ' ')) == NULL) {
  6383. p = end;
  6384. }
  6385. if (p[-1] == ';') {
  6386. p--;
  6387. }
  6388. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6389. s++;
  6390. p--;
  6391. }
  6392. if ((size_t)(p - s) < dst_size) {
  6393. len = (int)(p - s);
  6394. mg_strlcpy(dst, s, (size_t)len + 1);
  6395. } else {
  6396. len = -3;
  6397. }
  6398. break;
  6399. }
  6400. }
  6401. }
  6402. return len;
  6403. }
  6404. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6405. static void
  6406. base64_encode(const unsigned char *src, int src_len, char *dst)
  6407. {
  6408. static const char *b64 =
  6409. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6410. int i, j, a, b, c;
  6411. for (i = j = 0; i < src_len; i += 3) {
  6412. a = src[i];
  6413. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6414. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6415. dst[j++] = b64[a >> 2];
  6416. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6417. if (i + 1 < src_len) {
  6418. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6419. }
  6420. if (i + 2 < src_len) {
  6421. dst[j++] = b64[c & 63];
  6422. }
  6423. }
  6424. while (j % 4 != 0) {
  6425. dst[j++] = '=';
  6426. }
  6427. dst[j++] = '\0';
  6428. }
  6429. #endif
  6430. #if defined(USE_LUA)
  6431. static unsigned char
  6432. b64reverse(char letter)
  6433. {
  6434. if ((letter >= 'A') && (letter <= 'Z')) {
  6435. return letter - 'A';
  6436. }
  6437. if ((letter >= 'a') && (letter <= 'z')) {
  6438. return letter - 'a' + 26;
  6439. }
  6440. if ((letter >= '0') && (letter <= '9')) {
  6441. return letter - '0' + 52;
  6442. }
  6443. if (letter == '+') {
  6444. return 62;
  6445. }
  6446. if (letter == '/') {
  6447. return 63;
  6448. }
  6449. if (letter == '=') {
  6450. return 255; /* normal end */
  6451. }
  6452. return 254; /* error */
  6453. }
  6454. static int
  6455. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6456. {
  6457. int i;
  6458. unsigned char a, b, c, d;
  6459. *dst_len = 0;
  6460. for (i = 0; i < src_len; i += 4) {
  6461. a = b64reverse(src[i]);
  6462. if (a >= 254) {
  6463. return i;
  6464. }
  6465. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6466. if (b >= 254) {
  6467. return i + 1;
  6468. }
  6469. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6470. if (c == 254) {
  6471. return i + 2;
  6472. }
  6473. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6474. if (d == 254) {
  6475. return i + 3;
  6476. }
  6477. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6478. if (c != 255) {
  6479. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6480. if (d != 255) {
  6481. dst[(*dst_len)++] = (c << 6) + d;
  6482. }
  6483. }
  6484. }
  6485. return -1;
  6486. }
  6487. #endif
  6488. static int
  6489. is_put_or_delete_method(const struct mg_connection *conn)
  6490. {
  6491. if (conn) {
  6492. const char *s = conn->request_info.request_method;
  6493. return (s != NULL)
  6494. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6495. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6496. }
  6497. return 0;
  6498. }
  6499. #if !defined(NO_FILES)
  6500. static int
  6501. extention_matches_script(
  6502. struct mg_connection *conn, /* in: request (must be valid) */
  6503. const char *filename /* in: filename (must be valid) */
  6504. )
  6505. {
  6506. #if !defined(NO_CGI)
  6507. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6508. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6509. filename)
  6510. > 0) {
  6511. return 1;
  6512. }
  6513. #endif
  6514. #if defined(USE_LUA)
  6515. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6516. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6517. filename)
  6518. > 0) {
  6519. return 1;
  6520. }
  6521. #endif
  6522. #if defined(USE_DUKTAPE)
  6523. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6524. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6525. filename)
  6526. > 0) {
  6527. return 1;
  6528. }
  6529. #endif
  6530. /* filename and conn could be unused, if all preocessor conditions
  6531. * are false (no script language supported). */
  6532. (void)filename;
  6533. (void)conn;
  6534. return 0;
  6535. }
  6536. /* For given directory path, substitute it to valid index file.
  6537. * Return 1 if index file has been found, 0 if not found.
  6538. * If the file is found, it's stats is returned in stp. */
  6539. static int
  6540. substitute_index_file(struct mg_connection *conn,
  6541. char *path,
  6542. size_t path_len,
  6543. struct mg_file_stat *filestat)
  6544. {
  6545. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6546. struct vec filename_vec;
  6547. size_t n = strlen(path);
  6548. int found = 0;
  6549. /* The 'path' given to us points to the directory. Remove all trailing
  6550. * directory separator characters from the end of the path, and
  6551. * then append single directory separator character. */
  6552. while ((n > 0) && (path[n - 1] == '/')) {
  6553. n--;
  6554. }
  6555. path[n] = '/';
  6556. /* Traverse index files list. For each entry, append it to the given
  6557. * path and see if the file exists. If it exists, break the loop */
  6558. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6559. /* Ignore too long entries that may overflow path buffer */
  6560. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6561. continue;
  6562. }
  6563. /* Prepare full path to the index file */
  6564. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6565. /* Does it exist? */
  6566. if (mg_stat(conn, path, filestat)) {
  6567. /* Yes it does, break the loop */
  6568. found = 1;
  6569. break;
  6570. }
  6571. }
  6572. /* If no index file exists, restore directory path */
  6573. if (!found) {
  6574. path[n] = '\0';
  6575. }
  6576. return found;
  6577. }
  6578. #endif
  6579. static void
  6580. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6581. char *filename, /* out: filename */
  6582. size_t filename_buf_len, /* in: size of filename buffer */
  6583. struct mg_file_stat *filestat, /* out: file status structure */
  6584. int *is_found, /* out: file found (directly) */
  6585. int *is_script_resource, /* out: handled by a script? */
  6586. int *is_websocket_request, /* out: websocket connetion? */
  6587. int *is_put_or_delete_request /* out: put/delete a file? */
  6588. )
  6589. {
  6590. char const *accept_encoding;
  6591. #if !defined(NO_FILES)
  6592. const char *uri = conn->request_info.local_uri;
  6593. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6594. const char *rewrite;
  6595. struct vec a, b;
  6596. ptrdiff_t match_len;
  6597. char gz_path[PATH_MAX];
  6598. int truncated;
  6599. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6600. char *tmp_str;
  6601. size_t tmp_str_len, sep_pos;
  6602. int allow_substitute_script_subresources;
  6603. #endif
  6604. #else
  6605. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6606. #endif
  6607. /* Step 1: Set all initially unknown outputs to zero */
  6608. memset(filestat, 0, sizeof(*filestat));
  6609. *filename = 0;
  6610. *is_found = 0;
  6611. *is_script_resource = 0;
  6612. /* Step 2: Check if the request attempts to modify the file system */
  6613. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6614. /* Step 3: Check if it is a websocket request, and modify the document
  6615. * root if required */
  6616. #if defined(USE_WEBSOCKET)
  6617. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6618. #if !defined(NO_FILES)
  6619. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6620. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6621. }
  6622. #endif /* !NO_FILES */
  6623. #else /* USE_WEBSOCKET */
  6624. *is_websocket_request = 0;
  6625. #endif /* USE_WEBSOCKET */
  6626. /* Step 4: Check if gzip encoded response is allowed */
  6627. conn->accept_gzip = 0;
  6628. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6629. if (strstr(accept_encoding, "gzip") != NULL) {
  6630. conn->accept_gzip = 1;
  6631. }
  6632. }
  6633. #if !defined(NO_FILES)
  6634. /* Step 5: If there is no root directory, don't look for files. */
  6635. /* Note that root == NULL is a regular use case here. This occurs,
  6636. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6637. * config is not required. */
  6638. if (root == NULL) {
  6639. /* all file related outputs have already been set to 0, just return
  6640. */
  6641. return;
  6642. }
  6643. /* Step 6: Determine the local file path from the root path and the
  6644. * request uri. */
  6645. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6646. * part of the path one byte on the right. */
  6647. mg_snprintf(
  6648. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6649. if (truncated) {
  6650. goto interpret_cleanup;
  6651. }
  6652. /* Step 7: URI rewriting */
  6653. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6654. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6655. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6656. mg_snprintf(conn,
  6657. &truncated,
  6658. filename,
  6659. filename_buf_len - 1,
  6660. "%.*s%s",
  6661. (int)b.len,
  6662. b.ptr,
  6663. uri + match_len);
  6664. break;
  6665. }
  6666. }
  6667. if (truncated) {
  6668. goto interpret_cleanup;
  6669. }
  6670. /* Step 8: Check if the file exists at the server */
  6671. /* Local file path and name, corresponding to requested URI
  6672. * is now stored in "filename" variable. */
  6673. if (mg_stat(conn, filename, filestat)) {
  6674. int uri_len = (int)strlen(uri);
  6675. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6676. /* 8.1: File exists. */
  6677. *is_found = 1;
  6678. /* 8.2: Check if it is a script type. */
  6679. if (extention_matches_script(conn, filename)) {
  6680. /* The request addresses a CGI resource, Lua script or
  6681. * server-side javascript.
  6682. * The URI corresponds to the script itself (like
  6683. * /path/script.cgi), and there is no additional resource
  6684. * path (like /path/script.cgi/something).
  6685. * Requests that modify (replace or delete) a resource, like
  6686. * PUT and DELETE requests, should replace/delete the script
  6687. * file.
  6688. * Requests that read or write from/to a resource, like GET and
  6689. * POST requests, should call the script and return the
  6690. * generated response. */
  6691. *is_script_resource = (!*is_put_or_delete_request);
  6692. }
  6693. /* 8.3: If the request target is a directory, there could be
  6694. * a substitute file (index.html, index.cgi, ...). */
  6695. if (filestat->is_directory && is_uri_end_slash) {
  6696. /* Use a local copy here, since substitute_index_file will
  6697. * change the content of the file status */
  6698. struct mg_file_stat tmp_filestat;
  6699. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6700. if (substitute_index_file(
  6701. conn, filename, filename_buf_len, &tmp_filestat)) {
  6702. /* Substitute file found. Copy stat to the output, then
  6703. * check if the file is a script file */
  6704. *filestat = tmp_filestat;
  6705. if (extention_matches_script(conn, filename)) {
  6706. /* Substitute file is a script file */
  6707. *is_script_resource = 1;
  6708. } else {
  6709. /* Substitute file is a regular file */
  6710. *is_script_resource = 0;
  6711. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6712. }
  6713. }
  6714. /* If there is no substitute file, the server could return
  6715. * a directory listing in a later step */
  6716. }
  6717. return;
  6718. }
  6719. /* Step 9: Check for zipped files: */
  6720. /* If we can't find the actual file, look for the file
  6721. * with the same name but a .gz extension. If we find it,
  6722. * use that and set the gzipped flag in the file struct
  6723. * to indicate that the response need to have the content-
  6724. * encoding: gzip header.
  6725. * We can only do this if the browser declares support. */
  6726. if (conn->accept_gzip) {
  6727. mg_snprintf(
  6728. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6729. if (truncated) {
  6730. goto interpret_cleanup;
  6731. }
  6732. if (mg_stat(conn, gz_path, filestat)) {
  6733. if (filestat) {
  6734. filestat->is_gzipped = 1;
  6735. *is_found = 1;
  6736. }
  6737. /* Currently gz files can not be scripts. */
  6738. return;
  6739. }
  6740. }
  6741. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6742. /* Step 10: Script resources may handle sub-resources */
  6743. /* Support PATH_INFO for CGI scripts. */
  6744. tmp_str_len = strlen(filename);
  6745. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6746. if (!tmp_str) {
  6747. /* Out of memory */
  6748. goto interpret_cleanup;
  6749. }
  6750. memcpy(tmp_str, filename, tmp_str_len + 1);
  6751. /* Check config, if index scripts may have sub-resources */
  6752. allow_substitute_script_subresources =
  6753. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6754. "yes");
  6755. sep_pos = tmp_str_len;
  6756. while (sep_pos > 0) {
  6757. sep_pos--;
  6758. if (tmp_str[sep_pos] == '/') {
  6759. int is_script = 0, does_exist = 0;
  6760. tmp_str[sep_pos] = 0;
  6761. if (tmp_str[0]) {
  6762. is_script = extention_matches_script(conn, tmp_str);
  6763. does_exist = mg_stat(conn, tmp_str, filestat);
  6764. }
  6765. if (does_exist && is_script) {
  6766. filename[sep_pos] = 0;
  6767. memmove(filename + sep_pos + 2,
  6768. filename + sep_pos + 1,
  6769. strlen(filename + sep_pos + 1) + 1);
  6770. conn->path_info = filename + sep_pos + 1;
  6771. filename[sep_pos + 1] = '/';
  6772. *is_script_resource = 1;
  6773. *is_found = 1;
  6774. break;
  6775. }
  6776. if (allow_substitute_script_subresources) {
  6777. if (substitute_index_file(
  6778. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6779. /* some intermediate directory has an index file */
  6780. if (extention_matches_script(conn, tmp_str)) {
  6781. DEBUG_TRACE("Substitute script %s serving path %s",
  6782. tmp_str,
  6783. filename);
  6784. /* this index file is a script */
  6785. mg_snprintf(conn,
  6786. &truncated,
  6787. filename,
  6788. filename_buf_len,
  6789. "%s//%s",
  6790. tmp_str,
  6791. filename + sep_pos + 1);
  6792. if (truncated) {
  6793. mg_free(tmp_str);
  6794. goto interpret_cleanup;
  6795. }
  6796. sep_pos = strlen(tmp_str);
  6797. filename[sep_pos] = 0;
  6798. conn->path_info = filename + sep_pos + 1;
  6799. *is_script_resource = 1;
  6800. *is_found = 1;
  6801. break;
  6802. } else {
  6803. DEBUG_TRACE("Substitute file %s serving path %s",
  6804. tmp_str,
  6805. filename);
  6806. /* non-script files will not have sub-resources */
  6807. filename[sep_pos] = 0;
  6808. conn->path_info = 0;
  6809. *is_script_resource = 0;
  6810. *is_found = 0;
  6811. break;
  6812. }
  6813. }
  6814. }
  6815. tmp_str[sep_pos] = '/';
  6816. }
  6817. }
  6818. mg_free(tmp_str);
  6819. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6820. #endif /* !defined(NO_FILES) */
  6821. return;
  6822. #if !defined(NO_FILES)
  6823. /* Reset all outputs */
  6824. interpret_cleanup:
  6825. memset(filestat, 0, sizeof(*filestat));
  6826. *filename = 0;
  6827. *is_found = 0;
  6828. *is_script_resource = 0;
  6829. *is_websocket_request = 0;
  6830. *is_put_or_delete_request = 0;
  6831. #endif /* !defined(NO_FILES) */
  6832. }
  6833. /* Check whether full request is buffered. Return:
  6834. * -1 if request or response is malformed
  6835. * 0 if request or response is not yet fully buffered
  6836. * >0 actual request length, including last \r\n\r\n */
  6837. static int
  6838. get_http_header_len(const char *buf, int buflen)
  6839. {
  6840. int i;
  6841. for (i = 0; i < buflen; i++) {
  6842. /* Do an unsigned comparison in some conditions below */
  6843. const unsigned char c = (unsigned char)buf[i];
  6844. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6845. && !isprint(c)) {
  6846. /* abort scan as soon as one malformed character is found */
  6847. return -1;
  6848. }
  6849. if (i < buflen - 1) {
  6850. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6851. /* Two newline, no carriage return - not standard compliant,
  6852. * but it should be accepted */
  6853. return i + 2;
  6854. }
  6855. }
  6856. if (i < buflen - 3) {
  6857. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6858. && (buf[i + 3] == '\n')) {
  6859. /* Two \r\n - standard compliant */
  6860. return i + 4;
  6861. }
  6862. }
  6863. }
  6864. return 0;
  6865. }
  6866. #if !defined(NO_CACHING)
  6867. /* Convert month to the month number. Return -1 on error, or month number */
  6868. static int
  6869. get_month_index(const char *s)
  6870. {
  6871. size_t i;
  6872. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6873. if (!strcmp(s, month_names[i])) {
  6874. return (int)i;
  6875. }
  6876. }
  6877. return -1;
  6878. }
  6879. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6880. static time_t
  6881. parse_date_string(const char *datetime)
  6882. {
  6883. char month_str[32] = {0};
  6884. int second, minute, hour, day, month, year;
  6885. time_t result = (time_t)0;
  6886. struct tm tm;
  6887. if ((sscanf(datetime,
  6888. "%d/%3s/%d %d:%d:%d",
  6889. &day,
  6890. month_str,
  6891. &year,
  6892. &hour,
  6893. &minute,
  6894. &second)
  6895. == 6)
  6896. || (sscanf(datetime,
  6897. "%d %3s %d %d:%d:%d",
  6898. &day,
  6899. month_str,
  6900. &year,
  6901. &hour,
  6902. &minute,
  6903. &second)
  6904. == 6)
  6905. || (sscanf(datetime,
  6906. "%*3s, %d %3s %d %d:%d:%d",
  6907. &day,
  6908. month_str,
  6909. &year,
  6910. &hour,
  6911. &minute,
  6912. &second)
  6913. == 6)
  6914. || (sscanf(datetime,
  6915. "%d-%3s-%d %d:%d:%d",
  6916. &day,
  6917. month_str,
  6918. &year,
  6919. &hour,
  6920. &minute,
  6921. &second)
  6922. == 6)) {
  6923. month = get_month_index(month_str);
  6924. if ((month >= 0) && (year >= 1970)) {
  6925. memset(&tm, 0, sizeof(tm));
  6926. tm.tm_year = year - 1900;
  6927. tm.tm_mon = month;
  6928. tm.tm_mday = day;
  6929. tm.tm_hour = hour;
  6930. tm.tm_min = minute;
  6931. tm.tm_sec = second;
  6932. result = timegm(&tm);
  6933. }
  6934. }
  6935. return result;
  6936. }
  6937. #endif /* !NO_CACHING */
  6938. /* Pre-process URIs according to RFC + protect against directory disclosure
  6939. * attacks by removing '..', excessive '/' and '\' characters */
  6940. static void
  6941. remove_dot_segments(char *inout)
  6942. {
  6943. /* Windows backend protection
  6944. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6945. * in URI by slash */
  6946. char *out_end = inout;
  6947. char *in = inout;
  6948. if (!in) {
  6949. /* Param error. */
  6950. return;
  6951. }
  6952. while (*in) {
  6953. if (*in == '\\') {
  6954. *in = '/';
  6955. }
  6956. in++;
  6957. }
  6958. /* Algorithm "remove_dot_segments" from
  6959. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6960. /* Step 1:
  6961. * The input buffer is initialized.
  6962. * The output buffer is initialized to the empty string.
  6963. */
  6964. in = inout;
  6965. /* Step 2:
  6966. * While the input buffer is not empty, loop as follows:
  6967. */
  6968. /* Less than out_end of the inout buffer is used as output, so keep
  6969. * condition: out_end <= in */
  6970. while (*in) {
  6971. /* Step 2a:
  6972. * If the input buffer begins with a prefix of "../" or "./",
  6973. * then remove that prefix from the input buffer;
  6974. */
  6975. if (!strncmp(in, "../", 3)) {
  6976. in += 3;
  6977. } else if (!strncmp(in, "./", 2)) {
  6978. in += 2;
  6979. }
  6980. /* otherwise */
  6981. /* Step 2b:
  6982. * if the input buffer begins with a prefix of "/./" or "/.",
  6983. * where "." is a complete path segment, then replace that
  6984. * prefix with "/" in the input buffer;
  6985. */
  6986. else if (!strncmp(in, "/./", 3)) {
  6987. in += 2;
  6988. } else if (!strcmp(in, "/.")) {
  6989. in[1] = 0;
  6990. }
  6991. /* otherwise */
  6992. /* Step 2c:
  6993. * if the input buffer begins with a prefix of "/../" or "/..",
  6994. * where ".." is a complete path segment, then replace that
  6995. * prefix with "/" in the input buffer and remove the last
  6996. * segment and its preceding "/" (if any) from the output
  6997. * buffer;
  6998. */
  6999. else if (!strncmp(in, "/../", 4)) {
  7000. in += 3;
  7001. if (inout != out_end) {
  7002. /* remove last segment */
  7003. do {
  7004. out_end--;
  7005. } while ((inout != out_end) && (*out_end != '/'));
  7006. }
  7007. } else if (!strcmp(in, "/..")) {
  7008. in[1] = 0;
  7009. if (inout != out_end) {
  7010. /* remove last segment */
  7011. do {
  7012. out_end--;
  7013. } while ((inout != out_end) && (*out_end != '/'));
  7014. }
  7015. }
  7016. /* otherwise */
  7017. /* Step 2d:
  7018. * if the input buffer consists only of "." or "..", then remove
  7019. * that from the input buffer;
  7020. */
  7021. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7022. *in = 0;
  7023. }
  7024. /* otherwise */
  7025. /* Step 2e:
  7026. * move the first path segment in the input buffer to the end of
  7027. * the output buffer, including the initial "/" character (if
  7028. * any) and any subsequent characters up to, but not including,
  7029. * the next "/" character or the end of the input buffer.
  7030. */
  7031. else {
  7032. do {
  7033. *out_end = *in;
  7034. out_end++;
  7035. in++;
  7036. } while ((*in != 0) && (*in != '/'));
  7037. }
  7038. }
  7039. /* Step 3:
  7040. * Finally, the output buffer is returned as the result of
  7041. * remove_dot_segments.
  7042. */
  7043. /* Terminate output */
  7044. *out_end = 0;
  7045. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7046. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7047. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7048. * or "//" anymore.
  7049. */
  7050. out_end = in = inout;
  7051. while (*in) {
  7052. if (*in == '.') {
  7053. /* remove . at the end or preceding of / */
  7054. char *in_ahead = in;
  7055. do {
  7056. in_ahead++;
  7057. } while (*in_ahead == '.');
  7058. if (*in_ahead == '/') {
  7059. in = in_ahead;
  7060. if ((out_end != inout) && (out_end[-1] == '/')) {
  7061. /* remove generated // */
  7062. out_end--;
  7063. }
  7064. } else if (*in_ahead == 0) {
  7065. in = in_ahead;
  7066. } else {
  7067. do {
  7068. *out_end++ = '.';
  7069. in++;
  7070. } while (in != in_ahead);
  7071. }
  7072. } else if (*in == '/') {
  7073. /* replace // by / */
  7074. *out_end++ = '/';
  7075. do {
  7076. in++;
  7077. } while (*in == '/');
  7078. } else {
  7079. *out_end++ = *in;
  7080. in++;
  7081. }
  7082. }
  7083. *out_end = 0;
  7084. }
  7085. static const struct {
  7086. const char *extension;
  7087. size_t ext_len;
  7088. const char *mime_type;
  7089. } builtin_mime_types[] = {
  7090. /* IANA registered MIME types
  7091. * (http://www.iana.org/assignments/media-types)
  7092. * application types */
  7093. {".doc", 4, "application/msword"},
  7094. {".eps", 4, "application/postscript"},
  7095. {".exe", 4, "application/octet-stream"},
  7096. {".js", 3, "application/javascript"},
  7097. {".json", 5, "application/json"},
  7098. {".pdf", 4, "application/pdf"},
  7099. {".ps", 3, "application/postscript"},
  7100. {".rtf", 4, "application/rtf"},
  7101. {".xhtml", 6, "application/xhtml+xml"},
  7102. {".xsl", 4, "application/xml"},
  7103. {".xslt", 5, "application/xml"},
  7104. /* fonts */
  7105. {".ttf", 4, "application/font-sfnt"},
  7106. {".cff", 4, "application/font-sfnt"},
  7107. {".otf", 4, "application/font-sfnt"},
  7108. {".aat", 4, "application/font-sfnt"},
  7109. {".sil", 4, "application/font-sfnt"},
  7110. {".pfr", 4, "application/font-tdpfr"},
  7111. {".woff", 5, "application/font-woff"},
  7112. /* audio */
  7113. {".mp3", 4, "audio/mpeg"},
  7114. {".oga", 4, "audio/ogg"},
  7115. {".ogg", 4, "audio/ogg"},
  7116. /* image */
  7117. {".gif", 4, "image/gif"},
  7118. {".ief", 4, "image/ief"},
  7119. {".jpeg", 5, "image/jpeg"},
  7120. {".jpg", 4, "image/jpeg"},
  7121. {".jpm", 4, "image/jpm"},
  7122. {".jpx", 4, "image/jpx"},
  7123. {".png", 4, "image/png"},
  7124. {".svg", 4, "image/svg+xml"},
  7125. {".tif", 4, "image/tiff"},
  7126. {".tiff", 5, "image/tiff"},
  7127. /* model */
  7128. {".wrl", 4, "model/vrml"},
  7129. /* text */
  7130. {".css", 4, "text/css"},
  7131. {".csv", 4, "text/csv"},
  7132. {".htm", 4, "text/html"},
  7133. {".html", 5, "text/html"},
  7134. {".sgm", 4, "text/sgml"},
  7135. {".shtm", 5, "text/html"},
  7136. {".shtml", 6, "text/html"},
  7137. {".txt", 4, "text/plain"},
  7138. {".xml", 4, "text/xml"},
  7139. /* video */
  7140. {".mov", 4, "video/quicktime"},
  7141. {".mp4", 4, "video/mp4"},
  7142. {".mpeg", 5, "video/mpeg"},
  7143. {".mpg", 4, "video/mpeg"},
  7144. {".ogv", 4, "video/ogg"},
  7145. {".qt", 3, "video/quicktime"},
  7146. /* not registered types
  7147. * (http://reference.sitepoint.com/html/mime-types-full,
  7148. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7149. {".arj", 4, "application/x-arj-compressed"},
  7150. {".gz", 3, "application/x-gunzip"},
  7151. {".rar", 4, "application/x-arj-compressed"},
  7152. {".swf", 4, "application/x-shockwave-flash"},
  7153. {".tar", 4, "application/x-tar"},
  7154. {".tgz", 4, "application/x-tar-gz"},
  7155. {".torrent", 8, "application/x-bittorrent"},
  7156. {".ppt", 4, "application/x-mspowerpoint"},
  7157. {".xls", 4, "application/x-msexcel"},
  7158. {".zip", 4, "application/x-zip-compressed"},
  7159. {".aac",
  7160. 4,
  7161. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7162. {".aif", 4, "audio/x-aif"},
  7163. {".m3u", 4, "audio/x-mpegurl"},
  7164. {".mid", 4, "audio/x-midi"},
  7165. {".ra", 3, "audio/x-pn-realaudio"},
  7166. {".ram", 4, "audio/x-pn-realaudio"},
  7167. {".wav", 4, "audio/x-wav"},
  7168. {".bmp", 4, "image/bmp"},
  7169. {".ico", 4, "image/x-icon"},
  7170. {".pct", 4, "image/x-pct"},
  7171. {".pict", 5, "image/pict"},
  7172. {".rgb", 4, "image/x-rgb"},
  7173. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7174. {".asf", 4, "video/x-ms-asf"},
  7175. {".avi", 4, "video/x-msvideo"},
  7176. {".m4v", 4, "video/x-m4v"},
  7177. {NULL, 0, NULL}};
  7178. const char *
  7179. mg_get_builtin_mime_type(const char *path)
  7180. {
  7181. const char *ext;
  7182. size_t i, path_len;
  7183. path_len = strlen(path);
  7184. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7185. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7186. if ((path_len > builtin_mime_types[i].ext_len)
  7187. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7188. return builtin_mime_types[i].mime_type;
  7189. }
  7190. }
  7191. return "text/plain";
  7192. }
  7193. /* Look at the "path" extension and figure what mime type it has.
  7194. * Store mime type in the vector. */
  7195. static void
  7196. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7197. {
  7198. struct vec ext_vec, mime_vec;
  7199. const char *list, *ext;
  7200. size_t path_len;
  7201. path_len = strlen(path);
  7202. if ((conn == NULL) || (vec == NULL)) {
  7203. if (vec != NULL) {
  7204. memset(vec, '\0', sizeof(struct vec));
  7205. }
  7206. return;
  7207. }
  7208. /* Scan user-defined mime types first, in case user wants to
  7209. * override default mime types. */
  7210. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7211. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7212. /* ext now points to the path suffix */
  7213. ext = path + path_len - ext_vec.len;
  7214. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7215. *vec = mime_vec;
  7216. return;
  7217. }
  7218. }
  7219. vec->ptr = mg_get_builtin_mime_type(path);
  7220. vec->len = strlen(vec->ptr);
  7221. }
  7222. /* Stringify binary data. Output buffer must be twice as big as input,
  7223. * because each byte takes 2 bytes in string representation */
  7224. static void
  7225. bin2str(char *to, const unsigned char *p, size_t len)
  7226. {
  7227. static const char *hex = "0123456789abcdef";
  7228. for (; len--; p++) {
  7229. *to++ = hex[p[0] >> 4];
  7230. *to++ = hex[p[0] & 0x0f];
  7231. }
  7232. *to = '\0';
  7233. }
  7234. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7235. */
  7236. char *
  7237. mg_md5(char buf[33], ...)
  7238. {
  7239. md5_byte_t hash[16];
  7240. const char *p;
  7241. va_list ap;
  7242. md5_state_t ctx;
  7243. md5_init(&ctx);
  7244. va_start(ap, buf);
  7245. while ((p = va_arg(ap, const char *)) != NULL) {
  7246. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7247. }
  7248. va_end(ap);
  7249. md5_finish(&ctx, hash);
  7250. bin2str(buf, hash, sizeof(hash));
  7251. return buf;
  7252. }
  7253. /* Check the user's password, return 1 if OK */
  7254. static int
  7255. check_password(const char *method,
  7256. const char *ha1,
  7257. const char *uri,
  7258. const char *nonce,
  7259. const char *nc,
  7260. const char *cnonce,
  7261. const char *qop,
  7262. const char *response)
  7263. {
  7264. char ha2[32 + 1], expected_response[32 + 1];
  7265. /* Some of the parameters may be NULL */
  7266. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7267. || (qop == NULL) || (response == NULL)) {
  7268. return 0;
  7269. }
  7270. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7271. if (strlen(response) != 32) {
  7272. return 0;
  7273. }
  7274. mg_md5(ha2, method, ":", uri, NULL);
  7275. mg_md5(expected_response,
  7276. ha1,
  7277. ":",
  7278. nonce,
  7279. ":",
  7280. nc,
  7281. ":",
  7282. cnonce,
  7283. ":",
  7284. qop,
  7285. ":",
  7286. ha2,
  7287. NULL);
  7288. return mg_strcasecmp(response, expected_response) == 0;
  7289. }
  7290. #if !defined(NO_FILESYSTEMS)
  7291. /* Use the global passwords file, if specified by auth_gpass option,
  7292. * or search for .htpasswd in the requested directory. */
  7293. static void
  7294. open_auth_file(struct mg_connection *conn,
  7295. const char *path,
  7296. struct mg_file *filep)
  7297. {
  7298. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7299. char name[PATH_MAX];
  7300. const char *p, *e,
  7301. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7302. int truncated;
  7303. if (gpass != NULL) {
  7304. /* Use global passwords file */
  7305. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7306. #if defined(DEBUG)
  7307. /* Use mg_cry_internal here, since gpass has been
  7308. * configured. */
  7309. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7310. #endif
  7311. }
  7312. /* Important: using local struct mg_file to test path for
  7313. * is_directory flag. If filep is used, mg_stat() makes it
  7314. * appear as if auth file was opened.
  7315. * TODO(mid): Check if this is still required after rewriting
  7316. * mg_stat */
  7317. } else if (mg_stat(conn, path, &filep->stat)
  7318. && filep->stat.is_directory) {
  7319. mg_snprintf(conn,
  7320. &truncated,
  7321. name,
  7322. sizeof(name),
  7323. "%s/%s",
  7324. path,
  7325. PASSWORDS_FILE_NAME);
  7326. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7327. #if defined(DEBUG)
  7328. /* Don't use mg_cry_internal here, but only a trace, since
  7329. * this is a typical case. It will occur for every directory
  7330. * without a password file. */
  7331. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7332. #endif
  7333. }
  7334. } else {
  7335. /* Try to find .htpasswd in requested directory. */
  7336. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7337. if (e[0] == '/') {
  7338. break;
  7339. }
  7340. }
  7341. mg_snprintf(conn,
  7342. &truncated,
  7343. name,
  7344. sizeof(name),
  7345. "%.*s/%s",
  7346. (int)(e - p),
  7347. p,
  7348. PASSWORDS_FILE_NAME);
  7349. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7350. #if defined(DEBUG)
  7351. /* Don't use mg_cry_internal here, but only a trace, since
  7352. * this is a typical case. It will occur for every directory
  7353. * without a password file. */
  7354. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7355. #endif
  7356. }
  7357. }
  7358. }
  7359. }
  7360. #endif /* NO_FILESYSTEMS */
  7361. /* Parsed Authorization header */
  7362. struct ah {
  7363. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7364. };
  7365. /* Return 1 on success. Always initializes the ah structure. */
  7366. static int
  7367. parse_auth_header(struct mg_connection *conn,
  7368. char *buf,
  7369. size_t buf_size,
  7370. struct ah *ah)
  7371. {
  7372. char *name, *value, *s;
  7373. const char *auth_header;
  7374. uint64_t nonce;
  7375. if (!ah || !conn) {
  7376. return 0;
  7377. }
  7378. (void)memset(ah, 0, sizeof(*ah));
  7379. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7380. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7381. return 0;
  7382. }
  7383. /* Make modifiable copy of the auth header */
  7384. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7385. s = buf;
  7386. /* Parse authorization header */
  7387. for (;;) {
  7388. /* Gobble initial spaces */
  7389. while (isspace((unsigned char)*s)) {
  7390. s++;
  7391. }
  7392. name = skip_quoted(&s, "=", " ", 0);
  7393. /* Value is either quote-delimited, or ends at first comma or space.
  7394. */
  7395. if (s[0] == '\"') {
  7396. s++;
  7397. value = skip_quoted(&s, "\"", " ", '\\');
  7398. if (s[0] == ',') {
  7399. s++;
  7400. }
  7401. } else {
  7402. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7403. * uses spaces */
  7404. }
  7405. if (*name == '\0') {
  7406. break;
  7407. }
  7408. if (!strcmp(name, "username")) {
  7409. ah->user = value;
  7410. } else if (!strcmp(name, "cnonce")) {
  7411. ah->cnonce = value;
  7412. } else if (!strcmp(name, "response")) {
  7413. ah->response = value;
  7414. } else if (!strcmp(name, "uri")) {
  7415. ah->uri = value;
  7416. } else if (!strcmp(name, "qop")) {
  7417. ah->qop = value;
  7418. } else if (!strcmp(name, "nc")) {
  7419. ah->nc = value;
  7420. } else if (!strcmp(name, "nonce")) {
  7421. ah->nonce = value;
  7422. }
  7423. }
  7424. #if !defined(NO_NONCE_CHECK)
  7425. /* Read the nonce from the response. */
  7426. if (ah->nonce == NULL) {
  7427. return 0;
  7428. }
  7429. s = NULL;
  7430. nonce = strtoull(ah->nonce, &s, 10);
  7431. if ((s == NULL) || (*s != 0)) {
  7432. return 0;
  7433. }
  7434. /* Convert the nonce from the client to a number. */
  7435. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7436. /* The converted number corresponds to the time the nounce has been
  7437. * created. This should not be earlier than the server start. */
  7438. /* Server side nonce check is valuable in all situations but one:
  7439. * if the server restarts frequently, but the client should not see
  7440. * that, so the server should accept nonces from previous starts. */
  7441. /* However, the reasonable default is to not accept a nonce from a
  7442. * previous start, so if anyone changed the access rights between
  7443. * two restarts, a new login is required. */
  7444. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7445. /* nonce is from a previous start of the server and no longer valid
  7446. * (replay attack?) */
  7447. return 0;
  7448. }
  7449. /* Check if the nonce is too high, so it has not (yet) been used by the
  7450. * server. */
  7451. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7452. + conn->dom_ctx->nonce_count)) {
  7453. return 0;
  7454. }
  7455. #else
  7456. (void)nonce;
  7457. #endif
  7458. /* CGI needs it as REMOTE_USER */
  7459. if (ah->user != NULL) {
  7460. conn->request_info.remote_user =
  7461. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7462. } else {
  7463. return 0;
  7464. }
  7465. return 1;
  7466. }
  7467. static const char *
  7468. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7469. {
  7470. #if defined(MG_USE_OPEN_FILE)
  7471. const char *eof;
  7472. size_t len;
  7473. const char *memend;
  7474. #else
  7475. (void)p; /* parameter is unused */
  7476. #endif
  7477. if (!filep) {
  7478. return NULL;
  7479. }
  7480. #if defined(MG_USE_OPEN_FILE)
  7481. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7482. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7483. /* Search for \n from p till the end of stream */
  7484. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7485. if (eof != NULL) {
  7486. eof += 1; /* Include \n */
  7487. } else {
  7488. eof = memend; /* Copy remaining data */
  7489. }
  7490. len =
  7491. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7492. memcpy(buf, *p, len);
  7493. buf[len] = '\0';
  7494. *p += len;
  7495. return len ? eof : NULL;
  7496. } else /* filep->access.fp block below */
  7497. #endif
  7498. if (filep->access.fp != NULL) {
  7499. return fgets(buf, (int)size, filep->access.fp);
  7500. } else {
  7501. return NULL;
  7502. }
  7503. }
  7504. /* Define the initial recursion depth for procesesing htpasswd files that
  7505. * include other htpasswd
  7506. * (or even the same) files. It is not difficult to provide a file or files
  7507. * s.t. they force civetweb
  7508. * to infinitely recurse and then crash.
  7509. */
  7510. #define INITIAL_DEPTH 9
  7511. #if INITIAL_DEPTH <= 0
  7512. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7513. #endif
  7514. #if !defined(NO_FILESYSTEMS)
  7515. struct read_auth_file_struct {
  7516. struct mg_connection *conn;
  7517. struct ah ah;
  7518. const char *domain;
  7519. char buf[256 + 256 + 40];
  7520. const char *f_user;
  7521. const char *f_domain;
  7522. const char *f_ha1;
  7523. };
  7524. static int
  7525. read_auth_file(struct mg_file *filep,
  7526. struct read_auth_file_struct *workdata,
  7527. int depth)
  7528. {
  7529. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7530. int is_authorized = 0;
  7531. struct mg_file fp;
  7532. size_t l;
  7533. if (!filep || !workdata || (0 == depth)) {
  7534. return 0;
  7535. }
  7536. /* Loop over passwords file */
  7537. #if defined(MG_USE_OPEN_FILE)
  7538. p = (char *)filep->access.membuf;
  7539. #endif
  7540. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7541. l = strlen(workdata->buf);
  7542. while (l > 0) {
  7543. if (isspace((unsigned char)workdata->buf[l - 1])
  7544. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7545. l--;
  7546. workdata->buf[l] = 0;
  7547. } else
  7548. break;
  7549. }
  7550. if (l < 1) {
  7551. continue;
  7552. }
  7553. workdata->f_user = workdata->buf;
  7554. if (workdata->f_user[0] == ':') {
  7555. /* user names may not contain a ':' and may not be empty,
  7556. * so lines starting with ':' may be used for a special purpose
  7557. */
  7558. if (workdata->f_user[1] == '#') {
  7559. /* :# is a comment */
  7560. continue;
  7561. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7562. if (mg_fopen(workdata->conn,
  7563. workdata->f_user + 9,
  7564. MG_FOPEN_MODE_READ,
  7565. &fp)) {
  7566. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7567. (void)mg_fclose(
  7568. &fp.access); /* ignore error on read only file */
  7569. /* No need to continue processing files once we have a
  7570. * match, since nothing will reset it back
  7571. * to 0.
  7572. */
  7573. if (is_authorized) {
  7574. return is_authorized;
  7575. }
  7576. } else {
  7577. mg_cry_internal(workdata->conn,
  7578. "%s: cannot open authorization file: %s",
  7579. __func__,
  7580. workdata->buf);
  7581. }
  7582. continue;
  7583. }
  7584. /* everything is invalid for the moment (might change in the
  7585. * future) */
  7586. mg_cry_internal(workdata->conn,
  7587. "%s: syntax error in authorization file: %s",
  7588. __func__,
  7589. workdata->buf);
  7590. continue;
  7591. }
  7592. workdata->f_domain = strchr(workdata->f_user, ':');
  7593. if (workdata->f_domain == NULL) {
  7594. mg_cry_internal(workdata->conn,
  7595. "%s: syntax error in authorization file: %s",
  7596. __func__,
  7597. workdata->buf);
  7598. continue;
  7599. }
  7600. *(char *)(workdata->f_domain) = 0;
  7601. (workdata->f_domain)++;
  7602. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7603. if (workdata->f_ha1 == NULL) {
  7604. mg_cry_internal(workdata->conn,
  7605. "%s: syntax error in authorization file: %s",
  7606. __func__,
  7607. workdata->buf);
  7608. continue;
  7609. }
  7610. *(char *)(workdata->f_ha1) = 0;
  7611. (workdata->f_ha1)++;
  7612. if (!strcmp(workdata->ah.user, workdata->f_user)
  7613. && !strcmp(workdata->domain, workdata->f_domain)) {
  7614. return check_password(workdata->conn->request_info.request_method,
  7615. workdata->f_ha1,
  7616. workdata->ah.uri,
  7617. workdata->ah.nonce,
  7618. workdata->ah.nc,
  7619. workdata->ah.cnonce,
  7620. workdata->ah.qop,
  7621. workdata->ah.response);
  7622. }
  7623. }
  7624. return is_authorized;
  7625. }
  7626. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7627. static int
  7628. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7629. {
  7630. struct read_auth_file_struct workdata;
  7631. char buf[MG_BUF_LEN];
  7632. if (!conn || !conn->dom_ctx) {
  7633. return 0;
  7634. }
  7635. memset(&workdata, 0, sizeof(workdata));
  7636. workdata.conn = conn;
  7637. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7638. return 0;
  7639. }
  7640. if (realm) {
  7641. workdata.domain = realm;
  7642. } else {
  7643. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7644. }
  7645. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7646. }
  7647. /* Public function to check http digest authentication header */
  7648. int
  7649. mg_check_digest_access_authentication(struct mg_connection *conn,
  7650. const char *realm,
  7651. const char *filename)
  7652. {
  7653. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7654. int auth;
  7655. if (!conn || !filename) {
  7656. return -1;
  7657. }
  7658. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7659. return -2;
  7660. }
  7661. auth = authorize(conn, &file, realm);
  7662. mg_fclose(&file.access);
  7663. return auth;
  7664. }
  7665. #endif /* NO_FILESYSTEMS */
  7666. /* Return 1 if request is authorised, 0 otherwise. */
  7667. static int
  7668. check_authorization(struct mg_connection *conn, const char *path)
  7669. {
  7670. #if !defined(NO_FILESYSTEMS)
  7671. char fname[PATH_MAX];
  7672. struct vec uri_vec, filename_vec;
  7673. const char *list;
  7674. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7675. int authorized = 1, truncated;
  7676. if (!conn || !conn->dom_ctx) {
  7677. return 0;
  7678. }
  7679. list = conn->dom_ctx->config[PROTECT_URI];
  7680. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7681. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7682. mg_snprintf(conn,
  7683. &truncated,
  7684. fname,
  7685. sizeof(fname),
  7686. "%.*s",
  7687. (int)filename_vec.len,
  7688. filename_vec.ptr);
  7689. if (truncated
  7690. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7691. mg_cry_internal(conn,
  7692. "%s: cannot open %s: %s",
  7693. __func__,
  7694. fname,
  7695. strerror(errno));
  7696. }
  7697. break;
  7698. }
  7699. }
  7700. if (!is_file_opened(&file.access)) {
  7701. open_auth_file(conn, path, &file);
  7702. }
  7703. if (is_file_opened(&file.access)) {
  7704. authorized = authorize(conn, &file, NULL);
  7705. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7706. }
  7707. return authorized;
  7708. #else
  7709. (void)conn;
  7710. (void)path;
  7711. return 1;
  7712. #endif /* NO_FILESYSTEMS */
  7713. }
  7714. /* Internal function. Assumes conn is valid */
  7715. static void
  7716. send_authorization_request(struct mg_connection *conn, const char *realm)
  7717. {
  7718. char date[64];
  7719. time_t curtime = time(NULL);
  7720. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7721. if (!realm) {
  7722. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7723. }
  7724. mg_lock_context(conn->phys_ctx);
  7725. nonce += conn->dom_ctx->nonce_count;
  7726. ++conn->dom_ctx->nonce_count;
  7727. mg_unlock_context(conn->phys_ctx);
  7728. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7729. conn->status_code = 401;
  7730. conn->must_close = 1;
  7731. gmt_time_string(date, sizeof(date), &curtime);
  7732. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7733. send_no_cache_header(conn);
  7734. send_additional_header(conn);
  7735. mg_printf(conn,
  7736. "Date: %s\r\n"
  7737. "Connection: %s\r\n"
  7738. "Content-Length: 0\r\n"
  7739. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7740. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7741. date,
  7742. suggest_connection_header(conn),
  7743. realm,
  7744. nonce);
  7745. }
  7746. /* Interface function. Parameters are provided by the user, so do
  7747. * at least some basic checks.
  7748. */
  7749. int
  7750. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7751. const char *realm)
  7752. {
  7753. if (conn && conn->dom_ctx) {
  7754. send_authorization_request(conn, realm);
  7755. return 0;
  7756. }
  7757. return -1;
  7758. }
  7759. #if !defined(NO_FILES)
  7760. static int
  7761. is_authorized_for_put(struct mg_connection *conn)
  7762. {
  7763. if (conn) {
  7764. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7765. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7766. int ret = 0;
  7767. if (passfile != NULL
  7768. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7769. ret = authorize(conn, &file, NULL);
  7770. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7771. }
  7772. return ret;
  7773. }
  7774. return 0;
  7775. }
  7776. #endif
  7777. int
  7778. mg_modify_passwords_file(const char *fname,
  7779. const char *domain,
  7780. const char *user,
  7781. const char *pass)
  7782. {
  7783. int found, i;
  7784. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7785. FILE *fp, *fp2;
  7786. found = 0;
  7787. fp = fp2 = NULL;
  7788. /* Regard empty password as no password - remove user record. */
  7789. if ((pass != NULL) && (pass[0] == '\0')) {
  7790. pass = NULL;
  7791. }
  7792. /* Other arguments must not be empty */
  7793. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7794. return 0;
  7795. }
  7796. /* Using the given file format, user name and domain must not contain
  7797. * ':'
  7798. */
  7799. if (strchr(user, ':') != NULL) {
  7800. return 0;
  7801. }
  7802. if (strchr(domain, ':') != NULL) {
  7803. return 0;
  7804. }
  7805. /* Do not allow control characters like newline in user name and domain.
  7806. * Do not allow excessively long names either. */
  7807. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7808. if (iscntrl((unsigned char)user[i])) {
  7809. return 0;
  7810. }
  7811. }
  7812. if (user[i]) {
  7813. return 0;
  7814. }
  7815. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7816. if (iscntrl((unsigned char)domain[i])) {
  7817. return 0;
  7818. }
  7819. }
  7820. if (domain[i]) {
  7821. return 0;
  7822. }
  7823. /* The maximum length of the path to the password file is limited */
  7824. if ((strlen(fname) + 4) >= PATH_MAX) {
  7825. return 0;
  7826. }
  7827. /* Create a temporary file name. Length has been checked before. */
  7828. strcpy(tmp, fname);
  7829. strcat(tmp, ".tmp");
  7830. /* Create the file if does not exist */
  7831. /* Use of fopen here is OK, since fname is only ASCII */
  7832. if ((fp = fopen(fname, "a+")) != NULL) {
  7833. (void)fclose(fp);
  7834. }
  7835. /* Open the given file and temporary file */
  7836. if ((fp = fopen(fname, "r")) == NULL) {
  7837. return 0;
  7838. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7839. fclose(fp);
  7840. return 0;
  7841. }
  7842. /* Copy the stuff to temporary file */
  7843. while (fgets(line, sizeof(line), fp) != NULL) {
  7844. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7845. continue;
  7846. }
  7847. u[255] = 0;
  7848. d[255] = 0;
  7849. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7850. found++;
  7851. if (pass != NULL) {
  7852. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7853. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7854. }
  7855. } else {
  7856. fprintf(fp2, "%s", line);
  7857. }
  7858. }
  7859. /* If new user, just add it */
  7860. if (!found && (pass != NULL)) {
  7861. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7862. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7863. }
  7864. /* Close files */
  7865. fclose(fp);
  7866. fclose(fp2);
  7867. /* Put the temp file in place of real file */
  7868. IGNORE_UNUSED_RESULT(remove(fname));
  7869. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7870. return 1;
  7871. }
  7872. static int
  7873. is_valid_port(unsigned long port)
  7874. {
  7875. return (port <= 0xffff);
  7876. }
  7877. static int
  7878. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7879. {
  7880. struct addrinfo hints, *res, *ressave;
  7881. int func_ret = 0;
  7882. int gai_ret;
  7883. memset(&hints, 0, sizeof(struct addrinfo));
  7884. hints.ai_family = af;
  7885. if (!resolve_src) {
  7886. hints.ai_flags = AI_NUMERICHOST;
  7887. }
  7888. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7889. if (gai_ret != 0) {
  7890. /* gai_strerror could be used to convert gai_ret to a string */
  7891. /* POSIX return values: see
  7892. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7893. */
  7894. /* Windows return values: see
  7895. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7896. */
  7897. return 0;
  7898. }
  7899. ressave = res;
  7900. while (res) {
  7901. if ((dstlen >= (size_t)res->ai_addrlen)
  7902. && (res->ai_addr->sa_family == af)) {
  7903. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7904. func_ret = 1;
  7905. }
  7906. res = res->ai_next;
  7907. }
  7908. freeaddrinfo(ressave);
  7909. return func_ret;
  7910. }
  7911. static int
  7912. connect_socket(struct mg_context *ctx /* may be NULL */,
  7913. const char *host,
  7914. int port,
  7915. int use_ssl,
  7916. char *ebuf,
  7917. size_t ebuf_len,
  7918. SOCKET *sock /* output: socket, must not be NULL */,
  7919. union usa *sa /* output: socket address, must not be NULL */
  7920. )
  7921. {
  7922. int ip_ver = 0;
  7923. int conn_ret = -1;
  7924. int sockerr = 0;
  7925. *sock = INVALID_SOCKET;
  7926. memset(sa, 0, sizeof(*sa));
  7927. if (ebuf_len > 0) {
  7928. *ebuf = 0;
  7929. }
  7930. if (host == NULL) {
  7931. mg_snprintf(NULL,
  7932. NULL, /* No truncation check for ebuf */
  7933. ebuf,
  7934. ebuf_len,
  7935. "%s",
  7936. "NULL host");
  7937. return 0;
  7938. }
  7939. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7940. mg_snprintf(NULL,
  7941. NULL, /* No truncation check for ebuf */
  7942. ebuf,
  7943. ebuf_len,
  7944. "%s",
  7945. "invalid port");
  7946. return 0;
  7947. }
  7948. #if !defined(NO_SSL)
  7949. #if !defined(NO_SSL_DL)
  7950. #if defined(OPENSSL_API_1_1)
  7951. if (use_ssl && (TLS_client_method == NULL)) {
  7952. mg_snprintf(NULL,
  7953. NULL, /* No truncation check for ebuf */
  7954. ebuf,
  7955. ebuf_len,
  7956. "%s",
  7957. "SSL is not initialized");
  7958. return 0;
  7959. }
  7960. #else
  7961. if (use_ssl && (SSLv23_client_method == NULL)) {
  7962. mg_snprintf(NULL,
  7963. NULL, /* No truncation check for ebuf */
  7964. ebuf,
  7965. ebuf_len,
  7966. "%s",
  7967. "SSL is not initialized");
  7968. return 0;
  7969. }
  7970. #endif /* OPENSSL_API_1_1 */
  7971. #else
  7972. (void)use_ssl;
  7973. #endif /* NO_SSL_DL */
  7974. #else
  7975. (void)use_ssl;
  7976. #endif /* !defined(NO_SSL) */
  7977. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7978. sa->sin.sin_port = htons((uint16_t)port);
  7979. ip_ver = 4;
  7980. #if defined(USE_IPV6)
  7981. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7982. sa->sin6.sin6_port = htons((uint16_t)port);
  7983. ip_ver = 6;
  7984. } else if (host[0] == '[') {
  7985. /* While getaddrinfo on Windows will work with [::1],
  7986. * getaddrinfo on Linux only works with ::1 (without []). */
  7987. size_t l = strlen(host + 1);
  7988. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7989. if (h) {
  7990. h[l - 1] = 0;
  7991. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7992. sa->sin6.sin6_port = htons((uint16_t)port);
  7993. ip_ver = 6;
  7994. }
  7995. mg_free(h);
  7996. }
  7997. #endif
  7998. }
  7999. if (ip_ver == 0) {
  8000. mg_snprintf(NULL,
  8001. NULL, /* No truncation check for ebuf */
  8002. ebuf,
  8003. ebuf_len,
  8004. "%s",
  8005. "host not found");
  8006. return 0;
  8007. }
  8008. if (ip_ver == 4) {
  8009. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8010. }
  8011. #if defined(USE_IPV6)
  8012. else if (ip_ver == 6) {
  8013. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8014. }
  8015. #endif
  8016. if (*sock == INVALID_SOCKET) {
  8017. mg_snprintf(NULL,
  8018. NULL, /* No truncation check for ebuf */
  8019. ebuf,
  8020. ebuf_len,
  8021. "socket(): %s",
  8022. strerror(ERRNO));
  8023. return 0;
  8024. }
  8025. if (0 != set_non_blocking_mode(*sock)) {
  8026. mg_snprintf(NULL,
  8027. NULL, /* No truncation check for ebuf */
  8028. ebuf,
  8029. ebuf_len,
  8030. "Cannot set socket to non-blocking: %s",
  8031. strerror(ERRNO));
  8032. closesocket(*sock);
  8033. *sock = INVALID_SOCKET;
  8034. return 0;
  8035. }
  8036. set_close_on_exec(*sock, NULL, ctx);
  8037. if (ip_ver == 4) {
  8038. /* connected with IPv4 */
  8039. conn_ret = connect(*sock,
  8040. (struct sockaddr *)((void *)&sa->sin),
  8041. sizeof(sa->sin));
  8042. }
  8043. #if defined(USE_IPV6)
  8044. else if (ip_ver == 6) {
  8045. /* connected with IPv6 */
  8046. conn_ret = connect(*sock,
  8047. (struct sockaddr *)((void *)&sa->sin6),
  8048. sizeof(sa->sin6));
  8049. }
  8050. #endif
  8051. if (conn_ret != 0) {
  8052. sockerr = ERRNO;
  8053. }
  8054. #if defined(_WIN32)
  8055. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8056. #else
  8057. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8058. #endif
  8059. /* Data for getsockopt */
  8060. void *psockerr = &sockerr;
  8061. int ret;
  8062. #if defined(_WIN32)
  8063. int len = (int)sizeof(sockerr);
  8064. #else
  8065. socklen_t len = (socklen_t)sizeof(sockerr);
  8066. #endif
  8067. /* Data for poll */
  8068. struct mg_pollfd pfd[1];
  8069. int pollres;
  8070. int ms_wait = 10000; /* 10 second timeout */
  8071. stop_flag_t nonstop;
  8072. STOP_FLAG_ASSIGN(&nonstop, 0);
  8073. /* For a non-blocking socket, the connect sequence is:
  8074. * 1) call connect (will not block)
  8075. * 2) wait until the socket is ready for writing (select or poll)
  8076. * 3) check connection state with getsockopt
  8077. */
  8078. pfd[0].fd = *sock;
  8079. pfd[0].events = POLLOUT;
  8080. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8081. if (pollres != 1) {
  8082. /* Not connected */
  8083. mg_snprintf(NULL,
  8084. NULL, /* No truncation check for ebuf */
  8085. ebuf,
  8086. ebuf_len,
  8087. "connect(%s:%d): timeout",
  8088. host,
  8089. port);
  8090. closesocket(*sock);
  8091. *sock = INVALID_SOCKET;
  8092. return 0;
  8093. }
  8094. #if defined(_WIN32)
  8095. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8096. #else
  8097. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8098. #endif
  8099. if ((ret == 0) && (sockerr == 0)) {
  8100. conn_ret = 0;
  8101. }
  8102. }
  8103. if (conn_ret != 0) {
  8104. /* Not connected */
  8105. mg_snprintf(NULL,
  8106. NULL, /* No truncation check for ebuf */
  8107. ebuf,
  8108. ebuf_len,
  8109. "connect(%s:%d): error %s",
  8110. host,
  8111. port,
  8112. strerror(sockerr));
  8113. closesocket(*sock);
  8114. *sock = INVALID_SOCKET;
  8115. return 0;
  8116. }
  8117. return 1;
  8118. }
  8119. int
  8120. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8121. {
  8122. static const char *dont_escape = "._-$,;~()";
  8123. static const char *hex = "0123456789abcdef";
  8124. char *pos = dst;
  8125. const char *end = dst + dst_len - 1;
  8126. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8127. if (isalnum((unsigned char)*src)
  8128. || (strchr(dont_escape, *src) != NULL)) {
  8129. *pos = *src;
  8130. } else if (pos + 2 < end) {
  8131. pos[0] = '%';
  8132. pos[1] = hex[(unsigned char)*src >> 4];
  8133. pos[2] = hex[(unsigned char)*src & 0xf];
  8134. pos += 2;
  8135. } else {
  8136. break;
  8137. }
  8138. }
  8139. *pos = '\0';
  8140. return (*src == '\0') ? (int)(pos - dst) : -1;
  8141. }
  8142. /* Return 0 on success, non-zero if an error occurs. */
  8143. static int
  8144. print_dir_entry(struct de *de)
  8145. {
  8146. size_t namesize, escsize, i;
  8147. char *href, *esc, *p;
  8148. char size[64], mod[64];
  8149. #if defined(REENTRANT_TIME)
  8150. struct tm _tm;
  8151. struct tm *tm = &_tm;
  8152. #else
  8153. struct tm *tm;
  8154. #endif
  8155. /* Estimate worst case size for encoding and escaping */
  8156. namesize = strlen(de->file_name) + 1;
  8157. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8158. href = (char *)mg_malloc(namesize * 3 + escsize);
  8159. if (href == NULL) {
  8160. return -1;
  8161. }
  8162. mg_url_encode(de->file_name, href, namesize * 3);
  8163. esc = NULL;
  8164. if (escsize > 0) {
  8165. /* HTML escaping needed */
  8166. esc = href + namesize * 3;
  8167. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8168. mg_strlcpy(p, de->file_name + i, 2);
  8169. if (*p == '&') {
  8170. strcpy(p, "&amp;");
  8171. } else if (*p == '<') {
  8172. strcpy(p, "&lt;");
  8173. } else if (*p == '>') {
  8174. strcpy(p, "&gt;");
  8175. }
  8176. }
  8177. }
  8178. if (de->file.is_directory) {
  8179. mg_snprintf(de->conn,
  8180. NULL, /* Buffer is big enough */
  8181. size,
  8182. sizeof(size),
  8183. "%s",
  8184. "[DIRECTORY]");
  8185. } else {
  8186. /* We use (signed) cast below because MSVC 6 compiler cannot
  8187. * convert unsigned __int64 to double. Sigh. */
  8188. if (de->file.size < 1024) {
  8189. mg_snprintf(de->conn,
  8190. NULL, /* Buffer is big enough */
  8191. size,
  8192. sizeof(size),
  8193. "%d",
  8194. (int)de->file.size);
  8195. } else if (de->file.size < 0x100000) {
  8196. mg_snprintf(de->conn,
  8197. NULL, /* Buffer is big enough */
  8198. size,
  8199. sizeof(size),
  8200. "%.1fk",
  8201. (double)de->file.size / 1024.0);
  8202. } else if (de->file.size < 0x40000000) {
  8203. mg_snprintf(de->conn,
  8204. NULL, /* Buffer is big enough */
  8205. size,
  8206. sizeof(size),
  8207. "%.1fM",
  8208. (double)de->file.size / 1048576);
  8209. } else {
  8210. mg_snprintf(de->conn,
  8211. NULL, /* Buffer is big enough */
  8212. size,
  8213. sizeof(size),
  8214. "%.1fG",
  8215. (double)de->file.size / 1073741824);
  8216. }
  8217. }
  8218. /* Note: mg_snprintf will not cause a buffer overflow above.
  8219. * So, string truncation checks are not required here. */
  8220. #if defined(REENTRANT_TIME)
  8221. localtime_r(&de->file.last_modified, tm);
  8222. #else
  8223. tm = localtime(&de->file.last_modified);
  8224. #endif
  8225. if (tm != NULL) {
  8226. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8227. } else {
  8228. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8229. mod[sizeof(mod) - 1] = '\0';
  8230. }
  8231. mg_printf(de->conn,
  8232. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8233. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8234. href,
  8235. de->file.is_directory ? "/" : "",
  8236. esc ? esc : de->file_name,
  8237. de->file.is_directory ? "/" : "",
  8238. mod,
  8239. size);
  8240. mg_free(href);
  8241. return 0;
  8242. }
  8243. /* This function is called from send_directory() and used for
  8244. * sorting directory entries by size, or name, or modification time.
  8245. * On windows, __cdecl specification is needed in case if project is built
  8246. * with __stdcall convention. qsort always requires __cdels callback. */
  8247. static int WINCDECL
  8248. compare_dir_entries(const void *p1, const void *p2)
  8249. {
  8250. if (p1 && p2) {
  8251. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8252. const char *query_string = a->conn->request_info.query_string;
  8253. int cmp_result = 0;
  8254. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8255. query_string = "n";
  8256. }
  8257. if (a->file.is_directory && !b->file.is_directory) {
  8258. return -1; /* Always put directories on top */
  8259. } else if (!a->file.is_directory && b->file.is_directory) {
  8260. return 1; /* Always put directories on top */
  8261. } else if (*query_string == 'n') {
  8262. cmp_result = strcmp(a->file_name, b->file_name);
  8263. } else if (*query_string == 's') {
  8264. cmp_result = (a->file.size == b->file.size)
  8265. ? 0
  8266. : ((a->file.size > b->file.size) ? 1 : -1);
  8267. } else if (*query_string == 'd') {
  8268. cmp_result =
  8269. (a->file.last_modified == b->file.last_modified)
  8270. ? 0
  8271. : ((a->file.last_modified > b->file.last_modified) ? 1
  8272. : -1);
  8273. }
  8274. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8275. }
  8276. return 0;
  8277. }
  8278. static int
  8279. must_hide_file(struct mg_connection *conn, const char *path)
  8280. {
  8281. if (conn && conn->dom_ctx) {
  8282. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8283. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8284. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8285. || ((pattern != NULL)
  8286. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8287. }
  8288. return 0;
  8289. }
  8290. #if !defined(NO_FILESYSTEMS)
  8291. static int
  8292. scan_directory(struct mg_connection *conn,
  8293. const char *dir,
  8294. void *data,
  8295. int (*cb)(struct de *, void *))
  8296. {
  8297. char path[PATH_MAX];
  8298. struct dirent *dp;
  8299. DIR *dirp;
  8300. struct de de;
  8301. int truncated;
  8302. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8303. return 0;
  8304. } else {
  8305. de.conn = conn;
  8306. while ((dp = mg_readdir(dirp)) != NULL) {
  8307. /* Do not show current dir and hidden files */
  8308. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8309. || must_hide_file(conn, dp->d_name)) {
  8310. continue;
  8311. }
  8312. mg_snprintf(
  8313. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8314. /* If we don't memset stat structure to zero, mtime will have
  8315. * garbage and strftime() will segfault later on in
  8316. * print_dir_entry(). memset is required only if mg_stat()
  8317. * fails. For more details, see
  8318. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8319. memset(&de.file, 0, sizeof(de.file));
  8320. if (truncated) {
  8321. /* If the path is not complete, skip processing. */
  8322. continue;
  8323. }
  8324. if (!mg_stat(conn, path, &de.file)) {
  8325. mg_cry_internal(conn,
  8326. "%s: mg_stat(%s) failed: %s",
  8327. __func__,
  8328. path,
  8329. strerror(ERRNO));
  8330. }
  8331. de.file_name = dp->d_name;
  8332. cb(&de, data);
  8333. }
  8334. (void)mg_closedir(dirp);
  8335. }
  8336. return 1;
  8337. }
  8338. #endif /* NO_FILESYSTEMS */
  8339. #if !defined(NO_FILES)
  8340. static int
  8341. remove_directory(struct mg_connection *conn, const char *dir)
  8342. {
  8343. char path[PATH_MAX];
  8344. struct dirent *dp;
  8345. DIR *dirp;
  8346. struct de de;
  8347. int truncated;
  8348. int ok = 1;
  8349. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8350. return 0;
  8351. } else {
  8352. de.conn = conn;
  8353. while ((dp = mg_readdir(dirp)) != NULL) {
  8354. /* Do not show current dir (but show hidden files as they will
  8355. * also be removed) */
  8356. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8357. continue;
  8358. }
  8359. mg_snprintf(
  8360. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8361. /* If we don't memset stat structure to zero, mtime will have
  8362. * garbage and strftime() will segfault later on in
  8363. * print_dir_entry(). memset is required only if mg_stat()
  8364. * fails. For more details, see
  8365. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8366. memset(&de.file, 0, sizeof(de.file));
  8367. if (truncated) {
  8368. /* Do not delete anything shorter */
  8369. ok = 0;
  8370. continue;
  8371. }
  8372. if (!mg_stat(conn, path, &de.file)) {
  8373. mg_cry_internal(conn,
  8374. "%s: mg_stat(%s) failed: %s",
  8375. __func__,
  8376. path,
  8377. strerror(ERRNO));
  8378. ok = 0;
  8379. }
  8380. if (de.file.is_directory) {
  8381. if (remove_directory(conn, path) == 0) {
  8382. ok = 0;
  8383. }
  8384. } else {
  8385. /* This will fail file is the file is in memory */
  8386. if (mg_remove(conn, path) == 0) {
  8387. ok = 0;
  8388. }
  8389. }
  8390. }
  8391. (void)mg_closedir(dirp);
  8392. IGNORE_UNUSED_RESULT(rmdir(dir));
  8393. }
  8394. return ok;
  8395. }
  8396. #endif
  8397. struct dir_scan_data {
  8398. struct de *entries;
  8399. unsigned int num_entries;
  8400. unsigned int arr_size;
  8401. };
  8402. /* Behaves like realloc(), but frees original pointer on failure */
  8403. static void *
  8404. realloc2(void *ptr, size_t size)
  8405. {
  8406. void *new_ptr = mg_realloc(ptr, size);
  8407. if ((new_ptr == NULL) && (size > 0)) {
  8408. mg_free(ptr);
  8409. }
  8410. return new_ptr;
  8411. }
  8412. #if !defined(NO_FILESYSTEMS)
  8413. static int
  8414. dir_scan_callback(struct de *de, void *data)
  8415. {
  8416. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8417. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8418. dsd->arr_size *= 2;
  8419. dsd->entries =
  8420. (struct de *)realloc2(dsd->entries,
  8421. dsd->arr_size * sizeof(dsd->entries[0]));
  8422. }
  8423. if (dsd->entries == NULL) {
  8424. /* TODO(lsm, low): propagate an error to the caller */
  8425. dsd->num_entries = 0;
  8426. } else {
  8427. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8428. dsd->entries[dsd->num_entries].file = de->file;
  8429. dsd->entries[dsd->num_entries].conn = de->conn;
  8430. dsd->num_entries++;
  8431. }
  8432. return 0;
  8433. }
  8434. static void
  8435. handle_directory_request(struct mg_connection *conn, const char *dir)
  8436. {
  8437. unsigned int i;
  8438. int sort_direction;
  8439. struct dir_scan_data data = {NULL, 0, 128};
  8440. char date[64], *esc, *p;
  8441. const char *title;
  8442. time_t curtime = time(NULL);
  8443. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8444. mg_send_http_error(conn,
  8445. 500,
  8446. "Error: Cannot open directory\nopendir(%s): %s",
  8447. dir,
  8448. strerror(ERRNO));
  8449. return;
  8450. }
  8451. gmt_time_string(date, sizeof(date), &curtime);
  8452. if (!conn) {
  8453. return;
  8454. }
  8455. esc = NULL;
  8456. title = conn->request_info.local_uri;
  8457. if (title[strcspn(title, "&<>")]) {
  8458. /* HTML escaping needed */
  8459. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8460. if (esc) {
  8461. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8462. mg_strlcpy(p, title + i, 2);
  8463. if (*p == '&') {
  8464. strcpy(p, "&amp;");
  8465. } else if (*p == '<') {
  8466. strcpy(p, "&lt;");
  8467. } else if (*p == '>') {
  8468. strcpy(p, "&gt;");
  8469. }
  8470. }
  8471. } else {
  8472. title = "";
  8473. }
  8474. }
  8475. sort_direction = ((conn->request_info.query_string != NULL)
  8476. && (conn->request_info.query_string[0] != '\0')
  8477. && (conn->request_info.query_string[1] == 'd'))
  8478. ? 'a'
  8479. : 'd';
  8480. conn->must_close = 1;
  8481. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8482. send_static_cache_header(conn);
  8483. send_additional_header(conn);
  8484. mg_printf(conn,
  8485. "Date: %s\r\n"
  8486. "Connection: close\r\n"
  8487. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8488. date);
  8489. mg_printf(conn,
  8490. "<html><head><title>Index of %s</title>"
  8491. "<style>th {text-align: left;}</style></head>"
  8492. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8493. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8494. "<th><a href=\"?d%c\">Modified</a></th>"
  8495. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8496. "<tr><td colspan=\"3\"><hr></td></tr>",
  8497. esc ? esc : title,
  8498. esc ? esc : title,
  8499. sort_direction,
  8500. sort_direction,
  8501. sort_direction);
  8502. mg_free(esc);
  8503. /* Print first entry - link to a parent directory */
  8504. mg_printf(conn,
  8505. "<tr><td><a href=\"%s\">%s</a></td>"
  8506. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8507. "..",
  8508. "Parent directory",
  8509. "-",
  8510. "-");
  8511. /* Sort and print directory entries */
  8512. if (data.entries != NULL) {
  8513. qsort(data.entries,
  8514. (size_t)data.num_entries,
  8515. sizeof(data.entries[0]),
  8516. compare_dir_entries);
  8517. for (i = 0; i < data.num_entries; i++) {
  8518. print_dir_entry(&data.entries[i]);
  8519. mg_free(data.entries[i].file_name);
  8520. }
  8521. mg_free(data.entries);
  8522. }
  8523. mg_printf(conn, "%s", "</table></pre></body></html>");
  8524. conn->status_code = 200;
  8525. }
  8526. #endif /* NO_FILESYSTEMS */
  8527. /* Send len bytes from the opened file to the client. */
  8528. static void
  8529. send_file_data(struct mg_connection *conn,
  8530. struct mg_file *filep,
  8531. int64_t offset,
  8532. int64_t len)
  8533. {
  8534. char buf[MG_BUF_LEN];
  8535. int to_read, num_read, num_written;
  8536. int64_t size;
  8537. if (!filep || !conn) {
  8538. return;
  8539. }
  8540. /* Sanity check the offset */
  8541. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8542. : (int64_t)(filep->stat.size);
  8543. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8544. #if defined(MG_USE_OPEN_FILE)
  8545. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8546. /* file stored in memory */
  8547. if (len > size - offset) {
  8548. len = size - offset;
  8549. }
  8550. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8551. } else /* else block below */
  8552. #endif
  8553. if (len > 0 && filep->access.fp != NULL) {
  8554. /* file stored on disk */
  8555. #if defined(__linux__)
  8556. /* sendfile is only available for Linux */
  8557. if ((conn->ssl == 0) && (conn->throttle == 0)
  8558. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8559. "yes"))) {
  8560. off_t sf_offs = (off_t)offset;
  8561. ssize_t sf_sent;
  8562. int sf_file = fileno(filep->access.fp);
  8563. int loop_cnt = 0;
  8564. do {
  8565. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8566. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8567. size_t sf_tosend =
  8568. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8569. sf_sent =
  8570. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8571. if (sf_sent > 0) {
  8572. len -= sf_sent;
  8573. offset += sf_sent;
  8574. } else if (loop_cnt == 0) {
  8575. /* This file can not be sent using sendfile.
  8576. * This might be the case for pseudo-files in the
  8577. * /sys/ and /proc/ file system.
  8578. * Use the regular user mode copy code instead. */
  8579. break;
  8580. } else if (sf_sent == 0) {
  8581. /* No error, but 0 bytes sent. May be EOF? */
  8582. return;
  8583. }
  8584. loop_cnt++;
  8585. } while ((len > 0) && (sf_sent >= 0));
  8586. if (sf_sent > 0) {
  8587. return; /* OK */
  8588. }
  8589. /* sf_sent<0 means error, thus fall back to the classic way */
  8590. /* This is always the case, if sf_file is not a "normal" file,
  8591. * e.g., for sending data from the output of a CGI process. */
  8592. offset = (int64_t)sf_offs;
  8593. }
  8594. #endif
  8595. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8596. mg_cry_internal(conn,
  8597. "%s: fseeko() failed: %s",
  8598. __func__,
  8599. strerror(ERRNO));
  8600. mg_send_http_error(
  8601. conn,
  8602. 500,
  8603. "%s",
  8604. "Error: Unable to access file at requested position.");
  8605. } else {
  8606. while (len > 0) {
  8607. /* Calculate how much to read from the file in the buffer */
  8608. to_read = sizeof(buf);
  8609. if ((int64_t)to_read > len) {
  8610. to_read = (int)len;
  8611. }
  8612. /* Read from file, exit the loop on error */
  8613. if ((num_read =
  8614. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8615. <= 0) {
  8616. break;
  8617. }
  8618. /* Send read bytes to the client, exit the loop on error */
  8619. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8620. != num_read) {
  8621. break;
  8622. }
  8623. /* Both read and were successful, adjust counters */
  8624. len -= num_written;
  8625. }
  8626. }
  8627. }
  8628. }
  8629. static int
  8630. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8631. {
  8632. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8633. }
  8634. static void
  8635. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8636. {
  8637. if ((filestat != NULL) && (buf != NULL)) {
  8638. mg_snprintf(NULL,
  8639. NULL, /* All calls to construct_etag use 64 byte buffer */
  8640. buf,
  8641. buf_len,
  8642. "\"%lx.%" INT64_FMT "\"",
  8643. (unsigned long)filestat->last_modified,
  8644. filestat->size);
  8645. }
  8646. }
  8647. static void
  8648. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8649. {
  8650. if (filep != NULL && filep->fp != NULL) {
  8651. #if defined(_WIN32)
  8652. (void)conn; /* Unused. */
  8653. #else
  8654. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8655. mg_cry_internal(conn,
  8656. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8657. __func__,
  8658. strerror(ERRNO));
  8659. }
  8660. #endif
  8661. }
  8662. }
  8663. #if defined(USE_ZLIB)
  8664. #include "mod_zlib.inl"
  8665. #endif
  8666. #if !defined(NO_FILESYSTEMS)
  8667. static void
  8668. handle_static_file_request(struct mg_connection *conn,
  8669. const char *path,
  8670. struct mg_file *filep,
  8671. const char *mime_type,
  8672. const char *additional_headers)
  8673. {
  8674. char date[64], lm[64], etag[64];
  8675. char range[128]; /* large enough, so there will be no overflow */
  8676. const char *msg = "OK";
  8677. const char *range_hdr;
  8678. time_t curtime = time(NULL);
  8679. int64_t cl, r1, r2;
  8680. struct vec mime_vec;
  8681. int n, truncated;
  8682. char gz_path[PATH_MAX];
  8683. const char *encoding = "";
  8684. const char *origin_hdr;
  8685. const char *cors_orig_cfg;
  8686. const char *cors1, *cors2, *cors3;
  8687. int is_head_request;
  8688. #if defined(USE_ZLIB)
  8689. /* Compression is allowed, unless there is a reason not to use
  8690. * compression. If the file is already compressed, too small or a
  8691. * "range" request was made, on the fly compression is not possible. */
  8692. int allow_on_the_fly_compression = 1;
  8693. #endif
  8694. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8695. return;
  8696. }
  8697. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8698. if (mime_type == NULL) {
  8699. get_mime_type(conn, path, &mime_vec);
  8700. } else {
  8701. mime_vec.ptr = mime_type;
  8702. mime_vec.len = strlen(mime_type);
  8703. }
  8704. if (filep->stat.size > INT64_MAX) {
  8705. mg_send_http_error(conn,
  8706. 500,
  8707. "Error: File size is too large to send\n%" INT64_FMT,
  8708. filep->stat.size);
  8709. return;
  8710. }
  8711. cl = (int64_t)filep->stat.size;
  8712. conn->status_code = 200;
  8713. range[0] = '\0';
  8714. #if defined(USE_ZLIB)
  8715. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8716. * it's important to rewrite the filename after resolving
  8717. * the mime type from it, to preserve the actual file's type */
  8718. if (!conn->accept_gzip) {
  8719. allow_on_the_fly_compression = 0;
  8720. }
  8721. #endif
  8722. /* Check if there is a range header */
  8723. range_hdr = mg_get_header(conn, "Range");
  8724. /* For gzipped files, add *.gz */
  8725. if (filep->stat.is_gzipped) {
  8726. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8727. if (truncated) {
  8728. mg_send_http_error(conn,
  8729. 500,
  8730. "Error: Path of zipped file too long (%s)",
  8731. path);
  8732. return;
  8733. }
  8734. path = gz_path;
  8735. encoding = "Content-Encoding: gzip\r\n";
  8736. #if defined(USE_ZLIB)
  8737. /* File is already compressed. No "on the fly" compression. */
  8738. allow_on_the_fly_compression = 0;
  8739. #endif
  8740. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8741. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8742. struct mg_file_stat file_stat;
  8743. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8744. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8745. && !file_stat.is_directory) {
  8746. file_stat.is_gzipped = 1;
  8747. filep->stat = file_stat;
  8748. cl = (int64_t)filep->stat.size;
  8749. path = gz_path;
  8750. encoding = "Content-Encoding: gzip\r\n";
  8751. #if defined(USE_ZLIB)
  8752. /* File is already compressed. No "on the fly" compression. */
  8753. allow_on_the_fly_compression = 0;
  8754. #endif
  8755. }
  8756. }
  8757. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8758. mg_send_http_error(conn,
  8759. 500,
  8760. "Error: Cannot open file\nfopen(%s): %s",
  8761. path,
  8762. strerror(ERRNO));
  8763. return;
  8764. }
  8765. fclose_on_exec(&filep->access, conn);
  8766. /* If "Range" request was made: parse header, send only selected part
  8767. * of the file. */
  8768. r1 = r2 = 0;
  8769. if ((range_hdr != NULL)
  8770. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8771. && (r2 >= 0)) {
  8772. /* actually, range requests don't play well with a pre-gzipped
  8773. * file (since the range is specified in the uncompressed space) */
  8774. if (filep->stat.is_gzipped) {
  8775. mg_send_http_error(
  8776. conn,
  8777. 416, /* 416 = Range Not Satisfiable */
  8778. "%s",
  8779. "Error: Range requests in gzipped files are not supported");
  8780. (void)mg_fclose(
  8781. &filep->access); /* ignore error on read only file */
  8782. return;
  8783. }
  8784. conn->status_code = 206;
  8785. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8786. mg_snprintf(conn,
  8787. NULL, /* range buffer is big enough */
  8788. range,
  8789. sizeof(range),
  8790. "Content-Range: bytes "
  8791. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8792. r1,
  8793. r1 + cl - 1,
  8794. filep->stat.size);
  8795. msg = "Partial Content";
  8796. #if defined(USE_ZLIB)
  8797. /* Do not compress ranges. */
  8798. allow_on_the_fly_compression = 0;
  8799. #endif
  8800. }
  8801. /* Do not compress small files. Small files do not benefit from file
  8802. * compression, but there is still some overhead. */
  8803. #if defined(USE_ZLIB)
  8804. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8805. /* File is below the size limit. */
  8806. allow_on_the_fly_compression = 0;
  8807. }
  8808. #endif
  8809. /* Standard CORS header */
  8810. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8811. origin_hdr = mg_get_header(conn, "Origin");
  8812. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8813. /* Cross-origin resource sharing (CORS), see
  8814. * http://www.html5rocks.com/en/tutorials/cors/,
  8815. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8816. * -
  8817. * preflight is not supported for files. */
  8818. cors1 = "Access-Control-Allow-Origin: ";
  8819. cors2 = cors_orig_cfg;
  8820. cors3 = "\r\n";
  8821. } else {
  8822. cors1 = cors2 = cors3 = "";
  8823. }
  8824. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8825. * according to
  8826. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8827. gmt_time_string(date, sizeof(date), &curtime);
  8828. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8829. construct_etag(etag, sizeof(etag), &filep->stat);
  8830. /* Send header */
  8831. (void)mg_printf(conn,
  8832. "HTTP/1.1 %d %s\r\n"
  8833. "%s%s%s" /* CORS */
  8834. "Date: %s\r\n"
  8835. "Last-Modified: %s\r\n"
  8836. "Etag: %s\r\n"
  8837. "Content-Type: %.*s\r\n"
  8838. "Connection: %s\r\n",
  8839. conn->status_code,
  8840. msg,
  8841. cors1,
  8842. cors2,
  8843. cors3,
  8844. date,
  8845. lm,
  8846. etag,
  8847. (int)mime_vec.len,
  8848. mime_vec.ptr,
  8849. suggest_connection_header(conn));
  8850. send_static_cache_header(conn);
  8851. send_additional_header(conn);
  8852. #if defined(USE_ZLIB)
  8853. /* On the fly compression allowed */
  8854. if (allow_on_the_fly_compression) {
  8855. /* For on the fly compression, we don't know the content size in
  8856. * advance, so we have to use chunked encoding */
  8857. (void)mg_printf(conn,
  8858. "Content-Encoding: gzip\r\n"
  8859. "Transfer-Encoding: chunked\r\n");
  8860. } else
  8861. #endif
  8862. {
  8863. /* Without on-the-fly compression, we know the content-length
  8864. * and we can use ranges (with on-the-fly compression we cannot).
  8865. * So we send these response headers only in this case. */
  8866. (void)mg_printf(conn,
  8867. "Content-Length: %" INT64_FMT "\r\n"
  8868. "Accept-Ranges: bytes\r\n"
  8869. "%s" /* range */
  8870. "%s" /* encoding */,
  8871. cl,
  8872. range,
  8873. encoding);
  8874. }
  8875. /* The previous code must not add any header starting with X- to make
  8876. * sure no one of the additional_headers is included twice */
  8877. if (additional_headers != NULL) {
  8878. (void)mg_printf(conn,
  8879. "%.*s\r\n\r\n",
  8880. (int)strlen(additional_headers),
  8881. additional_headers);
  8882. } else {
  8883. (void)mg_printf(conn, "\r\n");
  8884. }
  8885. if (!is_head_request) {
  8886. #if defined(USE_ZLIB)
  8887. if (allow_on_the_fly_compression) {
  8888. /* Compress and send */
  8889. send_compressed_data(conn, filep);
  8890. } else
  8891. #endif
  8892. {
  8893. /* Send file directly */
  8894. send_file_data(conn, filep, r1, cl);
  8895. }
  8896. }
  8897. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8898. }
  8899. int
  8900. mg_send_file_body(struct mg_connection *conn, const char *path)
  8901. {
  8902. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8903. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8904. return -1;
  8905. }
  8906. fclose_on_exec(&file.access, conn);
  8907. send_file_data(conn, &file, 0, INT64_MAX);
  8908. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8909. return 0; /* >= 0 for OK */
  8910. }
  8911. #endif /* NO_FILESYSTEMS */
  8912. #if !defined(NO_CACHING)
  8913. /* Return True if we should reply 304 Not Modified. */
  8914. static int
  8915. is_not_modified(const struct mg_connection *conn,
  8916. const struct mg_file_stat *filestat)
  8917. {
  8918. char etag[64];
  8919. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8920. const char *inm = mg_get_header(conn, "If-None-Match");
  8921. construct_etag(etag, sizeof(etag), filestat);
  8922. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8923. || ((ims != NULL)
  8924. && (filestat->last_modified <= parse_date_string(ims)));
  8925. }
  8926. static void
  8927. handle_not_modified_static_file_request(struct mg_connection *conn,
  8928. struct mg_file *filep)
  8929. {
  8930. char date[64], lm[64], etag[64];
  8931. time_t curtime = time(NULL);
  8932. if ((conn == NULL) || (filep == NULL)) {
  8933. return;
  8934. }
  8935. conn->status_code = 304;
  8936. gmt_time_string(date, sizeof(date), &curtime);
  8937. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8938. construct_etag(etag, sizeof(etag), &filep->stat);
  8939. (void)mg_printf(conn,
  8940. "HTTP/1.1 %d %s\r\n"
  8941. "Date: %s\r\n",
  8942. conn->status_code,
  8943. mg_get_response_code_text(conn, conn->status_code),
  8944. date);
  8945. send_static_cache_header(conn);
  8946. send_additional_header(conn);
  8947. (void)mg_printf(conn,
  8948. "Last-Modified: %s\r\n"
  8949. "Etag: %s\r\n"
  8950. "Connection: %s\r\n"
  8951. "\r\n",
  8952. lm,
  8953. etag,
  8954. suggest_connection_header(conn));
  8955. }
  8956. #endif
  8957. #if !defined(NO_FILESYSTEMS)
  8958. void
  8959. mg_send_file(struct mg_connection *conn, const char *path)
  8960. {
  8961. mg_send_mime_file2(conn, path, NULL, NULL);
  8962. }
  8963. void
  8964. mg_send_mime_file(struct mg_connection *conn,
  8965. const char *path,
  8966. const char *mime_type)
  8967. {
  8968. mg_send_mime_file2(conn, path, mime_type, NULL);
  8969. }
  8970. void
  8971. mg_send_mime_file2(struct mg_connection *conn,
  8972. const char *path,
  8973. const char *mime_type,
  8974. const char *additional_headers)
  8975. {
  8976. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8977. if (!conn) {
  8978. /* No conn */
  8979. return;
  8980. }
  8981. if (mg_stat(conn, path, &file.stat)) {
  8982. #if !defined(NO_CACHING)
  8983. if (is_not_modified(conn, &file.stat)) {
  8984. /* Send 304 "Not Modified" - this must not send any body data */
  8985. handle_not_modified_static_file_request(conn, &file);
  8986. } else
  8987. #endif /* NO_CACHING */
  8988. if (file.stat.is_directory) {
  8989. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8990. "yes")) {
  8991. handle_directory_request(conn, path);
  8992. } else {
  8993. mg_send_http_error(conn,
  8994. 403,
  8995. "%s",
  8996. "Error: Directory listing denied");
  8997. }
  8998. } else {
  8999. handle_static_file_request(
  9000. conn, path, &file, mime_type, additional_headers);
  9001. }
  9002. } else {
  9003. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9004. }
  9005. }
  9006. /* For a given PUT path, create all intermediate subdirectories.
  9007. * Return 0 if the path itself is a directory.
  9008. * Return 1 if the path leads to a file.
  9009. * Return -1 for if the path is too long.
  9010. * Return -2 if path can not be created.
  9011. */
  9012. static int
  9013. put_dir(struct mg_connection *conn, const char *path)
  9014. {
  9015. char buf[PATH_MAX];
  9016. const char *s, *p;
  9017. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9018. size_t len;
  9019. int res = 1;
  9020. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9021. len = (size_t)(p - path);
  9022. if (len >= sizeof(buf)) {
  9023. /* path too long */
  9024. res = -1;
  9025. break;
  9026. }
  9027. memcpy(buf, path, len);
  9028. buf[len] = '\0';
  9029. /* Try to create intermediate directory */
  9030. DEBUG_TRACE("mkdir(%s)", buf);
  9031. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9032. /* path does not exixt and can not be created */
  9033. res = -2;
  9034. break;
  9035. }
  9036. /* Is path itself a directory? */
  9037. if (p[1] == '\0') {
  9038. res = 0;
  9039. }
  9040. }
  9041. return res;
  9042. }
  9043. static void
  9044. remove_bad_file(const struct mg_connection *conn, const char *path)
  9045. {
  9046. int r = mg_remove(conn, path);
  9047. if (r != 0) {
  9048. mg_cry_internal(conn,
  9049. "%s: Cannot remove invalid file %s",
  9050. __func__,
  9051. path);
  9052. }
  9053. }
  9054. long long
  9055. mg_store_body(struct mg_connection *conn, const char *path)
  9056. {
  9057. char buf[MG_BUF_LEN];
  9058. long long len = 0;
  9059. int ret, n;
  9060. struct mg_file fi;
  9061. if (conn->consumed_content != 0) {
  9062. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9063. return -11;
  9064. }
  9065. ret = put_dir(conn, path);
  9066. if (ret < 0) {
  9067. /* -1 for path too long,
  9068. * -2 for path can not be created. */
  9069. return ret;
  9070. }
  9071. if (ret != 1) {
  9072. /* Return 0 means, path itself is a directory. */
  9073. return 0;
  9074. }
  9075. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9076. return -12;
  9077. }
  9078. ret = mg_read(conn, buf, sizeof(buf));
  9079. while (ret > 0) {
  9080. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9081. if (n != ret) {
  9082. (void)mg_fclose(
  9083. &fi.access); /* File is bad and will be removed anyway. */
  9084. remove_bad_file(conn, path);
  9085. return -13;
  9086. }
  9087. len += ret;
  9088. ret = mg_read(conn, buf, sizeof(buf));
  9089. }
  9090. /* File is open for writing. If fclose fails, there was probably an
  9091. * error flushing the buffer to disk, so the file on disk might be
  9092. * broken. Delete it and return an error to the caller. */
  9093. if (mg_fclose(&fi.access) != 0) {
  9094. remove_bad_file(conn, path);
  9095. return -14;
  9096. }
  9097. return len;
  9098. }
  9099. #endif /* NO_FILESYSTEMS */
  9100. /* Parse a buffer:
  9101. * Forward the string pointer till the end of a word, then
  9102. * terminate it and forward till the begin of the next word.
  9103. */
  9104. static int
  9105. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9106. {
  9107. /* Forward until a space is found - use isgraph here */
  9108. /* See http://www.cplusplus.com/reference/cctype/ */
  9109. while (isgraph((unsigned char)**ppw)) {
  9110. (*ppw)++;
  9111. }
  9112. /* Check end of word */
  9113. if (eol) {
  9114. /* must be a end of line */
  9115. if ((**ppw != '\r') && (**ppw != '\n')) {
  9116. return -1;
  9117. }
  9118. } else {
  9119. /* must be a end of a word, but not a line */
  9120. if (**ppw != ' ') {
  9121. return -1;
  9122. }
  9123. }
  9124. /* Terminate and forward to the next word */
  9125. do {
  9126. **ppw = 0;
  9127. (*ppw)++;
  9128. } while (isspace((unsigned char)**ppw));
  9129. /* Check after term */
  9130. if (!eol) {
  9131. /* if it's not the end of line, there must be a next word */
  9132. if (!isgraph((unsigned char)**ppw)) {
  9133. return -1;
  9134. }
  9135. }
  9136. /* ok */
  9137. return 1;
  9138. }
  9139. /* Parse HTTP headers from the given buffer, advance buf pointer
  9140. * to the point where parsing stopped.
  9141. * All parameters must be valid pointers (not NULL).
  9142. * Return <0 on error. */
  9143. static int
  9144. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9145. {
  9146. int i;
  9147. int num_headers = 0;
  9148. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9149. char *dp = *buf;
  9150. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9151. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9152. dp++;
  9153. }
  9154. if (dp == *buf) {
  9155. /* End of headers reached. */
  9156. break;
  9157. }
  9158. if (*dp != ':') {
  9159. /* This is not a valid field. */
  9160. return -1;
  9161. }
  9162. /* End of header key (*dp == ':') */
  9163. /* Truncate here and set the key name */
  9164. *dp = 0;
  9165. hdr[i].name = *buf;
  9166. /* Skip all spaces */
  9167. do {
  9168. dp++;
  9169. } while ((*dp == ' ') || (*dp == '\t'));
  9170. /* The rest of the line is the value */
  9171. hdr[i].value = dp;
  9172. /* Find end of line */
  9173. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9174. dp++;
  9175. };
  9176. /* eliminate \r */
  9177. if (*dp == '\r') {
  9178. *dp = 0;
  9179. dp++;
  9180. if (*dp != '\n') {
  9181. /* This is not a valid line. */
  9182. return -1;
  9183. }
  9184. }
  9185. /* here *dp is either 0 or '\n' */
  9186. /* in any case, we have a new header */
  9187. num_headers = i + 1;
  9188. if (*dp) {
  9189. *dp = 0;
  9190. dp++;
  9191. *buf = dp;
  9192. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9193. /* This is the end of the header */
  9194. break;
  9195. }
  9196. } else {
  9197. *buf = dp;
  9198. break;
  9199. }
  9200. }
  9201. return num_headers;
  9202. }
  9203. struct mg_http_method_info {
  9204. const char *name;
  9205. int request_has_body;
  9206. int response_has_body;
  9207. int is_safe;
  9208. int is_idempotent;
  9209. int is_cacheable;
  9210. };
  9211. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9212. static const struct mg_http_method_info http_methods[] = {
  9213. /* HTTP (RFC 2616) */
  9214. {"GET", 0, 1, 1, 1, 1},
  9215. {"POST", 1, 1, 0, 0, 0},
  9216. {"PUT", 1, 0, 0, 1, 0},
  9217. {"DELETE", 0, 0, 0, 1, 0},
  9218. {"HEAD", 0, 0, 1, 1, 1},
  9219. {"OPTIONS", 0, 0, 1, 1, 0},
  9220. {"CONNECT", 1, 1, 0, 0, 0},
  9221. /* TRACE method (RFC 2616) is not supported for security reasons */
  9222. /* PATCH method (RFC 5789) */
  9223. {"PATCH", 1, 0, 0, 0, 0},
  9224. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9225. /* WEBDAV (RFC 2518) */
  9226. {"PROPFIND", 0, 1, 1, 1, 0},
  9227. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9228. * Some PROPFIND results MAY be cached, with care,
  9229. * as there is no cache validation mechanism for
  9230. * most properties. This method is both safe and
  9231. * idempotent (see Section 9.1 of [RFC2616]). */
  9232. {"MKCOL", 0, 0, 0, 1, 0},
  9233. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9234. * When MKCOL is invoked without a request body,
  9235. * the newly created collection SHOULD have no
  9236. * members. A MKCOL request message may contain
  9237. * a message body. The precise behavior of a MKCOL
  9238. * request when the body is present is undefined,
  9239. * ... ==> We do not support MKCOL with body data.
  9240. * This method is idempotent, but not safe (see
  9241. * Section 9.1 of [RFC2616]). Responses to this
  9242. * method MUST NOT be cached. */
  9243. /* Unsupported WEBDAV Methods: */
  9244. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9245. /* + 11 methods from RFC 3253 */
  9246. /* ORDERPATCH (RFC 3648) */
  9247. /* ACL (RFC 3744) */
  9248. /* SEARCH (RFC 5323) */
  9249. /* + MicroSoft extensions
  9250. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9251. /* REPORT method (RFC 3253) */
  9252. {"REPORT", 1, 1, 1, 1, 1},
  9253. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9254. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9255. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9256. * to be useful for REST in case a "GET request with body" is
  9257. * required. */
  9258. {NULL, 0, 0, 0, 0, 0}
  9259. /* end of list */
  9260. };
  9261. static const struct mg_http_method_info *
  9262. get_http_method_info(const char *method)
  9263. {
  9264. /* Check if the method is known to the server. The list of all known
  9265. * HTTP methods can be found here at
  9266. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9267. */
  9268. const struct mg_http_method_info *m = http_methods;
  9269. while (m->name) {
  9270. if (!strcmp(m->name, method)) {
  9271. return m;
  9272. }
  9273. m++;
  9274. }
  9275. return NULL;
  9276. }
  9277. static int
  9278. is_valid_http_method(const char *method)
  9279. {
  9280. return (get_http_method_info(method) != NULL);
  9281. }
  9282. /* Parse HTTP request, fill in mg_request_info structure.
  9283. * This function modifies the buffer by NUL-terminating
  9284. * HTTP request components, header names and header values.
  9285. * Parameters:
  9286. * buf (in/out): pointer to the HTTP header to parse and split
  9287. * len (in): length of HTTP header buffer
  9288. * re (out): parsed header as mg_request_info
  9289. * buf and ri must be valid pointers (not NULL), len>0.
  9290. * Returns <0 on error. */
  9291. static int
  9292. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9293. {
  9294. int request_length;
  9295. int init_skip = 0;
  9296. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9297. * remote_port */
  9298. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9299. NULL;
  9300. ri->num_headers = 0;
  9301. /* RFC says that all initial whitespaces should be ingored */
  9302. /* This included all leading \r and \n (isspace) */
  9303. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9304. while ((len > 0) && isspace((unsigned char)*buf)) {
  9305. buf++;
  9306. len--;
  9307. init_skip++;
  9308. }
  9309. if (len == 0) {
  9310. /* Incomplete request */
  9311. return 0;
  9312. }
  9313. /* Control characters are not allowed, including zero */
  9314. if (iscntrl((unsigned char)*buf)) {
  9315. return -1;
  9316. }
  9317. /* Find end of HTTP header */
  9318. request_length = get_http_header_len(buf, len);
  9319. if (request_length <= 0) {
  9320. return request_length;
  9321. }
  9322. buf[request_length - 1] = '\0';
  9323. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9324. return -1;
  9325. }
  9326. /* The first word has to be the HTTP method */
  9327. ri->request_method = buf;
  9328. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9329. return -1;
  9330. }
  9331. /* Check for a valid http method */
  9332. if (!is_valid_http_method(ri->request_method)) {
  9333. return -1;
  9334. }
  9335. /* The second word is the URI */
  9336. ri->request_uri = buf;
  9337. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9338. return -1;
  9339. }
  9340. /* Next would be the HTTP version */
  9341. ri->http_version = buf;
  9342. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9343. return -1;
  9344. }
  9345. /* Check for a valid HTTP version key */
  9346. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9347. /* Invalid request */
  9348. return -1;
  9349. }
  9350. ri->http_version += 5;
  9351. /* Parse all HTTP headers */
  9352. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9353. if (ri->num_headers < 0) {
  9354. /* Error while parsing headers */
  9355. return -1;
  9356. }
  9357. return request_length + init_skip;
  9358. }
  9359. static int
  9360. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9361. {
  9362. int response_length;
  9363. int init_skip = 0;
  9364. char *tmp, *tmp2;
  9365. long l;
  9366. /* Initialize elements. */
  9367. ri->http_version = ri->status_text = NULL;
  9368. ri->num_headers = ri->status_code = 0;
  9369. /* RFC says that all initial whitespaces should be ingored */
  9370. /* This included all leading \r and \n (isspace) */
  9371. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9372. while ((len > 0) && isspace((unsigned char)*buf)) {
  9373. buf++;
  9374. len--;
  9375. init_skip++;
  9376. }
  9377. if (len == 0) {
  9378. /* Incomplete request */
  9379. return 0;
  9380. }
  9381. /* Control characters are not allowed, including zero */
  9382. if (iscntrl((unsigned char)*buf)) {
  9383. return -1;
  9384. }
  9385. /* Find end of HTTP header */
  9386. response_length = get_http_header_len(buf, len);
  9387. if (response_length <= 0) {
  9388. return response_length;
  9389. }
  9390. buf[response_length - 1] = '\0';
  9391. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9392. return -1;
  9393. }
  9394. /* The first word is the HTTP version */
  9395. /* Check for a valid HTTP version key */
  9396. if (strncmp(buf, "HTTP/", 5) != 0) {
  9397. /* Invalid request */
  9398. return -1;
  9399. }
  9400. buf += 5;
  9401. if (!isgraph((unsigned char)buf[0])) {
  9402. /* Invalid request */
  9403. return -1;
  9404. }
  9405. ri->http_version = buf;
  9406. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9407. return -1;
  9408. }
  9409. /* The second word is the status as a number */
  9410. tmp = buf;
  9411. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9412. return -1;
  9413. }
  9414. l = strtol(tmp, &tmp2, 10);
  9415. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9416. /* Everything else but a 3 digit code is invalid */
  9417. return -1;
  9418. }
  9419. ri->status_code = (int)l;
  9420. /* The rest of the line is the status text */
  9421. ri->status_text = buf;
  9422. /* Find end of status text */
  9423. /* isgraph or isspace = isprint */
  9424. while (isprint((unsigned char)*buf)) {
  9425. buf++;
  9426. }
  9427. if ((*buf != '\r') && (*buf != '\n')) {
  9428. return -1;
  9429. }
  9430. /* Terminate string and forward buf to next line */
  9431. do {
  9432. *buf = 0;
  9433. buf++;
  9434. } while (isspace((unsigned char)*buf));
  9435. /* Parse all HTTP headers */
  9436. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9437. if (ri->num_headers < 0) {
  9438. /* Error while parsing headers */
  9439. return -1;
  9440. }
  9441. return response_length + init_skip;
  9442. }
  9443. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9444. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9445. * buffer (which marks the end of HTTP request). Buffer buf may already
  9446. * have some data. The length of the data is stored in nread.
  9447. * Upon every read operation, increase nread by the number of bytes read. */
  9448. static int
  9449. read_message(FILE *fp,
  9450. struct mg_connection *conn,
  9451. char *buf,
  9452. int bufsiz,
  9453. int *nread)
  9454. {
  9455. int request_len, n = 0;
  9456. struct timespec last_action_time;
  9457. double request_timeout;
  9458. if (!conn) {
  9459. return 0;
  9460. }
  9461. memset(&last_action_time, 0, sizeof(last_action_time));
  9462. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9463. /* value of request_timeout is in seconds, config in milliseconds */
  9464. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9465. } else {
  9466. request_timeout = -1.0;
  9467. }
  9468. if (conn->handled_requests > 0) {
  9469. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9470. request_timeout =
  9471. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9472. }
  9473. }
  9474. request_len = get_http_header_len(buf, *nread);
  9475. while (request_len == 0) {
  9476. /* Full request not yet received */
  9477. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9478. /* Server is to be stopped. */
  9479. return -1;
  9480. }
  9481. if (*nread >= bufsiz) {
  9482. /* Request too long */
  9483. return -2;
  9484. }
  9485. n = pull_inner(
  9486. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9487. if (n == -2) {
  9488. /* Receive error */
  9489. return -1;
  9490. }
  9491. /* update clock after every read request */
  9492. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9493. if (n > 0) {
  9494. *nread += n;
  9495. request_len = get_http_header_len(buf, *nread);
  9496. }
  9497. if ((request_len == 0) && (request_timeout >= 0)) {
  9498. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9499. > request_timeout) {
  9500. /* Timeout */
  9501. return -1;
  9502. }
  9503. }
  9504. }
  9505. return request_len;
  9506. }
  9507. #if !defined(NO_CGI) || !defined(NO_FILES)
  9508. static int
  9509. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9510. {
  9511. const char *expect;
  9512. char buf[MG_BUF_LEN];
  9513. int success = 0;
  9514. if (!conn) {
  9515. return 0;
  9516. }
  9517. expect = mg_get_header(conn, "Expect");
  9518. DEBUG_ASSERT(fp != NULL);
  9519. if (!fp) {
  9520. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9521. return 0;
  9522. }
  9523. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9524. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9525. */
  9526. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9527. } else {
  9528. if (expect != NULL) {
  9529. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9530. conn->status_code = 100;
  9531. } else {
  9532. conn->status_code = 200;
  9533. }
  9534. DEBUG_ASSERT(conn->consumed_content == 0);
  9535. if (conn->consumed_content != 0) {
  9536. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9537. return 0;
  9538. }
  9539. for (;;) {
  9540. int nread = mg_read(conn, buf, sizeof(buf));
  9541. if (nread <= 0) {
  9542. success = (nread == 0);
  9543. break;
  9544. }
  9545. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9546. break;
  9547. }
  9548. }
  9549. /* Each error code path in this function must send an error */
  9550. if (!success) {
  9551. /* NOTE: Maybe some data has already been sent. */
  9552. /* TODO (low): If some data has been sent, a correct error
  9553. * reply can no longer be sent, so just close the connection */
  9554. mg_send_http_error(conn, 500, "%s", "");
  9555. }
  9556. }
  9557. return success;
  9558. }
  9559. #endif
  9560. #if defined(USE_TIMERS)
  9561. #define TIMER_API static
  9562. #include "timer.inl"
  9563. #endif /* USE_TIMERS */
  9564. #if !defined(NO_CGI)
  9565. /* This structure helps to create an environment for the spawned CGI
  9566. * program.
  9567. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9568. * last element must be NULL.
  9569. * However, on Windows there is a requirement that all these
  9570. * VARIABLE=VALUE\0
  9571. * strings must reside in a contiguous buffer. The end of the buffer is
  9572. * marked by two '\0' characters.
  9573. * We satisfy both worlds: we create an envp array (which is vars), all
  9574. * entries are actually pointers inside buf. */
  9575. struct cgi_environment {
  9576. struct mg_connection *conn;
  9577. /* Data block */
  9578. char *buf; /* Environment buffer */
  9579. size_t buflen; /* Space available in buf */
  9580. size_t bufused; /* Space taken in buf */
  9581. /* Index block */
  9582. char **var; /* char **envp */
  9583. size_t varlen; /* Number of variables available in var */
  9584. size_t varused; /* Number of variables stored in var */
  9585. };
  9586. static void addenv(struct cgi_environment *env,
  9587. PRINTF_FORMAT_STRING(const char *fmt),
  9588. ...) PRINTF_ARGS(2, 3);
  9589. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9590. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9591. static void
  9592. addenv(struct cgi_environment *env, const char *fmt, ...)
  9593. {
  9594. size_t i, n, space;
  9595. int truncated = 0;
  9596. char *added;
  9597. va_list ap;
  9598. if ((env->varlen - env->varused) < 2) {
  9599. mg_cry_internal(env->conn,
  9600. "%s: Cannot register CGI variable [%s]",
  9601. __func__,
  9602. fmt);
  9603. return;
  9604. }
  9605. /* Calculate how much space is left in the buffer */
  9606. space = (env->buflen - env->bufused);
  9607. do {
  9608. /* Space for "\0\0" is always needed. */
  9609. if (space <= 2) {
  9610. /* Allocate new buffer */
  9611. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9612. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9613. if (!added) {
  9614. /* Out of memory */
  9615. mg_cry_internal(
  9616. env->conn,
  9617. "%s: Cannot allocate memory for CGI variable [%s]",
  9618. __func__,
  9619. fmt);
  9620. return;
  9621. }
  9622. /* Retarget pointers */
  9623. env->buf = added;
  9624. env->buflen = n;
  9625. for (i = 0, n = 0; i < env->varused; i++) {
  9626. env->var[i] = added + n;
  9627. n += strlen(added + n) + 1;
  9628. }
  9629. space = (env->buflen - env->bufused);
  9630. }
  9631. /* Make a pointer to the free space int the buffer */
  9632. added = env->buf + env->bufused;
  9633. /* Copy VARIABLE=VALUE\0 string into the free space */
  9634. va_start(ap, fmt);
  9635. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9636. va_end(ap);
  9637. /* Do not add truncated strings to the environment */
  9638. if (truncated) {
  9639. /* Reallocate the buffer */
  9640. space = 0;
  9641. }
  9642. } while (truncated);
  9643. /* Calculate number of bytes added to the environment */
  9644. n = strlen(added) + 1;
  9645. env->bufused += n;
  9646. /* Append a pointer to the added string into the envp array */
  9647. env->var[env->varused] = added;
  9648. env->varused++;
  9649. }
  9650. /* Return 0 on success, non-zero if an error occurs. */
  9651. static int
  9652. prepare_cgi_environment(struct mg_connection *conn,
  9653. const char *prog,
  9654. struct cgi_environment *env)
  9655. {
  9656. const char *s;
  9657. struct vec var_vec;
  9658. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9659. int i, truncated, uri_len;
  9660. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9661. return -1;
  9662. }
  9663. env->conn = conn;
  9664. env->buflen = CGI_ENVIRONMENT_SIZE;
  9665. env->bufused = 0;
  9666. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9667. if (env->buf == NULL) {
  9668. mg_cry_internal(conn,
  9669. "%s: Not enough memory for environmental buffer",
  9670. __func__);
  9671. return -1;
  9672. }
  9673. env->varlen = MAX_CGI_ENVIR_VARS;
  9674. env->varused = 0;
  9675. env->var =
  9676. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9677. if (env->var == NULL) {
  9678. mg_cry_internal(conn,
  9679. "%s: Not enough memory for environmental variables",
  9680. __func__);
  9681. mg_free(env->buf);
  9682. return -1;
  9683. }
  9684. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9685. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9686. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9687. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9688. /* Prepare the environment block */
  9689. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9690. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9691. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9692. addenv(env, "SERVER_PORT=%d", ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)));
  9693. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9694. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9695. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9696. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9697. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9698. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9699. /* SCRIPT_NAME */
  9700. uri_len = (int)strlen(conn->request_info.local_uri);
  9701. if (conn->path_info == NULL) {
  9702. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9703. /* URI: /path_to_script/script.cgi */
  9704. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9705. } else {
  9706. /* URI: /path_to_script/ ... using index.cgi */
  9707. const char *index_file = strrchr(prog, '/');
  9708. if (index_file) {
  9709. addenv(env,
  9710. "SCRIPT_NAME=%s%s",
  9711. conn->request_info.local_uri,
  9712. index_file + 1);
  9713. }
  9714. }
  9715. } else {
  9716. /* URI: /path_to_script/script.cgi/path_info */
  9717. addenv(env,
  9718. "SCRIPT_NAME=%.*s",
  9719. uri_len - (int)strlen(conn->path_info),
  9720. conn->request_info.local_uri);
  9721. }
  9722. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9723. if (conn->path_info == NULL) {
  9724. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9725. } else {
  9726. addenv(env,
  9727. "PATH_TRANSLATED=%s%s",
  9728. conn->dom_ctx->config[DOCUMENT_ROOT],
  9729. conn->path_info);
  9730. }
  9731. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9732. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9733. addenv(env, "CONTENT_TYPE=%s", s);
  9734. }
  9735. if (conn->request_info.query_string != NULL) {
  9736. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9737. }
  9738. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9739. addenv(env, "CONTENT_LENGTH=%s", s);
  9740. }
  9741. if ((s = getenv("PATH")) != NULL) {
  9742. addenv(env, "PATH=%s", s);
  9743. }
  9744. if (conn->path_info != NULL) {
  9745. addenv(env, "PATH_INFO=%s", conn->path_info);
  9746. }
  9747. if (conn->status_code > 0) {
  9748. /* CGI error handler should show the status code */
  9749. addenv(env, "STATUS=%d", conn->status_code);
  9750. }
  9751. #if defined(_WIN32)
  9752. if ((s = getenv("COMSPEC")) != NULL) {
  9753. addenv(env, "COMSPEC=%s", s);
  9754. }
  9755. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9756. addenv(env, "SYSTEMROOT=%s", s);
  9757. }
  9758. if ((s = getenv("SystemDrive")) != NULL) {
  9759. addenv(env, "SystemDrive=%s", s);
  9760. }
  9761. if ((s = getenv("ProgramFiles")) != NULL) {
  9762. addenv(env, "ProgramFiles=%s", s);
  9763. }
  9764. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9765. addenv(env, "ProgramFiles(x86)=%s", s);
  9766. }
  9767. #else
  9768. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9769. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9770. }
  9771. #endif /* _WIN32 */
  9772. if ((s = getenv("PERLLIB")) != NULL) {
  9773. addenv(env, "PERLLIB=%s", s);
  9774. }
  9775. if (conn->request_info.remote_user != NULL) {
  9776. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9777. addenv(env, "%s", "AUTH_TYPE=Digest");
  9778. }
  9779. /* Add all headers as HTTP_* variables */
  9780. for (i = 0; i < conn->request_info.num_headers; i++) {
  9781. (void)mg_snprintf(conn,
  9782. &truncated,
  9783. http_var_name,
  9784. sizeof(http_var_name),
  9785. "HTTP_%s",
  9786. conn->request_info.http_headers[i].name);
  9787. if (truncated) {
  9788. mg_cry_internal(conn,
  9789. "%s: HTTP header variable too long [%s]",
  9790. __func__,
  9791. conn->request_info.http_headers[i].name);
  9792. continue;
  9793. }
  9794. /* Convert variable name into uppercase, and change - to _ */
  9795. for (p = http_var_name; *p != '\0'; p++) {
  9796. if (*p == '-') {
  9797. *p = '_';
  9798. }
  9799. *p = (char)toupper((unsigned char)*p);
  9800. }
  9801. addenv(env,
  9802. "%s=%s",
  9803. http_var_name,
  9804. conn->request_info.http_headers[i].value);
  9805. }
  9806. /* Add user-specified variables */
  9807. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9808. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9809. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9810. }
  9811. env->var[env->varused] = NULL;
  9812. env->buf[env->bufused] = '\0';
  9813. return 0;
  9814. }
  9815. /* Data for CGI process control: PID and number of references */
  9816. struct process_control_data {
  9817. pid_t pid;
  9818. int references;
  9819. };
  9820. static int
  9821. abort_process(void *data)
  9822. {
  9823. /* Waitpid checks for child status and won't work for a pid that does
  9824. * not identify a child of the current process. Thus, if the pid is
  9825. * reused, we will not affect a different process. */
  9826. struct process_control_data *proc = (struct process_control_data *)data;
  9827. int status = 0;
  9828. int refs;
  9829. pid_t ret_pid;
  9830. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9831. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9832. /* Stop child process */
  9833. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9834. kill(proc->pid, SIGABRT);
  9835. /* Wait until process is terminated (don't leave zombies) */
  9836. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9837. ;
  9838. } else {
  9839. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9840. }
  9841. /* Dec reference counter */
  9842. refs = mg_atomic_dec(&proc->references);
  9843. if (refs == 0) {
  9844. /* no more references - free data */
  9845. mg_free(data);
  9846. }
  9847. return 0;
  9848. }
  9849. /* Local (static) function assumes all arguments are valid. */
  9850. static void
  9851. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9852. {
  9853. char *buf;
  9854. size_t buflen;
  9855. int headers_len, data_len, i, truncated;
  9856. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9857. const char *status, *status_text, *connection_state;
  9858. char *pbuf, dir[PATH_MAX], *p;
  9859. struct mg_request_info ri;
  9860. struct cgi_environment blk;
  9861. FILE *in = NULL, *out = NULL, *err = NULL;
  9862. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9863. pid_t pid = (pid_t)-1;
  9864. struct process_control_data *proc = NULL;
  9865. #if defined(USE_TIMERS)
  9866. double cgi_timeout = -1.0;
  9867. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9868. /* Get timeout in seconds */
  9869. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9870. }
  9871. #endif
  9872. buf = NULL;
  9873. buflen = conn->phys_ctx->max_request_size;
  9874. i = prepare_cgi_environment(conn, prog, &blk);
  9875. if (i != 0) {
  9876. blk.buf = NULL;
  9877. blk.var = NULL;
  9878. goto done;
  9879. }
  9880. /* CGI must be executed in its own directory. 'dir' must point to the
  9881. * directory containing executable program, 'p' must point to the
  9882. * executable program name relative to 'dir'. */
  9883. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9884. if (truncated) {
  9885. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9886. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9887. goto done;
  9888. }
  9889. if ((p = strrchr(dir, '/')) != NULL) {
  9890. *p++ = '\0';
  9891. } else {
  9892. dir[0] = '.';
  9893. dir[1] = '\0';
  9894. p = (char *)prog;
  9895. }
  9896. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9897. status = strerror(ERRNO);
  9898. mg_cry_internal(
  9899. conn,
  9900. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9901. prog,
  9902. status);
  9903. mg_send_http_error(conn,
  9904. 500,
  9905. "Error: Cannot create CGI pipe: %s",
  9906. status);
  9907. goto done;
  9908. }
  9909. proc = (struct process_control_data *)
  9910. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9911. if (proc == NULL) {
  9912. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9913. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9914. goto done;
  9915. }
  9916. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9917. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9918. if (pid == (pid_t)-1) {
  9919. status = strerror(ERRNO);
  9920. mg_cry_internal(
  9921. conn,
  9922. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9923. prog,
  9924. status);
  9925. mg_send_http_error(conn,
  9926. 500,
  9927. "Error: Cannot spawn CGI process [%s]: %s",
  9928. prog,
  9929. status);
  9930. mg_free(proc);
  9931. proc = NULL;
  9932. goto done;
  9933. }
  9934. /* Store data in shared process_control_data */
  9935. proc->pid = pid;
  9936. proc->references = 1;
  9937. #if defined(USE_TIMERS)
  9938. if (cgi_timeout > 0.0) {
  9939. proc->references = 2;
  9940. // Start a timer for CGI
  9941. timer_add(conn->phys_ctx,
  9942. cgi_timeout /* in seconds */,
  9943. 0.0,
  9944. 1,
  9945. abort_process,
  9946. (void *)proc);
  9947. }
  9948. #endif
  9949. /* Parent closes only one side of the pipes.
  9950. * If we don't mark them as closed, close() attempt before
  9951. * return from this function throws an exception on Windows.
  9952. * Windows does not like when closed descriptor is closed again. */
  9953. (void)close(fdin[0]);
  9954. (void)close(fdout[1]);
  9955. (void)close(fderr[1]);
  9956. fdin[0] = fdout[1] = fderr[1] = -1;
  9957. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9958. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9959. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9960. status = strerror(ERRNO);
  9961. mg_cry_internal(conn,
  9962. "Error: CGI program \"%s\": Can not open fd: %s",
  9963. prog,
  9964. status);
  9965. mg_send_http_error(conn,
  9966. 500,
  9967. "Error: CGI can not open fd\nfdopen: %s",
  9968. status);
  9969. goto done;
  9970. }
  9971. setbuf(in, NULL);
  9972. setbuf(out, NULL);
  9973. setbuf(err, NULL);
  9974. fout.access.fp = out;
  9975. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9976. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9977. conn->content_len);
  9978. /* This is a POST/PUT request, or another request with body data. */
  9979. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9980. /* Error sending the body data */
  9981. mg_cry_internal(
  9982. conn,
  9983. "Error: CGI program \"%s\": Forward body data failed",
  9984. prog);
  9985. goto done;
  9986. }
  9987. }
  9988. /* Close so child gets an EOF. */
  9989. fclose(in);
  9990. in = NULL;
  9991. fdin[1] = -1;
  9992. /* Now read CGI reply into a buffer. We need to set correct
  9993. * status code, thus we need to see all HTTP headers first.
  9994. * Do not send anything back to client, until we buffer in all
  9995. * HTTP headers. */
  9996. data_len = 0;
  9997. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9998. if (buf == NULL) {
  9999. mg_send_http_error(conn,
  10000. 500,
  10001. "Error: Not enough memory for CGI buffer (%u bytes)",
  10002. (unsigned int)buflen);
  10003. mg_cry_internal(
  10004. conn,
  10005. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10006. "bytes)",
  10007. prog,
  10008. (unsigned int)buflen);
  10009. goto done;
  10010. }
  10011. DEBUG_TRACE("CGI: %s", "wait for response");
  10012. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10013. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10014. if (headers_len <= 0) {
  10015. /* Could not parse the CGI response. Check if some error message on
  10016. * stderr. */
  10017. i = pull_all(err, conn, buf, (int)buflen);
  10018. if (i > 0) {
  10019. /* CGI program explicitly sent an error */
  10020. /* Write the error message to the internal log */
  10021. mg_cry_internal(conn,
  10022. "Error: CGI program \"%s\" sent error "
  10023. "message: [%.*s]",
  10024. prog,
  10025. i,
  10026. buf);
  10027. /* Don't send the error message back to the client */
  10028. mg_send_http_error(conn,
  10029. 500,
  10030. "Error: CGI program \"%s\" failed.",
  10031. prog);
  10032. } else {
  10033. /* CGI program did not explicitly send an error, but a broken
  10034. * respon header */
  10035. mg_cry_internal(conn,
  10036. "Error: CGI program sent malformed or too big "
  10037. "(>%u bytes) HTTP headers: [%.*s]",
  10038. (unsigned)buflen,
  10039. data_len,
  10040. buf);
  10041. mg_send_http_error(conn,
  10042. 500,
  10043. "Error: CGI program sent malformed or too big "
  10044. "(>%u bytes) HTTP headers: [%.*s]",
  10045. (unsigned)buflen,
  10046. data_len,
  10047. buf);
  10048. }
  10049. /* in both cases, abort processing CGI */
  10050. goto done;
  10051. }
  10052. pbuf = buf;
  10053. buf[headers_len - 1] = '\0';
  10054. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10055. /* Make up and send the status line */
  10056. status_text = "OK";
  10057. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10058. != NULL) {
  10059. conn->status_code = atoi(status);
  10060. status_text = status;
  10061. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10062. status_text++;
  10063. }
  10064. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10065. != NULL) {
  10066. conn->status_code = 307;
  10067. } else {
  10068. conn->status_code = 200;
  10069. }
  10070. connection_state =
  10071. get_header(ri.http_headers, ri.num_headers, "Connection");
  10072. if (!header_has_option(connection_state, "keep-alive")) {
  10073. conn->must_close = 1;
  10074. }
  10075. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10076. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10077. /* Send headers */
  10078. for (i = 0; i < ri.num_headers; i++) {
  10079. DEBUG_TRACE("CGI header: %s: %s",
  10080. ri.http_headers[i].name,
  10081. ri.http_headers[i].value);
  10082. mg_printf(conn,
  10083. "%s: %s\r\n",
  10084. ri.http_headers[i].name,
  10085. ri.http_headers[i].value);
  10086. }
  10087. mg_write(conn, "\r\n", 2);
  10088. /* Send chunk of data that may have been read after the headers */
  10089. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10090. /* Read the rest of CGI output and send to the client */
  10091. DEBUG_TRACE("CGI: %s", "forward all data");
  10092. send_file_data(conn, &fout, 0, INT64_MAX);
  10093. DEBUG_TRACE("CGI: %s", "all data sent");
  10094. done:
  10095. mg_free(blk.var);
  10096. mg_free(blk.buf);
  10097. if (pid != (pid_t)-1) {
  10098. abort_process((void *)proc);
  10099. }
  10100. if (fdin[0] != -1) {
  10101. close(fdin[0]);
  10102. }
  10103. if (fdout[1] != -1) {
  10104. close(fdout[1]);
  10105. }
  10106. if (fderr[1] != -1) {
  10107. close(fderr[1]);
  10108. }
  10109. if (in != NULL) {
  10110. fclose(in);
  10111. } else if (fdin[1] != -1) {
  10112. close(fdin[1]);
  10113. }
  10114. if (out != NULL) {
  10115. fclose(out);
  10116. } else if (fdout[0] != -1) {
  10117. close(fdout[0]);
  10118. }
  10119. if (err != NULL) {
  10120. fclose(err);
  10121. } else if (fderr[0] != -1) {
  10122. close(fderr[0]);
  10123. }
  10124. mg_free(buf);
  10125. }
  10126. #endif /* !NO_CGI */
  10127. #if !defined(NO_FILES)
  10128. static void
  10129. mkcol(struct mg_connection *conn, const char *path)
  10130. {
  10131. int rc, body_len;
  10132. struct de de;
  10133. char date[64];
  10134. time_t curtime = time(NULL);
  10135. if (conn == NULL) {
  10136. return;
  10137. }
  10138. /* TODO (mid): Check the mg_send_http_error situations in this function
  10139. */
  10140. memset(&de.file, 0, sizeof(de.file));
  10141. if (!mg_stat(conn, path, &de.file)) {
  10142. mg_cry_internal(conn,
  10143. "%s: mg_stat(%s) failed: %s",
  10144. __func__,
  10145. path,
  10146. strerror(ERRNO));
  10147. }
  10148. if (de.file.last_modified) {
  10149. /* TODO (mid): This check does not seem to make any sense ! */
  10150. /* TODO (mid): Add a webdav unit test first, before changing
  10151. * anything here. */
  10152. mg_send_http_error(
  10153. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10154. return;
  10155. }
  10156. body_len = conn->data_len - conn->request_len;
  10157. if (body_len > 0) {
  10158. mg_send_http_error(
  10159. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10160. return;
  10161. }
  10162. rc = mg_mkdir(conn, path, 0755);
  10163. if (rc == 0) {
  10164. conn->status_code = 201;
  10165. gmt_time_string(date, sizeof(date), &curtime);
  10166. mg_printf(conn,
  10167. "HTTP/1.1 %d Created\r\n"
  10168. "Date: %s\r\n",
  10169. conn->status_code,
  10170. date);
  10171. send_static_cache_header(conn);
  10172. send_additional_header(conn);
  10173. mg_printf(conn,
  10174. "Content-Length: 0\r\n"
  10175. "Connection: %s\r\n\r\n",
  10176. suggest_connection_header(conn));
  10177. } else {
  10178. if (errno == EEXIST) {
  10179. mg_send_http_error(
  10180. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10181. } else if (errno == EACCES) {
  10182. mg_send_http_error(
  10183. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10184. } else if (errno == ENOENT) {
  10185. mg_send_http_error(
  10186. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10187. } else {
  10188. mg_send_http_error(
  10189. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10190. }
  10191. }
  10192. }
  10193. static void
  10194. put_file(struct mg_connection *conn, const char *path)
  10195. {
  10196. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10197. const char *range;
  10198. int64_t r1, r2;
  10199. int rc;
  10200. char date[64];
  10201. time_t curtime = time(NULL);
  10202. if (conn == NULL) {
  10203. return;
  10204. }
  10205. if (mg_stat(conn, path, &file.stat)) {
  10206. /* File already exists */
  10207. conn->status_code = 200;
  10208. if (file.stat.is_directory) {
  10209. /* This is an already existing directory,
  10210. * so there is nothing to do for the server. */
  10211. rc = 0;
  10212. } else {
  10213. /* File exists and is not a directory. */
  10214. /* Can it be replaced? */
  10215. #if defined(MG_USE_OPEN_FILE)
  10216. if (file.access.membuf != NULL) {
  10217. /* This is an "in-memory" file, that can not be replaced */
  10218. mg_send_http_error(conn,
  10219. 405,
  10220. "Error: Put not possible\nReplacing %s "
  10221. "is not supported",
  10222. path);
  10223. return;
  10224. }
  10225. #endif
  10226. /* Check if the server may write this file */
  10227. if (access(path, W_OK) == 0) {
  10228. /* Access granted */
  10229. rc = 1;
  10230. } else {
  10231. mg_send_http_error(
  10232. conn,
  10233. 403,
  10234. "Error: Put not possible\nReplacing %s is not allowed",
  10235. path);
  10236. return;
  10237. }
  10238. }
  10239. } else {
  10240. /* File should be created */
  10241. conn->status_code = 201;
  10242. rc = put_dir(conn, path);
  10243. }
  10244. if (rc == 0) {
  10245. /* put_dir returns 0 if path is a directory */
  10246. gmt_time_string(date, sizeof(date), &curtime);
  10247. mg_printf(conn,
  10248. "HTTP/1.1 %d %s\r\n",
  10249. conn->status_code,
  10250. mg_get_response_code_text(NULL, conn->status_code));
  10251. send_no_cache_header(conn);
  10252. send_additional_header(conn);
  10253. mg_printf(conn,
  10254. "Date: %s\r\n"
  10255. "Content-Length: 0\r\n"
  10256. "Connection: %s\r\n\r\n",
  10257. date,
  10258. suggest_connection_header(conn));
  10259. /* Request to create a directory has been fulfilled successfully.
  10260. * No need to put a file. */
  10261. return;
  10262. }
  10263. if (rc == -1) {
  10264. /* put_dir returns -1 if the path is too long */
  10265. mg_send_http_error(conn,
  10266. 414,
  10267. "Error: Path too long\nput_dir(%s): %s",
  10268. path,
  10269. strerror(ERRNO));
  10270. return;
  10271. }
  10272. if (rc == -2) {
  10273. /* put_dir returns -2 if the directory can not be created */
  10274. mg_send_http_error(conn,
  10275. 500,
  10276. "Error: Can not create directory\nput_dir(%s): %s",
  10277. path,
  10278. strerror(ERRNO));
  10279. return;
  10280. }
  10281. /* A file should be created or overwritten. */
  10282. /* Currently CivetWeb does not nead read+write access. */
  10283. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10284. || file.access.fp == NULL) {
  10285. (void)mg_fclose(&file.access);
  10286. mg_send_http_error(conn,
  10287. 500,
  10288. "Error: Can not create file\nfopen(%s): %s",
  10289. path,
  10290. strerror(ERRNO));
  10291. return;
  10292. }
  10293. fclose_on_exec(&file.access, conn);
  10294. range = mg_get_header(conn, "Content-Range");
  10295. r1 = r2 = 0;
  10296. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10297. conn->status_code = 206; /* Partial content */
  10298. fseeko(file.access.fp, r1, SEEK_SET);
  10299. }
  10300. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10301. /* forward_body_data failed.
  10302. * The error code has already been sent to the client,
  10303. * and conn->status_code is already set. */
  10304. (void)mg_fclose(&file.access);
  10305. return;
  10306. }
  10307. if (mg_fclose(&file.access) != 0) {
  10308. /* fclose failed. This might have different reasons, but a likely
  10309. * one is "no space on disk", http 507. */
  10310. conn->status_code = 507;
  10311. }
  10312. gmt_time_string(date, sizeof(date), &curtime);
  10313. mg_printf(conn,
  10314. "HTTP/1.1 %d %s\r\n",
  10315. conn->status_code,
  10316. mg_get_response_code_text(NULL, conn->status_code));
  10317. send_no_cache_header(conn);
  10318. send_additional_header(conn);
  10319. mg_printf(conn,
  10320. "Date: %s\r\n"
  10321. "Content-Length: 0\r\n"
  10322. "Connection: %s\r\n\r\n",
  10323. date,
  10324. suggest_connection_header(conn));
  10325. }
  10326. static void
  10327. delete_file(struct mg_connection *conn, const char *path)
  10328. {
  10329. struct de de;
  10330. memset(&de.file, 0, sizeof(de.file));
  10331. if (!mg_stat(conn, path, &de.file)) {
  10332. /* mg_stat returns 0 if the file does not exist */
  10333. mg_send_http_error(conn,
  10334. 404,
  10335. "Error: Cannot delete file\nFile %s not found",
  10336. path);
  10337. return;
  10338. }
  10339. #if 0 /* Ignore if a file in memory is inside a folder */
  10340. if (de.access.membuf != NULL) {
  10341. /* the file is cached in memory */
  10342. mg_send_http_error(
  10343. conn,
  10344. 405,
  10345. "Error: Delete not possible\nDeleting %s is not supported",
  10346. path);
  10347. return;
  10348. }
  10349. #endif
  10350. if (de.file.is_directory) {
  10351. if (remove_directory(conn, path)) {
  10352. /* Delete is successful: Return 204 without content. */
  10353. mg_send_http_error(conn, 204, "%s", "");
  10354. } else {
  10355. /* Delete is not successful: Return 500 (Server error). */
  10356. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10357. }
  10358. return;
  10359. }
  10360. /* This is an existing file (not a directory).
  10361. * Check if write permission is granted. */
  10362. if (access(path, W_OK) != 0) {
  10363. /* File is read only */
  10364. mg_send_http_error(
  10365. conn,
  10366. 403,
  10367. "Error: Delete not possible\nDeleting %s is not allowed",
  10368. path);
  10369. return;
  10370. }
  10371. /* Try to delete it. */
  10372. if (mg_remove(conn, path) == 0) {
  10373. /* Delete was successful: Return 204 without content. */
  10374. mg_send_http_error(conn, 204, "%s", "");
  10375. } else {
  10376. /* Delete not successful (file locked). */
  10377. mg_send_http_error(conn,
  10378. 423,
  10379. "Error: Cannot delete file\nremove(%s): %s",
  10380. path,
  10381. strerror(ERRNO));
  10382. }
  10383. }
  10384. #endif /* !NO_FILES */
  10385. #if !defined(NO_FILESYSTEMS)
  10386. static void
  10387. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10388. static void
  10389. do_ssi_include(struct mg_connection *conn,
  10390. const char *ssi,
  10391. char *tag,
  10392. int include_level)
  10393. {
  10394. char file_name[MG_BUF_LEN], path[512], *p;
  10395. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10396. size_t len;
  10397. int truncated = 0;
  10398. if (conn == NULL) {
  10399. return;
  10400. }
  10401. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10402. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10403. * always < MG_BUF_LEN. */
  10404. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10405. /* File name is relative to the webserver root */
  10406. file_name[511] = 0;
  10407. (void)mg_snprintf(conn,
  10408. &truncated,
  10409. path,
  10410. sizeof(path),
  10411. "%s/%s",
  10412. conn->dom_ctx->config[DOCUMENT_ROOT],
  10413. file_name);
  10414. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10415. /* File name is relative to the webserver working directory
  10416. * or it is absolute system path */
  10417. file_name[511] = 0;
  10418. (void)
  10419. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10420. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10421. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10422. /* File name is relative to the currect document */
  10423. file_name[511] = 0;
  10424. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10425. if (!truncated) {
  10426. if ((p = strrchr(path, '/')) != NULL) {
  10427. p[1] = '\0';
  10428. }
  10429. len = strlen(path);
  10430. (void)mg_snprintf(conn,
  10431. &truncated,
  10432. path + len,
  10433. sizeof(path) - len,
  10434. "%s",
  10435. file_name);
  10436. }
  10437. } else {
  10438. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10439. return;
  10440. }
  10441. if (truncated) {
  10442. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10443. return;
  10444. }
  10445. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10446. mg_cry_internal(conn,
  10447. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10448. tag,
  10449. path,
  10450. strerror(ERRNO));
  10451. } else {
  10452. fclose_on_exec(&file.access, conn);
  10453. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10454. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10455. path)
  10456. > 0) {
  10457. send_ssi_file(conn, path, &file, include_level + 1);
  10458. } else {
  10459. send_file_data(conn, &file, 0, INT64_MAX);
  10460. }
  10461. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10462. }
  10463. }
  10464. #if !defined(NO_POPEN)
  10465. static void
  10466. do_ssi_exec(struct mg_connection *conn, char *tag)
  10467. {
  10468. char cmd[1024] = "";
  10469. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10470. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10471. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10472. } else {
  10473. cmd[1023] = 0;
  10474. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10475. mg_cry_internal(conn,
  10476. "Cannot SSI #exec: [%s]: %s",
  10477. cmd,
  10478. strerror(ERRNO));
  10479. } else {
  10480. send_file_data(conn, &file, 0, INT64_MAX);
  10481. pclose(file.access.fp);
  10482. }
  10483. }
  10484. }
  10485. #endif /* !NO_POPEN */
  10486. static int
  10487. mg_fgetc(struct mg_file *filep, int offset)
  10488. {
  10489. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10490. if (filep == NULL) {
  10491. return EOF;
  10492. }
  10493. #if defined(MG_USE_OPEN_FILE)
  10494. if ((filep->access.membuf != NULL) && (offset >= 0)
  10495. && (((unsigned int)(offset)) < filep->stat.size)) {
  10496. return ((const unsigned char *)filep->access.membuf)[offset];
  10497. } else /* else block below */
  10498. #endif
  10499. if (filep->access.fp != NULL) {
  10500. return fgetc(filep->access.fp);
  10501. } else {
  10502. return EOF;
  10503. }
  10504. }
  10505. static void
  10506. send_ssi_file(struct mg_connection *conn,
  10507. const char *path,
  10508. struct mg_file *filep,
  10509. int include_level)
  10510. {
  10511. char buf[MG_BUF_LEN];
  10512. int ch, offset, len, in_tag, in_ssi_tag;
  10513. if (include_level > 10) {
  10514. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10515. return;
  10516. }
  10517. in_tag = in_ssi_tag = len = offset = 0;
  10518. /* Read file, byte by byte, and look for SSI include tags */
  10519. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10520. if (in_tag) {
  10521. /* We are in a tag, either SSI tag or html tag */
  10522. if (ch == '>') {
  10523. /* Tag is closing */
  10524. buf[len++] = '>';
  10525. if (in_ssi_tag) {
  10526. /* Handle SSI tag */
  10527. buf[len] = 0;
  10528. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10529. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10530. #if !defined(NO_POPEN)
  10531. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10532. do_ssi_exec(conn, buf + 9);
  10533. #endif /* !NO_POPEN */
  10534. } else {
  10535. mg_cry_internal(conn,
  10536. "%s: unknown SSI "
  10537. "command: \"%s\"",
  10538. path,
  10539. buf);
  10540. }
  10541. len = 0;
  10542. in_ssi_tag = in_tag = 0;
  10543. } else {
  10544. /* Not an SSI tag */
  10545. /* Flush buffer */
  10546. (void)mg_write(conn, buf, (size_t)len);
  10547. len = 0;
  10548. in_tag = 0;
  10549. }
  10550. } else {
  10551. /* Tag is still open */
  10552. buf[len++] = (char)(ch & 0xff);
  10553. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10554. /* All SSI tags start with <!--# */
  10555. in_ssi_tag = 1;
  10556. }
  10557. if ((len + 2) > (int)sizeof(buf)) {
  10558. /* Tag to long for buffer */
  10559. mg_cry_internal(conn, "%s: tag is too large", path);
  10560. return;
  10561. }
  10562. }
  10563. } else {
  10564. /* We are not in a tag yet. */
  10565. if (ch == '<') {
  10566. /* Tag is opening */
  10567. in_tag = 1;
  10568. if (len > 0) {
  10569. /* Flush current buffer.
  10570. * Buffer is filled with "len" bytes. */
  10571. (void)mg_write(conn, buf, (size_t)len);
  10572. }
  10573. /* Store the < */
  10574. len = 1;
  10575. buf[0] = '<';
  10576. } else {
  10577. /* No Tag */
  10578. /* Add data to buffer */
  10579. buf[len++] = (char)(ch & 0xff);
  10580. /* Flush if buffer is full */
  10581. if (len == (int)sizeof(buf)) {
  10582. mg_write(conn, buf, (size_t)len);
  10583. len = 0;
  10584. }
  10585. }
  10586. }
  10587. }
  10588. /* Send the rest of buffered data */
  10589. if (len > 0) {
  10590. mg_write(conn, buf, (size_t)len);
  10591. }
  10592. }
  10593. static void
  10594. handle_ssi_file_request(struct mg_connection *conn,
  10595. const char *path,
  10596. struct mg_file *filep)
  10597. {
  10598. char date[64];
  10599. time_t curtime = time(NULL);
  10600. const char *cors_orig_cfg;
  10601. const char *cors1, *cors2, *cors3;
  10602. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10603. return;
  10604. }
  10605. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10606. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10607. /* Cross-origin resource sharing (CORS). */
  10608. cors1 = "Access-Control-Allow-Origin: ";
  10609. cors2 = cors_orig_cfg;
  10610. cors3 = "\r\n";
  10611. } else {
  10612. cors1 = cors2 = cors3 = "";
  10613. }
  10614. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10615. /* File exists (precondition for calling this function),
  10616. * but can not be opened by the server. */
  10617. mg_send_http_error(conn,
  10618. 500,
  10619. "Error: Cannot read file\nfopen(%s): %s",
  10620. path,
  10621. strerror(ERRNO));
  10622. } else {
  10623. conn->must_close = 1;
  10624. gmt_time_string(date, sizeof(date), &curtime);
  10625. fclose_on_exec(&filep->access, conn);
  10626. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10627. send_no_cache_header(conn);
  10628. send_additional_header(conn);
  10629. mg_printf(conn,
  10630. "%s%s%s"
  10631. "Date: %s\r\n"
  10632. "Content-Type: text/html\r\n"
  10633. "Connection: %s\r\n\r\n",
  10634. cors1,
  10635. cors2,
  10636. cors3,
  10637. date,
  10638. suggest_connection_header(conn));
  10639. send_ssi_file(conn, path, filep, 0);
  10640. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10641. }
  10642. }
  10643. #endif /* NO_FILESYSTEMS */
  10644. #if !defined(NO_FILES)
  10645. static void
  10646. send_options(struct mg_connection *conn)
  10647. {
  10648. char date[64];
  10649. time_t curtime = time(NULL);
  10650. if (!conn) {
  10651. return;
  10652. }
  10653. conn->status_code = 200;
  10654. conn->must_close = 1;
  10655. gmt_time_string(date, sizeof(date), &curtime);
  10656. /* We do not set a "Cache-Control" header here, but leave the default.
  10657. * Since browsers do not send an OPTIONS request, we can not test the
  10658. * effect anyway. */
  10659. mg_printf(conn,
  10660. "HTTP/1.1 200 OK\r\n"
  10661. "Date: %s\r\n"
  10662. "Connection: %s\r\n"
  10663. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10664. "PROPFIND, MKCOL\r\n"
  10665. "DAV: 1\r\n",
  10666. date,
  10667. suggest_connection_header(conn));
  10668. send_additional_header(conn);
  10669. mg_printf(conn, "\r\n");
  10670. }
  10671. /* Writes PROPFIND properties for a collection element */
  10672. static int
  10673. print_props(struct mg_connection *conn,
  10674. const char *uri,
  10675. const char *name,
  10676. struct mg_file_stat *filep)
  10677. {
  10678. size_t href_size, i, j;
  10679. int len;
  10680. char *href, mtime[64];
  10681. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10682. return 0;
  10683. }
  10684. /* Estimate worst case size for encoding */
  10685. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10686. href = (char *)mg_malloc(href_size);
  10687. if (href == NULL) {
  10688. return 0;
  10689. }
  10690. len = mg_url_encode(uri, href, href_size);
  10691. if (len >= 0) {
  10692. /* Append an extra string */
  10693. mg_url_encode(name, href + len, href_size - (size_t)len);
  10694. }
  10695. /* Directory separator should be preserved. */
  10696. for (i = j = 0; href[i]; j++) {
  10697. if (!strncmp(href + i, "%2f", 3)) {
  10698. href[j] = '/';
  10699. i += 3;
  10700. } else {
  10701. href[j] = href[i++];
  10702. }
  10703. }
  10704. href[j] = '\0';
  10705. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10706. mg_printf(conn,
  10707. "<d:response>"
  10708. "<d:href>%s</d:href>"
  10709. "<d:propstat>"
  10710. "<d:prop>"
  10711. "<d:resourcetype>%s</d:resourcetype>"
  10712. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10713. "<d:getlastmodified>%s</d:getlastmodified>"
  10714. "</d:prop>"
  10715. "<d:status>HTTP/1.1 200 OK</d:status>"
  10716. "</d:propstat>"
  10717. "</d:response>\n",
  10718. href,
  10719. filep->is_directory ? "<d:collection/>" : "",
  10720. filep->size,
  10721. mtime);
  10722. mg_free(href);
  10723. return 1;
  10724. }
  10725. static int
  10726. print_dav_dir_entry(struct de *de, void *data)
  10727. {
  10728. struct mg_connection *conn = (struct mg_connection *)data;
  10729. if (!de || !conn
  10730. || !print_props(
  10731. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10732. return -1;
  10733. }
  10734. return 0;
  10735. }
  10736. static void
  10737. handle_propfind(struct mg_connection *conn,
  10738. const char *path,
  10739. struct mg_file_stat *filep)
  10740. {
  10741. const char *depth = mg_get_header(conn, "Depth");
  10742. char date[64];
  10743. time_t curtime = time(NULL);
  10744. gmt_time_string(date, sizeof(date), &curtime);
  10745. if (!conn || !path || !filep || !conn->dom_ctx) {
  10746. return;
  10747. }
  10748. conn->must_close = 1;
  10749. conn->status_code = 207;
  10750. mg_printf(conn,
  10751. "HTTP/1.1 207 Multi-Status\r\n"
  10752. "Date: %s\r\n",
  10753. date);
  10754. send_static_cache_header(conn);
  10755. send_additional_header(conn);
  10756. mg_printf(conn,
  10757. "Connection: %s\r\n"
  10758. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10759. suggest_connection_header(conn));
  10760. mg_printf(conn,
  10761. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10762. "<d:multistatus xmlns:d='DAV:'>\n");
  10763. /* Print properties for the requested resource itself */
  10764. print_props(conn, conn->request_info.local_uri, "", filep);
  10765. /* If it is a directory, print directory entries too if Depth is not 0
  10766. */
  10767. if (filep->is_directory
  10768. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10769. "yes")
  10770. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10771. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10772. }
  10773. mg_printf(conn, "%s\n", "</d:multistatus>");
  10774. }
  10775. #endif
  10776. void
  10777. mg_lock_connection(struct mg_connection *conn)
  10778. {
  10779. if (conn) {
  10780. (void)pthread_mutex_lock(&conn->mutex);
  10781. }
  10782. }
  10783. void
  10784. mg_unlock_connection(struct mg_connection *conn)
  10785. {
  10786. if (conn) {
  10787. (void)pthread_mutex_unlock(&conn->mutex);
  10788. }
  10789. }
  10790. void
  10791. mg_lock_context(struct mg_context *ctx)
  10792. {
  10793. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10794. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10795. }
  10796. }
  10797. void
  10798. mg_unlock_context(struct mg_context *ctx)
  10799. {
  10800. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10801. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10802. }
  10803. }
  10804. #if defined(USE_LUA)
  10805. #include "mod_lua.inl"
  10806. #endif /* USE_LUA */
  10807. #if defined(USE_DUKTAPE)
  10808. #include "mod_duktape.inl"
  10809. #endif /* USE_DUKTAPE */
  10810. #if defined(USE_WEBSOCKET)
  10811. #if !defined(NO_SSL_DL)
  10812. #define SHA_API static
  10813. #include "sha1.inl"
  10814. #endif
  10815. static int
  10816. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10817. {
  10818. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10819. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10820. SHA_CTX sha_ctx;
  10821. int truncated;
  10822. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10823. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10824. if (truncated) {
  10825. conn->must_close = 1;
  10826. return 0;
  10827. }
  10828. DEBUG_TRACE("%s", "Send websocket handshake");
  10829. SHA1_Init(&sha_ctx);
  10830. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10831. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10832. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10833. mg_printf(conn,
  10834. "HTTP/1.1 101 Switching Protocols\r\n"
  10835. "Upgrade: websocket\r\n"
  10836. "Connection: Upgrade\r\n"
  10837. "Sec-WebSocket-Accept: %s\r\n",
  10838. b64_sha);
  10839. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10840. mg_printf(conn,
  10841. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10842. conn->request_info.acceptedWebSocketSubprotocol);
  10843. } else {
  10844. mg_printf(conn, "%s", "\r\n");
  10845. }
  10846. return 1;
  10847. }
  10848. #if !defined(MG_MAX_UNANSWERED_PING)
  10849. /* Configuration of the maximum number of websocket PINGs that might
  10850. * stay unanswered before the connection is considered broken.
  10851. * Note: The name of this define may still change (until it is
  10852. * defined as a compile parameter in a documentation).
  10853. */
  10854. #define MG_MAX_UNANSWERED_PING (5)
  10855. #endif
  10856. static void
  10857. read_websocket(struct mg_connection *conn,
  10858. mg_websocket_data_handler ws_data_handler,
  10859. void *callback_data)
  10860. {
  10861. /* Pointer to the beginning of the portion of the incoming websocket
  10862. * message queue.
  10863. * The original websocket upgrade request is never removed, so the queue
  10864. * begins after it. */
  10865. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10866. int n, error, exit_by_callback;
  10867. int ret;
  10868. /* body_len is the length of the entire queue in bytes
  10869. * len is the length of the current message
  10870. * data_len is the length of the current message's data payload
  10871. * header_len is the length of the current message's header */
  10872. size_t i, len, mask_len = 0, header_len, body_len;
  10873. uint64_t data_len = 0;
  10874. /* "The masking key is a 32-bit value chosen at random by the client."
  10875. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10876. */
  10877. unsigned char mask[4];
  10878. /* data points to the place where the message is stored when passed to
  10879. * the websocket_data callback. This is either mem on the stack, or a
  10880. * dynamically allocated buffer if it is too large. */
  10881. unsigned char mem[4096];
  10882. unsigned char mop; /* mask flag and opcode */
  10883. /* Variables used for connection monitoring */
  10884. double timeout = -1.0;
  10885. int enable_ping_pong = 0;
  10886. int ping_count = 0;
  10887. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10888. enable_ping_pong =
  10889. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10890. "yes");
  10891. }
  10892. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10893. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10894. }
  10895. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10896. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10897. }
  10898. /* Enter data processing loop */
  10899. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10900. conn->request_info.remote_addr,
  10901. conn->request_info.remote_port);
  10902. conn->in_websocket_handling = 1;
  10903. mg_set_thread_name("wsock");
  10904. /* Loop continuously, reading messages from the socket, invoking the
  10905. * callback, and waiting repeatedly until an error occurs. */
  10906. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10907. && (!conn->must_close)) {
  10908. header_len = 0;
  10909. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10910. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10911. len = buf[1] & 127;
  10912. mask_len = (buf[1] & 128) ? 4 : 0;
  10913. if ((len < 126) && (body_len >= mask_len)) {
  10914. /* inline 7-bit length field */
  10915. data_len = len;
  10916. header_len = 2 + mask_len;
  10917. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10918. /* 16-bit length field */
  10919. header_len = 4 + mask_len;
  10920. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10921. } else if (body_len >= (10 + mask_len)) {
  10922. /* 64-bit length field */
  10923. uint32_t l1, l2;
  10924. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10925. memcpy(&l2, &buf[6], 4);
  10926. header_len = 10 + mask_len;
  10927. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10928. if (data_len > (uint64_t)0x7FFF0000ul) {
  10929. /* no can do */
  10930. mg_cry_internal(
  10931. conn,
  10932. "%s",
  10933. "websocket out of memory; closing connection");
  10934. break;
  10935. }
  10936. }
  10937. }
  10938. if ((header_len > 0) && (body_len >= header_len)) {
  10939. /* Allocate space to hold websocket payload */
  10940. unsigned char *data = mem;
  10941. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10942. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10943. conn->phys_ctx);
  10944. if (data == NULL) {
  10945. /* Allocation failed, exit the loop and then close the
  10946. * connection */
  10947. mg_cry_internal(
  10948. conn,
  10949. "%s",
  10950. "websocket out of memory; closing connection");
  10951. break;
  10952. }
  10953. }
  10954. /* Copy the mask before we shift the queue and destroy it */
  10955. if (mask_len > 0) {
  10956. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10957. } else {
  10958. memset(mask, 0, sizeof(mask));
  10959. }
  10960. /* Read frame payload from the first message in the queue into
  10961. * data and advance the queue by moving the memory in place. */
  10962. DEBUG_ASSERT(body_len >= header_len);
  10963. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10964. mop = buf[0]; /* current mask and opcode */
  10965. /* Overflow case */
  10966. len = body_len - header_len;
  10967. memcpy(data, buf + header_len, len);
  10968. error = 0;
  10969. while ((uint64_t)len < data_len) {
  10970. n = pull_inner(NULL,
  10971. conn,
  10972. (char *)(data + len),
  10973. (int)(data_len - len),
  10974. timeout);
  10975. if (n <= -2) {
  10976. error = 1;
  10977. break;
  10978. } else if (n > 0) {
  10979. len += (size_t)n;
  10980. } else {
  10981. /* Timeout: should retry */
  10982. /* TODO: retry condition */
  10983. }
  10984. }
  10985. if (error) {
  10986. mg_cry_internal(
  10987. conn,
  10988. "%s",
  10989. "Websocket pull failed; closing connection");
  10990. if (data != mem) {
  10991. mg_free(data);
  10992. }
  10993. break;
  10994. }
  10995. conn->data_len = conn->request_len;
  10996. } else {
  10997. mop = buf[0]; /* current mask and opcode, overwritten by
  10998. * memmove() */
  10999. /* Length of the message being read at the front of the
  11000. * queue. Cast to 31 bit is OK, since we limited
  11001. * data_len before. */
  11002. len = (size_t)data_len + header_len;
  11003. /* Copy the data payload into the data pointer for the
  11004. * callback. Cast to 31 bit is OK, since we
  11005. * limited data_len */
  11006. memcpy(data, buf + header_len, (size_t)data_len);
  11007. /* Move the queue forward len bytes */
  11008. memmove(buf, buf + len, body_len - len);
  11009. /* Mark the queue as advanced */
  11010. conn->data_len -= (int)len;
  11011. }
  11012. /* Apply mask if necessary */
  11013. if (mask_len > 0) {
  11014. for (i = 0; i < (size_t)data_len; i++) {
  11015. data[i] ^= mask[i & 3];
  11016. }
  11017. }
  11018. exit_by_callback = 0;
  11019. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11020. /* filter PONG messages */
  11021. DEBUG_TRACE("PONG from %s:%u",
  11022. conn->request_info.remote_addr,
  11023. conn->request_info.remote_port);
  11024. /* No unanwered PINGs left */
  11025. ping_count = 0;
  11026. } else if (enable_ping_pong
  11027. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11028. /* reply PING messages */
  11029. DEBUG_TRACE("Reply PING from %s:%u",
  11030. conn->request_info.remote_addr,
  11031. conn->request_info.remote_port);
  11032. ret = mg_websocket_write(conn,
  11033. MG_WEBSOCKET_OPCODE_PONG,
  11034. (char *)data,
  11035. (size_t)data_len);
  11036. if (ret <= 0) {
  11037. /* Error: send failed */
  11038. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11039. break;
  11040. }
  11041. } else {
  11042. /* Exit the loop if callback signals to exit (server side),
  11043. * or "connection close" opcode received (client side). */
  11044. if ((ws_data_handler != NULL)
  11045. && !ws_data_handler(conn,
  11046. mop,
  11047. (char *)data,
  11048. (size_t)data_len,
  11049. callback_data)) {
  11050. exit_by_callback = 1;
  11051. }
  11052. }
  11053. /* It a buffer has been allocated, free it again */
  11054. if (data != mem) {
  11055. mg_free(data);
  11056. }
  11057. if (exit_by_callback) {
  11058. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11059. conn->request_info.remote_addr,
  11060. conn->request_info.remote_port);
  11061. break;
  11062. }
  11063. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11064. /* Opcode == 8, connection close */
  11065. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11066. conn->request_info.remote_addr,
  11067. conn->request_info.remote_port);
  11068. break;
  11069. }
  11070. /* Not breaking the loop, process next websocket frame. */
  11071. } else {
  11072. /* Read from the socket into the next available location in the
  11073. * message queue. */
  11074. n = pull_inner(NULL,
  11075. conn,
  11076. conn->buf + conn->data_len,
  11077. conn->buf_size - conn->data_len,
  11078. timeout);
  11079. if (n <= -2) {
  11080. /* Error, no bytes read */
  11081. DEBUG_TRACE("PULL from %s:%u failed",
  11082. conn->request_info.remote_addr,
  11083. conn->request_info.remote_port);
  11084. break;
  11085. }
  11086. if (n > 0) {
  11087. conn->data_len += n;
  11088. /* Reset open PING count */
  11089. ping_count = 0;
  11090. } else {
  11091. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11092. && (!conn->must_close)) {
  11093. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11094. /* Stop sending PING */
  11095. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11096. "- closing connection",
  11097. ping_count,
  11098. conn->request_info.remote_addr,
  11099. conn->request_info.remote_port);
  11100. break;
  11101. }
  11102. if (enable_ping_pong) {
  11103. /* Send Websocket PING message */
  11104. DEBUG_TRACE("PING to %s:%u",
  11105. conn->request_info.remote_addr,
  11106. conn->request_info.remote_port);
  11107. ret = mg_websocket_write(conn,
  11108. MG_WEBSOCKET_OPCODE_PING,
  11109. NULL,
  11110. 0);
  11111. if (ret <= 0) {
  11112. /* Error: send failed */
  11113. DEBUG_TRACE("Send PING failed (%i)", ret);
  11114. break;
  11115. }
  11116. ping_count++;
  11117. }
  11118. }
  11119. /* Timeout: should retry */
  11120. /* TODO: get timeout def */
  11121. }
  11122. }
  11123. }
  11124. /* Leave data processing loop */
  11125. mg_set_thread_name("worker");
  11126. conn->in_websocket_handling = 0;
  11127. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11128. conn->request_info.remote_addr,
  11129. conn->request_info.remote_port);
  11130. }
  11131. static int
  11132. mg_websocket_write_exec(struct mg_connection *conn,
  11133. int opcode,
  11134. const char *data,
  11135. size_t dataLen,
  11136. uint32_t masking_key)
  11137. {
  11138. unsigned char header[14];
  11139. size_t headerLen;
  11140. int retval;
  11141. #if defined(GCC_DIAGNOSTIC)
  11142. /* Disable spurious conversion warning for GCC */
  11143. #pragma GCC diagnostic push
  11144. #pragma GCC diagnostic ignored "-Wconversion"
  11145. #endif
  11146. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11147. #if defined(GCC_DIAGNOSTIC)
  11148. #pragma GCC diagnostic pop
  11149. #endif
  11150. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11151. if (dataLen < 126) {
  11152. /* inline 7-bit length field */
  11153. header[1] = (unsigned char)dataLen;
  11154. headerLen = 2;
  11155. } else if (dataLen <= 0xFFFF) {
  11156. /* 16-bit length field */
  11157. uint16_t len = htons((uint16_t)dataLen);
  11158. header[1] = 126;
  11159. memcpy(header + 2, &len, 2);
  11160. headerLen = 4;
  11161. } else {
  11162. /* 64-bit length field */
  11163. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11164. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11165. header[1] = 127;
  11166. memcpy(header + 2, &len1, 4);
  11167. memcpy(header + 6, &len2, 4);
  11168. headerLen = 10;
  11169. }
  11170. if (masking_key) {
  11171. /* add mask */
  11172. header[1] |= 0x80;
  11173. memcpy(header + headerLen, &masking_key, 4);
  11174. headerLen += 4;
  11175. }
  11176. /* Note that POSIX/Winsock's send() is threadsafe
  11177. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11178. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11179. * push(), although that is only a problem if the packet is large or
  11180. * outgoing buffer is full). */
  11181. /* TODO: Check if this lock should be moved to user land.
  11182. * Currently the server sets this lock for websockets, but
  11183. * not for any other connection. It must be set for every
  11184. * conn read/written by more than one thread, no matter if
  11185. * it is a websocket or regular connection. */
  11186. (void)mg_lock_connection(conn);
  11187. retval = mg_write(conn, header, headerLen);
  11188. if (retval != (int)headerLen) {
  11189. /* Did not send complete header */
  11190. retval = -1;
  11191. } else {
  11192. if (dataLen > 0) {
  11193. retval = mg_write(conn, data, dataLen);
  11194. }
  11195. /* if dataLen == 0, the header length (2) is returned */
  11196. }
  11197. /* TODO: Remove this unlock as well, when lock is removed. */
  11198. mg_unlock_connection(conn);
  11199. return retval;
  11200. }
  11201. int
  11202. mg_websocket_write(struct mg_connection *conn,
  11203. int opcode,
  11204. const char *data,
  11205. size_t dataLen)
  11206. {
  11207. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11208. }
  11209. static void
  11210. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11211. {
  11212. size_t i = 0;
  11213. i = 0;
  11214. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11215. /* Convert in 32 bit words, if data is 4 byte aligned */
  11216. while (i < (in_len - 3)) {
  11217. *(uint32_t *)(void *)(out + i) =
  11218. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11219. i += 4;
  11220. }
  11221. }
  11222. if (i != in_len) {
  11223. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11224. while (i < in_len) {
  11225. *(uint8_t *)(void *)(out + i) =
  11226. *(uint8_t *)(void *)(in + i)
  11227. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11228. i++;
  11229. }
  11230. }
  11231. }
  11232. int
  11233. mg_websocket_client_write(struct mg_connection *conn,
  11234. int opcode,
  11235. const char *data,
  11236. size_t dataLen)
  11237. {
  11238. int retval = -1;
  11239. char *masked_data =
  11240. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11241. uint32_t masking_key = 0;
  11242. if (masked_data == NULL) {
  11243. /* Return -1 in an error case */
  11244. mg_cry_internal(conn,
  11245. "%s",
  11246. "Cannot allocate buffer for masked websocket response: "
  11247. "Out of memory");
  11248. return -1;
  11249. }
  11250. do {
  11251. /* Get a masking key - but not 0 */
  11252. masking_key = (uint32_t)get_random();
  11253. } while (masking_key == 0);
  11254. mask_data(data, dataLen, masking_key, masked_data);
  11255. retval = mg_websocket_write_exec(
  11256. conn, opcode, masked_data, dataLen, masking_key);
  11257. mg_free(masked_data);
  11258. return retval;
  11259. }
  11260. static void
  11261. handle_websocket_request(struct mg_connection *conn,
  11262. const char *path,
  11263. int is_callback_resource,
  11264. struct mg_websocket_subprotocols *subprotocols,
  11265. mg_websocket_connect_handler ws_connect_handler,
  11266. mg_websocket_ready_handler ws_ready_handler,
  11267. mg_websocket_data_handler ws_data_handler,
  11268. mg_websocket_close_handler ws_close_handler,
  11269. void *cbData)
  11270. {
  11271. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11272. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11273. ptrdiff_t lua_websock = 0;
  11274. #if !defined(USE_LUA)
  11275. (void)path;
  11276. #endif
  11277. /* Step 1: Check websocket protocol version. */
  11278. /* Step 1.1: Check Sec-WebSocket-Key. */
  11279. if (!websock_key) {
  11280. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11281. * requires a Sec-WebSocket-Key header.
  11282. */
  11283. /* It could be the hixie draft version
  11284. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11285. */
  11286. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11287. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11288. char key3[8];
  11289. if ((key1 != NULL) && (key2 != NULL)) {
  11290. /* This version uses 8 byte body data in a GET request */
  11291. conn->content_len = 8;
  11292. if (8 == mg_read(conn, key3, 8)) {
  11293. /* This is the hixie version */
  11294. mg_send_http_error(conn,
  11295. 426,
  11296. "%s",
  11297. "Protocol upgrade to RFC 6455 required");
  11298. return;
  11299. }
  11300. }
  11301. /* This is an unknown version */
  11302. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11303. return;
  11304. }
  11305. /* Step 1.2: Check websocket protocol version. */
  11306. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11307. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11308. /* Reject wrong versions */
  11309. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11310. return;
  11311. }
  11312. /* Step 1.3: Could check for "Host", but we do not really nead this
  11313. * value for anything, so just ignore it. */
  11314. /* Step 2: If a callback is responsible, call it. */
  11315. if (is_callback_resource) {
  11316. /* Step 2.1 check and select subprotocol */
  11317. const char *protocols[64]; // max 64 headers
  11318. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11319. "Sec-WebSocket-Protocol",
  11320. protocols,
  11321. 64);
  11322. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11323. int cnt = 0;
  11324. int idx;
  11325. unsigned long len;
  11326. const char *sep, *curSubProtocol,
  11327. *acceptedWebSocketSubprotocol = NULL;
  11328. /* look for matching subprotocol */
  11329. do {
  11330. const char *protocol = protocols[cnt];
  11331. do {
  11332. sep = strchr(protocol, ',');
  11333. curSubProtocol = protocol;
  11334. len = sep ? (unsigned long)(sep - protocol)
  11335. : (unsigned long)strlen(protocol);
  11336. while (sep && isspace((unsigned char)*++sep))
  11337. ; // ignore leading whitespaces
  11338. protocol = sep;
  11339. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11340. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11341. && (strncmp(curSubProtocol,
  11342. subprotocols->subprotocols[idx],
  11343. len)
  11344. == 0)) {
  11345. acceptedWebSocketSubprotocol =
  11346. subprotocols->subprotocols[idx];
  11347. break;
  11348. }
  11349. }
  11350. } while (sep && !acceptedWebSocketSubprotocol);
  11351. } while (++cnt < nbSubprotocolHeader
  11352. && !acceptedWebSocketSubprotocol);
  11353. conn->request_info.acceptedWebSocketSubprotocol =
  11354. acceptedWebSocketSubprotocol;
  11355. } else if (nbSubprotocolHeader > 0) {
  11356. /* keep legacy behavior */
  11357. const char *protocol = protocols[0];
  11358. /* The protocol is a comma separated list of names. */
  11359. /* The server must only return one value from this list. */
  11360. /* First check if it is a list or just a single value. */
  11361. const char *sep = strrchr(protocol, ',');
  11362. if (sep == NULL) {
  11363. /* Just a single protocol -> accept it. */
  11364. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11365. } else {
  11366. /* Multiple protocols -> accept the last one. */
  11367. /* This is just a quick fix if the client offers multiple
  11368. * protocols. The handler should have a list of accepted
  11369. * protocols on his own
  11370. * and use it to select one protocol among those the client
  11371. * has
  11372. * offered.
  11373. */
  11374. while (isspace((unsigned char)*++sep)) {
  11375. ; /* ignore leading whitespaces */
  11376. }
  11377. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11378. }
  11379. }
  11380. if ((ws_connect_handler != NULL)
  11381. && (ws_connect_handler(conn, cbData) != 0)) {
  11382. /* C callback has returned non-zero, do not proceed with
  11383. * handshake.
  11384. */
  11385. /* Note that C callbacks are no longer called when Lua is
  11386. * responsible, so C can no longer filter callbacks for Lua. */
  11387. return;
  11388. }
  11389. }
  11390. #if defined(USE_LUA)
  11391. /* Step 3: No callback. Check if Lua is responsible. */
  11392. else {
  11393. /* Step 3.1: Check if Lua is responsible. */
  11394. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11395. lua_websock = match_prefix(
  11396. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11397. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11398. path);
  11399. }
  11400. if (lua_websock) {
  11401. /* Step 3.2: Lua is responsible: call it. */
  11402. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11403. if (!conn->lua_websocket_state) {
  11404. /* Lua rejected the new client */
  11405. return;
  11406. }
  11407. }
  11408. }
  11409. #endif
  11410. /* Step 4: Check if there is a responsible websocket handler. */
  11411. if (!is_callback_resource && !lua_websock) {
  11412. /* There is no callback, and Lua is not responsible either. */
  11413. /* Reply with a 404 Not Found. We are still at a standard
  11414. * HTTP request here, before the websocket handshake, so
  11415. * we can still send standard HTTP error replies. */
  11416. mg_send_http_error(conn, 404, "%s", "Not found");
  11417. return;
  11418. }
  11419. /* Step 5: The websocket connection has been accepted */
  11420. if (!send_websocket_handshake(conn, websock_key)) {
  11421. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11422. return;
  11423. }
  11424. /* Step 6: Call the ready handler */
  11425. if (is_callback_resource) {
  11426. if (ws_ready_handler != NULL) {
  11427. ws_ready_handler(conn, cbData);
  11428. }
  11429. #if defined(USE_LUA)
  11430. } else if (lua_websock) {
  11431. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11432. /* the ready handler returned false */
  11433. return;
  11434. }
  11435. #endif
  11436. }
  11437. /* Step 7: Enter the read loop */
  11438. if (is_callback_resource) {
  11439. read_websocket(conn, ws_data_handler, cbData);
  11440. #if defined(USE_LUA)
  11441. } else if (lua_websock) {
  11442. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11443. #endif
  11444. }
  11445. /* Step 8: Call the close handler */
  11446. if (ws_close_handler) {
  11447. ws_close_handler(conn, cbData);
  11448. }
  11449. }
  11450. #endif /* !USE_WEBSOCKET */
  11451. /* Is upgrade request:
  11452. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11453. * 1 = upgrade to websocket
  11454. * 2 = upgrade to HTTP/2
  11455. * -1 = upgrade to unknown protocol
  11456. */
  11457. static int
  11458. should_switch_to_protocol(const struct mg_connection *conn)
  11459. {
  11460. const char *upgrade, *connection;
  11461. /* A websocket protocoll has the following HTTP headers:
  11462. *
  11463. * Connection: Upgrade
  11464. * Upgrade: Websocket
  11465. */
  11466. connection = mg_get_header(conn, "Connection");
  11467. if (connection == NULL) {
  11468. return PROTOCOL_TYPE_HTTP1;
  11469. }
  11470. if (!mg_strcasestr(connection, "upgrade")) {
  11471. return PROTOCOL_TYPE_HTTP1;
  11472. }
  11473. upgrade = mg_get_header(conn, "Upgrade");
  11474. if (upgrade == NULL) {
  11475. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11476. return -1;
  11477. }
  11478. /* Upgrade to ... */
  11479. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11480. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11481. * "Sec-WebSocket-Version" are also required.
  11482. * Don't check them here, since even an unsupported websocket protocol
  11483. * request still IS a websocket request (in contrast to a standard HTTP
  11484. * request). It will fail later in handle_websocket_request.
  11485. */
  11486. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11487. }
  11488. if (0 != mg_strcasestr(upgrade, "h2")) {
  11489. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11490. }
  11491. /* Upgrade to another protocol */
  11492. return -1;
  11493. }
  11494. static int
  11495. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11496. {
  11497. int n;
  11498. unsigned int a, b, c, d, slash;
  11499. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11500. slash = 32;
  11501. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11502. n = 0;
  11503. }
  11504. }
  11505. if ((n > 0) && ((size_t)n == vec->len)) {
  11506. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11507. /* IPv4 format */
  11508. if (sa->sa.sa_family == AF_INET) {
  11509. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11510. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11511. | ((uint32_t)c << 8) | (uint32_t)d;
  11512. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11513. return (ip & mask) == net;
  11514. }
  11515. return 0;
  11516. }
  11517. }
  11518. #if defined(USE_IPV6)
  11519. else {
  11520. char ad[50];
  11521. const char *p;
  11522. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11523. slash = 128;
  11524. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11525. n = 0;
  11526. }
  11527. }
  11528. if ((n <= 0) && no_strict) {
  11529. /* no square brackets? */
  11530. p = strchr(vec->ptr, '/');
  11531. if (p && (p < (vec->ptr + vec->len))) {
  11532. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11533. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11534. n += (int)(p - vec->ptr);
  11535. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11536. } else {
  11537. n = 0;
  11538. }
  11539. } else if (vec->len < sizeof(ad)) {
  11540. n = (int)vec->len;
  11541. slash = 128;
  11542. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11543. }
  11544. }
  11545. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11546. p = ad;
  11547. c = 0;
  11548. /* zone indexes are unsupported, at least two colons are needed */
  11549. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11550. if (*(p++) == ':') {
  11551. c++;
  11552. }
  11553. }
  11554. if ((*p == '\0') && (c >= 2)) {
  11555. struct sockaddr_in6 sin6;
  11556. unsigned int i;
  11557. /* for strict validation, an actual IPv6 argument is needed */
  11558. if (sa->sa.sa_family != AF_INET6) {
  11559. return 0;
  11560. }
  11561. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11562. /* IPv6 format */
  11563. for (i = 0; i < 16; i++) {
  11564. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11565. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11566. uint8_t mask = 0;
  11567. if (8 * i + 8 < slash) {
  11568. mask = 0xFFu;
  11569. } else if (8 * i < slash) {
  11570. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11571. }
  11572. if ((ip & mask) != net) {
  11573. return 0;
  11574. }
  11575. }
  11576. return 1;
  11577. }
  11578. }
  11579. }
  11580. }
  11581. #else
  11582. (void)no_strict;
  11583. #endif
  11584. /* malformed */
  11585. return -1;
  11586. }
  11587. static int
  11588. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11589. {
  11590. int throttle = 0;
  11591. struct vec vec, val;
  11592. char mult;
  11593. double v;
  11594. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11595. mult = ',';
  11596. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11597. || (v < 0)
  11598. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11599. && (mult != ','))) {
  11600. continue;
  11601. }
  11602. v *= (lowercase(&mult) == 'k')
  11603. ? 1024
  11604. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11605. if (vec.len == 1 && vec.ptr[0] == '*') {
  11606. throttle = (int)v;
  11607. } else {
  11608. int matched = parse_match_net(&vec, rsa, 0);
  11609. if (matched >= 0) {
  11610. /* a valid IP subnet */
  11611. if (matched) {
  11612. throttle = (int)v;
  11613. }
  11614. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11615. throttle = (int)v;
  11616. }
  11617. }
  11618. }
  11619. return throttle;
  11620. }
  11621. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11622. #include "handle_form.inl"
  11623. #if defined(MG_LEGACY_INTERFACE)
  11624. /* Implement the deprecated mg_upload function by calling the new
  11625. * mg_handle_form_request function. While mg_upload could only handle
  11626. * HTML forms sent as POST request in multipart/form-data format
  11627. * containing only file input elements, mg_handle_form_request can
  11628. * handle all form input elements and all standard request methods. */
  11629. struct mg_upload_user_data {
  11630. struct mg_connection *conn;
  11631. const char *destination_dir;
  11632. int num_uploaded_files;
  11633. };
  11634. /* Helper function for deprecated mg_upload. */
  11635. static int
  11636. mg_upload_field_found(const char *key,
  11637. const char *filename,
  11638. char *path,
  11639. size_t pathlen,
  11640. void *user_data)
  11641. {
  11642. int truncated = 0;
  11643. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11644. (void)key;
  11645. if (!filename) {
  11646. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11647. return FORM_FIELD_STORAGE_ABORT;
  11648. }
  11649. mg_snprintf(fud->conn,
  11650. &truncated,
  11651. path,
  11652. pathlen - 1,
  11653. "%s/%s",
  11654. fud->destination_dir,
  11655. filename);
  11656. if (truncated) {
  11657. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11658. return FORM_FIELD_STORAGE_ABORT;
  11659. }
  11660. return FORM_FIELD_STORAGE_STORE;
  11661. }
  11662. /* Helper function for deprecated mg_upload. */
  11663. static int
  11664. mg_upload_field_get(const char *key,
  11665. const char *value,
  11666. size_t value_size,
  11667. void *user_data)
  11668. {
  11669. /* Function should never be called */
  11670. (void)key;
  11671. (void)value;
  11672. (void)value_size;
  11673. (void)user_data;
  11674. return 0;
  11675. }
  11676. /* Helper function for deprecated mg_upload. */
  11677. static int
  11678. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11679. {
  11680. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11681. (void)file_size;
  11682. fud->num_uploaded_files++;
  11683. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11684. return 0;
  11685. }
  11686. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11687. int
  11688. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11689. {
  11690. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11691. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11692. mg_upload_field_get,
  11693. mg_upload_field_stored,
  11694. 0};
  11695. int ret;
  11696. fdh.user_data = (void *)&fud;
  11697. ret = mg_handle_form_request(conn, &fdh);
  11698. if (ret < 0) {
  11699. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11700. }
  11701. return fud.num_uploaded_files;
  11702. }
  11703. #endif
  11704. static int
  11705. get_first_ssl_listener_index(const struct mg_context *ctx)
  11706. {
  11707. unsigned int i;
  11708. int idx = -1;
  11709. if (ctx) {
  11710. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11711. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11712. }
  11713. }
  11714. return idx;
  11715. }
  11716. /* Return host (without port) */
  11717. static void
  11718. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11719. {
  11720. const char *host_header =
  11721. get_header(ri->http_headers, ri->num_headers, "Host");
  11722. host->ptr = NULL;
  11723. host->len = 0;
  11724. if (host_header != NULL) {
  11725. char *pos;
  11726. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11727. * is found. */
  11728. if (*host_header == '[') {
  11729. pos = strchr(host_header, ']');
  11730. if (!pos) {
  11731. /* Malformed hostname starts with '[', but no ']' found */
  11732. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11733. return;
  11734. }
  11735. /* terminate after ']' */
  11736. host->ptr = host_header;
  11737. host->len = (size_t)(pos + 1 - host_header);
  11738. } else {
  11739. /* Otherwise, a ':' separates hostname and port number */
  11740. pos = strchr(host_header, ':');
  11741. if (pos != NULL) {
  11742. host->len = (size_t)(pos - host_header);
  11743. } else {
  11744. host->len = strlen(host_header);
  11745. }
  11746. host->ptr = host_header;
  11747. }
  11748. }
  11749. }
  11750. static int
  11751. switch_domain_context(struct mg_connection *conn)
  11752. {
  11753. struct vec host;
  11754. get_host_from_request_info(&host, &conn->request_info);
  11755. if (host.ptr) {
  11756. if (conn->ssl) {
  11757. /* This is a HTTPS connection, maybe we have a hostname
  11758. * from SNI (set in ssl_servername_callback). */
  11759. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11760. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11761. /* We are not using the default domain */
  11762. if ((strlen(sslhost) != host.len)
  11763. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11764. /* Mismatch between SNI domain and HTTP domain */
  11765. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11766. sslhost,
  11767. (int)host.len,
  11768. host.ptr);
  11769. return 0;
  11770. }
  11771. }
  11772. } else {
  11773. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11774. while (dom) {
  11775. if ((strlen(dom->config[AUTHENTICATION_DOMAIN]) == host.len)
  11776. && !mg_strncasecmp(host.ptr,
  11777. dom->config[AUTHENTICATION_DOMAIN],
  11778. host.len)) {
  11779. /* Found matching domain */
  11780. DEBUG_TRACE("HTTP domain %s found",
  11781. dom->config[AUTHENTICATION_DOMAIN]);
  11782. /* TODO: Check if this is a HTTP or HTTPS domain */
  11783. conn->dom_ctx = dom;
  11784. break;
  11785. }
  11786. mg_lock_context(conn->phys_ctx);
  11787. dom = dom->next;
  11788. mg_unlock_context(conn->phys_ctx);
  11789. }
  11790. }
  11791. } else {
  11792. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11793. return 1;
  11794. }
  11795. DEBUG_TRACE("HTTP%s Host: %.*s",
  11796. conn->ssl ? "S" : "",
  11797. (int)host.len,
  11798. host.ptr);
  11799. return 1;
  11800. }
  11801. static void
  11802. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11803. {
  11804. struct vec host;
  11805. char target_url[MG_BUF_LEN];
  11806. int truncated = 0;
  11807. conn->must_close = 1;
  11808. /* Send host, port, uri and (if it exists) ?query_string */
  11809. get_host_from_request_info(&host, &conn->request_info);
  11810. if (host.ptr) {
  11811. /* Use "308 Permanent Redirect" */
  11812. int redirect_code = 308;
  11813. /* Create target URL */
  11814. mg_snprintf(conn,
  11815. &truncated,
  11816. target_url,
  11817. sizeof(target_url),
  11818. "https://%.*s:%d%s%s%s",
  11819. (int)host.len,
  11820. host.ptr,
  11821. (int)ntohs(USA_IN_PORT_UNSAFE(
  11822. &(conn->phys_ctx->listening_sockets[ssl_index].lsa))),
  11823. conn->request_info.local_uri,
  11824. (conn->request_info.query_string == NULL) ? "" : "?",
  11825. (conn->request_info.query_string == NULL)
  11826. ? ""
  11827. : conn->request_info.query_string);
  11828. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11829. * is used as buffer size) */
  11830. if (truncated) {
  11831. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11832. return;
  11833. }
  11834. /* Use redirect helper function */
  11835. mg_send_http_redirect(conn, target_url, redirect_code);
  11836. } else {
  11837. mg_send_http_error(conn, 400, "%s", "Bad Request");
  11838. }
  11839. }
  11840. static void
  11841. mg_set_handler_type(struct mg_context *phys_ctx,
  11842. struct mg_domain_context *dom_ctx,
  11843. const char *uri,
  11844. int handler_type,
  11845. int is_delete_request,
  11846. mg_request_handler handler,
  11847. struct mg_websocket_subprotocols *subprotocols,
  11848. mg_websocket_connect_handler connect_handler,
  11849. mg_websocket_ready_handler ready_handler,
  11850. mg_websocket_data_handler data_handler,
  11851. mg_websocket_close_handler close_handler,
  11852. mg_authorization_handler auth_handler,
  11853. void *cbdata)
  11854. {
  11855. struct mg_handler_info *tmp_rh, **lastref;
  11856. size_t urilen = strlen(uri);
  11857. if (handler_type == WEBSOCKET_HANDLER) {
  11858. DEBUG_ASSERT(handler == NULL);
  11859. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11860. || ready_handler != NULL || data_handler != NULL
  11861. || close_handler != NULL);
  11862. DEBUG_ASSERT(auth_handler == NULL);
  11863. if (handler != NULL) {
  11864. return;
  11865. }
  11866. if (!is_delete_request && (connect_handler == NULL)
  11867. && (ready_handler == NULL) && (data_handler == NULL)
  11868. && (close_handler == NULL)) {
  11869. return;
  11870. }
  11871. if (auth_handler != NULL) {
  11872. return;
  11873. }
  11874. } else if (handler_type == REQUEST_HANDLER) {
  11875. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11876. && data_handler == NULL && close_handler == NULL);
  11877. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11878. DEBUG_ASSERT(auth_handler == NULL);
  11879. if ((connect_handler != NULL) || (ready_handler != NULL)
  11880. || (data_handler != NULL) || (close_handler != NULL)) {
  11881. return;
  11882. }
  11883. if (!is_delete_request && (handler == NULL)) {
  11884. return;
  11885. }
  11886. if (auth_handler != NULL) {
  11887. return;
  11888. }
  11889. } else { /* AUTH_HANDLER */
  11890. DEBUG_ASSERT(handler == NULL);
  11891. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11892. && data_handler == NULL && close_handler == NULL);
  11893. DEBUG_ASSERT(auth_handler != NULL);
  11894. if (handler != NULL) {
  11895. return;
  11896. }
  11897. if ((connect_handler != NULL) || (ready_handler != NULL)
  11898. || (data_handler != NULL) || (close_handler != NULL)) {
  11899. return;
  11900. }
  11901. if (!is_delete_request && (auth_handler == NULL)) {
  11902. return;
  11903. }
  11904. }
  11905. if (!phys_ctx || !dom_ctx) {
  11906. return;
  11907. }
  11908. mg_lock_context(phys_ctx);
  11909. /* first try to find an existing handler */
  11910. do {
  11911. lastref = &(dom_ctx->handlers);
  11912. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11913. tmp_rh = tmp_rh->next) {
  11914. if (tmp_rh->handler_type == handler_type
  11915. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11916. if (!is_delete_request) {
  11917. /* update existing handler */
  11918. if (handler_type == REQUEST_HANDLER) {
  11919. /* Wait for end of use before updating */
  11920. if (tmp_rh->refcount) {
  11921. mg_unlock_context(phys_ctx);
  11922. mg_sleep(1);
  11923. mg_lock_context(phys_ctx);
  11924. /* tmp_rh might have been freed, search again. */
  11925. break;
  11926. }
  11927. /* Ok, the handler is no more use -> Update it */
  11928. tmp_rh->handler = handler;
  11929. } else if (handler_type == WEBSOCKET_HANDLER) {
  11930. tmp_rh->subprotocols = subprotocols;
  11931. tmp_rh->connect_handler = connect_handler;
  11932. tmp_rh->ready_handler = ready_handler;
  11933. tmp_rh->data_handler = data_handler;
  11934. tmp_rh->close_handler = close_handler;
  11935. } else { /* AUTH_HANDLER */
  11936. tmp_rh->auth_handler = auth_handler;
  11937. }
  11938. tmp_rh->cbdata = cbdata;
  11939. } else {
  11940. /* remove existing handler */
  11941. if (handler_type == REQUEST_HANDLER) {
  11942. /* Wait for end of use before removing */
  11943. if (tmp_rh->refcount) {
  11944. tmp_rh->removing = 1;
  11945. mg_unlock_context(phys_ctx);
  11946. mg_sleep(1);
  11947. mg_lock_context(phys_ctx);
  11948. /* tmp_rh might have been freed, search again. */
  11949. break;
  11950. }
  11951. /* Ok, the handler is no more used */
  11952. }
  11953. *lastref = tmp_rh->next;
  11954. mg_free(tmp_rh->uri);
  11955. mg_free(tmp_rh);
  11956. }
  11957. mg_unlock_context(phys_ctx);
  11958. return;
  11959. }
  11960. lastref = &(tmp_rh->next);
  11961. }
  11962. } while (tmp_rh != NULL);
  11963. if (is_delete_request) {
  11964. /* no handler to set, this was a remove request to a non-existing
  11965. * handler */
  11966. mg_unlock_context(phys_ctx);
  11967. return;
  11968. }
  11969. tmp_rh =
  11970. (struct mg_handler_info *)mg_calloc_ctx(1,
  11971. sizeof(struct mg_handler_info),
  11972. phys_ctx);
  11973. if (tmp_rh == NULL) {
  11974. mg_unlock_context(phys_ctx);
  11975. mg_cry_ctx_internal(phys_ctx,
  11976. "%s",
  11977. "Cannot create new request handler struct, OOM");
  11978. return;
  11979. }
  11980. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11981. if (!tmp_rh->uri) {
  11982. mg_unlock_context(phys_ctx);
  11983. mg_free(tmp_rh);
  11984. mg_cry_ctx_internal(phys_ctx,
  11985. "%s",
  11986. "Cannot create new request handler struct, OOM");
  11987. return;
  11988. }
  11989. tmp_rh->uri_len = urilen;
  11990. if (handler_type == REQUEST_HANDLER) {
  11991. tmp_rh->refcount = 0;
  11992. tmp_rh->removing = 0;
  11993. tmp_rh->handler = handler;
  11994. } else if (handler_type == WEBSOCKET_HANDLER) {
  11995. tmp_rh->subprotocols = subprotocols;
  11996. tmp_rh->connect_handler = connect_handler;
  11997. tmp_rh->ready_handler = ready_handler;
  11998. tmp_rh->data_handler = data_handler;
  11999. tmp_rh->close_handler = close_handler;
  12000. } else { /* AUTH_HANDLER */
  12001. tmp_rh->auth_handler = auth_handler;
  12002. }
  12003. tmp_rh->cbdata = cbdata;
  12004. tmp_rh->handler_type = handler_type;
  12005. tmp_rh->next = NULL;
  12006. *lastref = tmp_rh;
  12007. mg_unlock_context(phys_ctx);
  12008. }
  12009. void
  12010. mg_set_request_handler(struct mg_context *ctx,
  12011. const char *uri,
  12012. mg_request_handler handler,
  12013. void *cbdata)
  12014. {
  12015. mg_set_handler_type(ctx,
  12016. &(ctx->dd),
  12017. uri,
  12018. REQUEST_HANDLER,
  12019. handler == NULL,
  12020. handler,
  12021. NULL,
  12022. NULL,
  12023. NULL,
  12024. NULL,
  12025. NULL,
  12026. NULL,
  12027. cbdata);
  12028. }
  12029. void
  12030. mg_set_websocket_handler(struct mg_context *ctx,
  12031. const char *uri,
  12032. mg_websocket_connect_handler connect_handler,
  12033. mg_websocket_ready_handler ready_handler,
  12034. mg_websocket_data_handler data_handler,
  12035. mg_websocket_close_handler close_handler,
  12036. void *cbdata)
  12037. {
  12038. mg_set_websocket_handler_with_subprotocols(ctx,
  12039. uri,
  12040. NULL,
  12041. connect_handler,
  12042. ready_handler,
  12043. data_handler,
  12044. close_handler,
  12045. cbdata);
  12046. }
  12047. void
  12048. mg_set_websocket_handler_with_subprotocols(
  12049. struct mg_context *ctx,
  12050. const char *uri,
  12051. struct mg_websocket_subprotocols *subprotocols,
  12052. mg_websocket_connect_handler connect_handler,
  12053. mg_websocket_ready_handler ready_handler,
  12054. mg_websocket_data_handler data_handler,
  12055. mg_websocket_close_handler close_handler,
  12056. void *cbdata)
  12057. {
  12058. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12059. && (data_handler == NULL)
  12060. && (close_handler == NULL);
  12061. mg_set_handler_type(ctx,
  12062. &(ctx->dd),
  12063. uri,
  12064. WEBSOCKET_HANDLER,
  12065. is_delete_request,
  12066. NULL,
  12067. subprotocols,
  12068. connect_handler,
  12069. ready_handler,
  12070. data_handler,
  12071. close_handler,
  12072. NULL,
  12073. cbdata);
  12074. }
  12075. void
  12076. mg_set_auth_handler(struct mg_context *ctx,
  12077. const char *uri,
  12078. mg_authorization_handler handler,
  12079. void *cbdata)
  12080. {
  12081. mg_set_handler_type(ctx,
  12082. &(ctx->dd),
  12083. uri,
  12084. AUTH_HANDLER,
  12085. handler == NULL,
  12086. NULL,
  12087. NULL,
  12088. NULL,
  12089. NULL,
  12090. NULL,
  12091. NULL,
  12092. handler,
  12093. cbdata);
  12094. }
  12095. static int
  12096. get_request_handler(struct mg_connection *conn,
  12097. int handler_type,
  12098. mg_request_handler *handler,
  12099. struct mg_websocket_subprotocols **subprotocols,
  12100. mg_websocket_connect_handler *connect_handler,
  12101. mg_websocket_ready_handler *ready_handler,
  12102. mg_websocket_data_handler *data_handler,
  12103. mg_websocket_close_handler *close_handler,
  12104. mg_authorization_handler *auth_handler,
  12105. void **cbdata,
  12106. struct mg_handler_info **handler_info)
  12107. {
  12108. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12109. if (request_info) {
  12110. const char *uri = request_info->local_uri;
  12111. size_t urilen = strlen(uri);
  12112. struct mg_handler_info *tmp_rh;
  12113. int step, matched;
  12114. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12115. return 0;
  12116. }
  12117. mg_lock_context(conn->phys_ctx);
  12118. for (step = 0; step < 3; step++) {
  12119. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12120. tmp_rh = tmp_rh->next) {
  12121. if (tmp_rh->handler_type != handler_type) {
  12122. continue;
  12123. }
  12124. if (step == 0) {
  12125. /* first try for an exact match */
  12126. matched = (tmp_rh->uri_len == urilen)
  12127. && (strcmp(tmp_rh->uri, uri) == 0);
  12128. } else if (step == 1) {
  12129. /* next try for a partial match, we will accept
  12130. uri/something */
  12131. matched =
  12132. (tmp_rh->uri_len < urilen)
  12133. && (uri[tmp_rh->uri_len] == '/')
  12134. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12135. } else {
  12136. /* finally try for pattern match */
  12137. matched =
  12138. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12139. }
  12140. if (matched) {
  12141. if (handler_type == WEBSOCKET_HANDLER) {
  12142. *subprotocols = tmp_rh->subprotocols;
  12143. *connect_handler = tmp_rh->connect_handler;
  12144. *ready_handler = tmp_rh->ready_handler;
  12145. *data_handler = tmp_rh->data_handler;
  12146. *close_handler = tmp_rh->close_handler;
  12147. } else if (handler_type == REQUEST_HANDLER) {
  12148. if (tmp_rh->removing) {
  12149. /* Treat as none found */
  12150. step = 2;
  12151. break;
  12152. }
  12153. *handler = tmp_rh->handler;
  12154. /* Acquire handler and give it back */
  12155. tmp_rh->refcount++;
  12156. *handler_info = tmp_rh;
  12157. } else { /* AUTH_HANDLER */
  12158. *auth_handler = tmp_rh->auth_handler;
  12159. }
  12160. *cbdata = tmp_rh->cbdata;
  12161. mg_unlock_context(conn->phys_ctx);
  12162. return 1;
  12163. }
  12164. }
  12165. }
  12166. mg_unlock_context(conn->phys_ctx);
  12167. }
  12168. return 0; /* none found */
  12169. }
  12170. /* Check if the script file is in a path, allowed for script files.
  12171. * This can be used if uploading files is possible not only for the server
  12172. * admin, and the upload mechanism does not check the file extension.
  12173. */
  12174. static int
  12175. is_in_script_path(const struct mg_connection *conn, const char *path)
  12176. {
  12177. /* TODO (Feature): Add config value for allowed script path.
  12178. * Default: All allowed. */
  12179. (void)conn;
  12180. (void)path;
  12181. return 1;
  12182. }
  12183. #if defined(USE_WEBSOCKET) \
  12184. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12185. static int
  12186. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12187. void *cbdata)
  12188. {
  12189. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12190. if (pcallbacks->websocket_connect) {
  12191. return pcallbacks->websocket_connect(conn);
  12192. }
  12193. /* No handler set - assume "OK" */
  12194. return 0;
  12195. }
  12196. static void
  12197. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12198. {
  12199. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12200. if (pcallbacks->websocket_ready) {
  12201. pcallbacks->websocket_ready(conn);
  12202. }
  12203. }
  12204. static int
  12205. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12206. int bits,
  12207. char *data,
  12208. size_t len,
  12209. void *cbdata)
  12210. {
  12211. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12212. if (pcallbacks->websocket_data) {
  12213. return pcallbacks->websocket_data(conn, bits, data, len);
  12214. }
  12215. /* No handler set - assume "OK" */
  12216. return 1;
  12217. }
  12218. static void
  12219. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12220. void *cbdata)
  12221. {
  12222. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12223. if (pcallbacks->connection_close) {
  12224. pcallbacks->connection_close(conn);
  12225. }
  12226. }
  12227. #endif
  12228. /* This is the heart of the Civetweb's logic.
  12229. * This function is called when the request is read, parsed and validated,
  12230. * and Civetweb must decide what action to take: serve a file, or
  12231. * a directory, or call embedded function, etcetera. */
  12232. static void
  12233. handle_request(struct mg_connection *conn)
  12234. {
  12235. struct mg_request_info *ri = &conn->request_info;
  12236. char path[PATH_MAX];
  12237. int uri_len, ssl_index;
  12238. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12239. is_put_or_delete_request = 0, is_callback_resource = 0;
  12240. int i;
  12241. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12242. mg_request_handler callback_handler = NULL;
  12243. struct mg_handler_info *handler_info = NULL;
  12244. struct mg_websocket_subprotocols *subprotocols;
  12245. mg_websocket_connect_handler ws_connect_handler = NULL;
  12246. mg_websocket_ready_handler ws_ready_handler = NULL;
  12247. mg_websocket_data_handler ws_data_handler = NULL;
  12248. mg_websocket_close_handler ws_close_handler = NULL;
  12249. void *callback_data = NULL;
  12250. mg_authorization_handler auth_handler = NULL;
  12251. void *auth_callback_data = NULL;
  12252. int handler_type;
  12253. time_t curtime = time(NULL);
  12254. char date[64];
  12255. path[0] = 0;
  12256. /* 1. get the request url */
  12257. /* 1.1. split into url and query string */
  12258. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12259. != NULL) {
  12260. *((char *)conn->request_info.query_string++) = '\0';
  12261. }
  12262. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12263. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12264. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12265. if (ssl_index >= 0) {
  12266. redirect_to_https_port(conn, ssl_index);
  12267. } else {
  12268. /* A http to https forward port has been specified,
  12269. * but no https port to forward to. */
  12270. mg_send_http_error(conn,
  12271. 503,
  12272. "%s",
  12273. "Error: SSL forward not configured properly");
  12274. mg_cry_internal(conn,
  12275. "%s",
  12276. "Can not redirect to SSL, no SSL port available");
  12277. }
  12278. return;
  12279. }
  12280. uri_len = (int)strlen(ri->local_uri);
  12281. /* 1.3. decode url (if config says so) */
  12282. if (should_decode_url(conn)) {
  12283. mg_url_decode(
  12284. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12285. }
  12286. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12287. * not possible */
  12288. remove_dot_segments((char *)ri->local_uri);
  12289. /* step 1. completed, the url is known now */
  12290. uri_len = (int)strlen(ri->local_uri);
  12291. DEBUG_TRACE("URL: %s", ri->local_uri);
  12292. /* 2. if this ip has limited speed, set it for this connection */
  12293. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12294. &conn->client.rsa,
  12295. ri->local_uri);
  12296. /* 3. call a "handle everything" callback, if registered */
  12297. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12298. /* Note that since V1.7 the "begin_request" function is called
  12299. * before an authorization check. If an authorization check is
  12300. * required, use a request_handler instead. */
  12301. i = conn->phys_ctx->callbacks.begin_request(conn);
  12302. if (i > 0) {
  12303. /* callback already processed the request. Store the
  12304. return value as a status code for the access log. */
  12305. conn->status_code = i;
  12306. if (!conn->must_close) {
  12307. discard_unread_request_data(conn);
  12308. }
  12309. return;
  12310. } else if (i == 0) {
  12311. /* civetweb should process the request */
  12312. } else {
  12313. /* unspecified - may change with the next version */
  12314. return;
  12315. }
  12316. }
  12317. /* request not yet handled by a handler or redirect, so the request
  12318. * is processed here */
  12319. /* 4. Check for CORS preflight requests and handle them (if configured).
  12320. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12321. */
  12322. if (!strcmp(ri->request_method, "OPTIONS")) {
  12323. /* Send a response to CORS preflights only if
  12324. * access_control_allow_methods is not NULL and not an empty string.
  12325. * In this case, scripts can still handle CORS. */
  12326. const char *cors_meth_cfg =
  12327. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12328. const char *cors_orig_cfg =
  12329. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12330. const char *cors_origin =
  12331. get_header(ri->http_headers, ri->num_headers, "Origin");
  12332. const char *cors_acrm = get_header(ri->http_headers,
  12333. ri->num_headers,
  12334. "Access-Control-Request-Method");
  12335. /* Todo: check if cors_origin is in cors_orig_cfg.
  12336. * Or, let the client check this. */
  12337. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12338. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12339. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12340. /* This is a valid CORS preflight, and the server is configured
  12341. * to
  12342. * handle it automatically. */
  12343. const char *cors_acrh =
  12344. get_header(ri->http_headers,
  12345. ri->num_headers,
  12346. "Access-Control-Request-Headers");
  12347. gmt_time_string(date, sizeof(date), &curtime);
  12348. mg_printf(conn,
  12349. "HTTP/1.1 200 OK\r\n"
  12350. "Date: %s\r\n"
  12351. "Access-Control-Allow-Origin: %s\r\n"
  12352. "Access-Control-Allow-Methods: %s\r\n"
  12353. "Content-Length: 0\r\n"
  12354. "Connection: %s\r\n",
  12355. date,
  12356. cors_orig_cfg,
  12357. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12358. suggest_connection_header(conn));
  12359. if (cors_acrh != NULL) {
  12360. /* CORS request is asking for additional headers */
  12361. const char *cors_hdr_cfg =
  12362. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12363. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12364. /* Allow only if access_control_allow_headers is
  12365. * not NULL and not an empty string. If this
  12366. * configuration is set to *, allow everything.
  12367. * Otherwise this configuration must be a list
  12368. * of allowed HTTP header names. */
  12369. mg_printf(conn,
  12370. "Access-Control-Allow-Headers: %s\r\n",
  12371. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12372. : cors_hdr_cfg));
  12373. }
  12374. }
  12375. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12376. mg_printf(conn, "\r\n");
  12377. return;
  12378. }
  12379. }
  12380. /* 5. interpret the url to find out how the request must be handled
  12381. */
  12382. /* 5.1. first test, if the request targets the regular http(s)://
  12383. * protocol namespace or the websocket ws(s):// protocol namespace.
  12384. */
  12385. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12386. #if defined(USE_WEBSOCKET)
  12387. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12388. #else
  12389. handler_type = REQUEST_HANDLER;
  12390. #endif /* defined(USE_WEBSOCKET) */
  12391. /* 5.2. check if the request will be handled by a callback */
  12392. if (get_request_handler(conn,
  12393. handler_type,
  12394. &callback_handler,
  12395. &subprotocols,
  12396. &ws_connect_handler,
  12397. &ws_ready_handler,
  12398. &ws_data_handler,
  12399. &ws_close_handler,
  12400. NULL,
  12401. &callback_data,
  12402. &handler_info)) {
  12403. /* 5.2.1. A callback will handle this request. All requests
  12404. * handled
  12405. * by a callback have to be considered as requests to a script
  12406. * resource. */
  12407. is_callback_resource = 1;
  12408. is_script_resource = 1;
  12409. is_put_or_delete_request = is_put_or_delete_method(conn);
  12410. } else {
  12411. no_callback_resource:
  12412. /* 5.2.2. No callback is responsible for this request. The URI
  12413. * addresses a file based resource (static content or Lua/cgi
  12414. * scripts in the file system). */
  12415. is_callback_resource = 0;
  12416. interpret_uri(conn,
  12417. path,
  12418. sizeof(path),
  12419. &file.stat,
  12420. &is_found,
  12421. &is_script_resource,
  12422. &is_websocket_request,
  12423. &is_put_or_delete_request);
  12424. }
  12425. /* 6. authorization check */
  12426. /* 6.1. a custom authorization handler is installed */
  12427. if (get_request_handler(conn,
  12428. AUTH_HANDLER,
  12429. NULL,
  12430. NULL,
  12431. NULL,
  12432. NULL,
  12433. NULL,
  12434. NULL,
  12435. &auth_handler,
  12436. &auth_callback_data,
  12437. NULL)) {
  12438. if (!auth_handler(conn, auth_callback_data)) {
  12439. return;
  12440. }
  12441. } else if (is_put_or_delete_request && !is_script_resource
  12442. && !is_callback_resource) {
  12443. /* 6.2. this request is a PUT/DELETE to a real file */
  12444. /* 6.2.1. thus, the server must have real files */
  12445. #if defined(NO_FILES)
  12446. if (1) {
  12447. #else
  12448. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12449. #endif
  12450. /* This server does not have any real files, thus the
  12451. * PUT/DELETE methods are not valid. */
  12452. mg_send_http_error(conn,
  12453. 405,
  12454. "%s method not allowed",
  12455. conn->request_info.request_method);
  12456. return;
  12457. }
  12458. #if !defined(NO_FILES)
  12459. /* 6.2.2. Check if put authorization for static files is
  12460. * available.
  12461. */
  12462. if (!is_authorized_for_put(conn)) {
  12463. send_authorization_request(conn, NULL);
  12464. return;
  12465. }
  12466. #endif
  12467. } else {
  12468. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12469. * or it is a PUT or DELETE request to a resource that does not
  12470. * correspond to a file. Check authorization. */
  12471. if (!check_authorization(conn, path)) {
  12472. send_authorization_request(conn, NULL);
  12473. return;
  12474. }
  12475. }
  12476. /* request is authorized or does not need authorization */
  12477. /* 7. check if there are request handlers for this uri */
  12478. if (is_callback_resource) {
  12479. if (!is_websocket_request) {
  12480. i = callback_handler(conn, callback_data);
  12481. /* Callback handler will not be used anymore. Release it */
  12482. mg_lock_context(conn->phys_ctx);
  12483. handler_info->refcount--;
  12484. mg_unlock_context(conn->phys_ctx);
  12485. if (i > 0) {
  12486. /* Do nothing, callback has served the request. Store
  12487. * then return value as status code for the log and discard
  12488. * all data from the client not used by the callback. */
  12489. conn->status_code = i;
  12490. if (!conn->must_close) {
  12491. discard_unread_request_data(conn);
  12492. }
  12493. } else {
  12494. /* The handler did NOT handle the request. */
  12495. /* Some proper reactions would be:
  12496. * a) close the connections without sending anything
  12497. * b) send a 404 not found
  12498. * c) try if there is a file matching the URI
  12499. * It would be possible to do a, b or c in the callback
  12500. * implementation, and return 1 - we cannot do anything
  12501. * here, that is not possible in the callback.
  12502. *
  12503. * TODO: What would be the best reaction here?
  12504. * (Note: The reaction may change, if there is a better
  12505. *idea.)
  12506. */
  12507. /* For the moment, use option c: We look for a proper file,
  12508. * but since a file request is not always a script resource,
  12509. * the authorization check might be different. */
  12510. interpret_uri(conn,
  12511. path,
  12512. sizeof(path),
  12513. &file.stat,
  12514. &is_found,
  12515. &is_script_resource,
  12516. &is_websocket_request,
  12517. &is_put_or_delete_request);
  12518. callback_handler = NULL;
  12519. /* Here we are at a dead end:
  12520. * According to URI matching, a callback should be
  12521. * responsible for handling the request,
  12522. * we called it, but the callback declared itself
  12523. * not responsible.
  12524. * We use a goto here, to get out of this dead end,
  12525. * and continue with the default handling.
  12526. * A goto here is simpler and better to understand
  12527. * than some curious loop. */
  12528. goto no_callback_resource;
  12529. }
  12530. } else {
  12531. #if defined(USE_WEBSOCKET)
  12532. handle_websocket_request(conn,
  12533. path,
  12534. is_callback_resource,
  12535. subprotocols,
  12536. ws_connect_handler,
  12537. ws_ready_handler,
  12538. ws_data_handler,
  12539. ws_close_handler,
  12540. callback_data);
  12541. #endif
  12542. }
  12543. return;
  12544. }
  12545. /* 8. handle websocket requests */
  12546. #if defined(USE_WEBSOCKET)
  12547. if (is_websocket_request) {
  12548. if (is_script_resource) {
  12549. if (is_in_script_path(conn, path)) {
  12550. /* Websocket Lua script */
  12551. handle_websocket_request(conn,
  12552. path,
  12553. 0 /* Lua Script */,
  12554. NULL,
  12555. NULL,
  12556. NULL,
  12557. NULL,
  12558. NULL,
  12559. conn->phys_ctx->user_data);
  12560. } else {
  12561. /* Script was in an illegal path */
  12562. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12563. }
  12564. } else {
  12565. #if defined(MG_LEGACY_INTERFACE)
  12566. handle_websocket_request(
  12567. conn,
  12568. path,
  12569. !is_script_resource /* could be deprecated global callback
  12570. */
  12571. ,
  12572. NULL,
  12573. deprecated_websocket_connect_wrapper,
  12574. deprecated_websocket_ready_wrapper,
  12575. deprecated_websocket_data_wrapper,
  12576. NULL,
  12577. conn->phys_ctx->callbacks);
  12578. #else
  12579. mg_send_http_error(conn, 404, "%s", "Not found");
  12580. #endif
  12581. }
  12582. return;
  12583. } else
  12584. #endif
  12585. #if defined(NO_FILES)
  12586. /* 9a. In case the server uses only callbacks, this uri is
  12587. * unknown.
  12588. * Then, all request handling ends here. */
  12589. mg_send_http_error(conn, 404, "%s", "Not Found");
  12590. #else
  12591. /* 9b. This request is either for a static file or resource handled
  12592. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12593. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12594. mg_send_http_error(conn, 404, "%s", "Not Found");
  12595. return;
  12596. }
  12597. /* 10. Request is handled by a script */
  12598. if (is_script_resource) {
  12599. handle_file_based_request(conn, path, &file);
  12600. return;
  12601. }
  12602. /* 11. Handle put/delete/mkcol requests */
  12603. if (is_put_or_delete_request) {
  12604. /* 11.1. PUT method */
  12605. if (!strcmp(ri->request_method, "PUT")) {
  12606. put_file(conn, path);
  12607. return;
  12608. }
  12609. /* 11.2. DELETE method */
  12610. if (!strcmp(ri->request_method, "DELETE")) {
  12611. delete_file(conn, path);
  12612. return;
  12613. }
  12614. /* 11.3. MKCOL method */
  12615. if (!strcmp(ri->request_method, "MKCOL")) {
  12616. mkcol(conn, path);
  12617. return;
  12618. }
  12619. /* 11.4. PATCH method
  12620. * This method is not supported for static resources,
  12621. * only for scripts (Lua, CGI) and callbacks. */
  12622. mg_send_http_error(conn,
  12623. 405,
  12624. "%s method not allowed",
  12625. conn->request_info.request_method);
  12626. return;
  12627. }
  12628. /* 11. File does not exist, or it was configured that it should be
  12629. * hidden */
  12630. if (!is_found || (must_hide_file(conn, path))) {
  12631. mg_send_http_error(conn, 404, "%s", "Not found");
  12632. return;
  12633. }
  12634. /* 12. Directory uris should end with a slash */
  12635. if (file.stat.is_directory && (uri_len > 0)
  12636. && (ri->local_uri[uri_len - 1] != '/')) {
  12637. gmt_time_string(date, sizeof(date), &curtime);
  12638. mg_printf(conn,
  12639. "HTTP/1.1 301 Moved Permanently\r\n"
  12640. "Location: %s/\r\n"
  12641. "Date: %s\r\n"
  12642. /* "Cache-Control: private\r\n" (= default) */
  12643. "Content-Length: 0\r\n"
  12644. "Connection: %s\r\n",
  12645. ri->request_uri,
  12646. date,
  12647. suggest_connection_header(conn));
  12648. send_additional_header(conn);
  12649. mg_printf(conn, "\r\n");
  12650. return;
  12651. }
  12652. /* 13. Handle other methods than GET/HEAD */
  12653. /* 13.1. Handle PROPFIND */
  12654. if (!strcmp(ri->request_method, "PROPFIND")) {
  12655. handle_propfind(conn, path, &file.stat);
  12656. return;
  12657. }
  12658. /* 13.2. Handle OPTIONS for files */
  12659. if (!strcmp(ri->request_method, "OPTIONS")) {
  12660. /* This standard handler is only used for real files.
  12661. * Scripts should support the OPTIONS method themselves, to allow a
  12662. * maximum flexibility.
  12663. * Lua and CGI scripts may fully support CORS this way (including
  12664. * preflights). */
  12665. send_options(conn);
  12666. return;
  12667. }
  12668. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12669. if ((0 != strcmp(ri->request_method, "GET"))
  12670. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12671. mg_send_http_error(conn,
  12672. 405,
  12673. "%s method not allowed",
  12674. conn->request_info.request_method);
  12675. return;
  12676. }
  12677. /* 14. directories */
  12678. if (file.stat.is_directory) {
  12679. /* Substitute files have already been handled above. */
  12680. /* Here we can either generate and send a directory listing,
  12681. * or send an "access denied" error. */
  12682. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12683. "yes")) {
  12684. handle_directory_request(conn, path);
  12685. } else {
  12686. mg_send_http_error(conn,
  12687. 403,
  12688. "%s",
  12689. "Error: Directory listing denied");
  12690. }
  12691. return;
  12692. }
  12693. /* 15. read a normal file with GET or HEAD */
  12694. handle_file_based_request(conn, path, &file);
  12695. #endif /* !defined(NO_FILES) */
  12696. }
  12697. /* Include HTTP/2 modules */
  12698. #ifdef USE_HTTP2
  12699. #if defined(NO_SSL)
  12700. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  12701. #endif
  12702. #include "mod_http2.inl"
  12703. #endif
  12704. #if !defined(NO_FILESYSTEMS)
  12705. static void
  12706. handle_file_based_request(struct mg_connection *conn,
  12707. const char *path,
  12708. struct mg_file *file)
  12709. {
  12710. if (!conn || !conn->dom_ctx) {
  12711. return;
  12712. }
  12713. if (0) {
  12714. #if defined(USE_LUA)
  12715. } else if (match_prefix(
  12716. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12717. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12718. path)
  12719. > 0) {
  12720. if (is_in_script_path(conn, path)) {
  12721. /* Lua server page: an SSI like page containing mostly plain
  12722. * html
  12723. * code
  12724. * plus some tags with server generated contents. */
  12725. handle_lsp_request(conn, path, file, NULL);
  12726. } else {
  12727. /* Script was in an illegal path */
  12728. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12729. }
  12730. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12731. strlen(
  12732. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12733. path)
  12734. > 0) {
  12735. if (is_in_script_path(conn, path)) {
  12736. /* Lua in-server module script: a CGI like script used to
  12737. * generate
  12738. * the
  12739. * entire reply. */
  12740. mg_exec_lua_script(conn, path, NULL);
  12741. } else {
  12742. /* Script was in an illegal path */
  12743. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12744. }
  12745. #endif
  12746. #if defined(USE_DUKTAPE)
  12747. } else if (match_prefix(
  12748. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12749. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12750. path)
  12751. > 0) {
  12752. if (is_in_script_path(conn, path)) {
  12753. /* Call duktape to generate the page */
  12754. mg_exec_duktape_script(conn, path);
  12755. } else {
  12756. /* Script was in an illegal path */
  12757. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12758. }
  12759. #endif
  12760. #if !defined(NO_CGI)
  12761. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12762. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12763. path)
  12764. > 0) {
  12765. if (is_in_script_path(conn, path)) {
  12766. /* CGI scripts may support all HTTP methods */
  12767. handle_cgi_request(conn, path);
  12768. } else {
  12769. /* Script was in an illegal path */
  12770. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12771. }
  12772. #endif /* !NO_CGI */
  12773. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12774. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12775. path)
  12776. > 0) {
  12777. if (is_in_script_path(conn, path)) {
  12778. handle_ssi_file_request(conn, path, file);
  12779. } else {
  12780. /* Script was in an illegal path */
  12781. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12782. }
  12783. #if !defined(NO_CACHING)
  12784. } else if ((!conn->in_error_handler)
  12785. && is_not_modified(conn, &file->stat)) {
  12786. /* Send 304 "Not Modified" - this must not send any body data */
  12787. handle_not_modified_static_file_request(conn, file);
  12788. #endif /* !NO_CACHING */
  12789. } else {
  12790. handle_static_file_request(conn, path, file, NULL, NULL);
  12791. }
  12792. }
  12793. #endif /* NO_FILESYSTEMS */
  12794. static void
  12795. close_all_listening_sockets(struct mg_context *ctx)
  12796. {
  12797. unsigned int i;
  12798. if (!ctx) {
  12799. return;
  12800. }
  12801. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12802. closesocket(ctx->listening_sockets[i].sock);
  12803. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12804. }
  12805. mg_free(ctx->listening_sockets);
  12806. ctx->listening_sockets = NULL;
  12807. mg_free(ctx->listening_socket_fds);
  12808. ctx->listening_socket_fds = NULL;
  12809. }
  12810. /* Valid listening port specification is: [ip_address:]port[s]
  12811. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12812. * Examples for IPv6: [::]:80, [::1]:80,
  12813. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12814. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12815. * In order to bind to both, IPv4 and IPv6, you can either add
  12816. * both ports using 8080,[::]:8080, or the short form +8080.
  12817. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12818. * one only accepting IPv4 the other only IPv6. +8080 creates
  12819. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12820. * environment, they might work differently, or might not work
  12821. * at all - it must be tested what options work best in the
  12822. * relevant network environment.
  12823. */
  12824. static int
  12825. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12826. {
  12827. unsigned int a, b, c, d;
  12828. unsigned port;
  12829. unsigned long portUL;
  12830. int ch, len;
  12831. const char *cb;
  12832. char *endptr;
  12833. #if defined(USE_IPV6)
  12834. char buf[100] = {0};
  12835. #endif
  12836. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12837. * Also, all-zeroes in the socket address means binding to all addresses
  12838. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12839. memset(so, 0, sizeof(*so));
  12840. so->lsa.sin.sin_family = AF_INET;
  12841. *ip_version = 0;
  12842. /* Initialize len as invalid. */
  12843. port = 0;
  12844. len = 0;
  12845. /* Test for different ways to format this string */
  12846. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12847. == 5) {
  12848. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12849. so->lsa.sin.sin_addr.s_addr =
  12850. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12851. so->lsa.sin.sin_port = htons((uint16_t)port);
  12852. *ip_version = 4;
  12853. #if defined(USE_IPV6)
  12854. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12855. && ((size_t)len <= vec->len)
  12856. && mg_inet_pton(
  12857. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12858. /* IPv6 address, examples: see above */
  12859. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12860. */
  12861. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12862. *ip_version = 6;
  12863. #endif
  12864. } else if ((vec->ptr[0] == '+')
  12865. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12866. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12867. /* Add 1 to len for the + character we skipped before */
  12868. len++;
  12869. #if defined(USE_IPV6)
  12870. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12871. so->lsa.sin6.sin6_family = AF_INET6;
  12872. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12873. *ip_version = 4 + 6;
  12874. #else
  12875. /* Bind to IPv4 only, since IPv6 is not built in. */
  12876. so->lsa.sin.sin_port = htons((uint16_t)port);
  12877. *ip_version = 4;
  12878. #endif
  12879. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12880. && (vec->ptr != endptr)) {
  12881. len = (int)(endptr - vec->ptr);
  12882. port = (uint16_t)portUL;
  12883. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12884. so->lsa.sin.sin_port = htons((uint16_t)port);
  12885. *ip_version = 4;
  12886. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12887. /* String could be a hostname. This check algotithm
  12888. * will only work for RFC 952 compliant hostnames,
  12889. * starting with a letter, containing only letters,
  12890. * digits and hyphen ('-'). Newer specs may allow
  12891. * more, but this is not guaranteed here, since it
  12892. * may interfere with rules for port option lists. */
  12893. /* According to RFC 1035, hostnames are restricted to 255 characters
  12894. * in total (63 between two dots). */
  12895. char hostname[256];
  12896. size_t hostnlen = (size_t)(cb - vec->ptr);
  12897. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12898. /* This would be invalid in any case */
  12899. *ip_version = 0;
  12900. return 0;
  12901. }
  12902. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12903. if (mg_inet_pton(
  12904. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12905. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12906. *ip_version = 4;
  12907. so->lsa.sin.sin_port = htons((uint16_t)port);
  12908. len += (int)(hostnlen + 1);
  12909. } else {
  12910. len = 0;
  12911. }
  12912. #if defined(USE_IPV6)
  12913. } else if (mg_inet_pton(AF_INET6,
  12914. hostname,
  12915. &so->lsa.sin6,
  12916. sizeof(so->lsa.sin6),
  12917. 1)) {
  12918. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12919. *ip_version = 6;
  12920. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12921. len += (int)(hostnlen + 1);
  12922. } else {
  12923. len = 0;
  12924. }
  12925. #endif
  12926. } else {
  12927. len = 0;
  12928. }
  12929. } else {
  12930. /* Parsing failure. */
  12931. len = 0;
  12932. }
  12933. /* sscanf and the option splitting code ensure the following condition
  12934. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12935. if ((len > 0) && is_valid_port(port)
  12936. && (((size_t)len == vec->len) || ((size_t)(len + 1) == vec->len))) {
  12937. /* Next character after the port number */
  12938. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12939. so->is_ssl = (ch == 's');
  12940. so->ssl_redir = (ch == 'r');
  12941. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12942. return 1;
  12943. }
  12944. }
  12945. /* Reset ip_version to 0 if there is an error */
  12946. *ip_version = 0;
  12947. return 0;
  12948. }
  12949. /* Is there any SSL port in use? */
  12950. static int
  12951. is_ssl_port_used(const char *ports)
  12952. {
  12953. if (ports) {
  12954. /* There are several different allowed syntax variants:
  12955. * - "80" for a single port using every network interface
  12956. * - "localhost:80" for a single port using only localhost
  12957. * - "80,localhost:8080" for two ports, one bound to localhost
  12958. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12959. * to IPv4 localhost, one to IPv6 localhost
  12960. * - "+80" use port 80 for IPv4 and IPv6
  12961. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12962. * for both: IPv4 and IPv4
  12963. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12964. * additionally port 8080 bound to localhost connections
  12965. *
  12966. * If we just look for 's' anywhere in the string, "localhost:80"
  12967. * will be detected as SSL (false positive).
  12968. * Looking for 's' after a digit may cause false positives in
  12969. * "my24service:8080".
  12970. * Looking from 's' backward if there are only ':' and numbers
  12971. * before will not work for "24service:8080" (non SSL, port 8080)
  12972. * or "24s" (SSL, port 24).
  12973. *
  12974. * Remark: Initially hostnames were not allowed to start with a
  12975. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12976. * Section 2.1).
  12977. *
  12978. * To get this correct, the entire string must be parsed as a whole,
  12979. * reading it as a list element for element and parsing with an
  12980. * algorithm equivalent to parse_port_string.
  12981. *
  12982. * In fact, we use local interface names here, not arbitrary
  12983. * hostnames, so in most cases the only name will be "localhost".
  12984. *
  12985. * So, for now, we use this simple algorithm, that may still return
  12986. * a false positive in bizarre cases.
  12987. */
  12988. int i;
  12989. int portslen = (int)strlen(ports);
  12990. char prevIsNumber = 0;
  12991. for (i = 0; i < portslen; i++) {
  12992. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12993. return 1;
  12994. }
  12995. if (ports[i] >= '0' && ports[i] <= '9') {
  12996. prevIsNumber = 1;
  12997. } else {
  12998. prevIsNumber = 0;
  12999. }
  13000. }
  13001. }
  13002. return 0;
  13003. }
  13004. static int
  13005. set_ports_option(struct mg_context *phys_ctx)
  13006. {
  13007. const char *list;
  13008. int on = 1;
  13009. #if defined(USE_IPV6)
  13010. int off = 0;
  13011. #endif
  13012. struct vec vec;
  13013. struct socket so, *ptr;
  13014. struct mg_pollfd *pfd;
  13015. union usa usa;
  13016. socklen_t len;
  13017. int ip_version;
  13018. int portsTotal = 0;
  13019. int portsOk = 0;
  13020. const char *opt_txt;
  13021. long opt_listen_backlog;
  13022. if (!phys_ctx) {
  13023. return 0;
  13024. }
  13025. memset(&so, 0, sizeof(so));
  13026. memset(&usa, 0, sizeof(usa));
  13027. len = sizeof(usa);
  13028. list = phys_ctx->dd.config[LISTENING_PORTS];
  13029. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13030. portsTotal++;
  13031. if (!parse_port_string(&vec, &so, &ip_version)) {
  13032. mg_cry_ctx_internal(
  13033. phys_ctx,
  13034. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13035. (int)vec.len,
  13036. vec.ptr,
  13037. portsTotal,
  13038. "[IP_ADDRESS:]PORT[s|r]");
  13039. continue;
  13040. }
  13041. #if !defined(NO_SSL)
  13042. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13043. mg_cry_ctx_internal(phys_ctx,
  13044. "Cannot add SSL socket (entry %i)",
  13045. portsTotal);
  13046. continue;
  13047. }
  13048. #endif
  13049. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  13050. == INVALID_SOCKET) {
  13051. mg_cry_ctx_internal(phys_ctx,
  13052. "cannot create socket (entry %i)",
  13053. portsTotal);
  13054. continue;
  13055. }
  13056. #if defined(_WIN32)
  13057. /* Windows SO_REUSEADDR lets many procs binds to a
  13058. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13059. * if someone already has the socket -- DTL */
  13060. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13061. * Windows might need a few seconds before
  13062. * the same port can be used again in the
  13063. * same process, so a short Sleep may be
  13064. * required between mg_stop and mg_start.
  13065. */
  13066. if (setsockopt(so.sock,
  13067. SOL_SOCKET,
  13068. SO_EXCLUSIVEADDRUSE,
  13069. (SOCK_OPT_TYPE)&on,
  13070. sizeof(on))
  13071. != 0) {
  13072. /* Set reuse option, but don't abort on errors. */
  13073. mg_cry_ctx_internal(
  13074. phys_ctx,
  13075. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13076. portsTotal);
  13077. }
  13078. #else
  13079. if (setsockopt(so.sock,
  13080. SOL_SOCKET,
  13081. SO_REUSEADDR,
  13082. (SOCK_OPT_TYPE)&on,
  13083. sizeof(on))
  13084. != 0) {
  13085. /* Set reuse option, but don't abort on errors. */
  13086. mg_cry_ctx_internal(
  13087. phys_ctx,
  13088. "cannot set socket option SO_REUSEADDR (entry %i)",
  13089. portsTotal);
  13090. }
  13091. #endif
  13092. if (ip_version > 4) {
  13093. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13094. #if defined(USE_IPV6)
  13095. if (ip_version > 6) {
  13096. if (so.lsa.sa.sa_family == AF_INET6
  13097. && setsockopt(so.sock,
  13098. IPPROTO_IPV6,
  13099. IPV6_V6ONLY,
  13100. (void *)&off,
  13101. sizeof(off))
  13102. != 0) {
  13103. /* Set IPv6 only option, but don't abort on errors. */
  13104. mg_cry_ctx_internal(phys_ctx,
  13105. "cannot set socket option "
  13106. "IPV6_V6ONLY=off (entry %i)",
  13107. portsTotal);
  13108. }
  13109. } else {
  13110. if (so.lsa.sa.sa_family == AF_INET6
  13111. && setsockopt(so.sock,
  13112. IPPROTO_IPV6,
  13113. IPV6_V6ONLY,
  13114. (void *)&on,
  13115. sizeof(on))
  13116. != 0) {
  13117. /* Set IPv6 only option, but don't abort on errors. */
  13118. mg_cry_ctx_internal(phys_ctx,
  13119. "cannot set socket option "
  13120. "IPV6_V6ONLY=on (entry %i)",
  13121. portsTotal);
  13122. }
  13123. }
  13124. #else
  13125. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13126. closesocket(so.sock);
  13127. so.sock = INVALID_SOCKET;
  13128. continue;
  13129. #endif
  13130. }
  13131. if (so.lsa.sa.sa_family == AF_INET) {
  13132. len = sizeof(so.lsa.sin);
  13133. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13134. mg_cry_ctx_internal(phys_ctx,
  13135. "cannot bind to %.*s: %d (%s)",
  13136. (int)vec.len,
  13137. vec.ptr,
  13138. (int)ERRNO,
  13139. strerror(errno));
  13140. closesocket(so.sock);
  13141. so.sock = INVALID_SOCKET;
  13142. continue;
  13143. }
  13144. }
  13145. #if defined(USE_IPV6)
  13146. else if (so.lsa.sa.sa_family == AF_INET6) {
  13147. len = sizeof(so.lsa.sin6);
  13148. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13149. mg_cry_ctx_internal(phys_ctx,
  13150. "cannot bind to IPv6 %.*s: %d (%s)",
  13151. (int)vec.len,
  13152. vec.ptr,
  13153. (int)ERRNO,
  13154. strerror(errno));
  13155. closesocket(so.sock);
  13156. so.sock = INVALID_SOCKET;
  13157. continue;
  13158. }
  13159. }
  13160. #endif
  13161. else {
  13162. mg_cry_ctx_internal(
  13163. phys_ctx,
  13164. "cannot bind: address family not supported (entry %i)",
  13165. portsTotal);
  13166. closesocket(so.sock);
  13167. so.sock = INVALID_SOCKET;
  13168. continue;
  13169. }
  13170. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13171. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13172. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13173. mg_cry_ctx_internal(phys_ctx,
  13174. "%s value \"%s\" is invalid",
  13175. config_options[LISTEN_BACKLOG_SIZE].name,
  13176. opt_txt);
  13177. closesocket(so.sock);
  13178. so.sock = INVALID_SOCKET;
  13179. continue;
  13180. }
  13181. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13182. mg_cry_ctx_internal(phys_ctx,
  13183. "cannot listen to %.*s: %d (%s)",
  13184. (int)vec.len,
  13185. vec.ptr,
  13186. (int)ERRNO,
  13187. strerror(errno));
  13188. closesocket(so.sock);
  13189. so.sock = INVALID_SOCKET;
  13190. continue;
  13191. }
  13192. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13193. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13194. int err = (int)ERRNO;
  13195. mg_cry_ctx_internal(phys_ctx,
  13196. "call to getsockname failed %.*s: %d (%s)",
  13197. (int)vec.len,
  13198. vec.ptr,
  13199. err,
  13200. strerror(errno));
  13201. closesocket(so.sock);
  13202. so.sock = INVALID_SOCKET;
  13203. continue;
  13204. }
  13205. /* Update lsa port in case of random free ports */
  13206. #if defined(USE_IPV6)
  13207. if (so.lsa.sa.sa_family == AF_INET6) {
  13208. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13209. } else
  13210. #endif
  13211. {
  13212. so.lsa.sin.sin_port = usa.sin.sin_port;
  13213. }
  13214. if ((ptr = (struct socket *)
  13215. mg_realloc_ctx(phys_ctx->listening_sockets,
  13216. (phys_ctx->num_listening_sockets + 1)
  13217. * sizeof(phys_ctx->listening_sockets[0]),
  13218. phys_ctx))
  13219. == NULL) {
  13220. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13221. closesocket(so.sock);
  13222. so.sock = INVALID_SOCKET;
  13223. continue;
  13224. }
  13225. if ((pfd = (struct mg_pollfd *)
  13226. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13227. (phys_ctx->num_listening_sockets + 1)
  13228. * sizeof(phys_ctx->listening_socket_fds[0]),
  13229. phys_ctx))
  13230. == NULL) {
  13231. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13232. closesocket(so.sock);
  13233. so.sock = INVALID_SOCKET;
  13234. mg_free(ptr);
  13235. continue;
  13236. }
  13237. set_close_on_exec(so.sock, NULL, phys_ctx);
  13238. phys_ctx->listening_sockets = ptr;
  13239. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13240. phys_ctx->listening_socket_fds = pfd;
  13241. phys_ctx->num_listening_sockets++;
  13242. portsOk++;
  13243. }
  13244. if (portsOk != portsTotal) {
  13245. close_all_listening_sockets(phys_ctx);
  13246. portsOk = 0;
  13247. }
  13248. return portsOk;
  13249. }
  13250. static const char *
  13251. header_val(const struct mg_connection *conn, const char *header)
  13252. {
  13253. const char *header_value;
  13254. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13255. return "-";
  13256. } else {
  13257. return header_value;
  13258. }
  13259. }
  13260. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13261. static void log_access(const struct mg_connection *conn);
  13262. #include "external_log_access.inl"
  13263. #elif !defined(NO_FILESYSTEMS)
  13264. static void
  13265. log_access(const struct mg_connection *conn)
  13266. {
  13267. const struct mg_request_info *ri;
  13268. struct mg_file fi;
  13269. char date[64], src_addr[IP_ADDR_STR_LEN];
  13270. struct tm *tm;
  13271. const char *referer;
  13272. const char *user_agent;
  13273. char buf[4096];
  13274. if (!conn || !conn->dom_ctx) {
  13275. return;
  13276. }
  13277. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13278. if (mg_fopen(conn,
  13279. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13280. MG_FOPEN_MODE_APPEND,
  13281. &fi)
  13282. == 0) {
  13283. fi.access.fp = NULL;
  13284. }
  13285. } else {
  13286. fi.access.fp = NULL;
  13287. }
  13288. /* Log is written to a file and/or a callback. If both are not set,
  13289. * executing the rest of the function is pointless. */
  13290. if ((fi.access.fp == NULL)
  13291. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13292. return;
  13293. }
  13294. tm = localtime(&conn->conn_birth_time);
  13295. if (tm != NULL) {
  13296. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13297. } else {
  13298. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13299. date[sizeof(date) - 1] = '\0';
  13300. }
  13301. ri = &conn->request_info;
  13302. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13303. referer = header_val(conn, "Referer");
  13304. user_agent = header_val(conn, "User-Agent");
  13305. mg_snprintf(conn,
  13306. NULL, /* Ignore truncation in access log */
  13307. buf,
  13308. sizeof(buf),
  13309. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13310. src_addr,
  13311. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13312. date,
  13313. ri->request_method ? ri->request_method : "-",
  13314. ri->request_uri ? ri->request_uri : "-",
  13315. ri->query_string ? "?" : "",
  13316. ri->query_string ? ri->query_string : "",
  13317. ri->http_version,
  13318. conn->status_code,
  13319. conn->num_bytes_sent,
  13320. referer,
  13321. user_agent);
  13322. if (conn->phys_ctx->callbacks.log_access) {
  13323. conn->phys_ctx->callbacks.log_access(conn, buf);
  13324. }
  13325. if (fi.access.fp) {
  13326. int ok = 1;
  13327. flockfile(fi.access.fp);
  13328. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13329. ok = 0;
  13330. }
  13331. if (fflush(fi.access.fp) != 0) {
  13332. ok = 0;
  13333. }
  13334. funlockfile(fi.access.fp);
  13335. if (mg_fclose(&fi.access) != 0) {
  13336. ok = 0;
  13337. }
  13338. if (!ok) {
  13339. mg_cry_internal(conn,
  13340. "Error writing log file %s",
  13341. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13342. }
  13343. }
  13344. }
  13345. #else
  13346. #error Must either enable filesystems or provide a custom log_access implementation
  13347. #endif /* Externally provided function */
  13348. /* Verify given socket address against the ACL.
  13349. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13350. */
  13351. static int
  13352. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13353. {
  13354. int allowed, flag, matched;
  13355. struct vec vec;
  13356. if (phys_ctx) {
  13357. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13358. /* If any ACL is set, deny by default */
  13359. allowed = (list == NULL) ? '+' : '-';
  13360. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13361. flag = vec.ptr[0];
  13362. matched = -1;
  13363. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13364. vec.ptr++;
  13365. vec.len--;
  13366. matched = parse_match_net(&vec, sa, 1);
  13367. }
  13368. if (matched < 0) {
  13369. mg_cry_ctx_internal(phys_ctx,
  13370. "%s: subnet must be [+|-]IP-addr[/x]",
  13371. __func__);
  13372. return -1;
  13373. }
  13374. if (matched) {
  13375. allowed = flag;
  13376. }
  13377. }
  13378. return allowed == '+';
  13379. }
  13380. return -1;
  13381. }
  13382. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13383. static int
  13384. set_uid_option(struct mg_context *phys_ctx)
  13385. {
  13386. int success = 0;
  13387. if (phys_ctx) {
  13388. /* We are currently running as curr_uid. */
  13389. const uid_t curr_uid = getuid();
  13390. /* If set, we want to run as run_as_user. */
  13391. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13392. const struct passwd *to_pw = NULL;
  13393. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13394. /* run_as_user does not exist on the system. We can't proceed
  13395. * further. */
  13396. mg_cry_ctx_internal(phys_ctx,
  13397. "%s: unknown user [%s]",
  13398. __func__,
  13399. run_as_user);
  13400. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13401. /* There was either no request to change user, or we're already
  13402. * running as run_as_user. Nothing else to do.
  13403. */
  13404. success = 1;
  13405. } else {
  13406. /* Valid change request. */
  13407. if (setgid(to_pw->pw_gid) == -1) {
  13408. mg_cry_ctx_internal(phys_ctx,
  13409. "%s: setgid(%s): %s",
  13410. __func__,
  13411. run_as_user,
  13412. strerror(errno));
  13413. } else if (setgroups(0, NULL) == -1) {
  13414. mg_cry_ctx_internal(phys_ctx,
  13415. "%s: setgroups(): %s",
  13416. __func__,
  13417. strerror(errno));
  13418. } else if (setuid(to_pw->pw_uid) == -1) {
  13419. mg_cry_ctx_internal(phys_ctx,
  13420. "%s: setuid(%s): %s",
  13421. __func__,
  13422. run_as_user,
  13423. strerror(errno));
  13424. } else {
  13425. success = 1;
  13426. }
  13427. }
  13428. }
  13429. return success;
  13430. }
  13431. #endif /* !_WIN32 */
  13432. static void
  13433. tls_dtor(void *key)
  13434. {
  13435. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13436. /* key == pthread_getspecific(sTlsKey); */
  13437. if (tls) {
  13438. if (tls->is_master == 2) {
  13439. tls->is_master = -3; /* Mark memory as dead */
  13440. mg_free(tls);
  13441. }
  13442. }
  13443. pthread_setspecific(sTlsKey, NULL);
  13444. }
  13445. #if !defined(NO_SSL)
  13446. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13447. struct mg_domain_context *dom_ctx,
  13448. const char *pem,
  13449. const char *chain);
  13450. static const char *ssl_error(void);
  13451. static int
  13452. refresh_trust(struct mg_connection *conn)
  13453. {
  13454. struct stat cert_buf;
  13455. int64_t t = 0;
  13456. const char *pem;
  13457. const char *chain;
  13458. int should_verify_peer;
  13459. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13460. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13461. * refresh_trust still can not work. */
  13462. return 0;
  13463. }
  13464. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13465. if (chain == NULL) {
  13466. /* pem is not NULL here */
  13467. chain = pem;
  13468. }
  13469. if (*chain == 0) {
  13470. chain = NULL;
  13471. }
  13472. if (stat(pem, &cert_buf) != -1) {
  13473. t = (int64_t)cert_buf.st_mtime;
  13474. }
  13475. mg_lock_context(conn->phys_ctx);
  13476. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13477. conn->dom_ctx->ssl_cert_last_mtime = t;
  13478. should_verify_peer = 0;
  13479. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13480. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13481. == 0) {
  13482. should_verify_peer = 1;
  13483. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13484. "optional")
  13485. == 0) {
  13486. should_verify_peer = 1;
  13487. }
  13488. }
  13489. if (should_verify_peer) {
  13490. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13491. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13492. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13493. ca_file,
  13494. ca_path)
  13495. != 1) {
  13496. mg_unlock_context(conn->phys_ctx);
  13497. mg_cry_ctx_internal(
  13498. conn->phys_ctx,
  13499. "SSL_CTX_load_verify_locations error: %s "
  13500. "ssl_verify_peer requires setting "
  13501. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13502. "present in "
  13503. "the .conf file?",
  13504. ssl_error());
  13505. return 0;
  13506. }
  13507. }
  13508. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13509. mg_unlock_context(conn->phys_ctx);
  13510. return 0;
  13511. }
  13512. }
  13513. mg_unlock_context(conn->phys_ctx);
  13514. return 1;
  13515. }
  13516. #if defined(OPENSSL_API_1_1)
  13517. #else
  13518. static pthread_mutex_t *ssl_mutexes;
  13519. #endif /* OPENSSL_API_1_1 */
  13520. static int
  13521. sslize(struct mg_connection *conn,
  13522. int (*func)(SSL *),
  13523. const struct mg_client_options *client_options)
  13524. {
  13525. int ret, err;
  13526. int short_trust;
  13527. unsigned timeout = 1024;
  13528. unsigned i;
  13529. if (!conn) {
  13530. return 0;
  13531. }
  13532. short_trust =
  13533. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13534. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13535. if (short_trust) {
  13536. int trust_ret = refresh_trust(conn);
  13537. if (!trust_ret) {
  13538. return trust_ret;
  13539. }
  13540. }
  13541. mg_lock_context(conn->phys_ctx);
  13542. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13543. mg_unlock_context(conn->phys_ctx);
  13544. if (conn->ssl == NULL) {
  13545. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13546. OPENSSL_REMOVE_THREAD_STATE();
  13547. return 0;
  13548. }
  13549. SSL_set_app_data(conn->ssl, (char *)conn);
  13550. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13551. if (ret != 1) {
  13552. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13553. SSL_free(conn->ssl);
  13554. conn->ssl = NULL;
  13555. OPENSSL_REMOVE_THREAD_STATE();
  13556. return 0;
  13557. }
  13558. if (client_options) {
  13559. if (client_options->host_name) {
  13560. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13561. }
  13562. }
  13563. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13564. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13565. /* NOTE: The loop below acts as a back-off, so we can end
  13566. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13567. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13568. if (to >= 0) {
  13569. timeout = (unsigned)to;
  13570. }
  13571. }
  13572. /* SSL functions may fail and require to be called again:
  13573. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13574. * Here "func" could be SSL_connect or SSL_accept. */
  13575. for (i = 0; i <= timeout; i += 50) {
  13576. ERR_clear_error();
  13577. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13578. ret = func(conn->ssl);
  13579. if (ret != 1) {
  13580. err = SSL_get_error(conn->ssl, ret);
  13581. if ((err == SSL_ERROR_WANT_CONNECT)
  13582. || (err == SSL_ERROR_WANT_ACCEPT)
  13583. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13584. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13585. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13586. /* Don't wait if the server is going to be stopped. */
  13587. break;
  13588. }
  13589. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13590. /* Simply retry the function call. */
  13591. mg_sleep(50);
  13592. } else {
  13593. /* Need to retry the function call "later".
  13594. * See https://linux.die.net/man/3/ssl_get_error
  13595. * This is typical for non-blocking sockets. */
  13596. struct mg_pollfd pfd;
  13597. int pollres;
  13598. pfd.fd = conn->client.sock;
  13599. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13600. || (err == SSL_ERROR_WANT_WRITE))
  13601. ? POLLOUT
  13602. : POLLIN;
  13603. pollres =
  13604. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13605. if (pollres < 0) {
  13606. /* Break if error occured (-1)
  13607. * or server shutdown (-2) */
  13608. break;
  13609. }
  13610. }
  13611. } else if (err == SSL_ERROR_SYSCALL) {
  13612. /* This is an IO error. Look at errno. */
  13613. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13614. break;
  13615. } else {
  13616. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13617. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13618. break;
  13619. }
  13620. } else {
  13621. /* success */
  13622. break;
  13623. }
  13624. }
  13625. ERR_clear_error();
  13626. if (ret != 1) {
  13627. SSL_free(conn->ssl);
  13628. conn->ssl = NULL;
  13629. OPENSSL_REMOVE_THREAD_STATE();
  13630. return 0;
  13631. }
  13632. return 1;
  13633. }
  13634. /* Return OpenSSL error message (from CRYPTO lib) */
  13635. static const char *
  13636. ssl_error(void)
  13637. {
  13638. unsigned long err;
  13639. err = ERR_get_error();
  13640. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13641. }
  13642. static int
  13643. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13644. {
  13645. int i;
  13646. const char hexdigit[] = "0123456789abcdef";
  13647. if ((memlen <= 0) || (buflen <= 0)) {
  13648. return 0;
  13649. }
  13650. if (buflen < (3 * memlen)) {
  13651. return 0;
  13652. }
  13653. for (i = 0; i < memlen; i++) {
  13654. if (i > 0) {
  13655. buf[3 * i - 1] = ' ';
  13656. }
  13657. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13658. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13659. }
  13660. buf[3 * memlen - 1] = 0;
  13661. return 1;
  13662. }
  13663. static int
  13664. ssl_get_client_cert_info(const struct mg_connection *conn,
  13665. struct mg_client_cert *client_cert)
  13666. {
  13667. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13668. if (cert) {
  13669. char str_buf[1024];
  13670. unsigned char buf[256];
  13671. char *str_serial = NULL;
  13672. unsigned int ulen;
  13673. int ilen;
  13674. unsigned char *tmp_buf;
  13675. unsigned char *tmp_p;
  13676. /* Handle to algorithm used for fingerprint */
  13677. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13678. /* Get Subject and issuer */
  13679. X509_NAME *subj = X509_get_subject_name(cert);
  13680. X509_NAME *iss = X509_get_issuer_name(cert);
  13681. /* Get serial number */
  13682. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13683. /* Translate serial number to a hex string */
  13684. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13685. if (serial_bn) {
  13686. str_serial = BN_bn2hex(serial_bn);
  13687. BN_free(serial_bn);
  13688. }
  13689. client_cert->serial =
  13690. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13691. /* Translate subject and issuer to a string */
  13692. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13693. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13694. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13695. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13696. /* Calculate SHA1 fingerprint and store as a hex string */
  13697. ulen = 0;
  13698. /* ASN1_digest is deprecated. Do the calculation manually,
  13699. * using EVP_Digest. */
  13700. ilen = i2d_X509(cert, NULL);
  13701. tmp_buf = (ilen > 0)
  13702. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13703. conn->phys_ctx)
  13704. : NULL;
  13705. if (tmp_buf) {
  13706. tmp_p = tmp_buf;
  13707. (void)i2d_X509(cert, &tmp_p);
  13708. if (!EVP_Digest(
  13709. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13710. ulen = 0;
  13711. }
  13712. mg_free(tmp_buf);
  13713. }
  13714. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13715. *str_buf = 0;
  13716. }
  13717. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13718. client_cert->peer_cert = (void *)cert;
  13719. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13720. * see https://linux.die.net/man/3/bn_bn2hex */
  13721. OPENSSL_free(str_serial);
  13722. return 1;
  13723. }
  13724. return 0;
  13725. }
  13726. #if defined(OPENSSL_API_1_1)
  13727. #else
  13728. static void
  13729. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13730. {
  13731. (void)line;
  13732. (void)file;
  13733. if (mode & 1) {
  13734. /* 1 is CRYPTO_LOCK */
  13735. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13736. } else {
  13737. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13738. }
  13739. }
  13740. #endif /* OPENSSL_API_1_1 */
  13741. #if !defined(NO_SSL_DL)
  13742. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13743. static void *
  13744. load_tls_dll(char *ebuf,
  13745. size_t ebuf_len,
  13746. const char *dll_name,
  13747. struct ssl_func *sw)
  13748. {
  13749. union {
  13750. void *p;
  13751. void (*fp)(void);
  13752. } u;
  13753. void *dll_handle;
  13754. struct ssl_func *fp;
  13755. int ok;
  13756. int truncated = 0;
  13757. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13758. mg_snprintf(NULL,
  13759. NULL, /* No truncation check for ebuf */
  13760. ebuf,
  13761. ebuf_len,
  13762. "%s: cannot load %s",
  13763. __func__,
  13764. dll_name);
  13765. return NULL;
  13766. }
  13767. ok = 1;
  13768. for (fp = sw; fp->name != NULL; fp++) {
  13769. enum ssl_func_category req = fp->required;
  13770. #if defined(_WIN32)
  13771. /* GetProcAddress() returns pointer to function */
  13772. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13773. #else
  13774. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13775. * pointers to function pointers. We need to use a union to make a
  13776. * cast. */
  13777. u.p = dlsym(dll_handle, fp->name);
  13778. #endif /* _WIN32 */
  13779. /* Set pointer (might be NULL) */
  13780. fp->ptr = u.fp;
  13781. if (u.fp == NULL) {
  13782. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13783. tls_feature_missing[req]++;
  13784. if (req == TLS_Mandatory) {
  13785. /* Mandatory function is missing */
  13786. if (ok) {
  13787. /* This is the first missing function.
  13788. * Create a new error message. */
  13789. mg_snprintf(NULL,
  13790. &truncated,
  13791. ebuf,
  13792. ebuf_len,
  13793. "%s: %s: cannot find %s",
  13794. __func__,
  13795. dll_name,
  13796. fp->name);
  13797. ok = 0;
  13798. } else {
  13799. /* This is yet anothermissing function.
  13800. * Append existing error message. */
  13801. size_t cur_len = strlen(ebuf);
  13802. if (!truncated) {
  13803. mg_snprintf(NULL,
  13804. &truncated,
  13805. ebuf + cur_len,
  13806. ebuf_len - cur_len - 3,
  13807. ", %s",
  13808. fp->name);
  13809. if (truncated) {
  13810. /* If truncated, add "..." */
  13811. strcat(ebuf, "...");
  13812. }
  13813. }
  13814. }
  13815. }
  13816. }
  13817. }
  13818. if (!ok) {
  13819. (void)dlclose(dll_handle);
  13820. return NULL;
  13821. }
  13822. return dll_handle;
  13823. }
  13824. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13825. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13826. #endif /* NO_SSL_DL */
  13827. #if defined(SSL_ALREADY_INITIALIZED)
  13828. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13829. #else
  13830. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13831. #endif
  13832. static int
  13833. initialize_ssl(char *ebuf, size_t ebuf_len)
  13834. {
  13835. #if defined(OPENSSL_API_1_1)
  13836. if (ebuf_len > 0) {
  13837. ebuf[0] = 0;
  13838. }
  13839. #if !defined(NO_SSL_DL)
  13840. if (!cryptolib_dll_handle) {
  13841. cryptolib_dll_handle =
  13842. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13843. if (!cryptolib_dll_handle) {
  13844. mg_snprintf(NULL,
  13845. NULL, /* No truncation check for ebuf */
  13846. ebuf,
  13847. ebuf_len,
  13848. "%s: error loading library %s",
  13849. __func__,
  13850. CRYPTO_LIB);
  13851. DEBUG_TRACE("%s", ebuf);
  13852. return 0;
  13853. }
  13854. }
  13855. #endif /* NO_SSL_DL */
  13856. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13857. return 1;
  13858. }
  13859. #else /* not OPENSSL_API_1_1 */
  13860. int i, num_locks;
  13861. size_t size;
  13862. if (ebuf_len > 0) {
  13863. ebuf[0] = 0;
  13864. }
  13865. #if !defined(NO_SSL_DL)
  13866. if (!cryptolib_dll_handle) {
  13867. cryptolib_dll_handle =
  13868. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13869. if (!cryptolib_dll_handle) {
  13870. mg_snprintf(NULL,
  13871. NULL, /* No truncation check for ebuf */
  13872. ebuf,
  13873. ebuf_len,
  13874. "%s: error loading library %s",
  13875. __func__,
  13876. CRYPTO_LIB);
  13877. DEBUG_TRACE("%s", ebuf);
  13878. return 0;
  13879. }
  13880. }
  13881. #endif /* NO_SSL_DL */
  13882. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13883. return 1;
  13884. }
  13885. /* Initialize locking callbacks, needed for thread safety.
  13886. * http://www.openssl.org/support/faq.html#PROG1
  13887. */
  13888. num_locks = CRYPTO_num_locks();
  13889. if (num_locks < 0) {
  13890. num_locks = 0;
  13891. }
  13892. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13893. /* allocate mutex array, if required */
  13894. if (num_locks == 0) {
  13895. /* No mutex array required */
  13896. ssl_mutexes = NULL;
  13897. } else {
  13898. /* Mutex array required - allocate it */
  13899. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13900. /* Check OOM */
  13901. if (ssl_mutexes == NULL) {
  13902. mg_snprintf(NULL,
  13903. NULL, /* No truncation check for ebuf */
  13904. ebuf,
  13905. ebuf_len,
  13906. "%s: cannot allocate mutexes: %s",
  13907. __func__,
  13908. ssl_error());
  13909. DEBUG_TRACE("%s", ebuf);
  13910. return 0;
  13911. }
  13912. /* initialize mutex array */
  13913. for (i = 0; i < num_locks; i++) {
  13914. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13915. mg_snprintf(NULL,
  13916. NULL, /* No truncation check for ebuf */
  13917. ebuf,
  13918. ebuf_len,
  13919. "%s: error initializing mutex %i of %i",
  13920. __func__,
  13921. i,
  13922. num_locks);
  13923. DEBUG_TRACE("%s", ebuf);
  13924. mg_free(ssl_mutexes);
  13925. return 0;
  13926. }
  13927. }
  13928. }
  13929. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13930. CRYPTO_set_id_callback(&mg_current_thread_id);
  13931. #endif /* OPENSSL_API_1_1 */
  13932. #if !defined(NO_SSL_DL)
  13933. if (!ssllib_dll_handle) {
  13934. ssllib_dll_handle = load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13935. if (!ssllib_dll_handle) {
  13936. #if !defined(OPENSSL_API_1_1)
  13937. mg_free(ssl_mutexes);
  13938. #endif
  13939. DEBUG_TRACE("%s", ebuf);
  13940. return 0;
  13941. }
  13942. }
  13943. #endif /* NO_SSL_DL */
  13944. #if defined(OPENSSL_API_1_1)
  13945. /* Initialize SSL library */
  13946. OPENSSL_init_ssl(0, NULL);
  13947. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13948. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13949. NULL);
  13950. #else
  13951. /* Initialize SSL library */
  13952. SSL_library_init();
  13953. SSL_load_error_strings();
  13954. #endif
  13955. return 1;
  13956. }
  13957. static int
  13958. ssl_use_pem_file(struct mg_context *phys_ctx,
  13959. struct mg_domain_context *dom_ctx,
  13960. const char *pem,
  13961. const char *chain)
  13962. {
  13963. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13964. mg_cry_ctx_internal(phys_ctx,
  13965. "%s: cannot open certificate file %s: %s",
  13966. __func__,
  13967. pem,
  13968. ssl_error());
  13969. return 0;
  13970. }
  13971. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13972. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13973. mg_cry_ctx_internal(phys_ctx,
  13974. "%s: cannot open private key file %s: %s",
  13975. __func__,
  13976. pem,
  13977. ssl_error());
  13978. return 0;
  13979. }
  13980. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13981. mg_cry_ctx_internal(phys_ctx,
  13982. "%s: certificate and private key do not match: %s",
  13983. __func__,
  13984. pem);
  13985. return 0;
  13986. }
  13987. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13988. * chain files that contain private keys and certificates in
  13989. * SSL_CTX_use_certificate_chain_file.
  13990. * The CivetWeb-Server used pem-Files that contained both information.
  13991. * In order to make wolfSSL work, it is split in two files.
  13992. * One file that contains key and certificate used by the server and
  13993. * an optional chain file for the ssl stack.
  13994. */
  13995. if (chain) {
  13996. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13997. mg_cry_ctx_internal(phys_ctx,
  13998. "%s: cannot use certificate chain file %s: %s",
  13999. __func__,
  14000. chain,
  14001. ssl_error());
  14002. return 0;
  14003. }
  14004. }
  14005. return 1;
  14006. }
  14007. #if defined(OPENSSL_API_1_1)
  14008. static unsigned long
  14009. ssl_get_protocol(int version_id)
  14010. {
  14011. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14012. if (version_id > 0)
  14013. ret |= SSL_OP_NO_SSLv2;
  14014. if (version_id > 1)
  14015. ret |= SSL_OP_NO_SSLv3;
  14016. if (version_id > 2)
  14017. ret |= SSL_OP_NO_TLSv1;
  14018. if (version_id > 3)
  14019. ret |= SSL_OP_NO_TLSv1_1;
  14020. if (version_id > 4)
  14021. ret |= SSL_OP_NO_TLSv1_2;
  14022. #if defined(SSL_OP_NO_TLSv1_3)
  14023. if (version_id > 5)
  14024. ret |= SSL_OP_NO_TLSv1_3;
  14025. #endif
  14026. return ret;
  14027. }
  14028. #else
  14029. static long
  14030. ssl_get_protocol(int version_id)
  14031. {
  14032. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14033. if (version_id > 0)
  14034. ret |= SSL_OP_NO_SSLv2;
  14035. if (version_id > 1)
  14036. ret |= SSL_OP_NO_SSLv3;
  14037. if (version_id > 2)
  14038. ret |= SSL_OP_NO_TLSv1;
  14039. if (version_id > 3)
  14040. ret |= SSL_OP_NO_TLSv1_1;
  14041. if (version_id > 4)
  14042. ret |= SSL_OP_NO_TLSv1_2;
  14043. #if defined(SSL_OP_NO_TLSv1_3)
  14044. if (version_id > 5)
  14045. ret |= SSL_OP_NO_TLSv1_3;
  14046. #endif
  14047. return (long)ret;
  14048. }
  14049. #endif /* OPENSSL_API_1_1 */
  14050. /* SSL callback documentation:
  14051. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14052. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14053. * https://linux.die.net/man/3/ssl_set_info_callback */
  14054. /* Note: There is no "const" for the first argument in the documentation
  14055. * examples, however some (maybe most, but not all) headers of OpenSSL
  14056. * versions / OpenSSL compatibility layers have it. Having a different
  14057. * definition will cause a warning in C and an error in C++. Use "const SSL
  14058. * *", while automatical conversion from "SSL *" works for all compilers,
  14059. * but not other way around */
  14060. static void
  14061. ssl_info_callback(const SSL *ssl, int what, int ret)
  14062. {
  14063. (void)ret;
  14064. if (what & SSL_CB_HANDSHAKE_START) {
  14065. SSL_get_app_data(ssl);
  14066. }
  14067. if (what & SSL_CB_HANDSHAKE_DONE) {
  14068. /* TODO: check for openSSL 1.1 */
  14069. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14070. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14071. }
  14072. }
  14073. static int
  14074. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14075. {
  14076. #if defined(GCC_DIAGNOSTIC)
  14077. #pragma GCC diagnostic push
  14078. #pragma GCC diagnostic ignored "-Wcast-align"
  14079. #endif /* defined(GCC_DIAGNOSTIC) */
  14080. /* We used an aligned pointer in SSL_set_app_data */
  14081. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14082. #if defined(GCC_DIAGNOSTIC)
  14083. #pragma GCC diagnostic pop
  14084. #endif /* defined(GCC_DIAGNOSTIC) */
  14085. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14086. (void)ad;
  14087. (void)arg;
  14088. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14089. DEBUG_ASSERT(0);
  14090. return SSL_TLSEXT_ERR_NOACK;
  14091. }
  14092. conn->dom_ctx = &(conn->phys_ctx->dd);
  14093. /* Old clients (Win XP) will not support SNI. Then, there
  14094. * is no server name available in the request - we can
  14095. * only work with the default certificate.
  14096. * Multiple HTTPS hosts on one IP+port are only possible
  14097. * with a certificate containing all alternative names.
  14098. */
  14099. if ((servername == NULL) || (*servername == 0)) {
  14100. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14101. mg_lock_context(conn->phys_ctx);
  14102. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14103. mg_unlock_context(conn->phys_ctx);
  14104. return SSL_TLSEXT_ERR_NOACK;
  14105. }
  14106. DEBUG_TRACE("TLS connection to host %s", servername);
  14107. while (conn->dom_ctx) {
  14108. if (!mg_strcasecmp(servername,
  14109. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14110. /* Found matching domain */
  14111. DEBUG_TRACE("TLS domain %s found",
  14112. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14113. break;
  14114. }
  14115. mg_lock_context(conn->phys_ctx);
  14116. conn->dom_ctx = conn->dom_ctx->next;
  14117. mg_unlock_context(conn->phys_ctx);
  14118. }
  14119. if (conn->dom_ctx == NULL) {
  14120. /* Default domain */
  14121. DEBUG_TRACE("TLS default domain %s used",
  14122. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14123. conn->dom_ctx = &(conn->phys_ctx->dd);
  14124. }
  14125. mg_lock_context(conn->phys_ctx);
  14126. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14127. mg_unlock_context(conn->phys_ctx);
  14128. return SSL_TLSEXT_ERR_OK;
  14129. }
  14130. #if defined(USE_HTTP2)
  14131. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14132. static const char *alpn_proto_order[] = {alpn_proto_list,
  14133. alpn_proto_list + 3,
  14134. alpn_proto_list + 3 + 8,
  14135. NULL};
  14136. #else
  14137. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14138. static const char *alpn_proto_order[] = {alpn_proto_list,
  14139. alpn_proto_list + 8,
  14140. NULL};
  14141. #endif
  14142. static int
  14143. alpn_select_cb(SSL *ssl,
  14144. const unsigned char **out,
  14145. unsigned char *outlen,
  14146. const unsigned char *in,
  14147. unsigned int inlen,
  14148. void *arg)
  14149. {
  14150. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14151. unsigned int i, j;
  14152. struct mg_workerTLS *tls =
  14153. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14154. (void)ssl;
  14155. (void)dom_ctx;
  14156. if (tls == NULL) {
  14157. /* Need to store protocol in Thread Local Storage */
  14158. /* If there is no Thread Local Storage, don't use ALPN */
  14159. return SSL_TLSEXT_ERR_NOACK;
  14160. }
  14161. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14162. /* check all accepted protocols in this order */
  14163. const char *alpn_proto = alpn_proto_order[j];
  14164. /* search input for matching protocol */
  14165. for (i = 0; i < inlen; i++) {
  14166. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14167. *out = in + i + 1;
  14168. *outlen = in[i];
  14169. tls->alpn_proto = alpn_proto;
  14170. return SSL_TLSEXT_ERR_OK;
  14171. }
  14172. }
  14173. }
  14174. /* Nothing found */
  14175. return SSL_TLSEXT_ERR_NOACK;
  14176. }
  14177. static int
  14178. next_protos_advertised_cb(SSL *ssl,
  14179. const unsigned char **data,
  14180. unsigned int *len,
  14181. void *arg)
  14182. {
  14183. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14184. *data = (const unsigned char *)alpn_proto_list;
  14185. *len = (unsigned int)strlen((const char *)data);
  14186. (void)ssl;
  14187. (void)dom_ctx;
  14188. return SSL_TLSEXT_ERR_OK;
  14189. }
  14190. static int
  14191. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14192. {
  14193. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14194. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14195. (const unsigned char *)alpn_proto_list,
  14196. alpn_len);
  14197. if (ret != 0) {
  14198. mg_cry_ctx_internal(phys_ctx,
  14199. "SSL_CTX_set_alpn_protos error: %s",
  14200. ssl_error());
  14201. }
  14202. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14203. alpn_select_cb,
  14204. (void *)dom_ctx);
  14205. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14206. next_protos_advertised_cb,
  14207. (void *)dom_ctx);
  14208. return ret;
  14209. }
  14210. /* Setup SSL CTX as required by CivetWeb */
  14211. static int
  14212. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14213. struct mg_domain_context *dom_ctx,
  14214. const char *pem,
  14215. const char *chain)
  14216. {
  14217. int callback_ret;
  14218. int should_verify_peer;
  14219. int peer_certificate_optional;
  14220. const char *ca_path;
  14221. const char *ca_file;
  14222. int use_default_verify_paths;
  14223. int verify_depth;
  14224. struct timespec now_mt;
  14225. md5_byte_t ssl_context_id[16];
  14226. md5_state_t md5state;
  14227. int protocol_ver;
  14228. #if defined(OPENSSL_API_1_1)
  14229. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14230. mg_cry_ctx_internal(phys_ctx,
  14231. "SSL_CTX_new (server) error: %s",
  14232. ssl_error());
  14233. return 0;
  14234. }
  14235. #else
  14236. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14237. mg_cry_ctx_internal(phys_ctx,
  14238. "SSL_CTX_new (server) error: %s",
  14239. ssl_error());
  14240. return 0;
  14241. }
  14242. #endif /* OPENSSL_API_1_1 */
  14243. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14244. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14245. | SSL_OP_NO_TLSv1_1);
  14246. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14247. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14248. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14249. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14250. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14251. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14252. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14253. #if defined(SSL_OP_NO_RENEGOTIATION)
  14254. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14255. #endif
  14256. #if !defined(NO_SSL_DL)
  14257. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14258. #endif /* NO_SSL_DL */
  14259. /* In SSL documentation examples callback defined without const
  14260. * specifier 'void (*)(SSL *, int, int)' See:
  14261. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14262. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14263. * But in the source code const SSL is used:
  14264. * 'void (*)(const SSL *, int, int)' See:
  14265. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14266. * Problem about wrong documentation described, but not resolved:
  14267. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14268. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14269. * But when compiled with modern C++ compiler, correct const should be
  14270. * provided
  14271. */
  14272. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14273. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14274. ssl_servername_callback);
  14275. /* If a callback has been specified, call it. */
  14276. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14277. ? 0
  14278. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14279. phys_ctx->user_data));
  14280. /* If callback returns 0, civetweb sets up the SSL certificate.
  14281. * If it returns 1, civetweb assumes the calback already did this.
  14282. * If it returns -1, initializing ssl fails. */
  14283. if (callback_ret < 0) {
  14284. mg_cry_ctx_internal(phys_ctx,
  14285. "SSL callback returned error: %i",
  14286. callback_ret);
  14287. return 0;
  14288. }
  14289. if (callback_ret > 0) {
  14290. /* Callback did everything. */
  14291. return 1;
  14292. }
  14293. /* If a domain callback has been specified, call it. */
  14294. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14295. ? 0
  14296. : (phys_ctx->callbacks.init_ssl_domain(
  14297. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14298. dom_ctx->ssl_ctx,
  14299. phys_ctx->user_data));
  14300. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14301. * If it returns 1, civetweb assumes the calback already did this.
  14302. * If it returns -1, initializing ssl fails. */
  14303. if (callback_ret < 0) {
  14304. mg_cry_ctx_internal(phys_ctx,
  14305. "Domain SSL callback returned error: %i",
  14306. callback_ret);
  14307. return 0;
  14308. }
  14309. if (callback_ret > 0) {
  14310. /* Domain callback did everything. */
  14311. return 1;
  14312. }
  14313. /* Use some combination of start time, domain and port as a SSL
  14314. * context ID. This should be unique on the current machine. */
  14315. md5_init(&md5state);
  14316. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14317. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14318. md5_append(&md5state,
  14319. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14320. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14321. md5_append(&md5state,
  14322. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14323. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14324. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14325. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14326. md5_finish(&md5state, ssl_context_id);
  14327. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14328. (unsigned char *)ssl_context_id,
  14329. sizeof(ssl_context_id));
  14330. if (pem != NULL) {
  14331. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14332. return 0;
  14333. }
  14334. }
  14335. /* Should we support client certificates? */
  14336. /* Default is "no". */
  14337. should_verify_peer = 0;
  14338. peer_certificate_optional = 0;
  14339. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14340. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14341. /* Yes, they are mandatory */
  14342. should_verify_peer = 1;
  14343. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14344. "optional")
  14345. == 0) {
  14346. /* Yes, they are optional */
  14347. should_verify_peer = 1;
  14348. peer_certificate_optional = 1;
  14349. }
  14350. }
  14351. use_default_verify_paths =
  14352. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14353. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14354. == 0);
  14355. if (should_verify_peer) {
  14356. ca_path = dom_ctx->config[SSL_CA_PATH];
  14357. ca_file = dom_ctx->config[SSL_CA_FILE];
  14358. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14359. != 1) {
  14360. mg_cry_ctx_internal(phys_ctx,
  14361. "SSL_CTX_load_verify_locations error: %s "
  14362. "ssl_verify_peer requires setting "
  14363. "either ssl_ca_path or ssl_ca_file. "
  14364. "Is any of them present in the "
  14365. ".conf file?",
  14366. ssl_error());
  14367. return 0;
  14368. }
  14369. if (peer_certificate_optional) {
  14370. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14371. } else {
  14372. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14373. SSL_VERIFY_PEER
  14374. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14375. NULL);
  14376. }
  14377. if (use_default_verify_paths
  14378. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14379. mg_cry_ctx_internal(phys_ctx,
  14380. "SSL_CTX_set_default_verify_paths error: %s",
  14381. ssl_error());
  14382. return 0;
  14383. }
  14384. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14385. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14386. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14387. }
  14388. }
  14389. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14390. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14391. dom_ctx->config[SSL_CIPHER_LIST])
  14392. != 1) {
  14393. mg_cry_ctx_internal(phys_ctx,
  14394. "SSL_CTX_set_cipher_list error: %s",
  14395. ssl_error());
  14396. }
  14397. }
  14398. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14399. #if !defined(NO_SSL_DL)
  14400. if (!tls_feature_missing[TLS_ALPN])
  14401. #endif
  14402. {
  14403. init_alpn(phys_ctx, dom_ctx);
  14404. }
  14405. return 1;
  14406. }
  14407. /* Check if SSL is required.
  14408. * If so, dynamically load SSL library
  14409. * and set up ctx->ssl_ctx pointer. */
  14410. static int
  14411. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14412. {
  14413. void *ssl_ctx = 0;
  14414. int callback_ret;
  14415. const char *pem;
  14416. const char *chain;
  14417. char ebuf[128];
  14418. if (!phys_ctx) {
  14419. return 0;
  14420. }
  14421. if (!dom_ctx) {
  14422. dom_ctx = &(phys_ctx->dd);
  14423. }
  14424. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14425. /* No SSL port is set. No need to setup SSL. */
  14426. return 1;
  14427. }
  14428. /* Check for external SSL_CTX */
  14429. callback_ret =
  14430. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14431. ? 0
  14432. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14433. phys_ctx->user_data));
  14434. if (callback_ret < 0) {
  14435. mg_cry_ctx_internal(phys_ctx,
  14436. "external_ssl_ctx callback returned error: %i",
  14437. callback_ret);
  14438. return 0;
  14439. } else if (callback_ret > 0) {
  14440. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14441. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14442. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14443. return 0;
  14444. }
  14445. return 1;
  14446. }
  14447. /* Check for external domain SSL_CTX */
  14448. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14449. ? 0
  14450. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14451. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14452. &ssl_ctx,
  14453. phys_ctx->user_data));
  14454. if (callback_ret < 0) {
  14455. mg_cry_ctx_internal(
  14456. phys_ctx,
  14457. "external_ssl_ctx_domain callback returned error: %i",
  14458. callback_ret);
  14459. return 0;
  14460. } else if (callback_ret > 0) {
  14461. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14462. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14463. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14464. return 0;
  14465. }
  14466. return 1;
  14467. }
  14468. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14469. * 0, CivetWeb should continue initializing SSL */
  14470. /* If PEM file is not specified and the init_ssl callbacks
  14471. * are not specified, setup will fail. */
  14472. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14473. && (phys_ctx->callbacks.init_ssl == NULL)
  14474. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14475. /* No certificate and no init_ssl callbacks:
  14476. * Essential data to set up TLS is missing.
  14477. */
  14478. mg_cry_ctx_internal(phys_ctx,
  14479. "Initializing SSL failed: -%s is not set",
  14480. config_options[SSL_CERTIFICATE].name);
  14481. return 0;
  14482. }
  14483. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14484. if (chain == NULL) {
  14485. chain = pem;
  14486. }
  14487. if ((chain != NULL) && (*chain == 0)) {
  14488. chain = NULL;
  14489. }
  14490. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14491. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14492. return 0;
  14493. }
  14494. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14495. }
  14496. static void
  14497. uninitialize_ssl(void)
  14498. {
  14499. #if defined(OPENSSL_API_1_1)
  14500. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14501. /* Shutdown according to
  14502. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14503. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14504. */
  14505. CONF_modules_unload(1);
  14506. #else
  14507. int i;
  14508. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14509. /* Shutdown according to
  14510. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14511. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14512. */
  14513. CRYPTO_set_locking_callback(NULL);
  14514. CRYPTO_set_id_callback(NULL);
  14515. ENGINE_cleanup();
  14516. CONF_modules_unload(1);
  14517. ERR_free_strings();
  14518. EVP_cleanup();
  14519. CRYPTO_cleanup_all_ex_data();
  14520. OPENSSL_REMOVE_THREAD_STATE();
  14521. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14522. pthread_mutex_destroy(&ssl_mutexes[i]);
  14523. }
  14524. mg_free(ssl_mutexes);
  14525. ssl_mutexes = NULL;
  14526. #endif /* OPENSSL_API_1_1 */
  14527. }
  14528. }
  14529. #endif /* !NO_SSL */
  14530. #if !defined(NO_FILESYSTEMS)
  14531. static int
  14532. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14533. {
  14534. if (phys_ctx) {
  14535. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14536. const char *path;
  14537. struct mg_connection fc;
  14538. if (!dom_ctx) {
  14539. dom_ctx = &(phys_ctx->dd);
  14540. }
  14541. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14542. if ((path != NULL)
  14543. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14544. mg_cry_ctx_internal(phys_ctx,
  14545. "Cannot open %s: %s",
  14546. path,
  14547. strerror(ERRNO));
  14548. return 0;
  14549. }
  14550. return 1;
  14551. }
  14552. return 0;
  14553. }
  14554. #endif /* NO_FILESYSTEMS */
  14555. static int
  14556. set_acl_option(struct mg_context *phys_ctx)
  14557. {
  14558. union usa sa;
  14559. memset(&sa, 0, sizeof(sa));
  14560. #if defined(USE_IPV6)
  14561. sa.sin6.sin6_family = AF_INET6;
  14562. #else
  14563. sa.sin.sin_family = AF_INET;
  14564. #endif
  14565. return check_acl(phys_ctx, &sa) != -1;
  14566. }
  14567. static void
  14568. reset_per_request_attributes(struct mg_connection *conn)
  14569. {
  14570. if (!conn) {
  14571. return;
  14572. }
  14573. conn->connection_type =
  14574. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14575. conn->num_bytes_sent = conn->consumed_content = 0;
  14576. conn->path_info = NULL;
  14577. conn->status_code = -1;
  14578. conn->content_len = -1;
  14579. conn->is_chunked = 0;
  14580. conn->must_close = 0;
  14581. conn->request_len = 0;
  14582. conn->throttle = 0;
  14583. conn->accept_gzip = 0;
  14584. conn->response_info.content_length = conn->request_info.content_length = -1;
  14585. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14586. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14587. conn->response_info.status_text = NULL;
  14588. conn->response_info.status_code = 0;
  14589. conn->request_info.remote_user = NULL;
  14590. conn->request_info.request_method = NULL;
  14591. conn->request_info.request_uri = NULL;
  14592. conn->request_info.local_uri = NULL;
  14593. #if defined(MG_LEGACY_INTERFACE)
  14594. /* Legacy before split into local_uri and request_uri */
  14595. conn->request_info.uri = NULL;
  14596. #endif
  14597. }
  14598. static int
  14599. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14600. {
  14601. if (setsockopt(sock,
  14602. IPPROTO_TCP,
  14603. TCP_NODELAY,
  14604. (SOCK_OPT_TYPE)&nodelay_on,
  14605. sizeof(nodelay_on))
  14606. != 0) {
  14607. /* Error */
  14608. return 1;
  14609. }
  14610. /* OK */
  14611. return 0;
  14612. }
  14613. #if !defined(__ZEPHYR__)
  14614. static void
  14615. close_socket_gracefully(struct mg_connection *conn)
  14616. {
  14617. #if defined(_WIN32)
  14618. char buf[MG_BUF_LEN];
  14619. int n;
  14620. #endif
  14621. struct linger linger;
  14622. int error_code = 0;
  14623. int linger_timeout = -2;
  14624. socklen_t opt_len = sizeof(error_code);
  14625. if (!conn) {
  14626. return;
  14627. }
  14628. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14629. * "Note that enabling a nonzero timeout on a nonblocking socket
  14630. * is not recommended.", so set it to blocking now */
  14631. set_blocking_mode(conn->client.sock);
  14632. /* Send FIN to the client */
  14633. shutdown(conn->client.sock, SHUTDOWN_WR);
  14634. #if defined(_WIN32)
  14635. /* Read and discard pending incoming data. If we do not do that and
  14636. * close
  14637. * the socket, the data in the send buffer may be discarded. This
  14638. * behaviour is seen on Windows, when client keeps sending data
  14639. * when server decides to close the connection; then when client
  14640. * does recv() it gets no data back. */
  14641. do {
  14642. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14643. } while (n > 0);
  14644. #endif
  14645. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14646. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14647. }
  14648. /* Set linger option according to configuration */
  14649. if (linger_timeout >= 0) {
  14650. /* Set linger option to avoid socket hanging out after close. This
  14651. * prevent ephemeral port exhaust problem under high QPS. */
  14652. linger.l_onoff = 1;
  14653. #if defined(_MSC_VER)
  14654. #pragma warning(push)
  14655. #pragma warning(disable : 4244)
  14656. #endif
  14657. #if defined(GCC_DIAGNOSTIC)
  14658. #pragma GCC diagnostic push
  14659. #pragma GCC diagnostic ignored "-Wconversion"
  14660. #endif
  14661. /* Data type of linger structure elements may differ,
  14662. * so we don't know what cast we need here.
  14663. * Disable type conversion warnings. */
  14664. linger.l_linger = (linger_timeout + 999) / 1000;
  14665. #if defined(GCC_DIAGNOSTIC)
  14666. #pragma GCC diagnostic pop
  14667. #endif
  14668. #if defined(_MSC_VER)
  14669. #pragma warning(pop)
  14670. #endif
  14671. } else {
  14672. linger.l_onoff = 0;
  14673. linger.l_linger = 0;
  14674. }
  14675. if (linger_timeout < -1) {
  14676. /* Default: don't configure any linger */
  14677. } else if (getsockopt(conn->client.sock,
  14678. SOL_SOCKET,
  14679. SO_ERROR,
  14680. #if defined(_WIN32) /* WinSock uses different data type here */
  14681. (char *)&error_code,
  14682. #else
  14683. &error_code,
  14684. #endif
  14685. &opt_len)
  14686. != 0) {
  14687. /* Cannot determine if socket is already closed. This should
  14688. * not occur and never did in a test. Log an error message
  14689. * and continue. */
  14690. mg_cry_internal(conn,
  14691. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14692. __func__,
  14693. strerror(ERRNO));
  14694. #if defined(_WIN32)
  14695. } else if (error_code == WSAECONNRESET) {
  14696. #else
  14697. } else if (error_code == ECONNRESET) {
  14698. #endif
  14699. /* Socket already closed by client/peer, close socket without linger
  14700. */
  14701. } else {
  14702. /* Set linger timeout */
  14703. if (setsockopt(conn->client.sock,
  14704. SOL_SOCKET,
  14705. SO_LINGER,
  14706. (char *)&linger,
  14707. sizeof(linger))
  14708. != 0) {
  14709. mg_cry_internal(
  14710. conn,
  14711. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14712. __func__,
  14713. linger.l_onoff,
  14714. linger.l_linger,
  14715. strerror(ERRNO));
  14716. }
  14717. }
  14718. /* Now we know that our FIN is ACK-ed, safe to close */
  14719. closesocket(conn->client.sock);
  14720. conn->client.sock = INVALID_SOCKET;
  14721. }
  14722. #endif
  14723. static void
  14724. close_connection(struct mg_connection *conn)
  14725. {
  14726. #if defined(USE_SERVER_STATS)
  14727. conn->conn_state = 6; /* to close */
  14728. #endif
  14729. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14730. if (conn->lua_websocket_state) {
  14731. lua_websocket_close(conn, conn->lua_websocket_state);
  14732. conn->lua_websocket_state = NULL;
  14733. }
  14734. #endif
  14735. mg_lock_connection(conn);
  14736. /* Set close flag, so keep-alive loops will stop */
  14737. conn->must_close = 1;
  14738. /* call the connection_close callback if assigned */
  14739. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14740. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14741. conn->phys_ctx->callbacks.connection_close(conn);
  14742. }
  14743. }
  14744. /* Reset user data, after close callback is called.
  14745. * Do not reuse it. If the user needs a destructor,
  14746. * it must be done in the connection_close callback. */
  14747. mg_set_user_connection_data(conn, NULL);
  14748. #if defined(USE_SERVER_STATS)
  14749. conn->conn_state = 7; /* closing */
  14750. #endif
  14751. #if !defined(NO_SSL)
  14752. if (conn->ssl != NULL) {
  14753. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14754. */
  14755. SSL_shutdown(conn->ssl);
  14756. SSL_free(conn->ssl);
  14757. OPENSSL_REMOVE_THREAD_STATE();
  14758. conn->ssl = NULL;
  14759. }
  14760. #endif
  14761. if (conn->client.sock != INVALID_SOCKET) {
  14762. #if defined(__ZEPHYR__)
  14763. closesocket(conn->client.sock);
  14764. #else
  14765. close_socket_gracefully(conn);
  14766. #endif
  14767. conn->client.sock = INVALID_SOCKET;
  14768. }
  14769. mg_unlock_connection(conn);
  14770. #if defined(USE_SERVER_STATS)
  14771. conn->conn_state = 8; /* closed */
  14772. #endif
  14773. }
  14774. void
  14775. mg_close_connection(struct mg_connection *conn)
  14776. {
  14777. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14778. return;
  14779. }
  14780. #if defined(USE_WEBSOCKET)
  14781. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14782. if (conn->in_websocket_handling) {
  14783. /* Set close flag, so the server thread can exit. */
  14784. conn->must_close = 1;
  14785. return;
  14786. }
  14787. }
  14788. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14789. unsigned int i;
  14790. /* client context: loops must end */
  14791. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14792. conn->must_close = 1;
  14793. /* We need to get the client thread out of the select/recv call
  14794. * here. */
  14795. /* Since we use a sleep quantum of some seconds to check for recv
  14796. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14797. /* join worker thread */
  14798. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14799. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14800. }
  14801. }
  14802. #endif /* defined(USE_WEBSOCKET) */
  14803. close_connection(conn);
  14804. #if !defined(NO_SSL)
  14805. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14806. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14807. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14808. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14809. }
  14810. #endif
  14811. #if defined(USE_WEBSOCKET)
  14812. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14813. mg_free(conn->phys_ctx->worker_threadids);
  14814. (void)pthread_mutex_destroy(&conn->mutex);
  14815. mg_free(conn);
  14816. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14817. (void)pthread_mutex_destroy(&conn->mutex);
  14818. mg_free(conn);
  14819. }
  14820. #else
  14821. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14822. (void)pthread_mutex_destroy(&conn->mutex);
  14823. mg_free(conn);
  14824. }
  14825. #endif /* defined(USE_WEBSOCKET) */
  14826. }
  14827. static struct mg_connection *
  14828. mg_connect_client_impl(const struct mg_client_options *client_options,
  14829. int use_ssl,
  14830. char *ebuf,
  14831. size_t ebuf_len)
  14832. {
  14833. struct mg_connection *conn = NULL;
  14834. SOCKET sock;
  14835. union usa sa;
  14836. struct sockaddr *psa;
  14837. socklen_t len;
  14838. unsigned max_req_size =
  14839. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14840. /* Size of structures, aligned to 8 bytes */
  14841. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14842. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14843. conn =
  14844. (struct mg_connection *)mg_calloc(1,
  14845. conn_size + ctx_size + max_req_size);
  14846. if (conn == NULL) {
  14847. mg_snprintf(NULL,
  14848. NULL, /* No truncation check for ebuf */
  14849. ebuf,
  14850. ebuf_len,
  14851. "calloc(): %s",
  14852. strerror(ERRNO));
  14853. return NULL;
  14854. }
  14855. #if defined(GCC_DIAGNOSTIC)
  14856. #pragma GCC diagnostic push
  14857. #pragma GCC diagnostic ignored "-Wcast-align"
  14858. #endif /* defined(GCC_DIAGNOSTIC) */
  14859. /* conn_size is aligned to 8 bytes */
  14860. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14861. #if defined(GCC_DIAGNOSTIC)
  14862. #pragma GCC diagnostic pop
  14863. #endif /* defined(GCC_DIAGNOSTIC) */
  14864. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14865. conn->buf_size = (int)max_req_size;
  14866. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14867. conn->dom_ctx = &(conn->phys_ctx->dd);
  14868. if (!connect_socket(conn->phys_ctx,
  14869. client_options->host,
  14870. client_options->port,
  14871. use_ssl,
  14872. ebuf,
  14873. ebuf_len,
  14874. &sock,
  14875. &sa)) {
  14876. /* ebuf is set by connect_socket,
  14877. * free all memory and return NULL; */
  14878. mg_free(conn);
  14879. return NULL;
  14880. }
  14881. #if !defined(NO_SSL)
  14882. #if defined(OPENSSL_API_1_1)
  14883. if (use_ssl
  14884. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14885. == NULL) {
  14886. mg_snprintf(NULL,
  14887. NULL, /* No truncation check for ebuf */
  14888. ebuf,
  14889. ebuf_len,
  14890. "SSL_CTX_new error: %s",
  14891. ssl_error());
  14892. closesocket(sock);
  14893. mg_free(conn);
  14894. return NULL;
  14895. }
  14896. #else
  14897. if (use_ssl
  14898. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14899. == NULL) {
  14900. mg_snprintf(NULL,
  14901. NULL, /* No truncation check for ebuf */
  14902. ebuf,
  14903. ebuf_len,
  14904. "SSL_CTX_new error: %s",
  14905. ssl_error());
  14906. closesocket(sock);
  14907. mg_free(conn);
  14908. return NULL;
  14909. }
  14910. #endif /* OPENSSL_API_1_1 */
  14911. #endif /* NO_SSL */
  14912. #if defined(USE_IPV6)
  14913. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14914. : sizeof(conn->client.rsa.sin6);
  14915. psa = (sa.sa.sa_family == AF_INET)
  14916. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14917. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14918. #else
  14919. len = sizeof(conn->client.rsa.sin);
  14920. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14921. #endif
  14922. conn->client.sock = sock;
  14923. conn->client.lsa = sa;
  14924. if (getsockname(sock, psa, &len) != 0) {
  14925. mg_cry_internal(conn,
  14926. "%s: getsockname() failed: %s",
  14927. __func__,
  14928. strerror(ERRNO));
  14929. }
  14930. conn->client.is_ssl = use_ssl ? 1 : 0;
  14931. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14932. mg_snprintf(NULL,
  14933. NULL, /* No truncation check for ebuf */
  14934. ebuf,
  14935. ebuf_len,
  14936. "Can not create mutex");
  14937. #if !defined(NO_SSL)
  14938. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14939. #endif
  14940. closesocket(sock);
  14941. mg_free(conn);
  14942. return NULL;
  14943. }
  14944. #if !defined(NO_SSL)
  14945. if (use_ssl) {
  14946. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14947. * SSL_CTX_set_verify call is needed to switch off server
  14948. * certificate checking, which is off by default in OpenSSL and
  14949. * on in yaSSL. */
  14950. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14951. * SSL_VERIFY_PEER, verify_ssl_server); */
  14952. if (client_options->client_cert) {
  14953. if (!ssl_use_pem_file(conn->phys_ctx,
  14954. conn->dom_ctx,
  14955. client_options->client_cert,
  14956. NULL)) {
  14957. mg_snprintf(NULL,
  14958. NULL, /* No truncation check for ebuf */
  14959. ebuf,
  14960. ebuf_len,
  14961. "Can not use SSL client certificate");
  14962. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14963. closesocket(sock);
  14964. mg_free(conn);
  14965. return NULL;
  14966. }
  14967. }
  14968. if (client_options->server_cert) {
  14969. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14970. client_options->server_cert,
  14971. NULL)
  14972. != 1) {
  14973. mg_cry_internal(conn,
  14974. "SSL_CTX_load_verify_locations error: %s ",
  14975. ssl_error());
  14976. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14977. closesocket(sock);
  14978. mg_free(conn);
  14979. return NULL;
  14980. }
  14981. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14982. } else {
  14983. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14984. }
  14985. if (!sslize(conn, SSL_connect, client_options)) {
  14986. mg_snprintf(NULL,
  14987. NULL, /* No truncation check for ebuf */
  14988. ebuf,
  14989. ebuf_len,
  14990. "SSL connection error");
  14991. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14992. closesocket(sock);
  14993. mg_free(conn);
  14994. return NULL;
  14995. }
  14996. }
  14997. #endif
  14998. return conn;
  14999. }
  15000. CIVETWEB_API struct mg_connection *
  15001. mg_connect_client_secure(const struct mg_client_options *client_options,
  15002. char *error_buffer,
  15003. size_t error_buffer_size)
  15004. {
  15005. return mg_connect_client_impl(client_options,
  15006. 1,
  15007. error_buffer,
  15008. error_buffer_size);
  15009. }
  15010. struct mg_connection *
  15011. mg_connect_client(const char *host,
  15012. int port,
  15013. int use_ssl,
  15014. char *error_buffer,
  15015. size_t error_buffer_size)
  15016. {
  15017. struct mg_client_options opts;
  15018. memset(&opts, 0, sizeof(opts));
  15019. opts.host = host;
  15020. opts.port = port;
  15021. return mg_connect_client_impl(&opts,
  15022. use_ssl,
  15023. error_buffer,
  15024. error_buffer_size);
  15025. }
  15026. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15027. struct mg_connection *
  15028. mg_connect_client2(const char *host,
  15029. const char *protocol,
  15030. int port,
  15031. const char *path,
  15032. struct mg_init_data *init,
  15033. struct mg_error_data *error)
  15034. {
  15035. int is_ssl, is_ws;
  15036. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15037. if (error != NULL) {
  15038. error->code = 0;
  15039. if (error->text_buffer_size > 0) {
  15040. *error->text = 0;
  15041. }
  15042. }
  15043. if ((host == NULL) || (protocol == NULL)) {
  15044. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15045. mg_snprintf(NULL,
  15046. NULL, /* No truncation check for error buffers */
  15047. error->text,
  15048. error->text_buffer_size,
  15049. "%s",
  15050. "Invalid parameters");
  15051. }
  15052. return NULL;
  15053. }
  15054. /* check all known protocolls */
  15055. if (!mg_strcasecmp(protocol, "http")) {
  15056. is_ssl = 0;
  15057. is_ws = 0;
  15058. } else if (!mg_strcasecmp(protocol, "https")) {
  15059. is_ssl = 1;
  15060. is_ws = 0;
  15061. #if defined(USE_WEBSOCKET)
  15062. } else if (!mg_strcasecmp(protocol, "ws")) {
  15063. is_ssl = 0;
  15064. is_ws = 1;
  15065. } else if (!mg_strcasecmp(protocol, "wss")) {
  15066. is_ssl = 1;
  15067. is_ws = 1;
  15068. #endif
  15069. } else {
  15070. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15071. mg_snprintf(NULL,
  15072. NULL, /* No truncation check for error buffers */
  15073. error->text,
  15074. error->text_buffer_size,
  15075. "Protocol %s not supported",
  15076. protocol);
  15077. }
  15078. return NULL;
  15079. }
  15080. /* TODO: The current implementation here just calls the old
  15081. * implementations, without using any new options. This is just a first
  15082. * step to test the new interfaces. */
  15083. #if defined(USE_WEBSOCKET)
  15084. if (is_ws) {
  15085. /* TODO: implement all options */
  15086. return mg_connect_websocket_client(
  15087. host,
  15088. port,
  15089. is_ssl,
  15090. ((error != NULL) ? error->text : NULL),
  15091. ((error != NULL) ? error->text_buffer_size : 0),
  15092. (path ? path : ""),
  15093. NULL /* TODO: origin */,
  15094. deprecated_websocket_data_wrapper,
  15095. deprecated_websocket_close_wrapper,
  15096. (void *)init->callbacks);
  15097. }
  15098. #endif
  15099. /* TODO: all additional options */
  15100. struct mg_client_options opts;
  15101. memset(&opts, 0, sizeof(opts));
  15102. opts.host = host;
  15103. opts.port = port;
  15104. return mg_connect_client_impl(&opts,
  15105. is_ssl,
  15106. ((error != NULL) ? error->text : NULL),
  15107. ((error != NULL) ? error->text_buffer_size
  15108. : 0));
  15109. }
  15110. #endif
  15111. static const struct {
  15112. const char *proto;
  15113. size_t proto_len;
  15114. unsigned default_port;
  15115. } abs_uri_protocols[] = {{"http://", 7, 80},
  15116. {"https://", 8, 443},
  15117. {"ws://", 5, 80},
  15118. {"wss://", 6, 443},
  15119. {NULL, 0, 0}};
  15120. /* Check if the uri is valid.
  15121. * return 0 for invalid uri,
  15122. * return 1 for *,
  15123. * return 2 for relative uri,
  15124. * return 3 for absolute uri without port,
  15125. * return 4 for absolute uri with port */
  15126. static int
  15127. get_uri_type(const char *uri)
  15128. {
  15129. int i;
  15130. const char *hostend, *portbegin;
  15131. char *portend;
  15132. unsigned long port;
  15133. /* According to the HTTP standard
  15134. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15135. * URI can be an asterisk (*) or should start with slash (relative uri),
  15136. * or it should start with the protocol (absolute uri). */
  15137. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15138. /* asterisk */
  15139. return 1;
  15140. }
  15141. /* Valid URIs according to RFC 3986
  15142. * (https://www.ietf.org/rfc/rfc3986.txt)
  15143. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15144. * and unreserved characters A-Z a-z 0-9 and -._~
  15145. * and % encoded symbols.
  15146. */
  15147. for (i = 0; uri[i] != 0; i++) {
  15148. if (uri[i] < 33) {
  15149. /* control characters and spaces are invalid */
  15150. return 0;
  15151. }
  15152. if (uri[i] > 126) {
  15153. /* non-ascii characters must be % encoded */
  15154. return 0;
  15155. } else {
  15156. switch (uri[i]) {
  15157. case '"': /* 34 */
  15158. case '<': /* 60 */
  15159. case '>': /* 62 */
  15160. case '\\': /* 92 */
  15161. case '^': /* 94 */
  15162. case '`': /* 96 */
  15163. case '{': /* 123 */
  15164. case '|': /* 124 */
  15165. case '}': /* 125 */
  15166. return 0;
  15167. default:
  15168. /* character is ok */
  15169. break;
  15170. }
  15171. }
  15172. }
  15173. /* A relative uri starts with a / character */
  15174. if (uri[0] == '/') {
  15175. /* relative uri */
  15176. return 2;
  15177. }
  15178. /* It could be an absolute uri: */
  15179. /* This function only checks if the uri is valid, not if it is
  15180. * addressing the current server. So civetweb can also be used
  15181. * as a proxy server. */
  15182. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15183. if (mg_strncasecmp(uri,
  15184. abs_uri_protocols[i].proto,
  15185. abs_uri_protocols[i].proto_len)
  15186. == 0) {
  15187. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15188. if (!hostend) {
  15189. return 0;
  15190. }
  15191. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15192. if (!portbegin) {
  15193. return 3;
  15194. }
  15195. port = strtoul(portbegin + 1, &portend, 10);
  15196. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15197. return 0;
  15198. }
  15199. return 4;
  15200. }
  15201. }
  15202. return 0;
  15203. }
  15204. /* Return NULL or the relative uri at the current server */
  15205. static const char *
  15206. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15207. {
  15208. const char *server_domain;
  15209. size_t server_domain_len;
  15210. size_t request_domain_len = 0;
  15211. unsigned long port = 0;
  15212. int i, auth_domain_check_enabled;
  15213. const char *hostbegin = NULL;
  15214. const char *hostend = NULL;
  15215. const char *portbegin;
  15216. char *portend;
  15217. auth_domain_check_enabled =
  15218. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15219. /* DNS is case insensitive, so use case insensitive string compare here
  15220. */
  15221. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15222. if (mg_strncasecmp(uri,
  15223. abs_uri_protocols[i].proto,
  15224. abs_uri_protocols[i].proto_len)
  15225. == 0) {
  15226. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15227. hostend = strchr(hostbegin, '/');
  15228. if (!hostend) {
  15229. return 0;
  15230. }
  15231. portbegin = strchr(hostbegin, ':');
  15232. if ((!portbegin) || (portbegin > hostend)) {
  15233. port = abs_uri_protocols[i].default_port;
  15234. request_domain_len = (size_t)(hostend - hostbegin);
  15235. } else {
  15236. port = strtoul(portbegin + 1, &portend, 10);
  15237. if ((portend != hostend) || (port <= 0)
  15238. || !is_valid_port(port)) {
  15239. return 0;
  15240. }
  15241. request_domain_len = (size_t)(portbegin - hostbegin);
  15242. }
  15243. /* protocol found, port set */
  15244. break;
  15245. }
  15246. }
  15247. if (!port) {
  15248. /* port remains 0 if the protocol is not found */
  15249. return 0;
  15250. }
  15251. /* Check if the request is directed to a different server. */
  15252. /* First check if the port is the same. */
  15253. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15254. /* Request is directed to a different port */
  15255. return 0;
  15256. }
  15257. /* Finally check if the server corresponds to the authentication
  15258. * domain of the server (the server domain).
  15259. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15260. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15261. * but do not allow substrings (like
  15262. * http://notmydomain.com/path/file.ext
  15263. * or http://mydomain.com.fake/path/file.ext).
  15264. */
  15265. if (auth_domain_check_enabled) {
  15266. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15267. server_domain_len = strlen(server_domain);
  15268. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15269. return 0;
  15270. }
  15271. if ((request_domain_len == server_domain_len)
  15272. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15273. /* Request is directed to this server - full name match. */
  15274. } else {
  15275. if (request_domain_len < (server_domain_len + 2)) {
  15276. /* Request is directed to another server: The server name
  15277. * is longer than the request name.
  15278. * Drop this case here to avoid overflows in the
  15279. * following checks. */
  15280. return 0;
  15281. }
  15282. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15283. /* Request is directed to another server: It could be a
  15284. * substring
  15285. * like notmyserver.com */
  15286. return 0;
  15287. }
  15288. if (0
  15289. != memcmp(server_domain,
  15290. hostbegin + request_domain_len - server_domain_len,
  15291. server_domain_len)) {
  15292. /* Request is directed to another server:
  15293. * The server name is different. */
  15294. return 0;
  15295. }
  15296. }
  15297. }
  15298. return hostend;
  15299. }
  15300. static int
  15301. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15302. {
  15303. if (ebuf_len > 0) {
  15304. ebuf[0] = '\0';
  15305. }
  15306. *err = 0;
  15307. reset_per_request_attributes(conn);
  15308. if (!conn) {
  15309. mg_snprintf(conn,
  15310. NULL, /* No truncation check for ebuf */
  15311. ebuf,
  15312. ebuf_len,
  15313. "%s",
  15314. "Internal error");
  15315. *err = 500;
  15316. return 0;
  15317. }
  15318. /* Set the time the request was received. This value should be used for
  15319. * timeouts. */
  15320. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15321. conn->request_len =
  15322. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15323. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15324. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15325. mg_snprintf(conn,
  15326. NULL, /* No truncation check for ebuf */
  15327. ebuf,
  15328. ebuf_len,
  15329. "%s",
  15330. "Invalid message size");
  15331. *err = 500;
  15332. return 0;
  15333. }
  15334. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15335. mg_snprintf(conn,
  15336. NULL, /* No truncation check for ebuf */
  15337. ebuf,
  15338. ebuf_len,
  15339. "%s",
  15340. "Message too large");
  15341. *err = 413;
  15342. return 0;
  15343. }
  15344. if (conn->request_len <= 0) {
  15345. if (conn->data_len > 0) {
  15346. mg_snprintf(conn,
  15347. NULL, /* No truncation check for ebuf */
  15348. ebuf,
  15349. ebuf_len,
  15350. "%s",
  15351. "Malformed message");
  15352. *err = 400;
  15353. } else {
  15354. /* Server did not recv anything -> just close the connection */
  15355. conn->must_close = 1;
  15356. mg_snprintf(conn,
  15357. NULL, /* No truncation check for ebuf */
  15358. ebuf,
  15359. ebuf_len,
  15360. "%s",
  15361. "No data received");
  15362. *err = 0;
  15363. }
  15364. return 0;
  15365. }
  15366. return 1;
  15367. }
  15368. static int
  15369. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15370. {
  15371. const char *cl;
  15372. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15373. return 0;
  15374. }
  15375. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15376. <= 0) {
  15377. mg_snprintf(conn,
  15378. NULL, /* No truncation check for ebuf */
  15379. ebuf,
  15380. ebuf_len,
  15381. "%s",
  15382. "Bad request");
  15383. *err = 400;
  15384. return 0;
  15385. }
  15386. /* Message is a valid request */
  15387. if (!switch_domain_context(conn)) {
  15388. mg_snprintf(conn,
  15389. NULL, /* No truncation check for ebuf */
  15390. ebuf,
  15391. ebuf_len,
  15392. "%s",
  15393. "Bad request: Host mismatch");
  15394. *err = 400;
  15395. return 0;
  15396. }
  15397. if (((cl = get_header(conn->request_info.http_headers,
  15398. conn->request_info.num_headers,
  15399. "Transfer-Encoding"))
  15400. != NULL)
  15401. && mg_strcasecmp(cl, "identity")) {
  15402. if (mg_strcasecmp(cl, "chunked")) {
  15403. mg_snprintf(conn,
  15404. NULL, /* No truncation check for ebuf */
  15405. ebuf,
  15406. ebuf_len,
  15407. "%s",
  15408. "Bad request");
  15409. *err = 400;
  15410. return 0;
  15411. }
  15412. conn->is_chunked = 1;
  15413. conn->content_len = 0; /* not yet read */
  15414. } else if ((cl = get_header(conn->request_info.http_headers,
  15415. conn->request_info.num_headers,
  15416. "Content-Length"))
  15417. != NULL) {
  15418. /* Request has content length set */
  15419. char *endptr = NULL;
  15420. conn->content_len = strtoll(cl, &endptr, 10);
  15421. if ((endptr == cl) || (conn->content_len < 0)) {
  15422. mg_snprintf(conn,
  15423. NULL, /* No truncation check for ebuf */
  15424. ebuf,
  15425. ebuf_len,
  15426. "%s",
  15427. "Bad request");
  15428. *err = 411;
  15429. return 0;
  15430. }
  15431. /* Publish the content length back to the request info. */
  15432. conn->request_info.content_length = conn->content_len;
  15433. } else {
  15434. /* There is no exception, see RFC7230. */
  15435. conn->content_len = 0;
  15436. }
  15437. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15438. return 1;
  15439. }
  15440. /* conn is assumed to be valid in this internal function */
  15441. static int
  15442. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15443. {
  15444. const char *cl;
  15445. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15446. return 0;
  15447. }
  15448. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15449. <= 0) {
  15450. mg_snprintf(conn,
  15451. NULL, /* No truncation check for ebuf */
  15452. ebuf,
  15453. ebuf_len,
  15454. "%s",
  15455. "Bad response");
  15456. *err = 400;
  15457. return 0;
  15458. }
  15459. /* Message is a valid response */
  15460. if (((cl = get_header(conn->response_info.http_headers,
  15461. conn->response_info.num_headers,
  15462. "Transfer-Encoding"))
  15463. != NULL)
  15464. && mg_strcasecmp(cl, "identity")) {
  15465. if (mg_strcasecmp(cl, "chunked")) {
  15466. mg_snprintf(conn,
  15467. NULL, /* No truncation check for ebuf */
  15468. ebuf,
  15469. ebuf_len,
  15470. "%s",
  15471. "Bad request");
  15472. *err = 400;
  15473. return 0;
  15474. }
  15475. conn->is_chunked = 1;
  15476. conn->content_len = 0; /* not yet read */
  15477. } else if ((cl = get_header(conn->response_info.http_headers,
  15478. conn->response_info.num_headers,
  15479. "Content-Length"))
  15480. != NULL) {
  15481. char *endptr = NULL;
  15482. conn->content_len = strtoll(cl, &endptr, 10);
  15483. if ((endptr == cl) || (conn->content_len < 0)) {
  15484. mg_snprintf(conn,
  15485. NULL, /* No truncation check for ebuf */
  15486. ebuf,
  15487. ebuf_len,
  15488. "%s",
  15489. "Bad request");
  15490. *err = 411;
  15491. return 0;
  15492. }
  15493. /* Publish the content length back to the response info. */
  15494. conn->response_info.content_length = conn->content_len;
  15495. /* TODO: check if it is still used in response_info */
  15496. conn->request_info.content_length = conn->content_len;
  15497. /* TODO: we should also consider HEAD method */
  15498. if (conn->response_info.status_code == 304) {
  15499. conn->content_len = 0;
  15500. }
  15501. } else {
  15502. /* TODO: we should also consider HEAD method */
  15503. if (((conn->response_info.status_code >= 100)
  15504. && (conn->response_info.status_code <= 199))
  15505. || (conn->response_info.status_code == 204)
  15506. || (conn->response_info.status_code == 304)) {
  15507. conn->content_len = 0;
  15508. } else {
  15509. conn->content_len = -1; /* unknown content length */
  15510. }
  15511. }
  15512. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15513. return 1;
  15514. }
  15515. int
  15516. mg_get_response(struct mg_connection *conn,
  15517. char *ebuf,
  15518. size_t ebuf_len,
  15519. int timeout)
  15520. {
  15521. int err, ret;
  15522. char txt[32]; /* will not overflow */
  15523. char *save_timeout;
  15524. char *new_timeout;
  15525. if (ebuf_len > 0) {
  15526. ebuf[0] = '\0';
  15527. }
  15528. if (!conn) {
  15529. mg_snprintf(conn,
  15530. NULL, /* No truncation check for ebuf */
  15531. ebuf,
  15532. ebuf_len,
  15533. "%s",
  15534. "Parameter error");
  15535. return -1;
  15536. }
  15537. /* Reset the previous responses */
  15538. conn->data_len = 0;
  15539. /* Implementation of API function for HTTP clients */
  15540. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15541. if (timeout >= 0) {
  15542. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15543. new_timeout = txt;
  15544. } else {
  15545. new_timeout = NULL;
  15546. }
  15547. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15548. ret = get_response(conn, ebuf, ebuf_len, &err);
  15549. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15550. #if defined(MG_LEGACY_INTERFACE)
  15551. /* TODO: 1) uri is deprecated;
  15552. * 2) here, ri.uri is the http response code */
  15553. conn->request_info.uri = conn->request_info.request_uri;
  15554. #endif
  15555. conn->request_info.local_uri = conn->request_info.request_uri;
  15556. /* TODO (mid): Define proper return values - maybe return length?
  15557. * For the first test use <0 for error and >0 for OK */
  15558. return (ret == 0) ? -1 : +1;
  15559. }
  15560. struct mg_connection *
  15561. mg_download(const char *host,
  15562. int port,
  15563. int use_ssl,
  15564. char *ebuf,
  15565. size_t ebuf_len,
  15566. const char *fmt,
  15567. ...)
  15568. {
  15569. struct mg_connection *conn;
  15570. va_list ap;
  15571. int i;
  15572. int reqerr;
  15573. if (ebuf_len > 0) {
  15574. ebuf[0] = '\0';
  15575. }
  15576. va_start(ap, fmt);
  15577. /* open a connection */
  15578. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15579. if (conn != NULL) {
  15580. i = mg_vprintf(conn, fmt, ap);
  15581. if (i <= 0) {
  15582. mg_snprintf(conn,
  15583. NULL, /* No truncation check for ebuf */
  15584. ebuf,
  15585. ebuf_len,
  15586. "%s",
  15587. "Error sending request");
  15588. } else {
  15589. /* make sure the buffer is clear */
  15590. conn->data_len = 0;
  15591. get_response(conn, ebuf, ebuf_len, &reqerr);
  15592. #if defined(MG_LEGACY_INTERFACE)
  15593. /* TODO: 1) uri is deprecated;
  15594. * 2) here, ri.uri is the http response code */
  15595. conn->request_info.uri = conn->request_info.request_uri;
  15596. #endif
  15597. conn->request_info.local_uri = conn->request_info.request_uri;
  15598. }
  15599. }
  15600. /* if an error occurred, close the connection */
  15601. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15602. mg_close_connection(conn);
  15603. conn = NULL;
  15604. }
  15605. va_end(ap);
  15606. return conn;
  15607. }
  15608. struct websocket_client_thread_data {
  15609. struct mg_connection *conn;
  15610. mg_websocket_data_handler data_handler;
  15611. mg_websocket_close_handler close_handler;
  15612. void *callback_data;
  15613. };
  15614. #if defined(USE_WEBSOCKET)
  15615. #if defined(_WIN32)
  15616. static unsigned __stdcall websocket_client_thread(void *data)
  15617. #else
  15618. static void *
  15619. websocket_client_thread(void *data)
  15620. #endif
  15621. {
  15622. struct websocket_client_thread_data *cdata =
  15623. (struct websocket_client_thread_data *)data;
  15624. void *user_thread_ptr = NULL;
  15625. #if !defined(_WIN32)
  15626. struct sigaction sa;
  15627. /* Ignore SIGPIPE */
  15628. memset(&sa, 0, sizeof(sa));
  15629. sa.sa_handler = SIG_IGN;
  15630. sigaction(SIGPIPE, &sa, NULL);
  15631. #endif
  15632. mg_set_thread_name("ws-clnt");
  15633. if (cdata->conn->phys_ctx) {
  15634. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15635. /* 3 indicates a websocket client thread */
  15636. /* TODO: check if conn->phys_ctx can be set */
  15637. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15638. cdata->conn->phys_ctx, 3);
  15639. }
  15640. }
  15641. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15642. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15643. if (cdata->close_handler != NULL) {
  15644. cdata->close_handler(cdata->conn, cdata->callback_data);
  15645. }
  15646. /* The websocket_client context has only this thread. If it runs out,
  15647. set the stop_flag to 2 (= "stopped"). */
  15648. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15649. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15650. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15651. 3,
  15652. user_thread_ptr);
  15653. }
  15654. mg_free((void *)cdata);
  15655. #if defined(_WIN32)
  15656. return 0;
  15657. #else
  15658. return NULL;
  15659. #endif
  15660. }
  15661. #endif
  15662. static struct mg_connection *
  15663. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15664. int use_ssl,
  15665. char *error_buffer,
  15666. size_t error_buffer_size,
  15667. const char *path,
  15668. const char *origin,
  15669. mg_websocket_data_handler data_func,
  15670. mg_websocket_close_handler close_func,
  15671. void *user_data)
  15672. {
  15673. struct mg_connection *conn = NULL;
  15674. #if defined(USE_WEBSOCKET)
  15675. struct websocket_client_thread_data *thread_data;
  15676. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15677. const char *handshake_req;
  15678. int port = client_options->port;
  15679. const char *host = client_options->host;
  15680. int i;
  15681. if (origin != NULL) {
  15682. handshake_req = "GET %s HTTP/1.1\r\n"
  15683. "Host: %s\r\n"
  15684. "Upgrade: websocket\r\n"
  15685. "Connection: Upgrade\r\n"
  15686. "Sec-WebSocket-Key: %s\r\n"
  15687. "Sec-WebSocket-Version: 13\r\n"
  15688. "Origin: %s\r\n"
  15689. "\r\n";
  15690. } else {
  15691. handshake_req = "GET %s HTTP/1.1\r\n"
  15692. "Host: %s\r\n"
  15693. "Upgrade: websocket\r\n"
  15694. "Connection: Upgrade\r\n"
  15695. "Sec-WebSocket-Key: %s\r\n"
  15696. "Sec-WebSocket-Version: 13\r\n"
  15697. "\r\n";
  15698. }
  15699. #if defined(__clang__)
  15700. #pragma clang diagnostic push
  15701. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15702. #endif
  15703. /* Establish the client connection and request upgrade */
  15704. conn =
  15705. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15706. if (conn == NULL) {
  15707. /* error_buffer already filled */
  15708. return NULL;
  15709. }
  15710. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15711. if (i <= 0) {
  15712. mg_snprintf(conn,
  15713. NULL, /* No truncation check for ebuf */
  15714. error_buffer,
  15715. error_buffer_size,
  15716. "%s",
  15717. "Error sending request");
  15718. mg_close_connection(conn);
  15719. return NULL;
  15720. }
  15721. conn->data_len = 0;
  15722. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15723. mg_close_connection(conn);
  15724. return NULL;
  15725. }
  15726. conn->request_info.local_uri = conn->request_info.request_uri;
  15727. #if defined(__clang__)
  15728. #pragma clang diagnostic pop
  15729. #endif
  15730. /* Connection object will be null if something goes wrong */
  15731. if (conn == NULL) {
  15732. if (!*error_buffer) {
  15733. /* There should be already an error message */
  15734. mg_snprintf(conn,
  15735. NULL, /* No truncation check for ebuf */
  15736. error_buffer,
  15737. error_buffer_size,
  15738. "Unexpected error");
  15739. }
  15740. return NULL;
  15741. }
  15742. if (conn->response_info.status_code != 101) {
  15743. /* We sent an "upgrade" request. For a correct websocket
  15744. * protocol handshake, we expect a "101 Continue" response.
  15745. * Otherwise it is a protocol violation. Maybe the HTTP
  15746. * Server does not know websockets. */
  15747. if (!*error_buffer) {
  15748. /* set an error, if not yet set */
  15749. mg_snprintf(conn,
  15750. NULL, /* No truncation check for ebuf */
  15751. error_buffer,
  15752. error_buffer_size,
  15753. "Unexpected server reply");
  15754. }
  15755. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15756. mg_close_connection(conn);
  15757. return NULL;
  15758. }
  15759. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15760. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15761. if (!thread_data) {
  15762. DEBUG_TRACE("%s\r\n", "Out of memory");
  15763. mg_close_connection(conn);
  15764. return NULL;
  15765. }
  15766. thread_data->conn = conn;
  15767. thread_data->data_handler = data_func;
  15768. thread_data->close_handler = close_func;
  15769. thread_data->callback_data = user_data;
  15770. conn->phys_ctx->worker_threadids =
  15771. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15772. if (!conn->phys_ctx->worker_threadids) {
  15773. DEBUG_TRACE("%s\r\n", "Out of memory");
  15774. mg_free(thread_data);
  15775. mg_close_connection(conn);
  15776. return NULL;
  15777. }
  15778. /* Now upgrade to ws/wss client context */
  15779. conn->phys_ctx->user_data = user_data;
  15780. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15781. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15782. /* Start a thread to read the websocket client connection
  15783. * This thread will automatically stop when mg_disconnect is
  15784. * called on the client connection */
  15785. if (mg_start_thread_with_id(websocket_client_thread,
  15786. thread_data,
  15787. conn->phys_ctx->worker_threadids)
  15788. != 0) {
  15789. conn->phys_ctx->cfg_worker_threads = 0;
  15790. mg_free(thread_data);
  15791. mg_close_connection(conn);
  15792. conn = NULL;
  15793. DEBUG_TRACE("%s",
  15794. "Websocket client connect thread could not be started\r\n");
  15795. }
  15796. #else
  15797. /* Appease "unused parameter" warnings */
  15798. (void)client_options;
  15799. (void)use_ssl;
  15800. (void)error_buffer;
  15801. (void)error_buffer_size;
  15802. (void)path;
  15803. (void)origin;
  15804. (void)user_data;
  15805. (void)data_func;
  15806. (void)close_func;
  15807. #endif
  15808. return conn;
  15809. }
  15810. struct mg_connection *
  15811. mg_connect_websocket_client(const char *host,
  15812. int port,
  15813. int use_ssl,
  15814. char *error_buffer,
  15815. size_t error_buffer_size,
  15816. const char *path,
  15817. const char *origin,
  15818. mg_websocket_data_handler data_func,
  15819. mg_websocket_close_handler close_func,
  15820. void *user_data)
  15821. {
  15822. struct mg_client_options client_options;
  15823. memset(&client_options, 0, sizeof(client_options));
  15824. client_options.host = host;
  15825. client_options.port = port;
  15826. return mg_connect_websocket_client_impl(&client_options,
  15827. use_ssl,
  15828. error_buffer,
  15829. error_buffer_size,
  15830. path,
  15831. origin,
  15832. data_func,
  15833. close_func,
  15834. user_data);
  15835. }
  15836. struct mg_connection *
  15837. mg_connect_websocket_client_secure(
  15838. const struct mg_client_options *client_options,
  15839. char *error_buffer,
  15840. size_t error_buffer_size,
  15841. const char *path,
  15842. const char *origin,
  15843. mg_websocket_data_handler data_func,
  15844. mg_websocket_close_handler close_func,
  15845. void *user_data)
  15846. {
  15847. if (!client_options) {
  15848. return NULL;
  15849. }
  15850. return mg_connect_websocket_client_impl(client_options,
  15851. 1,
  15852. error_buffer,
  15853. error_buffer_size,
  15854. path,
  15855. origin,
  15856. data_func,
  15857. close_func,
  15858. user_data);
  15859. }
  15860. /* Prepare connection data structure */
  15861. static void
  15862. init_connection(struct mg_connection *conn)
  15863. {
  15864. /* Is keep alive allowed by the server */
  15865. int keep_alive_enabled =
  15866. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15867. if (!keep_alive_enabled) {
  15868. conn->must_close = 1;
  15869. }
  15870. /* Important: on new connection, reset the receiving buffer. Credit
  15871. * goes to crule42. */
  15872. conn->data_len = 0;
  15873. conn->handled_requests = 0;
  15874. mg_set_user_connection_data(conn, NULL);
  15875. #if defined(USE_SERVER_STATS)
  15876. conn->conn_state = 2; /* init */
  15877. #endif
  15878. /* call the init_connection callback if assigned */
  15879. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15880. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15881. void *conn_data = NULL;
  15882. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15883. mg_set_user_connection_data(conn, conn_data);
  15884. }
  15885. }
  15886. }
  15887. /* Process a connection - may handle multiple requests
  15888. * using the same connection.
  15889. * Must be called with a valid connection (conn and
  15890. * conn->phys_ctx must be valid).
  15891. */
  15892. static void
  15893. process_new_connection(struct mg_connection *conn)
  15894. {
  15895. struct mg_request_info *ri = &conn->request_info;
  15896. int keep_alive, discard_len;
  15897. char ebuf[100];
  15898. const char *hostend;
  15899. int reqerr, uri_type;
  15900. #if defined(USE_SERVER_STATS)
  15901. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15902. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15903. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15904. /* could use atomic compare exchange, but this
  15905. * seems overkill for statistics data */
  15906. conn->phys_ctx->max_active_connections = mcon;
  15907. }
  15908. #endif
  15909. init_connection(conn);
  15910. DEBUG_TRACE("Start processing connection from %s",
  15911. conn->request_info.remote_addr);
  15912. /* Loop over multiple requests sent using the same connection
  15913. * (while "keep alive"). */
  15914. do {
  15915. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15916. conn->handled_requests + 1);
  15917. #if defined(USE_SERVER_STATS)
  15918. conn->conn_state = 3; /* ready */
  15919. #endif
  15920. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15921. /* The request sent by the client could not be understood by
  15922. * the server, or it was incomplete or a timeout. Send an
  15923. * error message and close the connection. */
  15924. if (reqerr > 0) {
  15925. DEBUG_ASSERT(ebuf[0] != '\0');
  15926. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15927. }
  15928. } else if (strcmp(ri->http_version, "1.0")
  15929. && strcmp(ri->http_version, "1.1")) {
  15930. /* HTTP/2 is not allowed here */
  15931. mg_snprintf(conn,
  15932. NULL, /* No truncation check for ebuf */
  15933. ebuf,
  15934. sizeof(ebuf),
  15935. "Bad HTTP version: [%s]",
  15936. ri->http_version);
  15937. mg_send_http_error(conn, 505, "%s", ebuf);
  15938. }
  15939. if (ebuf[0] == '\0') {
  15940. uri_type = get_uri_type(conn->request_info.request_uri);
  15941. switch (uri_type) {
  15942. case 1:
  15943. /* Asterisk */
  15944. conn->request_info.local_uri = 0;
  15945. /* TODO: Deal with '*'. */
  15946. break;
  15947. case 2:
  15948. /* relative uri */
  15949. conn->request_info.local_uri = conn->request_info.request_uri;
  15950. break;
  15951. case 3:
  15952. case 4:
  15953. /* absolute uri (with/without port) */
  15954. hostend = get_rel_url_at_current_server(
  15955. conn->request_info.request_uri, conn);
  15956. if (hostend) {
  15957. conn->request_info.local_uri = hostend;
  15958. } else {
  15959. conn->request_info.local_uri = NULL;
  15960. }
  15961. break;
  15962. default:
  15963. mg_snprintf(conn,
  15964. NULL, /* No truncation check for ebuf */
  15965. ebuf,
  15966. sizeof(ebuf),
  15967. "Invalid URI");
  15968. mg_send_http_error(conn, 400, "%s", ebuf);
  15969. conn->request_info.local_uri = NULL;
  15970. break;
  15971. }
  15972. #if defined(MG_LEGACY_INTERFACE)
  15973. /* Legacy before split into local_uri and request_uri */
  15974. conn->request_info.uri = conn->request_info.local_uri;
  15975. #endif
  15976. }
  15977. if (ebuf[0] != '\0') {
  15978. conn->protocol_type = -1;
  15979. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  15980. /* HTTP/1 allows protocol upgrade */
  15981. conn->protocol_type = should_switch_to_protocol(conn);
  15982. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15983. /* This will occur, if a HTTP/1.1 request should be upgraded
  15984. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15985. * Since most (all?) major browsers only support HTTP/2 using
  15986. * ALPN, this is hard to test and very low priority.
  15987. * Deactivate it (at least for now).
  15988. */
  15989. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15990. }
  15991. }
  15992. DEBUG_TRACE("http: %s, error: %s",
  15993. (ri->http_version ? ri->http_version : "none"),
  15994. (ebuf[0] ? ebuf : "none"));
  15995. if (ebuf[0] == '\0') {
  15996. if (conn->request_info.local_uri) {
  15997. /* handle request to local server */
  15998. #if defined(USE_SERVER_STATS)
  15999. conn->conn_state = 4; /* processing */
  16000. #endif
  16001. handle_request(conn);
  16002. #if defined(USE_SERVER_STATS)
  16003. conn->conn_state = 5; /* processed */
  16004. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  16005. conn->consumed_content);
  16006. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  16007. conn->num_bytes_sent);
  16008. #endif
  16009. DEBUG_TRACE("%s", "handle_request done");
  16010. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16011. conn->phys_ctx->callbacks.end_request(conn,
  16012. conn->status_code);
  16013. DEBUG_TRACE("%s", "end_request callback done");
  16014. }
  16015. log_access(conn);
  16016. } else {
  16017. /* TODO: handle non-local request (PROXY) */
  16018. conn->must_close = 1;
  16019. }
  16020. } else {
  16021. conn->must_close = 1;
  16022. }
  16023. if (ri->remote_user != NULL) {
  16024. mg_free((void *)ri->remote_user);
  16025. /* Important! When having connections with and without auth
  16026. * would cause double free and then crash */
  16027. ri->remote_user = NULL;
  16028. }
  16029. /* NOTE(lsm): order is important here. should_keep_alive() call
  16030. * is using parsed request, which will be invalid after
  16031. * memmove's below.
  16032. * Therefore, memorize should_keep_alive() result now for later
  16033. * use in loop exit condition. */
  16034. /* Enable it only if this request is completely discardable. */
  16035. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16036. && should_keep_alive(conn) && (conn->content_len >= 0)
  16037. && (conn->request_len > 0)
  16038. && ((conn->is_chunked == 4)
  16039. || (!conn->is_chunked
  16040. && ((conn->consumed_content == conn->content_len)
  16041. || ((conn->request_len + conn->content_len)
  16042. <= conn->data_len))))
  16043. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16044. if (keep_alive) {
  16045. /* Discard all buffered data for this request */
  16046. discard_len =
  16047. ((conn->request_len + conn->content_len) < conn->data_len)
  16048. ? (int)(conn->request_len + conn->content_len)
  16049. : conn->data_len;
  16050. conn->data_len -= discard_len;
  16051. if (conn->data_len > 0) {
  16052. DEBUG_TRACE("discard_len = %d", discard_len);
  16053. memmove(conn->buf,
  16054. conn->buf + discard_len,
  16055. (size_t)conn->data_len);
  16056. }
  16057. }
  16058. DEBUG_ASSERT(conn->data_len >= 0);
  16059. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16060. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16061. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16062. (long int)conn->data_len,
  16063. (long int)conn->buf_size);
  16064. break;
  16065. }
  16066. conn->handled_requests++;
  16067. } while (keep_alive);
  16068. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16069. conn->request_info.remote_addr,
  16070. difftime(time(NULL), conn->conn_birth_time));
  16071. close_connection(conn);
  16072. #if defined(USE_SERVER_STATS)
  16073. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16074. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16075. #endif
  16076. }
  16077. #if defined(ALTERNATIVE_QUEUE)
  16078. static void
  16079. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16080. {
  16081. unsigned int i;
  16082. while (!ctx->stop_flag) {
  16083. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16084. /* find a free worker slot and signal it */
  16085. if (ctx->client_socks[i].in_use == 2) {
  16086. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16087. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16088. ctx->client_socks[i] = *sp;
  16089. ctx->client_socks[i].in_use = 1;
  16090. /* socket has been moved to the consumer */
  16091. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16092. (void)event_signal(ctx->client_wait_events[i]);
  16093. return;
  16094. }
  16095. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16096. }
  16097. }
  16098. /* queue is full */
  16099. mg_sleep(1);
  16100. }
  16101. /* must consume */
  16102. set_blocking_mode(sp->sock);
  16103. closesocket(sp->sock);
  16104. }
  16105. static int
  16106. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16107. {
  16108. DEBUG_TRACE("%s", "going idle");
  16109. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16110. ctx->client_socks[thread_index].in_use = 2;
  16111. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16112. event_wait(ctx->client_wait_events[thread_index]);
  16113. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16114. *sp = ctx->client_socks[thread_index];
  16115. if (ctx->stop_flag) {
  16116. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16117. if (sp->in_use == 1) {
  16118. /* must consume */
  16119. set_blocking_mode(sp->sock);
  16120. closesocket(sp->sock);
  16121. }
  16122. return 0;
  16123. }
  16124. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16125. if (sp->in_use == 1) {
  16126. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16127. return 1;
  16128. }
  16129. /* must not reach here */
  16130. DEBUG_ASSERT(0);
  16131. return 0;
  16132. }
  16133. #else /* ALTERNATIVE_QUEUE */
  16134. /* Worker threads take accepted socket from the queue */
  16135. static int
  16136. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16137. {
  16138. (void)thread_index;
  16139. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16140. DEBUG_TRACE("%s", "going idle");
  16141. /* If the queue is empty, wait. We're idle at this point. */
  16142. while ((ctx->sq_head == ctx->sq_tail)
  16143. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16144. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16145. }
  16146. /* If we're stopping, sq_head may be equal to sq_tail. */
  16147. if (ctx->sq_head > ctx->sq_tail) {
  16148. /* Copy socket from the queue and increment tail */
  16149. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16150. ctx->sq_tail++;
  16151. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16152. /* Wrap pointers if needed */
  16153. while (ctx->sq_tail > ctx->sq_size) {
  16154. ctx->sq_tail -= ctx->sq_size;
  16155. ctx->sq_head -= ctx->sq_size;
  16156. }
  16157. }
  16158. (void)pthread_cond_signal(&ctx->sq_empty);
  16159. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16160. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16161. }
  16162. /* Master thread adds accepted socket to a queue */
  16163. static void
  16164. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16165. {
  16166. int queue_filled;
  16167. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16168. queue_filled = ctx->sq_head - ctx->sq_tail;
  16169. /* If the queue is full, wait */
  16170. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16171. && (queue_filled >= ctx->sq_size)) {
  16172. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16173. #if defined(USE_SERVER_STATS)
  16174. if (queue_filled > ctx->sq_max_fill) {
  16175. ctx->sq_max_fill = queue_filled;
  16176. }
  16177. #endif
  16178. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16179. ctx->sq_blocked = 0; /* Not blocked now */
  16180. queue_filled = ctx->sq_head - ctx->sq_tail;
  16181. }
  16182. if (queue_filled < ctx->sq_size) {
  16183. /* Copy socket to the queue and increment head */
  16184. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16185. ctx->sq_head++;
  16186. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16187. }
  16188. queue_filled = ctx->sq_head - ctx->sq_tail;
  16189. #if defined(USE_SERVER_STATS)
  16190. if (queue_filled > ctx->sq_max_fill) {
  16191. ctx->sq_max_fill = queue_filled;
  16192. }
  16193. #endif
  16194. (void)pthread_cond_signal(&ctx->sq_full);
  16195. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16196. }
  16197. #endif /* ALTERNATIVE_QUEUE */
  16198. static void
  16199. worker_thread_run(struct mg_connection *conn)
  16200. {
  16201. struct mg_context *ctx = conn->phys_ctx;
  16202. int thread_index;
  16203. struct mg_workerTLS tls;
  16204. #if defined(MG_LEGACY_INTERFACE)
  16205. uint32_t addr;
  16206. #endif
  16207. mg_set_thread_name("worker");
  16208. tls.is_master = 0;
  16209. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16210. #if defined(_WIN32)
  16211. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16212. #endif
  16213. /* Initialize thread local storage before calling any callback */
  16214. pthread_setspecific(sTlsKey, &tls);
  16215. /* Check if there is a user callback */
  16216. if (ctx->callbacks.init_thread) {
  16217. /* call init_thread for a worker thread (type 1), and store the
  16218. * return value */
  16219. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16220. } else {
  16221. /* No callback: set user pointer to NULL */
  16222. tls.user_ptr = NULL;
  16223. }
  16224. /* Connection structure has been pre-allocated */
  16225. thread_index = (int)(conn - ctx->worker_connections);
  16226. if ((thread_index < 0)
  16227. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16228. mg_cry_ctx_internal(ctx,
  16229. "Internal error: Invalid worker index %i",
  16230. thread_index);
  16231. return;
  16232. }
  16233. /* Request buffers are not pre-allocated. They are private to the
  16234. * request and do not contain any state information that might be
  16235. * of interest to anyone observing a server status. */
  16236. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16237. if (conn->buf == NULL) {
  16238. mg_cry_ctx_internal(
  16239. ctx,
  16240. "Out of memory: Cannot allocate buffer for worker %i",
  16241. thread_index);
  16242. return;
  16243. }
  16244. conn->buf_size = (int)ctx->max_request_size;
  16245. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16246. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16247. conn->request_info.user_data = ctx->user_data;
  16248. /* Allocate a mutex for this connection to allow communication both
  16249. * within the request handler and from elsewhere in the application
  16250. */
  16251. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16252. mg_free(conn->buf);
  16253. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16254. return;
  16255. }
  16256. #if defined(USE_SERVER_STATS)
  16257. conn->conn_state = 1; /* not consumed */
  16258. #endif
  16259. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16260. * signal sq_empty condvar to wake up the master waiting in
  16261. * produce_socket() */
  16262. while (consume_socket(ctx, &conn->client, thread_index)) {
  16263. /* New connections must start with new protocol negotiation */
  16264. tls.alpn_proto = NULL;
  16265. #if defined(USE_SERVER_STATS)
  16266. conn->conn_close_time = 0;
  16267. #endif
  16268. conn->conn_birth_time = time(NULL);
  16269. /* Fill in IP, port info early so even if SSL setup below fails,
  16270. * error handler would have the corresponding info.
  16271. * Thanks to Johannes Winkelmann for the patch.
  16272. */
  16273. conn->request_info.remote_port =
  16274. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16275. sockaddr_to_string(conn->request_info.remote_addr,
  16276. sizeof(conn->request_info.remote_addr),
  16277. &conn->client.rsa);
  16278. DEBUG_TRACE("Start processing connection from %s",
  16279. conn->request_info.remote_addr);
  16280. conn->request_info.is_ssl = conn->client.is_ssl;
  16281. if (conn->client.is_ssl) {
  16282. #if !defined(NO_SSL)
  16283. /* HTTPS connection */
  16284. if (sslize(conn, SSL_accept, NULL)) {
  16285. /* conn->dom_ctx is set in get_request */
  16286. /* Get SSL client certificate information (if set) */
  16287. struct mg_client_cert client_cert;
  16288. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16289. conn->request_info.client_cert = &client_cert;
  16290. }
  16291. /* process HTTPS connection */
  16292. #if defined(USE_HTTP2)
  16293. if ((tls.alpn_proto != NULL)
  16294. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16295. /* process HTTPS/2 connection */
  16296. init_connection(conn);
  16297. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16298. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16299. conn->content_len = -1;
  16300. conn->is_chunked = 0;
  16301. process_new_http2_connection(conn);
  16302. } else
  16303. #endif
  16304. {
  16305. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16306. process_new_connection(conn);
  16307. }
  16308. /* Free client certificate info */
  16309. if (conn->request_info.client_cert) {
  16310. mg_free((void *)(conn->request_info.client_cert->subject));
  16311. mg_free((void *)(conn->request_info.client_cert->issuer));
  16312. mg_free((void *)(conn->request_info.client_cert->serial));
  16313. mg_free((void *)(conn->request_info.client_cert->finger));
  16314. /* Free certificate memory */
  16315. X509_free(
  16316. (X509 *)conn->request_info.client_cert->peer_cert);
  16317. conn->request_info.client_cert->peer_cert = 0;
  16318. conn->request_info.client_cert->subject = 0;
  16319. conn->request_info.client_cert->issuer = 0;
  16320. conn->request_info.client_cert->serial = 0;
  16321. conn->request_info.client_cert->finger = 0;
  16322. conn->request_info.client_cert = 0;
  16323. }
  16324. } else {
  16325. /* make sure the connection is cleaned up on SSL failure */
  16326. close_connection(conn);
  16327. }
  16328. #endif
  16329. } else {
  16330. /* process HTTP connection */
  16331. process_new_connection(conn);
  16332. }
  16333. DEBUG_TRACE("%s", "Connection closed");
  16334. #if defined(USE_SERVER_STATS)
  16335. conn->conn_close_time = time(NULL);
  16336. #endif
  16337. }
  16338. /* Call exit thread user callback */
  16339. if (ctx->callbacks.exit_thread) {
  16340. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16341. }
  16342. /* delete thread local storage objects */
  16343. pthread_setspecific(sTlsKey, NULL);
  16344. #if defined(_WIN32)
  16345. CloseHandle(tls.pthread_cond_helper_mutex);
  16346. #endif
  16347. pthread_mutex_destroy(&conn->mutex);
  16348. /* Free the request buffer. */
  16349. conn->buf_size = 0;
  16350. mg_free(conn->buf);
  16351. conn->buf = NULL;
  16352. #if defined(USE_SERVER_STATS)
  16353. conn->conn_state = 9; /* done */
  16354. #endif
  16355. DEBUG_TRACE("%s", "exiting");
  16356. }
  16357. /* Threads have different return types on Windows and Unix. */
  16358. #if defined(_WIN32)
  16359. static unsigned __stdcall worker_thread(void *thread_func_param)
  16360. {
  16361. worker_thread_run((struct mg_connection *)thread_func_param);
  16362. return 0;
  16363. }
  16364. #else
  16365. static void *
  16366. worker_thread(void *thread_func_param)
  16367. {
  16368. #if !defined(__ZEPHYR__)
  16369. struct sigaction sa;
  16370. /* Ignore SIGPIPE */
  16371. memset(&sa, 0, sizeof(sa));
  16372. sa.sa_handler = SIG_IGN;
  16373. sigaction(SIGPIPE, &sa, NULL);
  16374. #endif
  16375. worker_thread_run((struct mg_connection *)thread_func_param);
  16376. return NULL;
  16377. }
  16378. #endif /* _WIN32 */
  16379. /* This is an internal function, thus all arguments are expected to be
  16380. * valid - a NULL check is not required. */
  16381. static void
  16382. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16383. {
  16384. struct socket so;
  16385. char src_addr[IP_ADDR_STR_LEN];
  16386. socklen_t len = sizeof(so.rsa);
  16387. #if !defined(__ZEPHYR__)
  16388. int on = 1;
  16389. #endif
  16390. memset(&so, 0, sizeof(so));
  16391. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16392. == INVALID_SOCKET) {
  16393. } else if (check_acl(ctx, &so.rsa) != 1) {
  16394. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16395. mg_cry_ctx_internal(ctx,
  16396. "%s: %s is not allowed to connect",
  16397. __func__,
  16398. src_addr);
  16399. closesocket(so.sock);
  16400. } else {
  16401. /* Put so socket structure into the queue */
  16402. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16403. set_close_on_exec(so.sock, NULL, ctx);
  16404. so.is_ssl = listener->is_ssl;
  16405. so.ssl_redir = listener->ssl_redir;
  16406. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16407. mg_cry_ctx_internal(ctx,
  16408. "%s: getsockname() failed: %s",
  16409. __func__,
  16410. strerror(ERRNO));
  16411. }
  16412. #if !defined(__ZEPHYR__)
  16413. /* Set TCP keep-alive. This is needed because if HTTP-level
  16414. * keep-alive
  16415. * is enabled, and client resets the connection, server won't get
  16416. * TCP FIN or RST and will keep the connection open forever. With
  16417. * TCP keep-alive, next keep-alive handshake will figure out that
  16418. * the client is down and will close the server end.
  16419. * Thanks to Igor Klopov who suggested the patch. */
  16420. if (setsockopt(so.sock,
  16421. SOL_SOCKET,
  16422. SO_KEEPALIVE,
  16423. (SOCK_OPT_TYPE)&on,
  16424. sizeof(on))
  16425. != 0) {
  16426. mg_cry_ctx_internal(
  16427. ctx,
  16428. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16429. __func__,
  16430. strerror(ERRNO));
  16431. }
  16432. #endif
  16433. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16434. * to effectively fill up the underlying IP packet payload and
  16435. * reduce the overhead of sending lots of small buffers. However
  16436. * this hurts the server's throughput (ie. operations per second)
  16437. * when HTTP 1.1 persistent connections are used and the responses
  16438. * are relatively small (eg. less than 1400 bytes).
  16439. */
  16440. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16441. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16442. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16443. mg_cry_ctx_internal(
  16444. ctx,
  16445. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16446. __func__,
  16447. strerror(ERRNO));
  16448. }
  16449. }
  16450. /* The "non blocking" property should already be
  16451. * inherited from the parent socket. Set it for
  16452. * non-compliant socket implementations. */
  16453. set_non_blocking_mode(so.sock);
  16454. so.in_use = 0;
  16455. produce_socket(ctx, &so);
  16456. }
  16457. }
  16458. static void
  16459. master_thread_run(struct mg_context *ctx)
  16460. {
  16461. struct mg_workerTLS tls;
  16462. struct mg_pollfd *pfd;
  16463. unsigned int i;
  16464. unsigned int workerthreadcount;
  16465. if (!ctx) {
  16466. return;
  16467. }
  16468. mg_set_thread_name("master");
  16469. /* Increase priority of the master thread */
  16470. #if defined(_WIN32)
  16471. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16472. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16473. int min_prio = sched_get_priority_min(SCHED_RR);
  16474. int max_prio = sched_get_priority_max(SCHED_RR);
  16475. if ((min_prio >= 0) && (max_prio >= 0)
  16476. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16477. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16478. struct sched_param sched_param = {0};
  16479. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16480. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16481. }
  16482. #endif
  16483. /* Initialize thread local storage */
  16484. #if defined(_WIN32)
  16485. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16486. #endif
  16487. tls.is_master = 1;
  16488. pthread_setspecific(sTlsKey, &tls);
  16489. if (ctx->callbacks.init_thread) {
  16490. /* Callback for the master thread (type 0) */
  16491. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16492. } else {
  16493. tls.user_ptr = NULL;
  16494. }
  16495. /* Server starts *now* */
  16496. ctx->start_time = time(NULL);
  16497. /* Start the server */
  16498. pfd = ctx->listening_socket_fds;
  16499. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16500. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16501. pfd[i].fd = ctx->listening_sockets[i].sock;
  16502. pfd[i].events = POLLIN;
  16503. }
  16504. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16505. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16506. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16507. * successful poll, and POLLIN is defined as
  16508. * (POLLRDNORM | POLLRDBAND)
  16509. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16510. * pfd[i].revents == POLLIN. */
  16511. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16512. && (pfd[i].revents & POLLIN)) {
  16513. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16514. }
  16515. }
  16516. }
  16517. }
  16518. /* Here stop_flag is 1 - Initiate shutdown. */
  16519. DEBUG_TRACE("%s", "stopping workers");
  16520. /* Stop signal received: somebody called mg_stop. Quit. */
  16521. close_all_listening_sockets(ctx);
  16522. /* Wakeup workers that are waiting for connections to handle. */
  16523. #if defined(ALTERNATIVE_QUEUE)
  16524. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16525. event_signal(ctx->client_wait_events[i]);
  16526. }
  16527. #else
  16528. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16529. pthread_cond_broadcast(&ctx->sq_full);
  16530. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16531. #endif
  16532. /* Join all worker threads to avoid leaking threads. */
  16533. workerthreadcount = ctx->cfg_worker_threads;
  16534. for (i = 0; i < workerthreadcount; i++) {
  16535. if (ctx->worker_threadids[i] != 0) {
  16536. mg_join_thread(ctx->worker_threadids[i]);
  16537. }
  16538. }
  16539. #if defined(USE_LUA)
  16540. /* Free Lua state of lua background task */
  16541. if (ctx->lua_background_state) {
  16542. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16543. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16544. if (lua_istable(lstate, -1)) {
  16545. reg_boolean(lstate, "shutdown", 1);
  16546. lua_pop(lstate, 1);
  16547. mg_sleep(2);
  16548. }
  16549. lua_close(lstate);
  16550. ctx->lua_background_state = 0;
  16551. }
  16552. #endif
  16553. DEBUG_TRACE("%s", "exiting");
  16554. /* call exit thread callback */
  16555. if (ctx->callbacks.exit_thread) {
  16556. /* Callback for the master thread (type 0) */
  16557. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16558. }
  16559. #if defined(_WIN32)
  16560. CloseHandle(tls.pthread_cond_helper_mutex);
  16561. #endif
  16562. pthread_setspecific(sTlsKey, NULL);
  16563. /* Signal mg_stop() that we're done.
  16564. * WARNING: This must be the very last thing this
  16565. * thread does, as ctx becomes invalid after this line. */
  16566. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16567. }
  16568. /* Threads have different return types on Windows and Unix. */
  16569. #if defined(_WIN32)
  16570. static unsigned __stdcall master_thread(void *thread_func_param)
  16571. {
  16572. master_thread_run((struct mg_context *)thread_func_param);
  16573. return 0;
  16574. }
  16575. #else
  16576. static void *
  16577. master_thread(void *thread_func_param)
  16578. {
  16579. #if !defined(__ZEPHYR__)
  16580. struct sigaction sa;
  16581. /* Ignore SIGPIPE */
  16582. memset(&sa, 0, sizeof(sa));
  16583. sa.sa_handler = SIG_IGN;
  16584. sigaction(SIGPIPE, &sa, NULL);
  16585. #endif
  16586. master_thread_run((struct mg_context *)thread_func_param);
  16587. return NULL;
  16588. }
  16589. #endif /* _WIN32 */
  16590. static void
  16591. free_context(struct mg_context *ctx)
  16592. {
  16593. int i;
  16594. struct mg_handler_info *tmp_rh;
  16595. if (ctx == NULL) {
  16596. return;
  16597. }
  16598. if (ctx->callbacks.exit_context) {
  16599. ctx->callbacks.exit_context(ctx);
  16600. }
  16601. /* All threads exited, no sync is needed. Destroy thread mutex and
  16602. * condvars
  16603. */
  16604. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16605. #if defined(ALTERNATIVE_QUEUE)
  16606. mg_free(ctx->client_socks);
  16607. if (ctx->client_wait_events != NULL) {
  16608. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16609. event_destroy(ctx->client_wait_events[i]);
  16610. }
  16611. mg_free(ctx->client_wait_events);
  16612. }
  16613. #else
  16614. (void)pthread_cond_destroy(&ctx->sq_empty);
  16615. (void)pthread_cond_destroy(&ctx->sq_full);
  16616. mg_free(ctx->squeue);
  16617. #endif
  16618. /* Destroy other context global data structures mutex */
  16619. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16620. #if defined(USE_TIMERS)
  16621. timers_exit(ctx);
  16622. #endif
  16623. /* Deallocate config parameters */
  16624. for (i = 0; i < NUM_OPTIONS; i++) {
  16625. if (ctx->dd.config[i] != NULL) {
  16626. #if defined(_MSC_VER)
  16627. #pragma warning(suppress : 6001)
  16628. #endif
  16629. mg_free(ctx->dd.config[i]);
  16630. }
  16631. }
  16632. /* Deallocate request handlers */
  16633. while (ctx->dd.handlers) {
  16634. tmp_rh = ctx->dd.handlers;
  16635. ctx->dd.handlers = tmp_rh->next;
  16636. mg_free(tmp_rh->uri);
  16637. mg_free(tmp_rh);
  16638. }
  16639. #if !defined(NO_SSL)
  16640. /* Deallocate SSL context */
  16641. if (ctx->dd.ssl_ctx != NULL) {
  16642. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16643. int callback_ret =
  16644. (ctx->callbacks.external_ssl_ctx == NULL)
  16645. ? 0
  16646. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16647. if (callback_ret == 0) {
  16648. SSL_CTX_free(ctx->dd.ssl_ctx);
  16649. }
  16650. /* else: ignore error and ommit SSL_CTX_free in case
  16651. * callback_ret is 1 */
  16652. }
  16653. #endif /* !NO_SSL */
  16654. /* Deallocate worker thread ID array */
  16655. mg_free(ctx->worker_threadids);
  16656. /* Deallocate worker thread ID array */
  16657. mg_free(ctx->worker_connections);
  16658. /* deallocate system name string */
  16659. mg_free(ctx->systemName);
  16660. /* Deallocate context itself */
  16661. mg_free(ctx);
  16662. }
  16663. void
  16664. mg_stop(struct mg_context *ctx)
  16665. {
  16666. pthread_t mt;
  16667. if (!ctx) {
  16668. return;
  16669. }
  16670. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16671. * two threads is not allowed. */
  16672. mt = ctx->masterthreadid;
  16673. if (mt == 0) {
  16674. return;
  16675. }
  16676. ctx->masterthreadid = 0;
  16677. /* Set stop flag, so all threads know they have to exit. */
  16678. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16679. /* Wait until everything has stopped. */
  16680. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16681. (void)mg_sleep(10);
  16682. }
  16683. mg_join_thread(mt);
  16684. free_context(ctx);
  16685. }
  16686. static void
  16687. get_system_name(char **sysName)
  16688. {
  16689. #if defined(_WIN32)
  16690. #if defined(_WIN32_WCE)
  16691. *sysName = mg_strdup("WinCE");
  16692. #else
  16693. char name[128];
  16694. DWORD dwVersion = 0;
  16695. DWORD dwMajorVersion = 0;
  16696. DWORD dwMinorVersion = 0;
  16697. DWORD dwBuild = 0;
  16698. BOOL wowRet, isWoW = FALSE;
  16699. #if defined(_MSC_VER)
  16700. #pragma warning(push)
  16701. /* GetVersion was declared deprecated */
  16702. #pragma warning(disable : 4996)
  16703. #endif
  16704. dwVersion = GetVersion();
  16705. #if defined(_MSC_VER)
  16706. #pragma warning(pop)
  16707. #endif
  16708. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16709. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16710. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16711. (void)dwBuild;
  16712. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16713. sprintf(name,
  16714. "Windows %u.%u%s",
  16715. (unsigned)dwMajorVersion,
  16716. (unsigned)dwMinorVersion,
  16717. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16718. *sysName = mg_strdup(name);
  16719. #endif
  16720. #elif defined(__ZEPHYR__)
  16721. *sysName = mg_strdup("Zephyr OS");
  16722. #else
  16723. struct utsname name;
  16724. memset(&name, 0, sizeof(name));
  16725. uname(&name);
  16726. *sysName = mg_strdup(name.sysname);
  16727. #endif
  16728. }
  16729. static void
  16730. legacy_init(const char **options)
  16731. {
  16732. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16733. if (options) {
  16734. const char **run_options = options;
  16735. const char *optname = config_options[LISTENING_PORTS].name;
  16736. /* Try to find the "listening_ports" option */
  16737. while (*run_options) {
  16738. if (!strcmp(*run_options, optname)) {
  16739. ports_option = run_options[1];
  16740. }
  16741. run_options += 2;
  16742. }
  16743. }
  16744. if (is_ssl_port_used(ports_option)) {
  16745. /* Initialize with SSL support */
  16746. mg_init_library(MG_FEATURES_TLS);
  16747. } else {
  16748. /* Initialize without SSL support */
  16749. mg_init_library(MG_FEATURES_DEFAULT);
  16750. }
  16751. }
  16752. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16753. static
  16754. #endif
  16755. struct mg_context *
  16756. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16757. {
  16758. struct mg_context *ctx;
  16759. const char *name, *value, *default_value;
  16760. int idx, ok, workerthreadcount;
  16761. unsigned int i;
  16762. int itmp;
  16763. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16764. const char **options =
  16765. ((init != NULL) ? (init->configuration_options) : (NULL));
  16766. struct mg_workerTLS tls;
  16767. if (error != NULL) {
  16768. error->code = 0;
  16769. if (error->text_buffer_size > 0) {
  16770. *error->text = 0;
  16771. }
  16772. }
  16773. if (mg_init_library_called == 0) {
  16774. /* Legacy INIT, if mg_start is called without mg_init_library.
  16775. * Note: This will cause a memory leak when unloading the library.
  16776. */
  16777. legacy_init(options);
  16778. }
  16779. if (mg_init_library_called == 0) {
  16780. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16781. mg_snprintf(NULL,
  16782. NULL, /* No truncation check for error buffers */
  16783. error->text,
  16784. error->text_buffer_size,
  16785. "%s",
  16786. "Library uninitialized");
  16787. }
  16788. return NULL;
  16789. }
  16790. /* Allocate context and initialize reasonable general case defaults. */
  16791. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16792. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16793. mg_snprintf(NULL,
  16794. NULL, /* No truncation check for error buffers */
  16795. error->text,
  16796. error->text_buffer_size,
  16797. "%s",
  16798. "Out of memory");
  16799. }
  16800. return NULL;
  16801. }
  16802. /* Random number generator will initialize at the first call */
  16803. ctx->dd.auth_nonce_mask =
  16804. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16805. /* Save started thread index to reuse in other external API calls
  16806. * For the sake of thread synchronization all non-civetweb threads
  16807. * can be considered as single external thread */
  16808. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16809. tls.is_master = -1; /* Thread calling mg_start */
  16810. tls.thread_idx = ctx->starter_thread_idx;
  16811. #if defined(_WIN32)
  16812. tls.pthread_cond_helper_mutex = NULL;
  16813. #endif
  16814. pthread_setspecific(sTlsKey, &tls);
  16815. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16816. #if !defined(ALTERNATIVE_QUEUE)
  16817. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16818. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16819. ctx->sq_blocked = 0;
  16820. #endif
  16821. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16822. if (!ok) {
  16823. const char *err_msg =
  16824. "Cannot initialize thread synchronization objects";
  16825. /* Fatal error - abort start. However, this situation should never
  16826. * occur in practice. */
  16827. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16828. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16829. mg_snprintf(NULL,
  16830. NULL, /* No truncation check for error buffers */
  16831. error->text,
  16832. error->text_buffer_size,
  16833. "%s",
  16834. err_msg);
  16835. }
  16836. mg_free(ctx);
  16837. pthread_setspecific(sTlsKey, NULL);
  16838. return NULL;
  16839. }
  16840. if ((init != NULL) && (init->callbacks != NULL)) {
  16841. /* Set all callbacks except exit_context. */
  16842. ctx->callbacks = *init->callbacks;
  16843. exit_callback = init->callbacks->exit_context;
  16844. /* The exit callback is activated once the context is successfully
  16845. * created. It should not be called, if an incomplete context object
  16846. * is deleted during a failed initialization. */
  16847. ctx->callbacks.exit_context = 0;
  16848. }
  16849. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16850. ctx->dd.handlers = NULL;
  16851. ctx->dd.next = NULL;
  16852. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16853. ctx->dd.shared_lua_websockets = NULL;
  16854. #endif
  16855. /* Store options */
  16856. while (options && (name = *options++) != NULL) {
  16857. if ((idx = get_option_index(name)) == -1) {
  16858. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16859. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16860. mg_snprintf(NULL,
  16861. NULL, /* No truncation check for error buffers */
  16862. error->text,
  16863. error->text_buffer_size,
  16864. "Invalid configuration option: %s",
  16865. name);
  16866. }
  16867. free_context(ctx);
  16868. pthread_setspecific(sTlsKey, NULL);
  16869. return NULL;
  16870. } else if ((value = *options++) == NULL) {
  16871. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16872. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16873. mg_snprintf(NULL,
  16874. NULL, /* No truncation check for error buffers */
  16875. error->text,
  16876. error->text_buffer_size,
  16877. "Invalid configuration option value: %s",
  16878. name);
  16879. }
  16880. free_context(ctx);
  16881. pthread_setspecific(sTlsKey, NULL);
  16882. return NULL;
  16883. }
  16884. if (ctx->dd.config[idx] != NULL) {
  16885. /* A duplicate configuration option is not an error - the last
  16886. * option value will be used. */
  16887. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16888. mg_free(ctx->dd.config[idx]);
  16889. }
  16890. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16891. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16892. }
  16893. /* Set default value if needed */
  16894. for (i = 0; config_options[i].name != NULL; i++) {
  16895. default_value = config_options[i].default_value;
  16896. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16897. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16898. }
  16899. }
  16900. /* Request size option */
  16901. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16902. if (itmp < 1024) {
  16903. mg_cry_ctx_internal(ctx,
  16904. "%s too small",
  16905. config_options[MAX_REQUEST_SIZE].name);
  16906. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16907. mg_snprintf(NULL,
  16908. NULL, /* No truncation check for error buffers */
  16909. error->text,
  16910. error->text_buffer_size,
  16911. "Invalid configuration option value: %s",
  16912. config_options[MAX_REQUEST_SIZE].name);
  16913. }
  16914. free_context(ctx);
  16915. pthread_setspecific(sTlsKey, NULL);
  16916. return NULL;
  16917. }
  16918. ctx->max_request_size = (unsigned)itmp;
  16919. /* Queue length */
  16920. #if !defined(ALTERNATIVE_QUEUE)
  16921. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16922. if (itmp < 1) {
  16923. mg_cry_ctx_internal(ctx,
  16924. "%s too small",
  16925. config_options[CONNECTION_QUEUE_SIZE].name);
  16926. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16927. mg_snprintf(NULL,
  16928. NULL, /* No truncation check for error buffers */
  16929. error->text,
  16930. error->text_buffer_size,
  16931. "Invalid configuration option value: %s",
  16932. config_options[CONNECTION_QUEUE_SIZE].name);
  16933. }
  16934. free_context(ctx);
  16935. pthread_setspecific(sTlsKey, NULL);
  16936. return NULL;
  16937. }
  16938. ctx->squeue =
  16939. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16940. if (ctx->squeue == NULL) {
  16941. mg_cry_ctx_internal(ctx,
  16942. "Out of memory: Cannot allocate %s",
  16943. config_options[CONNECTION_QUEUE_SIZE].name);
  16944. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16945. mg_snprintf(NULL,
  16946. NULL, /* No truncation check for error buffers */
  16947. error->text,
  16948. error->text_buffer_size,
  16949. "Out of memory: Cannot allocate %s",
  16950. config_options[CONNECTION_QUEUE_SIZE].name);
  16951. }
  16952. free_context(ctx);
  16953. pthread_setspecific(sTlsKey, NULL);
  16954. return NULL;
  16955. }
  16956. ctx->sq_size = itmp;
  16957. #endif
  16958. /* Worker thread count option */
  16959. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16960. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16961. if (workerthreadcount <= 0) {
  16962. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16963. } else {
  16964. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16965. }
  16966. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16967. mg_snprintf(NULL,
  16968. NULL, /* No truncation check for error buffers */
  16969. error->text,
  16970. error->text_buffer_size,
  16971. "Invalid configuration option value: %s",
  16972. config_options[NUM_THREADS].name);
  16973. }
  16974. free_context(ctx);
  16975. pthread_setspecific(sTlsKey, NULL);
  16976. return NULL;
  16977. }
  16978. /* Document root */
  16979. #if defined(NO_FILES)
  16980. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16981. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16982. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16983. mg_snprintf(NULL,
  16984. NULL, /* No truncation check for error buffers */
  16985. error->text,
  16986. error->text_buffer_size,
  16987. "Invalid configuration option value: %s",
  16988. config_options[DOCUMENT_ROOT].name);
  16989. }
  16990. free_context(ctx);
  16991. pthread_setspecific(sTlsKey, NULL);
  16992. return NULL;
  16993. }
  16994. #endif
  16995. get_system_name(&ctx->systemName);
  16996. #if defined(USE_LUA)
  16997. /* If a Lua background script has been configured, start it. */
  16998. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16999. char ebuf[256];
  17000. struct vec opt_vec;
  17001. struct vec eq_vec;
  17002. const char *sparams;
  17003. lua_State *state = mg_prepare_lua_context_script(
  17004. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17005. if (!state) {
  17006. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  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. "Error in script %s: %s",
  17013. config_options[DOCUMENT_ROOT].name,
  17014. ebuf);
  17015. }
  17016. free_context(ctx);
  17017. pthread_setspecific(sTlsKey, NULL);
  17018. return NULL;
  17019. }
  17020. ctx->lua_background_state = (void *)state;
  17021. lua_newtable(state);
  17022. reg_boolean(state, "shutdown", 0);
  17023. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17024. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17025. reg_llstring(
  17026. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17027. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17028. break;
  17029. }
  17030. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17031. } else {
  17032. ctx->lua_background_state = 0;
  17033. }
  17034. #endif
  17035. /* Step by step initialization of ctx - depending on build options */
  17036. #if !defined(NO_FILESYSTEMS)
  17037. if (!set_gpass_option(ctx, NULL)) {
  17038. const char *err_msg = "Invalid global password file";
  17039. /* Fatal error - abort start. */
  17040. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17041. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17042. mg_snprintf(NULL,
  17043. NULL, /* No truncation check for error buffers */
  17044. error->text,
  17045. error->text_buffer_size,
  17046. "%s",
  17047. err_msg);
  17048. }
  17049. free_context(ctx);
  17050. pthread_setspecific(sTlsKey, NULL);
  17051. return NULL;
  17052. }
  17053. #endif
  17054. #if !defined(NO_SSL)
  17055. if (!init_ssl_ctx(ctx, NULL)) {
  17056. const char *err_msg = "Error initializing SSL context";
  17057. /* Fatal error - abort start. */
  17058. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17059. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17060. mg_snprintf(NULL,
  17061. NULL, /* No truncation check for error buffers */
  17062. error->text,
  17063. error->text_buffer_size,
  17064. "%s",
  17065. err_msg);
  17066. }
  17067. free_context(ctx);
  17068. pthread_setspecific(sTlsKey, NULL);
  17069. return NULL;
  17070. }
  17071. #endif
  17072. if (!set_ports_option(ctx)) {
  17073. const char *err_msg = "Failed to setup server ports";
  17074. /* Fatal error - abort start. */
  17075. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17076. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17077. mg_snprintf(NULL,
  17078. NULL, /* No truncation check for error buffers */
  17079. error->text,
  17080. error->text_buffer_size,
  17081. "%s",
  17082. err_msg);
  17083. }
  17084. free_context(ctx);
  17085. pthread_setspecific(sTlsKey, NULL);
  17086. return NULL;
  17087. }
  17088. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17089. if (!set_uid_option(ctx)) {
  17090. const char *err_msg = "Failed to run as configured user";
  17091. /* Fatal error - abort start. */
  17092. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17093. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17094. mg_snprintf(NULL,
  17095. NULL, /* No truncation check for error buffers */
  17096. error->text,
  17097. error->text_buffer_size,
  17098. "%s",
  17099. err_msg);
  17100. }
  17101. free_context(ctx);
  17102. pthread_setspecific(sTlsKey, NULL);
  17103. return NULL;
  17104. }
  17105. #endif
  17106. if (!set_acl_option(ctx)) {
  17107. const char *err_msg = "Failed to setup access control list";
  17108. /* Fatal error - abort start. */
  17109. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17110. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17111. mg_snprintf(NULL,
  17112. NULL, /* No truncation check for error buffers */
  17113. error->text,
  17114. error->text_buffer_size,
  17115. "%s",
  17116. err_msg);
  17117. }
  17118. free_context(ctx);
  17119. pthread_setspecific(sTlsKey, NULL);
  17120. return NULL;
  17121. }
  17122. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17123. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17124. sizeof(pthread_t),
  17125. ctx);
  17126. if (ctx->worker_threadids == NULL) {
  17127. const char *err_msg = "Not enough memory for worker thread ID array";
  17128. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17129. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17130. mg_snprintf(NULL,
  17131. NULL, /* No truncation check for error buffers */
  17132. error->text,
  17133. error->text_buffer_size,
  17134. "%s",
  17135. err_msg);
  17136. }
  17137. free_context(ctx);
  17138. pthread_setspecific(sTlsKey, NULL);
  17139. return NULL;
  17140. }
  17141. ctx->worker_connections =
  17142. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17143. sizeof(struct mg_connection),
  17144. ctx);
  17145. if (ctx->worker_connections == NULL) {
  17146. const char *err_msg =
  17147. "Not enough memory for worker thread connection array";
  17148. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17149. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17150. mg_snprintf(NULL,
  17151. NULL, /* No truncation check for error buffers */
  17152. error->text,
  17153. error->text_buffer_size,
  17154. "%s",
  17155. err_msg);
  17156. }
  17157. free_context(ctx);
  17158. pthread_setspecific(sTlsKey, NULL);
  17159. return NULL;
  17160. }
  17161. #if defined(ALTERNATIVE_QUEUE)
  17162. ctx->client_wait_events =
  17163. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17164. sizeof(ctx->client_wait_events[0]),
  17165. ctx);
  17166. if (ctx->client_wait_events == NULL) {
  17167. const char *err_msg = "Not enough memory for worker event array";
  17168. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17169. mg_free(ctx->worker_threadids);
  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->client_socks =
  17183. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17184. sizeof(ctx->client_socks[0]),
  17185. ctx);
  17186. if (ctx->client_socks == NULL) {
  17187. const char *err_msg = "Not enough memory for worker socket array";
  17188. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17189. mg_free(ctx->client_wait_events);
  17190. mg_free(ctx->worker_threadids);
  17191. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17192. mg_snprintf(NULL,
  17193. NULL, /* No truncation check for error buffers */
  17194. error->text,
  17195. error->text_buffer_size,
  17196. "%s",
  17197. err_msg);
  17198. }
  17199. free_context(ctx);
  17200. pthread_setspecific(sTlsKey, NULL);
  17201. return NULL;
  17202. }
  17203. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17204. ctx->client_wait_events[i] = event_create();
  17205. if (ctx->client_wait_events[i] == 0) {
  17206. const char *err_msg = "Error creating worker event %i";
  17207. mg_cry_ctx_internal(ctx, err_msg, i);
  17208. while (i > 0) {
  17209. i--;
  17210. event_destroy(ctx->client_wait_events[i]);
  17211. }
  17212. mg_free(ctx->client_socks);
  17213. mg_free(ctx->client_wait_events);
  17214. mg_free(ctx->worker_threadids);
  17215. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17216. mg_snprintf(NULL,
  17217. NULL, /* No truncation check for error buffers */
  17218. error->text,
  17219. error->text_buffer_size,
  17220. err_msg,
  17221. i);
  17222. }
  17223. free_context(ctx);
  17224. pthread_setspecific(sTlsKey, NULL);
  17225. return NULL;
  17226. }
  17227. }
  17228. #endif
  17229. #if defined(USE_TIMERS)
  17230. if (timers_init(ctx) != 0) {
  17231. const char *err_msg = "Error creating timers";
  17232. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17233. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17234. mg_snprintf(NULL,
  17235. NULL, /* No truncation check for error buffers */
  17236. error->text,
  17237. error->text_buffer_size,
  17238. "%s",
  17239. err_msg);
  17240. }
  17241. free_context(ctx);
  17242. pthread_setspecific(sTlsKey, NULL);
  17243. return NULL;
  17244. }
  17245. #endif
  17246. /* Context has been created - init user libraries */
  17247. if (ctx->callbacks.init_context) {
  17248. ctx->callbacks.init_context(ctx);
  17249. }
  17250. /* From now, the context is successfully created.
  17251. * When it is destroyed, the exit callback should be called. */
  17252. ctx->callbacks.exit_context = exit_callback;
  17253. ctx->context_type = CONTEXT_SERVER; /* server context */
  17254. /* Start worker threads */
  17255. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17256. /* worker_thread sets up the other fields */
  17257. ctx->worker_connections[i].phys_ctx = ctx;
  17258. if (mg_start_thread_with_id(worker_thread,
  17259. &ctx->worker_connections[i],
  17260. &ctx->worker_threadids[i])
  17261. != 0) {
  17262. long error_no = (long)ERRNO;
  17263. /* thread was not created */
  17264. if (i > 0) {
  17265. /* If the second, third, ... thread cannot be created, set a
  17266. * warning, but keep running. */
  17267. mg_cry_ctx_internal(ctx,
  17268. "Cannot start worker thread %i: error %ld",
  17269. i + 1,
  17270. error_no);
  17271. /* If the server initialization should stop here, all
  17272. * threads that have already been created must be stopped
  17273. * first, before any free_context(ctx) call.
  17274. */
  17275. } else {
  17276. /* If the first worker thread cannot be created, stop
  17277. * initialization and free the entire server context. */
  17278. mg_cry_ctx_internal(ctx,
  17279. "Cannot create threads: error %ld",
  17280. error_no);
  17281. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17282. mg_snprintf(
  17283. NULL,
  17284. NULL, /* No truncation check for error buffers */
  17285. error->text,
  17286. error->text_buffer_size,
  17287. "Cannot create first worker thread: error %ld",
  17288. error_no);
  17289. }
  17290. free_context(ctx);
  17291. pthread_setspecific(sTlsKey, NULL);
  17292. return NULL;
  17293. }
  17294. break;
  17295. }
  17296. }
  17297. /* Start master (listening) thread */
  17298. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17299. pthread_setspecific(sTlsKey, NULL);
  17300. return ctx;
  17301. }
  17302. struct mg_context *
  17303. mg_start(const struct mg_callbacks *callbacks,
  17304. void *user_data,
  17305. const char **options)
  17306. {
  17307. struct mg_init_data init = {0};
  17308. init.callbacks = callbacks;
  17309. init.user_data = user_data;
  17310. init.configuration_options = options;
  17311. return mg_start2(&init, NULL);
  17312. }
  17313. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17314. /* Add an additional domain to an already running web server. */
  17315. int
  17316. mg_start_domain2(struct mg_context *ctx,
  17317. const char **options,
  17318. struct mg_error_data *error)
  17319. {
  17320. const char *name;
  17321. const char *value;
  17322. const char *default_value;
  17323. struct mg_domain_context *new_dom;
  17324. struct mg_domain_context *dom;
  17325. int idx, i;
  17326. if (error != NULL) {
  17327. error->code = 0;
  17328. if (error->text_buffer_size > 0) {
  17329. *error->text = 0;
  17330. }
  17331. }
  17332. if ((ctx == NULL) || (options == NULL)) {
  17333. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17334. mg_snprintf(NULL,
  17335. NULL, /* No truncation check for error buffers */
  17336. error->text,
  17337. error->text_buffer_size,
  17338. "%s",
  17339. "Invalid parameters");
  17340. }
  17341. return -1;
  17342. }
  17343. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17344. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17345. mg_snprintf(NULL,
  17346. NULL, /* No truncation check for error buffers */
  17347. error->text,
  17348. error->text_buffer_size,
  17349. "%s",
  17350. "Server already stopped");
  17351. }
  17352. return -1;
  17353. }
  17354. new_dom = (struct mg_domain_context *)
  17355. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17356. if (!new_dom) {
  17357. /* Out of memory */
  17358. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17359. mg_snprintf(NULL,
  17360. NULL, /* No truncation check for error buffers */
  17361. error->text,
  17362. error->text_buffer_size,
  17363. "%s",
  17364. "Out or memory");
  17365. }
  17366. return -6;
  17367. }
  17368. /* Store options - TODO: unite duplicate code */
  17369. while (options && (name = *options++) != NULL) {
  17370. if ((idx = get_option_index(name)) == -1) {
  17371. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17372. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17373. mg_snprintf(NULL,
  17374. NULL, /* No truncation check for error buffers */
  17375. error->text,
  17376. error->text_buffer_size,
  17377. "Invalid option: %s",
  17378. name);
  17379. }
  17380. mg_free(new_dom);
  17381. return -2;
  17382. } else if ((value = *options++) == NULL) {
  17383. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17384. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17385. mg_snprintf(NULL,
  17386. NULL, /* No truncation check for error buffers */
  17387. error->text,
  17388. error->text_buffer_size,
  17389. "Invalid option value: %s",
  17390. name);
  17391. }
  17392. mg_free(new_dom);
  17393. return -2;
  17394. }
  17395. if (new_dom->config[idx] != NULL) {
  17396. /* Duplicate option: Later values overwrite earlier ones. */
  17397. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17398. mg_free(new_dom->config[idx]);
  17399. }
  17400. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17401. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17402. }
  17403. /* Authentication domain is mandatory */
  17404. /* TODO: Maybe use a new option hostname? */
  17405. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17406. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17407. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17408. mg_snprintf(NULL,
  17409. NULL, /* No truncation check for error buffers */
  17410. error->text,
  17411. error->text_buffer_size,
  17412. "Mandatory option %s missing",
  17413. config_options[AUTHENTICATION_DOMAIN].name);
  17414. }
  17415. mg_free(new_dom);
  17416. return -4;
  17417. }
  17418. /* Set default value if needed. Take the config value from
  17419. * ctx as a default value. */
  17420. for (i = 0; config_options[i].name != NULL; i++) {
  17421. default_value = ctx->dd.config[i];
  17422. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17423. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17424. }
  17425. }
  17426. new_dom->handlers = NULL;
  17427. new_dom->next = NULL;
  17428. new_dom->nonce_count = 0;
  17429. new_dom->auth_nonce_mask =
  17430. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17431. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17432. new_dom->shared_lua_websockets = NULL;
  17433. #endif
  17434. #if !defined(NO_SSL)
  17435. if (!init_ssl_ctx(ctx, new_dom)) {
  17436. /* Init SSL failed */
  17437. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17438. mg_snprintf(NULL,
  17439. NULL, /* No truncation check for error buffers */
  17440. error->text,
  17441. error->text_buffer_size,
  17442. "%s",
  17443. "Initializing SSL context failed");
  17444. }
  17445. mg_free(new_dom);
  17446. return -3;
  17447. }
  17448. #endif
  17449. /* Add element to linked list. */
  17450. mg_lock_context(ctx);
  17451. idx = 0;
  17452. dom = &(ctx->dd);
  17453. for (;;) {
  17454. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17455. dom->config[AUTHENTICATION_DOMAIN])) {
  17456. /* Domain collision */
  17457. mg_cry_ctx_internal(ctx,
  17458. "domain %s already in use",
  17459. new_dom->config[AUTHENTICATION_DOMAIN]);
  17460. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17461. mg_snprintf(NULL,
  17462. NULL, /* No truncation check for error buffers */
  17463. error->text,
  17464. error->text_buffer_size,
  17465. "Domain %s specified by %s is already in use",
  17466. new_dom->config[AUTHENTICATION_DOMAIN],
  17467. config_options[AUTHENTICATION_DOMAIN].name);
  17468. }
  17469. mg_free(new_dom);
  17470. mg_unlock_context(ctx);
  17471. return -5;
  17472. }
  17473. /* Count number of domains */
  17474. idx++;
  17475. if (dom->next == NULL) {
  17476. dom->next = new_dom;
  17477. break;
  17478. }
  17479. dom = dom->next;
  17480. }
  17481. mg_unlock_context(ctx);
  17482. /* Return domain number */
  17483. return idx;
  17484. }
  17485. int
  17486. mg_start_domain(struct mg_context *ctx, const char **options)
  17487. {
  17488. return mg_start_domain2(ctx, options, NULL);
  17489. }
  17490. #endif
  17491. /* Feature check API function */
  17492. unsigned
  17493. mg_check_feature(unsigned feature)
  17494. {
  17495. static const unsigned feature_set = 0
  17496. /* Set bits for available features according to API documentation.
  17497. * This bit mask is created at compile time, according to the active
  17498. * preprocessor defines. It is a single const value at runtime. */
  17499. #if !defined(NO_FILES)
  17500. | MG_FEATURES_FILES
  17501. #endif
  17502. #if !defined(NO_SSL)
  17503. | MG_FEATURES_SSL
  17504. #endif
  17505. #if !defined(NO_CGI)
  17506. | MG_FEATURES_CGI
  17507. #endif
  17508. #if defined(USE_IPV6)
  17509. | MG_FEATURES_IPV6
  17510. #endif
  17511. #if defined(USE_WEBSOCKET)
  17512. | MG_FEATURES_WEBSOCKET
  17513. #endif
  17514. #if defined(USE_LUA)
  17515. | MG_FEATURES_LUA
  17516. #endif
  17517. #if defined(USE_DUKTAPE)
  17518. | MG_FEATURES_SSJS
  17519. #endif
  17520. #if !defined(NO_CACHING)
  17521. | MG_FEATURES_CACHE
  17522. #endif
  17523. #if defined(USE_SERVER_STATS)
  17524. | MG_FEATURES_STATS
  17525. #endif
  17526. #if defined(USE_ZLIB)
  17527. | MG_FEATURES_COMPRESSION
  17528. #endif
  17529. /* Set some extra bits not defined in the API documentation.
  17530. * These bits may change without further notice. */
  17531. #if defined(MG_LEGACY_INTERFACE)
  17532. | 0x00008000u
  17533. #endif
  17534. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17535. | 0x00004000u
  17536. #endif
  17537. #if defined(MEMORY_DEBUGGING)
  17538. | 0x00001000u
  17539. #endif
  17540. #if defined(USE_TIMERS)
  17541. | 0x00020000u
  17542. #endif
  17543. #if !defined(NO_NONCE_CHECK)
  17544. | 0x00040000u
  17545. #endif
  17546. #if !defined(NO_POPEN)
  17547. | 0x00080000u
  17548. #endif
  17549. ;
  17550. return (feature & feature_set);
  17551. }
  17552. static size_t
  17553. mg_str_append(char **dst, char *end, const char *src)
  17554. {
  17555. size_t len = strlen(src);
  17556. if (*dst != end) {
  17557. /* Append src if enough space, or close dst. */
  17558. if ((size_t)(end - *dst) > len) {
  17559. strcpy(*dst, src);
  17560. *dst += len;
  17561. } else {
  17562. *dst = end;
  17563. }
  17564. }
  17565. return len;
  17566. }
  17567. /* Get system information. It can be printed or stored by the caller.
  17568. * Return the size of available information. */
  17569. int
  17570. mg_get_system_info(char *buffer, int buflen)
  17571. {
  17572. char *end, *append_eoobj = NULL, block[256];
  17573. size_t system_info_length = 0;
  17574. #if defined(_WIN32)
  17575. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17576. #else
  17577. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17578. #endif
  17579. if ((buffer == NULL) || (buflen < 1)) {
  17580. buflen = 0;
  17581. end = buffer;
  17582. } else {
  17583. *buffer = 0;
  17584. end = buffer + buflen;
  17585. }
  17586. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17587. /* has enough space to append eoobj */
  17588. append_eoobj = buffer;
  17589. if (end) {
  17590. end -= sizeof(eoobj) - 1;
  17591. }
  17592. }
  17593. system_info_length += mg_str_append(&buffer, end, "{");
  17594. /* Server version */
  17595. {
  17596. const char *version = mg_version();
  17597. mg_snprintf(NULL,
  17598. NULL,
  17599. block,
  17600. sizeof(block),
  17601. "%s\"version\" : \"%s\"",
  17602. eol,
  17603. version);
  17604. system_info_length += mg_str_append(&buffer, end, block);
  17605. }
  17606. /* System info */
  17607. {
  17608. #if defined(_WIN32)
  17609. DWORD dwVersion = 0;
  17610. DWORD dwMajorVersion = 0;
  17611. DWORD dwMinorVersion = 0;
  17612. SYSTEM_INFO si;
  17613. GetSystemInfo(&si);
  17614. #if defined(_MSC_VER)
  17615. #pragma warning(push)
  17616. /* GetVersion was declared deprecated */
  17617. #pragma warning(disable : 4996)
  17618. #endif
  17619. dwVersion = GetVersion();
  17620. #if defined(_MSC_VER)
  17621. #pragma warning(pop)
  17622. #endif
  17623. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17624. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17625. mg_snprintf(NULL,
  17626. NULL,
  17627. block,
  17628. sizeof(block),
  17629. ",%s\"os\" : \"Windows %u.%u\"",
  17630. eol,
  17631. (unsigned)dwMajorVersion,
  17632. (unsigned)dwMinorVersion);
  17633. system_info_length += mg_str_append(&buffer, end, block);
  17634. mg_snprintf(NULL,
  17635. NULL,
  17636. block,
  17637. sizeof(block),
  17638. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17639. eol,
  17640. (unsigned)si.wProcessorArchitecture,
  17641. (unsigned)si.dwNumberOfProcessors,
  17642. (unsigned)si.dwActiveProcessorMask);
  17643. system_info_length += mg_str_append(&buffer, end, block);
  17644. #elif defined(__ZEPHYR__)
  17645. mg_snprintf(NULL,
  17646. NULL,
  17647. block,
  17648. sizeof(block),
  17649. ",%s\"os\" : \"%s %s\"",
  17650. eol,
  17651. "Zephyr OS",
  17652. ZEPHYR_VERSION);
  17653. system_info_length += mg_str_append(&buffer, end, block);
  17654. #else
  17655. struct utsname name;
  17656. memset(&name, 0, sizeof(name));
  17657. uname(&name);
  17658. mg_snprintf(NULL,
  17659. NULL,
  17660. block,
  17661. sizeof(block),
  17662. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17663. eol,
  17664. name.sysname,
  17665. name.version,
  17666. name.release,
  17667. name.machine);
  17668. system_info_length += mg_str_append(&buffer, end, block);
  17669. #endif
  17670. }
  17671. /* Features */
  17672. {
  17673. mg_snprintf(NULL,
  17674. NULL,
  17675. block,
  17676. sizeof(block),
  17677. ",%s\"features\" : %lu"
  17678. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17679. eol,
  17680. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17681. eol,
  17682. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17683. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17684. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17685. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17686. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17687. : "",
  17688. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17689. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17690. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17691. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17692. system_info_length += mg_str_append(&buffer, end, block);
  17693. #if defined(USE_LUA)
  17694. mg_snprintf(NULL,
  17695. NULL,
  17696. block,
  17697. sizeof(block),
  17698. ",%s\"lua_version\" : \"%u (%s)\"",
  17699. eol,
  17700. (unsigned)LUA_VERSION_NUM,
  17701. LUA_RELEASE);
  17702. system_info_length += mg_str_append(&buffer, end, block);
  17703. #endif
  17704. #if defined(USE_DUKTAPE)
  17705. mg_snprintf(NULL,
  17706. NULL,
  17707. block,
  17708. sizeof(block),
  17709. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17710. eol,
  17711. (unsigned)DUK_VERSION / 10000,
  17712. ((unsigned)DUK_VERSION / 100) % 100,
  17713. (unsigned)DUK_VERSION % 100);
  17714. system_info_length += mg_str_append(&buffer, end, block);
  17715. #endif
  17716. }
  17717. /* Build date */
  17718. {
  17719. #if defined(GCC_DIAGNOSTIC)
  17720. #if GCC_VERSION >= 40900
  17721. #pragma GCC diagnostic push
  17722. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17723. #pragma GCC diagnostic ignored "-Wdate-time"
  17724. #endif
  17725. #endif
  17726. mg_snprintf(NULL,
  17727. NULL,
  17728. block,
  17729. sizeof(block),
  17730. ",%s\"build\" : \"%s\"",
  17731. eol,
  17732. __DATE__);
  17733. #if defined(GCC_DIAGNOSTIC)
  17734. #if GCC_VERSION >= 40900
  17735. #pragma GCC diagnostic pop
  17736. #endif
  17737. #endif
  17738. system_info_length += mg_str_append(&buffer, end, block);
  17739. }
  17740. /* Compiler information */
  17741. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17742. {
  17743. #if defined(_MSC_VER)
  17744. mg_snprintf(NULL,
  17745. NULL,
  17746. block,
  17747. sizeof(block),
  17748. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17749. eol,
  17750. (unsigned)_MSC_VER,
  17751. (unsigned)_MSC_FULL_VER);
  17752. system_info_length += mg_str_append(&buffer, end, block);
  17753. #elif defined(__MINGW64__)
  17754. mg_snprintf(NULL,
  17755. NULL,
  17756. block,
  17757. sizeof(block),
  17758. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17759. eol,
  17760. (unsigned)__MINGW64_VERSION_MAJOR,
  17761. (unsigned)__MINGW64_VERSION_MINOR);
  17762. system_info_length += mg_str_append(&buffer, end, block);
  17763. mg_snprintf(NULL,
  17764. NULL,
  17765. block,
  17766. sizeof(block),
  17767. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17768. eol,
  17769. (unsigned)__MINGW32_MAJOR_VERSION,
  17770. (unsigned)__MINGW32_MINOR_VERSION);
  17771. system_info_length += mg_str_append(&buffer, end, block);
  17772. #elif defined(__MINGW32__)
  17773. mg_snprintf(NULL,
  17774. NULL,
  17775. block,
  17776. sizeof(block),
  17777. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17778. eol,
  17779. (unsigned)__MINGW32_MAJOR_VERSION,
  17780. (unsigned)__MINGW32_MINOR_VERSION);
  17781. system_info_length += mg_str_append(&buffer, end, block);
  17782. #elif defined(__clang__)
  17783. mg_snprintf(NULL,
  17784. NULL,
  17785. block,
  17786. sizeof(block),
  17787. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17788. eol,
  17789. __clang_major__,
  17790. __clang_minor__,
  17791. __clang_patchlevel__,
  17792. __clang_version__);
  17793. system_info_length += mg_str_append(&buffer, end, block);
  17794. #elif defined(__GNUC__)
  17795. mg_snprintf(NULL,
  17796. NULL,
  17797. block,
  17798. sizeof(block),
  17799. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17800. eol,
  17801. (unsigned)__GNUC__,
  17802. (unsigned)__GNUC_MINOR__,
  17803. (unsigned)__GNUC_PATCHLEVEL__);
  17804. system_info_length += mg_str_append(&buffer, end, block);
  17805. #elif defined(__INTEL_COMPILER)
  17806. mg_snprintf(NULL,
  17807. NULL,
  17808. block,
  17809. sizeof(block),
  17810. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17811. eol,
  17812. (unsigned)__INTEL_COMPILER);
  17813. system_info_length += mg_str_append(&buffer, end, block);
  17814. #elif defined(__BORLANDC__)
  17815. mg_snprintf(NULL,
  17816. NULL,
  17817. block,
  17818. sizeof(block),
  17819. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17820. eol,
  17821. (unsigned)__BORLANDC__);
  17822. system_info_length += mg_str_append(&buffer, end, block);
  17823. #elif defined(__SUNPRO_C)
  17824. mg_snprintf(NULL,
  17825. NULL,
  17826. block,
  17827. sizeof(block),
  17828. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17829. eol,
  17830. (unsigned)__SUNPRO_C);
  17831. system_info_length += mg_str_append(&buffer, end, block);
  17832. #else
  17833. mg_snprintf(NULL,
  17834. NULL,
  17835. block,
  17836. sizeof(block),
  17837. ",%s\"compiler\" : \"other\"",
  17838. eol);
  17839. system_info_length += mg_str_append(&buffer, end, block);
  17840. #endif
  17841. }
  17842. /* Determine 32/64 bit data mode.
  17843. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17844. {
  17845. mg_snprintf(NULL,
  17846. NULL,
  17847. block,
  17848. sizeof(block),
  17849. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17850. "char:%u/%u, "
  17851. "ptr:%u, size:%u, time:%u\"",
  17852. eol,
  17853. (unsigned)sizeof(short),
  17854. (unsigned)sizeof(int),
  17855. (unsigned)sizeof(long),
  17856. (unsigned)sizeof(long long),
  17857. (unsigned)sizeof(float),
  17858. (unsigned)sizeof(double),
  17859. (unsigned)sizeof(long double),
  17860. (unsigned)sizeof(char),
  17861. (unsigned)sizeof(wchar_t),
  17862. (unsigned)sizeof(void *),
  17863. (unsigned)sizeof(size_t),
  17864. (unsigned)sizeof(time_t));
  17865. system_info_length += mg_str_append(&buffer, end, block);
  17866. }
  17867. /* Terminate string */
  17868. if (append_eoobj) {
  17869. strcat(append_eoobj, eoobj);
  17870. }
  17871. system_info_length += sizeof(eoobj) - 1;
  17872. return (int)system_info_length;
  17873. }
  17874. /* Get context information. It can be printed or stored by the caller.
  17875. * Return the size of available information. */
  17876. int
  17877. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17878. {
  17879. #if defined(USE_SERVER_STATS)
  17880. char *end, *append_eoobj = NULL, block[256];
  17881. size_t context_info_length = 0;
  17882. #if defined(_WIN32)
  17883. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17884. #else
  17885. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17886. #endif
  17887. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17888. if ((buffer == NULL) || (buflen < 1)) {
  17889. buflen = 0;
  17890. end = buffer;
  17891. } else {
  17892. *buffer = 0;
  17893. end = buffer + buflen;
  17894. }
  17895. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17896. /* has enough space to append eoobj */
  17897. append_eoobj = buffer;
  17898. end -= sizeof(eoobj) - 1;
  17899. }
  17900. context_info_length += mg_str_append(&buffer, end, "{");
  17901. if (ms) { /* <-- should be always true */
  17902. /* Memory information */
  17903. mg_snprintf(NULL,
  17904. NULL,
  17905. block,
  17906. sizeof(block),
  17907. "%s\"memory\" : {%s"
  17908. "\"blocks\" : %i,%s"
  17909. "\"used\" : %" INT64_FMT ",%s"
  17910. "\"maxUsed\" : %" INT64_FMT "%s"
  17911. "}",
  17912. eol,
  17913. eol,
  17914. ms->blockCount,
  17915. eol,
  17916. ms->totalMemUsed,
  17917. eol,
  17918. ms->maxMemUsed,
  17919. eol);
  17920. context_info_length += mg_str_append(&buffer, end, block);
  17921. }
  17922. if (ctx) {
  17923. /* Declare all variables at begin of the block, to comply
  17924. * with old C standards. */
  17925. char start_time_str[64] = {0};
  17926. char now_str[64] = {0};
  17927. time_t start_time = ctx->start_time;
  17928. time_t now = time(NULL);
  17929. /* Connections information */
  17930. mg_snprintf(NULL,
  17931. NULL,
  17932. block,
  17933. sizeof(block),
  17934. ",%s\"connections\" : {%s"
  17935. "\"active\" : %i,%s"
  17936. "\"maxActive\" : %i,%s"
  17937. "\"total\" : %" INT64_FMT "%s"
  17938. "}",
  17939. eol,
  17940. eol,
  17941. ctx->active_connections,
  17942. eol,
  17943. ctx->max_active_connections,
  17944. eol,
  17945. ctx->total_connections,
  17946. eol);
  17947. context_info_length += mg_str_append(&buffer, end, block);
  17948. /* Queue information */
  17949. #if !defined(ALTERNATIVE_QUEUE)
  17950. mg_snprintf(NULL,
  17951. NULL,
  17952. block,
  17953. sizeof(block),
  17954. ",%s\"queue\" : {%s"
  17955. "\"length\" : %i,%s"
  17956. "\"filled\" : %i,%s"
  17957. "\"maxFilled\" : %i,%s"
  17958. "\"full\" : %s%s"
  17959. "}",
  17960. eol,
  17961. eol,
  17962. ctx->sq_size,
  17963. eol,
  17964. ctx->sq_head - ctx->sq_tail,
  17965. eol,
  17966. ctx->sq_max_fill,
  17967. eol,
  17968. (ctx->sq_blocked ? "true" : "false"),
  17969. eol);
  17970. context_info_length += mg_str_append(&buffer, end, block);
  17971. #endif
  17972. /* Requests information */
  17973. mg_snprintf(NULL,
  17974. NULL,
  17975. block,
  17976. sizeof(block),
  17977. ",%s\"requests\" : {%s"
  17978. "\"total\" : %" INT64_FMT "%s"
  17979. "}",
  17980. eol,
  17981. eol,
  17982. ctx->total_requests,
  17983. eol);
  17984. context_info_length += mg_str_append(&buffer, end, block);
  17985. /* Data information */
  17986. mg_snprintf(NULL,
  17987. NULL,
  17988. block,
  17989. sizeof(block),
  17990. ",%s\"data\" : {%s"
  17991. "\"read\" : %" INT64_FMT ",%s"
  17992. "\"written\" : %" INT64_FMT "%s"
  17993. "}",
  17994. eol,
  17995. eol,
  17996. ctx->total_data_read,
  17997. eol,
  17998. ctx->total_data_written,
  17999. eol);
  18000. context_info_length += mg_str_append(&buffer, end, block);
  18001. /* Execution time information */
  18002. gmt_time_string(start_time_str,
  18003. sizeof(start_time_str) - 1,
  18004. &start_time);
  18005. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18006. mg_snprintf(NULL,
  18007. NULL,
  18008. block,
  18009. sizeof(block),
  18010. ",%s\"time\" : {%s"
  18011. "\"uptime\" : %.0f,%s"
  18012. "\"start\" : \"%s\",%s"
  18013. "\"now\" : \"%s\"%s"
  18014. "}",
  18015. eol,
  18016. eol,
  18017. difftime(now, start_time),
  18018. eol,
  18019. start_time_str,
  18020. eol,
  18021. now_str,
  18022. eol);
  18023. context_info_length += mg_str_append(&buffer, end, block);
  18024. }
  18025. /* Terminate string */
  18026. if (append_eoobj) {
  18027. strcat(append_eoobj, eoobj);
  18028. }
  18029. context_info_length += sizeof(eoobj) - 1;
  18030. return (int)context_info_length;
  18031. #else
  18032. (void)ctx;
  18033. if ((buffer != NULL) && (buflen > 0)) {
  18034. *buffer = 0;
  18035. }
  18036. return 0;
  18037. #endif
  18038. }
  18039. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18040. /* Get connection information. It can be printed or stored by the caller.
  18041. * Return the size of available information. */
  18042. int
  18043. mg_get_connection_info(const struct mg_context *ctx,
  18044. int idx,
  18045. char *buffer,
  18046. int buflen)
  18047. {
  18048. const struct mg_connection *conn;
  18049. const struct mg_request_info *ri;
  18050. char *end, *append_eoobj = NULL, block[256];
  18051. size_t connection_info_length = 0;
  18052. int state = 0;
  18053. const char *state_str = "unknown";
  18054. #if defined(_WIN32)
  18055. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18056. #else
  18057. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18058. #endif
  18059. if ((buffer == NULL) || (buflen < 1)) {
  18060. buflen = 0;
  18061. end = buffer;
  18062. } else {
  18063. *buffer = 0;
  18064. end = buffer + buflen;
  18065. }
  18066. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18067. /* has enough space to append eoobj */
  18068. append_eoobj = buffer;
  18069. end -= sizeof(eoobj) - 1;
  18070. }
  18071. if ((ctx == NULL) || (idx < 0)) {
  18072. /* Parameter error */
  18073. return 0;
  18074. }
  18075. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18076. /* Out of range */
  18077. return 0;
  18078. }
  18079. /* Take connection [idx]. This connection is not locked in
  18080. * any way, so some other thread might use it. */
  18081. conn = (ctx->worker_connections) + idx;
  18082. /* Initialize output string */
  18083. connection_info_length += mg_str_append(&buffer, end, "{");
  18084. /* Init variables */
  18085. ri = &(conn->request_info);
  18086. #if defined(USE_SERVER_STATS)
  18087. state = conn->conn_state;
  18088. /* State as string */
  18089. switch (state) {
  18090. case 0:
  18091. state_str = "undefined";
  18092. break;
  18093. case 1:
  18094. state_str = "not used";
  18095. break;
  18096. case 2:
  18097. state_str = "init";
  18098. break;
  18099. case 3:
  18100. state_str = "ready";
  18101. break;
  18102. case 4:
  18103. state_str = "processing";
  18104. break;
  18105. case 5:
  18106. state_str = "processed";
  18107. break;
  18108. case 6:
  18109. state_str = "to close";
  18110. break;
  18111. case 7:
  18112. state_str = "closing";
  18113. break;
  18114. case 8:
  18115. state_str = "closed";
  18116. break;
  18117. case 9:
  18118. state_str = "done";
  18119. break;
  18120. }
  18121. #endif
  18122. /* Connection info */
  18123. if ((state >= 3) && (state < 9)) {
  18124. mg_snprintf(NULL,
  18125. NULL,
  18126. block,
  18127. sizeof(block),
  18128. "%s\"connection\" : {%s"
  18129. "\"remote\" : {%s"
  18130. "\"protocol\" : \"%s\",%s"
  18131. "\"addr\" : \"%s\",%s"
  18132. "\"port\" : %u%s"
  18133. "},%s"
  18134. "\"handled_requests\" : %u%s"
  18135. "}",
  18136. eol,
  18137. eol,
  18138. eol,
  18139. get_proto_name(conn),
  18140. eol,
  18141. ri->remote_addr,
  18142. eol,
  18143. ri->remote_port,
  18144. eol,
  18145. eol,
  18146. conn->handled_requests,
  18147. eol);
  18148. connection_info_length += mg_str_append(&buffer, end, block);
  18149. }
  18150. /* Request info */
  18151. if ((state >= 4) && (state < 6)) {
  18152. mg_snprintf(NULL,
  18153. NULL,
  18154. block,
  18155. sizeof(block),
  18156. "%s%s\"request_info\" : {%s"
  18157. "\"method\" : \"%s\",%s"
  18158. "\"uri\" : \"%s\",%s"
  18159. "\"query\" : %s%s%s%s"
  18160. "}",
  18161. (connection_info_length > 1 ? "," : ""),
  18162. eol,
  18163. eol,
  18164. ri->request_method,
  18165. eol,
  18166. ri->request_uri,
  18167. eol,
  18168. ri->query_string ? "\"" : "",
  18169. ri->query_string ? ri->query_string : "null",
  18170. ri->query_string ? "\"" : "",
  18171. eol);
  18172. connection_info_length += mg_str_append(&buffer, end, block);
  18173. }
  18174. /* Execution time information */
  18175. if ((state >= 2) && (state < 9)) {
  18176. char start_time_str[64] = {0};
  18177. char close_time_str[64] = {0};
  18178. time_t start_time = conn->conn_birth_time;
  18179. time_t close_time = 0;
  18180. double time_diff;
  18181. gmt_time_string(start_time_str,
  18182. sizeof(start_time_str) - 1,
  18183. &start_time);
  18184. #if defined(USE_SERVER_STATS)
  18185. close_time = conn->conn_close_time;
  18186. #endif
  18187. if (close_time != 0) {
  18188. time_diff = difftime(close_time, start_time);
  18189. gmt_time_string(close_time_str,
  18190. sizeof(close_time_str) - 1,
  18191. &close_time);
  18192. } else {
  18193. time_t now = time(NULL);
  18194. time_diff = difftime(now, start_time);
  18195. close_time_str[0] = 0; /* or use "now" ? */
  18196. }
  18197. mg_snprintf(NULL,
  18198. NULL,
  18199. block,
  18200. sizeof(block),
  18201. "%s%s\"time\" : {%s"
  18202. "\"uptime\" : %.0f,%s"
  18203. "\"start\" : \"%s\",%s"
  18204. "\"closed\" : \"%s\"%s"
  18205. "}",
  18206. (connection_info_length > 1 ? "," : ""),
  18207. eol,
  18208. eol,
  18209. time_diff,
  18210. eol,
  18211. start_time_str,
  18212. eol,
  18213. close_time_str,
  18214. eol);
  18215. connection_info_length += mg_str_append(&buffer, end, block);
  18216. }
  18217. /* Remote user name */
  18218. if ((ri->remote_user) && (state < 9)) {
  18219. mg_snprintf(NULL,
  18220. NULL,
  18221. block,
  18222. sizeof(block),
  18223. "%s%s\"user\" : {%s"
  18224. "\"name\" : \"%s\",%s"
  18225. "}",
  18226. (connection_info_length > 1 ? "," : ""),
  18227. eol,
  18228. eol,
  18229. ri->remote_user,
  18230. eol);
  18231. connection_info_length += mg_str_append(&buffer, end, block);
  18232. }
  18233. /* Data block */
  18234. if (state >= 3) {
  18235. mg_snprintf(NULL,
  18236. NULL,
  18237. block,
  18238. sizeof(block),
  18239. "%s%s\"data\" : {%s"
  18240. "\"read\" : %" INT64_FMT ",%s"
  18241. "\"written\" : %" INT64_FMT "%s"
  18242. "}",
  18243. (connection_info_length > 1 ? "," : ""),
  18244. eol,
  18245. eol,
  18246. conn->consumed_content,
  18247. eol,
  18248. conn->num_bytes_sent,
  18249. eol);
  18250. connection_info_length += mg_str_append(&buffer, end, block);
  18251. }
  18252. /* State */
  18253. mg_snprintf(NULL,
  18254. NULL,
  18255. block,
  18256. sizeof(block),
  18257. "%s%s\"state\" : \"%s\"",
  18258. (connection_info_length > 1 ? "," : ""),
  18259. eol,
  18260. state_str);
  18261. connection_info_length += mg_str_append(&buffer, end, block);
  18262. /* Terminate string */
  18263. if (append_eoobj) {
  18264. strcat(append_eoobj, eoobj);
  18265. }
  18266. connection_info_length += sizeof(eoobj) - 1;
  18267. return (int)connection_info_length;
  18268. }
  18269. #endif
  18270. /* Initialize this library. This function does not need to be thread safe.
  18271. */
  18272. unsigned
  18273. mg_init_library(unsigned features)
  18274. {
  18275. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18276. unsigned features_inited = features_to_init;
  18277. if (mg_init_library_called <= 0) {
  18278. /* Not initialized yet */
  18279. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18280. return 0;
  18281. }
  18282. }
  18283. mg_global_lock();
  18284. if (mg_init_library_called <= 0) {
  18285. #if defined(_WIN32)
  18286. int file_mutex_init = 1;
  18287. int wsa = 1;
  18288. #else
  18289. int mutexattr_init = 1;
  18290. #endif
  18291. int failed = 1;
  18292. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18293. if (key_create == 0) {
  18294. #if defined(_WIN32)
  18295. file_mutex_init =
  18296. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18297. if (file_mutex_init == 0) {
  18298. /* Start WinSock */
  18299. WSADATA data;
  18300. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18301. }
  18302. #else
  18303. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18304. if (mutexattr_init == 0) {
  18305. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18306. PTHREAD_MUTEX_RECURSIVE);
  18307. }
  18308. #endif
  18309. }
  18310. if (failed) {
  18311. #if defined(_WIN32)
  18312. if (wsa == 0) {
  18313. (void)WSACleanup();
  18314. }
  18315. if (file_mutex_init == 0) {
  18316. (void)pthread_mutex_destroy(&global_log_file_lock);
  18317. }
  18318. #else
  18319. if (mutexattr_init == 0) {
  18320. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18321. }
  18322. #endif
  18323. if (key_create == 0) {
  18324. (void)pthread_key_delete(sTlsKey);
  18325. }
  18326. mg_global_unlock();
  18327. (void)pthread_mutex_destroy(&global_lock_mutex);
  18328. return 0;
  18329. }
  18330. #if defined(USE_LUA)
  18331. lua_init_optional_libraries();
  18332. #endif
  18333. }
  18334. mg_global_unlock();
  18335. #if !defined(NO_SSL)
  18336. if (features_to_init & MG_FEATURES_SSL) {
  18337. if (!mg_ssl_initialized) {
  18338. char ebuf[128];
  18339. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18340. mg_ssl_initialized = 1;
  18341. } else {
  18342. (void)ebuf;
  18343. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18344. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18345. }
  18346. } else {
  18347. /* ssl already initialized */
  18348. }
  18349. }
  18350. #endif
  18351. mg_global_lock();
  18352. if (mg_init_library_called <= 0) {
  18353. mg_init_library_called = 1;
  18354. } else {
  18355. mg_init_library_called++;
  18356. }
  18357. mg_global_unlock();
  18358. return features_inited;
  18359. }
  18360. /* Un-initialize this library. */
  18361. unsigned
  18362. mg_exit_library(void)
  18363. {
  18364. if (mg_init_library_called <= 0) {
  18365. return 0;
  18366. }
  18367. mg_global_lock();
  18368. mg_init_library_called--;
  18369. if (mg_init_library_called == 0) {
  18370. #if !defined(NO_SSL)
  18371. if (mg_ssl_initialized) {
  18372. uninitialize_ssl();
  18373. mg_ssl_initialized = 0;
  18374. }
  18375. #endif
  18376. #if defined(_WIN32)
  18377. (void)WSACleanup();
  18378. (void)pthread_mutex_destroy(&global_log_file_lock);
  18379. #else
  18380. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18381. #endif
  18382. (void)pthread_key_delete(sTlsKey);
  18383. #if defined(USE_LUA)
  18384. lua_exit_optional_libraries();
  18385. #endif
  18386. mg_global_unlock();
  18387. (void)pthread_mutex_destroy(&global_lock_mutex);
  18388. return 1;
  18389. }
  18390. mg_global_unlock();
  18391. return 1;
  18392. }
  18393. /* End of civetweb.c */